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 | bsd-3-clause | bf7ce8ab24ac417c7216d22325fe4eb656bc587e | 0 | ksclarke/basex,BaseXdb/basex,BaseXdb/basex,drmacro/basex,deshmnnit04/basex,BaseXdb/basex,BaseXdb/basex,ksclarke/basex,dimitarp/basex,ksclarke/basex,joansmith/basex,deshmnnit04/basex,JensErat/basex,vincentml/basex,deshmnnit04/basex,vincentml/basex,joansmith/basex,ksclarke/basex,BaseXdb/basex,BaseXdb/basex,dimitarp/basex,ksclarke/basex,JensErat/basex,vincentml/basex,drmacro/basex,deshmnnit04/basex,drmacro/basex,dimitarp/basex,vincentml/basex,BaseXdb/basex,BaseXdb/basex,joansmith/basex,JensErat/basex,ksclarke/basex,vincentml/basex,dimitarp/basex,drmacro/basex,vincentml/basex,JensErat/basex,joansmith/basex,vincentml/basex,drmacro/basex,vincentml/basex,vincentml/basex,joansmith/basex,drmacro/basex,JensErat/basex,joansmith/basex,deshmnnit04/basex,deshmnnit04/basex,deshmnnit04/basex,JensErat/basex,joansmith/basex,dimitarp/basex,dimitarp/basex,vincentml/basex,joansmith/basex,ksclarke/basex,ksclarke/basex,deshmnnit04/basex,ksclarke/basex,ksclarke/basex,vincentml/basex,joansmith/basex,dimitarp/basex,dimitarp/basex,BaseXdb/basex,BaseXdb/basex,deshmnnit04/basex,drmacro/basex,dimitarp/basex,dimitarp/basex,deshmnnit04/basex,joansmith/basex,deshmnnit04/basex,drmacro/basex,JensErat/basex,JensErat/basex,vincentml/basex,ksclarke/basex,JensErat/basex,drmacro/basex,joansmith/basex,drmacro/basex,ksclarke/basex,JensErat/basex,drmacro/basex,BaseXdb/basex,JensErat/basex,dimitarp/basex,drmacro/basex,dimitarp/basex,JensErat/basex,BaseXdb/basex,deshmnnit04/basex,joansmith/basex | package org.basex.query.item;
import static org.basex.data.DataText.*;
import org.basex.query.QueryException;
import org.basex.query.expr.Expr;
import org.basex.util.InputInfo;
import org.basex.util.Token;
import org.basex.util.list.ByteList;
/**
* String item.
*
* @author BaseX Team 2005-11, BSD License
* @author Christian Gruen
*/
public class Str extends Item {
/** String data. */
public static final Str ZERO = new Str(Token.EMPTY);
/** String data. */
protected final byte[] val;
/**
* Constructor.
* @param v value
*/
private Str(final byte[] v) {
this(v, AtomType.STR);
}
/**
* Constructor.
* @param v value
* @param t data type
*/
protected Str(final byte[] v, final Type t) {
super(t);
val = v;
}
/**
* Returns an instance of this class.
* @param v value
* @return instance
*/
public static Str get(final byte[] v) {
return v.length == 0 ? ZERO : new Str(v);
}
/**
* Returns an instance of this class.
* @param v object (will be converted to token)
* @return instance
*/
public static Str get(final Object v) {
return get(Token.token(v.toString()));
}
@Override
public final byte[] atom(final InputInfo ii) {
return val;
}
/**
* Returns an atomized string.
* @return Returns an atomized string.
*/
public final byte[] atom() {
return atom(null);
}
@Override
public final boolean bool(final InputInfo ii) {
return atom(ii).length != 0;
}
@Override
public boolean eq(final InputInfo ii, final Item it) throws QueryException {
return Token.eq(val, it.atom(ii));
}
@Override
public int diff(final InputInfo ii, final Item it) throws QueryException {
return Token.diff(val, it.atom(ii));
}
@Override
public final boolean sameAs(final Expr cmp) {
if(!(cmp instanceof Str)) return false;
final Str i = (Str) cmp;
return type == i.type && Token.eq(val, i.val);
}
@Override
public final String toJava() {
return Token.string(val);
}
@Override
public final String toString() {
final ByteList tb = new ByteList();
tb.add('"');
for(final byte v : val) {
if(v == '&') tb.add(E_AMP);
else tb.add(v);
}
return tb.add('"').toString();
}
}
| src/main/java/org/basex/query/item/Str.java | package org.basex.query.item;
import static org.basex.data.DataText.*;
import org.basex.query.QueryException;
import org.basex.query.expr.Expr;
import org.basex.util.InputInfo;
import org.basex.util.Token;
import org.basex.util.list.ByteList;
/**
* String item.
*
* @author BaseX Team 2005-11, BSD License
* @author Christian Gruen
*/
public class Str extends Item {
/** String data. */
public static final Str ZERO = new Str(Token.EMPTY);
/** String data. */
protected final byte[] val;
/**
* Constructor.
* @param v value
*/
private Str(final byte[] v) {
this(v, AtomType.STR);
}
/**
* Constructor.
* @param v value
* @param t data type
*/
protected Str(final byte[] v, final Type t) {
super(t);
val = v;
}
/**
* Returns an instance of this class.
* @param v value
* @return instance
*/
public static Str get(final byte[] v) {
return v.length == 0 ? ZERO : new Str(v);
}
/**
* Returns an instance of this class.
* @param v object (will be converted to token)
* @return instance
*/
public static Str get(final Object v) {
return get(Token.token(v.toString()));
}
@Override
public final byte[] atom(final InputInfo ii) {
return val;
}
/**
* Returns an atomized string.
* @return Returns an atomized string.
*/
public final byte[] atom() {
return atom(null);
}
@Override
public final boolean bool(final InputInfo ii) {
return atom(ii).length != 0;
}
@Override
public boolean eq(final InputInfo ii, final Item it) throws QueryException {
return Token.eq(val, it.atom(ii));
}
@Override
public int diff(final InputInfo ii, final Item it) throws QueryException {
return Token.diff(val, it.atom(ii));
}
@Override
public final boolean sameAs(final Expr cmp) {
if(!(cmp instanceof Str)) return false;
final Str i = (Str) cmp;
return type == i.type && Token.eq(val, i.val);
}
@Override
public final String toJava() {
return Token.string(val);
}
@Override
public final String toString() {
final ByteList tb = new ByteList();
tb.add('"');
for(final byte v : val) {
switch(v) {
case '&': tb.add(E_AMP); break;
case '>': tb.add(E_GT); break;
case '<': tb.add(E_LT); break;
default: tb.add(v);
}
}
return tb.add('"').toString();
}
}
| [MOD] XQuery: Str dump output fix | src/main/java/org/basex/query/item/Str.java | [MOD] XQuery: Str dump output fix | <ide><path>rc/main/java/org/basex/query/item/Str.java
<ide> final ByteList tb = new ByteList();
<ide> tb.add('"');
<ide> for(final byte v : val) {
<del> switch(v) {
<del> case '&': tb.add(E_AMP); break;
<del> case '>': tb.add(E_GT); break;
<del> case '<': tb.add(E_LT); break;
<del> default: tb.add(v);
<del> }
<add> if(v == '&') tb.add(E_AMP);
<add> else tb.add(v);
<ide> }
<ide> return tb.add('"').toString();
<ide> } |
|
Java | apache-2.0 | 6de40319a37291c51d17426c70a7e70a2fb26c4c | 0 | psoreide/bnd,psoreide/bnd,psoreide/bnd | package aQute.tester.bundle.engine;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.junit.platform.engine.ConfigurationParameters;
import org.junit.platform.engine.EngineExecutionListener;
import org.junit.platform.engine.ExecutionRequest;
import org.junit.platform.engine.TestDescriptor;
import org.junit.platform.engine.TestEngine;
import org.junit.platform.engine.UniqueId;
import org.junit.platform.engine.support.descriptor.AbstractTestDescriptor;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import aQute.bnd.osgi.Constants;
public class BundleDescriptor extends AbstractTestDescriptor {
final private Bundle bundle;
final private BundleException bundleException;
final private Map<TestDescriptor, TestEngine> engineMap = new HashMap<>();
public static String displayNameOf(Bundle bundle) {
final Optional<String> bundleName = Optional.ofNullable(bundle.getHeaders()
.get(Constants.BUNDLE_NAME));
return "[" + bundle.getBundleId() + "] " + bundleName.orElseGet(bundle::getSymbolicName) + ';'
+ bundle.getVersion();
}
public BundleDescriptor(Bundle bundle, UniqueId uniqueId) {
this(bundle, uniqueId, null);
}
public BundleDescriptor(Bundle bundle, UniqueId uniqueId, BundleException bundleException) {
super(uniqueId, displayNameOf(bundle));
this.bundle = bundle;
this.bundleException = bundleException;
}
public Bundle getBundle() {
return bundle;
}
public void addChild(TestDescriptor descriptor, TestEngine engine) {
engineMap.put(descriptor, engine);
addChild(descriptor);
}
public void executeChild(TestDescriptor descriptor, EngineExecutionListener listener, ConfigurationParameters params) {
TestEngine engine = engineMap.get(descriptor);
ExecutionRequest er = new ExecutionRequest(descriptor, listener, params);
engine.execute(er);
}
@Override
public Type getType() {
return bundleException == null ? Type.CONTAINER : Type.TEST;
}
public BundleException getException() {
return bundleException;
}
}
| biz.aQute.tester.junit-platform/src/aQute/tester/bundle/engine/BundleDescriptor.java | package aQute.tester.bundle.engine;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.junit.platform.engine.ConfigurationParameters;
import org.junit.platform.engine.EngineExecutionListener;
import org.junit.platform.engine.ExecutionRequest;
import org.junit.platform.engine.TestDescriptor;
import org.junit.platform.engine.TestEngine;
import org.junit.platform.engine.UniqueId;
import org.junit.platform.engine.support.descriptor.AbstractTestDescriptor;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
public class BundleDescriptor extends AbstractTestDescriptor {
final private Bundle bundle;
final private BundleException bundleException;
final private Map<TestDescriptor, TestEngine> engineMap = new HashMap<>();
public static String displayNameOf(Bundle bundle) {
final Optional<String> bundleName = Optional.ofNullable(bundle.getHeaders()
.get(aQute.bnd.osgi.Constants.BUNDLE_NAME));
return "[" + bundle.getBundleId() + "] " + bundleName.orElse(bundle.getSymbolicName()) + ';'
+ bundle.getVersion();
}
public BundleDescriptor(Bundle bundle, UniqueId uniqueId) {
this(bundle, uniqueId, null);
}
public BundleDescriptor(Bundle bundle, UniqueId uniqueId, BundleException bundleException) {
super(uniqueId, displayNameOf(bundle));
this.bundle = bundle;
this.bundleException = bundleException;
}
public Bundle getBundle() {
return bundle;
}
public void addChild(TestDescriptor descriptor, TestEngine engine) {
engineMap.put(descriptor, engine);
addChild(descriptor);
}
public void executeChild(TestDescriptor descriptor, EngineExecutionListener listener, ConfigurationParameters params) {
TestEngine engine = engineMap.get(descriptor);
ExecutionRequest er = new ExecutionRequest(descriptor, listener, params);
engine.execute(er);
}
@Override
public Type getType() {
return bundleException == null ? Type.CONTAINER : Type.TEST;
}
public BundleException getException() {
return bundleException;
}
}
| junit: Use method reference for optional else operation
Signed-off-by: BJ Hargrave <[email protected]>
| biz.aQute.tester.junit-platform/src/aQute/tester/bundle/engine/BundleDescriptor.java | junit: Use method reference for optional else operation | <ide><path>iz.aQute.tester.junit-platform/src/aQute/tester/bundle/engine/BundleDescriptor.java
<ide> import org.osgi.framework.Bundle;
<ide> import org.osgi.framework.BundleException;
<ide>
<add>import aQute.bnd.osgi.Constants;
<add>
<ide> public class BundleDescriptor extends AbstractTestDescriptor {
<ide>
<ide> final private Bundle bundle;
<ide>
<ide> public static String displayNameOf(Bundle bundle) {
<ide> final Optional<String> bundleName = Optional.ofNullable(bundle.getHeaders()
<del> .get(aQute.bnd.osgi.Constants.BUNDLE_NAME));
<del> return "[" + bundle.getBundleId() + "] " + bundleName.orElse(bundle.getSymbolicName()) + ';'
<add> .get(Constants.BUNDLE_NAME));
<add> return "[" + bundle.getBundleId() + "] " + bundleName.orElseGet(bundle::getSymbolicName) + ';'
<ide> + bundle.getVersion();
<ide> }
<ide> |
|
Java | mit | 79e53231b8db2073c29c6f75e620c7e0994ab4da | 0 | nandan4/Jenkins,duzifang/my-jenkins,goldchang/jenkins,samatdav/jenkins,dariver/jenkins,godfath3r/jenkins,Jimilian/jenkins,scoheb/jenkins,thomassuckow/jenkins,gusreiber/jenkins,jglick/jenkins,Vlatombe/jenkins,mrooney/jenkins,SenolOzer/jenkins,petermarcoen/jenkins,seanlin816/jenkins,csimons/jenkins,wangyikai/jenkins,morficus/jenkins,github-api-test-org/jenkins,Jimilian/jenkins,Vlatombe/jenkins,vjuranek/jenkins,amuniz/jenkins,protazy/jenkins,iterate/coding-dojo,mattclark/jenkins,jhoblitt/jenkins,jpbriend/jenkins,elkingtonmcb/jenkins,recena/jenkins,mrooney/jenkins,varmenise/jenkins,FarmGeek4Life/jenkins,khmarbaise/jenkins,yonglehou/jenkins,hemantojhaa/jenkins,gitaccountforprashant/gittest,sathiya-mit/jenkins,jtnord/jenkins,rlugojr/jenkins,shahharsh/jenkins,elkingtonmcb/jenkins,jtnord/jenkins,MichaelPranovich/jenkins_sc,SebastienGllmt/jenkins,patbos/jenkins,mcanthony/jenkins,samatdav/jenkins,soenter/jenkins,my7seven/jenkins,hemantojhaa/jenkins,lindzh/jenkins,petermarcoen/jenkins,AustinKwang/jenkins,pjanouse/jenkins,liupugong/jenkins,lordofthejars/jenkins,Ykus/jenkins,Jochen-A-Fuerbacher/jenkins,pjanouse/jenkins,CodeShane/jenkins,aduprat/jenkins,SenolOzer/jenkins,ErikVerheul/jenkins,synopsys-arc-oss/jenkins,svanoort/jenkins,iqstack/jenkins,vivek/hudson,jk47/jenkins,dbroady1/jenkins,FTG-003/jenkins,h4ck3rm1k3/jenkins,hudson/hudson-2.x,292388900/jenkins,jtnord/jenkins,liorhson/jenkins,morficus/jenkins,arunsingh/jenkins,rlugojr/jenkins,Wilfred/jenkins,duzifang/my-jenkins,jcarrothers-sap/jenkins,jcarrothers-sap/jenkins,daspilker/jenkins,liorhson/jenkins,wangyikai/jenkins,abayer/jenkins,lvotypko/jenkins3,varmenise/jenkins,daniel-beck/jenkins,292388900/jenkins,gorcz/jenkins,nandan4/Jenkins,andresrc/jenkins,lvotypko/jenkins2,kohsuke/hudson,ns163/jenkins,singh88/jenkins,jenkinsci/jenkins,patbos/jenkins,SebastienGllmt/jenkins,hudson/hudson-2.x,guoxu0514/jenkins,protazy/jenkins,vjuranek/jenkins,gusreiber/jenkins,jtnord/jenkins,KostyaSha/jenkins,viqueen/jenkins,dennisjlee/jenkins,ajshastri/jenkins,FTG-003/jenkins,wuwen5/jenkins,iqstack/jenkins,amuniz/jenkins,jzjzjzj/jenkins,luoqii/jenkins,vlajos/jenkins,sathiya-mit/jenkins,khmarbaise/jenkins,amuniz/jenkins,albers/jenkins,scoheb/jenkins,intelchen/jenkins,github-api-test-org/jenkins,yonglehou/jenkins,yonglehou/jenkins,brunocvcunha/jenkins,shahharsh/jenkins,aldaris/jenkins,hemantojhaa/jenkins,dennisjlee/jenkins,ydubreuil/jenkins,yonglehou/jenkins,ndeloof/jenkins,escoem/jenkins,iterate/coding-dojo,liupugong/jenkins,ydubreuil/jenkins,iterate/coding-dojo,olivergondza/jenkins,lvotypko/jenkins3,kzantow/jenkins,maikeffi/hudson,scoheb/jenkins,tastatur/jenkins,paulmillar/jenkins,MarkEWaite/jenkins,kzantow/jenkins,jenkinsci/jenkins,ajshastri/jenkins,jpbriend/jenkins,Wilfred/jenkins,samatdav/jenkins,godfath3r/jenkins,tangkun75/jenkins,292388900/jenkins,dbroady1/jenkins,hashar/jenkins,protazy/jenkins,azweb76/jenkins,hplatou/jenkins,lvotypko/jenkins3,ErikVerheul/jenkins,vivek/hudson,ikedam/jenkins,godfath3r/jenkins,ydubreuil/jenkins,daniel-beck/jenkins,oleg-nenashev/jenkins,DoctorQ/jenkins,aheritier/jenkins,rsandell/jenkins,vvv444/jenkins,MadsNielsen/jtemp,liupugong/jenkins,akshayabd/jenkins,shahharsh/jenkins,bpzhang/jenkins,wuwen5/jenkins,Jochen-A-Fuerbacher/jenkins,shahharsh/jenkins,AustinKwang/jenkins,mattclark/jenkins,goldchang/jenkins,SenolOzer/jenkins,vivek/hudson,jcarrothers-sap/jenkins,MadsNielsen/jtemp,guoxu0514/jenkins,Krasnyanskiy/jenkins,CodeShane/jenkins,jtnord/jenkins,varmenise/jenkins,292388900/jenkins,gorcz/jenkins,github-api-test-org/jenkins,iterate/coding-dojo,NehemiahMi/jenkins,fbelzunc/jenkins,FTG-003/jenkins,gitaccountforprashant/gittest,escoem/jenkins,DoctorQ/jenkins,v1v/jenkins,petermarcoen/jenkins,rlugojr/jenkins,aldaris/jenkins,NehemiahMi/jenkins,shahharsh/jenkins,1and1/jenkins,synopsys-arc-oss/jenkins,damianszczepanik/jenkins,batmat/jenkins,tangkun75/jenkins,jenkinsci/jenkins,elkingtonmcb/jenkins,jcarrothers-sap/jenkins,jcsirot/jenkins,seanlin816/jenkins,ChrisA89/jenkins,my7seven/jenkins,elkingtonmcb/jenkins,verbitan/jenkins,verbitan/jenkins,1and1/jenkins,arunsingh/jenkins,gorcz/jenkins,tangkun75/jenkins,brunocvcunha/jenkins,seanlin816/jenkins,daniel-beck/jenkins,mpeltonen/jenkins,olivergondza/jenkins,lindzh/jenkins,aldaris/jenkins,nandan4/Jenkins,bkmeneguello/jenkins,DoctorQ/jenkins,tfennelly/jenkins,mcanthony/jenkins,h4ck3rm1k3/jenkins,guoxu0514/jenkins,noikiy/jenkins,protazy/jenkins,MarkEWaite/jenkins,mdonohue/jenkins,dariver/jenkins,pantheon-systems/jenkins,stephenc/jenkins,jhoblitt/jenkins,luoqii/jenkins,akshayabd/jenkins,akshayabd/jenkins,intelchen/jenkins,jpederzolli/jenkins-1,bkmeneguello/jenkins,Krasnyanskiy/jenkins,noikiy/jenkins,vlajos/jenkins,intelchen/jenkins,lvotypko/jenkins3,evernat/jenkins,varmenise/jenkins,akshayabd/jenkins,liorhson/jenkins,Krasnyanskiy/jenkins,csimons/jenkins,chbiel/jenkins,goldchang/jenkins,jcsirot/jenkins,goldchang/jenkins,viqueen/jenkins,hashar/jenkins,6WIND/jenkins,elkingtonmcb/jenkins,lindzh/jenkins,292388900/jenkins,andresrc/jenkins,amruthsoft9/Jenkis,Wilfred/jenkins,daspilker/jenkins,NehemiahMi/jenkins,tfennelly/jenkins,akshayabd/jenkins,NehemiahMi/jenkins,godfath3r/jenkins,h4ck3rm1k3/jenkins,amruthsoft9/Jenkis,khmarbaise/jenkins,luoqii/jenkins,Ykus/jenkins,hemantojhaa/jenkins,brunocvcunha/jenkins,arunsingh/jenkins,mpeltonen/jenkins,dennisjlee/jenkins,DoctorQ/jenkins,mcanthony/jenkins,dennisjlee/jenkins,github-api-test-org/jenkins,jzjzjzj/jenkins,paulmillar/jenkins,deadmoose/jenkins,aheritier/jenkins,samatdav/jenkins,pselle/jenkins,godfath3r/jenkins,goldchang/jenkins,MichaelPranovich/jenkins_sc,ChrisA89/jenkins,pantheon-systems/jenkins,synopsys-arc-oss/jenkins,soenter/jenkins,paulmillar/jenkins,deadmoose/jenkins,alvarolobato/jenkins,jk47/jenkins,h4ck3rm1k3/jenkins,stefanbrausch/hudson-main,ChrisA89/jenkins,dennisjlee/jenkins,MadsNielsen/jtemp,singh88/jenkins,olivergondza/jenkins,kohsuke/hudson,gitaccountforprashant/gittest,verbitan/jenkins,nandan4/Jenkins,duzifang/my-jenkins,292388900/jenkins,mrobinet/jenkins,Ykus/jenkins,lordofthejars/jenkins,lilyJi/jenkins,batmat/jenkins,pantheon-systems/jenkins,kohsuke/hudson,mrobinet/jenkins,ns163/jenkins,pjanouse/jenkins,ajshastri/jenkins,hplatou/jenkins,mpeltonen/jenkins,albers/jenkins,scoheb/jenkins,v1v/jenkins,singh88/jenkins,tfennelly/jenkins,h4ck3rm1k3/jenkins,iterate/coding-dojo,jcsirot/jenkins,protazy/jenkins,svanoort/jenkins,lilyJi/jenkins,bpzhang/jenkins,KostyaSha/jenkins,paulmillar/jenkins,daspilker/jenkins,jglick/jenkins,maikeffi/hudson,jpederzolli/jenkins-1,guoxu0514/jenkins,jpederzolli/jenkins-1,gusreiber/jenkins,DoctorQ/jenkins,DoctorQ/jenkins,pselle/jenkins,patbos/jenkins,jenkinsci/jenkins,bkmeneguello/jenkins,aheritier/jenkins,morficus/jenkins,intelchen/jenkins,tastatur/jenkins,FarmGeek4Life/jenkins,akshayabd/jenkins,NehemiahMi/jenkins,noikiy/jenkins,luoqii/jenkins,oleg-nenashev/jenkins,jglick/jenkins,wuwen5/jenkins,seanlin816/jenkins,rashmikanta-1984/jenkins,jenkinsci/jenkins,wangyikai/jenkins,wuwen5/jenkins,msrb/jenkins,vlajos/jenkins,iterate/coding-dojo,Jimilian/jenkins,daspilker/jenkins,MichaelPranovich/jenkins_sc,olivergondza/jenkins,pselle/jenkins,Ykus/jenkins,jtnord/jenkins,ikedam/jenkins,petermarcoen/jenkins,aquarellian/jenkins,Ykus/jenkins,lvotypko/jenkins3,hashar/jenkins,daniel-beck/jenkins,dariver/jenkins,tfennelly/jenkins,wangyikai/jenkins,lvotypko/jenkins3,aduprat/jenkins,jenkinsci/jenkins,rlugojr/jenkins,6WIND/jenkins,christ66/jenkins,Vlatombe/jenkins,duzifang/my-jenkins,mpeltonen/jenkins,fbelzunc/jenkins,liorhson/jenkins,daniel-beck/jenkins,amruthsoft9/Jenkis,jcsirot/jenkins,soenter/jenkins,DanielWeber/jenkins,ikedam/jenkins,liupugong/jenkins,vvv444/jenkins,lvotypko/jenkins2,tastatur/jenkins,rsandell/jenkins,iqstack/jenkins,arcivanov/jenkins,Vlatombe/jenkins,github-api-test-org/jenkins,v1v/jenkins,oleg-nenashev/jenkins,dennisjlee/jenkins,soenter/jenkins,verbitan/jenkins,ajshastri/jenkins,daspilker/jenkins,Jimilian/jenkins,jcarrothers-sap/jenkins,paulmillar/jenkins,MarkEWaite/jenkins,dbroady1/jenkins,vijayto/jenkins,Wilfred/jenkins,aldaris/jenkins,msrb/jenkins,everyonce/jenkins,maikeffi/hudson,vivek/hudson,khmarbaise/jenkins,tastatur/jenkins,Jochen-A-Fuerbacher/jenkins,abayer/jenkins,patbos/jenkins,jcsirot/jenkins,morficus/jenkins,jk47/jenkins,mrooney/jenkins,sathiya-mit/jenkins,everyonce/jenkins,olivergondza/jenkins,Wilfred/jenkins,MadsNielsen/jtemp,MadsNielsen/jtemp,singh88/jenkins,MarkEWaite/jenkins,ajshastri/jenkins,daniel-beck/jenkins,mcanthony/jenkins,pantheon-systems/jenkins,DanielWeber/jenkins,lindzh/jenkins,jhoblitt/jenkins,CodeShane/jenkins,ikedam/jenkins,292388900/jenkins,huybrechts/hudson,yonglehou/jenkins,vvv444/jenkins,gorcz/jenkins,petermarcoen/jenkins,mrobinet/jenkins,vijayto/jenkins,jk47/jenkins,Krasnyanskiy/jenkins,jzjzjzj/jenkins,oleg-nenashev/jenkins,yonglehou/jenkins,mrooney/jenkins,svanoort/jenkins,brunocvcunha/jenkins,recena/jenkins,escoem/jenkins,arcivanov/jenkins,jenkinsci/jenkins,chbiel/jenkins,soenter/jenkins,jpederzolli/jenkins-1,ErikVerheul/jenkins,bpzhang/jenkins,jpederzolli/jenkins-1,csimons/jenkins,recena/jenkins,mcanthony/jenkins,duzifang/my-jenkins,rlugojr/jenkins,csimons/jenkins,andresrc/jenkins,DoctorQ/jenkins,damianszczepanik/jenkins,stephenc/jenkins,MichaelPranovich/jenkins_sc,intelchen/jenkins,deadmoose/jenkins,Wilfred/jenkins,gusreiber/jenkins,FTG-003/jenkins,iqstack/jenkins,everyonce/jenkins,Jimilian/jenkins,lvotypko/jenkins2,SebastienGllmt/jenkins,keyurpatankar/hudson,petermarcoen/jenkins,DanielWeber/jenkins,rashmikanta-1984/jenkins,lilyJi/jenkins,rlugojr/jenkins,lvotypko/jenkins,bkmeneguello/jenkins,ydubreuil/jenkins,soenter/jenkins,goldchang/jenkins,thomassuckow/jenkins,seanlin816/jenkins,christ66/jenkins,KostyaSha/jenkins,amruthsoft9/Jenkis,ns163/jenkins,ndeloof/jenkins,my7seven/jenkins,albers/jenkins,chbiel/jenkins,tangkun75/jenkins,ChrisA89/jenkins,svanoort/jenkins,azweb76/jenkins,iterate/coding-dojo,christ66/jenkins,huybrechts/hudson,alvarolobato/jenkins,kzantow/jenkins,dbroady1/jenkins,daniel-beck/jenkins,huybrechts/hudson,amruthsoft9/Jenkis,ydubreuil/jenkins,lilyJi/jenkins,verbitan/jenkins,paulwellnerbou/jenkins,vivek/hudson,AustinKwang/jenkins,6WIND/jenkins,aquarellian/jenkins,v1v/jenkins,damianszczepanik/jenkins,stefanbrausch/hudson-main,lordofthejars/jenkins,luoqii/jenkins,oleg-nenashev/jenkins,vivek/hudson,jzjzjzj/jenkins,tangkun75/jenkins,hudson/hudson-2.x,paulwellnerbou/jenkins,evernat/jenkins,andresrc/jenkins,MarkEWaite/jenkins,liorhson/jenkins,mrobinet/jenkins,aheritier/jenkins,keyurpatankar/hudson,mpeltonen/jenkins,pjanouse/jenkins,SebastienGllmt/jenkins,viqueen/jenkins,Jimilian/jenkins,6WIND/jenkins,rashmikanta-1984/jenkins,AustinKwang/jenkins,github-api-test-org/jenkins,CodeShane/jenkins,christ66/jenkins,arunsingh/jenkins,maikeffi/hudson,escoem/jenkins,tastatur/jenkins,lvotypko/jenkins3,dennisjlee/jenkins,mrooney/jenkins,arcivanov/jenkins,stefanbrausch/hudson-main,vlajos/jenkins,wangyikai/jenkins,hemantojhaa/jenkins,batmat/jenkins,amuniz/jenkins,mattclark/jenkins,daspilker/jenkins,amruthsoft9/Jenkis,ajshastri/jenkins,fbelzunc/jenkins,jk47/jenkins,verbitan/jenkins,dbroady1/jenkins,DanielWeber/jenkins,jcsirot/jenkins,vvv444/jenkins,ns163/jenkins,ErikVerheul/jenkins,aduprat/jenkins,FarmGeek4Life/jenkins,stephenc/jenkins,keyurpatankar/hudson,luoqii/jenkins,abayer/jenkins,KostyaSha/jenkins,damianszczepanik/jenkins,msrb/jenkins,vlajos/jenkins,varmenise/jenkins,jcarrothers-sap/jenkins,bkmeneguello/jenkins,gorcz/jenkins,arcivanov/jenkins,khmarbaise/jenkins,batmat/jenkins,keyurpatankar/hudson,lvotypko/jenkins,lvotypko/jenkins,aquarellian/jenkins,paulmillar/jenkins,v1v/jenkins,rsandell/jenkins,DanielWeber/jenkins,vjuranek/jenkins,deadmoose/jenkins,noikiy/jenkins,mdonohue/jenkins,mcanthony/jenkins,escoem/jenkins,pselle/jenkins,gusreiber/jenkins,jk47/jenkins,vijayto/jenkins,vvv444/jenkins,huybrechts/hudson,tastatur/jenkins,rashmikanta-1984/jenkins,damianszczepanik/jenkins,FTG-003/jenkins,albers/jenkins,vijayto/jenkins,albers/jenkins,jhoblitt/jenkins,lvotypko/jenkins,intelchen/jenkins,mcanthony/jenkins,pjanouse/jenkins,h4ck3rm1k3/jenkins,SenolOzer/jenkins,evernat/jenkins,paulwellnerbou/jenkins,azweb76/jenkins,deadmoose/jenkins,SebastienGllmt/jenkins,aduprat/jenkins,MichaelPranovich/jenkins_sc,tangkun75/jenkins,MarkEWaite/jenkins,keyurpatankar/hudson,sathiya-mit/jenkins,thomassuckow/jenkins,1and1/jenkins,jglick/jenkins,stephenc/jenkins,Vlatombe/jenkins,rlugojr/jenkins,1and1/jenkins,sathiya-mit/jenkins,viqueen/jenkins,jpederzolli/jenkins-1,lilyJi/jenkins,morficus/jenkins,amuniz/jenkins,Vlatombe/jenkins,gitaccountforprashant/gittest,arcivanov/jenkins,mrooney/jenkins,hplatou/jenkins,noikiy/jenkins,shahharsh/jenkins,ChrisA89/jenkins,maikeffi/hudson,paulmillar/jenkins,dbroady1/jenkins,arunsingh/jenkins,ndeloof/jenkins,liorhson/jenkins,daniel-beck/jenkins,my7seven/jenkins,ajshastri/jenkins,jglick/jenkins,FTG-003/jenkins,chbiel/jenkins,oleg-nenashev/jenkins,KostyaSha/jenkins,christ66/jenkins,stefanbrausch/hudson-main,CodeShane/jenkins,abayer/jenkins,lindzh/jenkins,seanlin816/jenkins,morficus/jenkins,msrb/jenkins,github-api-test-org/jenkins,ns163/jenkins,vjuranek/jenkins,lvotypko/jenkins2,vlajos/jenkins,alvarolobato/jenkins,recena/jenkins,Jochen-A-Fuerbacher/jenkins,guoxu0514/jenkins,iqstack/jenkins,patbos/jenkins,varmenise/jenkins,pselle/jenkins,arunsingh/jenkins,SebastienGllmt/jenkins,lordofthejars/jenkins,NehemiahMi/jenkins,wuwen5/jenkins,hashar/jenkins,Jochen-A-Fuerbacher/jenkins,arunsingh/jenkins,aldaris/jenkins,rashmikanta-1984/jenkins,sathiya-mit/jenkins,pselle/jenkins,kohsuke/hudson,1and1/jenkins,MichaelPranovich/jenkins_sc,amuniz/jenkins,shahharsh/jenkins,guoxu0514/jenkins,mdonohue/jenkins,deadmoose/jenkins,nandan4/Jenkins,paulwellnerbou/jenkins,stefanbrausch/hudson-main,damianszczepanik/jenkins,duzifang/my-jenkins,mdonohue/jenkins,duzifang/my-jenkins,kzantow/jenkins,damianszczepanik/jenkins,jpbriend/jenkins,jpbriend/jenkins,mattclark/jenkins,hudson/hudson-2.x,ErikVerheul/jenkins,stefanbrausch/hudson-main,aquarellian/jenkins,dbroady1/jenkins,6WIND/jenkins,mpeltonen/jenkins,SebastienGllmt/jenkins,jhoblitt/jenkins,mrooney/jenkins,christ66/jenkins,stephenc/jenkins,lilyJi/jenkins,hashar/jenkins,thomassuckow/jenkins,evernat/jenkins,msrb/jenkins,aheritier/jenkins,mdonohue/jenkins,ChrisA89/jenkins,Jochen-A-Fuerbacher/jenkins,AustinKwang/jenkins,DoctorQ/jenkins,azweb76/jenkins,aduprat/jenkins,vivek/hudson,hplatou/jenkins,tastatur/jenkins,rsandell/jenkins,huybrechts/hudson,liupugong/jenkins,my7seven/jenkins,wuwen5/jenkins,olivergondza/jenkins,rsandell/jenkins,iqstack/jenkins,vlajos/jenkins,paulwellnerbou/jenkins,hplatou/jenkins,hplatou/jenkins,ndeloof/jenkins,soenter/jenkins,ikedam/jenkins,elkingtonmcb/jenkins,noikiy/jenkins,oleg-nenashev/jenkins,andresrc/jenkins,intelchen/jenkins,akshayabd/jenkins,alvarolobato/jenkins,hemantojhaa/jenkins,kohsuke/hudson,ydubreuil/jenkins,keyurpatankar/hudson,kzantow/jenkins,samatdav/jenkins,thomassuckow/jenkins,kohsuke/hudson,brunocvcunha/jenkins,ns163/jenkins,ikedam/jenkins,huybrechts/hudson,chbiel/jenkins,stephenc/jenkins,wuwen5/jenkins,luoqii/jenkins,chbiel/jenkins,rsandell/jenkins,MadsNielsen/jtemp,jcarrothers-sap/jenkins,scoheb/jenkins,aldaris/jenkins,hashar/jenkins,jzjzjzj/jenkins,jpbriend/jenkins,FTG-003/jenkins,goldchang/jenkins,synopsys-arc-oss/jenkins,stefanbrausch/hudson-main,ndeloof/jenkins,maikeffi/hudson,azweb76/jenkins,aheritier/jenkins,arcivanov/jenkins,hudson/hudson-2.x,jtnord/jenkins,Wilfred/jenkins,vvv444/jenkins,lvotypko/jenkins,noikiy/jenkins,v1v/jenkins,FarmGeek4Life/jenkins,albers/jenkins,jcsirot/jenkins,jpederzolli/jenkins-1,ChrisA89/jenkins,gusreiber/jenkins,kzantow/jenkins,lvotypko/jenkins2,FarmGeek4Life/jenkins,gitaccountforprashant/gittest,pantheon-systems/jenkins,vvv444/jenkins,ns163/jenkins,brunocvcunha/jenkins,thomassuckow/jenkins,liupugong/jenkins,amuniz/jenkins,nandan4/Jenkins,Krasnyanskiy/jenkins,csimons/jenkins,iqstack/jenkins,everyonce/jenkins,godfath3r/jenkins,gorcz/jenkins,goldchang/jenkins,maikeffi/hudson,samatdav/jenkins,jzjzjzj/jenkins,aldaris/jenkins,patbos/jenkins,lindzh/jenkins,evernat/jenkins,svanoort/jenkins,azweb76/jenkins,Jochen-A-Fuerbacher/jenkins,MichaelPranovich/jenkins_sc,scoheb/jenkins,v1v/jenkins,KostyaSha/jenkins,DanielWeber/jenkins,huybrechts/hudson,CodeShane/jenkins,scoheb/jenkins,lindzh/jenkins,ndeloof/jenkins,my7seven/jenkins,mattclark/jenkins,fbelzunc/jenkins,FarmGeek4Life/jenkins,abayer/jenkins,6WIND/jenkins,jglick/jenkins,recena/jenkins,vjuranek/jenkins,Krasnyanskiy/jenkins,pselle/jenkins,evernat/jenkins,everyonce/jenkins,ydubreuil/jenkins,dariver/jenkins,tangkun75/jenkins,kohsuke/hudson,dariver/jenkins,hashar/jenkins,mdonohue/jenkins,jenkinsci/jenkins,paulwellnerbou/jenkins,andresrc/jenkins,MarkEWaite/jenkins,samatdav/jenkins,viqueen/jenkins,khmarbaise/jenkins,tfennelly/jenkins,vijayto/jenkins,batmat/jenkins,pjanouse/jenkins,lilyJi/jenkins,vijayto/jenkins,batmat/jenkins,fbelzunc/jenkins,andresrc/jenkins,aquarellian/jenkins,arcivanov/jenkins,keyurpatankar/hudson,AustinKwang/jenkins,protazy/jenkins,liupugong/jenkins,lordofthejars/jenkins,bpzhang/jenkins,mrobinet/jenkins,rashmikanta-1984/jenkins,Ykus/jenkins,recena/jenkins,escoem/jenkins,aquarellian/jenkins,MarkEWaite/jenkins,msrb/jenkins,msrb/jenkins,christ66/jenkins,bkmeneguello/jenkins,nandan4/Jenkins,NehemiahMi/jenkins,paulwellnerbou/jenkins,fbelzunc/jenkins,alvarolobato/jenkins,ErikVerheul/jenkins,vjuranek/jenkins,my7seven/jenkins,recena/jenkins,protazy/jenkins,aduprat/jenkins,liorhson/jenkins,singh88/jenkins,KostyaSha/jenkins,jglick/jenkins,verbitan/jenkins,jpbriend/jenkins,abayer/jenkins,tfennelly/jenkins,petermarcoen/jenkins,brunocvcunha/jenkins,synopsys-arc-oss/jenkins,aheritier/jenkins,albers/jenkins,yonglehou/jenkins,Krasnyanskiy/jenkins,svanoort/jenkins,kohsuke/hudson,ErikVerheul/jenkins,hemantojhaa/jenkins,seanlin816/jenkins,AustinKwang/jenkins,kzantow/jenkins,gitaccountforprashant/gittest,SenolOzer/jenkins,lvotypko/jenkins,hplatou/jenkins,stephenc/jenkins,jcarrothers-sap/jenkins,dariver/jenkins,amruthsoft9/Jenkis,6WIND/jenkins,azweb76/jenkins,damianszczepanik/jenkins,lvotypko/jenkins2,Ykus/jenkins,mrobinet/jenkins,jzjzjzj/jenkins,bkmeneguello/jenkins,dariver/jenkins,elkingtonmcb/jenkins,ikedam/jenkins,vjuranek/jenkins,thomassuckow/jenkins,svanoort/jenkins,FarmGeek4Life/jenkins,tfennelly/jenkins,KostyaSha/jenkins,csimons/jenkins,1and1/jenkins,lvotypko/jenkins,DanielWeber/jenkins,ndeloof/jenkins,maikeffi/hudson,SenolOzer/jenkins,jhoblitt/jenkins,morficus/jenkins,Jimilian/jenkins,bpzhang/jenkins,aquarellian/jenkins,viqueen/jenkins,alvarolobato/jenkins,gorcz/jenkins,bpzhang/jenkins,jpbriend/jenkins,singh88/jenkins,ikedam/jenkins,wangyikai/jenkins,patbos/jenkins,pantheon-systems/jenkins,mpeltonen/jenkins,rsandell/jenkins,csimons/jenkins,everyonce/jenkins,shahharsh/jenkins,singh88/jenkins,batmat/jenkins,deadmoose/jenkins,guoxu0514/jenkins,pjanouse/jenkins,godfath3r/jenkins,keyurpatankar/hudson,pantheon-systems/jenkins,wangyikai/jenkins,hudson/hudson-2.x,mattclark/jenkins,synopsys-arc-oss/jenkins,gorcz/jenkins,vijayto/jenkins,gusreiber/jenkins,Vlatombe/jenkins,mrobinet/jenkins,h4ck3rm1k3/jenkins,mattclark/jenkins,aduprat/jenkins,synopsys-arc-oss/jenkins,evernat/jenkins,abayer/jenkins,sathiya-mit/jenkins,jhoblitt/jenkins,MadsNielsen/jtemp,daspilker/jenkins,github-api-test-org/jenkins,CodeShane/jenkins,viqueen/jenkins,lvotypko/jenkins2,vivek/hudson,chbiel/jenkins,mdonohue/jenkins,everyonce/jenkins,lordofthejars/jenkins,escoem/jenkins,1and1/jenkins,rashmikanta-1984/jenkins,gitaccountforprashant/gittest,SenolOzer/jenkins,khmarbaise/jenkins,fbelzunc/jenkins,jk47/jenkins,rsandell/jenkins,bpzhang/jenkins,varmenise/jenkins,jzjzjzj/jenkins,alvarolobato/jenkins,lordofthejars/jenkins,olivergondza/jenkins | package hudson.scm;
import hudson.FilePath;
import hudson.FilePath.FileCallable;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Hudson;
import hudson.model.TaskListener;
import hudson.remoting.Callable;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.util.FormFieldValidator;
import hudson.util.IOException2;
import hudson.util.MultipartFormDataParser;
import hudson.util.Scrambler;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FileUtils;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Chmod;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationProvider;
import org.tmatesoft.svn.core.auth.SVNAuthentication;
import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication;
import org.tmatesoft.svn.core.auth.SVNSSHAuthentication;
import org.tmatesoft.svn.core.auth.SVNSSLAuthentication;
import org.tmatesoft.svn.core.auth.SVNUserNameAuthentication;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNAuthenticationManager;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNInfo;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;
import org.tmatesoft.svn.core.wc.SVNWCClient;
import org.tmatesoft.svn.core.wc.SVNWCUtil;
import javax.servlet.ServletException;
import javax.xml.transform.stream.StreamResult;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* Subversion SCM.
*
* @author Kohsuke Kawaguchi
*/
public class SubversionSCM extends SCM implements Serializable {
/**
* the locations field is used to store all configured SVN locations (with
* their local and remote part). Direct access to this filed should be
* avoided and the getLocations() method should be used instead. This is
* needed to make importing of old hudson-configurations possible as
* getLocations() will check if the modules field has been set and import
* the data.
*
* @since 1.91
*/
private ModuleLocation[] locations = new ModuleLocation[0];
private boolean useUpdate;
private String username;
private final SubversionRepositoryBrowser browser;
// No longer in use but left for serialization compatibility.
@Deprecated
private String modules;
SubversionSCM(String[] remoteLocations, String[] localLocations,
boolean useUpdate, String username, SubversionRepositoryBrowser browser) {
List<ModuleLocation> modules = new ArrayList<ModuleLocation>();
if (remoteLocations != null && localLocations != null) {
int entries = Math.min(remoteLocations.length, localLocations.length);
for (int i = 0; i < entries; i++) {
// the remote (repository) location
String remoteLoc = nullify(remoteLocations[i]);
if (remoteLoc != null) {// null if skipped
remoteLoc = Util.removeTrailingSlash(remoteLoc.trim());
modules.add(new ModuleLocation(remoteLoc, nullify(localLocations[i])));
}
}
}
locations = modules.toArray(new ModuleLocation[modules.size()]);
this.useUpdate = useUpdate;
this.username = nullify(username);
this.browser = browser;
}
/**
* @deprecated
* as of 1.91. Use {@link #getLocations()} instead.
*/
public String getModules() {
return null;
}
/**
* list of all configured svn locations
*
* @since 1.91
*/
public ModuleLocation[] getLocations() {
// check if we've got a old location
if (modules != null) {
// import the old configuration
List<ModuleLocation> oldLocations = new ArrayList<ModuleLocation>();
StringTokenizer tokens = new StringTokenizer(modules);
while (tokens.hasMoreTokens()) {
// the remote (repository location)
// the normalized name is always without the trailing '/'
String remoteLoc = Util.removeTrailingSlash(tokens.nextToken());
oldLocations.add(new ModuleLocation(remoteLoc, null));
}
locations = oldLocations.toArray(new ModuleLocation[oldLocations.size()]);
modules = null;
}
return locations;
}
public boolean isUseUpdate() {
return useUpdate;
}
public String getUsername() {
return username;
}
public SubversionRepositoryBrowser getBrowser() {
return browser;
}
/**
* Called after checkout/update has finished to compute the changelog.
*/
private boolean calcChangeLog(AbstractBuild<?,?> build, File changelogFile, BuildListener listener, List<String> externals) throws IOException, InterruptedException {
if(build.getPreviousBuild()==null) {
// nothing to compare against
return createEmptyChangeLog(changelogFile, listener, "log");
}
if(!new SubversionChangeLogBuilder(build,listener,this).run(externals,new StreamResult(changelogFile)))
createEmptyChangeLog(changelogFile, listener, "log");
return true;
}
/*package*/ static Map<String,Long> parseRevisionFile(AbstractBuild build) throws IOException {
Map<String,Long> revisions = new HashMap<String,Long>(); // module -> revision
{// read the revision file of the last build
File file = getRevisionFile(build);
if(!file.exists())
// nothing to compare against
return revisions;
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while((line=br.readLine())!=null) {
int index = line.lastIndexOf('/');
if(index<0) {
continue; // invalid line?
}
try {
revisions.put(line.substring(0,index), Long.parseLong(line.substring(index+1)));
} catch (NumberFormatException e) {
// perhaps a corrupted line. ignore
}
}
}
return revisions;
}
/**
* Parses the file that stores the locations in the workspace where modules loaded by svn:external
* is placed.
*/
/*package*/ static List<String> parseExternalsFile(AbstractProject project) throws IOException {
List<String> ext = new ArrayList<String>(); // workspace-relative path
{// read the revision file of the last build
File file = getExternalsFile(project);
if(!file.exists())
// nothing to compare against
return ext;
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String line;
while((line=br.readLine())!=null) {
ext.add(line);
}
} finally {
br.close();
}
}
return ext;
}
public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, final BuildListener listener, File changelogFile) throws IOException, InterruptedException {
List<String> externals = checkout(workspace,listener);
if(externals==null)
return false;
// write out the revision file
PrintWriter w = new PrintWriter(new FileOutputStream(getRevisionFile(build)));
try {
Map<String,SvnInfo> revMap = buildRevisionMap(workspace,listener,externals);
for (Entry<String,SvnInfo> e : revMap.entrySet()) {
w.println( e.getKey() +'/'+ e.getValue().revision );
}
if(tagEnabled)
build.addAction(new SubversionTagAction(build,revMap.values()));
} finally {
w.close();
}
// write out the externals info
w = new PrintWriter(new FileOutputStream(getExternalsFile(build.getProject())));
try {
for (String p : externals) {
w.println( p );
}
} finally {
w.close();
}
return calcChangeLog(build, changelogFile, listener, externals);
}
/**
* Performs the checkout or update, depending on the configuration and workspace state.
*
* @return null
* if the operation failed. Otherwise the set of local workspace paths
* (relative to the workspace root) that has loaded due to svn:external.
*/
private List<String> checkout(FilePath workspace, final TaskListener listener) throws IOException, InterruptedException {
final ISVNAuthenticationProvider authProvider = getDescriptor().createAuthenticationProvider();
// true to "svn update", false to "svn checkout".
final boolean update = useUpdate && isUpdatable(workspace, listener);
return workspace.act(new FileCallable<List<String>>() {
public List<String> invoke(File ws, VirtualChannel channel) throws IOException {
SVNUpdateClient svnuc = createSvnClientManager(authProvider).getUpdateClient();
List<String> externals = new ArrayList<String>(); // store discovered externals to here
if(update) {
for (ModuleLocation l : getLocations()) {
try {
listener.getLogger().println("Updating "+ l.remote);
svnuc.setEventHandler(new SubversionUpdateEventHandler(listener, externals, l.local));
svnuc.doUpdate(new File(ws, l.local), SVNRevision.HEAD, true);
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to update "+l.remote));
return null;
}
}
} else {
Util.deleteContentsRecursive(ws);
for (ModuleLocation l : getLocations()) {
try {
SVNURL url = SVNURL.parseURIEncoded(l.remote);
listener.getLogger().println("Checking out "+url);
svnuc.setEventHandler(new SubversionUpdateEventHandler(listener, externals, l.local));
svnuc.doCheckout(url, new File(ws, l.local), SVNRevision.HEAD, SVNRevision.HEAD, true);
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to check out "+l.remote));
return null;
}
}
}
return externals;
}
});
}
/**
* Creates {@link SVNClientManager}.
*
* <p>
* This method must be executed on the slave where svn operations are performed.
*
* @param authProvider
* The value obtained from {@link DescriptorImpl#createAuthenticationProvider()}.
* If the operation runs on slaves,
* (and properly remoted, if the svn operations run on slaves.)
*/
/*package*/ static SVNClientManager createSvnClientManager(ISVNAuthenticationProvider authProvider) {
ISVNAuthenticationManager sam = SVNWCUtil.createDefaultAuthenticationManager();
sam.setAuthenticationProvider(authProvider);
return SVNClientManager.newInstance(SVNWCUtil.createDefaultOptions(true),sam);
}
public static final class SvnInfo implements Serializable, Comparable<SvnInfo> {
/**
* Decoded repository URL.
*/
public final String url;
public final long revision;
public SvnInfo(String url, long revision) {
this.url = url;
this.revision = revision;
}
public SvnInfo(SVNInfo info) {
this( info.getURL().toDecodedString(), info.getCommittedRevision().getNumber() );
}
public SVNURL getSVNURL() throws SVNException {
return SVNURL.parseURIDecoded(url);
}
public int compareTo(SvnInfo that) {
int r = this.url.compareTo(that.url);
if(r!=0) return r;
if(this.revision<that.revision) return -1;
if(this.revision>that.revision) return +1;
return 0;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SvnInfo svnInfo = (SvnInfo) o;
if (revision != svnInfo.revision) return false;
if (!url.equals(svnInfo.url)) return false;
return true;
}
public int hashCode() {
int result;
result = url.hashCode();
result = 31 * result + (int) (revision ^ (revision >>> 32));
return result;
}
public String toString() {
return String.format("%s (rev.%s)",url,revision);
}
private static final long serialVersionUID = 1L;
}
/**
* Gets the SVN metadata for the given local workspace.
*
* @param workspace
* The target to run "svn info".
*/
private SVNInfo parseSvnInfo(File workspace, ISVNAuthenticationProvider authProvider) throws SVNException {
SVNWCClient svnWc = createSvnClientManager(authProvider).getWCClient();
return svnWc.doInfo(workspace,SVNRevision.WORKING);
}
/**
* Gets the SVN metadata for the remote repository.
*
* @param remoteUrl
* The target to run "svn info".
*/
private SVNInfo parseSvnInfo(SVNURL remoteUrl, ISVNAuthenticationProvider authProvider) throws SVNException {
SVNWCClient svnWc = createSvnClientManager(authProvider).getWCClient();
return svnWc.doInfo(remoteUrl, SVNRevision.HEAD, SVNRevision.HEAD);
}
/**
* Checks .svn files in the workspace and finds out revisions of the modules
* that the workspace has.
*
* @return
* null if the parsing somehow fails. Otherwise a map from the repository URL to revisions.
*/
private Map<String,SvnInfo> buildRevisionMap(FilePath workspace, final TaskListener listener, final List<String> externals) throws IOException, InterruptedException {
final ISVNAuthenticationProvider authProvider = getDescriptor().createAuthenticationProvider();
return workspace.act(new FileCallable<Map<String,SvnInfo>>() {
public Map<String,SvnInfo> invoke(File ws, VirtualChannel channel) throws IOException {
Map<String/*module name*/,SvnInfo> revisions = new HashMap<String,SvnInfo>();
SVNWCClient svnWc = createSvnClientManager(authProvider).getWCClient();
// invoke the "svn info"
for( ModuleLocation module : getLocations() ) {
try {
SvnInfo info = new SvnInfo(svnWc.doInfo(new File(ws,module.local),SVNRevision.WORKING));
revisions.put(info.url,info);
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to parse svn info for "+module));
}
}
for(String local : externals){
try {
SvnInfo info = new SvnInfo(svnWc.doInfo(new File(ws, local),SVNRevision.WORKING));
revisions.put(info.url,info);
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to parse svn info for external "+local));
}
}
return revisions;
}
});
}
/**
* Gets the file that stores the revision.
*/
private static File getRevisionFile(AbstractBuild build) {
return new File(build.getRootDir(),"revision.txt");
}
/**
* Gets the file that stores the externals.
*/
private static File getExternalsFile(AbstractProject project) {
return new File(project.getRootDir(),"svnexternals.txt");
}
/**
* Returns true if we can use "svn update" instead of "svn checkout"
*/
private boolean isUpdatable(FilePath workspace, final TaskListener listener) throws IOException, InterruptedException {
final ISVNAuthenticationProvider authProvider = getDescriptor().createAuthenticationProvider();
return workspace.act(new FileCallable<Boolean>() {
public Boolean invoke(File ws, VirtualChannel channel) throws IOException {
for (ModuleLocation l : getLocations()) {
String url = l.remote;
String moduleName = l.local;
File module = new File(ws,moduleName).getCanonicalFile(); // canonicalize to remove ".." and ".". See #474
if(!module.exists()) {
listener.getLogger().println("Checking out a fresh workspace because "+module+" doesn't exist");
return false;
}
try {
SvnInfo svnInfo = new SvnInfo(parseSvnInfo(module,authProvider));
if(!svnInfo.url.equals(url)) {
listener.getLogger().println("Checking out a fresh workspace because the workspace is not "+url);
return false;
}
} catch (SVNException e) {
listener.getLogger().println("Checking out a fresh workspace because Hudson failed to detect the current workspace "+module);
e.printStackTrace(listener.error(e.getMessage()));
return false;
}
}
return true;
}
});
}
public boolean pollChanges(AbstractProject project, Launcher launcher, FilePath workspace, TaskListener listener) throws IOException, InterruptedException {
// we need to load the externals info, if any
List<String> externals = parseExternalsFile(project);
// current workspace revision
Map<String,SvnInfo> wsRev = buildRevisionMap(workspace,listener,externals);
ISVNAuthenticationProvider authProvider = getDescriptor().createAuthenticationProvider();
// check the corresponding remote revision
for (SvnInfo localInfo : wsRev.values()) {
try {
SvnInfo remoteInfo = new SvnInfo(parseSvnInfo(localInfo.getSVNURL(),authProvider));
listener.getLogger().println("Revision:"+remoteInfo.revision);
if(remoteInfo.revision > localInfo.revision)
return true; // change found
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to check repository revision for "+localInfo.url));
}
}
return false; // no change
}
public ChangeLogParser createChangeLogParser() {
return new SubversionChangeLogParser();
}
public DescriptorImpl getDescriptor() {
return DescriptorImpl.DESCRIPTOR;
}
public FilePath getModuleRoot(FilePath workspace) {
if (getLocations().length > 0)
return workspace.child(getLocations()[0].local);
return workspace;
}
private static String getLastPathComponent(String s) {
String[] tokens = s.split("/");
return tokens[tokens.length-1]; // return the last token
}
public static final class DescriptorImpl extends SCMDescriptor<SubversionSCM> {
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
/**
* SVN authentication realm to its associated credentials.
*/
private final Map<String,Credential> credentials = new Hashtable<String,Credential>();
/**
* Stores {@link SVNAuthentication} for a single realm.
*
* <p>
* {@link Credential} holds data in a persistence-friendly way,
* and it's capable of creating {@link SVNAuthentication} object,
* to be passed to SVNKit.
*/
private static abstract class Credential implements Serializable {
/**
* @param kind
* One of the constants defined in {@link ISVNAuthenticationManager},
* indicating what subype of {@link SVNAuthentication} is expected.
*/
abstract SVNAuthentication createSVNAuthentication(String kind) throws SVNException;
}
/**
* Username/password based authentication.
*/
private static final class PasswordCredential extends Credential {
private final String userName;
private final String password; // scrambled by base64
public PasswordCredential(String userName, String password) {
this.userName = userName;
this.password = Scrambler.scramble(password);
}
@Override
SVNAuthentication createSVNAuthentication(String kind) {
if(kind.equals(ISVNAuthenticationManager.SSH))
return new SVNSSHAuthentication(userName,password,-1,false);
else
return new SVNPasswordAuthentication(userName,Scrambler.descramble(password),false);
}
}
/**
* Publickey authentication for Subversion over SSH.
*/
private static final class SshPublicKeyCredential extends Credential {
private final String userName;
private final String passphrase; // scrambled by base64
private final String id;
/**
* @param keyFile
* stores SSH private key. The file will be copied.
*/
public SshPublicKeyCredential(String userName, String passphrase, File keyFile) throws SVNException {
this.userName = userName;
this.passphrase = Scrambler.scramble(passphrase);
Random r = new Random();
StringBuilder buf = new StringBuilder();
for(int i=0;i<16;i++)
buf.append(Integer.toHexString(r.nextInt(16)));
this.id = buf.toString();
try {
FileUtils.copyFile(keyFile,getKeyFile());
} catch (IOException e) {
throw new SVNException(SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE,"Unable to save private key"),e);
}
}
/**
* Gets the location where the private key will be permanently stored.
*/
private File getKeyFile() {
File dir = new File(Hudson.getInstance().getRootDir(),"subversion-credentials");
if(dir.mkdirs()) {
// make sure the directory exists. if we created it, try to set the permission to 600
// since this is sensitive information
try {
Chmod chmod = new Chmod();
chmod.setProject(new Project());
chmod.setFile(dir);
chmod.setPerm("600");
chmod.execute();
} catch (Throwable e) {
// if we failed to set the permission, that's fine.
LOGGER.log(Level.WARNING, "Failed to set directory permission of "+dir,e);
}
}
return new File(dir,id);
}
@Override
SVNSSHAuthentication createSVNAuthentication(String kind) throws SVNException {
if(kind.equals(ISVNAuthenticationManager.SSH)) {
try {
Channel channel = Channel.current();
String privateKey;
if(channel!=null) {
// remote
privateKey = channel.call(new Callable<String,IOException>() {
public String call() throws IOException {
return FileUtils.readFileToString(getKeyFile(),"iso-8859-1");
}
});
} else {
privateKey = FileUtils.readFileToString(getKeyFile(),"iso-8859-1");
}
return new SVNSSHAuthentication(userName, privateKey.toCharArray(), Scrambler.descramble(passphrase),-1,false);
} catch (IOException e) {
throw new SVNException(SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE,"Unable to load private key"),e);
} catch (InterruptedException e) {
throw new SVNException(SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE,"Unable to load private key"),e);
}
} else
return null; // unknown
}
}
/**
* SSL client certificate based authentication.
*/
private static final class SslClientCertificateCredential extends Credential {
private final String password; // scrambled by base64
public SslClientCertificateCredential(File certificate, String password) {
this.password = Scrambler.scramble(password);
}
@Override
SVNAuthentication createSVNAuthentication(String kind) {
if(kind.equals(ISVNAuthenticationManager.SSL))
return new SVNSSLAuthentication(null,Scrambler.descramble(password),false);
else
return null; // unexpected authentication type
}
}
/**
* Remoting interface that allows remote {@link ISVNAuthenticationProvider}
* to read from local {@link DescriptorImpl#credentials}.
*/
private interface RemotableSVNAuthenticationProvider {
Credential getCredential(String realm);
}
private final class RemotableSVNAuthenticationProviderImpl implements RemotableSVNAuthenticationProvider, Serializable {
public Credential getCredential(String realm) {
LOGGER.fine(String.format("getCredential(%s)=>%s",realm,credentials.get(realm)));
return credentials.get(realm);
}
/**
* When sent to the remote node, send a proxy.
*/
private Object writeReplace() {
return Channel.current().export(RemotableSVNAuthenticationProvider.class, this);
}
}
/**
* See {@link DescriptorImpl#createAuthenticationProvider()}.
*/
private static final class SVNAuthenticationProviderImpl implements ISVNAuthenticationProvider, Serializable {
private final RemotableSVNAuthenticationProvider source;
public SVNAuthenticationProviderImpl(RemotableSVNAuthenticationProvider source) {
this.source = source;
}
public SVNAuthentication requestClientAuthentication(String kind, SVNURL url, String realm, SVNErrorMessage errorMessage, SVNAuthentication previousAuth, boolean authMayBeStored) {
Credential cred = source.getCredential(realm);
LOGGER.fine(String.format("requestClientAuthentication(%s,%s,%s)=>%s",kind,url,realm,cred));
if(cred==null) {
// this happens with file:// URL. The base class does this, too.
if (ISVNAuthenticationManager.USERNAME.equals(kind))
// user auth shouldn't be null.
return new SVNUserNameAuthentication("",false);
}
try {
return cred.createSVNAuthentication(kind);
} catch (SVNException e) {
logger.log(Level.SEVERE, "Failed to authorize",e);
throw new RuntimeException("Failed to authorize",e);
}
}
public int acceptServerAuthentication(SVNURL url, String realm, Object certificate, boolean resultMayBeStored) {
return ACCEPTED_TEMPORARY;
}
private static final long serialVersionUID = 1L;
}
private DescriptorImpl() {
super(SubversionSCM.class,SubversionRepositoryBrowser.class);
load();
}
public String getDisplayName() {
return "Subversion";
}
public SCM newInstance(StaplerRequest req) throws FormException {
return new SubversionSCM(
req.getParameterValues("svn.location_remote"),
req.getParameterValues("svn.location_local"),
req.getParameter("svn_use_update") != null,
req.getParameter("svn_username"),
RepositoryBrowsers.createInstance(SubversionRepositoryBrowser.class, req, "svn.browser"));
}
/**
* Creates {@link ISVNAuthenticationProvider} backed by {@link #credentials}.
* This method must be invoked on the master, but the returned object is remotable.
*/
public ISVNAuthenticationProvider createAuthenticationProvider() {
return new SVNAuthenticationProviderImpl(new RemotableSVNAuthenticationProviderImpl());
}
/**
* Submits the authentication info.
*
* This code is fairly ugly because of the way SVNKit handles credentials.
*/
public void doPostCredential(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
if(!Hudson.adminCheck(req,rsp)) return;
MultipartFormDataParser parser = new MultipartFormDataParser(req);
String url = parser.get("url");
String kind = parser.get("kind");
int idx = Arrays.asList("","password","publickey","certificate").indexOf(kind);
final String username = parser.get("username"+idx);
final String password = parser.get("password"+idx);
// SVNKit wants a key in a file
final File keyFile;
FileItem item=null;
if(kind.equals("password")) {
keyFile = null;
} else {
item = parser.getFileItem(kind.equals("publickey")?"privateKey":"certificate");
keyFile = File.createTempFile("hudson","key");
if(item!=null)
try {
item.write(keyFile);
} catch (Exception e) {
throw new IOException2(e);
}
}
try {
// the way it works with SVNKit is that
// 1) svnkit calls AuthenticationManager asking for a credential.
// this is when we can see the 'realm', which identifies the user domain.
// 2) DefaultSVNAuthenticationManager returns the username and password we set below
// 3) if the authentication is successful, svnkit calls back acknowledgeAuthentication
// (so we store the password info here)
SVNRepository repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
repository.setAuthenticationManager(new DefaultSVNAuthenticationManager(SVNWCUtil.getDefaultConfigurationDirectory(),true,username,password,keyFile,password) {
Credential cred = null;
@Override
public SVNAuthentication getFirstAuthentication(String kind, String realm, SVNURL url) throws SVNException {
if(kind.equals(ISVNAuthenticationManager.PASSWORD))
cred = new PasswordCredential(username,password);
if(kind.equals(ISVNAuthenticationManager.SSH)) {
if(keyFile==null)
cred = new PasswordCredential(username,password);
else
cred = new SshPublicKeyCredential(username,password,keyFile);
}
if(kind.equals(ISVNAuthenticationManager.SSL))
cred = new SslClientCertificateCredential(keyFile,password);
if(cred==null) return null;
return cred.createSVNAuthentication(kind);
}
@Override
public void acknowledgeAuthentication(boolean accepted, String kind, String realm, SVNErrorMessage errorMessage, SVNAuthentication authentication) throws SVNException {
if(accepted) {
assert cred!=null;
credentials.put(realm,cred);
save();
}
super.acknowledgeAuthentication(accepted, kind, realm, errorMessage, authentication);
}
});
repository.testConnection();
rsp.sendRedirect("credentialOK");
} catch (SVNException e) {
req.setAttribute("message",e.getErrorMessage());
rsp.forward(Hudson.getInstance(),"error",req);
} finally {
if(keyFile!=null)
keyFile.delete();
if(item!=null)
item.delete();
}
}
/**
* validate the value for a remote (repository) location.
*/
public void doSvnRemoteLocationCheck(final StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this can be used to hit any accessible URL, so limit that to admins
new FormFieldValidator(req, rsp, true) {
protected void check() throws IOException, ServletException {
// syntax check first
String url = Util.nullify(request.getParameter("value"));
if (url == null) {
ok(); // not entered yet
return;
}
// remove unneeded whitespaces
url = url.trim();
if(!URL_PATTERN.matcher(url).matches()) {
error("Invalid URL syntax. See "
+ "<a href=\"http://svnbook.red-bean.com/en/1.2/svn-book.html#svn.basic.in-action.wc.tbl-1\">this</a> "
+ "for information about valid URLs.");
return;
}
// test the connection
try {
SVNRepository repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
ISVNAuthenticationManager sam = SVNWCUtil.createDefaultAuthenticationManager();
sam.setAuthenticationProvider(createAuthenticationProvider());
repository.setAuthenticationManager(sam);
repository.testConnection();
ok();
} catch (SVNException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String message="";
message += "Unable to access "+url+" : "+Util.escape( e.getErrorMessage().getFullMessage());
message += " <a href='#' id=svnerrorlink onclick='javascript:" +
"document.getElementById(\"svnerror\").style.display=\"block\";" +
"document.getElementById(\"svnerrorlink\").style.display=\"none\";" +
"return false;'>(show details)</a>";
message += "<pre id=svnerror style='display:none'>"+sw+"</pre>";
message += " (Maybe you need to <a href='"+req.getContextPath()+"/scm/SubversionSCM/enterCredential?"+url+"'>enter credential</a>?)";
message += "<br>";
logger.log(Level.INFO, "Failed to access subversion repository "+url,e);
error(message);
}
}
}.process();
}
/**
* validate the value for a local location (local checkout directory).
*/
public void doSvnLocalLocationCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
new FormFieldValidator(req, rsp, false) {
protected void check() throws IOException, ServletException {
String v = Util.nullify(request.getParameter("value"));
if (v == null) {
// local directory is optional so this is ok
ok();
return;
}
v = v.trim();
// check if a absolute path has been supplied
// (the last check with the regex will match windows drives)
if (v.startsWith("/") || v.startsWith("\\") || v.startsWith("..") || v.matches("^[A-Za-z]:")) {
error("absolute path is not allowed");
}
// all tests passed so far
ok();
}
}.process();
}
static {
new Initializer();
}
}
static final Pattern URL_PATTERN = Pattern.compile("(https?|svn(\\+[a-z0-9]+)?|file)://.+");
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(SubversionSCM.class.getName());
static {
new Initializer();
}
private static final class Initializer {
static {
DAVRepositoryFactory.setup(); // http, https
SVNRepositoryFactoryImpl.setup(); // svn, svn+xxx
FSRepositoryFactory.setup(); // file
}
}
/**
* small structure to store local and remote (repository) location
* information of the repository. As a addition it holds the invalid field
* to make failure messages when doing a checkout possible
*/
public static final class ModuleLocation implements Serializable {
public final String remote;
public final String local;
public ModuleLocation(String remote, String local) {
if(local==null)
local = getLastPathComponent(remote);
this.remote = remote.trim();
this.local = local.trim();
}
private static final long serialVersionUID = 1L;
}
private static final Logger LOGGER = Logger.getLogger(SubversionSCM.class.getName());
/**
* Optionally enable tagging support, so that this feature can be hidden
* until it becomes stable.
*/
public static boolean tagEnabled = Boolean.getBoolean(SubversionSCM.class.getName()+".tag");
}
| core/src/main/java/hudson/scm/SubversionSCM.java | package hudson.scm;
import hudson.FilePath;
import hudson.FilePath.FileCallable;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Hudson;
import hudson.model.TaskListener;
import hudson.remoting.Callable;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.util.FormFieldValidator;
import hudson.util.IOException2;
import hudson.util.MultipartFormDataParser;
import hudson.util.Scrambler;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FileUtils;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Chmod;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationProvider;
import org.tmatesoft.svn.core.auth.SVNAuthentication;
import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication;
import org.tmatesoft.svn.core.auth.SVNSSHAuthentication;
import org.tmatesoft.svn.core.auth.SVNSSLAuthentication;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNAuthenticationManager;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNInfo;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;
import org.tmatesoft.svn.core.wc.SVNWCClient;
import org.tmatesoft.svn.core.wc.SVNWCUtil;
import javax.servlet.ServletException;
import javax.xml.transform.stream.StreamResult;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* Subversion SCM.
*
* @author Kohsuke Kawaguchi
*/
public class SubversionSCM extends SCM implements Serializable {
/**
* the locations field is used to store all configured SVN locations (with
* their local and remote part). Direct access to this filed should be
* avoided and the getLocations() method should be used instead. This is
* needed to make importing of old hudson-configurations possible as
* getLocations() will check if the modules field has been set and import
* the data.
*
* @since 1.91
*/
private ModuleLocation[] locations = new ModuleLocation[0];
private boolean useUpdate;
private String username;
private final SubversionRepositoryBrowser browser;
// No longer in use but left for serialization compatibility.
@Deprecated
private String modules;
SubversionSCM(String[] remoteLocations, String[] localLocations,
boolean useUpdate, String username, SubversionRepositoryBrowser browser) {
List<ModuleLocation> modules = new ArrayList<ModuleLocation>();
if (remoteLocations != null && localLocations != null) {
int entries = Math.min(remoteLocations.length, localLocations.length);
for (int i = 0; i < entries; i++) {
// the remote (repository) location
String remoteLoc = nullify(remoteLocations[i]);
if (remoteLoc != null) {// null if skipped
remoteLoc = Util.removeTrailingSlash(remoteLoc.trim());
modules.add(new ModuleLocation(remoteLoc, nullify(localLocations[i])));
}
}
}
locations = modules.toArray(new ModuleLocation[modules.size()]);
this.useUpdate = useUpdate;
this.username = nullify(username);
this.browser = browser;
}
/**
* @deprecated
* as of 1.91. Use {@link #getLocations()} instead.
*/
public String getModules() {
return null;
}
/**
* list of all configured svn locations
*
* @since 1.91
*/
public ModuleLocation[] getLocations() {
// check if we've got a old location
if (modules != null) {
// import the old configuration
List<ModuleLocation> oldLocations = new ArrayList<ModuleLocation>();
StringTokenizer tokens = new StringTokenizer(modules);
while (tokens.hasMoreTokens()) {
// the remote (repository location)
// the normalized name is always without the trailing '/'
String remoteLoc = Util.removeTrailingSlash(tokens.nextToken());
oldLocations.add(new ModuleLocation(remoteLoc, null));
}
locations = oldLocations.toArray(new ModuleLocation[oldLocations.size()]);
modules = null;
}
return locations;
}
public boolean isUseUpdate() {
return useUpdate;
}
public String getUsername() {
return username;
}
public SubversionRepositoryBrowser getBrowser() {
return browser;
}
/**
* Called after checkout/update has finished to compute the changelog.
*/
private boolean calcChangeLog(AbstractBuild<?,?> build, File changelogFile, BuildListener listener, List<String> externals) throws IOException, InterruptedException {
if(build.getPreviousBuild()==null) {
// nothing to compare against
return createEmptyChangeLog(changelogFile, listener, "log");
}
if(!new SubversionChangeLogBuilder(build,listener,this).run(externals,new StreamResult(changelogFile)))
createEmptyChangeLog(changelogFile, listener, "log");
return true;
}
/*package*/ static Map<String,Long> parseRevisionFile(AbstractBuild build) throws IOException {
Map<String,Long> revisions = new HashMap<String,Long>(); // module -> revision
{// read the revision file of the last build
File file = getRevisionFile(build);
if(!file.exists())
// nothing to compare against
return revisions;
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while((line=br.readLine())!=null) {
int index = line.lastIndexOf('/');
if(index<0) {
continue; // invalid line?
}
try {
revisions.put(line.substring(0,index), Long.parseLong(line.substring(index+1)));
} catch (NumberFormatException e) {
// perhaps a corrupted line. ignore
}
}
}
return revisions;
}
/**
* Parses the file that stores the locations in the workspace where modules loaded by svn:external
* is placed.
*/
/*package*/ static List<String> parseExternalsFile(AbstractProject project) throws IOException {
List<String> ext = new ArrayList<String>(); // workspace-relative path
{// read the revision file of the last build
File file = getExternalsFile(project);
if(!file.exists())
// nothing to compare against
return ext;
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String line;
while((line=br.readLine())!=null) {
ext.add(line);
}
} finally {
br.close();
}
}
return ext;
}
public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, final BuildListener listener, File changelogFile) throws IOException, InterruptedException {
List<String> externals = checkout(workspace,listener);
if(externals==null)
return false;
// write out the revision file
PrintWriter w = new PrintWriter(new FileOutputStream(getRevisionFile(build)));
try {
Map<String,SvnInfo> revMap = buildRevisionMap(workspace,listener,externals);
for (Entry<String,SvnInfo> e : revMap.entrySet()) {
w.println( e.getKey() +'/'+ e.getValue().revision );
}
if(tagEnabled)
build.addAction(new SubversionTagAction(build,revMap.values()));
} finally {
w.close();
}
// write out the externals info
w = new PrintWriter(new FileOutputStream(getExternalsFile(build.getProject())));
try {
for (String p : externals) {
w.println( p );
}
} finally {
w.close();
}
return calcChangeLog(build, changelogFile, listener, externals);
}
/**
* Performs the checkout or update, depending on the configuration and workspace state.
*
* @return null
* if the operation failed. Otherwise the set of local workspace paths
* (relative to the workspace root) that has loaded due to svn:external.
*/
private List<String> checkout(FilePath workspace, final TaskListener listener) throws IOException, InterruptedException {
final ISVNAuthenticationProvider authProvider = getDescriptor().createAuthenticationProvider();
// true to "svn update", false to "svn checkout".
final boolean update = useUpdate && isUpdatable(workspace, listener);
return workspace.act(new FileCallable<List<String>>() {
public List<String> invoke(File ws, VirtualChannel channel) throws IOException {
SVNUpdateClient svnuc = createSvnClientManager(authProvider).getUpdateClient();
List<String> externals = new ArrayList<String>(); // store discovered externals to here
if(update) {
for (ModuleLocation l : getLocations()) {
try {
listener.getLogger().println("Updating "+ l.remote);
svnuc.setEventHandler(new SubversionUpdateEventHandler(listener, externals, l.local));
svnuc.doUpdate(new File(ws, l.local), SVNRevision.HEAD, true);
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to update "+l.remote));
return null;
}
}
} else {
Util.deleteContentsRecursive(ws);
for (ModuleLocation l : getLocations()) {
try {
SVNURL url = SVNURL.parseURIEncoded(l.remote);
listener.getLogger().println("Checking out "+url);
svnuc.setEventHandler(new SubversionUpdateEventHandler(listener, externals, l.local));
svnuc.doCheckout(url, new File(ws, l.local), SVNRevision.HEAD, SVNRevision.HEAD, true);
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to check out "+l.remote));
return null;
}
}
}
return externals;
}
});
}
/**
* Creates {@link SVNClientManager}.
*
* <p>
* This method must be executed on the slave where svn operations are performed.
*
* @param authProvider
* The value obtained from {@link DescriptorImpl#createAuthenticationProvider()}.
* If the operation runs on slaves,
* (and properly remoted, if the svn operations run on slaves.)
*/
/*package*/ static SVNClientManager createSvnClientManager(ISVNAuthenticationProvider authProvider) {
ISVNAuthenticationManager sam = SVNWCUtil.createDefaultAuthenticationManager();
sam.setAuthenticationProvider(authProvider);
return SVNClientManager.newInstance(SVNWCUtil.createDefaultOptions(true),sam);
}
public static final class SvnInfo implements Serializable, Comparable<SvnInfo> {
/**
* Decoded repository URL.
*/
public final String url;
public final long revision;
public SvnInfo(String url, long revision) {
this.url = url;
this.revision = revision;
}
public SvnInfo(SVNInfo info) {
this( info.getURL().toDecodedString(), info.getCommittedRevision().getNumber() );
}
public SVNURL getSVNURL() throws SVNException {
return SVNURL.parseURIDecoded(url);
}
public int compareTo(SvnInfo that) {
int r = this.url.compareTo(that.url);
if(r!=0) return r;
if(this.revision<that.revision) return -1;
if(this.revision>that.revision) return +1;
return 0;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SvnInfo svnInfo = (SvnInfo) o;
if (revision != svnInfo.revision) return false;
if (!url.equals(svnInfo.url)) return false;
return true;
}
public int hashCode() {
int result;
result = url.hashCode();
result = 31 * result + (int) (revision ^ (revision >>> 32));
return result;
}
public String toString() {
return String.format("%s (rev.%s)",url,revision);
}
private static final long serialVersionUID = 1L;
}
/**
* Gets the SVN metadata for the given local workspace.
*
* @param workspace
* The target to run "svn info".
*/
private SVNInfo parseSvnInfo(File workspace, ISVNAuthenticationProvider authProvider) throws SVNException {
SVNWCClient svnWc = createSvnClientManager(authProvider).getWCClient();
return svnWc.doInfo(workspace,SVNRevision.WORKING);
}
/**
* Gets the SVN metadata for the remote repository.
*
* @param remoteUrl
* The target to run "svn info".
*/
private SVNInfo parseSvnInfo(SVNURL remoteUrl, ISVNAuthenticationProvider authProvider) throws SVNException {
SVNWCClient svnWc = createSvnClientManager(authProvider).getWCClient();
return svnWc.doInfo(remoteUrl, SVNRevision.HEAD, SVNRevision.HEAD);
}
/**
* Checks .svn files in the workspace and finds out revisions of the modules
* that the workspace has.
*
* @return
* null if the parsing somehow fails. Otherwise a map from the repository URL to revisions.
*/
private Map<String,SvnInfo> buildRevisionMap(FilePath workspace, final TaskListener listener, final List<String> externals) throws IOException, InterruptedException {
final ISVNAuthenticationProvider authProvider = getDescriptor().createAuthenticationProvider();
return workspace.act(new FileCallable<Map<String,SvnInfo>>() {
public Map<String,SvnInfo> invoke(File ws, VirtualChannel channel) throws IOException {
Map<String/*module name*/,SvnInfo> revisions = new HashMap<String,SvnInfo>();
SVNWCClient svnWc = createSvnClientManager(authProvider).getWCClient();
// invoke the "svn info"
for( ModuleLocation module : getLocations() ) {
try {
SvnInfo info = new SvnInfo(svnWc.doInfo(new File(ws,module.local),SVNRevision.WORKING));
revisions.put(info.url,info);
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to parse svn info for "+module));
}
}
for(String local : externals){
try {
SvnInfo info = new SvnInfo(svnWc.doInfo(new File(ws, local),SVNRevision.WORKING));
revisions.put(info.url,info);
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to parse svn info for external "+local));
}
}
return revisions;
}
});
}
/**
* Gets the file that stores the revision.
*/
private static File getRevisionFile(AbstractBuild build) {
return new File(build.getRootDir(),"revision.txt");
}
/**
* Gets the file that stores the externals.
*/
private static File getExternalsFile(AbstractProject project) {
return new File(project.getRootDir(),"svnexternals.txt");
}
/**
* Returns true if we can use "svn update" instead of "svn checkout"
*/
private boolean isUpdatable(FilePath workspace, final TaskListener listener) throws IOException, InterruptedException {
final ISVNAuthenticationProvider authProvider = getDescriptor().createAuthenticationProvider();
return workspace.act(new FileCallable<Boolean>() {
public Boolean invoke(File ws, VirtualChannel channel) throws IOException {
for (ModuleLocation l : getLocations()) {
String url = l.remote;
String moduleName = l.local;
File module = new File(ws,moduleName).getCanonicalFile(); // canonicalize to remove ".." and ".". See #474
if(!module.exists()) {
listener.getLogger().println("Checking out a fresh workspace because "+module+" doesn't exist");
return false;
}
try {
SvnInfo svnInfo = new SvnInfo(parseSvnInfo(module,authProvider));
if(!svnInfo.url.equals(url)) {
listener.getLogger().println("Checking out a fresh workspace because the workspace is not "+url);
return false;
}
} catch (SVNException e) {
listener.getLogger().println("Checking out a fresh workspace because Hudson failed to detect the current workspace "+module);
e.printStackTrace(listener.error(e.getMessage()));
return false;
}
}
return true;
}
});
}
public boolean pollChanges(AbstractProject project, Launcher launcher, FilePath workspace, TaskListener listener) throws IOException, InterruptedException {
// we need to load the externals info, if any
List<String> externals = parseExternalsFile(project);
// current workspace revision
Map<String,SvnInfo> wsRev = buildRevisionMap(workspace,listener,externals);
ISVNAuthenticationProvider authProvider = getDescriptor().createAuthenticationProvider();
// check the corresponding remote revision
for (SvnInfo localInfo : wsRev.values()) {
try {
SvnInfo remoteInfo = new SvnInfo(parseSvnInfo(localInfo.getSVNURL(),authProvider));
listener.getLogger().println("Revision:"+remoteInfo.revision);
if(remoteInfo.revision > localInfo.revision)
return true; // change found
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to check repository revision for "+localInfo.url));
}
}
return false; // no change
}
public ChangeLogParser createChangeLogParser() {
return new SubversionChangeLogParser();
}
public DescriptorImpl getDescriptor() {
return DescriptorImpl.DESCRIPTOR;
}
public FilePath getModuleRoot(FilePath workspace) {
if (getLocations().length > 0)
return workspace.child(getLocations()[0].local);
return workspace;
}
private static String getLastPathComponent(String s) {
String[] tokens = s.split("/");
return tokens[tokens.length-1]; // return the last token
}
public static final class DescriptorImpl extends SCMDescriptor<SubversionSCM> {
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
/**
* SVN authentication realm to its associated credentials.
*/
private final Map<String,Credential> credentials = new Hashtable<String,Credential>();
/**
* Stores {@link SVNAuthentication} for a single realm.
*
* <p>
* {@link Credential} holds data in a persistence-friendly way,
* and it's capable of creating {@link SVNAuthentication} object,
* to be passed to SVNKit.
*/
private static abstract class Credential implements Serializable {
/**
* @param kind
* One of the constants defined in {@link ISVNAuthenticationManager},
* indicating what subype of {@link SVNAuthentication} is expected.
*/
abstract SVNAuthentication createSVNAuthentication(String kind) throws SVNException;
}
/**
* Username/password based authentication.
*/
private static final class PasswordCredential extends Credential {
private final String userName;
private final String password; // scrambled by base64
public PasswordCredential(String userName, String password) {
this.userName = userName;
this.password = Scrambler.scramble(password);
}
@Override
SVNAuthentication createSVNAuthentication(String kind) {
if(kind.equals(ISVNAuthenticationManager.SSH))
return new SVNSSHAuthentication(userName,password,-1,false);
else
return new SVNPasswordAuthentication(userName,Scrambler.descramble(password),false);
}
}
/**
* Publickey authentication for Subversion over SSH.
*/
private static final class SshPublicKeyCredential extends Credential {
private final String userName;
private final String passphrase; // scrambled by base64
private final String id;
/**
* @param keyFile
* stores SSH private key. The file will be copied.
*/
public SshPublicKeyCredential(String userName, String passphrase, File keyFile) throws SVNException {
this.userName = userName;
this.passphrase = Scrambler.scramble(passphrase);
Random r = new Random();
StringBuilder buf = new StringBuilder();
for(int i=0;i<16;i++)
buf.append(Integer.toHexString(r.nextInt(16)));
this.id = buf.toString();
try {
FileUtils.copyFile(keyFile,getKeyFile());
} catch (IOException e) {
throw new SVNException(SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE,"Unable to save private key"),e);
}
}
/**
* Gets the location where the private key will be permanently stored.
*/
private File getKeyFile() {
File dir = new File(Hudson.getInstance().getRootDir(),"subversion-credentials");
if(dir.mkdirs()) {
// make sure the directory exists. if we created it, try to set the permission to 600
// since this is sensitive information
try {
Chmod chmod = new Chmod();
chmod.setProject(new Project());
chmod.setFile(dir);
chmod.setPerm("600");
chmod.execute();
} catch (Throwable e) {
// if we failed to set the permission, that's fine.
LOGGER.log(Level.WARNING, "Failed to set directory permission of "+dir,e);
}
}
return new File(dir,id);
}
@Override
SVNSSHAuthentication createSVNAuthentication(String kind) throws SVNException {
if(kind.equals(ISVNAuthenticationManager.SSH)) {
try {
Channel channel = Channel.current();
String privateKey;
if(channel!=null) {
// remote
privateKey = channel.call(new Callable<String,IOException>() {
public String call() throws IOException {
return FileUtils.readFileToString(getKeyFile(),"iso-8859-1");
}
});
} else {
privateKey = FileUtils.readFileToString(getKeyFile(),"iso-8859-1");
}
return new SVNSSHAuthentication(userName, privateKey.toCharArray(), Scrambler.descramble(passphrase),-1,false);
} catch (IOException e) {
throw new SVNException(SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE,"Unable to load private key"),e);
} catch (InterruptedException e) {
throw new SVNException(SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE,"Unable to load private key"),e);
}
} else
return null; // unknown
}
}
/**
* SSL client certificate based authentication.
*/
private static final class SslClientCertificateCredential extends Credential {
private final String password; // scrambled by base64
public SslClientCertificateCredential(File certificate, String password) {
this.password = Scrambler.scramble(password);
}
@Override
SVNAuthentication createSVNAuthentication(String kind) {
if(kind.equals(ISVNAuthenticationManager.SSL))
return new SVNSSLAuthentication(null,Scrambler.descramble(password),false);
else
return null; // unexpected authentication type
}
}
/**
* Remoting interface that allows remote {@link ISVNAuthenticationProvider}
* to read from local {@link DescriptorImpl#credentials}.
*/
private interface RemotableSVNAuthenticationProvider {
Credential getCredential(String realm);
}
private final class RemotableSVNAuthenticationProviderImpl implements RemotableSVNAuthenticationProvider, Serializable {
public Credential getCredential(String realm) {
LOGGER.fine(String.format("getCredential(%s)=>%s",realm,credentials.get(realm)));
return credentials.get(realm);
}
/**
* When sent to the remote node, send a proxy.
*/
private Object writeReplace() {
return Channel.current().export(RemotableSVNAuthenticationProvider.class, this);
}
}
/**
* See {@link DescriptorImpl#createAuthenticationProvider()}.
*/
private static final class SVNAuthenticationProviderImpl implements ISVNAuthenticationProvider, Serializable {
private final RemotableSVNAuthenticationProvider source;
public SVNAuthenticationProviderImpl(RemotableSVNAuthenticationProvider source) {
this.source = source;
}
public SVNAuthentication requestClientAuthentication(String kind, SVNURL url, String realm, SVNErrorMessage errorMessage, SVNAuthentication previousAuth, boolean authMayBeStored) {
Credential cred = source.getCredential(realm);
LOGGER.fine(String.format("requestClientAuthentication(%s,%s,%s)=>%s",kind,url,realm,cred));
if(cred==null) return null;
try {
return cred.createSVNAuthentication(kind);
} catch (SVNException e) {
logger.log(Level.SEVERE, "Failed to authorize",e);
throw new RuntimeException("Failed to authorize",e);
}
}
public int acceptServerAuthentication(SVNURL url, String realm, Object certificate, boolean resultMayBeStored) {
return ACCEPTED_TEMPORARY;
}
private static final long serialVersionUID = 1L;
}
private DescriptorImpl() {
super(SubversionSCM.class,SubversionRepositoryBrowser.class);
load();
}
public String getDisplayName() {
return "Subversion";
}
public SCM newInstance(StaplerRequest req) throws FormException {
return new SubversionSCM(
req.getParameterValues("svn.location_remote"),
req.getParameterValues("svn.location_local"),
req.getParameter("svn_use_update") != null,
req.getParameter("svn_username"),
RepositoryBrowsers.createInstance(SubversionRepositoryBrowser.class, req, "svn.browser"));
}
/**
* Creates {@link ISVNAuthenticationProvider} backed by {@link #credentials}.
* This method must be invoked on the master, but the returned object is remotable.
*/
public ISVNAuthenticationProvider createAuthenticationProvider() {
return new SVNAuthenticationProviderImpl(new RemotableSVNAuthenticationProviderImpl());
}
/**
* Submits the authentication info.
*
* This code is fairly ugly because of the way SVNKit handles credentials.
*/
public void doPostCredential(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
if(!Hudson.adminCheck(req,rsp)) return;
MultipartFormDataParser parser = new MultipartFormDataParser(req);
String url = parser.get("url");
String kind = parser.get("kind");
int idx = Arrays.asList("","password","publickey","certificate").indexOf(kind);
final String username = parser.get("username"+idx);
final String password = parser.get("password"+idx);
// SVNKit wants a key in a file
final File keyFile;
FileItem item=null;
if(kind.equals("password")) {
keyFile = null;
} else {
item = parser.getFileItem(kind.equals("publickey")?"privateKey":"certificate");
keyFile = File.createTempFile("hudson","key");
if(item!=null)
try {
item.write(keyFile);
} catch (Exception e) {
throw new IOException2(e);
}
}
try {
// the way it works with SVNKit is that
// 1) svnkit calls AuthenticationManager asking for a credential.
// this is when we can see the 'realm', which identifies the user domain.
// 2) DefaultSVNAuthenticationManager returns the username and password we set below
// 3) if the authentication is successful, svnkit calls back acknowledgeAuthentication
// (so we store the password info here)
SVNRepository repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
repository.setAuthenticationManager(new DefaultSVNAuthenticationManager(SVNWCUtil.getDefaultConfigurationDirectory(),true,username,password,keyFile,password) {
Credential cred = null;
@Override
public SVNAuthentication getFirstAuthentication(String kind, String realm, SVNURL url) throws SVNException {
if(kind.equals(ISVNAuthenticationManager.PASSWORD))
cred = new PasswordCredential(username,password);
if(kind.equals(ISVNAuthenticationManager.SSH)) {
if(keyFile==null)
cred = new PasswordCredential(username,password);
else
cred = new SshPublicKeyCredential(username,password,keyFile);
}
if(kind.equals(ISVNAuthenticationManager.SSL))
cred = new SslClientCertificateCredential(keyFile,password);
if(cred==null) return null;
return cred.createSVNAuthentication(kind);
}
@Override
public void acknowledgeAuthentication(boolean accepted, String kind, String realm, SVNErrorMessage errorMessage, SVNAuthentication authentication) throws SVNException {
if(accepted) {
assert cred!=null;
credentials.put(realm,cred);
save();
}
super.acknowledgeAuthentication(accepted, kind, realm, errorMessage, authentication);
}
});
repository.testConnection();
rsp.sendRedirect("credentialOK");
} catch (SVNException e) {
req.setAttribute("message",e.getErrorMessage());
rsp.forward(Hudson.getInstance(),"error",req);
} finally {
if(keyFile!=null)
keyFile.delete();
if(item!=null)
item.delete();
}
}
/**
* validate the value for a remote (repository) location.
*/
public void doSvnRemoteLocationCheck(final StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
// this can be used to hit any accessible URL, so limit that to admins
new FormFieldValidator(req, rsp, true) {
protected void check() throws IOException, ServletException {
// syntax check first
String url = Util.nullify(request.getParameter("value"));
if (url == null) {
ok(); // not entered yet
return;
}
// remove unneeded whitespaces
url = url.trim();
if(!URL_PATTERN.matcher(url).matches()) {
error("Invalid URL syntax. See "
+ "<a href=\"http://svnbook.red-bean.com/en/1.2/svn-book.html#svn.basic.in-action.wc.tbl-1\">this</a> "
+ "for information about valid URLs.");
return;
}
// test the connection
try {
SVNRepository repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
ISVNAuthenticationManager sam = SVNWCUtil.createDefaultAuthenticationManager();
sam.setAuthenticationProvider(createAuthenticationProvider());
repository.setAuthenticationManager(sam);
repository.testConnection();
ok();
} catch (SVNException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String message="";
message += "Unable to access "+url+" : "+Util.escape( e.getErrorMessage().getFullMessage());
message += " <a href='#' id=svnerrorlink onclick='javascript:" +
"document.getElementById(\"svnerror\").style.display=\"block\";" +
"document.getElementById(\"svnerrorlink\").style.display=\"none\";" +
"return false;'>(show details)</a>";
message += "<pre id=svnerror style='display:none'>"+sw+"</pre>";
message += " (Maybe you need to <a href='"+req.getContextPath()+"/scm/SubversionSCM/enterCredential?"+url+"'>enter credential</a>?)";
message += "<br>";
logger.log(Level.INFO, "Failed to access subversion repository "+url,e);
error(message);
}
}
}.process();
}
/**
* validate the value for a local location (local checkout directory).
*/
public void doSvnLocalLocationCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
new FormFieldValidator(req, rsp, false) {
protected void check() throws IOException, ServletException {
String v = Util.nullify(request.getParameter("value"));
if (v == null) {
// local directory is optional so this is ok
ok();
return;
}
v = v.trim();
// check if a absolute path has been supplied
// (the last check with the regex will match windows drives)
if (v.startsWith("/") || v.startsWith("\\") || v.startsWith("..") || v.matches("^[A-Za-z]:")) {
error("absolute path is not allowed");
}
// all tests passed so far
ok();
}
}.process();
}
static {
new Initializer();
}
}
static final Pattern URL_PATTERN = Pattern.compile("(https?|svn(\\+[a-z0-9]+)?|file)://.+");
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(SubversionSCM.class.getName());
static {
new Initializer();
}
private static final class Initializer {
static {
DAVRepositoryFactory.setup(); // http, https
SVNRepositoryFactoryImpl.setup(); // svn, svn+xxx
FSRepositoryFactory.setup(); // file
}
}
/**
* small structure to store local and remote (repository) location
* information of the repository. As a addition it holds the invalid field
* to make failure messages when doing a checkout possible
*/
public static final class ModuleLocation implements Serializable {
public final String remote;
public final String local;
public ModuleLocation(String remote, String local) {
if(local==null)
local = getLastPathComponent(remote);
this.remote = remote.trim();
this.local = local.trim();
}
private static final long serialVersionUID = 1L;
}
private static final Logger LOGGER = Logger.getLogger(SubversionSCM.class.getName());
/**
* Optionally enable tagging support, so that this feature can be hidden
* until it becomes stable.
*/
public static boolean tagEnabled = Boolean.getBoolean(SubversionSCM.class.getName()+".tag");
}
| file:// URL handling needs a non-null SVNAuthentication object to be returned.
git-svn-id: 28f34f9aa52bc55a5ddd5be9e183c5cccadc6ee4@3406 71c3de6d-444a-0410-be80-ed276b4c234a
| core/src/main/java/hudson/scm/SubversionSCM.java | file:// URL handling needs a non-null SVNAuthentication object to be returned. | <ide><path>ore/src/main/java/hudson/scm/SubversionSCM.java
<ide> import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication;
<ide> import org.tmatesoft.svn.core.auth.SVNSSHAuthentication;
<ide> import org.tmatesoft.svn.core.auth.SVNSSLAuthentication;
<add>import org.tmatesoft.svn.core.auth.SVNUserNameAuthentication;
<ide> import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
<ide> import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
<ide> import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
<ide> public SVNAuthentication requestClientAuthentication(String kind, SVNURL url, String realm, SVNErrorMessage errorMessage, SVNAuthentication previousAuth, boolean authMayBeStored) {
<ide> Credential cred = source.getCredential(realm);
<ide> LOGGER.fine(String.format("requestClientAuthentication(%s,%s,%s)=>%s",kind,url,realm,cred));
<del> if(cred==null) return null;
<add> if(cred==null) {
<add> // this happens with file:// URL. The base class does this, too.
<add> if (ISVNAuthenticationManager.USERNAME.equals(kind))
<add> // user auth shouldn't be null.
<add> return new SVNUserNameAuthentication("",false);
<add> }
<add>
<ide> try {
<ide> return cred.createSVNAuthentication(kind);
<ide> } catch (SVNException e) { |
|
Java | bsd-3-clause | 1975a3945ad29958c37ed5b9a3412cefc92c23ba | 0 | rnathanday/dryad-repo,ojacobson/dryad-repo,mdiggory/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,mdiggory/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,mdiggory/dryad-repo,ojacobson/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,jamie-dryad/dryad-repo,mdiggory/dryad-repo,jamie-dryad/dryad-repo,mdiggory/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo | /*
* ItemExport.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.itemexport;
import org.apache.commons.cli.*;
import org.dspace.content.*;
import org.dspace.content.dao.CollectionDAO;
import org.dspace.content.dao.CollectionDAOFactory;
import org.dspace.content.dao.ItemDAO;
import org.dspace.content.dao.ItemDAOFactory;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.Utils;
import org.dspace.uri.ExternalIdentifier;
import org.dspace.uri.IdentifierUtils;
import org.dspace.uri.ObjectIdentifier;
import org.dspace.uri.dao.ExternalIdentifierDAO;
import org.dspace.uri.dao.ExternalIdentifierDAOFactory;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* Item exporter to create simple AIPs for DSpace content. Currently exports
* individual items, or entire collections. For instructions on use, see
* printUsage() method.
* <P>
* ItemExport creates the simple AIP package that the importer also uses. It
* consists of:
* <P>
* /exportdir/42/ (one directory per item) / dublin_core.xml - qualified dublin
* core in RDF schema / contents - text file, listing one file per line / file1 -
* files contained in the item / file2 / ...
* <P>
* issues -doesn't handle special characters in metadata (needs to turn &'s into
* &, etc.)
* <P>
* Modified by David Little, UCSD Libraries 12/21/04 to
* allow the registration of files (bitstreams) into DSpace.
*/
public class ItemExport
{
private static final int SUBDIR_LIMIT = 0;
private static CollectionDAO collectionDAO;
private static ItemDAO itemDAO;
private static ExternalIdentifierDAO identifierDAO;
/*
*
*/
public static void main(String[] argv) throws Exception
{
// create an options object and populate it
CommandLineParser parser = new PosixParser();
Options options = new Options();
options.addOption("t", "type", true, "type: COLLECTION or ITEM");
options.addOption("i", "id", true, "ID or URI (canonical form) of thing to export");
options.addOption("d", "dest", true,
"destination where you want items to go");
options.addOption("n", "number", true,
"sequence number to begin exporting items with");
options.addOption("h", "help", false, "help");
CommandLine line = parser.parse(options, argv);
String typeString = null;
String destDirName = null;
String myIDString = null;
int seqStart = -1;
int myType = -1;
Item myItem = null;
Collection mycollection = null;
if (line.hasOption('h'))
{
HelpFormatter myhelp = new HelpFormatter();
myhelp.printHelp("ItemExport\n", options);
System.out
.println("\nfull collection: ItemExport -t COLLECTION -i ID -d dest -n number");
System.out
.println("singleitem: ItemExport -t ITEM -i ID -d dest -n number");
System.exit(0);
}
if (line.hasOption('t')) // type
{
typeString = line.getOptionValue('t');
if (typeString.equals("ITEM"))
{
myType = Constants.ITEM;
}
else if (typeString.equals("COLLECTION"))
{
myType = Constants.COLLECTION;
}
}
if (line.hasOption('i')) // id
{
myIDString = line.getOptionValue('i');
}
if (line.hasOption('d')) // dest
{
destDirName = line.getOptionValue('d');
}
if (line.hasOption('n')) // number
{
seqStart = Integer.parseInt(line.getOptionValue('n'));
}
// now validate the args
if (myType == -1)
{
System.out
.println("type must be either COLLECTION or ITEM (-h for help)");
System.exit(1);
}
if (destDirName == null)
{
System.out
.println("destination directory must be set (-h for help)");
System.exit(1);
}
if (seqStart == -1)
{
System.out
.println("sequence start number must be set (-h for help)");
System.exit(1);
}
if (myIDString == null)
{
System.out
.println("ID must be set to either a database ID or a canonical form of a URI (-h for help)");
System.exit(1);
}
Context c = new Context();
c.setIgnoreAuthorization(true);
collectionDAO = CollectionDAOFactory.getInstance(c);
itemDAO = ItemDAOFactory.getInstance(c);
identifierDAO = ExternalIdentifierDAOFactory.getInstance(c);
// First, add the namespace if necessary
if (myIDString.indexOf('/') != -1)
{
if (myIDString.indexOf(':') == -1)
{
// has no : must be a handle
myIDString = "hdl:" + myIDString;
System.out.println("no namespace provided. assuming handles.");
}
}
ObjectIdentifier oi = IdentifierUtils.fromString(c, myIDString);
if (oi == null)
{
System.err.println("Identifier " + myIDString + " not recognised.");
System.exit(1);
}
if (myType == Constants.ITEM)
{
// first, do we have a persistent identifier for the item?
myItem = (Item) oi.getObject(c);
if ((myItem == null) || (myItem.getType() != Constants.ITEM))
{
myItem = null;
}
if (myItem == null)
{
System.out
.println("Error, item cannot be found: " + myIDString);
}
}
else
{
mycollection = (Collection) oi.getObject(c);
// ensure it's a collection
if ((mycollection == null)
|| (mycollection.getType() != Constants.COLLECTION))
{
mycollection = null;
}
if (mycollection == null)
{
System.out.println("Error, collection cannot be found: "
+ myIDString);
System.exit(1);
}
}
if (myItem != null)
{
// it's only a single item
exportItem(c, myItem, destDirName, seqStart);
}
else
{
System.out.println("Exporting from collection: " + myIDString);
// it's a collection, so do a bunch of items
ItemIterator i = mycollection.getItems();
exportItem(c, i, destDirName, seqStart);
}
c.complete();
}
private static void exportItem(Context c, ItemIterator i,
String destDirName, int seqStart) throws Exception
{
int mySequenceNumber = seqStart;
int counter = SUBDIR_LIMIT - 1;
int subDirSuffix = 0;
String fullPath = destDirName;
String subdir = "";
File dir;
if (SUBDIR_LIMIT > 0)
{
dir = new File(destDirName);
if (!dir.isDirectory())
{
throw new IOException(destDirName + " is not a directory.");
}
}
System.out.println("Beginning export");
while (i.hasNext())
{
if (SUBDIR_LIMIT > 0 && ++counter == SUBDIR_LIMIT)
{
subdir = Integer.toString(subDirSuffix++);
fullPath = destDirName + dir.separatorChar + subdir;
counter = 0;
if (!new File(fullPath).mkdirs())
{
throw new IOException("Error, can't make dir " + fullPath);
}
}
System.out.println("Exporting item to " + mySequenceNumber);
exportItem(c, i.next(), fullPath, mySequenceNumber);
mySequenceNumber++;
}
}
private static void exportItem(Context c, Item myItem, String destDirName,
int seqStart) throws Exception
{
File destDir = new File(destDirName);
if (destDir.exists())
{
// now create a subdirectory
File itemDir = new File(destDir + "/" + seqStart);
System.out.println("Exporting Item " + myItem.getID() + " to "
+ itemDir);
if (itemDir.exists())
{
throw new Exception("Directory " + destDir + "/" + seqStart
+ " already exists!");
}
if (itemDir.mkdir())
{
// make it this far, now start exporting
writeMetadata(c, myItem, itemDir);
writeBitstreams(c, myItem, itemDir);
writeURI(c, myItem, itemDir);
}
else
{
throw new Exception("Error, can't make dir " + itemDir);
}
}
else
{
throw new Exception("Error, directory " + destDirName
+ " doesn't exist!");
}
}
/**
* Discover the different schemas in use and output a seperate metadata
* XML file for each schema.
*
* @param c
* @param i
* @param destDir
* @throws Exception
*/
private static void writeMetadata(Context c, Item i, File destDir)
throws Exception
{
// Build a list of schemas for the item
HashMap map = new HashMap();
DCValue[] dcorevalues = i.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
for (int ii = 0; ii < dcorevalues.length; ii++)
{
map.put(dcorevalues[ii].schema, null);
}
// Save each of the schemas into it's own metadata file
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext())
{
String schema = (String) iterator.next();
writeMetadata(c, schema, i, destDir);
}
}
// output the item's dublin core into the item directory
private static void writeMetadata(Context c, String schema, Item i, File destDir)
throws Exception
{
String filename;
if (schema.equals(MetadataSchema.DC_SCHEMA)) {
filename = "dublin_core.xml";
} else {
filename = "metadata_" + schema + ".xml";
}
File outFile = new File(destDir, filename);
System.out.println("Attempting to create file " + outFile);
if (outFile.createNewFile())
{
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(outFile));
DCValue[] dcorevalues = i.getMetadata(schema, Item.ANY, Item.ANY, Item.ANY);
// XML preamble
byte[] utf8 = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n"
.getBytes("UTF-8");
out.write(utf8, 0, utf8.length);
String dcTag = "<dublin_core schema=\""+schema+"\">\n";
utf8 = dcTag.getBytes("UTF-8");
out.write(utf8, 0, utf8.length);
for (int j = 0; j < dcorevalues.length; j++)
{
DCValue dcv = dcorevalues[j];
String qualifier = dcv.qualifier;
if (qualifier == null)
{
qualifier = "none";
}
utf8 = (" <dcvalue element=\"" + dcv.element + "\" "
+ "qualifier=\"" + qualifier + "\">"
+ Utils.addEntities(dcv.value) + "</dcvalue>\n").getBytes("UTF-8");
out.write(utf8, 0, utf8.length);
}
utf8 = "</dublin_core>\n".getBytes("UTF-8");
out.write(utf8, 0, utf8.length);
out.close();
}
else
{
throw new Exception("Cannot create dublin_core.xml in " + destDir);
}
}
// create the file 'uri' which contains (one of the) the URI(s) assigned
// to the item
private static void writeURI(Context c, Item i, File destDir)
throws Exception
{
String filename = "uri";
File outFile = new File(destDir, filename);
if (outFile.createNewFile())
{
PrintWriter out = new PrintWriter(new FileWriter(outFile));
// first do the internal UUID
out.println(i.getIdentifier().getCanonicalForm());
// next do the external identifiers
List<ExternalIdentifier> eids = i.getExternalIdentifiers();
for (ExternalIdentifier eid : eids)
{
out.println(eid.getCanonicalForm());
}
// close the contents file
out.close();
}
else
{
throw new Exception("Cannot create file " + filename + " in "
+ destDir);
}
}
/**
* Create both the bitstreams and the contents file. Any bitstreams that
* were originally registered will be marked in the contents file as such.
* However, the export directory will contain actual copies of the content
* files being exported.
*
* @param c the DSpace context
* @param i the item being exported
* @param destDir the item's export directory
* @throws Exception if there is any problem writing to the export
* directory
*/
private static void writeBitstreams(Context c, Item i, File destDir)
throws Exception
{
File outFile = new File(destDir, "contents");
if (outFile.createNewFile())
{
PrintWriter out = new PrintWriter(new FileWriter(outFile));
Bundle[] bundles = i.getBundles();
for (int j = 0; j < bundles.length; j++)
{
// bundles can have multiple bitstreams now...
Bitstream[] bitstreams = bundles[j].getBitstreams();
String bundleName = bundles[j].getName();
for (int k = 0; k < bitstreams.length; k++)
{
Bitstream b = bitstreams[k];
String myName = b.getName();
String oldName = myName;
int myPrefix = 1; // only used with name conflict
InputStream is = b.retrieve();
boolean isDone = false; // done when bitstream is finally
// written
while (!isDone)
{
File fout = new File(destDir, myName);
if (fout.createNewFile())
{
FileOutputStream fos = new FileOutputStream(fout);
Utils.bufferedCopy(is, fos);
// close streams
is.close();
fos.close();
// write the manifest file entry
if (b.isRegisteredBitstream()) {
out.println("-r -s " + b.getStoreNumber()
+ " -f " + myName
+ "\tbundle:" + bundleName);
} else {
out.println(myName + "\tbundle:" + bundleName);
}
isDone = true;
}
else
{
myName = myPrefix + "_" + oldName; // keep appending
// numbers to the
// filename until
// unique
myPrefix++;
}
}
}
}
// close the contents file
out.close();
}
else
{
throw new Exception("Cannot create contents in " + destDir);
}
}
}
| dspace-api/src/main/java/org/dspace/app/itemexport/ItemExport.java | /*
* ItemExport.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.itemexport;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.Collection;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.content.ItemIterator;
import org.dspace.content.MetadataSchema;
import org.dspace.content.dao.CollectionDAO;
import org.dspace.content.dao.CollectionDAOFactory;
import org.dspace.content.dao.ItemDAO;
import org.dspace.content.dao.ItemDAOFactory;
import org.dspace.uri.IdentifierUtils;
import org.dspace.uri.ObjectIdentifier;
import org.dspace.uri.dao.ExternalIdentifierDAO;
import org.dspace.uri.dao.ExternalIdentifierDAOFactory;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.Utils;
/**
* Item exporter to create simple AIPs for DSpace content. Currently exports
* individual items, or entire collections. For instructions on use, see
* printUsage() method.
* <P>
* ItemExport creates the simple AIP package that the importer also uses. It
* consists of:
* <P>
* /exportdir/42/ (one directory per item) / dublin_core.xml - qualified dublin
* core in RDF schema / contents - text file, listing one file per line / file1 -
* files contained in the item / file2 / ...
* <P>
* issues -doesn't handle special characters in metadata (needs to turn &'s into
* &, etc.)
* <P>
* Modified by David Little, UCSD Libraries 12/21/04 to
* allow the registration of files (bitstreams) into DSpace.
*/
public class ItemExport
{
private static final int SUBDIR_LIMIT = 0;
private static CollectionDAO collectionDAO;
private static ItemDAO itemDAO;
private static ExternalIdentifierDAO identifierDAO;
/*
*
*/
public static void main(String[] argv) throws Exception
{
// create an options object and populate it
CommandLineParser parser = new PosixParser();
Options options = new Options();
options.addOption("t", "type", true, "type: COLLECTION or ITEM");
options.addOption("i", "id", true, "ID or URI (canonical form) of thing to export");
options.addOption("d", "dest", true,
"destination where you want items to go");
options.addOption("n", "number", true,
"sequence number to begin exporting items with");
options.addOption("h", "help", false, "help");
CommandLine line = parser.parse(options, argv);
String typeString = null;
String destDirName = null;
String myIDString = null;
int seqStart = -1;
int myType = -1;
Item myItem = null;
Collection mycollection = null;
if (line.hasOption('h'))
{
HelpFormatter myhelp = new HelpFormatter();
myhelp.printHelp("ItemExport\n", options);
System.out
.println("\nfull collection: ItemExport -t COLLECTION -i ID -d dest -n number");
System.out
.println("singleitem: ItemExport -t ITEM -i ID -d dest -n number");
System.exit(0);
}
if (line.hasOption('t')) // type
{
typeString = line.getOptionValue('t');
if (typeString.equals("ITEM"))
{
myType = Constants.ITEM;
}
else if (typeString.equals("COLLECTION"))
{
myType = Constants.COLLECTION;
}
}
if (line.hasOption('i')) // id
{
myIDString = line.getOptionValue('i');
}
if (line.hasOption('d')) // dest
{
destDirName = line.getOptionValue('d');
}
if (line.hasOption('n')) // number
{
seqStart = Integer.parseInt(line.getOptionValue('n'));
}
// now validate the args
if (myType == -1)
{
System.out
.println("type must be either COLLECTION or ITEM (-h for help)");
System.exit(1);
}
if (destDirName == null)
{
System.out
.println("destination directory must be set (-h for help)");
System.exit(1);
}
if (seqStart == -1)
{
System.out
.println("sequence start number must be set (-h for help)");
System.exit(1);
}
if (myIDString == null)
{
System.out
.println("ID must be set to either a database ID or a canonical form of a URI (-h for help)");
System.exit(1);
}
Context c = new Context();
c.setIgnoreAuthorization(true);
collectionDAO = CollectionDAOFactory.getInstance(c);
itemDAO = ItemDAOFactory.getInstance(c);
identifierDAO = ExternalIdentifierDAOFactory.getInstance(c);
// First, add the namespace if necessary
if (myIDString.indexOf('/') != -1)
{
if (myIDString.indexOf(':') == -1)
{
// has no : must be a handle
myIDString = "hdl:" + myIDString;
System.out.println("no namespace provided. assuming handles.");
}
}
ObjectIdentifier oi = IdentifierUtils.fromString(c, myIDString);
if (oi == null)
{
System.err.println("Identifier " + myIDString + " not recognised.");
System.exit(1);
}
if (myType == Constants.ITEM)
{
// first, do we have a persistent identifier for the item?
myItem = (Item) oi.getObject(c);
if ((myItem == null) || (myItem.getType() != Constants.ITEM))
{
myItem = null;
}
if (myItem == null)
{
System.out
.println("Error, item cannot be found: " + myIDString);
}
}
else
{
mycollection = (Collection) oi.getObject(c);
// ensure it's a collection
if ((mycollection == null)
|| (mycollection.getType() != Constants.COLLECTION))
{
mycollection = null;
}
if (mycollection == null)
{
System.out.println("Error, collection cannot be found: "
+ myIDString);
System.exit(1);
}
}
if (myItem != null)
{
// it's only a single item
exportItem(c, myItem, destDirName, seqStart);
}
else
{
System.out.println("Exporting from collection: " + myIDString);
// it's a collection, so do a bunch of items
ItemIterator i = mycollection.getItems();
exportItem(c, i, destDirName, seqStart);
}
c.complete();
}
private static void exportItem(Context c, ItemIterator i,
String destDirName, int seqStart) throws Exception
{
int mySequenceNumber = seqStart;
int counter = SUBDIR_LIMIT - 1;
int subDirSuffix = 0;
String fullPath = destDirName;
String subdir = "";
File dir;
if (SUBDIR_LIMIT > 0)
{
dir = new File(destDirName);
if (!dir.isDirectory())
{
throw new IOException(destDirName + " is not a directory.");
}
}
System.out.println("Beginning export");
while (i.hasNext())
{
if (SUBDIR_LIMIT > 0 && ++counter == SUBDIR_LIMIT)
{
subdir = Integer.toString(subDirSuffix++);
fullPath = destDirName + dir.separatorChar + subdir;
counter = 0;
if (!new File(fullPath).mkdirs())
{
throw new IOException("Error, can't make dir " + fullPath);
}
}
System.out.println("Exporting item to " + mySequenceNumber);
exportItem(c, i.next(), fullPath, mySequenceNumber);
mySequenceNumber++;
}
}
private static void exportItem(Context c, Item myItem, String destDirName,
int seqStart) throws Exception
{
File destDir = new File(destDirName);
if (destDir.exists())
{
// now create a subdirectory
File itemDir = new File(destDir + "/" + seqStart);
System.out.println("Exporting Item " + myItem.getID() + " to "
+ itemDir);
if (itemDir.exists())
{
throw new Exception("Directory " + destDir + "/" + seqStart
+ " already exists!");
}
if (itemDir.mkdir())
{
// make it this far, now start exporting
writeMetadata(c, myItem, itemDir);
writeBitstreams(c, myItem, itemDir);
writeURI(c, myItem, itemDir);
}
else
{
throw new Exception("Error, can't make dir " + itemDir);
}
}
else
{
throw new Exception("Error, directory " + destDirName
+ " doesn't exist!");
}
}
/**
* Discover the different schemas in use and output a seperate metadata
* XML file for each schema.
*
* @param c
* @param i
* @param destDir
* @throws Exception
*/
private static void writeMetadata(Context c, Item i, File destDir)
throws Exception
{
// Build a list of schemas for the item
HashMap map = new HashMap();
DCValue[] dcorevalues = i.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
for (int ii = 0; ii < dcorevalues.length; ii++)
{
map.put(dcorevalues[ii].schema, null);
}
// Save each of the schemas into it's own metadata file
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext())
{
String schema = (String) iterator.next();
writeMetadata(c, schema, i, destDir);
}
}
// output the item's dublin core into the item directory
private static void writeMetadata(Context c, String schema, Item i, File destDir)
throws Exception
{
String filename;
if (schema.equals(MetadataSchema.DC_SCHEMA)) {
filename = "dublin_core.xml";
} else {
filename = "metadata_" + schema + ".xml";
}
File outFile = new File(destDir, filename);
System.out.println("Attempting to create file " + outFile);
if (outFile.createNewFile())
{
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(outFile));
DCValue[] dcorevalues = i.getMetadata(schema, Item.ANY, Item.ANY, Item.ANY);
// XML preamble
byte[] utf8 = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n"
.getBytes("UTF-8");
out.write(utf8, 0, utf8.length);
String dcTag = "<dublin_core schema=\""+schema+"\">\n";
utf8 = dcTag.getBytes("UTF-8");
out.write(utf8, 0, utf8.length);
for (int j = 0; j < dcorevalues.length; j++)
{
DCValue dcv = dcorevalues[j];
String qualifier = dcv.qualifier;
if (qualifier == null)
{
qualifier = "none";
}
utf8 = (" <dcvalue element=\"" + dcv.element + "\" "
+ "qualifier=\"" + qualifier + "\">"
+ Utils.addEntities(dcv.value) + "</dcvalue>\n").getBytes("UTF-8");
out.write(utf8, 0, utf8.length);
}
utf8 = "</dublin_core>\n".getBytes("UTF-8");
out.write(utf8, 0, utf8.length);
out.close();
}
else
{
throw new Exception("Cannot create dublin_core.xml in " + destDir);
}
}
// create the file 'handle' which contains (one of the) the URI(s) assigned
// to the item
private static void writeURI(Context c, Item i, File destDir)
throws Exception
{
String filename = "uri";
File outFile = new File(destDir, filename);
if (outFile.createNewFile())
{
PrintWriter out = new PrintWriter(new FileWriter(outFile));
out.println(i.getIdentifier().getCanonicalForm());
// close the contents file
out.close();
}
else
{
throw new Exception("Cannot create file " + filename + " in "
+ destDir);
}
}
/**
* Create both the bitstreams and the contents file. Any bitstreams that
* were originally registered will be marked in the contents file as such.
* However, the export directory will contain actual copies of the content
* files being exported.
*
* @param c the DSpace context
* @param i the item being exported
* @param destDir the item's export directory
* @throws Exception if there is any problem writing to the export
* directory
*/
private static void writeBitstreams(Context c, Item i, File destDir)
throws Exception
{
File outFile = new File(destDir, "contents");
if (outFile.createNewFile())
{
PrintWriter out = new PrintWriter(new FileWriter(outFile));
Bundle[] bundles = i.getBundles();
for (int j = 0; j < bundles.length; j++)
{
// bundles can have multiple bitstreams now...
Bitstream[] bitstreams = bundles[j].getBitstreams();
String bundleName = bundles[j].getName();
for (int k = 0; k < bitstreams.length; k++)
{
Bitstream b = bitstreams[k];
String myName = b.getName();
String oldName = myName;
int myPrefix = 1; // only used with name conflict
InputStream is = b.retrieve();
boolean isDone = false; // done when bitstream is finally
// written
while (!isDone)
{
File fout = new File(destDir, myName);
if (fout.createNewFile())
{
FileOutputStream fos = new FileOutputStream(fout);
Utils.bufferedCopy(is, fos);
// close streams
is.close();
fos.close();
// write the manifest file entry
if (b.isRegisteredBitstream()) {
out.println("-r -s " + b.getStoreNumber()
+ " -f " + myName
+ "\tbundle:" + bundleName);
} else {
out.println(myName + "\tbundle:" + bundleName);
}
isDone = true;
}
else
{
myName = myPrefix + "_" + oldName; // keep appending
// numbers to the
// filename until
// unique
myPrefix++;
}
}
}
}
// close the contents file
out.close();
}
else
{
throw new Exception("Cannot create contents in " + destDir);
}
}
}
| include in the 'uri' file the canonical forms of all the identifiers associated with an item
git-svn-id: 39c64a9546defcc59b5f71fe8fe20b2d01c24c1f@2424 9c30dcfa-912a-0410-8fc2-9e0234be79fd
| dspace-api/src/main/java/org/dspace/app/itemexport/ItemExport.java | include in the 'uri' file the canonical forms of all the identifiers associated with an item | <ide><path>space-api/src/main/java/org/dspace/app/itemexport/ItemExport.java
<ide> */
<ide> package org.dspace.app.itemexport;
<ide>
<del>import java.io.BufferedOutputStream;
<del>import java.io.File;
<del>import java.io.FileOutputStream;
<del>import java.io.FileWriter;
<del>import java.io.IOException;
<del>import java.io.InputStream;
<del>import java.io.PrintWriter;
<del>import java.util.HashMap;
<del>import java.util.Iterator;
<del>
<del>import org.apache.commons.cli.CommandLine;
<del>import org.apache.commons.cli.CommandLineParser;
<del>import org.apache.commons.cli.HelpFormatter;
<del>import org.apache.commons.cli.Options;
<del>import org.apache.commons.cli.PosixParser;
<del>
<del>import org.dspace.content.Bitstream;
<del>import org.dspace.content.Bundle;
<del>import org.dspace.content.Collection;
<del>import org.dspace.content.DCValue;
<del>import org.dspace.content.Item;
<del>import org.dspace.content.ItemIterator;
<del>import org.dspace.content.MetadataSchema;
<add>import org.apache.commons.cli.*;
<add>import org.dspace.content.*;
<ide> import org.dspace.content.dao.CollectionDAO;
<ide> import org.dspace.content.dao.CollectionDAOFactory;
<ide> import org.dspace.content.dao.ItemDAO;
<ide> import org.dspace.content.dao.ItemDAOFactory;
<add>import org.dspace.core.Constants;
<add>import org.dspace.core.Context;
<add>import org.dspace.core.Utils;
<add>import org.dspace.uri.ExternalIdentifier;
<ide> import org.dspace.uri.IdentifierUtils;
<ide> import org.dspace.uri.ObjectIdentifier;
<ide> import org.dspace.uri.dao.ExternalIdentifierDAO;
<ide> import org.dspace.uri.dao.ExternalIdentifierDAOFactory;
<del>import org.dspace.core.Constants;
<del>import org.dspace.core.Context;
<del>import org.dspace.core.Utils;
<add>
<add>import java.io.*;
<add>import java.util.HashMap;
<add>import java.util.Iterator;
<add>import java.util.List;
<ide>
<ide> /**
<ide> * Item exporter to create simple AIPs for DSpace content. Currently exports
<ide> }
<ide> }
<ide>
<del> // create the file 'handle' which contains (one of the) the URI(s) assigned
<add> // create the file 'uri' which contains (one of the) the URI(s) assigned
<ide> // to the item
<ide> private static void writeURI(Context c, Item i, File destDir)
<ide> throws Exception
<ide> {
<ide> PrintWriter out = new PrintWriter(new FileWriter(outFile));
<ide>
<add> // first do the internal UUID
<ide> out.println(i.getIdentifier().getCanonicalForm());
<add>
<add> // next do the external identifiers
<add> List<ExternalIdentifier> eids = i.getExternalIdentifiers();
<add> for (ExternalIdentifier eid : eids)
<add> {
<add> out.println(eid.getCanonicalForm());
<add> }
<ide>
<ide> // close the contents file
<ide> out.close(); |
|
JavaScript | mit | a2a2fceeb97d48c2173e16334083a28665c2c8b1 | 0 | moxie-lean/ng-patternlab,moxie-lean/ng-patternlab | 'use strict';
//
// imports
//
var gulp = require('gulp');
var gutil = require('gulp-util');
var templateCache = require('gulp-angular-templatecache');
var fs = require('fs');
var glob = require('glob');
var path = require('path');
var _ = require('lodash');
//
// constants
//
var CONFIG_FILE = '../../config/patterns.json';
var COMMON_HEADER = 'AUTO-GENERATED BY GULP';
var COMMON_HEADER_JS = '/*** ' + COMMON_HEADER + ' ***/';
var COMMON_HEADER_HTML = '<!-- ' + COMMON_HEADER + ' -->';
var TEMPLATE_CACHE_HEADER = COMMON_HEADER_JS + '\n\n' + 'angular.module("lnPatterns").run(["$templateCache", function($templateCache) {';
var PATTERNS_TEMPLATE = 'templates/patterns/template';
var PATTERNS_TEMPLATE_PAGE = PATTERNS_TEMPLATE + '.html';
var ENCODING = 'utf8';
var HEADER_REGEX = /\/\*\*\*.*\*\*\*\//;
var COMPONENT_REGEX = /{COMPONENT}[\s\S]*{END_COMPONENT}/m;
var EXAMPLE_REGEX = /{EXAMPLE}[\s\S]*{END_EXAMPLE}/m;
var CONTROLLER_REGEX = /{CONTROLLER}[\s\S]*{END_CONTROLLER}/m;
//
// global variables
//
var appConfig = null;
var enabledTemplates = [];
//
// tasks
//
gulp.task('lnPatternsLoadConfig', function (cb) {
//load application config file
try {
appConfig = require(CONFIG_FILE);
}
catch (e) {
gutil.log('Application config file not found. All components will be included.');
}
cb();
});
gulp.task('lnPatternsComponents', ['lnPatternsLoadConfig'], function (cb) {
var atoms = '';
var molecules = '';
var organisms = '';
var templates = '';
var controllers = '';
var count = 0;
//read tpl files
var componentsTpl = fs.readFileSync('./lib/ngComponents.tpl', ENCODING);
componentsTpl = componentsTpl.replace(HEADER_REGEX, COMMON_HEADER_JS);
var controllersTpl = fs.readFileSync('./lib/ngControllers.tpl', ENCODING);
controllersTpl = controllersTpl.replace(HEADER_REGEX, COMMON_HEADER_JS);
var patternsTpl = fs.readFileSync('./lib/' + PATTERNS_TEMPLATE + '.tpl', ENCODING);
patternsTpl = patternsTpl.replace(HEADER_REGEX, COMMON_HEADER_HTML);
//get component and example htmls and controller js from tpls
var componentHtml = COMPONENT_REGEX.exec(patternsTpl)[0];
componentHtml = componentHtml.replace('{COMPONENT}', '').replace('{END_COMPONENT}', '');
var exampleHtml = EXAMPLE_REGEX.exec(componentHtml)[0];
exampleHtml = exampleHtml.replace('{EXAMPLE}', '').replace('{END_EXAMPLE}', '');
var controllerJs = CONTROLLER_REGEX.exec(controllersTpl)[0];
controllerJs = controllerJs.replace('{CONTROLLER}', '').replace('{END_CONTROLLER}', '');
//clean patterns tpl
patternsTpl = patternsTpl.replace(COMPONENT_REGEX, '');
var include = function (file, collection) {
var splitted = file.split('/');
var folder = splitted.slice(2, -1).join('/');
var filename = splitted.pop().replace('.js', '');
var compEnabled = true;
var compConfig = null;
//check if the component is enabled in the application config file
if (appConfig) {
if (!_.has(appConfig, 'enabledComponents'))
compEnabled = false;
else if (_.isArray(appConfig.enabledComponents)) {
compConfig = _.find(appConfig.enabledComponents, {'component': folder});
if (!compConfig)
compEnabled = false;
}
else if (appConfig.enabledComponents != '*')
compEnabled = false;
}
if (compEnabled) {
//get component metadata
var metadata = require('./lib/' + folder + '/metadata.json');
//include import string into the corresponding atomic type
var reqStr = "require('./" + folder + "/" + filename + "');\n";
if (collection == 'atoms')
atoms += reqStr;
else if (collection == 'molecules')
molecules += reqStr;
else if (collection == 'organisms')
organisms += reqStr;
else
templates += reqStr;
if (filename.indexOf('directive') >= 0 || filename.indexOf('component') >= 0) {
count += 1;
//get component example instance html
var exampleInstanceHtml = fs.readFileSync('./lib/' + folder + '/example.html', ENCODING);
//generate examples with instantiated parameters
var examples = '';
if (compConfig && _.has(compConfig, 'examples') && _.isArray(compConfig.examples)) {
for (var i = 0; i < compConfig.examples.length; i++) {
var exampleInstance = compConfig.examples[i];
var controllerName = 'lnController_' + count + '_' + i;
var controllerAttrs = JSON.stringify(exampleInstance.params);
examples += exampleHtml
.replace(/{EXAMPLE_CONTROLLER}/g, controllerName)
.replace(/{EXAMPLE_NAME}/g, exampleInstance.name)
.replace(/{EXAMPLE_BG_COLOR}/g, (exampleInstance.bgColor || 'white'))
.replace(/{EXAMPLE_PARAMS}/g, controllerAttrs)
.replace(/{EXAMPLE_INSTANCE}/g, exampleInstanceHtml);
controllers += controllerJs
.replace(/{CONTROLLER_NAME}/g, controllerName)
.replace(/{CONTROLLER_ATTRIBUTES}/g, controllerAttrs);
}
}
//instantiate component html and include into patterns tpl
patternsTpl += componentHtml
.replace(/{COMPONENT_NAME}/g, metadata.name)
.replace(/{COMPONENT_DESCRIPTION}/g, metadata.description)
.replace(/{COMPONENT_PARAMS}/g, JSON.stringify(metadata.params))
.replace(/{COMPONENT_EXAMPLE}/g, _.escape(exampleInstanceHtml))
.replace(EXAMPLE_REGEX, examples);
//add component path to the enabled templates list
enabledTemplates.push('./lib/' + folder + '/template.html');
}
}
};
glob.sync('./lib/atoms/**/*.js').forEach(function (file) {
include(file, 'atoms');
});
glob.sync('./lib/molecules/**/*.js').forEach(function (file) {
include(file, 'molecules');
});
glob.sync('./lib/organisms/**/*.js').forEach(function (file) {
include(file, 'organisms');
});
glob.sync('./lib/templates/**/*.js').forEach(function (file) {
include(file, 'templates');
});
//instantiate components imports and generate ngComponents.js
componentsTpl = componentsTpl
.replace('{ATOMS}', atoms)
.replace('{MOLECULES}', molecules)
.replace('{ORGANISMS}', organisms)
.replace('{TEMPLATES}', templates);
fs.writeFileSync('./lib/ngComponents.js', componentsTpl);
//generate controllers and patterns page
var filePath = './lib/' + PATTERNS_TEMPLATE_PAGE;
if (!appConfig || appConfig.generatePatternsPage) {
enabledTemplates.push(filePath);
//generate patterns page
fs.writeFileSync(filePath, patternsTpl);
}
else {
//delete patterns page if exists
try {
fs.unlinkSync(filePath);
} catch (e) {
}
//clean controllers
controllers = '';
}
//instantiate controllers and generate ngControllers.js
controllersTpl = controllersTpl.replace(CONTROLLER_REGEX, controllers);
fs.writeFileSync('./lib/ngControllers.js', controllersTpl);
cb();
});
gulp.task('lnPatternsTemplates', ['lnPatternsComponents'], function () {
return gulp.src(enabledTemplates, {base: path.resolve(__dirname + '/lib/')})
//generate templates cache into ngTemplates.js
.pipe(templateCache('ngTemplates.js', {
transformUrl: function (url) {
if (url.indexOf(PATTERNS_TEMPLATE_PAGE) >= 0)
return PATTERNS_TEMPLATE_PAGE;
else {
//@Andy Barrios - there seems to be an issue here with the generated template address being incorrect
// This is hack fix for the moment!
return /*'lnPatterns' +*/ url.substring(1);
}
},
templateHeader: TEMPLATE_CACHE_HEADER
}))
//write ngTemplates.js into lib folder
.pipe(gulp.dest('./lib'));
});
gulp.task('lnPatterns', ['lnPatternsTemplates']);
| gulpfile.js | 'use strict';
//
// imports
//
var gulp = require('gulp');
var gutil = require('gulp-util');
var templateCache = require('gulp-angular-templatecache');
var fs = require('fs');
var glob = require('glob');
var path = require('path');
var _ = require('lodash');
//
// constants
//
var CONFIG_FILE = '../../config/patterns.json';
var COMMON_HEADER = 'AUTO-GENERATED BY GULP';
var COMMON_HEADER_JS = '/*** ' + COMMON_HEADER + ' ***/';
var COMMON_HEADER_HTML = '<!-- ' + COMMON_HEADER + ' -->';
var TEMPLATE_CACHE_HEADER = COMMON_HEADER_JS + '\n\n' + 'angular.module("lnPatterns").run(["$templateCache", function($templateCache) {';
var PATTERNS_TEMPLATE = 'templates/patterns/template';
var PATTERNS_TEMPLATE_PAGE = PATTERNS_TEMPLATE + '.html';
var ENCODING = 'utf8';
var HEADER_REGEX = /\/\*\*\*.*\*\*\*\//;
var COMPONENT_REGEX = /{COMPONENT}[\s\S]*{END_COMPONENT}/m;
var EXAMPLE_REGEX = /{EXAMPLE}[\s\S]*{END_EXAMPLE}/m;
var CONTROLLER_REGEX = /{CONTROLLER}[\s\S]*{END_CONTROLLER}/m;
//
// global variables
//
var appConfig = null;
var enabledTemplates = [];
//
// tasks
//
gulp.task('lnPatternsLoadConfig', function (cb) {
//load application config file
try {
appConfig = require(CONFIG_FILE);
}
catch (e) {
gutil.log('Application config file not found. All components will be included.');
}
cb();
});
gulp.task('lnPatternsComponents', ['lnPatternsLoadConfig'], function (cb) {
var atoms = '';
var molecules = '';
var organisms = '';
var templates = '';
var controllers = '';
var count = 0;
//read tpl files
var componentsTpl = fs.readFileSync('./lib/ngComponents.tpl', ENCODING);
componentsTpl = componentsTpl.replace(HEADER_REGEX, COMMON_HEADER_JS);
var controllersTpl = fs.readFileSync('./lib/ngControllers.tpl', ENCODING);
controllersTpl = controllersTpl.replace(HEADER_REGEX, COMMON_HEADER_JS);
var patternsTpl = fs.readFileSync('./lib/' + PATTERNS_TEMPLATE + '.tpl', ENCODING);
patternsTpl = patternsTpl.replace(HEADER_REGEX, COMMON_HEADER_HTML);
//get component and example htmls and controller js from tpls
var componentHtml = COMPONENT_REGEX.exec(patternsTpl)[0];
componentHtml = componentHtml.replace('{COMPONENT}', '').replace('{END_COMPONENT}', '');
var exampleHtml = EXAMPLE_REGEX.exec(componentHtml)[0];
exampleHtml = exampleHtml.replace('{EXAMPLE}', '').replace('{END_EXAMPLE}', '');
var controllerJs = CONTROLLER_REGEX.exec(controllersTpl)[0];
controllerJs = controllerJs.replace('{CONTROLLER}', '').replace('{END_CONTROLLER}', '');
//clean patterns tpl
patternsTpl = patternsTpl.replace(COMPONENT_REGEX, '');
var include = function (file, collection) {
var splitted = file.split('/');
var folder = splitted.slice(2, -1).join('/');
var filename = splitted.pop().replace('.js', '');
var compEnabled = true;
var compConfig = null;
//check if the component is enabled in the application config file
if (appConfig) {
if (!_.has(appConfig, 'enabledComponents'))
compEnabled = false;
else if (_.isArray(appConfig.enabledComponents)) {
compConfig = _.find(appConfig.enabledComponents, {'component': folder});
if (!compConfig)
compEnabled = false;
}
else if (appConfig.enabledComponents != '*')
compEnabled = false;
}
if (compEnabled) {
//get component metadata
var metadata = require('./lib/' + folder + '/metadata.json');
//include import string into the corresponding atomic type
var reqStr = "require('./" + folder + "/" + filename + "');\n";
if (collection == 'atoms')
atoms += reqStr;
else if (collection == 'molecules')
molecules += reqStr;
else if (collection == 'organisms')
organisms += reqStr;
else
templates += reqStr;
if (filename.indexOf('directive') >= 0 || filename.indexOf('component') >= 0) {
count += 1;
//get component example instance html
var exampleInstanceHtml = fs.readFileSync('./lib/' + folder + '/example.html', ENCODING);
//generate examples with instantiated parameters
var examples = '';
if (compConfig && _.has(compConfig, 'examples') && _.isArray(compConfig.examples)) {
for (var i = 0; i < compConfig.examples.length; i++) {
var exampleInstance = compConfig.examples[i];
var controllerName = 'lnController_' + count + '_' + i;
var controllerAttrs = JSON.stringify(exampleInstance.params);
examples += exampleHtml
.replace(/{EXAMPLE_CONTROLLER}/g, controllerName)
.replace(/{EXAMPLE_NAME}/g, exampleInstance.name)
.replace(/{EXAMPLE_BG_COLOR}/g, (exampleInstance.bgColor || 'white'))
.replace(/{EXAMPLE_PARAMS}/g, controllerAttrs)
.replace(/{EXAMPLE_INSTANCE}/g, exampleInstanceHtml);
controllers += controllerJs
.replace(/{CONTROLLER_NAME}/g, controllerName)
.replace(/{CONTROLLER_ATTRIBUTES}/g, controllerAttrs);
}
}
//instantiate component html and include into patterns tpl
patternsTpl += componentHtml
.replace(/{COMPONENT_NAME}/g, metadata.name)
.replace(/{COMPONENT_DESCRIPTION}/g, metadata.description)
.replace(/{COMPONENT_PARAMS}/g, JSON.stringify(metadata.params))
.replace(/{COMPONENT_EXAMPLE}/g, _.escape(exampleInstanceHtml))
.replace(EXAMPLE_REGEX, examples);
//add component path to the enabled templates list
enabledTemplates.push('./lib/' + folder + '/template.html');
}
}
};
glob.sync('./lib/atoms/**/*.js').forEach(function (file) {
include(file, 'atoms');
});
glob.sync('./lib/molecules/**/*.js').forEach(function (file) {
include(file, 'molecules');
});
glob.sync('./lib/organisms/**/*.js').forEach(function (file) {
include(file, 'organisms');
});
glob.sync('./lib/templates/**/*.js').forEach(function (file) {
include(file, 'templates');
});
//instantiate components imports and generate ngComponents.js
componentsTpl = componentsTpl
.replace('{ATOMS}', atoms)
.replace('{MOLECULES}', molecules)
.replace('{ORGANISMS}', organisms)
.replace('{TEMPLATES}', templates);
fs.writeFileSync('./lib/ngComponents.js', componentsTpl);
//generate controllers and patterns page
var filePath = './lib/' + PATTERNS_TEMPLATE_PAGE;
if (!appConfig || appConfig.generatePatternsPage) {
enabledTemplates.push(filePath);
//generate patterns page
fs.writeFileSync(filePath, patternsTpl);
}
else {
//delete patterns page if exists
try {
fs.unlinkSync(filePath);
} catch (e) {
}
//clean controllers
controllers = '';
}
//instantiate controllers and generate ngControllers.js
controllersTpl = controllersTpl.replace(CONTROLLER_REGEX, controllers);
fs.writeFileSync('./lib/ngControllers.js', controllersTpl);
cb();
});
gulp.task('lnPatternsTemplates', ['lnPatternsComponents'], function () {
return gulp.src(enabledTemplates, {base: path.resolve(__dirname + '/lib/')})
//generate templates cache into ngTemplates.js
.pipe(templateCache('ngTemplates.js', {
transformUrl: function (url) {
if (url.indexOf(PATTERNS_TEMPLATE_PAGE) >= 0)
return PATTERNS_TEMPLATE_PAGE;
else
return /*'lnPatterns' +*/ url.substring(1);
},
templateHeader: TEMPLATE_CACHE_HEADER
}))
//write ngTemplates.js into lib folder
.pipe(gulp.dest('./lib'));
});
gulp.task('lnPatterns', ['lnPatternsTemplates']);
| comment out gulpfile hack to fix template address issue
| gulpfile.js | comment out gulpfile hack to fix template address issue | <ide><path>ulpfile.js
<ide> transformUrl: function (url) {
<ide> if (url.indexOf(PATTERNS_TEMPLATE_PAGE) >= 0)
<ide> return PATTERNS_TEMPLATE_PAGE;
<del> else
<add> else {
<add> //@Andy Barrios - there seems to be an issue here with the generated template address being incorrect
<add> // This is hack fix for the moment!
<ide> return /*'lnPatterns' +*/ url.substring(1);
<add> }
<ide> },
<ide> templateHeader: TEMPLATE_CACHE_HEADER
<ide> })) |
|
JavaScript | mit | 5b168985806f7fd895bf7e603008c07a4ebd4c25 | 0 | damon-lanphear/ember-deploy-dynamodb,damon-lanphear/ember-deploy-dynamodb | /* jshint node: true */
'use strict';
var path = require('path');
var fs = require('fs');
var denodeify = require('rsvp').denodeify;
var readFile = denodeify(fs.readFile);
var DeployPluginBase = require('ember-cli-deploy-plugin');
var DynamoDBAdapter = require('./lib/dynamodb');
var Promise = require('rsvp').Promise;
var DEFAULT_MANIFEST_SIZE = 10;
module.exports = {
name: 'ember-cli-deploy-dynamodb',
createDeployPlugin: function(options) {
var DeployPlugin = DeployPluginBase.extend({
name: options.name,
defaultConfig: {
distDir: function(context) {
return context.distDir;
},
keyPrefix: function(context){
return context.project.name() + ':index';
},
filePattern: 'index.html',
activationSuffix: 'current',
manifestSize: DEFAULT_MANIFEST_SIZE,
revisionKey: function(context) {
return context.commandOptions.revision || (context.revisionData && context.revisionData.revisionKey);
},
dynamoDbClient: function(context) {
return new DynamoDBAdapter(this.pluginConfig);
},
didDeployMessage: function(context){
var revisionKey = context.revisionData && context.revisionData.revisionKey;
var activatedRevisionKey = context.revisionData && context.revisionData.activatedRevisionKey;
if (revisionKey && !activatedRevisionKey) {
return "Deployed but did not activate revision " + revisionKey + ". "
+ "To activate, run: "
+ "ember deploy:activate " + context.deployTarget + " --revision=" + revisionKey + "\n";
}
}
},
requiredConfig: ['region', 'table', 'indexName'],
upload: function(context) {
var filePattern = this.readConfig('filePattern');
var revisionKey = this.readConfig('revisionKey');
var distDir = this.readConfig('distDir');
var keyPrefix = this.readConfig('keyPrefix');
var dynamoDbClient = this.readConfig('dynamoDbClient');
var revision = this._makeKey(revisionKey);
return this._readFileContents(path.join(distDir, filePattern))
.then(function(indexContents) {
return dynamoDbClient.upload(indexContents, revision);
}).then(this._uploadSuccessMessage.bind(this))
.then(function(key) {
return { dynamodbKey: key };
})
.catch(this._errorMessage.bind(this));
},
activate: function(context) {
var dynamoDbClient = this.readConfig('dynamoDbClient');
var revisionKey = this.readConfig('revisionKey');
var keyPrefix = this.readConfig('keyPrefix');
var activationSuffix = this.readConfig('activationSuffix');
var currentKey = this._makeKey(activationSuffix);
var revision = this._makeKey(revisionKey);
this.log('Activating revision `' + revisionKey + '`', { verbose: true });
return dynamoDbClient.activate(revision, currentKey)
.then(this.log.bind(this, '✔ Activated revision `' + revisionKey + '`', {}))
.then(function(){
return {
revisionData: {
activatedRevisionKey: revisionKey
}
};
})
.catch(this._errorMessage.bind(this));
},
fetchRevisions: function(context) {
var keyPrefix = this.readConfig('keyPrefix');
var activationSuffix = this.readConfig('activationSuffix');
var dynamoDbClient = this.readConfig('dynamoDbClient');
this.log('Listing revisions');
return dynamoDbClient.list(this._makeKey(activationSuffix), this._makeKey())
.then(function(revisions) {
return { revisions: revisions };
})
.catch(this._errorMessage.bind(this));
},
didDeploy: function(context){
var didDeployMessage = this.readConfig('didDeployMessage');
if (didDeployMessage) {
this.log(didDeployMessage);
}
},
_readFileContents: function(path) {
return readFile(path)
.then(function(buffer) {
return buffer.toString();
});
},
_uploadSuccessMessage: function(key) {
this.log('Uploaded with key `' + key + '`', { verbose: true });
return Promise.resolve(key);
},
_errorMessage: function(error) {
this.log(error, { color: 'red' });
return Promise.reject(error);
},
_makeKey: function(value) {
value = value || '';
var keyPrefix = this.readConfig('keyPrefix');
return keyPrefix + ':' + value;
}
});
return new DeployPlugin();
}
};
| index.js | /* jshint node: true */
'use strict';
var path = require('path');
var fs = require('fs');
var denodeify = require('rsvp').denodeify;
var readFile = denodeify(fs.readFile);
var DeployPluginBase = require('ember-cli-deploy-plugin');
var DynamoDBAdapter = require('./lib/dynamodb');
var Promise = require('ember-cli/lib/ext/promise');
var DEFAULT_MANIFEST_SIZE = 10;
module.exports = {
name: 'ember-cli-deploy-dynamodb',
createDeployPlugin: function(options) {
var DeployPlugin = DeployPluginBase.extend({
name: options.name,
defaultConfig: {
distDir: function(context) {
return context.distDir;
},
keyPrefix: function(context){
return context.project.name() + ':index';
},
filePattern: 'index.html',
activationSuffix: 'current',
manifestSize: DEFAULT_MANIFEST_SIZE,
revisionKey: function(context) {
return context.commandOptions.revision || (context.revisionData && context.revisionData.revisionKey);
},
dynamoDbClient: function(context) {
return new DynamoDBAdapter(this.pluginConfig);
},
didDeployMessage: function(context){
var revisionKey = context.revisionData && context.revisionData.revisionKey;
var activatedRevisionKey = context.revisionData && context.revisionData.activatedRevisionKey;
if (revisionKey && !activatedRevisionKey) {
return "Deployed but did not activate revision " + revisionKey + ". "
+ "To activate, run: "
+ "ember deploy:activate " + context.deployTarget + " --revision=" + revisionKey + "\n";
}
}
},
requiredConfig: ['region', 'table', 'indexName'],
upload: function(context) {
var filePattern = this.readConfig('filePattern');
var revisionKey = this.readConfig('revisionKey');
var distDir = this.readConfig('distDir');
var keyPrefix = this.readConfig('keyPrefix');
var dynamoDbClient = this.readConfig('dynamoDbClient');
var revision = this._makeKey(revisionKey);
return this._readFileContents(path.join(distDir, filePattern))
.then(function(indexContents) {
return dynamoDbClient.upload(indexContents, revision);
}).then(this._uploadSuccessMessage.bind(this))
.then(function(key) {
return { dynamodbKey: key };
})
.catch(this._errorMessage.bind(this));
},
activate: function(context) {
var dynamoDbClient = this.readConfig('dynamoDbClient');
var revisionKey = this.readConfig('revisionKey');
var keyPrefix = this.readConfig('keyPrefix');
var activationSuffix = this.readConfig('activationSuffix');
var currentKey = this._makeKey(activationSuffix);
var revision = this._makeKey(revisionKey);
this.log('Activating revision `' + revisionKey + '`', { verbose: true });
return dynamoDbClient.activate(revision, currentKey)
.then(this.log.bind(this, '✔ Activated revision `' + revisionKey + '`', {}))
.then(function(){
return {
revisionData: {
activatedRevisionKey: revisionKey
}
};
})
.catch(this._errorMessage.bind(this));
},
fetchRevisions: function(context) {
var keyPrefix = this.readConfig('keyPrefix');
var activationSuffix = this.readConfig('activationSuffix');
var dynamoDbClient = this.readConfig('dynamoDbClient');
this.log('Listing revisions');
return dynamoDbClient.list(this._makeKey(activationSuffix), this._makeKey())
.then(function(revisions) {
return { revisions: revisions };
})
.catch(this._errorMessage.bind(this));
},
didDeploy: function(context){
var didDeployMessage = this.readConfig('didDeployMessage');
if (didDeployMessage) {
this.log(didDeployMessage);
}
},
_readFileContents: function(path) {
return readFile(path)
.then(function(buffer) {
return buffer.toString();
});
},
_uploadSuccessMessage: function(key) {
this.log('Uploaded with key `' + key + '`', { verbose: true });
return Promise.resolve(key);
},
_errorMessage: function(error) {
this.log(error, { color: 'red' });
return Promise.reject(error);
},
_makeKey: function(value) {
value = value || '';
var keyPrefix = this.readConfig('keyPrefix');
return keyPrefix + ':' + value;
}
});
return new DeployPlugin();
}
};
| Replace deprecated Promise with rsvp
Importing ember-cli/ext/promise has been deprecated and is generating warnings. This commit changes the require() to use rsvp directly. | index.js | Replace deprecated Promise with rsvp | <ide><path>ndex.js
<ide>
<ide> var DeployPluginBase = require('ember-cli-deploy-plugin');
<ide> var DynamoDBAdapter = require('./lib/dynamodb');
<del>var Promise = require('ember-cli/lib/ext/promise');
<add>var Promise = require('rsvp').Promise;
<ide>
<ide> var DEFAULT_MANIFEST_SIZE = 10;
<ide> |
|
Java | apache-2.0 | 11c6fcc1ea296497dcdfa445a58f7d2380b51b0b | 0 | quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus | package io.quarkus.arc.processor;
import io.quarkus.arc.Lock;
import io.quarkus.arc.impl.ActivateRequestContextInterceptor;
import io.quarkus.arc.impl.InjectableRequestContextController;
import io.quarkus.arc.impl.LockInterceptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.enterprise.context.BeforeDestroyed;
import javax.enterprise.context.Destroyed;
import javax.enterprise.context.Initialized;
import javax.enterprise.context.control.ActivateRequestContext;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.Intercepted;
import javax.enterprise.inject.Model;
import javax.inject.Named;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.CompositeIndex;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.Indexer;
import org.jboss.jandex.Type;
import org.jboss.logging.Logger;
public final class BeanArchives {
private static final Logger LOGGER = Logger.getLogger(BeanArchives.class);
/**
*
* @param applicationIndexes
* @return the final bean archive index
*/
public static IndexView buildBeanArchiveIndex(ClassLoader deploymentClassLoader,
Map<DotName, Optional<ClassInfo>> persistentClassIndex,
IndexView... applicationIndexes) {
List<IndexView> indexes = new ArrayList<>();
Collections.addAll(indexes, applicationIndexes);
indexes.add(buildAdditionalIndex());
return new IndexWrapper(CompositeIndex.create(indexes), deploymentClassLoader, persistentClassIndex);
}
private static IndexView buildAdditionalIndex() {
Indexer indexer = new Indexer();
// CDI API
index(indexer, ActivateRequestContext.class.getName());
index(indexer, Default.class.getName());
index(indexer, Any.class.getName());
index(indexer, Named.class.getName());
index(indexer, Initialized.class.getName());
index(indexer, BeforeDestroyed.class.getName());
index(indexer, Destroyed.class.getName());
index(indexer, Intercepted.class.getName());
index(indexer, Model.class.getName());
index(indexer, Lock.class.getName());
// Arc built-in beans
index(indexer, ActivateRequestContextInterceptor.class.getName());
index(indexer, InjectableRequestContextController.class.getName());
index(indexer, LockInterceptor.class.getName());
return indexer.complete();
}
/**
* This wrapper is used to index JDK classes on demand.
*/
static class IndexWrapper implements IndexView {
private final IndexView index;
private final ClassLoader deploymentClassLoader;
final Map<DotName, Optional<ClassInfo>> additionalClasses;
public IndexWrapper(IndexView index, ClassLoader deploymentClassLoader,
Map<DotName, Optional<ClassInfo>> additionalClasses) {
this.index = index;
this.deploymentClassLoader = deploymentClassLoader;
this.additionalClasses = additionalClasses;
}
@Override
public Collection<ClassInfo> getKnownClasses() {
return index.getKnownClasses();
}
@Override
public ClassInfo getClassByName(DotName className) {
ClassInfo classInfo = IndexClassLookupUtils.getClassByName(index, className, false);
if (classInfo == null) {
classInfo = additionalClasses.computeIfAbsent(className, this::computeAdditional).orElse(null);
}
return classInfo;
}
@Override
public Collection<ClassInfo> getKnownDirectSubclasses(DotName className) {
if (additionalClasses.isEmpty()) {
return index.getKnownDirectSubclasses(className);
}
Set<ClassInfo> directSubclasses = new HashSet<ClassInfo>(index.getKnownDirectSubclasses(className));
for (Optional<ClassInfo> additional : additionalClasses.values()) {
if (additional.isPresent() && className.equals(additional.get().superName())) {
directSubclasses.add(additional.get());
}
}
return directSubclasses;
}
@Override
public Collection<ClassInfo> getAllKnownSubclasses(DotName className) {
if (additionalClasses.isEmpty()) {
return index.getAllKnownSubclasses(className);
}
final Set<ClassInfo> allKnown = new HashSet<ClassInfo>();
final Set<DotName> processedClasses = new HashSet<DotName>();
getAllKnownSubClasses(className, allKnown, processedClasses);
return allKnown;
}
@Override
public Collection<ClassInfo> getKnownDirectImplementors(DotName className) {
if (additionalClasses.isEmpty()) {
return index.getKnownDirectImplementors(className);
}
Set<ClassInfo> directImplementors = new HashSet<ClassInfo>(index.getKnownDirectImplementors(className));
for (Optional<ClassInfo> additional : additionalClasses.values()) {
if (!additional.isPresent()) {
continue;
}
for (Type interfaceType : additional.get().interfaceTypes()) {
if (className.equals(interfaceType.name())) {
directImplementors.add(additional.get());
break;
}
}
}
return directImplementors;
}
@Override
public Collection<ClassInfo> getAllKnownImplementors(DotName interfaceName) {
if (additionalClasses.isEmpty()) {
return index.getAllKnownImplementors(interfaceName);
}
final Set<ClassInfo> allKnown = new HashSet<ClassInfo>();
final Set<DotName> subInterfacesToProcess = new HashSet<DotName>();
final Set<DotName> processedClasses = new HashSet<DotName>();
subInterfacesToProcess.add(interfaceName);
while (!subInterfacesToProcess.isEmpty()) {
final Iterator<DotName> toProcess = subInterfacesToProcess.iterator();
DotName name = toProcess.next();
toProcess.remove();
processedClasses.add(name);
getKnownImplementors(name, allKnown, subInterfacesToProcess, processedClasses);
}
return allKnown;
}
@Override
public Collection<AnnotationInstance> getAnnotations(DotName annotationName) {
return index.getAnnotations(annotationName);
}
@Override
public Collection<AnnotationInstance> getAnnotationsWithRepeatable(DotName annotationName, IndexView index) {
return this.index.getAnnotationsWithRepeatable(annotationName, index);
}
private void getAllKnownSubClasses(DotName className, Set<ClassInfo> allKnown, Set<DotName> processedClasses) {
final Set<DotName> subClassesToProcess = new HashSet<DotName>();
subClassesToProcess.add(className);
while (!subClassesToProcess.isEmpty()) {
final Iterator<DotName> toProcess = subClassesToProcess.iterator();
DotName name = toProcess.next();
toProcess.remove();
processedClasses.add(name);
getAllKnownSubClasses(name, allKnown, subClassesToProcess, processedClasses);
}
}
private void getAllKnownSubClasses(DotName name, Set<ClassInfo> allKnown, Set<DotName> subClassesToProcess,
Set<DotName> processedClasses) {
final Collection<ClassInfo> directSubclasses = getKnownDirectSubclasses(name);
if (directSubclasses != null) {
for (final ClassInfo clazz : directSubclasses) {
final DotName className = clazz.name();
if (!processedClasses.contains(className)) {
allKnown.add(clazz);
subClassesToProcess.add(className);
}
}
}
}
private void getKnownImplementors(DotName name, Set<ClassInfo> allKnown, Set<DotName> subInterfacesToProcess,
Set<DotName> processedClasses) {
final Collection<ClassInfo> list = getKnownDirectImplementors(name);
if (list != null) {
for (final ClassInfo clazz : list) {
final DotName className = clazz.name();
if (!processedClasses.contains(className)) {
if (Modifier.isInterface(clazz.flags())) {
subInterfacesToProcess.add(className);
} else {
if (!allKnown.contains(clazz)) {
allKnown.add(clazz);
processedClasses.add(className);
getAllKnownSubClasses(className, allKnown, processedClasses);
}
}
}
}
}
}
private Optional<ClassInfo> computeAdditional(DotName className) {
LOGGER.debugf("Index: %s", className);
Indexer indexer = new Indexer();
if (BeanArchives.index(indexer, className.toString(), deploymentClassLoader)) {
Index index = indexer.complete();
return Optional.of(index.getClassByName(className));
} else {
// Note that ConcurrentHashMap does not allow null to be used as a value
return Optional.empty();
}
}
}
static boolean index(Indexer indexer, String className) {
return index(indexer, className, BeanArchives.class.getClassLoader());
}
static boolean index(Indexer indexer, String className, ClassLoader classLoader) {
boolean result = false;
try (InputStream stream = classLoader
.getResourceAsStream(className.replace('.', '/') + ".class")) {
if (stream != null) {
indexer.index(stream);
result = true;
} else {
LOGGER.warnf("Failed to index %s: Class does not exist in ClassLoader %s", className, classLoader);
}
} catch (IOException e) {
LOGGER.warnf(e, "Failed to index %s: %s", className, e.getMessage());
}
return result;
}
}
| independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanArchives.java | package io.quarkus.arc.processor;
import io.quarkus.arc.Lock;
import io.quarkus.arc.impl.ActivateRequestContextInterceptor;
import io.quarkus.arc.impl.InjectableRequestContextController;
import io.quarkus.arc.impl.LockInterceptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.enterprise.context.BeforeDestroyed;
import javax.enterprise.context.Destroyed;
import javax.enterprise.context.Initialized;
import javax.enterprise.context.control.ActivateRequestContext;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.Intercepted;
import javax.enterprise.inject.Model;
import javax.inject.Named;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.CompositeIndex;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.Indexer;
import org.jboss.jandex.Type;
import org.jboss.logging.Logger;
public final class BeanArchives {
private static final Logger LOGGER = Logger.getLogger(BeanArchives.class);
/**
*
* @param applicationIndexes
* @return the final bean archive index
*/
public static IndexView buildBeanArchiveIndex(ClassLoader deploymentClassLoader,
Map<DotName, Optional<ClassInfo>> persistentClassIndex,
IndexView... applicationIndexes) {
List<IndexView> indexes = new ArrayList<>();
Collections.addAll(indexes, applicationIndexes);
indexes.add(buildAdditionalIndex());
return new IndexWrapper(CompositeIndex.create(indexes), deploymentClassLoader, persistentClassIndex);
}
private static IndexView buildAdditionalIndex() {
Indexer indexer = new Indexer();
// CDI API
index(indexer, ActivateRequestContext.class.getName());
index(indexer, Default.class.getName());
index(indexer, Any.class.getName());
index(indexer, Named.class.getName());
index(indexer, Initialized.class.getName());
index(indexer, BeforeDestroyed.class.getName());
index(indexer, Destroyed.class.getName());
index(indexer, Intercepted.class.getName());
index(indexer, Model.class.getName());
index(indexer, Lock.class.getName());
// Arc built-in beans
index(indexer, ActivateRequestContextInterceptor.class.getName());
index(indexer, InjectableRequestContextController.class.getName());
index(indexer, LockInterceptor.class.getName());
return indexer.complete();
}
/**
* This wrapper is used to index JDK classes on demand.
*/
static class IndexWrapper implements IndexView {
private final IndexView index;
private final ClassLoader deploymentClassLoader;
final Map<DotName, Optional<ClassInfo>> additionalClasses;
public IndexWrapper(IndexView index, ClassLoader deploymentClassLoader,
Map<DotName, Optional<ClassInfo>> additionalClasses) {
this.index = index;
this.deploymentClassLoader = deploymentClassLoader;
this.additionalClasses = additionalClasses;
}
@Override
public Collection<ClassInfo> getKnownClasses() {
if (additionalClasses.isEmpty()) {
return index.getKnownClasses();
}
Collection<ClassInfo> known = index.getKnownClasses();
Collection<ClassInfo> additional = additionalClasses.values().stream().filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
List<ClassInfo> all = new ArrayList<>(known.size() + additional.size());
all.addAll(known);
all.addAll(additional);
return all;
}
@Override
public ClassInfo getClassByName(DotName className) {
ClassInfo classInfo = IndexClassLookupUtils.getClassByName(index, className, false);
if (classInfo == null) {
classInfo = additionalClasses.computeIfAbsent(className, this::computeAdditional).orElse(null);
}
return classInfo;
}
@Override
public Collection<ClassInfo> getKnownDirectSubclasses(DotName className) {
if (additionalClasses.isEmpty()) {
return index.getKnownDirectSubclasses(className);
}
Set<ClassInfo> directSubclasses = new HashSet<ClassInfo>(index.getKnownDirectSubclasses(className));
for (Optional<ClassInfo> additional : additionalClasses.values()) {
if (additional.isPresent() && className.equals(additional.get().superName())) {
directSubclasses.add(additional.get());
}
}
return directSubclasses;
}
@Override
public Collection<ClassInfo> getAllKnownSubclasses(DotName className) {
if (additionalClasses.isEmpty()) {
return index.getAllKnownSubclasses(className);
}
final Set<ClassInfo> allKnown = new HashSet<ClassInfo>();
final Set<DotName> processedClasses = new HashSet<DotName>();
getAllKnownSubClasses(className, allKnown, processedClasses);
return allKnown;
}
@Override
public Collection<ClassInfo> getKnownDirectImplementors(DotName className) {
if (additionalClasses.isEmpty()) {
return index.getKnownDirectImplementors(className);
}
Set<ClassInfo> directImplementors = new HashSet<ClassInfo>(index.getKnownDirectImplementors(className));
for (Optional<ClassInfo> additional : additionalClasses.values()) {
if (!additional.isPresent()) {
continue;
}
for (Type interfaceType : additional.get().interfaceTypes()) {
if (className.equals(interfaceType.name())) {
directImplementors.add(additional.get());
break;
}
}
}
return directImplementors;
}
@Override
public Collection<ClassInfo> getAllKnownImplementors(DotName interfaceName) {
if (additionalClasses.isEmpty()) {
return index.getAllKnownImplementors(interfaceName);
}
final Set<ClassInfo> allKnown = new HashSet<ClassInfo>();
final Set<DotName> subInterfacesToProcess = new HashSet<DotName>();
final Set<DotName> processedClasses = new HashSet<DotName>();
subInterfacesToProcess.add(interfaceName);
while (!subInterfacesToProcess.isEmpty()) {
final Iterator<DotName> toProcess = subInterfacesToProcess.iterator();
DotName name = toProcess.next();
toProcess.remove();
processedClasses.add(name);
getKnownImplementors(name, allKnown, subInterfacesToProcess, processedClasses);
}
return allKnown;
}
@Override
public Collection<AnnotationInstance> getAnnotations(DotName annotationName) {
return index.getAnnotations(annotationName);
}
@Override
public Collection<AnnotationInstance> getAnnotationsWithRepeatable(DotName annotationName, IndexView index) {
return this.index.getAnnotationsWithRepeatable(annotationName, index);
}
private void getAllKnownSubClasses(DotName className, Set<ClassInfo> allKnown, Set<DotName> processedClasses) {
final Set<DotName> subClassesToProcess = new HashSet<DotName>();
subClassesToProcess.add(className);
while (!subClassesToProcess.isEmpty()) {
final Iterator<DotName> toProcess = subClassesToProcess.iterator();
DotName name = toProcess.next();
toProcess.remove();
processedClasses.add(name);
getAllKnownSubClasses(name, allKnown, subClassesToProcess, processedClasses);
}
}
private void getAllKnownSubClasses(DotName name, Set<ClassInfo> allKnown, Set<DotName> subClassesToProcess,
Set<DotName> processedClasses) {
final Collection<ClassInfo> directSubclasses = getKnownDirectSubclasses(name);
if (directSubclasses != null) {
for (final ClassInfo clazz : directSubclasses) {
final DotName className = clazz.name();
if (!processedClasses.contains(className)) {
allKnown.add(clazz);
subClassesToProcess.add(className);
}
}
}
}
private void getKnownImplementors(DotName name, Set<ClassInfo> allKnown, Set<DotName> subInterfacesToProcess,
Set<DotName> processedClasses) {
final Collection<ClassInfo> list = getKnownDirectImplementors(name);
if (list != null) {
for (final ClassInfo clazz : list) {
final DotName className = clazz.name();
if (!processedClasses.contains(className)) {
if (Modifier.isInterface(clazz.flags())) {
subInterfacesToProcess.add(className);
} else {
if (!allKnown.contains(clazz)) {
allKnown.add(clazz);
processedClasses.add(className);
getAllKnownSubClasses(className, allKnown, processedClasses);
}
}
}
}
}
}
private Optional<ClassInfo> computeAdditional(DotName className) {
LOGGER.debugf("Index: %s", className);
Indexer indexer = new Indexer();
if (BeanArchives.index(indexer, className.toString(), deploymentClassLoader)) {
Index index = indexer.complete();
return Optional.of(index.getClassByName(className));
} else {
// Note that ConcurrentHashMap does not allow null to be used as a value
return Optional.empty();
}
}
}
static boolean index(Indexer indexer, String className) {
return index(indexer, className, BeanArchives.class.getClassLoader());
}
static boolean index(Indexer indexer, String className, ClassLoader classLoader) {
boolean result = false;
try (InputStream stream = classLoader
.getResourceAsStream(className.replace('.', '/') + ".class")) {
if (stream != null) {
indexer.index(stream);
result = true;
} else {
LOGGER.warnf("Failed to index %s: Class does not exist in ClassLoader %s", className, classLoader);
}
} catch (IOException e) {
LOGGER.warnf(e, "Failed to index %s: %s", className, e.getMessage());
}
return result;
}
}
| Don't include on-demand indexed classes in getAllClasses
This can cause problems as on demand classes can be added
by other build steps concurrently, which can give an inconsistent
view. It can also lead to classes that are not in a bean archive
to be considered as beans.
| independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanArchives.java | Don't include on-demand indexed classes in getAllClasses | <ide><path>ndependent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanArchives.java
<ide> import java.util.Map;
<ide> import java.util.Optional;
<ide> import java.util.Set;
<del>import java.util.stream.Collectors;
<ide> import javax.enterprise.context.BeforeDestroyed;
<ide> import javax.enterprise.context.Destroyed;
<ide> import javax.enterprise.context.Initialized;
<ide>
<ide> @Override
<ide> public Collection<ClassInfo> getKnownClasses() {
<del> if (additionalClasses.isEmpty()) {
<del> return index.getKnownClasses();
<del> }
<del> Collection<ClassInfo> known = index.getKnownClasses();
<del> Collection<ClassInfo> additional = additionalClasses.values().stream().filter(Optional::isPresent)
<del> .map(Optional::get)
<del> .collect(Collectors.toList());
<del> List<ClassInfo> all = new ArrayList<>(known.size() + additional.size());
<del> all.addAll(known);
<del> all.addAll(additional);
<del> return all;
<add> return index.getKnownClasses();
<ide> }
<ide>
<ide> @Override |
|
JavaScript | mit | 8865bc6e145b9c7730a23a54857d9bac26370925 | 0 | educach/curricula-ui,educach/curricula-ui,educach/curricula-ui |
(function($, Backbone, _, Archibald) {
// Prepare a global item database. This will allow us to quickly update large
// lists of items, in case of recursive checking, for example.
var itemDatabase = new Archibald.ItemCollection();
// Prepare a global column database. This will allow us to manipulate columns,
// like collapsing, hiding, showing, etc.
var columnDatabase = new Archibald.ColumnCollection();
columnDatabase.on('remove', function(model) {
model.get('column').remove();
});
// Prepare a global reference to the application wrapper.
var $wrapper;
// Prepare a global reference to the application summary wrapper, if used.
var $summaryWrapper;
// Prepare a global reference to the summary view.
var summaryTreeView;
/**
* Set or refresh the application DOM wrapper.
*
* @param {Object} wrapper
* The jQuery object that serves as a wrapper for the application.
*/
Archibald.setWrapper = function(wrapper) {
$wrapper = wrapper;
}
/**
* Get the application DOM wrapper.
*
* @returns {Object}
*/
Archibald.getWrapper = function() {
return $wrapper;
}
/**
* Set or refresh the application summary DOM wrapper.
*
* @param {Object} wrapper
* The jQuery object that serves as a wrapper for the application summary.
*/
Archibald.setSummaryWrapper = function(wrapper) {
$summaryWrapper = wrapper;
// Empty the summary view.
wrapper.empty();
// Fetch all active elements from the database. We pass these to our View,
// which will render a tree recursively.
summaryTreeView = new Archibald.SummaryTreeView({
collection: Archibald.getItemDatabase()
});
wrapper.append(summaryTreeView.render().$el);
}
/**
* Get the application summary DOM wrapper.
*
* @returns {Object}
*/
Archibald.getSummaryWrapper = function() {
return $summaryWrapper;
}
/**
* Get the application summary view.
*
* @returns {Object}
*/
Archibald.getSummary = function() {
return summaryTreeView;
}
/**
* Set or refresh the global item database.
*
* @param {Object} items
* An object representing the JSON database of all curriculum items.
*/
Archibald.setItemDatabase = function(items) {
for (var group in items) {
for (var i in items[group]) {
Archibald.getItemDatabase().add(new Archibald.ItemModel({
id: items[group][i].id,
name: items[group][i].name,
hasChildren: !!(typeof items[items[group][i].id] !== undefined && items[items[group][i].id].length),
data: items[group][i].data,
parentId: group
}));
}
}
};
/**
* Get the global item database.
*
* @returns {ArchibaldCurriculum.ItemCollection}
*/
Archibald.getItemDatabase = function() {
return itemDatabase;
};
/**
* Get the global column database.
*
* @returns {ArchibaldCurriculum.ColumnCollection}
*/
Archibald.getColumnDatabase = function() {
return columnDatabase;
};
/**
* Prepare a new column.
*
* @param {Array} items
* The items to put in the column.
* @param {Boolean} editable
* (optional) Whether the column items are editable or not. Defaults to true.
* @param {Boolean} collapsed
* (optional) Whether the column should be collapsed on creation or not.
* Defaults to false.
*
* @returns {ArchibaldCurriculum.ItemListView}
*/
Archibald.createColumn = function(items, editable, collapsed) {
// Editable by default.
editable = typeof editable !== 'undefined' ? editable : true;
var column = new Archibald.ItemListView({
collection: new Archibald.ItemCollection(items),
editable: editable
});
if (collapsed) {
column.collapse();
}
// Add it to the wrapper.
Archibald.getWrapper().append(column.render().$el);
// Activate the nanoScroller plugin.
// @todo Handle this in Drupal scope?
if (typeof $.fn.nanoScroller !== 'undefined') {
column.$el.find('.nano').nanoScroller();
}
Archibald.getColumnDatabase().add({ column: column});
return column;
};
/**
* Get the columns on the right of the passed column.
*
* @param {ArchibaldCurriculum.ItemListView} column
*
* @returns {Array}
* An array of ArchibaldCurriculum.ColumnModel items.
*/
Archibald.getColumnRightSiblings = function(column) {
var index = Archibald.getColumnDatabase().indexOf(
Archibald.getColumnDatabase().findWhere({ column: column })
);
if (Archibald.getColumnDatabase().length > index + 1) {
return Archibald.getColumnDatabase().slice(index + 1);
}
else {
return [];
}
};
/**
* Get the columns on the left of the passed column.
*
* @returns {Array}
* An array of ArchibaldCurriculum.ColumnModel items.
*/
Archibald.getColumnLeftSiblings = function(column) {
var index = Archibald.getColumnDatabase().indexOf(
Archibald.getColumnDatabase().findWhere({ column: column })
);
return Archibald.getColumnDatabase().slice(0, index);
};
/**
* Helper function to recursively "check" or "uncheck" items.
*
* @param {ArchibaldCurriculum.ItemModel} item
* The item from which the recursive (un)checking must start.
* @param {Boolean} prompt
* (optional) Whether to prompt the user in case of recursively unchecking
* items. Defaults to true.
* @param {String} promptMessage
* (optional) If the user must be prompted, this message will be used.
* Defaults to "This will also uncheck all child items. Are you sure you want
* to continue?"
*/
Archibald.recursiveCheck = function(item, prompt, promptMessage) {
prompt = !!prompt;
promptMessage = promptMessage || "This will also uncheck all child items. Are you sure you want to continue?";
// If an item is selected, we must also select all its parents.
if (item.get('active')) {
var parentId = item.get('parentId'),
parentItem;
while (parentId !== 'root') {
parentItem = Archibald.getItemDatabase().get(parentId);
parentItem.set('active', true);
parentId = parentItem.get('parentId');
}
}
else if (item.get('hasChildren')) {
// Else, we must unselect its children. But, in order to prevent
// errors, we ask the user for confirmation.
if (!prompt || confirm(promptMessage)) {
// Helper function for recursively looking up selected child
// items.
var recursiveUnselect = function(item) {
item.set('active', false);
var childItems = Archibald.getItemDatabase().where({
parentId: item.get('id'),
active: true
});
for (var i in childItems) {
recursiveUnselect(childItems[i]);
}
};
recursiveUnselect(item);
}
else {
// Because the item was already unselected (the event is triggered
// after the actual property change), we must undo it and
// re-select our item.
item.set('active', true);
}
}
};
})(jQuery, Backbone, _, window.ArchibaldCurriculum || (window.ArchibaldCurriculum = {}));
| app/js/core.js |
(function($, Backbone, _, Archibald) {
// Prepare a global item database. This will allow us to quickly update large
// lists of items, in case of recursive checking, for example.
var itemDatabase = new Archibald.ItemCollection();
// Prepare a global column database. This will allow us to manipulate columns,
// like collapsing, hiding, showing, etc.
var columnDatabase = new Archibald.ColumnCollection();
columnDatabase.on('remove', function(model) {
model.get('column').remove();
});
// Prepare a global reference to the application wrapper.
var $wrapper;
// Prepare a global reference to the application summary wrapper, if used.
var $summaryWrapper;
// Prepare a global reference to the summary view.
var summaryTreeView;
/**
* Set or refresh the application DOM wrapper.
*
* @param {Object} wrapper
* The jQuery object that serves as a wrapper for the application.
*/
Archibald.setWrapper = function(wrapper) {
$wrapper = wrapper;
}
/**
* Get the application DOM wrapper.
*
* @returns {Object}
*/
Archibald.getWrapper = function() {
return $wrapper;
}
/**
* Set or refresh the application summary DOM wrapper.
*
* @param {Object} wrapper
* The jQuery object that serves as a wrapper for the application summary.
*/
Archibald.setSummaryWrapper = function(wrapper) {
$summaryWrapper = wrapper;
// Empty the summary view.
wrapper.empty();
// Fetch all active elements from the database. We pass these to our View,
// which will render a tree recursively.
summaryTreeView = new Archibald.SummaryTreeView({
collection: Archibald.getItemDatabase()
});
wrapper.append(summaryTreeView.render().$el);
}
/**
* Get the application summary DOM wrapper.
*
* @returns {Object}
*/
Archibald.getSummaryWrapper = function() {
return $summaryWrapper;
}
/**
* Get the application summary view.
*
* @returns {Object}
*/
Archibald.getSummary = function() {
return summaryTreeView;
}
/**
* Set or refresh the global item database.
*
* @param {Object} items
* An object representing the JSON database of all curriculum items.
*/
Archibald.setItemDatabase = function(items) {
for (var group in items) {
for (var i in items[group]) {
Archibald.getItemDatabase().add(new Archibald.ItemModel({
id: items[group][i].id,
name: items[group][i].name,
hasChildren: typeof items[items[group][i].id] !== undefined && items[items[group][i].id].length,
data: items[group][i].data,
parentId: group
}));
}
}
};
/**
* Get the global item database.
*
* @returns {ArchibaldCurriculum.ItemCollection}
*/
Archibald.getItemDatabase = function() {
return itemDatabase;
};
/**
* Get the global column database.
*
* @returns {ArchibaldCurriculum.ColumnCollection}
*/
Archibald.getColumnDatabase = function() {
return columnDatabase;
};
/**
* Prepare a new column.
*
* @param {Array} items
* The items to put in the column.
* @param {Boolean} editable
* (optional) Whether the column items are editable or not. Defaults to true.
* @param {Boolean} collapsed
* (optional) Whether the column should be collapsed on creation or not.
* Defaults to false.
*
* @returns {ArchibaldCurriculum.ItemListView}
*/
Archibald.createColumn = function(items, editable, collapsed) {
// Editable by default.
editable = typeof editable !== 'undefined' ? editable : true;
var column = new Archibald.ItemListView({
collection: new Archibald.ItemCollection(items),
editable: editable
});
if (collapsed) {
column.collapse();
}
// Add it to the wrapper.
Archibald.getWrapper().append(column.render().$el);
// Activate the nanoScroller plugin.
// @todo Handle this in Drupal scope?
if (typeof $.fn.nanoScroller !== 'undefined') {
column.$el.find('.nano').nanoScroller();
}
Archibald.getColumnDatabase().add({ column: column});
return column;
};
/**
* Get the columns on the right of the passed column.
*
* @param {ArchibaldCurriculum.ItemListView} column
*
* @returns {Array}
* An array of ArchibaldCurriculum.ColumnModel items.
*/
Archibald.getColumnRightSiblings = function(column) {
var index = Archibald.getColumnDatabase().indexOf(
Archibald.getColumnDatabase().findWhere({ column: column })
);
if (Archibald.getColumnDatabase().length > index + 1) {
return Archibald.getColumnDatabase().slice(index + 1);
}
else {
return [];
}
};
/**
* Get the columns on the left of the passed column.
*
* @returns {Array}
* An array of ArchibaldCurriculum.ColumnModel items.
*/
Archibald.getColumnLeftSiblings = function(column) {
var index = Archibald.getColumnDatabase().indexOf(
Archibald.getColumnDatabase().findWhere({ column: column })
);
return Archibald.getColumnDatabase().slice(0, index);
};
/**
* Helper function to recursively "check" or "uncheck" items.
*
* @param {ArchibaldCurriculum.ItemModel} item
* The item from which the recursive (un)checking must start.
* @param {Boolean} prompt
* (optional) Whether to prompt the user in case of recursively unchecking
* items. Defaults to true.
* @param {String} promptMessage
* (optional) If the user must be prompted, this message will be used.
* Defaults to "This will also uncheck all child items. Are you sure you want
* to continue?"
*/
Archibald.recursiveCheck = function(item, prompt, promptMessage) {
prompt = !!prompt;
promptMessage = promptMessage || "This will also uncheck all child items. Are you sure you want to continue?";
// If an item is selected, we must also select all its parents.
if (item.get('active')) {
var parentId = item.get('parentId'),
parentItem;
while (parentId !== 'root') {
parentItem = Archibald.getItemDatabase().get(parentId);
parentItem.set('active', true);
parentId = parentItem.get('parentId');
}
}
else if (item.get('hasChildren')) {
// Else, we must unselect its children. But, in order to prevent
// errors, we ask the user for confirmation.
if (!prompt || confirm(promptMessage)) {
// Helper function for recursively looking up selected child
// items.
var recursiveUnselect = function(item) {
item.set('active', false);
var childItems = Archibald.getItemDatabase().where({
parentId: item.get('id'),
active: true
});
for (var i in childItems) {
recursiveUnselect(childItems[i]);
}
};
recursiveUnselect(item);
}
else {
// Because the item was already unselected (the event is triggered
// after the actual property change), we must undo it and
// re-select our item.
item.set('active', true);
}
}
};
})(jQuery, Backbone, _, window.ArchibaldCurriculum || (window.ArchibaldCurriculum = {}));
| Make sure we cast this to a boolean, otherwise .where() queries might not return expected results.
| app/js/core.js | Make sure we cast this to a boolean, otherwise .where() queries might not return expected results. | <ide><path>pp/js/core.js
<ide> Archibald.getItemDatabase().add(new Archibald.ItemModel({
<ide> id: items[group][i].id,
<ide> name: items[group][i].name,
<del> hasChildren: typeof items[items[group][i].id] !== undefined && items[items[group][i].id].length,
<add> hasChildren: !!(typeof items[items[group][i].id] !== undefined && items[items[group][i].id].length),
<ide> data: items[group][i].data,
<ide> parentId: group
<ide> })); |
|
Java | mit | 141abe71c6fe44f7e8937d523183aa8b8c87b674 | 0 | dchouzer/OOGASalad,tjqadri101/oogasalad | package gameFactory;
import java.util.ResourceBundle;
import objects.GameObject;
import jgame.JGObject;
import util.reflection.*;
/*
* @Author: Steve (Siyang) Wang
*/
public class GameFactory {
private String myOrder;
private GameObject myObject;
public static final String RESOURCE_PACKAGE = "engineResources/";
public static final String DEFAULT_FORMAT= "DataFormat";
public static final String DEFAULT_NULL = "null";
protected ResourceBundle myFormat;
protected GameFactory(String order, GameObject object){
myOrder = order;
myObject = object;
myFormat = ResourceBundle.getBundle(RESOURCE_PACKAGE + DEFAULT_FORMAT);
}
/**
* Only takes String order as argument, for creation.
*/
public GameObject processOrder(String order){
parseOrder(order);
try{
Object myObject = Reflection.createInstance(myFormat.getString(myMoveMethod), this);
Reflection.callMethod(behavior, "move", mySetXSpeed, mySetYSpeed);
} catch (Exception e){
e.printStackTrace(); //should never reach here
}
return null;
}
private void parseOrder (String order) {
// TODO Auto-generated method stub
}
/**
* Takes Object and String order as argument, for modification.
*/
public void processOrder(JGObject object, String order){
parseOrder(order);
try{
// http://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html
// http://java.sun.com/docs/books/tutorial/reflect/member/methodInvocation.html
// http://docs.oracle.com/javase/tutorial/reflect/member/fieldValues.html
// Object instance = Class.forName("Foobar").newInstance();
Object behavior = Reflection.createInstance(myFormat.getString(myMoveMethod), this);
Reflection.callMethod(behavior, "move", mySetXSpeed, mySetYSpeed);
} catch (Exception e){
e.printStackTrace(); //should never reach here
}
}
}
| src/gameFactory/GameFactory.java | package gameFactory;
import objects.GameObject;
import jgame.JGObject;
public class GameFactory {
/**
* Only takes String ordre as argument, for creation.
*/
public GameObject processOrder(String order){
return null;
}
/**
* Takes Object and String order as argument, for modification.
*/
public void processOrder(JGObject object, String order){
}
}
| try to merge conflict
| src/gameFactory/GameFactory.java | try to merge conflict | <ide><path>rc/gameFactory/GameFactory.java
<ide> package gameFactory;
<ide>
<add>import java.util.ResourceBundle;
<ide> import objects.GameObject;
<ide> import jgame.JGObject;
<add>import util.reflection.*;
<add>/*
<add> * @Author: Steve (Siyang) Wang
<add> */
<add>public class GameFactory {
<add> private String myOrder;
<add> private GameObject myObject;
<add> public static final String RESOURCE_PACKAGE = "engineResources/";
<add> public static final String DEFAULT_FORMAT= "DataFormat";
<add> public static final String DEFAULT_NULL = "null";
<add>
<add> protected ResourceBundle myFormat;
<add>
<add> protected GameFactory(String order, GameObject object){
<add> myOrder = order;
<add> myObject = object;
<add> myFormat = ResourceBundle.getBundle(RESOURCE_PACKAGE + DEFAULT_FORMAT);
<add> }
<add>
<add> /**
<add> * Only takes String order as argument, for creation.
<add> */
<add> public GameObject processOrder(String order){
<add> parseOrder(order);
<add>
<add> try{
<add> Object myObject = Reflection.createInstance(myFormat.getString(myMoveMethod), this);
<add> Reflection.callMethod(behavior, "move", mySetXSpeed, mySetYSpeed);
<add> } catch (Exception e){
<add> e.printStackTrace(); //should never reach here
<add> }
<ide>
<del>public class GameFactory {
<del>
<del> /**
<del> * Only takes String ordre as argument, for creation.
<del> */
<del> public GameObject processOrder(String order){
<del>
<del>
<del>
<del>
<del> return null;
<del> }
<del>
<del> /**
<del> * Takes Object and String order as argument, for modification.
<del> */
<del> public void processOrder(JGObject object, String order){
<del>
<del> }
<del>
<del>
<add>
<add> return null;
<add> }
<add>
<add> private void parseOrder (String order) {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> /**
<add> * Takes Object and String order as argument, for modification.
<add> */
<add> public void processOrder(JGObject object, String order){
<add> parseOrder(order);
<add>
<add> try{
<add>// http://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html
<add>// http://java.sun.com/docs/books/tutorial/reflect/member/methodInvocation.html
<add>// http://docs.oracle.com/javase/tutorial/reflect/member/fieldValues.html
<add>// Object instance = Class.forName("Foobar").newInstance();
<add> Object behavior = Reflection.createInstance(myFormat.getString(myMoveMethod), this);
<add> Reflection.callMethod(behavior, "move", mySetXSpeed, mySetYSpeed);
<add> } catch (Exception e){
<add> e.printStackTrace(); //should never reach here
<add> }
<add>
<add> }
<add>
<add>
<ide>
<ide> } |
|
Java | apache-2.0 | b46c36ebcbb2de3ea2d6e5e522451ca58133dcb4 | 0 | ronsigal/xerces,jimma/xerces,jimma/xerces,RackerWilliams/xercesj,RackerWilliams/xercesj,ronsigal/xerces,ronsigal/xerces,jimma/xerces,RackerWilliams/xercesj | /*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000,2001 The Apache Software Foundation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.validators.schema;
import org.apache.xerces.framework.XMLErrorReporter;
import org.apache.xerces.validators.common.Grammar;
import org.apache.xerces.validators.common.GrammarResolver;
import org.apache.xerces.validators.common.GrammarResolverImpl;
import org.apache.xerces.validators.common.XMLElementDecl;
import org.apache.xerces.validators.common.XMLAttributeDecl;
import org.apache.xerces.validators.schema.SchemaSymbols;
import org.apache.xerces.validators.schema.XUtil;
import org.apache.xerces.validators.schema.identity.Field;
import org.apache.xerces.validators.schema.identity.IdentityConstraint;
import org.apache.xerces.validators.schema.identity.Key;
import org.apache.xerces.validators.schema.identity.KeyRef;
import org.apache.xerces.validators.schema.identity.Selector;
import org.apache.xerces.validators.schema.identity.Unique;
import org.apache.xerces.validators.schema.identity.XPath;
import org.apache.xerces.validators.schema.identity.XPathException;
import org.apache.xerces.validators.datatype.DatatypeValidator;
import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl;
import org.apache.xerces.validators.datatype.IDDatatypeValidator;
import org.apache.xerces.validators.datatype.NOTATIONDatatypeValidator;
import org.apache.xerces.validators.datatype.StringDatatypeValidator;
import org.apache.xerces.validators.datatype.ListDatatypeValidator;
import org.apache.xerces.validators.datatype.UnionDatatypeValidator;
import org.apache.xerces.validators.datatype.InvalidDatatypeValueException;
import org.apache.xerces.utils.StringPool;
import org.w3c.dom.Element;
import java.io.IOException;
import java.util.*;
import java.net.URL;
import java.net.MalformedURLException;
//REVISIT: for now, import everything in the DOM package
import org.w3c.dom.*;
//Unit Test
import org.apache.xerces.parsers.DOMParser;
import org.apache.xerces.validators.common.XMLValidator;
import org.apache.xerces.validators.datatype.DatatypeValidator.*;
import org.apache.xerces.validators.datatype.InvalidDatatypeValueException;
import org.apache.xerces.framework.XMLContentSpec;
import org.apache.xerces.utils.QName;
import org.apache.xerces.utils.NamespacesScope;
import org.apache.xerces.parsers.SAXParser;
import org.apache.xerces.framework.XMLParser;
import org.apache.xerces.framework.XMLDocumentScanner;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
/** Don't check the following code in because it creates a dependency on
the serializer, preventing to package the parser without the serializer.
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
**/
import org.apache.xerces.validators.schema.SchemaSymbols;
/**
* Instances of this class get delegated to Traverse the Schema and
* to populate the Grammar internal representation by
* instances of Grammar objects.
* Traverse a Schema Grammar:
*
* @author Eric Ye, IBM
* @author Jeffrey Rodriguez, IBM
* @author Andy Clark, IBM
*
* @see org.apache.xerces.validators.common.Grammar
*
* @version $Id$
*/
public class TraverseSchema implements
NamespacesScope.NamespacesHandler{
//CONSTANTS
private static final int TOP_LEVEL_SCOPE = -1;
/** Identity constraint keywords. */
private static final String[][] IDENTITY_CONSTRAINTS = {
{ SchemaSymbols.URI_SCHEMAFORSCHEMA, SchemaSymbols.ELT_UNIQUE },
{ SchemaSymbols.URI_SCHEMAFORSCHEMA, SchemaSymbols.ELT_KEY },
{ SchemaSymbols.URI_SCHEMAFORSCHEMA, SchemaSymbols.ELT_KEYREF },
};
private static final String redefIdentifier = "_redefined";
// Flags for handleOccurrences to indicate any special
// restrictions on minOccurs and maxOccurs relating to "all".
// NOT_ALL_CONTEXT - not processing an <all>
// PROCESSING_ALL - processing an <element> in an <all>
// GROUP_REF_WITH_ALL - processing <group> reference that contained <all>
// CHILD_OF_GROUP - processing a child of a model group definition
private static final int NOT_ALL_CONTEXT = 0;
private static final int PROCESSING_ALL = 1;
private static final int GROUP_REF_WITH_ALL = 2;
private static final int CHILD_OF_GROUP = 4;
//debugging
private static final boolean DEBUGGING = false;
/** Compile to true to debug identity constraints. */
private static final boolean DEBUG_IDENTITY_CONSTRAINTS = false;
/**
* Compile to true to debug datatype validator lookup for
* identity constraint support.
*/
private static final boolean DEBUG_IC_DATATYPES = false;
//private data members
private boolean fFullConstraintChecking = false;
private XMLErrorReporter fErrorReporter = null;
private StringPool fStringPool = null;
private GrammarResolver fGrammarResolver = null;
private SchemaGrammar fSchemaGrammar = null;
private Element fSchemaRootElement;
// this is always set to refer to the root of the linked list containing the root info of schemas under redefinition.
private SchemaInfo fSchemaInfoListRoot = null;
private SchemaInfo fCurrentSchemaInfo = null;
private boolean fRedefineSucceeded;
private DatatypeValidatorFactoryImpl fDatatypeRegistry = null;
private Hashtable fComplexTypeRegistry = new Hashtable();
private Hashtable fAttributeDeclRegistry = new Hashtable();
// stores the names of groups that we've traversed so we can avoid multiple traversals
// qualified group names are keys and their contentSpecIndexes are values.
private Hashtable fGroupNameRegistry = new Hashtable();
// this Hashtable keeps track of whether a given redefined group does so by restriction.
private Hashtable fRestrictedRedefinedGroupRegistry = new Hashtable();
// stores "final" values of simpleTypes--no clean way to integrate this into the existing datatype validation structure...
private Hashtable fSimpleTypeFinalRegistry = new Hashtable();
// stores <notation> decl
private Hashtable fNotationRegistry = new Hashtable();
private Vector fIncludeLocations = new Vector();
private Vector fImportLocations = new Vector();
private Hashtable fRedefineLocations = new Hashtable();
private Vector fTraversedRedefineElements = new Vector();
// Hashtable associating attributeGroups within a <redefine> which
// restrict attributeGroups in the original schema with the
// new name for those groups in the modified redefined schema.
private Hashtable fRedefineAttributeGroupMap = null;
// simpleType data
private Hashtable fFacetData = new Hashtable(10);
private Stack fSimpleTypeNameStack = new Stack();
private String fListName = "";
private int fAnonTypeCount =0;
private int fScopeCount=0;
private int fCurrentScope=TOP_LEVEL_SCOPE;
private int fSimpleTypeAnonCount = 0;
private Stack fCurrentTypeNameStack = new Stack();
private Stack fCurrentGroupNameStack = new Stack();
private Vector fElementRecurseComplex = new Vector();
private boolean fElementDefaultQualified = false;
private boolean fAttributeDefaultQualified = false;
private int fBlockDefault = 0;
private int fFinalDefault = 0;
private int fTargetNSURI;
private String fTargetNSURIString = "";
private NamespacesScope fNamespacesScope = null;
private String fCurrentSchemaURL = "";
private XMLAttributeDecl fTempAttributeDecl = new XMLAttributeDecl();
private XMLAttributeDecl fTemp2AttributeDecl = new XMLAttributeDecl();
private XMLElementDecl fTempElementDecl = new XMLElementDecl();
private XMLElementDecl fTempElementDecl2 = new XMLElementDecl();
private XMLContentSpec tempContentSpec1 = new XMLContentSpec();
private XMLContentSpec tempContentSpec2 = new XMLContentSpec();
private EntityResolver fEntityResolver = null;
private SubstitutionGroupComparator fSComp = null;
private Hashtable fIdentityConstraints = new Hashtable();
// Yet one more data structure; this one associates
// <unique> and <key> QNames with their corresponding objects,
// so that <keyRef>s can find them.
private Hashtable fIdentityConstraintNames = new Hashtable();
// General Attribute Checking
private GeneralAttrCheck fGeneralAttrCheck = null;
private int fXsiURI;
// REVISIT: maybe need to be moved into SchemaGrammar class
public class ComplexTypeInfo {
public String typeName;
public DatatypeValidator baseDataTypeValidator;
public ComplexTypeInfo baseComplexTypeInfo;
public int derivedBy = 0;
public int blockSet = 0;
public int finalSet = 0;
public int miscFlags=0;
public int scopeDefined = -1;
public int contentType;
public int contentSpecHandle = -1;
public int templateElementIndex = -1;
public int attlistHead = -1;
public DatatypeValidator datatypeValidator;
public boolean isAbstractType() {
return ((miscFlags & CT_IS_ABSTRACT)!=0);
}
public boolean containsAttrTypeID () {
return ((miscFlags & CT_CONTAINS_ATTR_TYPE_ID)!=0);
}
public boolean declSeen () {
return ((miscFlags & CT_DECL_SEEN)!=0);
}
public void setIsAbstractType() {
miscFlags |= CT_IS_ABSTRACT;
}
public void setContainsAttrTypeID() {
miscFlags |= CT_CONTAINS_ATTR_TYPE_ID;
}
public void setDeclSeen() {
miscFlags |= CT_DECL_SEEN;
}
}
private static final int CT_IS_ABSTRACT=1;
private static final int CT_CONTAINS_ATTR_TYPE_ID=2;
private static final int CT_DECL_SEEN=4; // indicates that the declaration was
// traversed as opposed to processed due
// to a forward reference
private class ComplexTypeRecoverableError extends Exception {
ComplexTypeRecoverableError() {super();}
ComplexTypeRecoverableError(String s) {super(s);}
}
private class ParticleRecoverableError extends Exception {
ParticleRecoverableError(String s) {super(s);}
}
private class ElementInfo {
int elementIndex;
String typeName;
private ElementInfo(int i, String name) {
elementIndex = i;
typeName = name;
}
}
//REVISIT: verify the URI.
public final static String SchemaForSchemaURI = "http://www.w3.org/TR-1/Schema";
private TraverseSchema( ) {
// new TraverseSchema() is forbidden;
}
public void setFullConstraintCheckingEnabled() {
fFullConstraintChecking = true;
}
public void setGrammarResolver(GrammarResolver grammarResolver){
fGrammarResolver = grammarResolver;
}
public void startNamespaceDeclScope(int prefix, int uri){
//TO DO
}
public void endNamespaceDeclScope(int prefix){
//TO DO, do we need to do anything here?
}
public boolean particleEmptiable(int contentSpecIndex) {
if (!fFullConstraintChecking) {
return true;
}
if (minEffectiveTotalRange(contentSpecIndex)==0)
return true;
else
return false;
}
public int minEffectiveTotalRange(int contentSpecIndex) {
fSchemaGrammar.getContentSpec(contentSpecIndex, tempContentSpec1);
int type = tempContentSpec1.type;
if (type == XMLContentSpec.CONTENTSPECNODE_SEQ ||
type == XMLContentSpec.CONTENTSPECNODE_ALL) {
return minEffectiveTotalRangeSeq(contentSpecIndex);
}
else if (type == XMLContentSpec.CONTENTSPECNODE_CHOICE) {
return minEffectiveTotalRangeChoice(contentSpecIndex);
}
else {
return(fSchemaGrammar.getContentSpecMinOccurs(contentSpecIndex));
}
}
private int minEffectiveTotalRangeSeq(int csIndex) {
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
int type = tempContentSpec1.type;
int left = tempContentSpec1.value;
int right = tempContentSpec1.otherValue;
int min = fSchemaGrammar.getContentSpecMinOccurs(csIndex);
int result;
if (right == -2)
result = min * minEffectiveTotalRange(left);
else
result = min * (minEffectiveTotalRange(left) + minEffectiveTotalRange(right));
return result;
}
private int minEffectiveTotalRangeChoice(int csIndex) {
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
int type = tempContentSpec1.type;
int left = tempContentSpec1.value;
int right = tempContentSpec1.otherValue;
int min = fSchemaGrammar.getContentSpecMinOccurs(csIndex);
int result;
if (right == -2)
result = min * minEffectiveTotalRange(left);
else {
int minLeft = minEffectiveTotalRange(left);
int minRight = minEffectiveTotalRange(right);
result = min * ((minLeft < minRight)?minLeft:minRight);
}
return result;
}
public int maxEffectiveTotalRange(int contentSpecIndex) {
fSchemaGrammar.getContentSpec(contentSpecIndex, tempContentSpec1);
int type = tempContentSpec1.type;
if (type == XMLContentSpec.CONTENTSPECNODE_SEQ ||
type == XMLContentSpec.CONTENTSPECNODE_ALL) {
return maxEffectiveTotalRangeSeq(contentSpecIndex);
}
else if (type == XMLContentSpec.CONTENTSPECNODE_CHOICE) {
return maxEffectiveTotalRangeChoice(contentSpecIndex);
}
else {
return(fSchemaGrammar.getContentSpecMaxOccurs(contentSpecIndex));
}
}
private int maxEffectiveTotalRangeSeq(int csIndex) {
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
int type = tempContentSpec1.type;
int left = tempContentSpec1.value;
int right = tempContentSpec1.otherValue;
int max = fSchemaGrammar.getContentSpecMaxOccurs(csIndex);
if (max == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
int maxLeft = maxEffectiveTotalRange(left);
if (right == -2) {
if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
else
return max * maxLeft;
}
else {
int maxRight = maxEffectiveTotalRange(right);
if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED ||
maxRight == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
else
return max * (maxLeft + maxRight);
}
}
private int maxEffectiveTotalRangeChoice(int csIndex) {
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
int type = tempContentSpec1.type;
int left = tempContentSpec1.value;
int right = tempContentSpec1.otherValue;
int max = fSchemaGrammar.getContentSpecMaxOccurs(csIndex);
if (max == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
int maxLeft = maxEffectiveTotalRange(left);
if (right == -2) {
if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
else
return max * maxLeft;
}
else {
int maxRight = maxEffectiveTotalRange(right);
if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED ||
maxRight == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
else
return max * ((maxLeft > maxRight)?maxLeft:maxRight);
}
}
private String resolvePrefixToURI (String prefix) throws Exception {
String uriStr = fStringPool.toString(fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix)));
if (uriStr.length() == 0 && prefix.length() > 0) {
// REVISIT: Localize
reportGenericSchemaError("prefix : [" + prefix +"] cannot be resolved to a URI");
return "";
}
//REVISIT, !!!! a hack: needs to be updated later, cause now we only use localpart to key build-in datatype.
if ( prefix.length()==0 && uriStr.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& fTargetNSURIString.length() == 0) {
uriStr = "";
}
return uriStr;
}
public TraverseSchema(Element root, StringPool stringPool,
SchemaGrammar schemaGrammar,
GrammarResolver grammarResolver,
XMLErrorReporter errorReporter,
String schemaURL,
EntityResolver entityResolver,
boolean fullChecking
) throws Exception {
fErrorReporter = errorReporter;
fCurrentSchemaURL = schemaURL;
fFullConstraintChecking = fullChecking;
fEntityResolver = entityResolver;
doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver);
}
public TraverseSchema(Element root, StringPool stringPool,
SchemaGrammar schemaGrammar,
GrammarResolver grammarResolver,
XMLErrorReporter errorReporter,
String schemaURL,
boolean fullChecking
) throws Exception {
fErrorReporter = errorReporter;
fCurrentSchemaURL = schemaURL;
fFullConstraintChecking = fullChecking;
doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver);
}
public TraverseSchema(Element root, StringPool stringPool,
SchemaGrammar schemaGrammar,
GrammarResolver grammarResolver,
boolean fullChecking
) throws Exception {
fFullConstraintChecking = fullChecking;
doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver);
}
public void doTraverseSchema(Element root, StringPool stringPool,
SchemaGrammar schemaGrammar,
GrammarResolver grammarResolver) throws Exception {
fNamespacesScope = new NamespacesScope(this);
fSchemaRootElement = root;
fStringPool = stringPool;
fSchemaGrammar = schemaGrammar;
if (fFullConstraintChecking) {
fSchemaGrammar.setDeferContentSpecExpansion();
fSchemaGrammar.setCheckUniqueParticleAttribution();
}
fGrammarResolver = grammarResolver;
fDatatypeRegistry = (DatatypeValidatorFactoryImpl) fGrammarResolver.getDatatypeRegistry();
//Expand to registry type to contain all primitive datatype
fDatatypeRegistry.expandRegistryToFullSchemaSet();
// General Attribute Checking
fGeneralAttrCheck = new GeneralAttrCheck(fErrorReporter);
fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI);
if (root == null) {
// REVISIT: Anything to do?
return;
}
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(root, scope);
//Make sure namespace binding is defaulted
String rootPrefix = root.getPrefix();
if( rootPrefix == null || rootPrefix.length() == 0 ){
String xmlns = root.getAttribute("xmlns");
if( xmlns.length() == 0 )
root.setAttribute("xmlns", SchemaSymbols.URI_SCHEMAFORSCHEMA );
}
//Retrieve the targetNamespace URI information
fTargetNSURIString = getTargetNamespaceString(root);
fTargetNSURI = fStringPool.addSymbol(fTargetNSURIString);
if (fGrammarResolver == null) {
// REVISIT: Localize
reportGenericSchemaError("Internal error: don't have a GrammarResolver for TraverseSchema");
}
else{
// for complex type registry, attribute decl registry and
// namespace mapping, needs to check whether the passed in
// Grammar was a newly instantiated one.
if (fSchemaGrammar.getComplexTypeRegistry() == null ) {
fSchemaGrammar.setComplexTypeRegistry(fComplexTypeRegistry);
}
else {
fComplexTypeRegistry = fSchemaGrammar.getComplexTypeRegistry();
}
if (fSchemaGrammar.getAttributeDeclRegistry() == null ) {
fSchemaGrammar.setAttributeDeclRegistry(fAttributeDeclRegistry);
}
else {
fAttributeDeclRegistry = fSchemaGrammar.getAttributeDeclRegistry();
}
if (fSchemaGrammar.getNamespacesScope() == null ) {
fSchemaGrammar.setNamespacesScope(fNamespacesScope);
}
else {
fNamespacesScope = fSchemaGrammar.getNamespacesScope();
}
fSchemaGrammar.setDatatypeRegistry(fDatatypeRegistry);
fSchemaGrammar.setTargetNamespaceURI(fTargetNSURIString);
fGrammarResolver.putGrammar(fTargetNSURIString, fSchemaGrammar);
}
// Retrived the Namespace mapping from the schema element.
NamedNodeMap schemaEltAttrs = root.getAttributes();
int i = 0;
Attr sattr = null;
boolean seenXMLNS = false;
while ((sattr = (Attr)schemaEltAttrs.item(i++)) != null) {
String attName = sattr.getName();
if (attName.startsWith("xmlns:")) {
String attValue = sattr.getValue();
String prefix = attName.substring(attName.indexOf(":")+1);
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(prefix),
fStringPool.addSymbol(attValue) );
}
if (attName.equals("xmlns")) {
String attValue = sattr.getValue();
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol(attValue) );
seenXMLNS = true;
}
}
if (!seenXMLNS && fTargetNSURIString.length() == 0 ) {
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol("") );
}
fElementDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ELEMENTFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
fAttributeDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ATTRIBUTEFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
Attr blockAttr = root.getAttributeNode(SchemaSymbols.ATT_BLOCKDEFAULT);
if (blockAttr == null)
fBlockDefault = 0;
else
fBlockDefault =
parseBlockSet(blockAttr.getValue());
Attr finalAttr = root.getAttributeNode(SchemaSymbols.ATT_FINALDEFAULT);
if (finalAttr == null)
fFinalDefault = 0;
else
fFinalDefault =
parseFinalSet(finalAttr.getValue());
//REVISIT, really sticky when noTargetNamesapce, for now, we assume everyting is in the same name space);
if (fTargetNSURI == StringPool.EMPTY_STRING) {
//fElementDefaultQualified = true;
//fAttributeDefaultQualified = true;
}
//fScopeCount++;
fCurrentScope = -1;
//extract all top-level attribute, attributeGroup, and group Decls and put them in the 3 hasn table in the SchemaGrammar.
extractTopLevel3Components(root);
// process <redefine>, <include> and <import> info items.
Element child = XUtil.getFirstChildElement(root);
for (; child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_INCLUDE)) {
fNamespacesScope.increaseDepth();
traverseInclude(child);
fNamespacesScope.decreaseDepth();
} else if (name.equals(SchemaSymbols.ELT_IMPORT)) {
traverseImport(child);
} else if (name.equals(SchemaSymbols.ELT_REDEFINE)) {
fRedefineSucceeded = true; // presume worked until proven failed.
traverseRedefine(child);
} else
break;
}
// child refers to the first info item which is not <annotation> or
// one of the schema inclusion/importation declarations.
for (; child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) {
traverseSimpleTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) {
traverseComplexTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ELEMENT )) {
traverseElementDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
traverseAttributeGroupDecl(child, null, null);
} else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) {
traverseAttributeDecl( child, null, false );
} else if (name.equals(SchemaSymbols.ELT_GROUP)) {
traverseGroupDecl(child);
} else if (name.equals(SchemaSymbols.ELT_NOTATION)) {
traverseNotationDecl(child); //TO DO
} else {
// REVISIT: Localize
reportGenericSchemaError("error in content of <schema> element information item");
}
} // for each child node
// handle identity constraints
// we must traverse <key>s and <unique>s before we tackel<keyref>s,
// since all have global scope and may be declared anywhere in the schema.
Enumeration elementIndexes = fIdentityConstraints.keys();
while (elementIndexes.hasMoreElements()) {
Integer elementIndexObj = (Integer)elementIndexes.nextElement();
if (DEBUG_IC_DATATYPES) {
System.out.println("<ICD>: traversing identity constraints for element: "+elementIndexObj);
}
Vector identityConstraints = (Vector)fIdentityConstraints.get(elementIndexObj);
if (identityConstraints != null) {
int elementIndex = elementIndexObj.intValue();
traverseIdentityNameConstraintsFor(elementIndex, identityConstraints);
}
}
elementIndexes = fIdentityConstraints.keys();
while (elementIndexes.hasMoreElements()) {
Integer elementIndexObj = (Integer)elementIndexes.nextElement();
if (DEBUG_IC_DATATYPES) {
System.out.println("<ICD>: traversing identity constraints for element: "+elementIndexObj);
}
Vector identityConstraints = (Vector)fIdentityConstraints.get(elementIndexObj);
if (identityConstraints != null) {
int elementIndex = elementIndexObj.intValue();
traverseIdentityRefConstraintsFor(elementIndex, identityConstraints);
}
}
// General Attribute Checking
fGeneralAttrCheck = null;
} // traverseSchema(Element)
private void extractTopLevel3Components(Element root) throws Exception {
for (Element child = XUtil.getFirstChildElement(root); child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
String compName = child.getAttribute(SchemaSymbols.ATT_NAME);
if (name.equals(SchemaSymbols.ELT_ELEMENT)) {
// Check if the element has already been declared
if (fSchemaGrammar.topLevelElemDecls.get(compName) != null) {
reportGenericSchemaError("sch-props-correct: Duplicate declaration for an element " +
compName);
}
else {
fSchemaGrammar.topLevelElemDecls.put(compName, child);
}
}
else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE) ||
name.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
// Check for dublicate declaration
if (fSchemaGrammar.topLevelTypeDecls.get(compName) != null) {
reportGenericSchemaError("sch-props-correct: Duplicate declaration for a type " +
compName);
}
else {
fSchemaGrammar.topLevelTypeDecls.put(compName, child);
}
}
else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
// Check for dublicate declaration
if (fSchemaGrammar.topLevelAttrGrpDecls.get(compName) != null) {
reportGenericSchemaError("sch-props-correct: Duplicate declaration for an attribute group " +
compName);
}
else {
fSchemaGrammar.topLevelAttrGrpDecls.put(compName, child);
}
} else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) {
// Check for dublicate declaration
if (fSchemaGrammar.topLevelAttrGrpDecls.get(compName) != null) {
reportGenericSchemaError("sch-props-correct: Duplicate declaration for an attribute " +
compName);
}
else {
fSchemaGrammar.topLevelAttrGrpDecls.put(compName, child);
}
} else if ( name.equals(SchemaSymbols.ELT_GROUP) ) {
// Check if the group has already been declared
if (fSchemaGrammar.topLevelGroupDecls.get(compName) != null){
reportGenericSchemaError("sch-props-correct: Duplicate declaration for a group " +
compName);
}
else {
fSchemaGrammar.topLevelGroupDecls.put(compName, child);
}
} else if ( name.equals(SchemaSymbols.ELT_NOTATION) ) {
// Check for dublicate declaration
if (fSchemaGrammar.topLevelNotationDecls.get(compName) != null) {
reportGenericSchemaError("sch-props-correct: Duplicate declaration for a notation " +
compName);
}
else {
fSchemaGrammar.topLevelNotationDecls.put(compName, child);
}
}
} // for each child node
}
/**
* Expands a system id and returns the system id as a URL, if
* it can be expanded. A return value of null means that the
* identifier is already expanded. An exception thrown
* indicates a failure to expand the id.
*
* @param systemId The systemId to be expanded.
*
* @return Returns the URL object representing the expanded system
* identifier. A null value indicates that the given
* system identifier is already expanded.
*
*/
private String expandSystemId(String systemId, String currentSystemId) throws Exception{
String id = systemId;
// check for bad parameters id
if (id == null || id.length() == 0) {
return systemId;
}
// if id already expanded, return
try {
URL url = new URL(id);
if (url != null) {
return systemId;
}
}
catch (MalformedURLException e) {
// continue on...
}
// normalize id
id = fixURI(id);
// normalize base
URL base = null;
URL url = null;
try {
if (currentSystemId == null) {
String dir;
try {
dir = fixURI(System.getProperty("user.dir"));
}
catch (SecurityException se) {
dir = "";
}
if (!dir.endsWith("/")) {
dir = dir + "/";
}
base = new URL("file", "", dir);
}
else {
base = new URL(currentSystemId);
}
// expand id
url = new URL(base, id);
}
catch (Exception e) {
// let it go through
}
if (url == null) {
return systemId;
}
return url.toString();
}
/**
* Fixes a platform dependent filename to standard URI form.
*
* @param str The string to fix.
*
* @return Returns the fixed URI string.
*/
private static String fixURI(String str) {
// handle platform dependent strings
str = str.replace(java.io.File.separatorChar, '/');
// Windows fix
if (str.length() >= 2) {
char ch1 = str.charAt(1);
if (ch1 == ':') {
char ch0 = Character.toUpperCase(str.charAt(0));
if (ch0 >= 'A' && ch0 <= 'Z') {
str = "/" + str;
}
}
}
// done
return str;
}
private void traverseInclude(Element includeDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(includeDecl, scope);
checkContent(includeDecl, XUtil.getFirstChildElement(includeDecl), true);
Attr locationAttr = includeDecl.getAttributeNode(SchemaSymbols.ATT_SCHEMALOCATION);
if (locationAttr == null) {
// REVISIT: Localize
reportGenericSchemaError("a schemaLocation attribute must be specified on an <include> element");
return;
}
String location = locationAttr.getValue();
// expand it before passing it to the parser
InputSource source = null;
if (fEntityResolver != null) {
source = fEntityResolver.resolveEntity("", location);
}
if (source == null) {
location = expandSystemId(location, fCurrentSchemaURL);
source = new InputSource(location);
}
else {
// create a string for uniqueness of this included schema in fIncludeLocations
if (source.getPublicId () != null)
location = source.getPublicId ();
location += (',' + source.getSystemId ());
}
if (fIncludeLocations.contains((Object)location)) {
return;
}
fIncludeLocations.addElement((Object)location);
DOMParser parser = new IgnoreWhitespaceParser();
parser.setEntityResolver( new Resolver() );
parser.setErrorHandler( new ErrorHandler()
{
public void fatalError(SAXParseException ex) throws SAXException {
StringBuffer str = new StringBuffer();
String systemId_ = ex.getSystemId();
if (systemId_ != null) {
int index = systemId_.lastIndexOf('/');
if (index != -1)
systemId_ = systemId_.substring(index + 1);
str.append(systemId_);
}
str.append(':').append(ex.getLineNumber()).append(':').append(ex.getColumnNumber());
String message = ex.getMessage();
if(message.toLowerCase().trim().endsWith("not found.")) {
System.err.println("[Warning] "+
str.toString()+": "+ message);
} else { // do standard thing
System.err.println("[Fatal Error] "+
str.toString()+":"+message);
throw ex;
}
}
});
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}catch( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
}catch( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
try {
parser.parse( source );
}catch( IOException e ) {
e.printStackTrace();
}catch( SAXException e ) {
//e.printStackTrace();
}
Document document = parser.getDocument(); //Our Grammar
Element root = null;
if (document != null) {
root = document.getDocumentElement();
}
if (root != null) {
String targetNSURI = getTargetNamespaceString(root);
if (targetNSURI.length() > 0 && !targetNSURI.equals(fTargetNSURIString) ) {
// REVISIT: Localize
reportGenericSchemaError("included schema '"+location+"' has a different targetNameSpace '"
+targetNSURI+"'");
}
else {
// We not creating another TraverseSchema object to compile
// the included schema file, because the scope count, anon-type count
// should not be reset for a included schema, this can be fixed by saving
// the counters in the Schema Grammar,
if (fSchemaInfoListRoot == null) {
fSchemaInfoListRoot = new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified,
fBlockDefault, fFinalDefault,
fCurrentScope, fCurrentSchemaURL, fSchemaRootElement,
fNamespacesScope, null, null);
fCurrentSchemaInfo = fSchemaInfoListRoot;
}
fSchemaRootElement = root;
fCurrentSchemaURL = location;
traverseIncludedSchemaHeader(root);
// and now we'd better save this stuff!
fCurrentSchemaInfo = new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified,
fBlockDefault, fFinalDefault,
fCurrentScope, fCurrentSchemaURL, fSchemaRootElement,
fNamespacesScope, fCurrentSchemaInfo.getNext(), fCurrentSchemaInfo);
(fCurrentSchemaInfo.getPrev()).setNext(fCurrentSchemaInfo);
traverseIncludedSchema(root);
// there must always be a previous element!
fCurrentSchemaInfo = fCurrentSchemaInfo.getPrev();
fCurrentSchemaInfo.restore();
}
}
}
private void traverseIncludedSchemaHeader(Element root) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(root, scope);
// Retrieved the Namespace mapping from the schema element.
NamedNodeMap schemaEltAttrs = root.getAttributes();
int i = 0;
Attr sattr = null;
boolean seenXMLNS = false;
while ((sattr = (Attr)schemaEltAttrs.item(i++)) != null) {
String attName = sattr.getName();
if (attName.startsWith("xmlns:")) {
String attValue = sattr.getValue();
String prefix = attName.substring(attName.indexOf(":")+1);
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(prefix),
fStringPool.addSymbol(attValue) );
}
if (attName.equals("xmlns")) {
String attValue = sattr.getValue();
fNamespacesScope.setNamespaceForPrefix( StringPool.EMPTY_STRING,
fStringPool.addSymbol(attValue) );
seenXMLNS = true;
}
}
if (!seenXMLNS && fTargetNSURIString.length() == 0 ) {
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol("") );
}
fElementDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ELEMENTFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
fAttributeDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ATTRIBUTEFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
Attr blockAttr = root.getAttributeNode(SchemaSymbols.ATT_BLOCKDEFAULT);
if (blockAttr == null)
fBlockDefault = 0;
else
fBlockDefault =
parseBlockSet(blockAttr.getValue());
Attr finalAttr = root.getAttributeNode(SchemaSymbols.ATT_FINALDEFAULT);
if (finalAttr == null)
fFinalDefault = 0;
else
fFinalDefault =
parseFinalSet(finalAttr.getValue());
//REVISIT, really sticky when noTargetNamesapce, for now, we assume everyting is in the same name space);
if (fTargetNSURI == StringPool.EMPTY_STRING) {
fElementDefaultQualified = true;
//fAttributeDefaultQualified = true;
}
//fScopeCount++;
fCurrentScope = -1;
} // traverseIncludedSchemaHeader
private void traverseIncludedSchema(Element root) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(root, scope);
//extract all top-level attribute, attributeGroup, and group Decls and put them in the 3 hasn table in the SchemaGrammar.
extractTopLevel3Components(root);
// handle <redefine>, <include> and <import> elements.
Element child = XUtil.getFirstChildElement(root);
for (; child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_INCLUDE)) {
fNamespacesScope.increaseDepth();
traverseInclude(child);
fNamespacesScope.decreaseDepth();
} else if (name.equals(SchemaSymbols.ELT_IMPORT)) {
traverseImport(child);
} else if (name.equals(SchemaSymbols.ELT_REDEFINE)) {
fRedefineSucceeded = true; // presume worked until proven failed.
traverseRedefine(child);
} else
break;
}
// handle the rest of the schema elements.
// BEWARE! this method gets called both from traverseRedefine and
// traverseInclude; the preconditions (especially with respect to
// groups and attributeGroups) are different!
for (; child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) {
traverseSimpleTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) {
traverseComplexTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ELEMENT )) {
traverseElementDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
if(fRedefineAttributeGroupMap != null) {
String dName = child.getAttribute(SchemaSymbols.ATT_NAME);
String bName = (String)fRedefineAttributeGroupMap.get(dName);
if(bName != null) {
child.setAttribute(SchemaSymbols.ATT_NAME, bName);
// and make sure we wipe this out of the grammar!
fSchemaGrammar.topLevelAttrGrpDecls.remove(dName);
// Now we reuse this location in the array to store info we'll need for validation...
ComplexTypeInfo typeInfo = new ComplexTypeInfo();
int templateElementNameIndex = fStringPool.addSymbol("$"+bName);
int typeNameIndex = fStringPool.addSymbol("%"+bName);
typeInfo.scopeDefined = -2;
typeInfo.contentSpecHandle = -1;
typeInfo.contentType = XMLElementDecl.TYPE_SIMPLE;
typeInfo.datatypeValidator = null;
typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(
new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI),
(fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : -2, typeInfo.scopeDefined,
typeInfo.contentType,
typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator);
Vector anyAttDecls = new Vector();
// need to determine how to initialize these babies; then
// on the <redefine> traversing end, try
// and cast the hash value into the right form;
// failure indicates nothing to redefine; success
// means we can feed checkAttribute... what it needs...
traverseAttributeGroupDecl(child, typeInfo, anyAttDecls);
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(
typeInfo.templateElementIndex);
fRedefineAttributeGroupMap.put(dName, new Object []{typeInfo, fSchemaGrammar, anyAttDecls});
continue;
}
}
traverseAttributeGroupDecl(child, null, null);
// fSchemaGrammar.topLevelAttrGrpDecls.remove(child.getAttribute("name"));
} else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) {
traverseAttributeDecl( child, null , false);
} else if (name.equals(SchemaSymbols.ELT_GROUP)) {
String dName = child.getAttribute(SchemaSymbols.ATT_NAME);
if(fGroupNameRegistry.get(fTargetNSURIString + ","+dName) == null) {
// we've been renamed already
traverseGroupDecl(child);
continue;
}
// if we're here: must have been a restriction.
// we have yet to be renamed.
try {
Integer i = (Integer)fGroupNameRegistry.get(fTargetNSURIString + ","+dName);
// if that succeeded then we're done; were ref'd here in
// an include most likely.
continue;
} catch (ClassCastException c) {
String s = (String)fGroupNameRegistry.get(fTargetNSURIString + ","+dName);
if (s == null) continue; // must have seen this already--somehow...
};
String bName = (String)fGroupNameRegistry.get(fTargetNSURIString +"," + dName);
if(bName != null) {
child.setAttribute(SchemaSymbols.ATT_NAME, bName);
// Now we reuse this location in the array to store info we'll need for validation...
// note that traverseGroupDecl will happily do that for us!
}
traverseGroupDecl(child);
} else if (name.equals(SchemaSymbols.ELT_NOTATION)) {
traverseNotationDecl(child);
} else {
// REVISIT: Localize
reportGenericSchemaError("error in content of included <schema> element information item");
}
} // for each child node
}
// This method's job is to open a redefined schema and store away its root element, defaultElementQualified and other
// such info, in order that it can be available when redefinition actually takes place.
// It assumes that it will be called from the schema doing the redefining, and it assumes
// that the other schema's info has already been saved, putting the info it finds into the
// SchemaInfoList element that is passed in.
private void openRedefinedSchema(Element redefineDecl, SchemaInfo store) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(redefineDecl, scope);
Attr locationAttr = redefineDecl.getAttributeNode(SchemaSymbols.ATT_SCHEMALOCATION);
if (locationAttr == null) {
// REVISIT: Localize
fRedefineSucceeded = false;
reportGenericSchemaError("a schemaLocation attribute must be specified on a <redefine> element");
return;
}
String location = locationAttr.getValue();
// expand it before passing it to the parser
InputSource source = null;
if (fEntityResolver != null) {
source = fEntityResolver.resolveEntity("", location);
}
if (source == null) {
location = expandSystemId(location, fCurrentSchemaURL);
source = new InputSource(location);
}
else {
// Make sure we don't redefine the same schema twice; it's allowed
// but the specs encourage us to avoid it.
if (source.getPublicId () != null)
location = source.getPublicId ();
// make sure we're not redefining ourselves!
if(source.getSystemId().equals(fCurrentSchemaURL)) {
// REVISIT: localize
reportGenericSchemaError("src-redefine.2: a schema cannot redefine itself");
fRedefineSucceeded = false;
return;
}
location += (',' + source.getSystemId ());
}
if (fRedefineLocations.get((Object)location) != null) {
// then we'd better make sure we're directed at that schema...
fCurrentSchemaInfo = (SchemaInfo)(fRedefineLocations.get((Object)location));
fCurrentSchemaInfo.restore();
return;
}
DOMParser parser = new IgnoreWhitespaceParser();
parser.setEntityResolver( new Resolver() );
parser.setErrorHandler( new ErrorHandler() );
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}catch( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
}catch( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
try {
parser.parse( source );
}catch( IOException e ) {
e.printStackTrace();
}catch( SAXException e ) {
//e.printStackTrace();
}
Document document = parser.getDocument(); //Our Grammar to be redefined
Element root = null;
if (document != null) {
root = document.getDocumentElement();
}
if (root == null) { // nothing to be redefined, so just continue; specs disallow an error here.
fRedefineSucceeded = false;
return;
}
// now if root isn't null, it'll contain the root of the schema we need to redefine.
// We do this in two phases: first, we look through the children of
// redefineDecl. Each one will correspond to an element of the
// redefined schema that we need to redefine. To do this, we rename the
// element of the redefined schema, and rework the base or ref tag of
// the kid we're working on to refer to the renamed group or derive the
// renamed type. Once we've done this, we actually go through the
// schema being redefined and convert it to a grammar. Only then do we
// run through redefineDecl's kids and put them in the grammar.
//
// This approach is kosher with the specs. It does raise interesting
// questions about error reporting, and perhaps also about grammar
// access, but it is comparatively efficient (we need make at most
// only 2 traversals of any given information item) and moreover
// we can use existing code to build the grammar structures once the
// first pass is out of the way, so this should be quite robust.
// check to see if the targetNameSpace is right
String redefinedTargetNSURIString = getTargetNamespaceString(root);
if (redefinedTargetNSURIString.length() > 0 && !redefinedTargetNSURIString.equals(fTargetNSURIString) ) {
// REVISIT: Localize
fRedefineSucceeded = false;
reportGenericSchemaError("redefined schema '"+location+"' has a different targetNameSpace '"
+redefinedTargetNSURIString+"' from the original schema");
}
else {
// targetNamespace is right, so let's do the renaming...
// and let's keep in mind that the targetNamespace of the redefined
// elements is that of the redefined schema!
fSchemaRootElement = root;
fCurrentSchemaURL = location;
fNamespacesScope = new NamespacesScope(this);
if((redefinedTargetNSURIString.length() == 0) && (root.getAttributeNode("xmlns") == null)) {
fNamespacesScope.setNamespaceForPrefix(StringPool.EMPTY_STRING, fTargetNSURI);
} else {
}
// get default form xmlns bindings et al.
traverseIncludedSchemaHeader(root);
// and then save them...
store.setNext(new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified,
fBlockDefault, fFinalDefault,
fCurrentScope, fCurrentSchemaURL, fSchemaRootElement,
fNamespacesScope, null, store));
(store.getNext()).setPrev(store);
fCurrentSchemaInfo = store.getNext();
fRedefineLocations.put((Object)location, store.getNext());
} // end if
} // end openRedefinedSchema
/****
* <redefine
* schemaLocation = uriReference
* {any attributes with non-schema namespace . . .}>
* Content: (annotation | (
* attributeGroup | complexType | group | simpleType))*
* </redefine>
*/
private void traverseRedefine(Element redefineDecl) throws Exception {
// initialize storage areas...
fRedefineAttributeGroupMap = new Hashtable();
NamespacesScope saveNSScope = (NamespacesScope)fNamespacesScope.clone();
// only case in which need to save contents is when fSchemaInfoListRoot is null; otherwise we'll have
// done this already one way or another.
if (fSchemaInfoListRoot == null) {
fSchemaInfoListRoot = new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified,
fBlockDefault, fFinalDefault,
fCurrentScope, fCurrentSchemaURL, fSchemaRootElement,
fNamespacesScope, null, null);
openRedefinedSchema(redefineDecl, fSchemaInfoListRoot);
if(!fRedefineSucceeded)
return;
fCurrentSchemaInfo = fSchemaInfoListRoot.getNext();
fNamespacesScope = (NamespacesScope)saveNSScope.clone();
renameRedefinedComponents(redefineDecl,fSchemaInfoListRoot.getNext().getRoot(), fSchemaInfoListRoot.getNext());
} else {
// may have a chain here; need to be wary!
SchemaInfo curr = fSchemaInfoListRoot;
for(; curr.getNext() != null; curr = curr.getNext());
fCurrentSchemaInfo = curr;
fCurrentSchemaInfo.restore();
openRedefinedSchema(redefineDecl, fCurrentSchemaInfo);
if(!fRedefineSucceeded)
return;
fNamespacesScope = (NamespacesScope)saveNSScope.clone();
renameRedefinedComponents(redefineDecl,fCurrentSchemaInfo.getRoot(), fCurrentSchemaInfo);
}
// Now we have to march through our nicely-renamed schemas from the
// bottom up. When we do these traversals other <redefine>'s may
// perhaps be encountered; we leave recursion to sort this out.
fCurrentSchemaInfo.restore();
traverseIncludedSchema(fSchemaRootElement);
fNamespacesScope = (NamespacesScope)saveNSScope.clone();
// and last but not least: traverse our own <redefine>--the one all
// this labour has been expended upon.
for (Element child = XUtil.getFirstChildElement(redefineDecl); child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
// annotations can occur anywhere in <redefine>s!
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) {
traverseSimpleTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) {
traverseComplexTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_GROUP)) {
String dName = child.getAttribute(SchemaSymbols.ATT_NAME);
if(fGroupNameRegistry.get(fTargetNSURIString +","+ dName) == null ||
((fRestrictedRedefinedGroupRegistry.get(fTargetNSURIString+","+dName) != null) &&
!((Boolean)fRestrictedRedefinedGroupRegistry.get(fTargetNSURIString+","+dName)).booleanValue())) { // extension!
traverseGroupDecl(child);
continue;
}
traverseGroupDecl(child);
Integer bCSIndexObj = null;
try {
bCSIndexObj = (Integer)fGroupNameRegistry.get(fTargetNSURIString +","+ dName+redefIdentifier);
} catch(ClassCastException c) {
// if it's still a String, then we mustn't have found a corresponding attributeGroup in the redefined schema.
// REVISIT: localize
reportGenericSchemaError("src-redefine.6.2: a <group> within a <redefine> must either have a ref to a <group> with the same name or must restrict such an <group>");
continue;
}
if(bCSIndexObj != null) { // we have something!
int bCSIndex = bCSIndexObj.intValue();
Integer dCSIndexObj;
try {
dCSIndexObj = (Integer)fGroupNameRegistry.get(fTargetNSURIString+","+dName);
} catch (ClassCastException c) {
continue;
}
if(dCSIndexObj == null) // something went wrong...
continue;
int dCSIndex = dCSIndexObj.intValue();
try {
checkParticleDerivationOK(dCSIndex, -1, bCSIndex, -1, null);
}
catch (ParticleRecoverableError e) {
reportGenericSchemaError(e.getMessage());
}
} else
// REVISIT: localize
reportGenericSchemaError("src-redefine.6.2: a <group> within a <redefine> must either have a ref to a <group> with the same name or must restrict such an <group>");
} else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
if(fRedefineAttributeGroupMap != null) {
String dName = child.getAttribute(SchemaSymbols.ATT_NAME);
Object [] bAttGrpStore = null;
try {
bAttGrpStore = (Object [])fRedefineAttributeGroupMap.get(dName);
} catch(ClassCastException c) {
// if it's still a String, then we mustn't have found a corresponding attributeGroup in the redefined schema.
// REVISIT: localize
reportGenericSchemaError("src-redefine.7.2: an <attributeGroup> within a <redefine> must either have a ref to an <attributeGroup> with the same name or must restrict such an <attributeGroup>");
continue;
}
if(bAttGrpStore != null) { // we have something!
ComplexTypeInfo bTypeInfo = (ComplexTypeInfo)bAttGrpStore[0];
SchemaGrammar bSchemaGrammar = (SchemaGrammar)bAttGrpStore[1];
Vector bAnyAttDecls = (Vector)bAttGrpStore[2];
XMLAttributeDecl bAnyAttDecl =
(bAnyAttDecls.size()>0 )? (XMLAttributeDecl)bAnyAttDecls.elementAt(0):null;
ComplexTypeInfo dTypeInfo = new ComplexTypeInfo();
int templateElementNameIndex = fStringPool.addSymbol("$"+dName);
int dTypeNameIndex = fStringPool.addSymbol("%"+dName);
dTypeInfo.scopeDefined = -2;
dTypeInfo.contentSpecHandle = -1;
dTypeInfo.contentType = XMLElementDecl.TYPE_SIMPLE;
dTypeInfo.datatypeValidator = null;
dTypeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(
new QName(-1, templateElementNameIndex,dTypeNameIndex,fTargetNSURI),
(fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : -2, dTypeInfo.scopeDefined,
dTypeInfo.contentType,
dTypeInfo.contentSpecHandle, -1, dTypeInfo.datatypeValidator);
Vector dAnyAttDecls = new Vector();
XMLAttributeDecl dAnyAttDecl =
(dAnyAttDecls.size()>0 )? (XMLAttributeDecl)dAnyAttDecls.elementAt(0):null;
traverseAttributeGroupDecl(child, dTypeInfo, dAnyAttDecls);
dTypeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(
dTypeInfo.templateElementIndex);
try {
checkAttributesDerivationOKRestriction(dTypeInfo.attlistHead,fSchemaGrammar,
dAnyAttDecl,bTypeInfo.attlistHead,bSchemaGrammar,bAnyAttDecl);
}
catch (ComplexTypeRecoverableError e) {
String message = e.getMessage();
reportGenericSchemaError("src-redefine.7.2: redefinition failed because of " + message);
}
continue;
}
}
traverseAttributeGroupDecl(child, null, null);
} // no else; error reported in the previous traversal
} //for
// and restore the original globals
fCurrentSchemaInfo = fCurrentSchemaInfo.getPrev();
fCurrentSchemaInfo.restore();
} // traverseRedefine
// the purpose of this method is twofold: 1. To find and appropriately modify all information items
// in redefinedSchema with names that are redefined by children of
// redefineDecl. 2. To make sure the redefine element represented by
// redefineDecl is valid as far as content goes and with regard to
// properly referencing components to be redefined. No traversing is done here!
// This method also takes actions to find and, if necessary, modify the names
// of elements in <redefine>'s in the schema that's being redefined.
private void renameRedefinedComponents(Element redefineDecl, Element schemaToRedefine, SchemaInfo currSchemaInfo) throws Exception {
for (Element child = XUtil.getFirstChildElement(redefineDecl);
child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) )
continue;
else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
String typeName = child.getAttribute( SchemaSymbols.ATT_NAME );
if(fTraversedRedefineElements.contains(typeName))
continue;
if(validateRedefineNameChange(SchemaSymbols.ELT_SIMPLETYPE, typeName, typeName+redefIdentifier, child)) {
fixRedefinedSchema(SchemaSymbols.ELT_SIMPLETYPE,
typeName, typeName+redefIdentifier,
schemaToRedefine, currSchemaInfo);
}
} else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
String typeName = child.getAttribute( SchemaSymbols.ATT_NAME );
if(fTraversedRedefineElements.contains(typeName))
continue;
if(validateRedefineNameChange(SchemaSymbols.ELT_COMPLEXTYPE, typeName, typeName+redefIdentifier, child)) {
fixRedefinedSchema(SchemaSymbols.ELT_COMPLEXTYPE,
typeName, typeName+redefIdentifier,
schemaToRedefine, currSchemaInfo);
}
} else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
String baseName = child.getAttribute( SchemaSymbols.ATT_NAME );
if(fTraversedRedefineElements.contains(baseName))
continue;
if(validateRedefineNameChange(SchemaSymbols.ELT_ATTRIBUTEGROUP, baseName, baseName+redefIdentifier, child)) {
fixRedefinedSchema(SchemaSymbols.ELT_ATTRIBUTEGROUP,
baseName, baseName+redefIdentifier,
schemaToRedefine, currSchemaInfo);
}
} else if (name.equals(SchemaSymbols.ELT_GROUP)) {
String baseName = child.getAttribute( SchemaSymbols.ATT_NAME );
if(fTraversedRedefineElements.contains(baseName))
continue;
if(validateRedefineNameChange(SchemaSymbols.ELT_GROUP, baseName, baseName+redefIdentifier, child)) {
fixRedefinedSchema(SchemaSymbols.ELT_GROUP,
baseName, baseName+redefIdentifier,
schemaToRedefine, currSchemaInfo);
}
} else {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("invalid top-level content for <redefine>");
return;
}
} // for
} // renameRedefinedComponents
// This function looks among the children of curr for an element of type elementSought.
// If it finds one, it evaluates whether its ref attribute contains a reference
// to originalName. If it does, it returns 1 + the value returned by
// calls to itself on all other children. In all other cases it returns 0 plus
// the sum of the values returned by calls to itself on curr's children.
// It also resets the value of ref so that it will refer to the renamed type from the schema
// being redefined.
private int changeRedefineGroup(QName originalName, String elementSought, String newName, Element curr) throws Exception {
int result = 0;
for (Element child = XUtil.getFirstChildElement(curr);
child != null; child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (!name.equals(elementSought))
result += changeRedefineGroup(originalName, elementSought, newName, child);
else {
String ref = child.getAttribute( SchemaSymbols.ATT_REF );
if (!ref.equals("")) {
String prefix = "";
String localpart = ref;
int colonptr = ref.indexOf(":");
if ( colonptr > 0) {
prefix = ref.substring(0,colonptr);
localpart = ref.substring(colonptr+1);
}
String uriStr = resolvePrefixToURI(prefix);
if(originalName.equals(new QName(-1, fStringPool.addSymbol(localpart), fStringPool.addSymbol(localpart), fStringPool.addSymbol(uriStr)))) {
if(prefix.equals(""))
child.setAttribute(SchemaSymbols.ATT_REF, newName);
else
child.setAttribute(SchemaSymbols.ATT_REF, prefix + ":" + newName);
result++;
if(elementSought.equals(SchemaSymbols.ELT_GROUP)) {
String minOccurs = child.getAttribute( SchemaSymbols.ATT_MINOCCURS );
String maxOccurs = child.getAttribute( SchemaSymbols.ATT_MAXOCCURS );
if(!((maxOccurs.length() == 0 || maxOccurs.equals("1"))
&& (minOccurs.length() == 0 || minOccurs.equals("1")))) {
//REVISIT: localize
reportGenericSchemaError("src-redefine.6.1.2: the group " + ref + " which contains a reference to a group being redefined must have minOccurs = maxOccurs = 1");
}
}
}
} // if ref was null some other stage of processing will flag the error
}
}
return result;
} // changeRedefineGroup
// This simple function looks for the first occurrence of an eltLocalname
// schema information item and appropriately changes the value of
// its name or type attribute from oldName to newName.
// Root contains the root of the schema being operated upon.
// If it turns out that what we're looking for is in a <redefine> though, then we
// just rename it--and it's reference--to be the same and wait until
// renameRedefineDecls can get its hands on it and do it properly.
private void fixRedefinedSchema(String eltLocalname, String oldName, String newName, Element schemaToRedefine,
SchemaInfo currSchema) throws Exception {
boolean foundIt = false;
for (Element child = XUtil.getFirstChildElement(schemaToRedefine);
child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if(name.equals(SchemaSymbols.ELT_REDEFINE)) { // need to search the redefine decl...
for (Element redefChild = XUtil.getFirstChildElement(child);
redefChild != null;
redefChild = XUtil.getNextSiblingElement(redefChild)) {
String redefName = redefChild.getLocalName();
if (redefName.equals(eltLocalname) ) {
String infoItemName = redefChild.getAttribute( SchemaSymbols.ATT_NAME );
if(!infoItemName.equals(oldName))
continue;
else { // found it!
foundIt = true;
openRedefinedSchema(child, currSchema);
if(!fRedefineSucceeded)
return;
NamespacesScope saveNSS = (NamespacesScope)fNamespacesScope.clone();
currSchema.restore();
if (validateRedefineNameChange(eltLocalname, oldName, newName+redefIdentifier, redefChild) &&
(currSchema.getNext() != null)) {
currSchema.getNext().restore();
fixRedefinedSchema(eltLocalname, oldName, newName+redefIdentifier, fSchemaRootElement, currSchema.getNext());
}
fNamespacesScope = saveNSS;
redefChild.setAttribute( SchemaSymbols.ATT_NAME, newName );
// and we now know we will traverse this, so set fTraversedRedefineElements appropriately...
fTraversedRedefineElements.addElement(newName);
currSchema.restore();
fCurrentSchemaInfo = currSchema;
break;
}
}
} //for
if (foundIt) break;
}
else if (name.equals(eltLocalname) ) {
String infoItemName = child.getAttribute( SchemaSymbols.ATT_NAME );
if(!infoItemName.equals(oldName))
continue;
else { // found it!
foundIt = true;
child.setAttribute( SchemaSymbols.ATT_NAME, newName );
break;
}
}
} //for
if(!foundIt) {
fRedefineSucceeded = false;
// REVISIT: localize
reportGenericSchemaError("could not find a declaration in the schema to be redefined corresponding to " + oldName);
}
} // end fixRedefinedSchema
// this method returns true if the redefine component is valid, and if
// it was possible to revise it correctly. The definition of
// correctly will depend on whether renameRedefineDecls
// or fixRedefineSchema is the caller.
// this method also prepends a prefix onto newName if necessary; newName will never contain one.
private boolean validateRedefineNameChange(String eltLocalname, String oldName, String newName, Element child) throws Exception {
if (eltLocalname.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
QName processedTypeName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI);
Element grandKid = XUtil.getFirstChildElement(child);
if (grandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a simpleType child of a <redefine> must have a restriction element as a child");
} else {
String grandKidName = grandKid.getLocalName();
if(grandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) {
grandKid = XUtil.getNextSiblingElement(grandKid);
grandKidName = grandKid.getLocalName();
}
if (grandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a simpleType child of a <redefine> must have a restriction element as a child");
} else if(!grandKidName.equals(SchemaSymbols.ELT_RESTRICTION)) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a simpleType child of a <redefine> must have a restriction element as a child");
} else {
String derivedBase = grandKid.getAttribute( SchemaSymbols.ATT_BASE );
QName processedDerivedBase = parseBase(derivedBase);
if(!processedTypeName.equals(processedDerivedBase)) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("the base attribute of the restriction child of a simpleType child of a redefine must have the same value as the simpleType's type attribute");
} else {
// now we have to do the renaming...
String prefix = "";
int colonptr = derivedBase.indexOf(":");
if ( colonptr > 0)
prefix = derivedBase.substring(0,colonptr) + ":";
grandKid.setAttribute( SchemaSymbols.ATT_BASE, prefix + newName );
return true;
}
}
}
} else if (eltLocalname.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
QName processedTypeName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI);
Element grandKid = XUtil.getFirstChildElement(child);
if (grandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild");
} else {
if(grandKid.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
grandKid = XUtil.getNextSiblingElement(grandKid);
}
if (grandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild");
} else {
// have to go one more level down; let another pass worry whether complexType is valid.
Element greatGrandKid = XUtil.getFirstChildElement(grandKid);
if (greatGrandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild");
} else {
String greatGrandKidName = greatGrandKid.getLocalName();
if(greatGrandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) {
greatGrandKid = XUtil.getNextSiblingElement(greatGrandKid);
greatGrandKidName = greatGrandKid.getLocalName();
}
if (greatGrandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild");
} else if(!greatGrandKidName.equals(SchemaSymbols.ELT_RESTRICTION) &&
!greatGrandKidName.equals(SchemaSymbols.ELT_EXTENSION)) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild");
} else {
String derivedBase = greatGrandKid.getAttribute( SchemaSymbols.ATT_BASE );
QName processedDerivedBase = parseBase(derivedBase);
if(!processedTypeName.equals(processedDerivedBase)) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("the base attribute of the restriction or extension grandchild of a complexType child of a redefine must have the same value as the complexType's type attribute");
} else {
// now we have to do the renaming...
String prefix = "";
int colonptr = derivedBase.indexOf(":");
if ( colonptr > 0)
prefix = derivedBase.substring(0,colonptr) + ":";
greatGrandKid.setAttribute( SchemaSymbols.ATT_BASE, prefix + newName );
return true;
}
}
}
}
}
} else if (eltLocalname.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
QName processedBaseName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI);
int attGroupRefsCount = changeRedefineGroup(processedBaseName, eltLocalname, newName, child);
if(attGroupRefsCount > 1) {
fRedefineSucceeded = false;
// REVISIT: localize
reportGenericSchemaError("if an attributeGroup child of a <redefine> element contains an attributeGroup ref'ing itself, it must have exactly 1; this one has " + attGroupRefsCount);
} else if (attGroupRefsCount == 1) {
return true;
} else
fRedefineAttributeGroupMap.put(oldName, newName);
} else if (eltLocalname.equals(SchemaSymbols.ELT_GROUP)) {
QName processedBaseName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI);
int groupRefsCount = changeRedefineGroup(processedBaseName, eltLocalname, newName, child);
String restrictedName = newName.substring(0, newName.length()-redefIdentifier.length());
if(!fRedefineSucceeded) {
fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+restrictedName, new Boolean(false));
}
if(groupRefsCount > 1) {
fRedefineSucceeded = false;
fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+restrictedName, new Boolean(false));
// REVISIT: localize
reportGenericSchemaError("if a group child of a <redefine> element contains a group ref'ing itself, it must have exactly 1; this one has " + groupRefsCount);
} else if (groupRefsCount == 1) {
fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+restrictedName, new Boolean(false));
return true;
} else {
fGroupNameRegistry.put(fTargetNSURIString + "," + oldName, newName);
fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+restrictedName, new Boolean(true));
}
} else {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("internal Xerces error; please submit a bug with schema as testcase");
}
// if we get here then we must have reported an error and failed somewhere...
return false;
} // validateRedefineNameChange
private void traverseImport(Element importDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(importDecl, scope);
checkContent(importDecl, XUtil.getFirstChildElement(importDecl), true);
String location = importDecl.getAttribute(SchemaSymbols.ATT_SCHEMALOCATION);
// expand it before passing it to the parser
InputSource source = null;
if (fEntityResolver != null) {
source = fEntityResolver.resolveEntity("", location);
}
if (source == null) {
location = expandSystemId(location, fCurrentSchemaURL);
source = new InputSource(location);
}
else {
// create a string for uniqueness of this imported schema in fImportLocations
if (source.getPublicId () != null)
location = source.getPublicId ();
location += (',' + source.getSystemId ());
}
if (fImportLocations.contains((Object)location)) {
return;
}
fImportLocations.addElement((Object)location);
// check to make sure we're not importing ourselves...
if(source.getSystemId().equals(fCurrentSchemaURL)) {
// REVISIT: localize
return;
}
String namespaceString = importDecl.getAttribute(SchemaSymbols.ATT_NAMESPACE);
if(namespaceString.length() == 0) {
if(fTargetNSURI == StringPool.EMPTY_STRING) {
// REVISIT: localize
reportGenericSchemaError("src-import.1.2: if the namespace attribute on an <import> element is not present, the <import>ing schema must have a targetNamespace");
}
} else {
if(fTargetNSURIString.equals(namespaceString.trim())) {
// REVISIT: localize
reportGenericSchemaError("src-import.1.1: the namespace attribute of an <import> element must not be the same as the targetNamespace of the <import>ing schema");
}
}
SchemaGrammar importedGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(namespaceString);
if (importedGrammar == null) {
importedGrammar = new SchemaGrammar();
}
DOMParser parser = new IgnoreWhitespaceParser();
parser.setEntityResolver( new Resolver() );
parser.setErrorHandler( new ErrorHandler()
{
public void fatalError(SAXParseException ex) throws SAXException {
StringBuffer str = new StringBuffer();
String systemId_ = ex.getSystemId();
if (systemId_ != null) {
int index = systemId_.lastIndexOf('/');
if (index != -1)
systemId_ = systemId_.substring(index + 1);
str.append(systemId_);
}
str.append(':').append(ex.getLineNumber()).append(':').append(ex.getColumnNumber());
String message = ex.getMessage();
if(message.toLowerCase().trim().endsWith("not found.")) {
System.err.println("[Warning] "+
str.toString()+": "+ message);
} else { // do standard thing
System.err.println("[Fatal Error] "+
str.toString()+":"+message);
throw ex;
}
}
});
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}catch( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
}catch( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
try {
parser.parse( source );
}catch( IOException e ) {
e.printStackTrace();
}catch( SAXException e ) {
e.printStackTrace();
}
Document document = parser.getDocument(); //Our Grammar
Element root = null;
if (document != null) {
root = document.getDocumentElement();
}
if (root != null) {
String targetNSURI = getTargetNamespaceString(root);
if (!targetNSURI.equals(namespaceString) ) {
// REVISIT: Localize
reportGenericSchemaError("imported schema '"+location+"' has a different targetNameSpace '"
+targetNSURI+"' from what is declared '"+namespaceString+"'.");
}
else {
TraverseSchema impSchema = new TraverseSchema(root, fStringPool, importedGrammar, fGrammarResolver, fErrorReporter, location, fEntityResolver, fFullConstraintChecking);
Enumeration ics = impSchema.fIdentityConstraints.keys();
while(ics.hasMoreElements()) {
Object icsKey = ics.nextElement();
fIdentityConstraints.put(icsKey, impSchema.fIdentityConstraints.get(icsKey));
}
Enumeration icNames = impSchema.fIdentityConstraintNames.keys();
while(icNames.hasMoreElements()) {
String icsNameKey = (String)icNames.nextElement();
fIdentityConstraintNames.put(icsNameKey, impSchema.fIdentityConstraintNames.get(icsNameKey));
}
}
}
else {
reportGenericSchemaError("Could not get the doc root for imported Schema file: "+location);
}
}
// utility method for finding the targetNamespace (and flagging errors if they occur)
private String getTargetNamespaceString( Element root) throws Exception {
String targetNSURI = "";
Attr targetNSAttr = root.getAttributeNode(SchemaSymbols.ATT_TARGETNAMESPACE);
if(targetNSAttr != null) {
targetNSURI=targetNSAttr.getValue();
if(targetNSURI.length() == 0) {
// REVISIT: localize
reportGenericSchemaError("sch-prop-correct.1: \"\" is not a legal value for the targetNamespace attribute; the attribute must either be absent or contain a nonempty value");
}
}
return targetNSURI;
} // end getTargetNamespaceString(Element)
/**
* <annotation>(<appinfo> | <documentation>)*</annotation>
*
* @param annotationDecl: the DOM node corresponding to the <annotation> info item
*/
private void traverseAnnotationDecl(Element annotationDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(annotationDecl, scope);
for(Element child = XUtil.getFirstChildElement(annotationDecl); child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if(!((name.equals(SchemaSymbols.ELT_APPINFO)) ||
(name.equals(SchemaSymbols.ELT_DOCUMENTATION)))) {
// REVISIT: Localize
reportGenericSchemaError("an <annotation> can only contain <appinfo> and <documentation> elements");
}
// General Attribute Checking
attrValues = fGeneralAttrCheck.checkAttributes(child, scope);
}
}
//
// Evaluates content of Annotation if present.
//
// @param: elm - top element
// @param: content - content must be annotation? or some other simple content
// @param: isEmpty: -- true if the content allowed is (annotation?) only
// false if must have some element (with possible preceding <annotation?>)
//
//REVISIT: this function should be used in all traverse* methods!
private Element checkContent( Element elm, Element content, boolean isEmpty ) throws Exception {
//isEmpty = true-> means content can be null!
if ( content == null) {
if (!isEmpty) {
reportSchemaError(SchemaMessageProvider.ContentError,
new Object [] { elm.getAttribute( SchemaSymbols.ATT_NAME )});
}
return null;
}
if (content.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
traverseAnnotationDecl( content );
content = XUtil.getNextSiblingElement(content);
if (content == null ) { //must be followed by <simpleType?>
if (!isEmpty) {
reportSchemaError(SchemaMessageProvider.ContentError,
new Object [] { elm.getAttribute( SchemaSymbols.ATT_NAME )});
}
return null;
}
if (content.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
reportSchemaError(SchemaMessageProvider.AnnotationError,
new Object [] { elm.getAttribute( SchemaSymbols.ATT_NAME )});
return null;
}
//return null if expected only annotation?, else returns updated content
}
return content;
}
//@param: elm - top element
//@param: baseTypeStr - type (base/itemType/memberTypes)
//@param: baseRefContext: whether the caller is using this type as a base for restriction, union or list
//return DatatypeValidator available for the baseTypeStr, null if not found or disallowed.
// also throws an error if the base type won't allow itself to be used in this context.
//REVISIT: this function should be used in some|all traverse* methods!
private DatatypeValidator findDTValidator (Element elm, String baseTypeStr, int baseRefContext ) throws Exception{
int baseType = fStringPool.addSymbol( baseTypeStr );
String prefix = "";
DatatypeValidator baseValidator = null;
String localpart = baseTypeStr;
int colonptr = baseTypeStr.indexOf(":");
if ( colonptr > 0) {
prefix = baseTypeStr.substring(0,colonptr);
localpart = baseTypeStr.substring(colonptr+1);
}
String uri = resolvePrefixToURI(prefix);
baseValidator = getDatatypeValidator(uri, localpart);
if (baseValidator == null) {
Element baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (baseTypeNode != null) {
traverseSimpleTypeDecl( baseTypeNode );
baseValidator = getDatatypeValidator(uri, localpart);
}
}
Integer finalValue;
if ( baseValidator == null ) {
reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype,
new Object [] { elm.getAttribute( SchemaSymbols.ATT_BASE ),
elm.getAttribute(SchemaSymbols.ATT_NAME)});
} else {
finalValue = (uri.equals("")?
((Integer)fSimpleTypeFinalRegistry.get(localpart)):
((Integer)fSimpleTypeFinalRegistry.get(uri + "," +localpart)));
if((finalValue != null) &&
((finalValue.intValue() & baseRefContext) != 0)) {
//REVISIT: localize
reportGenericSchemaError("the base type " + baseTypeStr + " does not allow itself to be used as the base for a restriction and/or as a type in a list and/or union");
return baseValidator;
}
}
return baseValidator;
}
private void checkEnumerationRequiredNotation(String name, String type) throws Exception{
String localpart = type;
int colonptr = type.indexOf(":");
if ( colonptr > 0) {
localpart = type.substring(colonptr+1);
}
if (localpart.equals("NOTATION")) {
reportGenericSchemaError("[enumeration-required-notation] It is an error for NOTATION to be used "+
"directly in a schema in element/attribute '"+name+"'");
}
}
// @used in traverseSimpleType
// on return we need to pop the last simpleType name from
// the name stack
private int resetSimpleTypeNameStack(int returnValue){
if (!fSimpleTypeNameStack.empty()) {
fSimpleTypeNameStack.pop();
}
return returnValue;
}
// @used in traverseSimpleType
// report an error cos-list-of-atomic and reset the last name of the list datatype we traversing
private void reportCosListOfAtomic () throws Exception{
reportGenericSchemaError("cos-list-of-atomic: The itemType must have a {variety} of atomic or union (in which case all the {member type definitions} must be atomic)");
fListName="";
}
// @used in traverseSimpleType
// find if union datatype validator has list datatype member.
private boolean isListDatatype (DatatypeValidator validator){
if (validator instanceof UnionDatatypeValidator) {
Vector temp = ((UnionDatatypeValidator)validator).getBaseValidators();
for (int i=0;i<temp.size();i++) {
if (temp.elementAt(i) instanceof ListDatatypeValidator) {
return true;
}
if (temp.elementAt(i) instanceof UnionDatatypeValidator) {
if (isListDatatype((DatatypeValidator)temp.elementAt(i))) {
return true;
}
}
}
}
return false;
}
/**
* Traverse SimpleType declaration:
* <simpleType
* final = #all | list of (restriction, union or list)
* id = ID
* name = NCName>
* Content: (annotation? , ((list | restriction | union)))
* </simpleType>
* traverse <list>|<restriction>|<union>
*
* @param simpleTypeDecl
* @return
*/
private int traverseSimpleTypeDecl( Element simpleTypeDecl ) throws Exception {
// General Attribute Checking
int scope = isTopLevel(simpleTypeDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(simpleTypeDecl, scope);
String nameProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME );
String qualifiedName = nameProperty;
//---------------------------------------------------
// set qualified name
//---------------------------------------------------
if ( nameProperty.length() == 0) { // anonymous simpleType
qualifiedName = "#S#"+(fSimpleTypeAnonCount++);
fStringPool.addSymbol(qualifiedName);
}
else {
if (fTargetNSURIString.length () != 0) {
qualifiedName = fTargetNSURIString+","+qualifiedName;
}
fStringPool.addSymbol( nameProperty );
}
//----------------------------------------------------------------------
//check if we have already traversed the same simpleType decl
//----------------------------------------------------------------------
if (fDatatypeRegistry.getDatatypeValidator(qualifiedName)!=null) {
return resetSimpleTypeNameStack(fStringPool.addSymbol(qualifiedName));
}
else {
if (fSimpleTypeNameStack.search(qualifiedName) != -1 ){
// cos-no-circular-unions && no circular definitions
reportGenericSchemaError("cos-no-circular-unions: no circular definitions are allowed for an element '"+ nameProperty+"'");
return resetSimpleTypeNameStack(-1);
}
}
//----------------------------------------------------------
// update _final_ registry
//----------------------------------------------------------
Attr finalAttr = simpleTypeDecl.getAttributeNode(SchemaSymbols.ATT_FINAL);
int finalProperty = 0;
if(finalAttr != null)
finalProperty = parseFinalSet(finalAttr.getValue());
else
finalProperty = parseFinalSet(null);
// if we have a nonzero final , store it in the hash...
if(finalProperty != 0)
fSimpleTypeFinalRegistry.put(qualifiedName, new Integer(finalProperty));
// -------------------------------
// remember name being traversed to
// avoid circular definitions in union
// -------------------------------
fSimpleTypeNameStack.push(qualifiedName);
//----------------------------------------------------------------------
//annotation?,(list|restriction|union)
//----------------------------------------------------------------------
Element content = XUtil.getFirstChildElement(simpleTypeDecl);
content = checkContent(simpleTypeDecl, content, false);
if (content == null) {
return resetSimpleTypeNameStack(-1);
}
// General Attribute Checking
scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable contentAttrs = fGeneralAttrCheck.checkAttributes(content, scope);
//----------------------------------------------------------------------
//use content.getLocalName for the cases there "xsd:" is a prefix, ei. "xsd:list"
//----------------------------------------------------------------------
String varietyProperty = content.getLocalName();
String baseTypeQNameProperty = null;
Vector dTValidators = null;
int size = 0;
StringTokenizer unionMembers = null;
boolean list = false;
boolean union = false;
boolean restriction = false;
int numOfTypes = 0; //list/restriction = 1, union = "+"
if (varietyProperty.equals(SchemaSymbols.ELT_LIST)) { //traverse List
baseTypeQNameProperty = content.getAttribute( SchemaSymbols.ATT_ITEMTYPE );
list = true;
if (fListName.length() != 0) { // parent is <list> datatype
reportCosListOfAtomic();
return resetSimpleTypeNameStack(-1);
}
else {
fListName = qualifiedName;
}
}
else if (varietyProperty.equals(SchemaSymbols.ELT_RESTRICTION)) { //traverse Restriction
baseTypeQNameProperty = content.getAttribute( SchemaSymbols.ATT_BASE );
restriction= true;
}
else if (varietyProperty.equals(SchemaSymbols.ELT_UNION)) { //traverse union
union = true;
baseTypeQNameProperty = content.getAttribute( SchemaSymbols.ATT_MEMBERTYPES);
if (baseTypeQNameProperty.length() != 0) {
unionMembers = new StringTokenizer( baseTypeQNameProperty );
size = unionMembers.countTokens();
}
else {
size = 1; //at least one must be seen as <simpleType> decl
}
dTValidators = new Vector (size, 2);
}
else {
reportSchemaError(SchemaMessageProvider.FeatureUnsupported,
new Object [] { varietyProperty });
return -1;
}
if(XUtil.getNextSiblingElement(content) != null) {
// REVISIT: Localize
reportGenericSchemaError("error in content of simpleType");
}
int typeNameIndex;
DatatypeValidator baseValidator = null;
if ( baseTypeQNameProperty.length() == 0 ) {
//---------------------------
//must 'see' <simpleType>
//---------------------------
//content = {annotation?,simpleType?...}
content = XUtil.getFirstChildElement(content);
//check content (annotation?, ...)
content = checkContent(simpleTypeDecl, content, false);
if (content == null) {
return resetSimpleTypeNameStack(-1);
}
if (content.getLocalName().equals( SchemaSymbols.ELT_SIMPLETYPE )) {
typeNameIndex = traverseSimpleTypeDecl(content);
if (typeNameIndex!=-1) {
baseValidator=fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex));
if (baseValidator !=null && union) {
dTValidators.addElement((DatatypeValidator)baseValidator);
}
}
if ( typeNameIndex == -1 || baseValidator == null) {
reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype,
new Object [] { content.getAttribute( SchemaSymbols.ATT_BASE ),
content.getAttribute(SchemaSymbols.ATT_NAME) });
return resetSimpleTypeNameStack(-1);
}
}
else {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
return resetSimpleTypeNameStack(-1);
}
} //end - must see simpleType?
else {
//-----------------------------
//base was provided - get proper validator.
//-----------------------------
numOfTypes = 1;
if (union) {
numOfTypes= size;
}
//--------------------------------------------------------------------
// this loop is also where we need to find out whether the type being used as
// a base (or itemType or whatever) allows such things.
//--------------------------------------------------------------------
int baseRefContext = (restriction? SchemaSymbols.RESTRICTION:0);
baseRefContext = baseRefContext | (union? SchemaSymbols.UNION:0);
baseRefContext = baseRefContext | (list ? SchemaSymbols.LIST:0);
for (int i=0; i<numOfTypes; i++) { //find all validators
if (union) {
baseTypeQNameProperty = unionMembers.nextToken();
}
baseValidator = findDTValidator ( simpleTypeDecl, baseTypeQNameProperty, baseRefContext);
if ( baseValidator == null) {
return resetSimpleTypeNameStack(-1);
}
// ------------------------------
// (variety is list)cos-list-of-atomic
// ------------------------------
if (fListName.length() != 0 ) {
if (baseValidator instanceof ListDatatypeValidator) {
reportCosListOfAtomic();
return resetSimpleTypeNameStack(-1);
}
//-----------------------------------------------------
// if baseValidator is of type (union) need to look
// at Union validators to make sure that List is not one of them
//-----------------------------------------------------
if (isListDatatype(baseValidator)) {
reportCosListOfAtomic();
return resetSimpleTypeNameStack(-1);
}
}
if (union) {
dTValidators.addElement((DatatypeValidator)baseValidator); //add validator to structure
}
//REVISIT: Should we raise exception here?
// if baseValidator.isInstanceOf(LIST) and UNION
if ( list && (baseValidator instanceof UnionDatatypeValidator)) {
reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE ),
simpleTypeDecl.getAttribute(SchemaSymbols.ATT_NAME)});
return -1;
}
}
} //end - base is available
// ------------------------------------------
// move to next child
// <base==empty)->[simpleType]->[facets] OR
// <base!=empty)->[facets]
// ------------------------------------------
if (baseTypeQNameProperty.length() == 0) {
content = XUtil.getNextSiblingElement( content );
}
else {
content = XUtil.getFirstChildElement(content);
}
// ------------------------------------------
//get more types for union if any
// ------------------------------------------
if (union) {
int index=size;
if (baseTypeQNameProperty.length() != 0 ) {
content = checkContent(simpleTypeDecl, content, true);
}
while (content!=null) {
typeNameIndex = traverseSimpleTypeDecl(content);
if (typeNameIndex!=-1) {
baseValidator=fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex));
if (baseValidator != null) {
if (fListName.length() != 0 && baseValidator instanceof ListDatatypeValidator) {
reportCosListOfAtomic();
return resetSimpleTypeNameStack(-1);
}
dTValidators.addElement((DatatypeValidator)baseValidator);
}
}
if ( baseValidator == null || typeNameIndex == -1) {
reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE ),
simpleTypeDecl.getAttribute(SchemaSymbols.ATT_NAME)});
return (-1);
}
content = XUtil.getNextSiblingElement( content );
}
} // end - traverse Union
if (fListName.length() != 0) {
// reset fListName, meaning that we are done with
// traversing <list> and its itemType resolves to atomic value
if (fListName.equals(qualifiedName)) {
fListName = "";
}
}
int numFacets=0;
fFacetData.clear();
if (restriction && content != null) {
short flags = 0; // flag facets that have fixed="true"
int numEnumerationLiterals = 0;
Vector enumData = new Vector();
content = checkContent(simpleTypeDecl, content , true);
StringBuffer pattern = null;
String facet;
while (content != null) {
if (content.getNodeType() == Node.ELEMENT_NODE) {
// General Attribute Checking
contentAttrs = fGeneralAttrCheck.checkAttributes(content, scope);
numFacets++;
facet =content.getLocalName();
if (facet.equals(SchemaSymbols.ELT_ENUMERATION)) {
numEnumerationLiterals++;
String enumVal = content.getAttribute(SchemaSymbols.ATT_VALUE);
String localName;
if (baseValidator instanceof NOTATIONDatatypeValidator) {
String prefix = "";
String localpart = enumVal;
int colonptr = enumVal.indexOf(":");
if ( colonptr > 0) {
prefix = enumVal.substring(0,colonptr);
localpart = enumVal.substring(colonptr+1);
}
String uriStr = (prefix.length() != 0)?resolvePrefixToURI(prefix):fTargetNSURIString;
nameProperty=uriStr + ":" + localpart;
localName = (String)fNotationRegistry.get(nameProperty);
if(localName == null){
localName = traverseNotationFromAnotherSchema( localpart, uriStr);
if (localName == null) {
reportGenericSchemaError("Notation '" + localpart +
"' not found in the grammar "+ uriStr);
}
}
enumVal=nameProperty;
}
enumData.addElement(enumVal);
checkContent(simpleTypeDecl, XUtil.getFirstChildElement( content ), true);
}
else if (facet.equals(SchemaSymbols.ELT_ANNOTATION) || facet.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
}
else if (facet.equals(SchemaSymbols.ELT_PATTERN)) {
if (pattern == null) {
pattern = new StringBuffer (content.getAttribute( SchemaSymbols.ATT_VALUE ));
}
else {
// ---------------------------------------------
//datatypes: 5.2.4 pattern: src-multiple-pattern
// ---------------------------------------------
pattern.append("|");
pattern.append(content.getAttribute( SchemaSymbols.ATT_VALUE ));
checkContent(simpleTypeDecl, XUtil.getFirstChildElement( content ), true);
}
}
else {
if ( fFacetData.containsKey(facet) )
reportSchemaError(SchemaMessageProvider.DatatypeError,
new Object [] {"The facet '" + facet + "' is defined more than once."} );
fFacetData.put(facet,content.getAttribute( SchemaSymbols.ATT_VALUE ));
if (content.getAttribute( SchemaSymbols.ATT_FIXED).equals("true") ||
content.getAttribute( SchemaSymbols.ATT_FIXED).equals("1")){
// --------------------------------------------
// set fixed facet flags
// length - must remain const through derivation
// thus we don't care if it fixed
// --------------------------------------------
if ( facet.equals(SchemaSymbols.ELT_MINLENGTH) ) {
flags |= DatatypeValidator.FACET_MINLENGTH;
}
else if (facet.equals(SchemaSymbols.ELT_MAXLENGTH)) {
flags |= DatatypeValidator.FACET_MAXLENGTH;
}
else if (facet.equals(SchemaSymbols.ELT_MAXEXCLUSIVE)) {
flags |= DatatypeValidator.FACET_MAXEXCLUSIVE;
}
else if (facet.equals(SchemaSymbols.ELT_MAXINCLUSIVE)) {
flags |= DatatypeValidator.FACET_MAXINCLUSIVE;
}
else if (facet.equals(SchemaSymbols.ELT_MINEXCLUSIVE)) {
flags |= DatatypeValidator.FACET_MINEXCLUSIVE;
}
else if (facet.equals(SchemaSymbols.ELT_MININCLUSIVE)) {
flags |= DatatypeValidator.FACET_MININCLUSIVE;
}
else if (facet.equals(SchemaSymbols.ELT_TOTALDIGITS)) {
flags |= DatatypeValidator.FACET_TOTALDIGITS;
}
else if (facet.equals(SchemaSymbols.ELT_FRACTIONDIGITS)) {
flags |= DatatypeValidator.FACET_FRACTIONDIGITS;
}
else if (facet.equals(SchemaSymbols.ELT_WHITESPACE) &&
baseValidator instanceof StringDatatypeValidator) {
flags |= DatatypeValidator.FACET_WHITESPACE;
}
}
checkContent(simpleTypeDecl, XUtil.getFirstChildElement( content ), true);
}
}
content = XUtil.getNextSiblingElement(content);
}
if (numEnumerationLiterals > 0) {
fFacetData.put(SchemaSymbols.ELT_ENUMERATION, enumData);
}
if (pattern !=null) {
fFacetData.put(SchemaSymbols.ELT_PATTERN, pattern.toString());
}
if (flags != 0) {
fFacetData.put(DatatypeValidator.FACET_FIXED, new Short(flags));
}
}
else if (list && content!=null) {
// report error - must not have any children!
if (baseTypeQNameProperty.length() != 0) {
content = checkContent(simpleTypeDecl, content, true);
if (content!=null) {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
}
}
else {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
//REVISIT: should we return?
}
}
else if (union && content!=null) {
//report error - must not have any children!
if (baseTypeQNameProperty.length() != 0) {
content = checkContent(simpleTypeDecl, content, true);
if (content!=null) {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
}
}
else {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
//REVISIT: should we return?
}
}
// ----------------------------------------------------------------------
// create & register validator for "generated" type if it doesn't exist
// ----------------------------------------------------------------------
try {
DatatypeValidator newValidator =
fDatatypeRegistry.getDatatypeValidator( qualifiedName );
if( newValidator == null ) { // not previously registered
if (list) {
fDatatypeRegistry.createDatatypeValidator( qualifiedName, baseValidator,
fFacetData,true);
}
else if (restriction) {
fDatatypeRegistry.createDatatypeValidator( qualifiedName, baseValidator,
fFacetData,false);
}
else { //union
fDatatypeRegistry.createDatatypeValidator( qualifiedName, dTValidators);
}
}
} catch (Exception e) {
reportSchemaError(SchemaMessageProvider.DatatypeError,new Object [] { e.getMessage() });
}
return resetSimpleTypeNameStack(fStringPool.addSymbol(qualifiedName));
}
/*
* <any
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* namespace = (##any | ##other) | List of (anyURI | (##targetNamespace | ##local))
* processContents = lax | skip | strict>
* Content: (annotation?)
* </any>
*/
private int traverseAny(Element child) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(child, scope);
Element annotation = checkContent( child, XUtil.getFirstChildElement(child), true );
if(annotation != null ) {
// REVISIT: Localize
reportGenericSchemaError("<any> elements can contain at most one <annotation> element in their children");
}
int anyIndex = -1;
String namespace = child.getAttribute(SchemaSymbols.ATT_NAMESPACE).trim();
String processContents = child.getAttribute("processContents").trim();
int processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY;
int processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER;
int processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_NS;
if (processContents.length() > 0 && !processContents.equals("strict")) {
if (processContents.equals("lax")) {
processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY_LAX;
processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_LAX;
processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_NS_LAX;
}
else if (processContents.equals("skip")) {
processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY_SKIP;
processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_SKIP;
processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_NS_SKIP;
}
}
if (namespace.length() == 0 || namespace.equals("##any")) {
anyIndex = fSchemaGrammar.addContentSpecNode(processContentsAny, -1, StringPool.EMPTY_STRING, false);
}
else if (namespace.equals("##other")) {
String uri = fTargetNSURIString;
int uriIndex = fStringPool.addSymbol(uri);
anyIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyOther, -1, uriIndex, false);
}
else if (namespace.length() > 0) {
int uriIndex, leafIndex, choiceIndex;
StringTokenizer tokenizer = new StringTokenizer(namespace);
String token = tokenizer.nextToken();
if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDLOCAL)) {
choiceIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, StringPool.EMPTY_STRING, false);
} else {
if (token.equals("##targetNamespace"))
token = fTargetNSURIString;
uriIndex = fStringPool.addSymbol(token);
choiceIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, uriIndex, false);
}
while (tokenizer.hasMoreElements()) {
token = tokenizer.nextToken();
if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDLOCAL)) {
leafIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, StringPool.EMPTY_STRING, false);
} else {
if (token.equals("##targetNamespace"))
token = fTargetNSURIString;
uriIndex = fStringPool.addSymbol(token);
leafIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, uriIndex, false);
}
choiceIndex = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_CHOICE, choiceIndex, leafIndex, false);
}
anyIndex = choiceIndex;
}
else {
// REVISIT: Localize
reportGenericSchemaError("Empty namespace attribute for any element");
}
return anyIndex;
}
public DatatypeValidator getDatatypeValidator(String uri, String localpart) {
DatatypeValidator dv = null;
if (uri.length()==0 || uri.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)) {
dv = fDatatypeRegistry.getDatatypeValidator( localpart );
}
else {
dv = fDatatypeRegistry.getDatatypeValidator( uri+","+localpart );
}
return dv;
}
/*
* <anyAttribute
* id = ID
* namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace}>
* Content: (annotation?)
* </anyAttribute>
*/
private XMLAttributeDecl traverseAnyAttribute(Element anyAttributeDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(anyAttributeDecl, scope);
Element annotation = checkContent( anyAttributeDecl, XUtil.getFirstChildElement(anyAttributeDecl), true );
if(annotation != null ) {
// REVISIT: Localize
reportGenericSchemaError("<anyAttribute> elements can contain at most one <annotation> element in their children");
}
XMLAttributeDecl anyAttDecl = new XMLAttributeDecl();
String processContents = anyAttributeDecl.getAttribute(SchemaSymbols.ATT_PROCESSCONTENTS).trim();
String namespace = anyAttributeDecl.getAttribute(SchemaSymbols.ATT_NAMESPACE).trim();
// simplify! NG
//String curTargetUri = anyAttributeDecl.getOwnerDocument().getDocumentElement().getAttribute("targetNamespace");
String curTargetUri = fTargetNSURIString;
if ( namespace.length() == 0 || namespace.equals(SchemaSymbols.ATTVAL_TWOPOUNDANY) ) {
anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_ANY;
}
else if (namespace.equals(SchemaSymbols.ATTVAL_TWOPOUNDOTHER)) {
anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_OTHER;
anyAttDecl.name.uri = fStringPool.addSymbol(curTargetUri);
}
else if (namespace.length() > 0){
anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_LIST;
StringTokenizer tokenizer = new StringTokenizer(namespace);
int aStringList = fStringPool.startStringList();
Vector tokens = new Vector();
int tokenStr;
while (tokenizer.hasMoreElements()) {
String token = tokenizer.nextToken();
if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDLOCAL)) {
tokenStr = fStringPool.EMPTY_STRING;
} else {
if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDTARGETNS))
token = curTargetUri;
tokenStr = fStringPool.addSymbol(token);
}
if (!fStringPool.addStringToList(aStringList, tokenStr)){
reportGenericSchemaError("Internal StringPool error when reading the "+
"namespace attribute for anyattribute declaration");
}
}
fStringPool.finishStringList(aStringList);
anyAttDecl.enumeration = aStringList;
}
else {
// REVISIT: Localize
reportGenericSchemaError("Empty namespace attribute for anyattribute declaration");
}
// default processContents is "strict";
if (processContents.equals(SchemaSymbols.ATTVAL_SKIP)){
anyAttDecl.defaultType |= XMLAttributeDecl.PROCESSCONTENTS_SKIP;
}
else if (processContents.equals(SchemaSymbols.ATTVAL_LAX)) {
anyAttDecl.defaultType |= XMLAttributeDecl.PROCESSCONTENTS_LAX;
}
else {
anyAttDecl.defaultType |= XMLAttributeDecl.PROCESSCONTENTS_STRICT;
}
return anyAttDecl;
}
// Schema Component Constraint: Attribute Wildcard Intersection
// For a wildcard's {namespace constraint} value to be the intensional intersection of two other such values (call them O1 and O2): the appropriate case among the following must be true:
// 1 If O1 and O2 are the same value, then that value must be the value.
// 2 If either O1 or O2 is any, then the other must be the value.
// 3 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or absent), then that set, minus the negated namespace name if it was in the set, must be the value.
// 4 If both O1 and O2 are sets of (namespace names or absent), then the intersection of those sets must be the value.
// 5 If the two are negations of different namespace names, then the intersection is not expressible.
// In the case where there are more than two values, the intensional intersection is determined by identifying the intensional intersection of two of the values as above, then the intensional intersection of that value with the third (providing the first intersection was expressible), and so on as required.
private XMLAttributeDecl AWildCardIntersection(XMLAttributeDecl oneAny, XMLAttributeDecl anotherAny) {
// if either one is not expressible, the result is still not expressible
if (oneAny.type == -1) {
return oneAny;
}
if (anotherAny.type == -1) {
return anotherAny;
}
// 1 If O1 and O2 are the same value, then that value must be the value.
// this one is dealt with in different branches
// 2 If either O1 or O2 is any, then the other must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return anotherAny;
}
if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return oneAny;
}
// 3 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or absent), then that set, minus the negated namespace name if it was in the set, must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST ||
oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
XMLAttributeDecl anyList, anyOther;
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
anyList = oneAny;
anyOther = anotherAny;
} else {
anyList = anotherAny;
anyOther = oneAny;
}
int[] uriList = fStringPool.stringListAsIntArray(anyList.enumeration);
if (elementInSet(anyOther.name.uri, uriList)) {
int newList = fStringPool.startStringList();
for (int i=0; i< uriList.length; i++) {
if (uriList[i] != anyOther.name.uri ) {
fStringPool.addStringToList(newList, uriList[i]);
}
}
fStringPool.finishStringList(newList);
anyList.enumeration = newList;
}
return anyList;
}
// 4 If both O1 and O2 are sets of (namespace names or absent), then the intersection of those sets must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
int[] result = intersect2sets(fStringPool.stringListAsIntArray(oneAny.enumeration),
fStringPool.stringListAsIntArray(anotherAny.enumeration));
int newList = fStringPool.startStringList();
for (int i=0; i<result.length; i++) {
fStringPool.addStringToList(newList, result[i]);
}
fStringPool.finishStringList(newList);
oneAny.enumeration = newList;
return oneAny;
}
// 5 If the two are negations of different namespace names, then the intersection is not expressible.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
if (oneAny.name.uri == anotherAny.name.uri) {
return oneAny;
} else {
oneAny.type = -1;
return oneAny;
}
}
// should never go there;
return oneAny;
}
// Schema Component Constraint: Attribute Wildcard Union
// For a wildcard's {namespace constraint} value to be the intensional union of two other such values (call them O1 and O2): the appropriate case among the following must be true:
// 1 If O1 and O2 are the same value, then that value must be the value.
// 2 If either O1 or O2 is any, then any must be the value.
// 3 If both O1 and O2 are sets of (namespace names or absent), then the union of those sets must be the value.
// 4 If the two are negations of different namespace names, then any must be the value.
// 5 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or absent), then The appropriate case among the following must be true:
// 5.1 If the set includes the negated namespace name, then any must be the value.
// 5.2 If the set does not include the negated namespace name, then whichever of O1 or O2 is a pair of not and a namespace name must be the value.
// In the case where there are more than two values, the intensional union is determined by identifying the intensional union of two of the values as above, then the intensional union of that value with the third, and so on as required.
private XMLAttributeDecl AWildCardUnion(XMLAttributeDecl oneAny, XMLAttributeDecl anotherAny) {
// if either one is not expressible, the result is still not expressible
if (oneAny.type == -1) {
return oneAny;
}
if (anotherAny.type == -1) {
return anotherAny;
}
// 1 If O1 and O2 are the same value, then that value must be the value.
// this one is dealt with in different branches
// 2 If either O1 or O2 is any, then any must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return oneAny;
}
if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return anotherAny;
}
// 3 If both O1 and O2 are sets of (namespace names or absent), then the union of those sets must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
int[] result = union2sets(fStringPool.stringListAsIntArray(oneAny.enumeration),
fStringPool.stringListAsIntArray(anotherAny.enumeration));
int newList = fStringPool.startStringList();
for (int i=0; i<result.length; i++) {
fStringPool.addStringToList(newList, result[i]);
}
fStringPool.finishStringList(newList);
oneAny.enumeration = newList;
return oneAny;
}
// 4 If the two are negations of different namespace names, then any must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
if (oneAny.name.uri == anotherAny.name.uri) {
return oneAny;
} else {
oneAny.type = XMLAttributeDecl.TYPE_ANY_ANY;
return oneAny;
}
}
// 5 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or absent), then The appropriate case among the following must be true:
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST ||
oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
XMLAttributeDecl anyList, anyOther;
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
anyList = oneAny;
anyOther = anotherAny;
} else {
anyList = anotherAny;
anyOther = oneAny;
}
// 5.1 If the set includes the negated namespace name, then any must be the value.
if (elementInSet(anyOther.name.uri,
fStringPool.stringListAsIntArray(anyList.enumeration))) {
anyOther.type = XMLAttributeDecl.TYPE_ANY_ANY;
}
// 5.2 If the set does not include the negated namespace name, then whichever of O1 or O2 is a pair of not and a namespace name must be the value.
return anyOther;
}
// should never go there;
return oneAny;
}
// Schema Component Constraint: Wildcard Subset
// For a namespace constraint (call it sub) to be an intensional subset of another namespace constraint (call it super) one of the following must be true:
// 1 super must be any.
// 2 All of the following must be true:
// 2.1 sub must be a pair of not and a namespace name or absent.
// 2.2 super must be a pair of not and the same value.
// 3 All of the following must be true:
// 3.1 sub must be a set whose members are either namespace names or absent.
// 3.2 One of the following must be true:
// 3.2.1 super must be the same set or a superset thereof.
// 3.2.2 super must be a pair of not and a namespace name or absent and that value must not be in sub's set.
private boolean AWildCardSubset(XMLAttributeDecl subAny, XMLAttributeDecl superAny) {
// if either one is not expressible, it can't be a subset
if (subAny.type == -1 || superAny.type == -1)
return false;
// 1 super must be any.
if (superAny.type == XMLAttributeDecl.TYPE_ANY_ANY)
return true;
// 2 All of the following must be true:
// 2.1 sub must be a pair of not and a namespace name or absent.
if (subAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
// 2.2 super must be a pair of not and the same value.
if (superAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
subAny.name.uri == superAny.name.uri) {
return true;
}
}
// 3 All of the following must be true:
// 3.1 sub must be a set whose members are either namespace names or absent.
if (subAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
// 3.2 One of the following must be true:
// 3.2.1 super must be the same set or a superset thereof.
if (superAny.type == XMLAttributeDecl.TYPE_ANY_LIST &&
subset2sets(fStringPool.stringListAsIntArray(subAny.enumeration),
fStringPool.stringListAsIntArray(superAny.enumeration))) {
return true;
}
// 3.2.2 super must be a pair of not and a namespace name or absent and that value must not be in sub's set.
if (superAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
!elementInSet(superAny.name.uri, fStringPool.stringListAsIntArray(superAny.enumeration))) {
return true;
}
}
return false;
}
// Validation Rule: Wildcard allows Namespace Name
// For a value which is either a namespace name or absent to be valid with respect to a wildcard constraint (the value of a {namespace constraint}) one of the following must be true:
// 1 The constraint must be any.
// 2 All of the following must be true:
// 2.1 The constraint is a pair of not and a namespace name or absent ([Definition:] call this the namespace test).
// 2.2 The value must not be identical to the namespace test.
// 2.3 The value must not be absent.
// 3 The constraint is a set, and the value is identical to one of the members of the set.
private boolean AWildCardAllowsNameSpace(XMLAttributeDecl wildcard, String uri) {
// if the constrain is not expressible, then nothing is allowed
if (wildcard.type == -1)
return false;
// 1 The constraint must be any.
if (wildcard.type == XMLAttributeDecl.TYPE_ANY_ANY)
return true;
int uriStr = fStringPool.addString(uri);
// 2 All of the following must be true:
// 2.1 The constraint is a pair of not and a namespace name or absent ([Definition:] call this the namespace test).
if (wildcard.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
// 2.2 The value must not be identical to the namespace test.
// 2.3 The value must not be absent.
if (uriStr != wildcard.name.uri && uriStr != StringPool.EMPTY_STRING)
return true;
}
// 3 The constraint is a set, and the value is identical to one of the members of the set.
if (wildcard.type == XMLAttributeDecl.TYPE_ANY_LIST) {
if (elementInSet(uriStr, fStringPool.stringListAsIntArray(wildcard.enumeration)))
return true;
}
return false;
}
private boolean isAWildCard(XMLAttributeDecl a) {
if (a.type == XMLAttributeDecl.TYPE_ANY_ANY
||a.type == XMLAttributeDecl.TYPE_ANY_LIST
||a.type == XMLAttributeDecl.TYPE_ANY_OTHER )
return true;
else
return false;
}
int[] intersect2sets(int[] one, int[] theOther){
int[] result = new int[(one.length>theOther.length?one.length:theOther.length)];
// simple implemention,
int count = 0;
for (int i=0; i<one.length; i++) {
if (elementInSet(one[i], theOther))
result[count++] = one[i];
}
int[] result2 = new int[count];
System.arraycopy(result, 0, result2, 0, count);
return result2;
}
int[] union2sets(int[] one, int[] theOther){
int[] result1 = new int[one.length];
// simple implemention,
int count = 0;
for (int i=0; i<one.length; i++) {
if (!elementInSet(one[i], theOther))
result1[count++] = one[i];
}
int[] result2 = new int[count+theOther.length];
System.arraycopy(result1, 0, result2, 0, count);
System.arraycopy(theOther, 0, result2, count, theOther.length);
return result2;
}
boolean subset2sets(int[] subSet, int[] superSet){
for (int i=0; i<subSet.length; i++) {
if (!elementInSet(subSet[i], superSet))
return false;
}
return true;
}
boolean elementInSet(int ele, int[] set){
boolean found = false;
for (int i=0; i<set.length && !found; i++) {
if (ele==set[i])
found = true;
}
return found;
}
// wrapper traverseComplexTypeDecl method
private int traverseComplexTypeDecl( Element complexTypeDecl ) throws Exception {
return traverseComplexTypeDecl (complexTypeDecl, false);
}
/**
* Traverse ComplexType Declaration - Rec Implementation.
*
* <complexType
* abstract = boolean
* block = #all or (possibly empty) subset of {extension, restriction}
* final = #all or (possibly empty) subset of {extension, restriction}
* id = ID
* mixed = boolean : false
* name = NCName>
* Content: (annotation? , (simpleContent | complexContent |
* ( (group | all | choice | sequence)? ,
* ( (attribute | attributeGroup)* , anyAttribute?))))
* </complexType>
* @param complexTypeDecl
* @param forwardRef
* @return
*/
private int traverseComplexTypeDecl( Element complexTypeDecl, boolean forwardRef)
throws Exception {
// General Attribute Checking
int scope = isTopLevel(complexTypeDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(complexTypeDecl, scope);
// ------------------------------------------------------------------
// Get the attributes of the type
// ------------------------------------------------------------------
String isAbstract = complexTypeDecl.getAttribute( SchemaSymbols.ATT_ABSTRACT );
String blockSet = null;
Attr blockAttr = complexTypeDecl.getAttributeNode( SchemaSymbols.ATT_BLOCK );
if (blockAttr != null)
blockSet = blockAttr.getValue();
String finalSet = null;
Attr finalAttr = complexTypeDecl.getAttributeNode( SchemaSymbols.ATT_FINAL );
if (finalAttr != null)
finalSet = finalAttr.getValue();
String typeId = complexTypeDecl.getAttribute( SchemaSymbols.ATTVAL_ID );
String typeName = complexTypeDecl.getAttribute(SchemaSymbols.ATT_NAME);
String mixed = complexTypeDecl.getAttribute(SchemaSymbols.ATT_MIXED);
boolean isNamedType = false;
// ------------------------------------------------------------------
// Generate a type name, if one wasn't specified
// ------------------------------------------------------------------
if (typeName.equals("")) { // gensym a unique name
typeName = genAnonTypeName(complexTypeDecl);
}
if ( DEBUGGING )
System.out.println("traversing complex Type : " + typeName);
fCurrentTypeNameStack.push(typeName);
int typeNameIndex = fStringPool.addSymbol(typeName);
// ------------------------------------------------------------------
// Check if the type has already been registered
// ------------------------------------------------------------------
if (isTopLevel(complexTypeDecl)) {
String fullName = fTargetNSURIString+","+typeName;
ComplexTypeInfo temp = (ComplexTypeInfo) fComplexTypeRegistry.get(fullName);
if (temp != null ) {
// check for duplicate declarations
if (!forwardRef) {
if (temp.declSeen())
reportGenericSchemaError("sch-props-correct: Duplicate declaration for complexType " +
typeName);
else
temp.setDeclSeen();
}
return fStringPool.addSymbol(fullName);
}
else {
// check if the type is the name of a simple type
if (getDatatypeValidator(fTargetNSURIString,typeName)!=null)
reportGenericSchemaError("sch-props-correct: Duplicate type declaration - type is " +
typeName);
}
}
int scopeDefined = fScopeCount++;
int previousScope = fCurrentScope;
fCurrentScope = scopeDefined;
Element child = null;
ComplexTypeInfo typeInfo = new ComplexTypeInfo();
try {
// ------------------------------------------------------------------
// First, handle any ANNOTATION declaration and get next child
// ------------------------------------------------------------------
child = checkContent(complexTypeDecl,XUtil.getFirstChildElement(complexTypeDecl),
true);
// ------------------------------------------------------------------
// Process the content of the complex type declaration
// ------------------------------------------------------------------
if (child==null) {
//
// EMPTY complexType with complexContent
//
processComplexContent(typeNameIndex, child, typeInfo, null, false);
}
else {
String childName = child.getLocalName();
int index = -2;
if (childName.equals(SchemaSymbols.ELT_SIMPLECONTENT)) {
//
// SIMPLE CONTENT element
//
traverseSimpleContentDecl(typeNameIndex, child, typeInfo);
if (XUtil.getNextSiblingElement(child) != null)
throw new ComplexTypeRecoverableError(
"Invalid child following the simpleContent child in the complexType");
}
else if (childName.equals(SchemaSymbols.ELT_COMPLEXCONTENT)) {
//
// COMPLEX CONTENT element
//
traverseComplexContentDecl(typeNameIndex, child, typeInfo,
mixed.equals(SchemaSymbols.ATTVAL_TRUE) ? true:false);
if (XUtil.getNextSiblingElement(child) != null)
throw new ComplexTypeRecoverableError(
"Invalid child following the complexContent child in the complexType");
}
else {
//
// We must have ....
// GROUP, ALL, SEQUENCE or CHOICE, followed by optional attributes
// Note that it's possible that only attributes are specified.
//
processComplexContent(typeNameIndex, child, typeInfo, null,
mixed.equals(SchemaSymbols.ATTVAL_TRUE) ? true:false);
}
}
typeInfo.blockSet = parseBlockSet(blockSet);
// make sure block's value was absent, #all or in {extension, restriction}
if( (blockSet != null ) && !blockSet.equals("") &&
(!blockSet.equals(SchemaSymbols.ATTVAL_POUNDALL) &&
(((typeInfo.blockSet & SchemaSymbols.RESTRICTION) == 0) &&
((typeInfo.blockSet & SchemaSymbols.EXTENSION) == 0))))
throw new ComplexTypeRecoverableError("The values of the 'block' attribute of a complexType must be either #all or a list of 'restriction' and 'extension'; " + blockSet + " was found");
typeInfo.finalSet = parseFinalSet(finalSet);
// make sure final's value was absent, #all or in {extension, restriction}
if( (finalSet != null ) && !finalSet.equals("") &&
(!finalSet.equals(SchemaSymbols.ATTVAL_POUNDALL) &&
(((typeInfo.finalSet & SchemaSymbols.RESTRICTION) == 0) &&
((typeInfo.finalSet & SchemaSymbols.EXTENSION) == 0))))
throw new ComplexTypeRecoverableError("The values of the 'final' attribute of a complexType must be either #all or a list of 'restriction' and 'extension'; " + finalSet + " was found");
}
catch (ComplexTypeRecoverableError e) {
String message = e.getMessage();
handleComplexTypeError(message,typeNameIndex,typeInfo);
}
// ------------------------------------------------------------------
// Finish the setup of the typeInfo and register the type
// ------------------------------------------------------------------
typeInfo.scopeDefined = scopeDefined;
if (isAbstract.equals(SchemaSymbols.ATTVAL_TRUE))
typeInfo.setIsAbstractType();
if (!forwardRef)
typeInfo.setDeclSeen();
typeName = fTargetNSURIString + "," + typeName;
typeInfo.typeName = new String(typeName);
if ( DEBUGGING )
System.out.println(">>>add complex Type to Registry: " + typeName +
" baseDTValidator=" + typeInfo.baseDataTypeValidator +
" baseCTInfo=" + typeInfo.baseComplexTypeInfo +
" derivedBy=" + typeInfo.derivedBy +
" contentType=" + typeInfo.contentType +
" contentSpecHandle=" + typeInfo.contentSpecHandle +
" datatypeValidator=" + typeInfo.datatypeValidator +
" scopeDefined=" + typeInfo.scopeDefined);
fComplexTypeRegistry.put(typeName,typeInfo);
// ------------------------------------------------------------------
// Before exiting, restore the scope, mainly for nested anonymous types
// ------------------------------------------------------------------
fCurrentScope = previousScope;
fCurrentTypeNameStack.pop();
checkRecursingComplexType();
//set template element's typeInfo
fSchemaGrammar.setElementComplexTypeInfo(typeInfo.templateElementIndex, typeInfo);
typeNameIndex = fStringPool.addSymbol(typeName);
return typeNameIndex;
} // end traverseComplexTypeDecl
/**
* Traverse SimpleContent Declaration
*
* <simpleContent
* id = ID
* {any attributes with non-schema namespace...}>
*
* Content: (annotation? , (restriction | extension))
* </simpleContent>
*
* <restriction
* base = QNAME
* id = ID
* {any attributes with non-schema namespace...}>
*
* Content: (annotation?,(simpleType?, (minExclusive|minInclusive|maxExclusive
* | maxInclusive | totalDigits | fractionDigits | length | minLength
* | maxLength | encoding | period | duration | enumeration
* | pattern | whiteSpace)*) ? ,
* ((attribute | attributeGroup)* , anyAttribute?))
* </restriction>
*
* <extension
* base = QNAME
* id = ID
* {any attributes with non-schema namespace...}>
* Content: (annotation? , ((attribute | attributeGroup)* , anyAttribute?))
* </extension>
*
* @param typeNameIndex
* @param simpleContentTypeDecl
* @param typeInfo
* @return
*/
private void traverseSimpleContentDecl(int typeNameIndex,
Element simpleContentDecl, ComplexTypeInfo typeInfo)
throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(simpleContentDecl, scope);
String typeName = fStringPool.toString(typeNameIndex);
// -----------------------------------------------------------------------
// Get attributes.
// -----------------------------------------------------------------------
String simpleContentTypeId = simpleContentDecl.getAttribute(SchemaSymbols.ATTVAL_ID);
// -----------------------------------------------------------------------
// Set the content type to be simple, and initialize content spec handle
// -----------------------------------------------------------------------
typeInfo.contentType = XMLElementDecl.TYPE_SIMPLE;
typeInfo.contentSpecHandle = -1;
Element simpleContent = checkContent(simpleContentDecl,
XUtil.getFirstChildElement(simpleContentDecl),false);
// If there are no children, return
if (simpleContent==null) {
throw new ComplexTypeRecoverableError();
}
// General Attribute Checking
attrValues = fGeneralAttrCheck.checkAttributes(simpleContent, scope);
// -----------------------------------------------------------------------
// The content should be either "restriction" or "extension"
// -----------------------------------------------------------------------
String simpleContentName = simpleContent.getLocalName();
if (simpleContentName.equals(SchemaSymbols.ELT_RESTRICTION))
typeInfo.derivedBy = SchemaSymbols.RESTRICTION;
else if (simpleContentName.equals(SchemaSymbols.ELT_EXTENSION))
typeInfo.derivedBy = SchemaSymbols.EXTENSION;
else {
throw new ComplexTypeRecoverableError(
"The content of the simpleContent element is invalid. The " +
"content must be RESTRICTION or EXTENSION");
}
// -----------------------------------------------------------------------
// Get the attributes of the restriction/extension element
// -----------------------------------------------------------------------
String base = simpleContent.getAttribute(SchemaSymbols.ATT_BASE);
String typeId = simpleContent.getAttribute(SchemaSymbols.ATTVAL_ID);
// -----------------------------------------------------------------------
// Skip over any annotations in the restriction or extension elements
// -----------------------------------------------------------------------
Element content = checkContent(simpleContent,
XUtil.getFirstChildElement(simpleContent),true);
// -----------------------------------------------------------------------
// Handle the base type name
// -----------------------------------------------------------------------
if (base.length() == 0) {
throw new ComplexTypeRecoverableError(
"The BASE attribute must be specified for the " +
"RESTRICTION or EXTENSION element");
}
QName baseQName = parseBase(base);
// check if we're extending a simpleType which has a "final" setting which precludes this
Integer finalValue = (baseQName.uri == StringPool.EMPTY_STRING?
((Integer)fSimpleTypeFinalRegistry.get(fStringPool.toString(baseQName.localpart))):
((Integer)fSimpleTypeFinalRegistry.get(fStringPool.toString(baseQName.uri) + "," +fStringPool.toString(baseQName.localpart))));
if(finalValue != null &&
(finalValue.intValue() == typeInfo.derivedBy))
throw new ComplexTypeRecoverableError(
"The simpleType " + base + " that " + typeName + " uses has a value of \"final\" which does not permit extension");
processBaseTypeInfo(baseQName,typeInfo);
// check that the base isn't a complex type with complex content
if (typeInfo.baseComplexTypeInfo != null) {
if (typeInfo.baseComplexTypeInfo.contentType != XMLElementDecl.TYPE_SIMPLE) {
throw new ComplexTypeRecoverableError(
"The type '"+ base +"' specified as the " +
"base in the simpleContent element must not have complexContent");
}
}
// -----------------------------------------------------------------------
// Process the content of the derivation
// -----------------------------------------------------------------------
Element attrNode = null;
//
// RESTRICTION
//
if (typeInfo.derivedBy==SchemaSymbols.RESTRICTION) {
//
//Schema Spec : Complex Type Definition Properties Correct : 2
//
if (typeInfo.baseDataTypeValidator != null) {
throw new ComplexTypeRecoverableError(
"ct-props-correct.2: The type '" + base +"' is a simple type. It cannot be used in a "+
"derivation by RESTRICTION for a complexType");
}
else {
typeInfo.baseDataTypeValidator = typeInfo.baseComplexTypeInfo.datatypeValidator;
}
//
// Check that the base's final set does not include RESTRICTION
//
if((typeInfo.baseComplexTypeInfo.finalSet & SchemaSymbols.RESTRICTION) != 0) {
throw new ComplexTypeRecoverableError("Derivation by restriction is forbidden by either the base type " + base + " or the schema");
}
// -----------------------------------------------------------------------
// There may be a simple type definition in the restriction element
// The data type validator will be based on it, if specified
// -----------------------------------------------------------------------
if (content.getLocalName().equals(SchemaSymbols.ELT_SIMPLETYPE )) {
int simpleTypeNameIndex = traverseSimpleTypeDecl(content);
if (simpleTypeNameIndex!=-1) {
DatatypeValidator dv=fDatatypeRegistry.getDatatypeValidator(
fStringPool.toString(simpleTypeNameIndex));
//check that this datatype validator is validly derived from the base
//according to derivation-ok-restriction 5.1.1
if (!checkSimpleTypeDerivationOK(dv,typeInfo.baseDataTypeValidator)) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.5.1.1: The content type is not a valid restriction of the content type of the base");
}
typeInfo.baseDataTypeValidator = dv;
content = XUtil.getNextSiblingElement(content);
}
else {
throw new ComplexTypeRecoverableError();
}
}
//
// Build up facet information
//
int numEnumerationLiterals = 0;
int numFacets = 0;
Hashtable facetData = new Hashtable();
Vector enumData = new Vector();
Element child;
// General Attribute Checking
scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable contentAttrs;
//REVISIT: there is a better way to do this,
for (child = content;
child != null && (child.getLocalName().equals(SchemaSymbols.ELT_MINEXCLUSIVE) ||
child.getLocalName().equals(SchemaSymbols.ELT_MININCLUSIVE) ||
child.getLocalName().equals(SchemaSymbols.ELT_MAXEXCLUSIVE) ||
child.getLocalName().equals(SchemaSymbols.ELT_MAXINCLUSIVE) ||
child.getLocalName().equals(SchemaSymbols.ELT_TOTALDIGITS) ||
child.getLocalName().equals(SchemaSymbols.ELT_FRACTIONDIGITS) ||
child.getLocalName().equals(SchemaSymbols.ELT_LENGTH) ||
child.getLocalName().equals(SchemaSymbols.ELT_MINLENGTH) ||
child.getLocalName().equals(SchemaSymbols.ELT_MAXLENGTH) ||
child.getLocalName().equals(SchemaSymbols.ELT_PERIOD) ||
child.getLocalName().equals(SchemaSymbols.ELT_DURATION) ||
child.getLocalName().equals(SchemaSymbols.ELT_ENUMERATION) ||
child.getLocalName().equals(SchemaSymbols.ELT_PATTERN) ||
child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION));
child = XUtil.getNextSiblingElement(child))
{
if ( child.getNodeType() == Node.ELEMENT_NODE ) {
Element facetElt = (Element) child;
// General Attribute Checking
contentAttrs = fGeneralAttrCheck.checkAttributes(facetElt, scope);
numFacets++;
if (facetElt.getLocalName().equals(SchemaSymbols.ELT_ENUMERATION)) {
numEnumerationLiterals++;
enumData.addElement(facetElt.getAttribute(SchemaSymbols.ATT_VALUE));
//Enumerations can have annotations ? ( 0 | 1 )
Element enumContent = XUtil.getFirstChildElement( facetElt );
if( enumContent != null &&
enumContent.getLocalName().equals
( SchemaSymbols.ELT_ANNOTATION )){
traverseAnnotationDecl( child );
}
// TO DO: if Jeff check in new changes to TraverseSimpleType, copy them over
}
else {
facetData.put(facetElt.getLocalName(),
facetElt.getAttribute( SchemaSymbols.ATT_VALUE ));
}
}
} // end of for loop thru facets
if (numEnumerationLiterals > 0) {
facetData.put(SchemaSymbols.ELT_ENUMERATION, enumData);
}
//
// If there were facets, create a new data type validator, otherwise
// the data type validator is from the base
//
if (numFacets > 0) {
try{
typeInfo.datatypeValidator = fDatatypeRegistry.createDatatypeValidator(
typeName,
typeInfo.baseDataTypeValidator, facetData, false);
} catch (Exception e) {
throw new ComplexTypeRecoverableError(e.getMessage());
}
}
else
typeInfo.datatypeValidator =
typeInfo.baseDataTypeValidator;
if (child != null) {
//
// Check that we have attributes
//
if (!isAttrOrAttrGroup(child)) {
throw new ComplexTypeRecoverableError(
"Invalid child in the RESTRICTION element of simpleContent");
}
else
attrNode = child;
}
} // end RESTRICTION
//
// EXTENSION
//
else {
if (typeInfo.baseComplexTypeInfo != null) {
typeInfo.baseDataTypeValidator = typeInfo.baseComplexTypeInfo.datatypeValidator;
//
// Check that the base's final set does not include EXTENSION
//
if((typeInfo.baseComplexTypeInfo.finalSet &
SchemaSymbols.EXTENSION) != 0) {
throw new ComplexTypeRecoverableError("Derivation by extension is forbidden by either the base type " + base + " or the schema");
}
}
typeInfo.datatypeValidator = typeInfo.baseDataTypeValidator;
//
// Look for attributes
//
if (content != null) {
//
// Check that we have attributes
//
if (!isAttrOrAttrGroup(content)) {
throw new ComplexTypeRecoverableError(
"Only annotations and attributes are allowed in the " +
"content of an EXTENSION element for a complexType with simpleContent");
}
else {
attrNode = content;
}
}
}
// -----------------------------------------------------------------------
// add a template element to the grammar element decl pool for the type
// -----------------------------------------------------------------------
int templateElementNameIndex = fStringPool.addSymbol("$"+typeName);
typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(
new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI),
(fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : fCurrentScope, typeInfo.scopeDefined,
typeInfo.contentType,
typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator);
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(
typeInfo.templateElementIndex);
// -----------------------------------------------------------------------
// Process attributes
// -----------------------------------------------------------------------
processAttributes(attrNode,baseQName,typeInfo);
if (XUtil.getNextSiblingElement(simpleContent) != null)
throw new ComplexTypeRecoverableError(
"Invalid child following the RESTRICTION or EXTENSION element in the " +
"complex type definition");
} // end traverseSimpleContentDecl
/**
* Traverse complexContent Declaration
*
* <complexContent
* id = ID
* mixed = boolean
* {any attributes with non-schema namespace...}>
*
* Content: (annotation? , (restriction | extension))
* </complexContent>
*
* <restriction
* base = QNAME
* id = ID
* {any attributes with non-schema namespace...}>
*
* Content: (annotation? , (group | all | choice | sequence)?,
* ((attribute | attributeGroup)* , anyAttribute?))
* </restriction>
*
* <extension
* base = QNAME
* id = ID
* {any attributes with non-schema namespace...}>
* Content: (annotation? , (group | all | choice | sequence)?,
* ((attribute | attributeGroup)* , anyAttribute?))
* </extension>
*
* @param typeNameIndex
* @param simpleContentTypeDecl
* @param typeInfo
* @param mixedOnComplexTypeDecl
* @return
*/
private void traverseComplexContentDecl(int typeNameIndex,
Element complexContentDecl, ComplexTypeInfo typeInfo,
boolean mixedOnComplexTypeDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(complexContentDecl, scope);
String typeName = fStringPool.toString(typeNameIndex);
// -----------------------------------------------------------------------
// Get the attributes
// -----------------------------------------------------------------------
String typeId = complexContentDecl.getAttribute(SchemaSymbols.ATTVAL_ID);
String mixed = complexContentDecl.getAttribute(SchemaSymbols.ATT_MIXED);
// -----------------------------------------------------------------------
// Determine whether the content is mixed, or element-only
// Setting here overrides any setting on the complex type decl
// -----------------------------------------------------------------------
boolean isMixed = mixedOnComplexTypeDecl;
if (mixed.equals(SchemaSymbols.ATTVAL_TRUE))
isMixed = true;
else if (mixed.equals(SchemaSymbols.ATTVAL_FALSE))
isMixed = false;
// -----------------------------------------------------------------------
// Since the type must have complex content, set the simple type validators
// to null
// -----------------------------------------------------------------------
typeInfo.datatypeValidator = null;
typeInfo.baseDataTypeValidator = null;
Element complexContent = checkContent(complexContentDecl,
XUtil.getFirstChildElement(complexContentDecl),false);
// If there are no children, return
if (complexContent==null) {
throw new ComplexTypeRecoverableError();
}
// -----------------------------------------------------------------------
// The content should be either "restriction" or "extension"
// -----------------------------------------------------------------------
String complexContentName = complexContent.getLocalName();
if (complexContentName.equals(SchemaSymbols.ELT_RESTRICTION))
typeInfo.derivedBy = SchemaSymbols.RESTRICTION;
else if (complexContentName.equals(SchemaSymbols.ELT_EXTENSION))
typeInfo.derivedBy = SchemaSymbols.EXTENSION;
else {
throw new ComplexTypeRecoverableError(
"The content of the complexContent element is invalid. " +
"The content must be RESTRICTION or EXTENSION");
}
// Get the attributes of the restriction/extension element
String base = complexContent.getAttribute(SchemaSymbols.ATT_BASE);
String complexContentTypeId=complexContent.getAttribute(SchemaSymbols.ATTVAL_ID);
// Skip over any annotations in the restriction or extension elements
Element content = checkContent(complexContent,
XUtil.getFirstChildElement(complexContent),true);
// -----------------------------------------------------------------------
// Handle the base type name
// -----------------------------------------------------------------------
if (base.length() == 0) {
throw new ComplexTypeRecoverableError(
"The BASE attribute must be specified for the " +
"RESTRICTION or EXTENSION element");
}
QName baseQName = parseBase(base);
// -------------------------------------------------------------
// check if the base is "anyType"
// -------------------------------------------------------------
String baseTypeURI = fStringPool.toString(baseQName.uri);
String baseLocalName = fStringPool.toString(baseQName.localpart);
if (!(baseTypeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) &&
baseLocalName.equals("anyType"))) {
processBaseTypeInfo(baseQName,typeInfo);
//Check that the base is a complex type
if (typeInfo.baseComplexTypeInfo == null) {
throw new ComplexTypeRecoverableError(
"The base type specified in the complexContent element must be a complexType");
}
}
// -----------------------------------------------------------------------
// Process the elements that make up the content
// -----------------------------------------------------------------------
processComplexContent(typeNameIndex,content,typeInfo,baseQName,isMixed);
if (XUtil.getNextSiblingElement(complexContent) != null)
throw new ComplexTypeRecoverableError(
"Invalid child following the RESTRICTION or EXTENSION element in the " +
"complex type definition");
} // end traverseComplexContentDecl
/**
* Handle complexType error
*
* @param message
* @param typeNameIndex
* @param typeInfo
* @return
*/
private void handleComplexTypeError(String message, int typeNameIndex,
ComplexTypeInfo typeInfo) throws Exception {
String typeName = fStringPool.toString(typeNameIndex);
if (message != null) {
if (typeName.startsWith("#"))
reportGenericSchemaError("Anonymous complexType: " + message);
else
reportGenericSchemaError("ComplexType '" + typeName + "': " + message);
}
//
// Mock up the typeInfo structure so that there won't be problems during
// validation
//
typeInfo.contentType = XMLElementDecl.TYPE_ANY; // this should match anything
typeInfo.contentSpecHandle = -1;
typeInfo.derivedBy = 0;
typeInfo.datatypeValidator = null;
typeInfo.attlistHead = -1;
int templateElementNameIndex = fStringPool.addSymbol("$"+typeName);
typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(
new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI),
(fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : fCurrentScope, typeInfo.scopeDefined,
typeInfo.contentType,
typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator);
return;
}
/**
* Generate a name for an anonymous type
*
* @param Element
* @return String
*/
private String genAnonTypeName(Element complexTypeDecl) throws Exception {
String typeName;
// If the anonymous type is not nested within another type, we can
// simply assign the type a numbered name
//
if (fCurrentTypeNameStack.empty())
typeName = "#"+fAnonTypeCount++;
// Otherwise, we must generate a name that can be looked up later
// Do this by concatenating outer type names with the name of the parent
// element
else {
String parentName = ((Element)complexTypeDecl.getParentNode()).getAttribute(
SchemaSymbols.ATT_NAME);
typeName = parentName + "_AnonType";
int index=fCurrentTypeNameStack.size() -1;
for (int i = index; i > -1; i--) {
String parentType = (String)fCurrentTypeNameStack.elementAt(i);
typeName = parentType + "_" + typeName;
if (!(parentType.startsWith("#")))
break;
}
typeName = "#" + typeName;
}
return typeName;
}
/**
* Parse base string
*
* @param base
* @return QName
*/
private QName parseBase(String base) throws Exception {
String prefix = "";
String localpart = base;
int colonptr = base.indexOf(":");
if ( colonptr > 0) {
prefix = base.substring(0,colonptr);
localpart = base.substring(colonptr+1);
}
int nameIndex = fStringPool.addSymbol(base);
int prefixIndex = fStringPool.addSymbol(prefix);
int localpartIndex = fStringPool.addSymbol(localpart);
int URIindex = fStringPool.addSymbol(resolvePrefixToURI(prefix));
return new QName(prefixIndex,localpartIndex,nameIndex,URIindex);
}
/**
* Check if base is from another schema
*
* @param baseName
* @return boolean
*/
private boolean baseFromAnotherSchema(QName baseName) throws Exception {
String typeURI = fStringPool.toString(baseName.uri);
if ( ! typeURI.equals(fTargetNSURIString)
&& ! typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& typeURI.length() != 0 )
//REVISIT, !!!! a hack: for schema that has no
//target namespace, e.g. personal-schema.xml
return true;
else
return false;
}
/**
* Process "base" information for a complexType
*
* @param baseTypeInfo
* @param baseName
* @param typeInfo
* @return
*/
private void processBaseTypeInfo(QName baseName, ComplexTypeInfo typeInfo) throws Exception {
ComplexTypeInfo baseComplexTypeInfo = null;
DatatypeValidator baseDTValidator = null;
String typeURI = fStringPool.toString(baseName.uri);
String localpart = fStringPool.toString(baseName.localpart);
String base = fStringPool.toString(baseName.rawname);
// -------------------------------------------------------------
// check if the base type is from another schema
// -------------------------------------------------------------
if (baseFromAnotherSchema(baseName)) {
baseComplexTypeInfo = getTypeInfoFromNS(typeURI, localpart);
if (baseComplexTypeInfo == null) {
baseDTValidator = getTypeValidatorFromNS(typeURI, localpart);
if (baseDTValidator == null) {
throw new ComplexTypeRecoverableError(
"Could not find base type " +localpart
+ " in schema " + typeURI);
}
}
}
// -------------------------------------------------------------
// type must be from same schema
// -------------------------------------------------------------
else {
String fullBaseName = typeURI+","+localpart;
// assume the base is a complexType and try to locate the base type first
baseComplexTypeInfo= (ComplexTypeInfo) fComplexTypeRegistry.get(fullBaseName);
// if not found, 2 possibilities:
// 1: ComplexType in question has not been compiled yet;
// 2: base is SimpleTYpe;
if (baseComplexTypeInfo == null) {
baseDTValidator = getDatatypeValidator(typeURI, localpart);
if (baseDTValidator == null) {
int baseTypeSymbol;
Element baseTypeNode = getTopLevelComponentByName(
SchemaSymbols.ELT_COMPLEXTYPE,localpart);
if (baseTypeNode != null) {
// Before traversing the base, make sure we're not already
// doing so..
// ct-props-correct 3
if (fCurrentTypeNameStack.search((Object)localpart) > - 1) {
throw new ComplexTypeRecoverableError(
"ct-props-correct.3: Recursive type definition");
}
baseTypeSymbol = traverseComplexTypeDecl( baseTypeNode, true );
baseComplexTypeInfo = (ComplexTypeInfo)
fComplexTypeRegistry.get(fStringPool.toString(baseTypeSymbol));
//REVISIT: should it be fullBaseName;
}
else {
baseTypeNode = getTopLevelComponentByName(
SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (baseTypeNode != null) {
baseTypeSymbol = traverseSimpleTypeDecl( baseTypeNode );
baseDTValidator = getDatatypeValidator(typeURI, localpart);
if (baseDTValidator == null) {
//TO DO: signal error here.
}
}
else {
throw new ComplexTypeRecoverableError(
"Base type could not be found : " + base);
}
}
}
}
} // end else (type must be from same schema)
typeInfo.baseComplexTypeInfo = baseComplexTypeInfo;
typeInfo.baseDataTypeValidator = baseDTValidator;
} // end processBaseTypeInfo
/**
* Process content which is complex
*
* (group | all | choice | sequence) ? ,
* ((attribute | attributeGroup)* , anyAttribute?))
*
* @param typeNameIndex
* @param complexContentChild
* @param typeInfo
* @return
*/
private void processComplexContent(int typeNameIndex,
Element complexContentChild, ComplexTypeInfo typeInfo, QName baseName,
boolean isMixed) throws Exception {
Element attrNode = null;
int index=-2;
String typeName = fStringPool.toString(typeNameIndex);
if (complexContentChild != null) {
// -------------------------------------------------------------
// GROUP, ALL, SEQUENCE or CHOICE, followed by attributes, if specified.
// Note that it's possible that only attributes are specified.
// -------------------------------------------------------------
String childName = complexContentChild.getLocalName();
if (childName.equals(SchemaSymbols.ELT_GROUP)) {
int groupIndex = traverseGroupDecl(complexContentChild);
index = handleOccurrences(groupIndex,
complexContentChild,
hasAllContent(groupIndex) ? GROUP_REF_WITH_ALL :
NOT_ALL_CONTEXT);
attrNode = XUtil.getNextSiblingElement(complexContentChild);
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = handleOccurrences(traverseSequence(complexContentChild),
complexContentChild);
attrNode = XUtil.getNextSiblingElement(complexContentChild);
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = handleOccurrences(traverseChoice(complexContentChild),
complexContentChild);
attrNode = XUtil.getNextSiblingElement(complexContentChild);
}
else if (childName.equals(SchemaSymbols.ELT_ALL)) {
index = handleOccurrences(traverseAll(complexContentChild),
complexContentChild, PROCESSING_ALL);
attrNode = XUtil.getNextSiblingElement(complexContentChild);
}
else if (isAttrOrAttrGroup(complexContentChild)) {
// reset the contentType
typeInfo.contentType = XMLElementDecl.TYPE_ANY;
attrNode = complexContentChild;
}
else {
throw new ComplexTypeRecoverableError(
"Invalid child '"+ childName +"' in the complex type");
}
}
typeInfo.contentSpecHandle = index;
// -----------------------------------------------------------------------
// Merge in information from base, if it exists
// -----------------------------------------------------------------------
if (typeInfo.baseComplexTypeInfo != null) {
int baseContentSpecHandle = typeInfo.baseComplexTypeInfo.contentSpecHandle;
//-------------------------------------------------------------
// RESTRICTION
//-------------------------------------------------------------
if (typeInfo.derivedBy == SchemaSymbols.RESTRICTION) {
// check to see if the baseType permits derivation by restriction
if((typeInfo.baseComplexTypeInfo.finalSet & SchemaSymbols.RESTRICTION) != 0)
throw new ComplexTypeRecoverableError("Derivation by restriction is forbidden by either the base type " + fStringPool.toString(baseName.localpart) + " or the schema");
// if the content is EMPTY, check that the base is correct
// according to derivation-ok-restriction 5.2
if (typeInfo.contentSpecHandle==-2) {
if (!(typeInfo.baseComplexTypeInfo.contentType==XMLElementDecl.TYPE_EMPTY ||
particleEmptiable(baseContentSpecHandle))) {
throw new ComplexTypeRecoverableError("derivation-ok-restrictoin.5.2 Content type of complexType is EMPTY but base is not EMPTY or does not have a particle which is emptiable");
}
}
//
// The hairy derivation by restriction particle constraints
// derivation-ok-restriction 5.3
//
else {
try {
checkParticleDerivationOK(typeInfo.contentSpecHandle,fCurrentScope,
baseContentSpecHandle,typeInfo.baseComplexTypeInfo.scopeDefined,
typeInfo.baseComplexTypeInfo);
}
catch (ParticleRecoverableError e) {
String message = e.getMessage();
throw new ComplexTypeRecoverableError(message);
}
}
}
//-------------------------------------------------------------
// EXTENSION
//-------------------------------------------------------------
else {
// check to see if the baseType permits derivation by extension
if((typeInfo.baseComplexTypeInfo.finalSet & SchemaSymbols.EXTENSION) != 0)
throw new ComplexTypeRecoverableError("cos-ct-extends.1.1: Derivation by extension is forbidden by either the base type " + fStringPool.toString(baseName.localpart) + " or the schema");
//
// Check if the contentType of the base is consistent with the new type
// cos-ct-extends.1.4.2.2
if (typeInfo.baseComplexTypeInfo.contentType != XMLElementDecl.TYPE_EMPTY) {
if (((typeInfo.baseComplexTypeInfo.contentType == XMLElementDecl.TYPE_CHILDREN) &&
isMixed) ||
((typeInfo.baseComplexTypeInfo.contentType == XMLElementDecl.TYPE_MIXED_COMPLEX) &&
!isMixed)) {
throw new ComplexTypeRecoverableError("cos-ct-extends.1.4.2.2.2.1: The content type of the base type " +
fStringPool.toString(baseName.localpart) + " and derived type " +
typeName + " must both be mixed or element-only");
}
}
//
// Compose the final content model by concatenating the base and the
// current in sequence
//
if (baseFromAnotherSchema(baseName)) {
String baseSchemaURI = fStringPool.toString(baseName.uri);
SchemaGrammar aGrammar= (SchemaGrammar) fGrammarResolver.getGrammar(
baseSchemaURI);
baseContentSpecHandle = importContentSpec(aGrammar, baseContentSpecHandle);
}
if (typeInfo.contentSpecHandle == -2) {
typeInfo.contentSpecHandle = baseContentSpecHandle;
}
else if (baseContentSpecHandle > -1) {
if (typeInfo.contentSpecHandle > -1 &&
(hasAllContent(typeInfo.contentSpecHandle) ||
hasAllContent(baseContentSpecHandle))) {
throw new ComplexTypeRecoverableError("cos-all-limited: An \"all\" model group that is part of a complex type definition must constitute the entire {content type} of the definition.");
}
typeInfo.contentSpecHandle =
fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ,
baseContentSpecHandle,
typeInfo.contentSpecHandle,
false);
}
//
// Check that there is a particle in the final content
// cos-ct-extends.1.4.2.1
// LM - commented out until I get a clarification from HT
//
if (typeInfo.contentSpecHandle <0) {
throw new ComplexTypeRecoverableError("cos-ct-extends.1.4.2.1: The content of a type derived by EXTENSION must contain a particle");
}
}
}
else {
typeInfo.derivedBy = 0;
}
// -------------------------------------------------------------
// Set the content type
// -------------------------------------------------------------
if (isMixed) {
// if there are no children, detect an error
// See the definition of content type in Structures 3.4.1
if (typeInfo.contentSpecHandle == -2) {
throw new ComplexTypeRecoverableError("Type '" + typeName + "': The content of a mixed complexType must not be empty");
}
else
typeInfo.contentType = XMLElementDecl.TYPE_MIXED_COMPLEX;
}
else if (typeInfo.contentSpecHandle == -2)
typeInfo.contentType = XMLElementDecl.TYPE_EMPTY;
else
typeInfo.contentType = XMLElementDecl.TYPE_CHILDREN;
// -------------------------------------------------------------
// add a template element to the grammar element decl pool.
// -------------------------------------------------------------
int templateElementNameIndex = fStringPool.addSymbol("$"+typeName);
typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(
new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI),
(fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : fCurrentScope, typeInfo.scopeDefined,
typeInfo.contentType,
typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator);
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(
typeInfo.templateElementIndex);
// -------------------------------------------------------------
// Now, check attributes and handle
// -------------------------------------------------------------
if (attrNode !=null) {
if (!isAttrOrAttrGroup(attrNode)) {
throw new ComplexTypeRecoverableError(
"Invalid child "+ attrNode.getLocalName() + " in the complexType or complexContent");
}
else
processAttributes(attrNode,baseName,typeInfo);
}
else if (typeInfo.baseComplexTypeInfo != null)
processAttributes(null,baseName,typeInfo);
} // end processComplexContent
/**
* Process attributes of a complex type
*
* @param attrNode
* @param typeInfo
* @return
*/
private void processAttributes(Element attrNode, QName baseName,
ComplexTypeInfo typeInfo) throws Exception {
XMLAttributeDecl attWildcard = null;
Vector anyAttDecls = new Vector();
Element child;
for (child = attrNode;
child != null;
child = XUtil.getNextSiblingElement(child)) {
String childName = child.getLocalName();
if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE)) {
traverseAttributeDecl(child, typeInfo, false);
}
else if ( childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) {
traverseAttributeGroupDecl(child,typeInfo,anyAttDecls);
}
else if ( childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) {
attWildcard = traverseAnyAttribute(child);
}
else {
throw new ComplexTypeRecoverableError( "Invalid child among the children of the complexType definition");
}
}
if (attWildcard != null) {
XMLAttributeDecl fromGroup = null;
final int count = anyAttDecls.size();
if ( count > 0) {
fromGroup = (XMLAttributeDecl) anyAttDecls.elementAt(0);
for (int i=1; i<count; i++) {
fromGroup = AWildCardIntersection(
fromGroup,(XMLAttributeDecl)anyAttDecls.elementAt(i));
}
}
if (fromGroup != null) {
int saveProcessContents = attWildcard.defaultType;
attWildcard = AWildCardIntersection(attWildcard, fromGroup);
attWildcard.defaultType = saveProcessContents;
}
}
else {
//REVISIT: unclear in the Scheme Structures 4.3.3 what to do in this case
if (anyAttDecls.size()>0) {
attWildcard = (XMLAttributeDecl)anyAttDecls.elementAt(0);
}
}
//
// merge in base type's attribute decls
//
XMLAttributeDecl baseAttWildcard = null;
ComplexTypeInfo baseTypeInfo = typeInfo.baseComplexTypeInfo;
SchemaGrammar aGrammar=null;
if (baseTypeInfo != null && baseTypeInfo.attlistHead > -1 ) {
int attDefIndex = baseTypeInfo.attlistHead;
aGrammar = fSchemaGrammar;
String baseTypeSchemaURI = baseFromAnotherSchema(baseName)?
fStringPool.toString(baseName.uri):null;
if (baseTypeSchemaURI != null) {
aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(baseTypeSchemaURI);
}
if (aGrammar == null) {
//reportGenericSchemaError("In complexType "+typeName+", can NOT find the grammar "+
// "with targetNamespace" + baseTypeSchemaURI+
// "for the base type");
}
else
while ( attDefIndex > -1 ) {
fTempAttributeDecl.clear();
aGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl);
if (fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_ANY
||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LIST
||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER ) {
if (attWildcard == null) {
baseAttWildcard = fTempAttributeDecl;
}
attDefIndex = aGrammar.getNextAttributeDeclIndex(attDefIndex);
continue;
}
// if found a duplicate, if it is derived by restriction,
// then skip the one from the base type
int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, fTempAttributeDecl.name);
if ( temp > -1) {
if (typeInfo.derivedBy==SchemaSymbols.EXTENSION) {
reportGenericSchemaError("Attribute that appeared in the base should nnot appear in a derivation by extension");
}
else {
attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex);
continue;
}
}
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
fTempAttributeDecl.name, fTempAttributeDecl.type,
fTempAttributeDecl.enumeration, fTempAttributeDecl.defaultType,
fTempAttributeDecl.defaultValue,
fTempAttributeDecl.datatypeValidator,
fTempAttributeDecl.list);
attDefIndex = aGrammar.getNextAttributeDeclIndex(attDefIndex);
}
}
// att wildcard will inserted after all attributes were processed
if (attWildcard != null) {
if (attWildcard.type != -1) {
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
attWildcard.name, attWildcard.type,
attWildcard.enumeration, attWildcard.defaultType,
attWildcard.defaultValue,
attWildcard.datatypeValidator,
attWildcard.list);
}
else {
//REVISIT: unclear in Schema spec if should report error here.
reportGenericSchemaError("The intensional intersection for {attribute wildcard}s must be expressible");
}
}
else if (baseAttWildcard != null) {
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
baseAttWildcard.name, baseAttWildcard.type,
baseAttWildcard.enumeration, baseAttWildcard.defaultType,
baseAttWildcard.defaultValue,
baseAttWildcard.datatypeValidator,
baseAttWildcard.list);
}
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex
(typeInfo.templateElementIndex);
// For derivation by restriction, ensure that the resulting attribute list
// satisfies the constraints in derivation-ok-restriction 2,3,4
if ((typeInfo.derivedBy==SchemaSymbols.RESTRICTION) &&
(typeInfo.attlistHead>-1 && baseTypeInfo != null)) {
checkAttributesDerivationOKRestriction(typeInfo.attlistHead,fSchemaGrammar,
attWildcard,baseTypeInfo.attlistHead,aGrammar,baseAttWildcard);
}
} // end processAttributes
// Check that the attributes of a type derived by restriction satisfy the
// constraints of derivation-ok-restriction
private void checkAttributesDerivationOKRestriction(int dAttListHead, SchemaGrammar dGrammar, XMLAttributeDecl dAttWildCard, int bAttListHead, SchemaGrammar bGrammar, XMLAttributeDecl bAttWildCard) throws ComplexTypeRecoverableError {
int attDefIndex = dAttListHead;
if (bAttListHead < 0) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.2: Base type definition does not have any attributes");
}
// Loop thru the attributes
while ( attDefIndex > -1 ) {
fTempAttributeDecl.clear();
dGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl);
if (isAWildCard(fTempAttributeDecl)) {
attDefIndex = dGrammar.getNextAttributeDeclIndex(attDefIndex);
continue;
}
int bAttDefIndex = bGrammar.findAttributeDecl(bAttListHead, fTempAttributeDecl.name);
if (bAttDefIndex > -1) {
fTemp2AttributeDecl.clear();
bGrammar.getAttributeDecl(bAttDefIndex, fTemp2AttributeDecl);
// derivation-ok-restriction. Constraint 2.1.1
if ((fTemp2AttributeDecl.defaultType &
XMLAttributeDecl.DEFAULT_TYPE_REQUIRED) > 0 &&
(fTempAttributeDecl.defaultType &
XMLAttributeDecl.DEFAULT_TYPE_REQUIRED) <= 0) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.1.1: Attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' in derivation has an inconsistent REQUIRED setting to that of attribute in base");
}
//
// derivation-ok-restriction. Constraint 2.1.2
//
if (!(checkSimpleTypeDerivationOK(
fTempAttributeDecl.datatypeValidator,
fTemp2AttributeDecl.datatypeValidator))) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.1.2: Type of attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' in derivation must be a restriction of type of attribute in base");
}
//
// derivation-ok-restriction. Constraint 2.1.3
//
if ((fTemp2AttributeDecl.defaultType &
XMLAttributeDecl.DEFAULT_TYPE_FIXED) > 0) {
if (!((fTempAttributeDecl.defaultType &
XMLAttributeDecl.DEFAULT_TYPE_FIXED) > 0) ||
!fTempAttributeDecl.defaultValue.equals(fTemp2AttributeDecl.defaultValue)) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.1.3: Attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' is either not fixed, or is not fixed with the same value as the attribute in the base");
}
}
}
else {
//
// derivation-ok-restriction. Constraint 2.2
//
if ((bAttWildCard==null) ||
!AWildCardAllowsNameSpace(bAttWildCard, dGrammar.getTargetNamespaceURI())) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.2: Attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' has a target namespace which is not valid with respect to a base type definition's wildcard or, the base does not contain a wildcard");
}
}
attDefIndex = dGrammar.getNextAttributeDeclIndex(attDefIndex);
}
// derivation-ok-restriction. Constraint 4
if (dAttWildCard!=null) {
if (bAttWildCard==null) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.4.1: An attribute wildcard is present in the derived type, but not the base");
}
if (!AWildCardSubset(dAttWildCard,bAttWildCard)) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.4.2: The attribute wildcard in the derived type is not a valid subset of that in the base");
}
}
}
private boolean isAttrOrAttrGroup(Element e)
{
String elementName = e.getLocalName();
if (elementName.equals(SchemaSymbols.ELT_ATTRIBUTE) ||
elementName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ||
elementName.equals(SchemaSymbols.ELT_ANYATTRIBUTE))
return true;
else
return false;
}
private void checkRecursingComplexType() throws Exception {
if ( fCurrentTypeNameStack.empty() ) {
if (! fElementRecurseComplex.isEmpty() ) {
int count= fElementRecurseComplex.size();
for (int i = 0; i<count; i++) {
ElementInfo eobj = (ElementInfo)fElementRecurseComplex.elementAt(i);
int elementIndex = eobj.elementIndex;
String typeName = eobj.typeName;
ComplexTypeInfo typeInfo =
(ComplexTypeInfo) fComplexTypeRegistry.get(fTargetNSURIString+","+typeName);
if (typeInfo==null) {
throw new Exception ( "Internal Error in void checkRecursingComplexType(). " );
}
else {
// update the element decl with info from the type
fSchemaGrammar.getElementDecl(elementIndex, fTempElementDecl);
fTempElementDecl.type = typeInfo.contentType;
fTempElementDecl.contentSpecIndex = typeInfo.contentSpecHandle;
fTempElementDecl.datatypeValidator = typeInfo.datatypeValidator;
fSchemaGrammar.setElementDecl(elementIndex, fTempElementDecl);
fSchemaGrammar.setFirstAttributeDeclIndex(elementIndex,
typeInfo.attlistHead);
fSchemaGrammar.setElementComplexTypeInfo(elementIndex,typeInfo);
}
}
fElementRecurseComplex.clear();
}
}
}
// Check that the particle defined by the derived ct tree is a valid restriction of
// that specified by baseContentSpecIndex. derivedScope and baseScope are the
// scopes of the particles, respectively. bInfo is supplied when the base particle
// is from a base type definition, and may be null - it helps determine other scopes
// that elements should be looked up in.
private void checkParticleDerivationOK(int derivedContentSpecIndex, int derivedScope, int baseContentSpecIndex, int baseScope, ComplexTypeInfo bInfo) throws Exception {
// Only do this if full checking is enabled
if (!fFullConstraintChecking)
return;
// Check for pointless occurrences of all, choice, sequence. The result is the
// contentspec which is not pointless. If the result is a non-pointless
// group, Vector is filled in with the children of interest
int csIndex1 = derivedContentSpecIndex;
fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1);
int csIndex2 = baseContentSpecIndex;
fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2);
Vector tempVector1 = new Vector();
Vector tempVector2 = new Vector();
if (tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_SEQ ||
tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_CHOICE ||
tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_ALL) {
csIndex1 = checkForPointlessOccurrences(csIndex1,tempVector1);
}
if (tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_SEQ ||
tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_CHOICE ||
tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_ALL) {
csIndex2 = checkForPointlessOccurrences(csIndex2,tempVector2);
}
fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1);
fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2);
switch (tempContentSpec1.type & 0x0f) {
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
switch (tempContentSpec2.type & 0x0f) {
// Elt:Elt NameAndTypeOK
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
checkNameAndTypeOK(csIndex1, derivedScope, csIndex2, baseScope, bInfo);
return;
}
// Elt:Any NSCompat
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_NS:
{
checkNSCompat(csIndex1, derivedScope, csIndex2);
return;
}
// Elt:All RecurseAsIfGroup
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
case XMLContentSpec.CONTENTSPECNODE_SEQ:
case XMLContentSpec.CONTENTSPECNODE_ALL:
{
checkRecurseAsIfGroup(csIndex1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
default:
{
throw new ParticleRecoverableError("internal Xerces error");
}
}
}
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_NS:
{
switch (tempContentSpec2.type & 0x0f) {
// Any:Any NSSubset
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_NS:
{
checkNSSubset(csIndex1, csIndex2);
return;
}
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
case XMLContentSpec.CONTENTSPECNODE_SEQ:
case XMLContentSpec.CONTENTSPECNODE_ALL:
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: Any: Choice,Seq,All,Elt");
}
default:
{
throw new ParticleRecoverableError("internal Xerces error");
}
}
}
case XMLContentSpec.CONTENTSPECNODE_ALL:
{
switch (tempContentSpec2.type & 0x0f) {
// All:Any NSRecurseCheckCardinality
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_NS:
{
checkNSRecurseCheckCardinality(csIndex1, tempVector1, derivedScope, csIndex2);
return;
}
case XMLContentSpec.CONTENTSPECNODE_ALL:
{
checkRecurse(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
case XMLContentSpec.CONTENTSPECNODE_SEQ:
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: All:Choice,Seq,Elt");
}
default:
{
throw new ParticleRecoverableError("internal Xerces error");
}
}
}
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
{
switch (tempContentSpec2.type & 0x0f) {
// Choice:Any NSRecurseCheckCardinality
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_NS:
{
checkNSRecurseCheckCardinality(csIndex1, tempVector1, derivedScope, csIndex2);
return;
}
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
{
checkRecurseLax(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
case XMLContentSpec.CONTENTSPECNODE_ALL:
case XMLContentSpec.CONTENTSPECNODE_SEQ:
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: Choice:All,Seq,Leaf");
}
default:
{
throw new ParticleRecoverableError("internal Xerces error");
}
}
}
case XMLContentSpec.CONTENTSPECNODE_SEQ:
{
switch (tempContentSpec2.type & 0x0f) {
// Choice:Any NSRecurseCheckCardinality
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_NS:
{
checkNSRecurseCheckCardinality(csIndex1, tempVector1, derivedScope, csIndex2);
return;
}
case XMLContentSpec.CONTENTSPECNODE_ALL:
{
checkRecurseUnordered(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
case XMLContentSpec.CONTENTSPECNODE_SEQ:
{
checkRecurse(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
{
checkMapAndSum(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: Seq:Elt");
}
default:
{
throw new ParticleRecoverableError("internal Xerces error");
}
}
}
}
}
private int checkForPointlessOccurrences(int csIndex, Vector tempVector) {
// Note: instead of using a Vector, we should use a growable array of int.
// To be cleaned up in release 1.4.1. (LM)
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
if (tempContentSpec1.otherValue == -2) {
gatherChildren(tempContentSpec1.type,tempContentSpec1.value,tempVector);
if (tempVector.size() == 1) {
Integer returnVal = (Integer)(tempVector.elementAt(0));
return returnVal.intValue();
}
}
int type = tempContentSpec1.type;
int value = tempContentSpec1.value;
int otherValue = tempContentSpec1.otherValue;
gatherChildren(type,value, tempVector);
gatherChildren(type,otherValue, tempVector);
return csIndex;
}
private void gatherChildren(int parentType, int csIndex, Vector tempVector) {
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
int min = fSchemaGrammar.getContentSpecMinOccurs(csIndex);
int max = fSchemaGrammar.getContentSpecMaxOccurs(csIndex);
int left = tempContentSpec1.value;
int right = tempContentSpec1.otherValue;
int type = tempContentSpec1.type;
if (type == XMLContentSpec.CONTENTSPECNODE_LEAF ||
(type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY ||
(type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY_NS ||
(type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER ) {
tempVector.addElement(new Integer(csIndex));
}
else if (! (min==1 && max==1)) {
tempVector.addElement(new Integer(csIndex));
}
else if (right == -2) {
gatherChildren(type,left,tempVector);
}
else if (parentType == type) {
gatherChildren(type,left,tempVector);
gatherChildren(type,right,tempVector);
}
else {
tempVector.addElement(new Integer(csIndex));
}
}
private void checkNameAndTypeOK(int csIndex1, int derivedScope, int csIndex2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1);
fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2);
int localpart1 = tempContentSpec1.value;
int uri1 = tempContentSpec1.otherValue;
int localpart2 = tempContentSpec2.value;
int uri2 = tempContentSpec2.otherValue;
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
//start the checking...
if (!(localpart1==localpart2 && uri1==uri2)) {
// we have non-matching names. Check substitution groups.
if (fSComp == null)
fSComp = new SubstitutionGroupComparator(fGrammarResolver,fStringPool,fErrorReporter);
if (!checkSubstitutionGroups(localpart1,uri1,localpart2,uri2))
throw new ParticleRecoverableError("rcase-nameAndTypeOK.1: Element name/uri in restriction does not match that of corresponding base element");
}
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.3: Element occurrence range not a restriction of base element's range: element is " + fStringPool.toString(localpart1));
}
SchemaGrammar aGrammar = fSchemaGrammar;
// get the element decl indices for the remainder...
String schemaURI = fStringPool.toString(uri1);
if ( !schemaURI.equals(fTargetNSURIString)
&& schemaURI.length() != 0 )
aGrammar= (SchemaGrammar) fGrammarResolver.getGrammar(schemaURI);
int eltndx1 = findElement(derivedScope, localpart1, aGrammar, null);
if (eltndx1 < 0)
return;
int eltndx2 = findElement(baseScope, localpart2, aGrammar, bInfo);
if (eltndx2 < 0)
return;
int miscFlags1 = ((SchemaGrammar) aGrammar).getElementDeclMiscFlags(eltndx1);
int miscFlags2 = ((SchemaGrammar) aGrammar).getElementDeclMiscFlags(eltndx2);
boolean element1IsNillable = (miscFlags1 & SchemaSymbols.NILLABLE) !=0;
boolean element2IsNillable = (miscFlags2 & SchemaSymbols.NILLABLE) !=0;
boolean element2IsFixed = (miscFlags2 & SchemaSymbols.FIXED) !=0;
boolean element1IsFixed = (miscFlags1 & SchemaSymbols.FIXED) !=0;
String element1Value = aGrammar.getElementDefaultValue(eltndx1);
String element2Value = aGrammar.getElementDefaultValue(eltndx2);
if (! (element2IsNillable || !element1IsNillable)) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.2: Element " +fStringPool.toString(localpart1) + " is nillable in the restriction but not the base");
}
if (! (element2Value == null || !element2IsFixed ||
(element1IsFixed && element1Value.equals(element2Value)))) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.4: Element " +fStringPool.toString(localpart1) + " is either not fixed, or is not fixed with the same value as in the base");
}
// check disallowed substitutions
int blockSet1 = ((SchemaGrammar) aGrammar).getElementDeclBlockSet(eltndx1);
int blockSet2 = ((SchemaGrammar) aGrammar).getElementDeclBlockSet(eltndx2);
if (((blockSet1 & blockSet2)!=blockSet2) ||
(blockSet1==0 && blockSet2!=0))
throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Element " +fStringPool.toString(localpart1) + "'s disallowed subsitutions are not a superset of those of the base element's");
// Need element decls for the remainder of the checks
aGrammar.getElementDecl(eltndx1, fTempElementDecl);
aGrammar.getElementDecl(eltndx2, fTempElementDecl2);
// check identity constraints
checkIDConstraintRestriction(fTempElementDecl, fTempElementDecl2, aGrammar, localpart1, localpart2);
// check that the derived element's type is derived from the base's. - TO BE DONE
checkTypesOK(fTempElementDecl,fTempElementDecl2,eltndx1,eltndx2,aGrammar,fStringPool.toString(localpart1));
}
private void checkTypesOK(XMLElementDecl derived, XMLElementDecl base, int dndx, int bndx, SchemaGrammar aGrammar, String elementName) throws Exception {
ComplexTypeInfo tempType=((SchemaGrammar)aGrammar).getElementComplexTypeInfo(dndx);
if (derived.type == XMLElementDecl.TYPE_SIMPLE ) {
if (base.type != XMLElementDecl.TYPE_SIMPLE)
throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derive from that of the base");
if (tempType == null) {
if (!(checkSimpleTypeDerivationOK(derived.datatypeValidator,
base.datatypeValidator)))
throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derives from that of the base");
return;
}
}
ComplexTypeInfo bType=((SchemaGrammar)aGrammar).getElementComplexTypeInfo(bndx);
for(; tempType != null; tempType = tempType.baseComplexTypeInfo) {
if (tempType.derivedBy != SchemaSymbols.RESTRICTION) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derives from that of the base");
}
if (tempType.typeName.equals(bType.typeName))
break;
}
if(tempType == null) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derives from that of the base");
}
}
private void checkIDConstraintRestriction(XMLElementDecl derivedElemDecl, XMLElementDecl baseElemDecl,
SchemaGrammar grammar, int derivedElemName, int baseElemName) throws Exception {
// this method throws no errors if the ID constraints on
// the derived element are a logical subset of those on the
// base element--that is, those that are present are
// identical to ones in the base element.
Vector derivedUnique = derivedElemDecl.unique;
Vector baseUnique = baseElemDecl.unique;
if(derivedUnique.size() > baseUnique.size()) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has fewer <unique> Identity Constraints than the base element"+
fStringPool.toString(baseElemName));
} else {
boolean found = true;
for(int i=0; i<derivedUnique.size() && found; i++) {
Unique id = (Unique)derivedUnique.elementAt(i);
found = false;
for(int j=0; j<baseUnique.size(); j++) {
if(id.equals((Unique)baseUnique.elementAt(j))) {
found = true;
break;
}
}
}
if(!found) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has a <unique> Identity Constraint that does not appear on the base element"+
fStringPool.toString(baseElemName));
}
}
Vector derivedKey = derivedElemDecl.key;
Vector baseKey = baseElemDecl.key;
if(derivedKey.size() > baseKey.size()) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has fewer <key> Identity Constraints than the base element"+
fStringPool.toString(baseElemName));
} else {
boolean found = true;
for(int i=0; i<derivedKey.size() && found; i++) {
Key id = (Key)derivedKey.elementAt(i);
found = false;
for(int j=0; j<baseKey.size(); j++) {
if(id.equals((Key)baseKey.elementAt(j))) {
found = true;
break;
}
}
}
if(!found) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has a <key> Identity Constraint that does not appear on the base element"+
fStringPool.toString(baseElemName));
}
}
Vector derivedKeyRef = derivedElemDecl.keyRef;
Vector baseKeyRef = baseElemDecl.keyRef;
if(derivedKeyRef.size() > baseKeyRef.size()) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has fewer <keyref> Identity Constraints than the base element"+
fStringPool.toString(baseElemName));
} else {
boolean found = true;
for(int i=0; i<derivedKeyRef.size() && found; i++) {
KeyRef id = (KeyRef)derivedKeyRef.elementAt(i);
found = false;
for(int j=0; j<baseKeyRef.size(); j++) {
if(id.equals((KeyRef)baseKeyRef.elementAt(j))) {
found = true;
break;
}
}
}
if(!found) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has a <keyref> Identity Constraint that does not appear on the base element"+
fStringPool.toString(baseElemName));
}
}
} // checkIDConstraintRestriction
private boolean checkSubstitutionGroups(int local1, int uri1, int local2, int uri2)
throws Exception {
// check if either name is in the other's substitution group
QName name1 = new QName(-1,local1,local1,uri1);
QName name2 = new QName(-1,local2,local2,uri2);
if (fSComp.isEquivalentTo(name1,name2) ||
fSComp.isEquivalentTo(name2,name1))
return true;
else
return false;
}
private boolean checkOccurrenceRange(int min1, int max1, int min2, int max2) {
if ((min1 >= min2) &&
((max2==SchemaSymbols.OCCURRENCE_UNBOUNDED) || (max1!=SchemaSymbols.OCCURRENCE_UNBOUNDED && max1<=max2)))
return true;
else
return false;
}
private int findElement(int scope, int nameIndex, SchemaGrammar gr, ComplexTypeInfo bInfo) {
// check for element at given scope first
int elementDeclIndex = gr.getElementDeclIndex(nameIndex,scope);
// if not found, check at global scope
if (elementDeclIndex == -1) {
elementDeclIndex = gr.getElementDeclIndex(nameIndex, -1);
// if still not found, and base is specified, look it up there
if (elementDeclIndex == -1 && bInfo != null) {
ComplexTypeInfo baseInfo = bInfo;
while (baseInfo != null) {
elementDeclIndex = gr.getElementDeclIndex(nameIndex,baseInfo.scopeDefined);
if (elementDeclIndex > -1)
break;
baseInfo = baseInfo.baseComplexTypeInfo;
}
}
}
return elementDeclIndex;
}
private void checkNSCompat(int csIndex1, int derivedScope, int csIndex2) throws Exception {
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-NSCompat.2: Element occurrence range not a restriction of base any element's range");
}
fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1);
int uri = tempContentSpec1.otherValue;
// check wildcard subset
if (!wildcardEltAllowsNamespace(csIndex2, uri))
throw new ParticleRecoverableError("rcase-NSCompat.1: Element's namespace not allowed by wildcard in base");
}
private boolean wildcardEltAllowsNamespace(int wildcardNode, int uriIndex) {
fSchemaGrammar.getContentSpec(wildcardNode, tempContentSpec1);
if ((tempContentSpec1.type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY)
return true;
if ((tempContentSpec1.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_NS) {
if (uriIndex == tempContentSpec1.otherValue)
return true;
}
else { // must be ANY_OTHER
if (uriIndex != tempContentSpec1.otherValue && uriIndex != StringPool.EMPTY_STRING)
return true;
}
return false;
}
private void checkNSSubset(int csIndex1, int csIndex2) throws Exception {
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-NSSubset.2: Wildcard's occurrence range not a restriction of base wildcard's range");
}
if (!wildcardEltSubset(csIndex1, csIndex2))
throw new ParticleRecoverableError("rcase-NSSubset.1: Wildcard is not a subset of corresponding wildcard in base");
}
private boolean wildcardEltSubset(int wildcardNode, int wildcardBaseNode) {
fSchemaGrammar.getContentSpec(wildcardNode, tempContentSpec1);
fSchemaGrammar.getContentSpec(wildcardBaseNode, tempContentSpec2);
if ((tempContentSpec2.type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY)
return true;
if ((tempContentSpec1.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_OTHER) {
if ((tempContentSpec2.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_OTHER &&
tempContentSpec1.otherValue == tempContentSpec2.otherValue)
return true;
}
if ((tempContentSpec1.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_NS) {
if ((tempContentSpec2.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_NS &&
tempContentSpec1.otherValue == tempContentSpec2.otherValue)
return true;
if ((tempContentSpec2.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_OTHER &&
tempContentSpec1.otherValue != tempContentSpec2.otherValue)
return true;
}
return false;
}
private void checkRecurseAsIfGroup(int csIndex1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2);
// Treat the element as if it were in a group of the same type as csindex2
int indexOfGrp=fSchemaGrammar.addContentSpecNode(tempContentSpec2.type,
csIndex1,-2, false);
Vector tmpVector = new Vector();
tmpVector.addElement(new Integer(csIndex1));
if (tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_ALL ||
tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_SEQ)
checkRecurse(indexOfGrp, tmpVector, derivedScope, csIndex2,
tempVector2, baseScope, bInfo);
else
checkRecurseLax(indexOfGrp, tmpVector, derivedScope, csIndex2,
tempVector2, baseScope, bInfo);
tmpVector = null;
}
private void checkNSRecurseCheckCardinality(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2) throws Exception {
// Implement total range check
int min1 = minEffectiveTotalRange(csIndex1);
int max1 = maxEffectiveTotalRange(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-NSSubset.2: Wildcard's occurrence range not a restriction of base wildcard's range");
}
if (!wildcardEltSubset(csIndex1, csIndex2))
throw new ParticleRecoverableError("rcase-NSSubset.1: Wildcard is not a subset of corresponding wildcard in base");
// Check that each member of the group is a valid restriction of the wildcard
int count = tempVector1.size();
for (int i = 0; i < count; i++) {
Integer particle1 = (Integer)tempVector1.elementAt(i);
checkParticleDerivationOK(particle1.intValue(),derivedScope,csIndex2,-1,null);
}
}
private void checkRecurse(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-Recurse.1: Occurrence range of group is not a valid restriction of occurence range of base group");
}
int count1= tempVector1.size();
int count2= tempVector2.size();
int current = 0;
label: for (int i = 0; i<count1; i++) {
Integer particle1 = (Integer)tempVector1.elementAt(i);
for (int j = current; j<count2; j++) {
Integer particle2 = (Integer)tempVector2.elementAt(j);
current +=1;
try {
checkParticleDerivationOK(particle1.intValue(),derivedScope,
particle2.intValue(), baseScope, bInfo);
continue label;
}
catch (ParticleRecoverableError e) {
if (!particleEmptiable(particle2.intValue()))
throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles");
}
}
throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles");
}
// Now, see if there are some elements in the base we didn't match up
for (int j=current; j < count2; j++) {
Integer particle2 = (Integer)tempVector2.elementAt(j);
if (!particleEmptiable(particle2.intValue())) {
throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles");
}
}
}
private void checkRecurseUnordered(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-RecurseUnordered.1: Occurrence range of group is not a valid restriction of occurence range of base group");
}
int count1= tempVector1.size();
int count2 = tempVector2.size();
boolean foundIt[] = new boolean[count2];
label: for (int i = 0; i<count1; i++) {
Integer particle1 = (Integer)tempVector1.elementAt(i);
for (int j = 0; j<count2; j++) {
Integer particle2 = (Integer)tempVector2.elementAt(j);
try {
checkParticleDerivationOK(particle1.intValue(),derivedScope,
particle2.intValue(), baseScope, bInfo);
if (foundIt[j])
throw new ParticleRecoverableError("rcase-RecurseUnordered.2: There is not a complete functional mapping between the particles");
else
foundIt[j]=true;
continue label;
}
catch (ParticleRecoverableError e) {
}
}
// didn't find a match. Detect an error
throw new ParticleRecoverableError("rcase-RecurseUnordered.2: There is not a complete functional mapping between the particles");
}
}
private void checkRecurseLax(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-RecurseLax.1: Occurrence range of group is not a valid restriction of occurence range of base group");
}
int count1= tempVector1.size();
int count2 = tempVector2.size();
int current = 0;
label: for (int i = 0; i<count1; i++) {
Integer particle1 = (Integer)tempVector1.elementAt(i);
for (int j = current; j<count2; j++) {
Integer particle2 = (Integer)tempVector2.elementAt(j);
current +=1;
try {
checkParticleDerivationOK(particle1.intValue(),derivedScope,
particle2.intValue(), baseScope, bInfo);
continue label;
}
catch (ParticleRecoverableError e) {
}
}
// didn't find a match. Detect an error
throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles");
}
}
private void checkMapAndSum(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
// See if the sequence group particle is a valid restriction of one of the particles
// of the choice
// This isn't what the spec says, but I can't make heads or tails of the
// algorithm in structures
int count2 = tempVector2.size();
boolean foundit = false;
for (int i=0; i<count2; i++) {
Integer particle = (Integer)tempVector2.elementAt(i);
fSchemaGrammar.getContentSpec(particle.intValue(),tempContentSpec1);
if (tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_SEQ)
try {
checkParticleDerivationOK(csIndex1,derivedScope,particle.intValue(),
baseScope, bInfo);
foundit = true;
break;
}
catch (ParticleRecoverableError e) {
}
}
if (!foundit)
throw new ParticleRecoverableError("rcase-MapAndSum: There is not a complete functional mapping between the particles");
}
private int importContentSpec(SchemaGrammar aGrammar, int contentSpecHead ) throws Exception {
XMLContentSpec ctsp = new XMLContentSpec();
aGrammar.getContentSpec(contentSpecHead, ctsp);
int left = -1;
int right = -1;
if ( ctsp.type == ctsp.CONTENTSPECNODE_LEAF
|| (ctsp.type & 0x0f) == ctsp.CONTENTSPECNODE_ANY
|| (ctsp.type & 0x0f) == ctsp.CONTENTSPECNODE_ANY_NS
|| (ctsp.type & 0x0f) == ctsp.CONTENTSPECNODE_ANY_OTHER ) {
return fSchemaGrammar.addContentSpecNode(ctsp.type, ctsp.value, ctsp.otherValue, false);
}
else if (ctsp.type == -1)
// case where type being extended has no content
return -2;
else {
if ( ctsp.value == -1 ) {
left = -1;
}
else {
left = importContentSpec(aGrammar, ctsp.value);
}
if ( ctsp.otherValue == -1 ) {
right = -1;
}
else {
right = importContentSpec(aGrammar, ctsp.otherValue);
}
return fSchemaGrammar.addContentSpecNode(ctsp.type, left, right, false);
}
}
private int handleOccurrences(int index,
Element particle) throws Exception {
// Pass through, indicating we're not processing an <all>
return handleOccurrences(index, particle, NOT_ALL_CONTEXT);
}
// Checks constraints for minOccurs, maxOccurs and expands content model
// accordingly
private int handleOccurrences(int index, Element particle,
int allContextFlags) throws Exception {
// if index is invalid, return
if (index < 0)
return index;
String minOccurs =
particle.getAttribute(SchemaSymbols.ATT_MINOCCURS).trim();
String maxOccurs =
particle.getAttribute(SchemaSymbols.ATT_MAXOCCURS).trim();
boolean processingAll = ((allContextFlags & PROCESSING_ALL) != 0);
boolean groupRefWithAll = ((allContextFlags & GROUP_REF_WITH_ALL) != 0);
boolean isGroupChild = ((allContextFlags & CHILD_OF_GROUP) != 0);
// Neither minOccurs nor maxOccurs may be specified
// for the child of a model group definition.
if (isGroupChild && (!minOccurs.equals("") || !maxOccurs.equals(""))) {
reportSchemaError(SchemaMessageProvider.MinMaxOnGroupChild, null);
minOccurs = (maxOccurs = "1");
}
// If minOccurs=maxOccurs=0, no component is specified
if(minOccurs.equals("0") && maxOccurs.equals("0")){
return -2;
}
int min=1, max=1;
if (minOccurs.equals("")) {
minOccurs = "1";
}
if (maxOccurs.equals("")) {
maxOccurs = "1";
}
// For the elements referenced in an <all>, minOccurs attribute
// must be zero or one, and maxOccurs attribute must be one.
if (processingAll || groupRefWithAll) {
if ((groupRefWithAll || !minOccurs.equals("0")) &&
!minOccurs.equals("1")) {
int minMsg = processingAll ?
SchemaMessageProvider.BadMinMaxForAll :
SchemaMessageProvider.BadMinMaxForGroupWithAll;
reportSchemaError(minMsg, new Object [] { "minOccurs",
minOccurs });
minOccurs = "1";
}
if (!maxOccurs.equals("1")) {
int maxMsg = processingAll ?
SchemaMessageProvider.BadMinMaxForAll :
SchemaMessageProvider.BadMinMaxForGroupWithAll;
reportSchemaError(maxMsg, new Object [] { "maxOccurs",
maxOccurs });
maxOccurs = "1";
}
}
try {
min = Integer.parseInt(minOccurs);
}
catch (Exception e){
reportSchemaError(SchemaMessageProvider.GenericError,
new Object [] { "illegal value for minOccurs or maxOccurs : '" +e.getMessage()+ "' "});
}
if (maxOccurs.equals("unbounded")) {
max = SchemaSymbols.OCCURRENCE_UNBOUNDED;
}
else {
try {
max = Integer.parseInt(maxOccurs);
}
catch (Exception e){
reportSchemaError(SchemaMessageProvider.GenericError,
new Object [] { "illegal value for minOccurs or maxOccurs : '" +e.getMessage()+ "' "});
}
// Check that minOccurs isn't greater than maxOccurs.
// p-props-correct 2.1
if (min > max) {
reportGenericSchemaError("p-props-correct:2.1 Value of minOccurs '" + minOccurs + "' must not be greater than value of maxOccurs '" + maxOccurs +"'");
}
if (max < 1) {
reportGenericSchemaError("p-props-correct:2.2 Value of maxOccurs " + maxOccurs + " is invalid. It must be greater than or equal to 1");
}
}
if (fSchemaGrammar.getDeferContentSpecExpansion()) {
fSchemaGrammar.setContentSpecMinOccurs(index,min);
fSchemaGrammar.setContentSpecMaxOccurs(index,max);
return index;
}
else {
return fSchemaGrammar.expandContentModel(index,min,max);
}
}
/**
* Traverses Schema attribute declaration.
*
* <attribute
* default = string
* fixed = string
* form = (qualified | unqualified)
* id = ID
* name = NCName
* ref = QName
* type = QName
* use = (optional | prohibited | required) : optional
* {any attributes with non-schema namespace ...}>
* Content: (annotation? , simpleType?)
* <attribute/>
*
* @param attributeDecl: the declaration of the attribute under
* consideration
* @param typeInfo: Contains the index of the element to which
* the attribute declaration is attached.
* @param referredTo: true iff traverseAttributeDecl was called because
* of encountering a ``ref''property (used
* to suppress error-reporting).
* @return 0 if the attribute schema is validated successfully, otherwise -1
* @exception Exception
*/
private int traverseAttributeDecl( Element attrDecl, ComplexTypeInfo typeInfo, boolean referredTo ) throws Exception {
// General Attribute Checking
int scope = isTopLevel(attrDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(attrDecl, scope);
////// Get declared fields of the attribute
String defaultStr = attrDecl.getAttribute(SchemaSymbols.ATT_DEFAULT);
String fixedStr = attrDecl.getAttribute(SchemaSymbols.ATT_FIXED);
String formStr = attrDecl.getAttribute(SchemaSymbols.ATT_FORM);//form attribute
String attNameStr = attrDecl.getAttribute(SchemaSymbols.ATT_NAME);
String refStr = attrDecl.getAttribute(SchemaSymbols.ATT_REF);
String datatypeStr = attrDecl.getAttribute(SchemaSymbols.ATT_TYPE);
String useStr = attrDecl.getAttribute(SchemaSymbols.ATT_USE);
Element simpleTypeChild = findAttributeSimpleType(attrDecl);
Attr defaultAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_DEFAULT);
Attr fixedAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_FIXED);
Attr formAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_FORM);
Attr attNameAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_NAME);
Attr refAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_REF);
Attr datatypeAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_TYPE);
Attr useAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_USE);
checkEnumerationRequiredNotation(attNameStr, datatypeStr);
////// define attribute declaration Schema components
int attName; // attribute name indexed in the string pool
int uriIndex; // indexed for target namespace uri
QName attQName; // QName combining attName and uriIndex
// attribute type
int attType;
boolean attIsList = false;
int dataTypeSymbol = -1;
String localpart = null;
// validator
DatatypeValidator dv;
boolean dvIsDerivedFromID = false;
// value constraints and use type
int attValueAndUseType = 0;
int attValueConstraint = -1; // indexed value in a string pool
////// Check W3C's PR-Structure 3.2.3
// --- Constraints on XML Representations of Attribute Declarations
boolean isAttrTopLevel = isTopLevel(attrDecl);
boolean isOptional = false;
boolean isProhibited = false;
boolean isRequired = false;
StringBuffer errorContext = new StringBuffer(30);
errorContext.append(" -- ");
if(typeInfo == null) {
errorContext.append("(global attribute) ");
}
else if(typeInfo.typeName == null) {
errorContext.append("(local attribute) ");
}
else {
errorContext.append("(attribute) ").append(typeInfo.typeName).append("/");
}
errorContext.append(attNameStr).append(' ').append(refStr);
if(useStr.equals("") || useStr.equals(SchemaSymbols.ATTVAL_OPTIONAL)) {
attValueAndUseType |= XMLAttributeDecl.USE_TYPE_OPTIONAL;
isOptional = true;
}
else if(useStr.equals(SchemaSymbols.ATTVAL_PROHIBITED)) {
attValueAndUseType |= XMLAttributeDecl.USE_TYPE_PROHIBITED;
isProhibited = true;
}
else if(useStr.equals(SchemaSymbols.ATTVAL_REQUIRED)) {
attValueAndUseType |= XMLAttributeDecl.USE_TYPE_REQUIRED;
isRequired = true;
}
else {
reportGenericSchemaError("An attribute cannot declare \"" +
SchemaSymbols.ATT_USE + "\" as \"" + useStr + "\"" + errorContext);
}
if(defaultAtt != null && fixedAtt != null) {
reportGenericSchemaError("src-attribute.1: \"" + SchemaSymbols.ATT_DEFAULT +
"\" and \"" + SchemaSymbols.ATT_FIXED +
"\" cannot be both present" + errorContext);
}
else if(defaultAtt != null && !isOptional) {
reportGenericSchemaError("src-attribute.2: If both \"" + SchemaSymbols.ATT_DEFAULT +
"\" and \"" + SchemaSymbols.ATT_USE + "\" " +
"are present for an attribute declaration, \"" +
SchemaSymbols.ATT_USE + "\" can only be \"" +
SchemaSymbols.ATTVAL_OPTIONAL + "\", not \"" + useStr + "\"." + errorContext);
}
if(!isAttrTopLevel) {
if((refAtt == null) == (attNameAtt == null)) {
reportGenericSchemaError("src-attribute.3.1: When the attribute's parent is not <schema> , one of \"" +
SchemaSymbols.ATT_REF + "\" and \"" + SchemaSymbols.ATT_NAME +
"\" should be declared, but not both."+ errorContext);
return -1;
}
else if((refAtt != null) && (simpleTypeChild != null || formAtt != null || datatypeAtt != null)) {
reportGenericSchemaError("src-attribute.3.2: When the attribute's parent is not <schema> and \"" +
SchemaSymbols.ATT_REF + "\" is present, " +
"all of <" + SchemaSymbols.ELT_SIMPLETYPE + ">, " +
SchemaSymbols.ATT_FORM + " and " + SchemaSymbols.ATT_TYPE +
" must be absent."+ errorContext);
}
}
if(datatypeAtt != null && simpleTypeChild != null) {
reportGenericSchemaError("src-attribute.4: \"" + SchemaSymbols.ATT_TYPE + "\" and <" +
SchemaSymbols.ELT_SIMPLETYPE + "> cannot both be present"+ errorContext);
}
////// Check W3C's PR-Structure 3.2.2
// --- XML Representation of Attribute Declaration Schema Components
// check case-dependent attribute declaration schema components
if (isAttrTopLevel) {
//// global attributes
// set name component
attName = fStringPool.addSymbol(attNameStr);
if(fTargetNSURIString.length() == 0) {
uriIndex = StringPool.EMPTY_STRING;
}
else {
uriIndex = fTargetNSURI;
}
// attQName = new QName(-1,attName,attName,uriIndex);
// Above line replaced by following 2 to work around a JIT problem.
attQName = new QName();
attQName.setValues(-1,attName,attName,uriIndex);
}
else if(refAtt == null) {
//// local attributes
// set name component
attName = fStringPool.addSymbol(attNameStr);
if((formStr.length() > 0 && formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)) ||
(formStr.length() == 0 && fAttributeDefaultQualified)) {
uriIndex = fTargetNSURI;
}
else {
uriIndex = StringPool.EMPTY_STRING;
}
// attQName = new QName(-1,attName,attName,uriIndex);
// Above line replaced by following 2 to work around a JIT problem.
attQName = new QName();
attQName.setValues(-1,attName,attName,uriIndex);
}
else {
//// locally referenced global attributes
String prefix;
int colonptr = refStr.indexOf(":");
if ( colonptr > 0) {
prefix = refStr.substring(0,colonptr);
localpart = refStr.substring(colonptr+1);
}
else {
prefix = "";
localpart = refStr;
}
String uriStr = resolvePrefixToURI(prefix);
if (!uriStr.equals(fTargetNSURIString)) {
addAttributeDeclFromAnotherSchema(localpart, uriStr, typeInfo);
return 0;
}
Element referredAttribute = getTopLevelComponentByName(SchemaSymbols.ELT_ATTRIBUTE,localpart);
if (referredAttribute != null) {
// don't need to traverse ref'd attribute if we're global; just make sure it's there...
traverseAttributeDecl(referredAttribute, typeInfo, true);
Attr referFixedAttr = referredAttribute.getAttributeNode(SchemaSymbols.ATT_FIXED);
String referFixed = referFixedAttr == null ? null : referFixedAttr.getValue();
if (referFixed != null && (defaultAtt != null || fixedAtt != null && !referFixed.equals(fixedStr))) {
reportGenericSchemaError("au-props-correct.2: If the {attribute declaration} has a fixed {value constraint}, then if the attribute use itself has a {value constraint}, it must also be fixed and its value must match that of the {attribute declaration}'s {value constraint}" + errorContext);
}
// this nasty hack needed to ``override'' the
// global attribute with "use" and "fixed" on the ref'ing attribute
if(!isOptional || fixedStr.length() > 0) {
int referredAttName = fStringPool.addSymbol(referredAttribute.getAttribute(SchemaSymbols.ATT_NAME));
uriIndex = StringPool.EMPTY_STRING;
if ( fTargetNSURIString.length() > 0) {
uriIndex = fTargetNSURI;
}
QName referredAttQName = new QName(-1,referredAttName,referredAttName,uriIndex);
int tempIndex = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, referredAttQName);
XMLAttributeDecl referredAttrDecl = new XMLAttributeDecl();
fSchemaGrammar.getAttributeDecl(tempIndex, referredAttrDecl);
boolean updated = false;
int useDigits = XMLAttributeDecl.USE_TYPE_OPTIONAL |
XMLAttributeDecl.USE_TYPE_PROHIBITED |
XMLAttributeDecl.USE_TYPE_REQUIRED;
int valueDigits = XMLAttributeDecl.VALUE_CONSTRAINT_DEFAULT |
XMLAttributeDecl.VALUE_CONSTRAINT_FIXED;
if(!isOptional &&
(referredAttrDecl.defaultType & useDigits) !=
(attValueAndUseType & useDigits))
{
if(referredAttrDecl.defaultType != XMLAttributeDecl.USE_TYPE_PROHIBITED) {
referredAttrDecl.defaultType |= useDigits;
referredAttrDecl.defaultType ^= useDigits; // clear the use
referredAttrDecl.defaultType |= (attValueAndUseType & useDigits);
updated = true;
}
}
if(fixedStr.length() > 0) {
if((referredAttrDecl.defaultType & XMLAttributeDecl.VALUE_CONSTRAINT_FIXED) == 0) {
referredAttrDecl.defaultType |= valueDigits;
referredAttrDecl.defaultType ^= valueDigits; // clear the value
referredAttrDecl.defaultType |= XMLAttributeDecl.VALUE_CONSTRAINT_FIXED;
referredAttrDecl.defaultValue = fixedStr;
updated = true;
}
}
if(updated) {
fSchemaGrammar.setAttributeDecl(typeInfo.templateElementIndex, tempIndex, referredAttrDecl);
}
}
}
else if (fAttributeDeclRegistry.get(localpart) != null) {
addAttributeDeclFromAnotherSchema(localpart, uriStr, typeInfo);
}
else {
// REVISIT: Localize
reportGenericSchemaError ( "Couldn't find top level attribute " + refStr + errorContext);
}
return 0;
}
if (uriIndex == fXsiURI) {
reportGenericSchemaError("no-xsi: The {target namespace} of an attribute declaration must not match " + SchemaSymbols.URI_XSI + errorContext);
}
// validation of attribute type is same for each case of declaration
if (simpleTypeChild != null) {
attType = XMLAttributeDecl.TYPE_SIMPLE;
dataTypeSymbol = traverseSimpleTypeDecl(simpleTypeChild);
localpart = fStringPool.toString(dataTypeSymbol);
dv = fDatatypeRegistry.getDatatypeValidator(localpart);
}
else if (datatypeStr.length() != 0) {
dataTypeSymbol = fStringPool.addSymbol(datatypeStr);
String prefix;
int colonptr = datatypeStr.indexOf(":");
if ( colonptr > 0) {
prefix = datatypeStr.substring(0,colonptr);
localpart = datatypeStr.substring(colonptr+1);
}
else {
prefix = "";
localpart = datatypeStr;
}
String typeURI = resolvePrefixToURI(prefix);
if ( typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
|| typeURI.length()==0) {
dv = getDatatypeValidator("", localpart);
if (localpart.equals("ID")) {
attType = XMLAttributeDecl.TYPE_ID;
} else if (localpart.equals("IDREF")) {
attType = XMLAttributeDecl.TYPE_IDREF;
} else if (localpart.equals("IDREFS")) {
attType = XMLAttributeDecl.TYPE_IDREF;
attIsList = true;
} else if (localpart.equals("ENTITY")) {
attType = XMLAttributeDecl.TYPE_ENTITY;
} else if (localpart.equals("ENTITIES")) {
attType = XMLAttributeDecl.TYPE_ENTITY;
attIsList = true;
} else if (localpart.equals("NMTOKEN")) {
attType = XMLAttributeDecl.TYPE_NMTOKEN;
} else if (localpart.equals("NMTOKENS")) {
attType = XMLAttributeDecl.TYPE_NMTOKEN;
attIsList = true;
} else if (localpart.equals(SchemaSymbols.ELT_NOTATION)) {
attType = XMLAttributeDecl.TYPE_NOTATION;
}
else {
attType = XMLAttributeDecl.TYPE_SIMPLE;
if (dv == null && typeURI.length() == 0) {
Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (topleveltype != null) {
traverseSimpleTypeDecl( topleveltype );
dv = getDatatypeValidator(typeURI, localpart);
}else if (!referredTo) {
// REVISIT: Localize
reportGenericSchemaError("simpleType not found : " + "("+typeURI+":"+localpart+")"+ errorContext);
}
}
}
} else { //isn't of the schema for schemas namespace...
attType = XMLAttributeDecl.TYPE_SIMPLE;
// check if the type is from the same Schema
dv = getDatatypeValidator(typeURI, localpart);
if (dv == null && typeURI.equals(fTargetNSURIString) ) {
Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (topleveltype != null) {
traverseSimpleTypeDecl( topleveltype );
dv = getDatatypeValidator(typeURI, localpart);
}else if (!referredTo) {
// REVISIT: Localize
reportGenericSchemaError("simpleType not found : " + "("+typeURI+":"+ localpart+")"+ errorContext);
}
}
}
}
else {
attType = XMLAttributeDecl.TYPE_SIMPLE;
localpart = "string";
dataTypeSymbol = fStringPool.addSymbol(localpart);
dv = fDatatypeRegistry.getDatatypeValidator(localpart);
} // if(...Type)
// validation of data constraint is same for each case of declaration
if(defaultStr.length() > 0) {
attValueAndUseType |= XMLAttributeDecl.VALUE_CONSTRAINT_DEFAULT;
attValueConstraint = fStringPool.addString(defaultStr);
}
else if(fixedStr.length() > 0) {
attValueAndUseType |= XMLAttributeDecl.VALUE_CONSTRAINT_FIXED;
attValueConstraint = fStringPool.addString(fixedStr);
}
////// Check W3C's PR-Structure 3.2.6
// --- Constraints on Attribute Declaration Schema Components
// check default value is valid for the datatype.
if (attType == XMLAttributeDecl.TYPE_SIMPLE && attValueConstraint != -1) {
try {
if (dv != null) {
if(defaultStr.length() > 0) {
//REVISIT
dv.validate(defaultStr, null);
}
else {
dv.validate(fixedStr, null);
}
}
else if (!referredTo)
reportSchemaError(SchemaMessageProvider.NoValidatorFor,
new Object [] { datatypeStr });
} catch (InvalidDatatypeValueException idve) {
if (!referredTo)
reportSchemaError(SchemaMessageProvider.IncorrectDefaultType,
new Object [] { attrDecl.getAttribute(SchemaSymbols.ATT_NAME), idve.getMessage() }); //a-props-correct.2
} catch (Exception e) {
e.printStackTrace();
System.out.println("Internal error in attribute datatype validation");
}
}
// check the coexistence of ID and value constraint
dvIsDerivedFromID =
((dv != null) && dv instanceof IDDatatypeValidator);
if (dvIsDerivedFromID && attValueConstraint != -1)
{
reportGenericSchemaError("a-props-correct.3: If type definition is or is derived from ID ," +
"there must not be a value constraint" + errorContext);
}
if (attNameStr.equals("xmlns")) {
reportGenericSchemaError("no-xmlns: The {name} of an attribute declaration must not match 'xmlns'" + errorContext);
}
////// every contraints were matched. Now register the attribute declaration
//put the top-levels in the attribute decl registry.
if (isAttrTopLevel) {
fTempAttributeDecl.datatypeValidator = dv;
fTempAttributeDecl.name.setValues(attQName);
fTempAttributeDecl.type = attType;
fTempAttributeDecl.defaultType = attValueAndUseType;
fTempAttributeDecl.list = attIsList;
if (attValueConstraint != -1 ) {
fTempAttributeDecl.defaultValue = fStringPool.toString(attValueConstraint);
}
fAttributeDeclRegistry.put(attNameStr, new XMLAttributeDecl(fTempAttributeDecl));
}
// add attribute to attr decl pool in fSchemaGrammar,
if (typeInfo != null) {
// check that there aren't duplicate attributes
int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, attQName);
if (temp > -1) {
reportGenericSchemaError("ct-props-correct.4: Duplicate attribute " +
fStringPool.toString(attQName.rawname) + " in type definition");
}
// check that there aren't multiple attributes with type derived from ID
if (dvIsDerivedFromID) {
if (typeInfo.containsAttrTypeID()) {
reportGenericSchemaError("ct-props-correct.5: More than one attribute derived from type ID cannot appear in the same complex type definition.");
}
typeInfo.setContainsAttrTypeID();
}
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
attQName, attType,
dataTypeSymbol, attValueAndUseType,
fStringPool.toString( attValueConstraint), dv, attIsList);
}
return 0;
} // end of method traverseAttribute
private int addAttributeDeclFromAnotherSchema( String name, String uriStr, ComplexTypeInfo typeInfo) throws Exception {
SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr);
if (uriStr == null || ! (aGrammar instanceof SchemaGrammar) ) {
// REVISIT: Localize
reportGenericSchemaError( "no attribute named \"" + name
+ "\" was defined in schema : " + uriStr);
return -1;
}
Hashtable attrRegistry = aGrammar.getAttributeDeclRegistry();
if (attrRegistry == null) {
// REVISIT: Localize
reportGenericSchemaError( "no attribute named \"" + name
+ "\" was defined in schema : " + uriStr);
return -1;
}
XMLAttributeDecl tempAttrDecl = (XMLAttributeDecl) attrRegistry.get(name);
if (tempAttrDecl == null) {
// REVISIT: Localize
reportGenericSchemaError( "no attribute named \"" + name
+ "\" was defined in schema : " + uriStr);
return -1;
}
if (typeInfo!= null) {
// check that there aren't duplicate attributes
int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, tempAttrDecl.name);
if (temp > -1) {
reportGenericSchemaError("ct-props-correct.4: Duplicate attribute " +
fStringPool.toString(tempAttrDecl.name.rawname) + " in type definition");
}
// check that there aren't multiple attributes with type derived from ID
if (tempAttrDecl.datatypeValidator != null &&
tempAttrDecl.datatypeValidator instanceof IDDatatypeValidator) {
if (typeInfo.containsAttrTypeID()) {
reportGenericSchemaError("ct-props-correct.5: More than one attribute derived from type ID cannot appear in the same complex type definition");
}
typeInfo.setContainsAttrTypeID();
}
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
tempAttrDecl.name, tempAttrDecl.type,
-1, tempAttrDecl.defaultType,
tempAttrDecl.defaultValue,
tempAttrDecl.datatypeValidator,
tempAttrDecl.list);
}
return 0;
}
/*
*
* <attributeGroup
* id = ID
* name = NCName
* ref = QName>
* Content: (annotation?, (attribute|attributeGroup)*, anyAttribute?)
* </>
*
*/
private int traverseAttributeGroupDecl( Element attrGrpDecl, ComplexTypeInfo typeInfo, Vector anyAttDecls ) throws Exception {
// General Attribute Checking
int scope = isTopLevel(attrGrpDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(attrGrpDecl, scope);
// attributeGroup name
String attGrpNameStr = attrGrpDecl.getAttribute(SchemaSymbols.ATT_NAME);
int attGrpName = fStringPool.addSymbol(attGrpNameStr);
String ref = attrGrpDecl.getAttribute(SchemaSymbols.ATT_REF);
Element child = checkContent( attrGrpDecl, XUtil.getFirstChildElement(attrGrpDecl), true );
if (!ref.equals("")) {
if(isTopLevel(attrGrpDecl))
// REVISIT: localize
reportGenericSchemaError ( "An attributeGroup with \"ref\" present must not have <schema> or <redefine> as its parent");
if(!attGrpNameStr.equals(""))
// REVISIT: localize
reportGenericSchemaError ( "attributeGroup " + attGrpNameStr + " cannot refer to another attributeGroup, but it refers to " + ref);
if (XUtil.getFirstChildElement(attrGrpDecl) != null ||
attrGrpDecl.getNodeValue() != null)
// REVISIT: localize
reportGenericSchemaError ( "An attributeGroup with \"ref\" present must be empty");
String prefix = "";
String localpart = ref;
int colonptr = ref.indexOf(":");
if ( colonptr > 0) {
prefix = ref.substring(0,colonptr);
localpart = ref.substring(colonptr+1);
}
String uriStr = resolvePrefixToURI(prefix);
if (!uriStr.equals(fTargetNSURIString)) {
traverseAttributeGroupDeclFromAnotherSchema(localpart, uriStr, typeInfo, anyAttDecls);
return -1;
// TO DO
// REVISIT: different NS, not supported yet.
// REVISIT: Localize
//reportGenericSchemaError("Feature not supported: see an attribute from different NS");
} else {
Element parent = (Element)attrGrpDecl.getParentNode();
if (parent.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) &&
parent.getAttribute(SchemaSymbols.ATT_NAME).equals(localpart)) {
if (!((Element)parent.getParentNode()).getLocalName().equals(SchemaSymbols.ELT_REDEFINE)) {
reportGenericSchemaError("src-attribute_group.3: Circular group reference is disallowed outside <redefine> -- "+ref);
}
return -1;
}
}
if(typeInfo != null) {
// only do this if we're traversing because we were ref'd here; when we come
// upon this decl by itself we're just validating.
Element referredAttrGrp = getTopLevelComponentByName(SchemaSymbols.ELT_ATTRIBUTEGROUP,localpart);
if (referredAttrGrp != null) {
traverseAttributeGroupDecl(referredAttrGrp, typeInfo, anyAttDecls);
}
else {
// REVISIT: Localize
reportGenericSchemaError ( "Couldn't find top level attributeGroup " + ref);
}
return -1;
}
} else if (attGrpNameStr.equals(""))
// REVISIT: localize
reportGenericSchemaError ( "an attributeGroup must have a name or a ref attribute present");
for (;
child != null ; child = XUtil.getNextSiblingElement(child)) {
if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTE) ){
traverseAttributeDecl(child, typeInfo, false);
}
else if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) {
NamespacesScope currScope = (NamespacesScope)fNamespacesScope.clone();
// if(typeInfo != null)
// only do this if we're traversing because we were ref'd here; when we come
// upon this decl by itself we're just validating.
traverseAttributeGroupDecl(child, typeInfo,anyAttDecls);
fNamespacesScope = currScope;
}
else
break;
}
if (child != null) {
if ( child.getLocalName().equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) {
if (anyAttDecls != null) {
anyAttDecls.addElement(traverseAnyAttribute(child));
}
if (XUtil.getNextSiblingElement(child) != null)
// REVISIT: localize
reportGenericSchemaError ( "src-attribute_group.0: The content of an attributeGroup declaration must match (annotation?, ((attribute | attributeGroup)*, anyAttribute?))");
return -1;
}
else
// REVISIT: localize
reportGenericSchemaError ( "src-attribute_group.0: The content of an attributeGroup declaration must match (annotation?, ((attribute | attributeGroup)*, anyAttribute?))");
}
return -1;
} // end of method traverseAttributeGroup
private int traverseAttributeGroupDeclFromAnotherSchema( String attGrpName , String uriStr,
ComplexTypeInfo typeInfo,
Vector anyAttDecls ) throws Exception {
SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr);
if (uriStr == null || aGrammar == null || ! (aGrammar instanceof SchemaGrammar) ) {
// REVISIT: Localize
reportGenericSchemaError("!!Schema not found in #traverseAttributeGroupDeclFromAnotherSchema, schema uri : " + uriStr);
return -1;
}
// attribute name
Element attGrpDecl = (Element) aGrammar.topLevelAttrGrpDecls.get((Object)attGrpName);
if (attGrpDecl == null) {
// REVISIT: Localize
reportGenericSchemaError( "no attribute group named \"" + attGrpName
+ "\" was defined in schema : " + uriStr);
return -1;
}
NamespacesScope saveNSMapping = fNamespacesScope;
int saveTargetNSUri = fTargetNSURI;
fTargetNSURI = fStringPool.addSymbol(aGrammar.getTargetNamespaceURI());
fNamespacesScope = aGrammar.getNamespacesScope();
// attribute type
int attType = -1;
int enumeration = -1;
Element child = checkContent(attGrpDecl, XUtil.getFirstChildElement(attGrpDecl), true);
for (;
child != null ; child = XUtil.getNextSiblingElement(child)) {
//child attribute couldn't be a top-level attribute DEFINITION,
if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTE) ){
String childAttName = child.getAttribute(SchemaSymbols.ATT_NAME);
if ( childAttName.length() > 0 ) {
Hashtable attDeclRegistry = aGrammar.getAttributeDeclRegistry();
if (attDeclRegistry != null) {
if (attDeclRegistry.get((Object)childAttName) != null ){
addAttributeDeclFromAnotherSchema(childAttName, uriStr, typeInfo);
return -1;
}
}
}
else
traverseAttributeDecl(child, typeInfo, false);
}
else if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) {
traverseAttributeGroupDecl(child, typeInfo, anyAttDecls);
}
else if ( child.getLocalName().equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) {
anyAttDecls.addElement(traverseAnyAttribute(child));
break;
}
else {
// REVISIT: Localize
reportGenericSchemaError("Invalid content for attributeGroup");
}
}
fNamespacesScope = saveNSMapping;
fTargetNSURI = saveTargetNSUri;
if(child != null) {
// REVISIT: Localize
reportGenericSchemaError("Invalid content for attributeGroup");
}
return -1;
} // end of method traverseAttributeGroupFromAnotherSchema
// This simple method takes an attribute declaration as a parameter and
// returns null if there is no simpleType defined or the simpleType
// declaration if one exists. It also throws an error if more than one
// <annotation> or <simpleType> group is present.
private Element findAttributeSimpleType(Element attrDecl) throws Exception {
Element child = checkContent(attrDecl, XUtil.getFirstChildElement(attrDecl), true);
// if there is only a annotatoin, then no simpleType
if (child == null)
return null;
// if the current one is not simpleType, or there are more elements,
// report an error
if (!child.getLocalName().equals(SchemaSymbols.ELT_SIMPLETYPE) ||
XUtil.getNextSiblingElement(child) != null)
//REVISIT: localize
reportGenericSchemaError("src-attribute.0: the content must match (annotation?, (simpleType?)) -- attribute declaration '"+
attrDecl.getAttribute(SchemaSymbols.ATT_NAME)+"'");
if (child.getLocalName().equals(SchemaSymbols.ELT_SIMPLETYPE))
return child;
return null;
} // end findAttributeSimpleType
/**
* Traverse element declaration:
* <element
* abstract = boolean
* block = #all or (possibly empty) subset of {substitutionGroup, extension, restriction}
* default = string
* substitutionGroup = QName
* final = #all or (possibly empty) subset of {extension, restriction}
* fixed = string
* form = qualified | unqualified
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* name = NCName
* nillable = boolean
* ref = QName
* type = QName>
* Content: (annotation? , (simpleType | complexType)? , (unique | key | keyref)*)
* </element>
*
*
* The following are identity-constraint definitions
* <unique
* id = ID
* name = NCName>
* Content: (annotation? , (selector , field+))
* </unique>
*
* <key
* id = ID
* name = NCName>
* Content: (annotation? , (selector , field+))
* </key>
*
* <keyref
* id = ID
* name = NCName
* refer = QName>
* Content: (annotation? , (selector , field+))
* </keyref>
*
* <selector>
* Content: XPathExprApprox : An XPath expression
* </selector>
*
* <field>
* Content: XPathExprApprox : An XPath expression
* </field>
*
*
* @param elementDecl
* @return
* @exception Exception
*/
private QName traverseElementDecl(Element elementDecl) throws Exception {
// General Attribute Checking
int scope = isTopLevel(elementDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(elementDecl, scope);
int contentSpecType = -1;
int contentSpecNodeIndex = -1;
int typeNameIndex = -1;
int scopeDefined = -2; //signal a error if -2 gets gets through
//cause scope can never be -2.
DatatypeValidator dv = null;
String abstractStr = elementDecl.getAttribute(SchemaSymbols.ATT_ABSTRACT);
String blockStr = elementDecl.getAttribute(SchemaSymbols.ATT_BLOCK);
String defaultStr = elementDecl.getAttribute(SchemaSymbols.ATT_DEFAULT);
String finalStr = elementDecl.getAttribute(SchemaSymbols.ATT_FINAL);
String fixedStr = elementDecl.getAttribute(SchemaSymbols.ATT_FIXED);
String formStr = elementDecl.getAttribute(SchemaSymbols.ATT_FORM);
String maxOccursStr = elementDecl.getAttribute(SchemaSymbols.ATT_MAXOCCURS);
String minOccursStr = elementDecl.getAttribute(SchemaSymbols.ATT_MINOCCURS);
String nameStr = elementDecl.getAttribute(SchemaSymbols.ATT_NAME);
String nillableStr = elementDecl.getAttribute(SchemaSymbols.ATT_NILLABLE);
String refStr = elementDecl.getAttribute(SchemaSymbols.ATT_REF);
String substitutionGroupStr = elementDecl.getAttribute(SchemaSymbols.ATT_SUBSTITUTIONGROUP);
String typeStr = elementDecl.getAttribute(SchemaSymbols.ATT_TYPE);
checkEnumerationRequiredNotation(nameStr, typeStr);
if ( DEBUGGING )
System.out.println("traversing element decl : " + nameStr );
Attr abstractAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_ABSTRACT);
Attr blockAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_BLOCK);
Attr defaultAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_DEFAULT);
Attr finalAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FINAL);
Attr fixedAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FIXED);
Attr formAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FORM);
Attr maxOccursAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_MAXOCCURS);
Attr minOccursAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_MINOCCURS);
Attr nameAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_NAME);
Attr nillableAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_NILLABLE);
Attr refAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_REF);
Attr substitutionGroupAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_SUBSTITUTIONGROUP);
Attr typeAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_TYPE);
if(defaultAtt != null && fixedAtt != null)
// REVISIT: localize
reportGenericSchemaError("src-element.1: an element cannot have both \"fixed\" and \"default\" present at the same time");
String fromAnotherSchema = null;
if (isTopLevel(elementDecl)) {
if(nameAtt == null)
// REVISIT: localize
reportGenericSchemaError("globally-declared element must have a name");
else if (refAtt != null)
// REVISIT: localize
reportGenericSchemaError("globally-declared element " + nameStr + " cannot have a ref attribute");
int nameIndex = fStringPool.addSymbol(nameStr);
int eltKey = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, nameIndex,TOP_LEVEL_SCOPE);
if (eltKey > -1 ) {
return new QName(-1,nameIndex,nameIndex,fTargetNSURI);
}
}
// parse out 'block', 'final', 'nillable', 'abstract'
if (blockAtt == null)
blockStr = null;
int blockSet = parseBlockSet(blockStr);
if( (blockStr != null) && !blockStr.equals("") &&
(!blockStr.equals(SchemaSymbols.ATTVAL_POUNDALL) &&
(((blockSet & SchemaSymbols.RESTRICTION) == 0) &&
(((blockSet & SchemaSymbols.EXTENSION) == 0) &&
((blockSet & SchemaSymbols.SUBSTITUTION) == 0)))))
reportGenericSchemaError("The values of the 'block' attribute of an element must be either #all or a list of 'substitution', 'restriction' and 'extension'; " + blockStr + " was found");
if (finalAtt == null)
finalStr = null;
int finalSet = parseFinalSet(finalStr);
if( (finalStr != null) && !finalStr.equals("") &&
(!finalStr.equals(SchemaSymbols.ATTVAL_POUNDALL) &&
(((finalSet & SchemaSymbols.RESTRICTION) == 0) &&
((finalSet & SchemaSymbols.EXTENSION) == 0))))
reportGenericSchemaError("The values of the 'final' attribute of an element must be either #all or a list of 'restriction' and 'extension'; " + finalStr + " was found");
boolean isNillable = nillableStr.equals(SchemaSymbols.ATTVAL_TRUE)? true:false;
boolean isAbstract = abstractStr.equals(SchemaSymbols.ATTVAL_TRUE)? true:false;
int elementMiscFlags = 0;
if (isNillable) {
elementMiscFlags += SchemaSymbols.NILLABLE;
}
if (isAbstract) {
elementMiscFlags += SchemaSymbols.ABSTRACT;
}
// make the property of the element's value being fixed also appear in elementMiscFlags
if(fixedAtt != null)
elementMiscFlags += SchemaSymbols.FIXED;
//if this is a reference to a global element
if (refAtt != null) {
//REVISIT top level check for ref
if (abstractAtt != null || blockAtt != null || defaultAtt != null ||
finalAtt != null || fixedAtt != null || formAtt != null ||
nillableAtt != null || substitutionGroupAtt != null || typeAtt != null)
reportSchemaError(SchemaMessageProvider.BadAttWithRef, null); //src-element.2.2
if (nameAtt != null)
// REVISIT: Localize
reportGenericSchemaError("src-element.2.1: element " + nameStr + " cannot also have a ref attribute");
Element child = XUtil.getFirstChildElement(elementDecl);
if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
if (XUtil.getNextSiblingElement(child) != null)
reportSchemaError(SchemaMessageProvider.NoContentForRef, null);
else
traverseAnnotationDecl(child);
}
else if (child != null)
reportSchemaError(SchemaMessageProvider.NoContentForRef, null);
String prefix = "";
String localpart = refStr;
int colonptr = refStr.indexOf(":");
if ( colonptr > 0) {
prefix = refStr.substring(0,colonptr);
localpart = refStr.substring(colonptr+1);
}
int localpartIndex = fStringPool.addSymbol(localpart);
String uriString = resolvePrefixToURI(prefix);
QName eltName = new QName(prefix != null ? fStringPool.addSymbol(prefix) : -1,
localpartIndex,
fStringPool.addSymbol(refStr),
uriString != null ? fStringPool.addSymbol(uriString) : StringPool.EMPTY_STRING);
//if from another schema, just return the element QName
if (! uriString.equals(fTargetNSURIString) ) {
return eltName;
}
int elementIndex = fSchemaGrammar.getElementDeclIndex(eltName, TOP_LEVEL_SCOPE);
//if not found, traverse the top level element that if referenced
if (elementIndex == -1 ) {
Element targetElement = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT,localpart);
if (targetElement == null ) {
// REVISIT: Localize
reportGenericSchemaError("Element " + localpart + " not found in the Schema");
//REVISIT, for now, the QName anyway
return eltName;
//return new QName(-1,fStringPool.addSymbol(localpart), -1, fStringPool.addSymbol(uriString));
}
else {
// do nothing here, other wise would cause infinite loop for
// <element name="recur"><complexType><element ref="recur"> ...
//eltName= traverseElementDecl(targetElement);
}
}
return eltName;
} else if (nameAtt == null)
// REVISIT: Localize
reportGenericSchemaError("src-element.2.1: a local element must have a name or a ref attribute present");
// Handle the substitutionGroup
Element substitutionGroupElementDecl = null;
int substitutionGroupElementDeclIndex = -1;
boolean noErrorSoFar = true;
String substitutionGroupUri = null;
String substitutionGroupLocalpart = null;
String substitutionGroupFullName = null;
ComplexTypeInfo substitutionGroupEltTypeInfo = null;
DatatypeValidator substitutionGroupEltDV = null;
SchemaGrammar subGrammar = fSchemaGrammar;
if ( substitutionGroupStr.length() > 0 ) {
if(refAtt != null)
// REVISIT: Localize
reportGenericSchemaError("a local element cannot have a substitutionGroup");
substitutionGroupUri = resolvePrefixToURI(getPrefix(substitutionGroupStr));
substitutionGroupLocalpart = getLocalPart(substitutionGroupStr);
substitutionGroupFullName = substitutionGroupUri+","+substitutionGroupLocalpart;
if ( !substitutionGroupUri.equals(fTargetNSURIString) ) {
Grammar grammar = fGrammarResolver.getGrammar(substitutionGroupUri);
if (grammar != null && grammar instanceof SchemaGrammar) {
subGrammar = (SchemaGrammar) grammar;
substitutionGroupElementDeclIndex = subGrammar.getElementDeclIndex(fStringPool.addSymbol(substitutionGroupUri),
fStringPool.addSymbol(substitutionGroupLocalpart),
TOP_LEVEL_SCOPE);
if (substitutionGroupElementDeclIndex<=-1) {
// REVISIT: localize
noErrorSoFar = false;
reportGenericSchemaError("couldn't find substitutionGroup " + substitutionGroupLocalpart + " referenced by element " + nameStr
+ " in the SchemaGrammar "+substitutionGroupUri);
} else {
substitutionGroupEltTypeInfo = getElementDeclTypeInfoFromNS(substitutionGroupUri, substitutionGroupLocalpart);
if (substitutionGroupEltTypeInfo == null) {
substitutionGroupEltDV = getElementDeclTypeValidatorFromNS(substitutionGroupUri, substitutionGroupLocalpart);
if (substitutionGroupEltDV == null) {
//TO DO: report error here;
noErrorSoFar = false;
reportGenericSchemaError("Could not find type for element '" +substitutionGroupLocalpart
+ "' in schema '" + substitutionGroupUri+"'");
}
}
}
} else {
// REVISIT: locallize
noErrorSoFar = false;
reportGenericSchemaError("couldn't find a schema grammar with target namespace " + substitutionGroupUri);
}
}
else {
substitutionGroupElementDecl = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT, substitutionGroupLocalpart);
if (substitutionGroupElementDecl == null) {
substitutionGroupElementDeclIndex =
fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE);
if ( substitutionGroupElementDeclIndex == -1) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("unable to locate substitutionGroup affiliation element "
+substitutionGroupStr
+" in element declaration "
+nameStr);
}
}
else {
substitutionGroupElementDeclIndex =
fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE);
if ( substitutionGroupElementDeclIndex == -1) {
traverseElementDecl(substitutionGroupElementDecl);
substitutionGroupElementDeclIndex =
fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE);
}
}
if (substitutionGroupElementDeclIndex != -1) {
substitutionGroupEltTypeInfo = fSchemaGrammar.getElementComplexTypeInfo( substitutionGroupElementDeclIndex );
if (substitutionGroupEltTypeInfo == null) {
fSchemaGrammar.getElementDecl(substitutionGroupElementDeclIndex, fTempElementDecl);
substitutionGroupEltDV = fTempElementDecl.datatypeValidator;
if (substitutionGroupEltDV == null) {
//TO DO: report error here;
noErrorSoFar = false;
reportGenericSchemaError("Could not find type for element '" +substitutionGroupLocalpart
+ "' in schema '" + substitutionGroupUri+"'");
}
}
}
}
}
//
// resolving the type for this element right here
//
ComplexTypeInfo typeInfo = null;
// element has a single child element, either a datatype or a type, null if primitive
Element child = XUtil.getFirstChildElement(elementDecl);
if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
traverseAnnotationDecl(child);
child = XUtil.getNextSiblingElement(child);
}
if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION))
// REVISIT: Localize
reportGenericSchemaError("element declarations can contain at most one annotation Element Information Item");
boolean haveAnonType = false;
// Handle Anonymous type if there is one
if (child != null) {
String childName = child.getLocalName();
if (childName.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("anonymous complexType in element '" + nameStr +"' has a name attribute");
}
else {
// Determine what the type name will be
String anonTypeName = genAnonTypeName(child);
if (fCurrentTypeNameStack.search((Object)anonTypeName) > - 1) {
// A recursing element using an anonymous type
int uriInd = StringPool.EMPTY_STRING;
if ( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)||
fElementDefaultQualified) {
uriInd = fTargetNSURI;
}
int nameIndex = fStringPool.addSymbol(nameStr);
QName tempQName = new QName(-1, nameIndex, nameIndex, uriInd);
int eltIndex = fSchemaGrammar.addElementDecl(tempQName,
fCurrentScope, fCurrentScope, -1, -1, -1, null);
fElementRecurseComplex.addElement(new ElementInfo(eltIndex,anonTypeName));
return tempQName;
}
else {
typeNameIndex = traverseComplexTypeDecl(child);
if (typeNameIndex != -1 ) {
typeInfo = (ComplexTypeInfo)
fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex));
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("traverse complexType error in element '" + nameStr +"'");
}
}
}
haveAnonType = true;
child = XUtil.getNextSiblingElement(child);
}
else if (childName.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("anonymous simpleType in element '" + nameStr +"' has a name attribute");
}
else
typeNameIndex = traverseSimpleTypeDecl(child);
if (typeNameIndex != -1) {
dv = fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex));
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("traverse simpleType error in element '" + nameStr +"'");
}
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
haveAnonType = true;
child = XUtil.getNextSiblingElement(child);
} else if (typeAtt == null) { // "ur-typed" leaf
contentSpecType = XMLElementDecl.TYPE_ANY;
//REVISIT: is this right?
//contentSpecType = fStringPool.addSymbol("UR_TYPE");
// set occurrence count
contentSpecNodeIndex = -1;
}
// see if there's something here; it had better be key, keyref or unique.
if (child != null)
childName = child.getLocalName();
while ((child != null) && ((childName.equals(SchemaSymbols.ELT_KEY))
|| (childName.equals(SchemaSymbols.ELT_KEYREF))
|| (childName.equals(SchemaSymbols.ELT_UNIQUE)))) {
child = XUtil.getNextSiblingElement(child);
if (child != null) {
childName = child.getLocalName();
}
}
if (child != null) {
// REVISIT: Localize
noErrorSoFar = false;
reportGenericSchemaError("src-element.0: the content of an element information item must match (annotation?, (simpleType | complexType)?, (unique | key | keyref)*)");
}
}
// handle type="" here
if (haveAnonType && (typeAtt != null)) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError( "src-element.3: Element '"+ nameStr +
"' have both a type attribute and a annoymous type child" );
}
// type specified as an attribute and no child is type decl.
else if (typeAtt != null) {
String prefix = "";
String localpart = typeStr;
int colonptr = typeStr.indexOf(":");
if ( colonptr > 0) {
prefix = typeStr.substring(0,colonptr);
localpart = typeStr.substring(colonptr+1);
}
String typeURI = resolvePrefixToURI(prefix);
// check if the type is from the same Schema
if ( !typeURI.equals(fTargetNSURIString)
&& !typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& typeURI.length() != 0) { // REVISIT, only needed because of resolvePrifixToURI.
fromAnotherSchema = typeURI;
typeInfo = getTypeInfoFromNS(typeURI, localpart);
if (typeInfo == null) {
dv = getTypeValidatorFromNS(typeURI, localpart);
if (dv == null) {
//TO DO: report error here;
noErrorSoFar = false;
reportGenericSchemaError("Could not find type " +localpart
+ " in schema " + typeURI);
}
}
}
else {
typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(typeURI+","+localpart);
if (typeInfo == null) {
dv = getDatatypeValidator(typeURI, localpart);
if (dv == null )
if (typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& !fTargetNSURIString.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA))
{
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("type not found : " + typeURI+":"+localpart);
}
else {
Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart);
if (topleveltype != null) {
if (fCurrentTypeNameStack.search((Object)localpart) > - 1) {
//then we found a recursive element using complexType.
// REVISIT: this will be broken when recursing happens between 2 schemas
int uriInd = StringPool.EMPTY_STRING;
if ( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)||
fElementDefaultQualified) {
uriInd = fTargetNSURI;
}
int nameIndex = fStringPool.addSymbol(nameStr);
QName tempQName = new QName(-1, nameIndex, nameIndex, uriInd);
int eltIndex = fSchemaGrammar.addElementDecl(tempQName,
fCurrentScope, fCurrentScope, -1, -1, -1, null);
fElementRecurseComplex.addElement(new ElementInfo(eltIndex,localpart));
return tempQName;
}
else {
typeNameIndex = traverseComplexTypeDecl( topleveltype, true );
typeInfo = (ComplexTypeInfo)
fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex));
}
}
else {
topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (topleveltype != null) {
typeNameIndex = traverseSimpleTypeDecl( topleveltype );
dv = getDatatypeValidator(typeURI, localpart);
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("type not found : " + typeURI+":"+localpart);
}
}
}
}
}
}
// now we need to make sure that our substitution (if any)
// is valid, now that we have all the requisite type-related info.
if(substitutionGroupStr.length() > 0) {
checkSubstitutionGroupOK(elementDecl, substitutionGroupElementDecl, noErrorSoFar, substitutionGroupElementDeclIndex, subGrammar, typeInfo, substitutionGroupEltTypeInfo, dv, substitutionGroupEltDV);
}
// this element is ur-type, check its substitutionGroup affiliation.
// if there is substitutionGroup affiliation and not type definition found for this element,
// then grab substitutionGroup affiliation's type and give it to this element
if ( noErrorSoFar && typeInfo == null && dv == null ) {
typeInfo = substitutionGroupEltTypeInfo;
dv = substitutionGroupEltDV;
}
if (typeInfo == null && dv==null) {
if (noErrorSoFar) {
// Actually this Element's type definition is ur-type;
contentSpecType = XMLElementDecl.TYPE_ANY;
// REVISIT, need to wait till we have wildcards implementation.
// ADD attribute wildcards here
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError ("untyped element : " + nameStr );
}
}
// if element belongs to a compelx type
if (typeInfo!=null) {
contentSpecNodeIndex = typeInfo.contentSpecHandle;
contentSpecType = typeInfo.contentType;
scopeDefined = typeInfo.scopeDefined;
dv = typeInfo.datatypeValidator;
}
// if element belongs to a simple type
if (dv!=null) {
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
if (typeInfo == null) {
fromAnotherSchema = null; // not to switch schema in this case
}
}
// Now we can handle validation etc. of default and fixed attributes,
// since we finally have all the type information.
if(fixedAtt != null) defaultStr = fixedStr;
if(!defaultStr.equals("")) {
if(typeInfo != null &&
(typeInfo.contentType != XMLElementDecl.TYPE_MIXED_SIMPLE &&
typeInfo.contentType != XMLElementDecl.TYPE_MIXED_COMPLEX &&
typeInfo.contentType != XMLElementDecl.TYPE_SIMPLE)) {
// REVISIT: Localize
reportGenericSchemaError ("e-props-correct.2.1: element " + nameStr + " has a fixed or default value and must have a mixed or simple content model");
}
if(typeInfo != null &&
(typeInfo.contentType == XMLElementDecl.TYPE_MIXED_SIMPLE ||
typeInfo.contentType == XMLElementDecl.TYPE_MIXED_COMPLEX)) {
if (!particleEmptiable(typeInfo.contentSpecHandle))
reportGenericSchemaError ("e-props-correct.2.2.2: for element " + nameStr + ", the {content type} is mixed, then the {content type}'s particle must be emptiable");
}
try {
if(dv != null) {
dv.validate(defaultStr, null);
}
} catch (InvalidDatatypeValueException ide) {
reportGenericSchemaError ("e-props-correct.2: invalid fixed or default value '" + defaultStr + "' in element " + nameStr);
}
}
if (!defaultStr.equals("") &&
dv != null && dv instanceof IDDatatypeValidator) {
reportGenericSchemaError ("e-props-correct.4: If the {type definition} or {type definition}'s {content type} is or is derived from ID then there must not be a {value constraint} -- element " + nameStr);
}
//
// Create element decl
//
int elementNameIndex = fStringPool.addSymbol(nameStr);
int localpartIndex = elementNameIndex;
int uriIndex = StringPool.EMPTY_STRING;
int enclosingScope = fCurrentScope;
//refer to 4.3.2 in "XML Schema Part 1: Structures"
if ( isTopLevel(elementDecl)) {
uriIndex = fTargetNSURI;
enclosingScope = TOP_LEVEL_SCOPE;
}
else if ( !formStr.equals(SchemaSymbols.ATTVAL_UNQUALIFIED) &&
(( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)||
fElementDefaultQualified ))) {
uriIndex = fTargetNSURI;
}
//There can never be two elements with the same name and different type in the same scope.
int existSuchElementIndex = fSchemaGrammar.getElementDeclIndex(uriIndex, localpartIndex, enclosingScope);
if ( existSuchElementIndex > -1) {
fSchemaGrammar.getElementDecl(existSuchElementIndex, fTempElementDecl);
DatatypeValidator edv = fTempElementDecl.datatypeValidator;
ComplexTypeInfo eTypeInfo = fSchemaGrammar.getElementComplexTypeInfo(existSuchElementIndex);
if ( ((eTypeInfo != null)&&(eTypeInfo!=typeInfo))
|| ((edv != null)&&(edv != dv)) ) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("duplicate element decl in the same scope : " +
fStringPool.toString(localpartIndex));
}
}
QName eltQName = new QName(-1,localpartIndex,elementNameIndex,uriIndex);
// add element decl to pool
int attrListHead = -1 ;
// copy up attribute decls from type object
if (typeInfo != null) {
attrListHead = typeInfo.attlistHead;
}
int elementIndex = fSchemaGrammar.addElementDecl(eltQName, enclosingScope, scopeDefined,
contentSpecType, contentSpecNodeIndex,
attrListHead, dv);
if ( DEBUGGING ) {
/***/
System.out.println("########elementIndex:"+elementIndex+" ("+fStringPool.toString(eltQName.uri)+","
+ fStringPool.toString(eltQName.localpart) + ")"+
" eltType:"+typeStr+" contentSpecType:"+contentSpecType+
" SpecNodeIndex:"+ contentSpecNodeIndex +" enclosingScope: " +enclosingScope +
" scopeDefined: " +scopeDefined+"\n");
/***/
}
fSchemaGrammar.setElementComplexTypeInfo(elementIndex, typeInfo);
// REVISIT: should we report error if typeInfo was null?
// mark element if its type belongs to different Schema.
fSchemaGrammar.setElementFromAnotherSchemaURI(elementIndex, fromAnotherSchema);
// set BlockSet, FinalSet, Nillable and Abstract for this element decl
fSchemaGrammar.setElementDeclBlockSet(elementIndex, blockSet);
fSchemaGrammar.setElementDeclFinalSet(elementIndex, finalSet);
fSchemaGrammar.setElementDeclMiscFlags(elementIndex, elementMiscFlags);
fSchemaGrammar.setElementDefault(elementIndex, defaultStr);
// setSubstitutionGroupElementFullName
fSchemaGrammar.setElementDeclSubstitutionGroupElementFullName(elementIndex, substitutionGroupFullName);
//
// key/keyref/unique processing
//
Element ic = XUtil.getFirstChildElementNS(elementDecl, IDENTITY_CONSTRAINTS);
if (ic != null) {
Integer elementIndexObj = new Integer(elementIndex);
Vector identityConstraints = (Vector)fIdentityConstraints.get(elementIndexObj);
if (identityConstraints == null) {
identityConstraints = new Vector();
fIdentityConstraints.put(elementIndexObj, identityConstraints);
}
while (ic != null) {
if (DEBUG_IC_DATATYPES) {
System.out.println("<ICD>: adding ic for later traversal: "+ic);
}
identityConstraints.addElement(ic);
ic = XUtil.getNextSiblingElementNS(ic, IDENTITY_CONSTRAINTS);
}
}
return eltQName;
}// end of method traverseElementDecl(Element)
private void traverseIdentityNameConstraintsFor(int elementIndex,
Vector identityConstraints)
throws Exception {
// iterate over identity constraints for this element
int size = identityConstraints != null ? identityConstraints.size() : 0;
if (size > 0) {
// REVISIT: Use cached copy. -Ac
XMLElementDecl edecl = new XMLElementDecl();
fSchemaGrammar.getElementDecl(elementIndex, edecl);
for (int i = 0; i < size; i++) {
Element ic = (Element)identityConstraints.elementAt(i);
String icName = ic.getLocalName();
if ( icName.equals(SchemaSymbols.ELT_KEY) ) {
traverseKey(ic, edecl);
}
else if ( icName.equals(SchemaSymbols.ELT_UNIQUE) ) {
traverseUnique(ic, edecl);
}
fSchemaGrammar.setElementDecl(elementIndex, edecl);
} // loop over vector elements
} // if size > 0
} // traverseIdentityNameConstraints(Vector)
private void traverseIdentityRefConstraintsFor(int elementIndex,
Vector identityConstraints)
throws Exception {
// iterate over identity constraints for this element
int size = identityConstraints != null ? identityConstraints.size() : 0;
if (size > 0) {
// REVISIT: Use cached copy. -Ac
XMLElementDecl edecl = new XMLElementDecl();
fSchemaGrammar.getElementDecl(elementIndex, edecl);
for (int i = 0; i < size; i++) {
Element ic = (Element)identityConstraints.elementAt(i);
String icName = ic.getLocalName();
if ( icName.equals(SchemaSymbols.ELT_KEYREF) ) {
traverseKeyRef(ic, edecl);
}
fSchemaGrammar.setElementDecl(elementIndex, edecl);
} // loop over vector elements
} // if size > 0
} // traverseIdentityRefConstraints(Vector)
private void traverseUnique(Element uElem, XMLElementDecl eDecl)
throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(uElem, scope);
// create identity constraint
String uName = uElem.getAttribute(SchemaSymbols.ATT_NAME);
if (DEBUG_IDENTITY_CONSTRAINTS) {
System.out.println("<IC>: traverseUnique(\""+uElem.getNodeName()+"\") ["+uName+']');
}
String eName = getElementNameFor(uElem);
Unique unique = new Unique(uName, eName);
if(fIdentityConstraintNames.get(fTargetNSURIString+","+uName) != null) {
reportGenericSchemaError("More than one identity constraint named " + uName);
}
fIdentityConstraintNames.put(fTargetNSURIString+","+uName, unique);
// get selector and fields
traverseIdentityConstraint(unique, uElem);
// add to element decl
eDecl.unique.addElement(unique);
} // traverseUnique(Element,XMLElementDecl)
private void traverseKey(Element kElem, XMLElementDecl eDecl)
throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(kElem, scope);
// create identity constraint
String kName = kElem.getAttribute(SchemaSymbols.ATT_NAME);
if (DEBUG_IDENTITY_CONSTRAINTS) {
System.out.println("<IC>: traverseKey(\""+kElem.getNodeName()+"\") ["+kName+']');
}
String eName = getElementNameFor(kElem);
Key key = new Key(kName, eName);
if(fIdentityConstraintNames.get(fTargetNSURIString+","+kName) != null) {
reportGenericSchemaError("More than one identity constraint named " + kName);
}
fIdentityConstraintNames.put(fTargetNSURIString+","+kName, key);
// get selector and fields
traverseIdentityConstraint(key, kElem);
// add to element decl
eDecl.key.addElement(key);
} // traverseKey(Element,XMLElementDecl)
private void traverseKeyRef(Element krElem, XMLElementDecl eDecl)
throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(krElem, scope);
// create identity constraint
String krName = krElem.getAttribute(SchemaSymbols.ATT_NAME);
String kName = krElem.getAttribute(SchemaSymbols.ATT_REFER);
if (DEBUG_IDENTITY_CONSTRAINTS) {
System.out.println("<IC>: traverseKeyRef(\""+krElem.getNodeName()+"\") ["+krName+','+kName+']');
}
if(fIdentityConstraintNames.get(fTargetNSURIString+","+krName) != null) {
reportGenericSchemaError("More than one identity constraint named " + krName);
}
// verify that key reference "refer" attribute is valid
String prefix = "";
String localpart = kName;
int colonptr = kName.indexOf(":");
if ( colonptr > 0) {
prefix = kName.substring(0,colonptr);
localpart = kName.substring(colonptr+1);
}
String uriStr = resolvePrefixToURI(prefix);
IdentityConstraint kId = (IdentityConstraint)fIdentityConstraintNames.get(uriStr+","+localpart);
if (kId== null) {
reportSchemaError(SchemaMessageProvider.KeyRefReferNotFound,
new Object[]{krName,kName});
return;
}
String eName = getElementNameFor(krElem);
KeyRef keyRef = new KeyRef(krName, kId, eName);
// add to element decl
traverseIdentityConstraint(keyRef, krElem);
// add key reference to element decl
eDecl.keyRef.addElement(keyRef);
// store in fIdentityConstraintNames so can flag schemas in which multiple
// keyrefs with the same name are present.
fIdentityConstraintNames.put(fTargetNSURIString+","+krName, keyRef);
} // traverseKeyRef(Element,XMLElementDecl)
private void traverseIdentityConstraint(IdentityConstraint ic,
Element icElem) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(icElem, scope);
// check for <annotation> and get selector
Element sElem = XUtil.getFirstChildElement(icElem);
if(sElem == null) {
// REVISIT: localize
reportGenericSchemaError("The content of an identity constraint must match (annotation?, selector, field+)");
return;
}
sElem = checkContent( icElem, sElem, false);
// General Attribute Checking
attrValues = fGeneralAttrCheck.checkAttributes(sElem, scope);
if(!sElem.getLocalName().equals(SchemaSymbols.ELT_SELECTOR)) {
// REVISIT: localize
reportGenericSchemaError("The content of an identity constraint must match (annotation?, selector, field+)");
}
// and make sure <selector>'s content is fine:
checkContent(icElem, XUtil.getFirstChildElement(sElem), true);
String sText = sElem.getAttribute(SchemaSymbols.ATT_XPATH);
sText = sText.trim();
Selector.XPath sXpath = null;
try {
// REVISIT: Must get ruling from XML Schema working group
// regarding whether steps in the XPath must be
// fully qualified if the grammar has a target
// namespace. -Ac
// RESOLUTION: Yes.
sXpath = new Selector.XPath(sText, fStringPool,
fNamespacesScope);
Selector selector = new Selector(sXpath, ic);
if (DEBUG_IDENTITY_CONSTRAINTS) {
System.out.println("<IC>: selector: "+selector);
}
ic.setSelector(selector);
}
catch (XPathException e) {
// REVISIT: Add error message.
reportGenericSchemaError(e.getMessage());
return;
}
// get fields
Element fElem = XUtil.getNextSiblingElement(sElem);
if(fElem == null) {
// REVISIT: localize
reportGenericSchemaError("The content of an identity constraint must match (annotation?, selector, field+)");
}
while (fElem != null) {
// General Attribute Checking
attrValues = fGeneralAttrCheck.checkAttributes(fElem, scope);
if(!fElem.getLocalName().equals(SchemaSymbols.ELT_FIELD))
// REVISIT: localize
reportGenericSchemaError("The content of an identity constraint must match (annotation?, selector, field+)");
// and make sure <field>'s content is fine:
checkContent(icElem, XUtil.getFirstChildElement(fElem), true);
String fText = fElem.getAttribute(SchemaSymbols.ATT_XPATH);
fText = fText.trim();
try {
// REVISIT: Must get ruling from XML Schema working group
// regarding whether steps in the XPath must be
// fully qualified if the grammar has a target
// namespace. -Ac
// RESOLUTION: Yes.
Field.XPath fXpath = new Field.XPath(fText, fStringPool,
fNamespacesScope);
// REVISIT: Get datatype validator. -Ac
// cannot statically determine type of field; not just because of descendant/union
// but because of <any> and <anyAttribute>. - NG
// DatatypeValidator validator = getDatatypeValidatorFor(parent, sXpath, fXpath);
// if (DEBUG_IC_DATATYPES) {
// System.out.println("<ICD>: datatype validator: "+validator);
// }
// must find DatatypeValidator in the Validator...
Field field = new Field(fXpath, ic);
if (DEBUG_IDENTITY_CONSTRAINTS) {
System.out.println("<IC>: field: "+field);
}
ic.addField(field);
}
catch (XPathException e) {
// REVISIT: Add error message.
reportGenericSchemaError(e.getMessage());
return;
}
fElem = XUtil.getNextSiblingElement(fElem);
}
} // traverseIdentityConstraint(IdentityConstraint,Element)
/* This code is no longer used because datatypes can't be found statically for ID constraints.
private DatatypeValidator getDatatypeValidatorFor(Element element,
Selector.XPath sxpath,
Field.XPath fxpath)
throws Exception {
// variables
String ename = element.getAttribute("name");
if (DEBUG_IC_DATATYPES) {
System.out.println("<ICD>: XMLValidator#getDatatypeValidatorFor("+
ename+','+sxpath+','+fxpath+')');
}
int localpart = fStringPool.addSymbol(ename);
String targetNamespace = fSchemaRootElement.getAttribute("targetNamespace");
int uri = fStringPool.addSymbol(targetNamespace);
int edeclIndex = fSchemaGrammar.getElementDeclIndex(uri, localpart,
Grammar.TOP_LEVEL_SCOPE);
// walk selector
XPath.LocationPath spath = sxpath.getLocationPath();
XPath.Step[] ssteps = spath.steps;
for (int i = 0; i < ssteps.length; i++) {
XPath.Step step = ssteps[i];
XPath.Axis axis = step.axis;
XPath.NodeTest nodeTest = step.nodeTest;
switch (axis.type) {
case XPath.Axis.ATTRIBUTE: {
// REVISIT: Add message. -Ac
reportGenericSchemaError("not allowed to select attribute");
return null;
}
case XPath.Axis.CHILD: {
int index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, edeclIndex);
if (index == -1) {
index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, Grammar.TOP_LEVEL_SCOPE);
}
if (index == -1) {
// REVISIT: Add message. -Ac
reportGenericSchemaError("no such element \""+fStringPool.toString(nodeTest.name.rawname)+'"');
return null;
}
edeclIndex = index;
break;
}
case XPath.Axis.SELF: {
// no-op
break;
}
default: {
// REVISIT: Add message. -Ac
reportGenericSchemaError("invalid selector axis");
return null;
}
}
}
// walk field
XPath.LocationPath fpath = fxpath.getLocationPath();
XPath.Step[] fsteps = fpath.steps;
for (int i = 0; i < fsteps.length; i++) {
XPath.Step step = fsteps[i];
XPath.Axis axis = step.axis;
XPath.NodeTest nodeTest = step.nodeTest;
switch (axis.type) {
case XPath.Axis.ATTRIBUTE: {
if (i != fsteps.length - 1) {
// REVISIT: Add message. -Ac
reportGenericSchemaError("attribute must be last step");
return null;
}
// look up validator
int adeclIndex = fSchemaGrammar.getAttributeDeclIndex(edeclIndex, nodeTest.name);
if (adeclIndex == -1) {
// REVISIT: Add message. -Ac
reportGenericSchemaError("no such attribute \""+fStringPool.toString(nodeTest.name.rawname)+'"');
}
XMLAttributeDecl adecl = new XMLAttributeDecl();
fSchemaGrammar.getAttributeDecl(adeclIndex, adecl);
DatatypeValidator validator = adecl.datatypeValidator;
return validator;
}
case XPath.Axis.CHILD: {
int index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, edeclIndex);
if (index == -1) {
index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, Grammar.TOP_LEVEL_SCOPE);
}
if (index == -1) {
// REVISIT: Add message. -Ac
reportGenericSchemaError("no such element \""+fStringPool.toString(nodeTest.name.rawname)+'"');
return null;
}
edeclIndex = index;
if (i < fsteps.length - 1) {
break;
}
// NOTE: Let fall through to self case so that we
// avoid duplicating code. -Ac
}
case XPath.Axis.SELF: {
// look up validator, if needed
if (i == fsteps.length - 1) {
XMLElementDecl edecl = new XMLElementDecl();
fSchemaGrammar.getElementDecl(edeclIndex, edecl);
if (edecl.type != XMLElementDecl.TYPE_SIMPLE) {
// REVISIT: Add message. -Ac
reportGenericSchemaError("selected element is not of simple type");
return null;
}
DatatypeValidator validator = edecl.datatypeValidator;
if (validator == null) validator = new StringDatatypeValidator();
return validator;
}
break;
}
default: {
// REVISIT: Add message. -Ac
reportGenericSchemaError("invalid selector axis");
return null;
}
}
}
// no validator!
// REVISIT: Add message. -Ac
reportGenericSchemaError("No datatype validator for field "+fxpath+
" of element "+ename);
return null;
} // getDatatypeValidatorFor(XPath):DatatypeValidator
*/ // back in to live code...
private String getElementNameFor(Element icnode) {
Element enode = (Element)icnode.getParentNode();
String ename = enode.getAttribute("name");
if (ename.length() == 0) {
ename = enode.getAttribute("ref");
}
return ename;
} // getElementNameFor(Element):String
int getLocalPartIndex(String fullName){
int colonAt = fullName.indexOf(":");
String localpart = fullName;
if ( colonAt > -1 ) {
localpart = fullName.substring(colonAt+1);
}
return fStringPool.addSymbol(localpart);
}
String getLocalPart(String fullName){
int colonAt = fullName.indexOf(":");
String localpart = fullName;
if ( colonAt > -1 ) {
localpart = fullName.substring(colonAt+1);
}
return localpart;
}
int getPrefixIndex(String fullName){
int colonAt = fullName.indexOf(":");
String prefix = "";
if ( colonAt > -1 ) {
prefix = fullName.substring(0,colonAt);
}
return fStringPool.addSymbol(prefix);
}
String getPrefix(String fullName){
int colonAt = fullName.indexOf(":");
String prefix = "";
if ( colonAt > -1 ) {
prefix = fullName.substring(0,colonAt);
}
return prefix;
}
private void checkSubstitutionGroupOK(Element elementDecl, Element substitutionGroupElementDecl,
boolean noErrorSoFar, int substitutionGroupElementDeclIndex, SchemaGrammar substitutionGroupGrammar, ComplexTypeInfo typeInfo,
ComplexTypeInfo substitutionGroupEltTypeInfo, DatatypeValidator dv,
DatatypeValidator substitutionGroupEltDV) throws Exception {
// here we must do two things:
// 1. Make sure there actually *is* a relation between the types of
// the element being nominated and the element doing the nominating;
// (see PR 3.3.6 point #3 in the first tableau, for instance; this
// and the corresponding tableaux from 3.4.6 and 3.14.6 rule out the nominated
// element having an anonymous type declaration.
// 2. Make sure the nominated element allows itself to be nominated by
// an element with the given type-relation.
// Note: we assume that (complex|simple)Type processing checks
// whether the type in question allows itself to
// be modified as this element desires.
// Check for type relationship;
// that is, make sure that the type we're deriving has some relationship
// to substitutionGroupElt's type.
if (typeInfo != null) {
int derivationMethod = typeInfo.derivedBy;
if(typeInfo.baseComplexTypeInfo == null) {
if (typeInfo.baseDataTypeValidator != null) { // take care of complexType based on simpleType case...
DatatypeValidator dTemp = typeInfo.baseDataTypeValidator;
for(; dTemp != null; dTemp = dTemp.getBaseValidator()) {
// WARNING!!! This uses comparison by reference andTemp is thus inherently suspect!
if(dTemp == substitutionGroupEltDV) break;
}
if (dTemp == null) {
if(substitutionGroupEltDV instanceof UnionDatatypeValidator) {
// dv must derive from one of its members...
Vector subUnionMemberDV = ((UnionDatatypeValidator)substitutionGroupEltDV).getBaseValidators();
int subUnionSize = subUnionMemberDV.size();
boolean found = false;
for (int i=0; i<subUnionSize && !found; i++) {
DatatypeValidator dTempSub = (DatatypeValidator)subUnionMemberDV.elementAt(i);
DatatypeValidator dTempOrig = typeInfo.baseDataTypeValidator;
for(; dTempOrig != null; dTempOrig = dTempOrig.getBaseValidator()) {
// WARNING!!! This uses comparison by reference andTemp is thus inherently suspect!
if(dTempSub == dTempOrig) {
found = true;
break;
}
}
}
if(!found) {
// REVISIT: localize
reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type which does not derive from the type of the element at the head of the substitution group");
noErrorSoFar = false;
}
} else {
// REVISIT: localize
reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type which does not derive from the type of the element at the head of the substitution group");
noErrorSoFar = false;
}
} else { // now let's see if substitutionGroup element allows this:
if((derivationMethod & substitutionGroupGrammar.getElementDeclFinalSet(substitutionGroupElementDeclIndex)) != 0) {
noErrorSoFar = false;
// REVISIT: localize
reportGenericSchemaError("element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME)
+ " cannot be part of the substitution group headed by "
+ substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME));
}
}
} else {
// REVISIT: localize
reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " which is part of a substitution must have a type which derives from the type of the element at the head of the substitution group");
noErrorSoFar = false;
}
} else {
String eltBaseName = typeInfo.baseComplexTypeInfo.typeName;
ComplexTypeInfo subTypeInfo = substitutionGroupEltTypeInfo;
for (; subTypeInfo != null && !subTypeInfo.typeName.equals(eltBaseName); subTypeInfo = subTypeInfo.baseComplexTypeInfo);
if (subTypeInfo == null) { // then this type isn't in the chain...
// REVISIT: localize
reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type whose base is " + eltBaseName + "; this basetype does not derive from the type of the element at the head of the substitution group");
noErrorSoFar = false;
} else { // type is fine; does substitutionElement allow this?
if((derivationMethod & substitutionGroupGrammar.getElementDeclFinalSet(substitutionGroupElementDeclIndex)) != 0) {
noErrorSoFar = false;
// REVISIT: localize
reportGenericSchemaError("element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME)
+ " cannot be part of the substitution group headed by "
+ substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME));
}
}
}
} else if (dv != null) { // do simpleType case...
// first, check for type relation.
if (!(checkSimpleTypeDerivationOK(dv,substitutionGroupEltDV))) {
// REVISIT: localize
reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type which does not derive from the type of the element at the head of the substitution group");
noErrorSoFar = false;
}
else { // now let's see if substitutionGroup element allows this:
if((SchemaSymbols.RESTRICTION & substitutionGroupGrammar.getElementDeclFinalSet(substitutionGroupElementDeclIndex)) != 0) {
noErrorSoFar = false;
// REVISIT: localize
reportGenericSchemaError("element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME)
+ " cannot be part of the substitution group headed by "
+ substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME));
}
}
}
}
//
// A utility method to check whether a particular datatypevalidator d, was validly
// derived from another datatypevalidator, b
//
private boolean checkSimpleTypeDerivationOK(DatatypeValidator d, DatatypeValidator b) {
DatatypeValidator dTemp = d;
for(; dTemp != null; dTemp = dTemp.getBaseValidator()) {
// WARNING!!! This uses comparison by reference andTemp is thus inherently suspect!
if(dTemp == b) break;
}
if (dTemp == null) {
// now if b is a union, then we can
// derive from it if we derive from any of its members' types.
if(b instanceof UnionDatatypeValidator) {
// d must derive from one of its members...
Vector subUnionMemberDV = ((UnionDatatypeValidator)b).getBaseValidators();
int subUnionSize = subUnionMemberDV.size();
boolean found = false;
for (int i=0; i<subUnionSize && !found; i++) {
DatatypeValidator dTempSub = (DatatypeValidator)subUnionMemberDV.elementAt(i);
DatatypeValidator dTempOrig = d;
for(; dTempOrig != null; dTempOrig = dTempOrig.getBaseValidator()) {
// WARNING!!! This uses comparison by reference andTemp is thus inherently suspect!
if(dTempSub == dTempOrig) {
found = true;
break;
}
}
}
if(!found) {
return false;
}
} else {
return false;
}
}
return true;
}
// this originally-simple method is much -complicated by the fact that, when we're
// redefining something, we've not only got to look at the space of the thing
// we're redefining but at the original schema too.
// The idea is to start from the top, then go down through
// our list of schemas until we find what we aant.
// This should not often be necessary, because we've processed
// all redefined schemas, but three are conditions in which
// not all elements so redefined may have been promoted to
// the topmost level.
private Element getTopLevelComponentByName(String componentCategory, String name) throws Exception {
Element child = null;
SchemaInfo curr = fSchemaInfoListRoot;
for (; curr != null || curr == fSchemaInfoListRoot; curr = curr.getNext()) {
if (curr != null) curr.restore();
if ( componentCategory.equals(SchemaSymbols.ELT_GROUP) ) {
child = (Element) fSchemaGrammar.topLevelGroupDecls.get(name);
}
else if ( componentCategory.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP ) && fSchemaInfoListRoot == null ) {
child = (Element) fSchemaGrammar.topLevelAttrGrpDecls.get(name);
}
else if ( componentCategory.equals(SchemaSymbols.ELT_ATTRIBUTE ) ) {
child = (Element) fSchemaGrammar.topLevelAttrDecls.get(name);
}
if (child != null ) {
break;
}
child = XUtil.getFirstChildElement(fSchemaRootElement);
if (child == null) {
continue;
}
while (child != null ){
if ( child.getLocalName().equals(componentCategory)) {
if (child.getAttribute(SchemaSymbols.ATT_NAME).equals(name)) {
break;
}
} else if (fRedefineSucceeded && child.getLocalName().equals(SchemaSymbols.ELT_REDEFINE)) {
Element gChild = XUtil.getFirstChildElement(child);
while (gChild != null ){
if (gChild.getLocalName().equals(componentCategory)) {
if (gChild.getAttribute(SchemaSymbols.ATT_NAME).equals(name)) {
break;
}
}
gChild = XUtil.getNextSiblingElement(gChild);
}
if (gChild != null) {
child = gChild;
break;
}
}
child = XUtil.getNextSiblingElement(child);
}
if (child != null || fSchemaInfoListRoot == null) break;
}
// have to reset fSchemaInfoList
if(curr != null)
curr.restore();
else
if (fSchemaInfoListRoot != null)
fSchemaInfoListRoot.restore();
return child;
}
private boolean isTopLevel(Element component) {
String parentName = component.getParentNode().getLocalName();
return (parentName.endsWith(SchemaSymbols.ELT_SCHEMA))
|| (parentName.endsWith(SchemaSymbols.ELT_REDEFINE)) ;
}
DatatypeValidator getTypeValidatorFromNS(String newSchemaURI, String localpart) throws Exception {
// The following impl is for the case where every Schema Grammar has its own instance of DatatypeRegistry.
// Now that we have only one DataTypeRegistry used by all schemas. this is not needed.
/*****
Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI);
if (grammar != null && grammar instanceof SchemaGrammar) {
SchemaGrammar sGrammar = (SchemaGrammar) grammar;
DatatypeValidator dv = (DatatypeValidator) fSchemaGrammar.getDatatypeRegistry().getDatatypeValidator(localpart);
return dv;
}
else {
reportGenericSchemaError("could not resolve URI : " + newSchemaURI + " to a SchemaGrammar in getTypeValidatorFromNS");
}
return null;
/*****/
return getDatatypeValidator(newSchemaURI, localpart);
}
ComplexTypeInfo getTypeInfoFromNS(String newSchemaURI, String localpart) throws Exception {
Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI);
if (grammar != null && grammar instanceof SchemaGrammar) {
SchemaGrammar sGrammar = (SchemaGrammar) grammar;
ComplexTypeInfo typeInfo = (ComplexTypeInfo) sGrammar.getComplexTypeRegistry().get(newSchemaURI+","+localpart);
return typeInfo;
}
else {
reportGenericSchemaError("could not resolve URI : " + newSchemaURI + " to a SchemaGrammar in getTypeInfoFromNS");
}
return null;
}
DatatypeValidator getElementDeclTypeValidatorFromNS(String newSchemaURI, String localpart) throws Exception {
Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI);
if (grammar != null && grammar instanceof SchemaGrammar) {
SchemaGrammar sGrammar = (SchemaGrammar) grammar;
int eltIndex = sGrammar.getElementDeclIndex(fStringPool.addSymbol(newSchemaURI),
fStringPool.addSymbol(localpart),
TOP_LEVEL_SCOPE);
DatatypeValidator dv = null;
if (eltIndex>-1) {
sGrammar.getElementDecl(eltIndex, fTempElementDecl);
dv = fTempElementDecl.datatypeValidator;
}
else {
reportGenericSchemaError("could not find global element : '" + localpart
+ " in the SchemaGrammar "+newSchemaURI);
}
return dv;
}
else {
reportGenericSchemaError("could not resolve URI : " + newSchemaURI
+ " to a SchemaGrammar in getELementDeclTypeValidatorFromNS");
}
return null;
}
ComplexTypeInfo getElementDeclTypeInfoFromNS(String newSchemaURI, String localpart) throws Exception {
Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI);
if (grammar != null && grammar instanceof SchemaGrammar) {
SchemaGrammar sGrammar = (SchemaGrammar) grammar;
int eltIndex = sGrammar.getElementDeclIndex(fStringPool.addSymbol(newSchemaURI),
fStringPool.addSymbol(localpart),
TOP_LEVEL_SCOPE);
ComplexTypeInfo typeInfo = null;
if (eltIndex>-1) {
typeInfo = sGrammar.getElementComplexTypeInfo(eltIndex);
}
else {
reportGenericSchemaError("could not find global element : '" + localpart
+ " in the SchemaGrammar "+newSchemaURI);
}
return typeInfo;
}
else {
reportGenericSchemaError("could not resolve URI : " + newSchemaURI
+ " to a SchemaGrammar in getElementDeclTypeInfoFromNS");
}
return null;
}
/**
* Traverses notation declaration
* and saves it in a registry.
* Notations are stored in registry with the following
* key: "uri:localname"
*
* @param notation child <notation>
* @return local name of notation
* @exception Exception
*/
private String traverseNotationDecl( Element notation ) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(notation, scope);
String name = notation.getAttribute(SchemaSymbols.ATT_NAME);
String qualifiedName =name;
if (fTargetNSURIString.length () != 0) {
qualifiedName = fTargetNSURIString+":"+name;
}
if (fNotationRegistry.get(qualifiedName)!=null) {
return name;
}
String publicId = notation.getAttribute(SchemaSymbols.ATT_PUBLIC);
String systemId = notation.getAttribute(SchemaSymbols.ATT_SYSTEM);
if (publicId.length() == 0 && systemId.length() == 0) {
//REVISIT: update error messages
reportGenericSchemaError("<notation> declaration is invalid");
}
if (name.equals("")) {
//REVISIT: update error messages
reportGenericSchemaError("<notation> declaration does not have a name");
}
fNotationRegistry.put(qualifiedName, name);
//we don't really care if something inside <notation> is wrong..
checkContent( notation, XUtil.getFirstChildElement(notation), true );
//REVISIT: wait for DOM L3 APIs to pass info to application
//REVISIT: SAX2 does not support notations. API should be changed.
return name;
}
/**
* This methods will traverse notation from current schema,
* as well as from included or imported schemas
*
* @param notationName
* localName of notation
* @param uriStr uriStr for schema grammar
* @return return local name for Notation (if found), otherwise
* return empty string;
* @exception Exception
*/
private String traverseNotationFromAnotherSchema( String notationName , String uriStr ) throws Exception {
SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr);
if (uriStr == null || aGrammar==null ||! (aGrammar instanceof SchemaGrammar) ) {
// REVISIT: Localize
reportGenericSchemaError("!!Schema not found in #traverseNotationDeclFromAnotherSchema, "+
"schema uri: " + uriStr
+", groupName: " + notationName);
return "";
}
String savedNSURIString = fTargetNSURIString;
fTargetNSURIString = fStringPool.toString(fStringPool.addSymbol(aGrammar.getTargetNamespaceURI()));
if (DEBUGGING) {
System.out.println("[traverseFromAnotherSchema]: " + fTargetNSURIString);
}
String qualifiedName = fTargetNSURIString + ":" + notationName;
String localName = (String)fNotationRegistry.get(qualifiedName);
if(localName != null ) // we've already traversed this notation
return localName;
//notation decl has not been traversed yet
Element notationDecl = (Element) aGrammar.topLevelNotationDecls.get((Object)notationName);
if (notationDecl == null) {
// REVISIT: Localize
reportGenericSchemaError( "no notation named \"" + notationName
+ "\" was defined in schema : " + uriStr);
return "";
}
localName = traverseNotationDecl(notationDecl);
fTargetNSURIString = savedNSURIString;
return localName;
} // end of method traverseNotationFromAnotherSchema
/**
* Traverse Group Declaration.
*
* <group
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* name = NCName
* ref = QName>
* Content: (annotation? , (all | choice | sequence)?)
* <group/>
*
* @param elementDecl
* @return
* @exception Exception
*/
private int traverseGroupDecl( Element groupDecl ) throws Exception {
// General Attribute Checking
int scope = isTopLevel(groupDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(groupDecl, scope);
String groupName = groupDecl.getAttribute(SchemaSymbols.ATT_NAME);
String ref = groupDecl.getAttribute(SchemaSymbols.ATT_REF);
Element child = checkContent( groupDecl, XUtil.getFirstChildElement(groupDecl), true );
if (!ref.equals("")) {
if (isTopLevel(groupDecl))
// REVISIT: localize
reportGenericSchemaError ( "A group with \"ref\" present must not have <schema> or <redefine> as its parent");
if (!groupName.equals(""))
// REVISIT: localize
reportGenericSchemaError ( "group " + groupName + " cannot refer to another group, but it refers to " + ref);
// there should be no children for <group ref="...">
if (XUtil.getFirstChildElement(groupDecl)!=null)
reportGenericSchemaError ( "A group with \"ref\" present must not have children");
String prefix = "";
String localpart = ref;
int colonptr = ref.indexOf(":");
if ( colonptr > 0) {
prefix = ref.substring(0,colonptr);
localpart = ref.substring(colonptr+1);
}
int localpartIndex = fStringPool.addSymbol(localpart);
String uriStr = resolvePrefixToURI(prefix);
if (!uriStr.equals(fTargetNSURIString)) {
return traverseGroupDeclFromAnotherSchema(localpart, uriStr);
}
Object contentSpecHolder = fGroupNameRegistry.get(uriStr + "," + localpart);
if(contentSpecHolder != null ) { // we may have already traversed this group
boolean fail = false;
int contentSpecHolderIndex = 0;
try {
contentSpecHolderIndex = ((Integer)contentSpecHolder).intValue();
} catch (ClassCastException c) {
fail = true;
}
if(!fail) {
return contentSpecHolderIndex;
}
}
// Check if we are in the middle of traversing this group (i.e. circular references)
if (fCurrentGroupNameStack.search((Object)localpart) > - 1) {
reportGenericSchemaError("mg-props-correct: Circular definition for group " + localpart);
return -2;
}
int contentSpecIndex = -1;
Element referredGroup = getTopLevelComponentByName(SchemaSymbols.ELT_GROUP,localpart);
if (referredGroup == null) {
// REVISIT: Localize
reportGenericSchemaError("Group " + localpart + " not found in the Schema");
//REVISIT, this should be some custom Exception
//throw new RuntimeException("Group " + localpart + " not found in the Schema");
}
else {
contentSpecIndex = traverseGroupDecl(referredGroup);
}
return contentSpecIndex;
} else if (groupName.equals(""))
// REVISIT: Localize
reportGenericSchemaError("a <group> must have a name or a ref present");
String qualifiedGroupName = fTargetNSURIString + "," + groupName;
Object contentSpecHolder = fGroupNameRegistry.get(qualifiedGroupName);
if(contentSpecHolder != null ) { // we may have already traversed this group
boolean fail = false;
int contentSpecHolderIndex = 0;
try {
contentSpecHolderIndex = ((Integer)contentSpecHolder).intValue();
} catch (ClassCastException c) {
fail = true;
}
if(!fail) {
return contentSpecHolderIndex;
}
}
// if we're here then we're traversing a top-level group that we've never seen before.
// Push the group name onto a stack, so that we can check for circular groups
fCurrentGroupNameStack.push(groupName);
// Save the scope and set the current scope to -1
int savedScope = fCurrentScope;
fCurrentScope = -1;
int index = -2;
boolean illegalChild = false;
String childName =
(child != null) ? child.getLocalName() : "";
if (childName.equals(SchemaSymbols.ELT_ALL)) {
index = traverseAll(child);
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
}
else if (!childName.equals("") || (child != null && XUtil.getNextSiblingElement(child) != null)) {
illegalChild = true;
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "group", childName });
}
//Must have all or choice or sequence child.
if (child == null) {
reportGenericSchemaError("Named group must contain an 'all', 'choice' or 'sequence' child");
}
else if (XUtil.getNextSiblingElement(child) != null) {
illegalChild = true;
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "group", childName });
}
if ( ! illegalChild && child != null) {
index = handleOccurrences(index, child, CHILD_OF_GROUP);
}
contentSpecHolder = new Integer(index);
fCurrentGroupNameStack.pop();
fCurrentScope = savedScope;
fGroupNameRegistry.put(qualifiedGroupName, contentSpecHolder);
return index;
}
private int traverseGroupDeclFromAnotherSchema( String groupName , String uriStr ) throws Exception {
SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr);
if (uriStr == null || aGrammar==null ||! (aGrammar instanceof SchemaGrammar) ) {
// REVISIT: Localize
reportGenericSchemaError("!!Schema not found in #traverseGroupDeclFromAnotherSchema, "+
"schema uri: " + uriStr
+", groupName: " + groupName);
return -1;
}
Element groupDecl = (Element) aGrammar.topLevelGroupDecls.get((Object)groupName);
if (groupDecl == null) {
// REVISIT: Localize
reportGenericSchemaError( "no group named \"" + groupName
+ "\" was defined in schema : " + uriStr);
return -1;
}
NamespacesScope saveNSMapping = fNamespacesScope;
int saveTargetNSUri = fTargetNSURI;
fTargetNSURI = fStringPool.addSymbol(aGrammar.getTargetNamespaceURI());
fNamespacesScope = aGrammar.getNamespacesScope();
Element child = checkContent( groupDecl, XUtil.getFirstChildElement(groupDecl), true );
String qualifiedGroupName = fTargetNSURIString + "," + groupName;
Object contentSpecHolder = fGroupNameRegistry.get(qualifiedGroupName);
if(contentSpecHolder != null ) { // we may have already traversed this group
boolean fail = false;
int contentSpecHolderIndex = 0;
try {
contentSpecHolderIndex = ((Integer)contentSpecHolder).intValue();
} catch (ClassCastException c) {
fail = true;
}
if(!fail) {
return contentSpecHolderIndex;
}
}
// ------------------------------------
// if we're here then we're traversing a top-level group that we've never seen before.
int index = -2;
boolean illegalChild = false;
String childName = (child != null) ? child.getLocalName() : "";
if (childName.equals(SchemaSymbols.ELT_ALL)) {
index = traverseAll(child);
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
}
else if (!childName.equals("") || (child != null && XUtil.getNextSiblingElement(child) != null)) {
illegalChild = true;
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "group", childName });
}
if ( ! illegalChild && child != null) {
index = handleOccurrences( index, child);
}
contentSpecHolder = new Integer(index);
fGroupNameRegistry.put(qualifiedGroupName, contentSpecHolder);
fNamespacesScope = saveNSMapping;
fTargetNSURI = saveTargetNSUri;
return index;
} // end of method traverseGroupDeclFromAnotherSchema
/**
*
* Traverse the Sequence declaration
*
* <sequence
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger>
* Content: (annotation? , (element | group | choice | sequence | any)*)
* </sequence>
*
**/
int traverseSequence (Element sequenceDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(sequenceDecl, scope);
Element child = checkContent(sequenceDecl, XUtil.getFirstChildElement(sequenceDecl), true);
int csnType = XMLContentSpec.CONTENTSPECNODE_SEQ;
int left = -2;
int right = -2;
boolean hadContent = false;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
boolean seeParticle = false;
String childName = child.getLocalName();
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_GROUP)) {
index = traverseGroupDecl(child);
// A content type of all can only appear
// as the content type of a complex type definition.
if (hasAllContent(index)) {
reportSchemaError(SchemaMessageProvider.AllContentLimited,
new Object [] { "sequence" });
continue;
}
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ANY)) {
index = traverseAny(child);
seeParticle = true;
}
else {
reportSchemaError(
SchemaMessageProvider.SeqChoiceContentRestricted,
new Object [] { "sequence", childName });
continue;
}
if (index != -2)
hadContent = true;
if (seeParticle) {
index = handleOccurrences( index, child);
}
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
right = index;
}
}
if (hadContent) {
if (right != -2 || fSchemaGrammar.getDeferContentSpecExpansion())
left = fSchemaGrammar.addContentSpecNode(csnType, left, right,
false);
}
return left;
}
/**
*
* Traverse the Choice declaration
*
* <choice
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger>
* Content: (annotation? , (element | group | choice | sequence | any)*)
* </choice>
*
**/
int traverseChoice (Element choiceDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(choiceDecl, scope);
// REVISIT: traverseChoice, traverseSequence can be combined
Element child = checkContent(choiceDecl, XUtil.getFirstChildElement(choiceDecl), true);
int csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE;
int left = -2;
int right = -2;
boolean hadContent = false;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
boolean seeParticle = false;
String childName = child.getLocalName();
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_GROUP)) {
index = traverseGroupDecl(child);
// A model group whose {compositor} is "all" can only appear
// as the {content type} of a complex type definition.
if (hasAllContent(index)) {
reportSchemaError(SchemaMessageProvider.AllContentLimited,
new Object [] { "choice" });
continue;
}
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ANY)) {
index = traverseAny(child);
seeParticle = true;
}
else {
reportSchemaError(
SchemaMessageProvider.SeqChoiceContentRestricted,
new Object [] { "choice", childName });
continue;
}
if (index != -2)
hadContent = true;
if (seeParticle) {
index = handleOccurrences( index, child);
}
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
right = index;
}
}
if (hadContent) {
if (right != -2 || fSchemaGrammar.getDeferContentSpecExpansion())
left = fSchemaGrammar.addContentSpecNode(csnType, left, right,
false);
}
return left;
}
/**
*
* Traverse the "All" declaration
*
* <all
* id = ID
* maxOccurs = 1 : 1
* minOccurs = (0 | 1) : 1>
* Content: (annotation? , element*)
* </all>
**/
int traverseAll(Element allDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(allDecl, scope);
Element child = checkContent(allDecl,
XUtil.getFirstChildElement(allDecl), true);
int csnType = XMLContentSpec.CONTENTSPECNODE_ALL;
int left = -2;
int right = -2;
boolean hadContent = false;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
String childName = child.getLocalName();
// Only elements are allowed in <all>
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode(
XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
index = handleOccurrences(index, child, PROCESSING_ALL);
}
else {
reportSchemaError(SchemaMessageProvider.AllContentRestricted,
new Object [] { childName });
continue;
}
hadContent = true;
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right,
false);
right = index;
}
}
if (hadContent) {
if (right != -2 || fSchemaGrammar.getDeferContentSpecExpansion())
left = fSchemaGrammar.addContentSpecNode(csnType, left, right,
false);
}
return left;
}
// Determines whether a content spec tree represents an "all" content model
private boolean hasAllContent(int contentSpecIndex) {
// If the content is not empty, is the top node ALL?
if (contentSpecIndex > -1) {
XMLContentSpec content = new XMLContentSpec();
fSchemaGrammar.getContentSpec(contentSpecIndex, content);
// An ALL node could be optional, so we have to be prepared
// to look one level below a ZERO_OR_ONE node for an ALL.
if (content.type == XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE) {
fSchemaGrammar.getContentSpec(content.value, content);
}
return (content.type == XMLContentSpec.CONTENTSPECNODE_ALL);
}
return false;
}
// utilities from Tom Watson's SchemaParser class
// TO DO: Need to make this more conformant with Schema int type parsing
private int parseInt (String intString) throws Exception
{
if ( intString.equals("*") ) {
return SchemaSymbols.INFINITY;
} else {
return Integer.parseInt (intString);
}
}
private int parseSimpleFinal (String finalString) throws Exception
{
if ( finalString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) {
return SchemaSymbols.ENUMERATION+SchemaSymbols.RESTRICTION+SchemaSymbols.LIST;
} else {
int enumerate = 0;
int restrict = 0;
int list = 0;
StringTokenizer t = new StringTokenizer (finalString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ("restriction in set twice");
}
} else if ( token.equals (SchemaSymbols.ELT_LIST) ) {
if ( list == 0 ) {
list = SchemaSymbols.LIST;
} else {
// REVISIT: Localize
reportGenericSchemaError ("list in set twice");
}
}
else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid value (" +
finalString +
")" );
}
}
return enumerate+list;
}
}
private int parseDerivationSet (String finalString) throws Exception
{
if ( finalString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) {
return SchemaSymbols.EXTENSION+SchemaSymbols.RESTRICTION;
} else {
int extend = 0;
int restrict = 0;
StringTokenizer t = new StringTokenizer (finalString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.EXTENSION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "extension already in set" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "restriction already in set" );
}
} else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid final value (" + finalString + ")" );
}
}
return extend+restrict;
}
}
private int parseBlockSet (String blockString) throws Exception
{
if( blockString == null)
return fBlockDefault;
else if ( blockString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) {
return SchemaSymbols.SUBSTITUTION+SchemaSymbols.EXTENSION+SchemaSymbols.RESTRICTION;
} else {
int extend = 0;
int restrict = 0;
int substitute = 0;
StringTokenizer t = new StringTokenizer (blockString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ATTVAL_SUBSTITUTION) ) {
if ( substitute == 0 ) {
substitute = SchemaSymbols.SUBSTITUTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'substitution' already in the list" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.EXTENSION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'extension' is already in the list" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'restriction' is already in the list" );
}
} else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid block value (" + blockString + ")" );
}
}
int defaultVal = extend+restrict+substitute;
return (defaultVal == 0 ? fBlockDefault : defaultVal);
}
}
private int parseFinalSet (String finalString) throws Exception
{
if( finalString == null) {
return fFinalDefault;
}
else if ( finalString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) {
return SchemaSymbols.EXTENSION+SchemaSymbols.LIST+SchemaSymbols.RESTRICTION+SchemaSymbols.UNION;
} else {
int extend = 0;
int restrict = 0;
int list = 0;
int union = 0;
StringTokenizer t = new StringTokenizer (finalString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ELT_UNION) ) {
if ( union == 0 ) {
union = SchemaSymbols.UNION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'union' is already in the list" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.EXTENSION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'extension' is already in the list" );
}
} else if ( token.equals (SchemaSymbols.ELT_LIST) ) {
if ( list == 0 ) {
list = SchemaSymbols.LIST;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'list' is already in the list" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'restriction' is already in the list" );
}
} else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid final value (" + finalString + ")" );
}
}
int defaultVal = extend+restrict+list+union;
return (defaultVal == 0 ? fFinalDefault : defaultVal);
}
}
private void reportGenericSchemaError (String error) throws Exception {
if (fErrorReporter == null) {
System.err.println("__TraverseSchemaError__ : " + error);
}
else {
reportSchemaError (SchemaMessageProvider.GenericError, new Object[] { error });
}
}
private void reportSchemaError(int major, Object args[]) throws Exception {
if (fErrorReporter == null) {
System.out.println("__TraverseSchemaError__ : " + SchemaMessageProvider.fgMessageKeys[major]);
for (int i=0; i< args.length ; i++) {
System.out.println((String)args[i]);
}
}
else {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
major,
SchemaMessageProvider.MSG_NONE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
/** Don't check the following code in because it creates a dependency on
the serializer, preventing to package the parser without the serializer
//Unit Test here
public static void main(String args[] ) {
if( args.length != 1 ) {
System.out.println( "Error: Usage java TraverseSchema yourFile.xsd" );
System.exit(0);
}
DOMParser parser = new IgnoreWhitespaceParser();
parser.setEntityResolver( new Resolver() );
parser.setErrorHandler( new ErrorHandler() );
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}catch( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
}catch( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
try {
parser.parse( args[0]);
}catch( IOException e ) {
e.printStackTrace();
}catch( SAXException e ) {
e.printStackTrace();
}
Document document = parser.getDocument(); //Our Grammar
OutputFormat format = new OutputFormat( document );
java.io.StringWriter outWriter = new java.io.StringWriter();
XMLSerializer serial = new XMLSerializer( outWriter,format);
TraverseSchema tst = null;
try {
Element root = document.getDocumentElement();// This is what we pass to TraverserSchema
//serial.serialize( root );
//System.out.println(outWriter.toString());
tst = new TraverseSchema( root, new StringPool(), new SchemaGrammar(), (GrammarResolver) new GrammarResolverImpl() );
}
catch (Exception e) {
e.printStackTrace(System.err);
}
parser.getDocument();
}
**/
static class Resolver implements EntityResolver {
private static final String SYSTEM[] = {
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/structures.dtd",
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/datatypes.dtd",
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/versionInfo.ent",
};
private static final String PATH[] = {
"structures.dtd",
"datatypes.dtd",
"versionInfo.ent",
};
public InputSource resolveEntity(String publicId, String systemId)
throws IOException {
// looking for the schema DTDs?
for (int i = 0; i < SYSTEM.length; i++) {
if (systemId.equals(SYSTEM[i])) {
InputSource source = new InputSource(getClass().getResourceAsStream(PATH[i]));
source.setPublicId(publicId);
source.setSystemId(systemId);
return source;
}
}
// use default resolution
return null;
} // resolveEntity(String,String):InputSource
} // class Resolver
static class ErrorHandler implements org.xml.sax.ErrorHandler {
/** Warning. */
public void warning(SAXParseException ex) {
System.err.println("[Warning] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Error. */
public void error(SAXParseException ex) {
System.err.println("[Error] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Fatal error. */
public void fatalError(SAXParseException ex) throws SAXException {
System.err.println("[Fatal Error] "+
getLocationString(ex)+": "+
ex.getMessage());
throw ex;
}
//
// Private methods
//
/** Returns a string of the location. */
private String getLocationString(SAXParseException ex) {
StringBuffer str = new StringBuffer();
String systemId_ = ex.getSystemId();
if (systemId_ != null) {
int index = systemId_.lastIndexOf('/');
if (index != -1)
systemId_ = systemId_.substring(index + 1);
str.append(systemId_);
}
str.append(':');
str.append(ex.getLineNumber());
str.append(':');
str.append(ex.getColumnNumber());
return str.toString();
} // getLocationString(SAXParseException):String
}
static class IgnoreWhitespaceParser
extends DOMParser {
public void ignorableWhitespace(char ch[], int start, int length) {}
public void ignorableWhitespace(int dataIdx) {}
} // class IgnoreWhitespaceParser
// When in a <redefine>, type definitions being used (and indeed
// refs to <group>'s and <attributeGroup>'s) may refer to info
// items either in the schema being redefined, in the <redefine>,
// or else in the schema doing the redefining. Because of this
// latter we have to be prepared sometimes to look for our type
// definitions outside the schema stored in fSchemaRootElement.
// This simple class does this; it's just a linked list that
// lets us look at the <schema>'s on the queue; note also that this
// should provide us with a mechanism to handle nested <redefine>'s.
// It's also a handy way of saving schema info when importing/including; saves some code.
public class SchemaInfo {
private Element saveRoot;
private SchemaInfo nextRoot;
private SchemaInfo prevRoot;
private String savedSchemaURL = fCurrentSchemaURL;
private boolean saveElementDefaultQualified = fElementDefaultQualified;
private boolean saveAttributeDefaultQualified = fAttributeDefaultQualified;
private int saveScope = fCurrentScope;
private int saveBlockDefault = fBlockDefault;
private int saveFinalDefault = fFinalDefault;
private NamespacesScope saveNamespacesScope = fNamespacesScope;
public SchemaInfo ( boolean saveElementDefaultQualified, boolean saveAttributeDefaultQualified,
int saveBlockDefault, int saveFinalDefault,
int saveScope, String savedSchemaURL, Element saveRoot,
NamespacesScope saveNamespacesScope, SchemaInfo nextRoot, SchemaInfo prevRoot) {
this.saveElementDefaultQualified = saveElementDefaultQualified;
this.saveAttributeDefaultQualified = saveAttributeDefaultQualified;
this.saveBlockDefault = saveBlockDefault;
this.saveFinalDefault = saveFinalDefault;
this.saveScope = saveScope ;
this.savedSchemaURL = savedSchemaURL;
this.saveRoot = saveRoot ;
if(saveNamespacesScope != null)
this.saveNamespacesScope = (NamespacesScope)saveNamespacesScope.clone();
this.nextRoot = nextRoot;
this.prevRoot = prevRoot;
}
public void setNext (SchemaInfo next) {
nextRoot = next;
}
public SchemaInfo getNext () {
return nextRoot;
}
public void setPrev (SchemaInfo prev) {
prevRoot = prev;
}
public String getCurrentSchemaURL() { return savedSchemaURL; }
public SchemaInfo getPrev () {
return prevRoot;
}
public Element getRoot() { return saveRoot; }
// NOTE: this has side-effects!!!
public void restore() {
fCurrentSchemaURL = savedSchemaURL;
fCurrentScope = saveScope;
fElementDefaultQualified = saveElementDefaultQualified;
fAttributeDefaultQualified = saveAttributeDefaultQualified;
fBlockDefault = saveBlockDefault;
fFinalDefault = saveFinalDefault;
fNamespacesScope = (NamespacesScope)saveNamespacesScope.clone();
fSchemaRootElement = saveRoot;
}
} // class SchemaInfo
} // class TraverseSchema
| src/org/apache/xerces/validators/schema/TraverseSchema.java | /*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000,2001 The Apache Software Foundation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.validators.schema;
import org.apache.xerces.framework.XMLErrorReporter;
import org.apache.xerces.validators.common.Grammar;
import org.apache.xerces.validators.common.GrammarResolver;
import org.apache.xerces.validators.common.GrammarResolverImpl;
import org.apache.xerces.validators.common.XMLElementDecl;
import org.apache.xerces.validators.common.XMLAttributeDecl;
import org.apache.xerces.validators.schema.SchemaSymbols;
import org.apache.xerces.validators.schema.XUtil;
import org.apache.xerces.validators.schema.identity.Field;
import org.apache.xerces.validators.schema.identity.IdentityConstraint;
import org.apache.xerces.validators.schema.identity.Key;
import org.apache.xerces.validators.schema.identity.KeyRef;
import org.apache.xerces.validators.schema.identity.Selector;
import org.apache.xerces.validators.schema.identity.Unique;
import org.apache.xerces.validators.schema.identity.XPath;
import org.apache.xerces.validators.schema.identity.XPathException;
import org.apache.xerces.validators.datatype.DatatypeValidator;
import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl;
import org.apache.xerces.validators.datatype.IDDatatypeValidator;
import org.apache.xerces.validators.datatype.NOTATIONDatatypeValidator;
import org.apache.xerces.validators.datatype.StringDatatypeValidator;
import org.apache.xerces.validators.datatype.ListDatatypeValidator;
import org.apache.xerces.validators.datatype.UnionDatatypeValidator;
import org.apache.xerces.validators.datatype.InvalidDatatypeValueException;
import org.apache.xerces.utils.StringPool;
import org.w3c.dom.Element;
import java.io.IOException;
import java.util.*;
import java.net.URL;
import java.net.MalformedURLException;
//REVISIT: for now, import everything in the DOM package
import org.w3c.dom.*;
//Unit Test
import org.apache.xerces.parsers.DOMParser;
import org.apache.xerces.validators.common.XMLValidator;
import org.apache.xerces.validators.datatype.DatatypeValidator.*;
import org.apache.xerces.validators.datatype.InvalidDatatypeValueException;
import org.apache.xerces.framework.XMLContentSpec;
import org.apache.xerces.utils.QName;
import org.apache.xerces.utils.NamespacesScope;
import org.apache.xerces.parsers.SAXParser;
import org.apache.xerces.framework.XMLParser;
import org.apache.xerces.framework.XMLDocumentScanner;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
/** Don't check the following code in because it creates a dependency on
the serializer, preventing to package the parser without the serializer.
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
**/
import org.apache.xerces.validators.schema.SchemaSymbols;
/**
* Instances of this class get delegated to Traverse the Schema and
* to populate the Grammar internal representation by
* instances of Grammar objects.
* Traverse a Schema Grammar:
*
* @author Eric Ye, IBM
* @author Jeffrey Rodriguez, IBM
* @author Andy Clark, IBM
*
* @see org.apache.xerces.validators.common.Grammar
*
* @version $Id$
*/
public class TraverseSchema implements
NamespacesScope.NamespacesHandler{
//CONSTANTS
private static final int TOP_LEVEL_SCOPE = -1;
/** Identity constraint keywords. */
private static final String[][] IDENTITY_CONSTRAINTS = {
{ SchemaSymbols.URI_SCHEMAFORSCHEMA, SchemaSymbols.ELT_UNIQUE },
{ SchemaSymbols.URI_SCHEMAFORSCHEMA, SchemaSymbols.ELT_KEY },
{ SchemaSymbols.URI_SCHEMAFORSCHEMA, SchemaSymbols.ELT_KEYREF },
};
private static final String redefIdentifier = "_redefined";
// Flags for handleOccurrences to indicate any special
// restrictions on minOccurs and maxOccurs relating to "all".
// NOT_ALL_CONTEXT - not processing an <all>
// PROCESSING_ALL - processing an <element> in an <all>
// GROUP_REF_WITH_ALL - processing <group> reference that contained <all>
// CHILD_OF_GROUP - processing a child of a model group definition
private static final int NOT_ALL_CONTEXT = 0;
private static final int PROCESSING_ALL = 1;
private static final int GROUP_REF_WITH_ALL = 2;
private static final int CHILD_OF_GROUP = 4;
//debugging
private static final boolean DEBUGGING = false;
/** Compile to true to debug identity constraints. */
private static final boolean DEBUG_IDENTITY_CONSTRAINTS = false;
/**
* Compile to true to debug datatype validator lookup for
* identity constraint support.
*/
private static final boolean DEBUG_IC_DATATYPES = false;
//private data members
private boolean fFullConstraintChecking = false;
private XMLErrorReporter fErrorReporter = null;
private StringPool fStringPool = null;
private GrammarResolver fGrammarResolver = null;
private SchemaGrammar fSchemaGrammar = null;
private Element fSchemaRootElement;
// this is always set to refer to the root of the linked list containing the root info of schemas under redefinition.
private SchemaInfo fSchemaInfoListRoot = null;
private SchemaInfo fCurrentSchemaInfo = null;
private boolean fRedefineSucceeded;
private DatatypeValidatorFactoryImpl fDatatypeRegistry = null;
private Hashtable fComplexTypeRegistry = new Hashtable();
private Hashtable fAttributeDeclRegistry = new Hashtable();
// stores the names of groups that we've traversed so we can avoid multiple traversals
// qualified group names are keys and their contentSpecIndexes are values.
private Hashtable fGroupNameRegistry = new Hashtable();
// this Hashtable keeps track of whether a given redefined group does so by restriction.
private Hashtable fRestrictedRedefinedGroupRegistry = new Hashtable();
// stores "final" values of simpleTypes--no clean way to integrate this into the existing datatype validation structure...
private Hashtable fSimpleTypeFinalRegistry = new Hashtable();
// stores <notation> decl
private Hashtable fNotationRegistry = new Hashtable();
private Vector fIncludeLocations = new Vector();
private Vector fImportLocations = new Vector();
private Hashtable fRedefineLocations = new Hashtable();
private Vector fTraversedRedefineElements = new Vector();
// Hashtable associating attributeGroups within a <redefine> which
// restrict attributeGroups in the original schema with the
// new name for those groups in the modified redefined schema.
private Hashtable fRedefineAttributeGroupMap = null;
// simpleType data
private Hashtable fFacetData = new Hashtable(10);
private Stack fSimpleTypeNameStack = new Stack();
private String fListName = "";
private int fAnonTypeCount =0;
private int fScopeCount=0;
private int fCurrentScope=TOP_LEVEL_SCOPE;
private int fSimpleTypeAnonCount = 0;
private Stack fCurrentTypeNameStack = new Stack();
private Stack fCurrentGroupNameStack = new Stack();
private Vector fElementRecurseComplex = new Vector();
private boolean fElementDefaultQualified = false;
private boolean fAttributeDefaultQualified = false;
private int fBlockDefault = 0;
private int fFinalDefault = 0;
private int fTargetNSURI;
private String fTargetNSURIString = "";
private NamespacesScope fNamespacesScope = null;
private String fCurrentSchemaURL = "";
private XMLAttributeDecl fTempAttributeDecl = new XMLAttributeDecl();
private XMLAttributeDecl fTemp2AttributeDecl = new XMLAttributeDecl();
private XMLElementDecl fTempElementDecl = new XMLElementDecl();
private XMLElementDecl fTempElementDecl2 = new XMLElementDecl();
private XMLContentSpec tempContentSpec1 = new XMLContentSpec();
private XMLContentSpec tempContentSpec2 = new XMLContentSpec();
private EntityResolver fEntityResolver = null;
private SubstitutionGroupComparator fSComp = null;
private Hashtable fIdentityConstraints = new Hashtable();
// Yet one more data structure; this one associates
// <unique> and <key> QNames with their corresponding objects,
// so that <keyRef>s can find them.
private Hashtable fIdentityConstraintNames = new Hashtable();
// General Attribute Checking
private GeneralAttrCheck fGeneralAttrCheck = null;
private int fXsiURI;
// REVISIT: maybe need to be moved into SchemaGrammar class
public class ComplexTypeInfo {
public String typeName;
public DatatypeValidator baseDataTypeValidator;
public ComplexTypeInfo baseComplexTypeInfo;
public int derivedBy = 0;
public int blockSet = 0;
public int finalSet = 0;
public int miscFlags=0;
public int scopeDefined = -1;
public int contentType;
public int contentSpecHandle = -1;
public int templateElementIndex = -1;
public int attlistHead = -1;
public DatatypeValidator datatypeValidator;
public boolean isAbstractType() {
return ((miscFlags & CT_IS_ABSTRACT)!=0);
}
public boolean containsAttrTypeID () {
return ((miscFlags & CT_CONTAINS_ATTR_TYPE_ID)!=0);
}
public boolean declSeen () {
return ((miscFlags & CT_DECL_SEEN)!=0);
}
public void setIsAbstractType() {
miscFlags |= CT_IS_ABSTRACT;
}
public void setContainsAttrTypeID() {
miscFlags |= CT_CONTAINS_ATTR_TYPE_ID;
}
public void setDeclSeen() {
miscFlags |= CT_DECL_SEEN;
}
}
private static final int CT_IS_ABSTRACT=1;
private static final int CT_CONTAINS_ATTR_TYPE_ID=2;
private static final int CT_DECL_SEEN=4; // indicates that the declaration was
// traversed as opposed to processed due
// to a forward reference
private class ComplexTypeRecoverableError extends Exception {
ComplexTypeRecoverableError() {super();}
ComplexTypeRecoverableError(String s) {super(s);}
}
private class ParticleRecoverableError extends Exception {
ParticleRecoverableError(String s) {super(s);}
}
private class ElementInfo {
int elementIndex;
String typeName;
private ElementInfo(int i, String name) {
elementIndex = i;
typeName = name;
}
}
//REVISIT: verify the URI.
public final static String SchemaForSchemaURI = "http://www.w3.org/TR-1/Schema";
private TraverseSchema( ) {
// new TraverseSchema() is forbidden;
}
public void setFullConstraintCheckingEnabled() {
fFullConstraintChecking = true;
}
public void setGrammarResolver(GrammarResolver grammarResolver){
fGrammarResolver = grammarResolver;
}
public void startNamespaceDeclScope(int prefix, int uri){
//TO DO
}
public void endNamespaceDeclScope(int prefix){
//TO DO, do we need to do anything here?
}
public boolean particleEmptiable(int contentSpecIndex) {
if (!fFullConstraintChecking) {
return true;
}
if (minEffectiveTotalRange(contentSpecIndex)==0)
return true;
else
return false;
}
public int minEffectiveTotalRange(int contentSpecIndex) {
fSchemaGrammar.getContentSpec(contentSpecIndex, tempContentSpec1);
int type = tempContentSpec1.type;
if (type == XMLContentSpec.CONTENTSPECNODE_SEQ ||
type == XMLContentSpec.CONTENTSPECNODE_ALL) {
return minEffectiveTotalRangeSeq(contentSpecIndex);
}
else if (type == XMLContentSpec.CONTENTSPECNODE_CHOICE) {
return minEffectiveTotalRangeChoice(contentSpecIndex);
}
else {
return(fSchemaGrammar.getContentSpecMinOccurs(contentSpecIndex));
}
}
private int minEffectiveTotalRangeSeq(int csIndex) {
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
int type = tempContentSpec1.type;
int left = tempContentSpec1.value;
int right = tempContentSpec1.otherValue;
int min = fSchemaGrammar.getContentSpecMinOccurs(csIndex);
int result;
if (right == -2)
result = min * minEffectiveTotalRange(left);
else
result = min * (minEffectiveTotalRange(left) + minEffectiveTotalRange(right));
return result;
}
private int minEffectiveTotalRangeChoice(int csIndex) {
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
int type = tempContentSpec1.type;
int left = tempContentSpec1.value;
int right = tempContentSpec1.otherValue;
int min = fSchemaGrammar.getContentSpecMinOccurs(csIndex);
int result;
if (right == -2)
result = min * minEffectiveTotalRange(left);
else {
int minLeft = minEffectiveTotalRange(left);
int minRight = minEffectiveTotalRange(right);
result = min * ((minLeft < minRight)?minLeft:minRight);
}
return result;
}
public int maxEffectiveTotalRange(int contentSpecIndex) {
fSchemaGrammar.getContentSpec(contentSpecIndex, tempContentSpec1);
int type = tempContentSpec1.type;
if (type == XMLContentSpec.CONTENTSPECNODE_SEQ ||
type == XMLContentSpec.CONTENTSPECNODE_ALL) {
return maxEffectiveTotalRangeSeq(contentSpecIndex);
}
else if (type == XMLContentSpec.CONTENTSPECNODE_CHOICE) {
return maxEffectiveTotalRangeChoice(contentSpecIndex);
}
else {
return(fSchemaGrammar.getContentSpecMaxOccurs(contentSpecIndex));
}
}
private int maxEffectiveTotalRangeSeq(int csIndex) {
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
int type = tempContentSpec1.type;
int left = tempContentSpec1.value;
int right = tempContentSpec1.otherValue;
int max = fSchemaGrammar.getContentSpecMaxOccurs(csIndex);
if (max == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
int maxLeft = maxEffectiveTotalRange(left);
if (right == -2) {
if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
else
return max * maxLeft;
}
else {
int maxRight = maxEffectiveTotalRange(right);
if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED ||
maxRight == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
else
return max * (maxLeft + maxRight);
}
}
private int maxEffectiveTotalRangeChoice(int csIndex) {
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
int type = tempContentSpec1.type;
int left = tempContentSpec1.value;
int right = tempContentSpec1.otherValue;
int max = fSchemaGrammar.getContentSpecMaxOccurs(csIndex);
if (max == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
int maxLeft = maxEffectiveTotalRange(left);
if (right == -2) {
if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
else
return max * maxLeft;
}
else {
int maxRight = maxEffectiveTotalRange(right);
if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED ||
maxRight == SchemaSymbols.OCCURRENCE_UNBOUNDED)
return SchemaSymbols.OCCURRENCE_UNBOUNDED;
else
return max * ((maxLeft > maxRight)?maxLeft:maxRight);
}
}
private String resolvePrefixToURI (String prefix) throws Exception {
String uriStr = fStringPool.toString(fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix)));
if (uriStr.length() == 0 && prefix.length() > 0) {
// REVISIT: Localize
reportGenericSchemaError("prefix : [" + prefix +"] cannot be resolved to a URI");
return "";
}
//REVISIT, !!!! a hack: needs to be updated later, cause now we only use localpart to key build-in datatype.
if ( prefix.length()==0 && uriStr.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& fTargetNSURIString.length() == 0) {
uriStr = "";
}
return uriStr;
}
public TraverseSchema(Element root, StringPool stringPool,
SchemaGrammar schemaGrammar,
GrammarResolver grammarResolver,
XMLErrorReporter errorReporter,
String schemaURL,
EntityResolver entityResolver,
boolean fullChecking
) throws Exception {
fErrorReporter = errorReporter;
fCurrentSchemaURL = schemaURL;
fFullConstraintChecking = fullChecking;
fEntityResolver = entityResolver;
doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver);
}
public TraverseSchema(Element root, StringPool stringPool,
SchemaGrammar schemaGrammar,
GrammarResolver grammarResolver,
XMLErrorReporter errorReporter,
String schemaURL,
boolean fullChecking
) throws Exception {
fErrorReporter = errorReporter;
fCurrentSchemaURL = schemaURL;
fFullConstraintChecking = fullChecking;
doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver);
}
public TraverseSchema(Element root, StringPool stringPool,
SchemaGrammar schemaGrammar,
GrammarResolver grammarResolver,
boolean fullChecking
) throws Exception {
fFullConstraintChecking = fullChecking;
doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver);
}
public void doTraverseSchema(Element root, StringPool stringPool,
SchemaGrammar schemaGrammar,
GrammarResolver grammarResolver) throws Exception {
fNamespacesScope = new NamespacesScope(this);
fSchemaRootElement = root;
fStringPool = stringPool;
fSchemaGrammar = schemaGrammar;
if (fFullConstraintChecking) {
fSchemaGrammar.setDeferContentSpecExpansion();
fSchemaGrammar.setCheckUniqueParticleAttribution();
}
fGrammarResolver = grammarResolver;
fDatatypeRegistry = (DatatypeValidatorFactoryImpl) fGrammarResolver.getDatatypeRegistry();
//Expand to registry type to contain all primitive datatype
fDatatypeRegistry.expandRegistryToFullSchemaSet();
// General Attribute Checking
fGeneralAttrCheck = new GeneralAttrCheck(fErrorReporter);
fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI);
if (root == null) {
// REVISIT: Anything to do?
return;
}
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(root, scope);
//Make sure namespace binding is defaulted
String rootPrefix = root.getPrefix();
if( rootPrefix == null || rootPrefix.length() == 0 ){
String xmlns = root.getAttribute("xmlns");
if( xmlns.length() == 0 )
root.setAttribute("xmlns", SchemaSymbols.URI_SCHEMAFORSCHEMA );
}
//Retrieve the targetNamespace URI information
fTargetNSURIString = getTargetNamespaceString(root);
fTargetNSURI = fStringPool.addSymbol(fTargetNSURIString);
if (fGrammarResolver == null) {
// REVISIT: Localize
reportGenericSchemaError("Internal error: don't have a GrammarResolver for TraverseSchema");
}
else{
// for complex type registry, attribute decl registry and
// namespace mapping, needs to check whether the passed in
// Grammar was a newly instantiated one.
if (fSchemaGrammar.getComplexTypeRegistry() == null ) {
fSchemaGrammar.setComplexTypeRegistry(fComplexTypeRegistry);
}
else {
fComplexTypeRegistry = fSchemaGrammar.getComplexTypeRegistry();
}
if (fSchemaGrammar.getAttributeDeclRegistry() == null ) {
fSchemaGrammar.setAttributeDeclRegistry(fAttributeDeclRegistry);
}
else {
fAttributeDeclRegistry = fSchemaGrammar.getAttributeDeclRegistry();
}
if (fSchemaGrammar.getNamespacesScope() == null ) {
fSchemaGrammar.setNamespacesScope(fNamespacesScope);
}
else {
fNamespacesScope = fSchemaGrammar.getNamespacesScope();
}
fSchemaGrammar.setDatatypeRegistry(fDatatypeRegistry);
fSchemaGrammar.setTargetNamespaceURI(fTargetNSURIString);
fGrammarResolver.putGrammar(fTargetNSURIString, fSchemaGrammar);
}
// Retrived the Namespace mapping from the schema element.
NamedNodeMap schemaEltAttrs = root.getAttributes();
int i = 0;
Attr sattr = null;
boolean seenXMLNS = false;
while ((sattr = (Attr)schemaEltAttrs.item(i++)) != null) {
String attName = sattr.getName();
if (attName.startsWith("xmlns:")) {
String attValue = sattr.getValue();
String prefix = attName.substring(attName.indexOf(":")+1);
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(prefix),
fStringPool.addSymbol(attValue) );
}
if (attName.equals("xmlns")) {
String attValue = sattr.getValue();
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol(attValue) );
seenXMLNS = true;
}
}
if (!seenXMLNS && fTargetNSURIString.length() == 0 ) {
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol("") );
}
fElementDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ELEMENTFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
fAttributeDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ATTRIBUTEFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
Attr blockAttr = root.getAttributeNode(SchemaSymbols.ATT_BLOCKDEFAULT);
if (blockAttr == null)
fBlockDefault = 0;
else
fBlockDefault =
parseBlockSet(blockAttr.getValue());
Attr finalAttr = root.getAttributeNode(SchemaSymbols.ATT_FINALDEFAULT);
if (finalAttr == null)
fFinalDefault = 0;
else
fFinalDefault =
parseFinalSet(finalAttr.getValue());
//REVISIT, really sticky when noTargetNamesapce, for now, we assume everyting is in the same name space);
if (fTargetNSURI == StringPool.EMPTY_STRING) {
//fElementDefaultQualified = true;
//fAttributeDefaultQualified = true;
}
//fScopeCount++;
fCurrentScope = -1;
//extract all top-level attribute, attributeGroup, and group Decls and put them in the 3 hasn table in the SchemaGrammar.
extractTopLevel3Components(root);
// process <redefine>, <include> and <import> info items.
Element child = XUtil.getFirstChildElement(root);
for (; child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_INCLUDE)) {
fNamespacesScope.increaseDepth();
traverseInclude(child);
fNamespacesScope.decreaseDepth();
} else if (name.equals(SchemaSymbols.ELT_IMPORT)) {
traverseImport(child);
} else if (name.equals(SchemaSymbols.ELT_REDEFINE)) {
fRedefineSucceeded = true; // presume worked until proven failed.
traverseRedefine(child);
} else
break;
}
// child refers to the first info item which is not <annotation> or
// one of the schema inclusion/importation declarations.
for (; child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) {
traverseSimpleTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) {
traverseComplexTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ELEMENT )) {
traverseElementDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
traverseAttributeGroupDecl(child, null, null);
} else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) {
traverseAttributeDecl( child, null, false );
} else if (name.equals(SchemaSymbols.ELT_GROUP)) {
traverseGroupDecl(child);
} else if (name.equals(SchemaSymbols.ELT_NOTATION)) {
traverseNotationDecl(child); //TO DO
} else {
// REVISIT: Localize
reportGenericSchemaError("error in content of <schema> element information item");
}
} // for each child node
// handle identity constraints
// we must traverse <key>s and <unique>s before we tackel<keyref>s,
// since all have global scope and may be declared anywhere in the schema.
Enumeration elementIndexes = fIdentityConstraints.keys();
while (elementIndexes.hasMoreElements()) {
Integer elementIndexObj = (Integer)elementIndexes.nextElement();
if (DEBUG_IC_DATATYPES) {
System.out.println("<ICD>: traversing identity constraints for element: "+elementIndexObj);
}
Vector identityConstraints = (Vector)fIdentityConstraints.get(elementIndexObj);
if (identityConstraints != null) {
int elementIndex = elementIndexObj.intValue();
traverseIdentityNameConstraintsFor(elementIndex, identityConstraints);
}
}
elementIndexes = fIdentityConstraints.keys();
while (elementIndexes.hasMoreElements()) {
Integer elementIndexObj = (Integer)elementIndexes.nextElement();
if (DEBUG_IC_DATATYPES) {
System.out.println("<ICD>: traversing identity constraints for element: "+elementIndexObj);
}
Vector identityConstraints = (Vector)fIdentityConstraints.get(elementIndexObj);
if (identityConstraints != null) {
int elementIndex = elementIndexObj.intValue();
traverseIdentityRefConstraintsFor(elementIndex, identityConstraints);
}
}
// General Attribute Checking
fGeneralAttrCheck = null;
} // traverseSchema(Element)
private void extractTopLevel3Components(Element root) throws Exception {
for (Element child = XUtil.getFirstChildElement(root); child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
String compName = child.getAttribute(SchemaSymbols.ATT_NAME);
if (name.equals(SchemaSymbols.ELT_ELEMENT)) {
// Check if the element has already been declared
if (fSchemaGrammar.topLevelElemDecls.get(compName) != null) {
reportGenericSchemaError("sch-props-correct: Duplicate declaration for an element " +
compName);
}
else {
fSchemaGrammar.topLevelElemDecls.put(compName, child);
}
}
else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE) ||
name.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
// Check for dublicate declaration
if (fSchemaGrammar.topLevelTypeDecls.get(compName) != null) {
reportGenericSchemaError("sch-props-correct: Duplicate declaration for a type " +
compName);
}
else {
fSchemaGrammar.topLevelTypeDecls.put(compName, child);
}
}
else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
// Check for dublicate declaration
if (fSchemaGrammar.topLevelAttrGrpDecls.get(compName) != null) {
reportGenericSchemaError("sch-props-correct: Duplicate declaration for an attribute group " +
compName);
}
else {
fSchemaGrammar.topLevelAttrGrpDecls.put(compName, child);
}
} else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) {
// Check for dublicate declaration
if (fSchemaGrammar.topLevelAttrGrpDecls.get(compName) != null) {
reportGenericSchemaError("sch-props-correct: Duplicate declaration for an attribute " +
compName);
}
else {
fSchemaGrammar.topLevelAttrGrpDecls.put(compName, child);
}
} else if ( name.equals(SchemaSymbols.ELT_GROUP) ) {
// Check if the group has already been declared
if (fSchemaGrammar.topLevelGroupDecls.get(compName) != null){
reportGenericSchemaError("sch-props-correct: Duplicate declaration for a group " +
compName);
}
else {
fSchemaGrammar.topLevelGroupDecls.put(compName, child);
}
} else if ( name.equals(SchemaSymbols.ELT_NOTATION) ) {
// Check for dublicate declaration
if (fSchemaGrammar.topLevelNotationDecls.get(compName) != null) {
reportGenericSchemaError("sch-props-correct: Duplicate declaration for a notation " +
compName);
}
else {
fSchemaGrammar.topLevelNotationDecls.put(compName, child);
}
}
} // for each child node
}
/**
* Expands a system id and returns the system id as a URL, if
* it can be expanded. A return value of null means that the
* identifier is already expanded. An exception thrown
* indicates a failure to expand the id.
*
* @param systemId The systemId to be expanded.
*
* @return Returns the URL object representing the expanded system
* identifier. A null value indicates that the given
* system identifier is already expanded.
*
*/
private String expandSystemId(String systemId, String currentSystemId) throws Exception{
String id = systemId;
// check for bad parameters id
if (id == null || id.length() == 0) {
return systemId;
}
// if id already expanded, return
try {
URL url = new URL(id);
if (url != null) {
return systemId;
}
}
catch (MalformedURLException e) {
// continue on...
}
// normalize id
id = fixURI(id);
// normalize base
URL base = null;
URL url = null;
try {
if (currentSystemId == null) {
String dir;
try {
dir = fixURI(System.getProperty("user.dir"));
}
catch (SecurityException se) {
dir = "";
}
if (!dir.endsWith("/")) {
dir = dir + "/";
}
base = new URL("file", "", dir);
}
else {
base = new URL(currentSystemId);
}
// expand id
url = new URL(base, id);
}
catch (Exception e) {
// let it go through
}
if (url == null) {
return systemId;
}
return url.toString();
}
/**
* Fixes a platform dependent filename to standard URI form.
*
* @param str The string to fix.
*
* @return Returns the fixed URI string.
*/
private static String fixURI(String str) {
// handle platform dependent strings
str = str.replace(java.io.File.separatorChar, '/');
// Windows fix
if (str.length() >= 2) {
char ch1 = str.charAt(1);
if (ch1 == ':') {
char ch0 = Character.toUpperCase(str.charAt(0));
if (ch0 >= 'A' && ch0 <= 'Z') {
str = "/" + str;
}
}
}
// done
return str;
}
private void traverseInclude(Element includeDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(includeDecl, scope);
checkContent(includeDecl, XUtil.getFirstChildElement(includeDecl), true);
Attr locationAttr = includeDecl.getAttributeNode(SchemaSymbols.ATT_SCHEMALOCATION);
if (locationAttr == null) {
// REVISIT: Localize
reportGenericSchemaError("a schemaLocation attribute must be specified on an <include> element");
return;
}
String location = locationAttr.getValue();
// expand it before passing it to the parser
InputSource source = null;
if (fEntityResolver != null) {
source = fEntityResolver.resolveEntity("", location);
}
if (source == null) {
location = expandSystemId(location, fCurrentSchemaURL);
source = new InputSource(location);
}
else {
// create a string for uniqueness of this included schema in fIncludeLocations
if (source.getPublicId () != null)
location = source.getPublicId ();
location += (',' + source.getSystemId ());
}
if (fIncludeLocations.contains((Object)location)) {
return;
}
fIncludeLocations.addElement((Object)location);
DOMParser parser = new IgnoreWhitespaceParser();
parser.setEntityResolver( new Resolver() );
parser.setErrorHandler( new ErrorHandler()
{
public void fatalError(SAXParseException ex) throws SAXException {
StringBuffer str = new StringBuffer();
String systemId_ = ex.getSystemId();
if (systemId_ != null) {
int index = systemId_.lastIndexOf('/');
if (index != -1)
systemId_ = systemId_.substring(index + 1);
str.append(systemId_);
}
str.append(':').append(ex.getLineNumber()).append(':').append(ex.getColumnNumber());
String message = ex.getMessage();
if(message.toLowerCase().trim().endsWith("not found.")) {
System.err.println("[Warning] "+
str.toString()+": "+ message);
} else { // do standard thing
System.err.println("[Fatal Error] "+
str.toString()+":"+message);
throw ex;
}
}
});
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}catch( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
}catch( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
try {
parser.parse( source );
}catch( IOException e ) {
e.printStackTrace();
}catch( SAXException e ) {
//e.printStackTrace();
}
Document document = parser.getDocument(); //Our Grammar
Element root = null;
if (document != null) {
root = document.getDocumentElement();
}
if (root != null) {
String targetNSURI = getTargetNamespaceString(root);
if (targetNSURI.length() > 0 && !targetNSURI.equals(fTargetNSURIString) ) {
// REVISIT: Localize
reportGenericSchemaError("included schema '"+location+"' has a different targetNameSpace '"
+targetNSURI+"'");
}
else {
// We not creating another TraverseSchema object to compile
// the included schema file, because the scope count, anon-type count
// should not be reset for a included schema, this can be fixed by saving
// the counters in the Schema Grammar,
if (fSchemaInfoListRoot == null) {
fSchemaInfoListRoot = new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified,
fBlockDefault, fFinalDefault,
fCurrentScope, fCurrentSchemaURL, fSchemaRootElement,
fNamespacesScope, null, null);
fCurrentSchemaInfo = fSchemaInfoListRoot;
}
fSchemaRootElement = root;
fCurrentSchemaURL = location;
traverseIncludedSchemaHeader(root);
// and now we'd better save this stuff!
fCurrentSchemaInfo = new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified,
fBlockDefault, fFinalDefault,
fCurrentScope, fCurrentSchemaURL, fSchemaRootElement,
fNamespacesScope, fCurrentSchemaInfo.getNext(), fCurrentSchemaInfo);
(fCurrentSchemaInfo.getPrev()).setNext(fCurrentSchemaInfo);
traverseIncludedSchema(root);
// there must always be a previous element!
fCurrentSchemaInfo = fCurrentSchemaInfo.getPrev();
fCurrentSchemaInfo.restore();
}
}
}
private void traverseIncludedSchemaHeader(Element root) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(root, scope);
// Retrieved the Namespace mapping from the schema element.
NamedNodeMap schemaEltAttrs = root.getAttributes();
int i = 0;
Attr sattr = null;
boolean seenXMLNS = false;
while ((sattr = (Attr)schemaEltAttrs.item(i++)) != null) {
String attName = sattr.getName();
if (attName.startsWith("xmlns:")) {
String attValue = sattr.getValue();
String prefix = attName.substring(attName.indexOf(":")+1);
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(prefix),
fStringPool.addSymbol(attValue) );
}
if (attName.equals("xmlns")) {
String attValue = sattr.getValue();
fNamespacesScope.setNamespaceForPrefix( StringPool.EMPTY_STRING,
fStringPool.addSymbol(attValue) );
seenXMLNS = true;
}
}
if (!seenXMLNS && fTargetNSURIString.length() == 0 ) {
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol("") );
}
fElementDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ELEMENTFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
fAttributeDefaultQualified =
root.getAttribute(SchemaSymbols.ATT_ATTRIBUTEFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED);
Attr blockAttr = root.getAttributeNode(SchemaSymbols.ATT_BLOCKDEFAULT);
if (blockAttr == null)
fBlockDefault = 0;
else
fBlockDefault =
parseBlockSet(blockAttr.getValue());
Attr finalAttr = root.getAttributeNode(SchemaSymbols.ATT_FINALDEFAULT);
if (finalAttr == null)
fFinalDefault = 0;
else
fFinalDefault =
parseFinalSet(finalAttr.getValue());
//REVISIT, really sticky when noTargetNamesapce, for now, we assume everyting is in the same name space);
if (fTargetNSURI == StringPool.EMPTY_STRING) {
fElementDefaultQualified = true;
//fAttributeDefaultQualified = true;
}
//fScopeCount++;
fCurrentScope = -1;
} // traverseIncludedSchemaHeader
private void traverseIncludedSchema(Element root) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(root, scope);
//extract all top-level attribute, attributeGroup, and group Decls and put them in the 3 hasn table in the SchemaGrammar.
extractTopLevel3Components(root);
// handle <redefine>, <include> and <import> elements.
Element child = XUtil.getFirstChildElement(root);
for (; child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_INCLUDE)) {
fNamespacesScope.increaseDepth();
traverseInclude(child);
fNamespacesScope.decreaseDepth();
} else if (name.equals(SchemaSymbols.ELT_IMPORT)) {
traverseImport(child);
} else if (name.equals(SchemaSymbols.ELT_REDEFINE)) {
fRedefineSucceeded = true; // presume worked until proven failed.
traverseRedefine(child);
} else
break;
}
// handle the rest of the schema elements.
// BEWARE! this method gets called both from traverseRedefine and
// traverseInclude; the preconditions (especially with respect to
// groups and attributeGroups) are different!
for (; child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) {
traverseSimpleTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) {
traverseComplexTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ELEMENT )) {
traverseElementDecl(child);
} else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
if(fRedefineAttributeGroupMap != null) {
String dName = child.getAttribute(SchemaSymbols.ATT_NAME);
String bName = (String)fRedefineAttributeGroupMap.get(dName);
if(bName != null) {
child.setAttribute(SchemaSymbols.ATT_NAME, bName);
// Now we reuse this location in the array to store info we'll need for validation...
ComplexTypeInfo typeInfo = new ComplexTypeInfo();
int templateElementNameIndex = fStringPool.addSymbol("$"+bName);
int typeNameIndex = fStringPool.addSymbol("%"+bName);
typeInfo.scopeDefined = -2;
typeInfo.contentSpecHandle = -1;
typeInfo.contentType = XMLElementDecl.TYPE_SIMPLE;
typeInfo.datatypeValidator = null;
typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(
new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI),
(fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : -2, typeInfo.scopeDefined,
typeInfo.contentType,
typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator);
Vector anyAttDecls = new Vector();
// need to determine how to initialize these babies; then
// on the <redefine> traversing end, try
// and cast the hash value into the right form;
// failure indicates nothing to redefine; success
// means we can feed checkAttribute... what it needs...
traverseAttributeGroupDecl(child, typeInfo, anyAttDecls);
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(
typeInfo.templateElementIndex);
fRedefineAttributeGroupMap.put(dName, new Object []{typeInfo, fSchemaGrammar, anyAttDecls});
continue;
}
}
traverseAttributeGroupDecl(child, null, null);
} else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) {
traverseAttributeDecl( child, null , false);
} else if (name.equals(SchemaSymbols.ELT_GROUP)) {
String dName = child.getAttribute(SchemaSymbols.ATT_NAME);
if(fGroupNameRegistry.get(fTargetNSURIString + ","+dName) == null) {
// we've been renamed already
traverseGroupDecl(child);
continue;
}
// if we're here: must have been a restriction.
// we have yet to be renamed.
try {
Integer i = (Integer)fGroupNameRegistry.get(fTargetNSURIString + ","+dName);
// if that succeeded then we're done; were ref'd here in
// an include most likely.
continue;
} catch (ClassCastException c) {
String s = (String)fGroupNameRegistry.get(fTargetNSURIString + ","+dName);
if (s == null) continue; // must have seen this already--somehow...
};
String bName = (String)fGroupNameRegistry.get(fTargetNSURIString +"," + dName);
if(bName != null) {
child.setAttribute(SchemaSymbols.ATT_NAME, bName);
// Now we reuse this location in the array to store info we'll need for validation...
// note that traverseGroupDecl will happily do that for us!
}
traverseGroupDecl(child);
} else if (name.equals(SchemaSymbols.ELT_NOTATION)) {
traverseNotationDecl(child);
} else {
// REVISIT: Localize
reportGenericSchemaError("error in content of included <schema> element information item");
}
} // for each child node
}
// This method's job is to open a redefined schema and store away its root element, defaultElementQualified and other
// such info, in order that it can be available when redefinition actually takes place.
// It assumes that it will be called from the schema doing the redefining, and it assumes
// that the other schema's info has already been saved, putting the info it finds into the
// SchemaInfoList element that is passed in.
private void openRedefinedSchema(Element redefineDecl, SchemaInfo store) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(redefineDecl, scope);
Attr locationAttr = redefineDecl.getAttributeNode(SchemaSymbols.ATT_SCHEMALOCATION);
if (locationAttr == null) {
// REVISIT: Localize
fRedefineSucceeded = false;
reportGenericSchemaError("a schemaLocation attribute must be specified on a <redefine> element");
return;
}
String location = locationAttr.getValue();
// expand it before passing it to the parser
InputSource source = null;
if (fEntityResolver != null) {
source = fEntityResolver.resolveEntity("", location);
}
if (source == null) {
location = expandSystemId(location, fCurrentSchemaURL);
source = new InputSource(location);
}
else {
// Make sure we don't redefine the same schema twice; it's allowed
// but the specs encourage us to avoid it.
if (source.getPublicId () != null)
location = source.getPublicId ();
// make sure we're not redefining ourselves!
if(source.getSystemId().equals(fCurrentSchemaURL)) {
// REVISIT: localize
reportGenericSchemaError("src-redefine.2: a schema cannot redefine itself");
fRedefineSucceeded = false;
return;
}
location += (',' + source.getSystemId ());
}
if (fRedefineLocations.get((Object)location) != null) {
// then we'd better make sure we're directed at that schema...
fCurrentSchemaInfo = (SchemaInfo)(fRedefineLocations.get((Object)location));
fCurrentSchemaInfo.restore();
return;
}
DOMParser parser = new IgnoreWhitespaceParser();
parser.setEntityResolver( new Resolver() );
parser.setErrorHandler( new ErrorHandler() );
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}catch( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
}catch( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
try {
parser.parse( source );
}catch( IOException e ) {
e.printStackTrace();
}catch( SAXException e ) {
//e.printStackTrace();
}
Document document = parser.getDocument(); //Our Grammar to be redefined
Element root = null;
if (document != null) {
root = document.getDocumentElement();
}
if (root == null) { // nothing to be redefined, so just continue; specs disallow an error here.
fRedefineSucceeded = false;
return;
}
// now if root isn't null, it'll contain the root of the schema we need to redefine.
// We do this in two phases: first, we look through the children of
// redefineDecl. Each one will correspond to an element of the
// redefined schema that we need to redefine. To do this, we rename the
// element of the redefined schema, and rework the base or ref tag of
// the kid we're working on to refer to the renamed group or derive the
// renamed type. Once we've done this, we actually go through the
// schema being redefined and convert it to a grammar. Only then do we
// run through redefineDecl's kids and put them in the grammar.
//
// This approach is kosher with the specs. It does raise interesting
// questions about error reporting, and perhaps also about grammar
// access, but it is comparatively efficient (we need make at most
// only 2 traversals of any given information item) and moreover
// we can use existing code to build the grammar structures once the
// first pass is out of the way, so this should be quite robust.
// check to see if the targetNameSpace is right
String redefinedTargetNSURIString = getTargetNamespaceString(root);
if (redefinedTargetNSURIString.length() > 0 && !redefinedTargetNSURIString.equals(fTargetNSURIString) ) {
// REVISIT: Localize
fRedefineSucceeded = false;
reportGenericSchemaError("redefined schema '"+location+"' has a different targetNameSpace '"
+redefinedTargetNSURIString+"' from the original schema");
}
else {
// targetNamespace is right, so let's do the renaming...
// and let's keep in mind that the targetNamespace of the redefined
// elements is that of the redefined schema!
fSchemaRootElement = root;
fCurrentSchemaURL = location;
fNamespacesScope = new NamespacesScope(this);
if((redefinedTargetNSURIString.length() == 0) && (root.getAttributeNode("xmlns") == null)) {
fNamespacesScope.setNamespaceForPrefix(StringPool.EMPTY_STRING, fTargetNSURI);
} else {
}
// get default form xmlns bindings et al.
traverseIncludedSchemaHeader(root);
// and then save them...
store.setNext(new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified,
fBlockDefault, fFinalDefault,
fCurrentScope, fCurrentSchemaURL, fSchemaRootElement,
fNamespacesScope, null, store));
(store.getNext()).setPrev(store);
fCurrentSchemaInfo = store.getNext();
fRedefineLocations.put((Object)location, store.getNext());
} // end if
} // end openRedefinedSchema
/****
* <redefine
* schemaLocation = uriReference
* {any attributes with non-schema namespace . . .}>
* Content: (annotation | (
* attributeGroup | complexType | group | simpleType))*
* </redefine>
*/
private void traverseRedefine(Element redefineDecl) throws Exception {
// initialize storage areas...
fRedefineAttributeGroupMap = new Hashtable();
NamespacesScope saveNSScope = (NamespacesScope)fNamespacesScope.clone();
// only case in which need to save contents is when fSchemaInfoListRoot is null; otherwise we'll have
// done this already one way or another.
if (fSchemaInfoListRoot == null) {
fSchemaInfoListRoot = new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified,
fBlockDefault, fFinalDefault,
fCurrentScope, fCurrentSchemaURL, fSchemaRootElement,
fNamespacesScope, null, null);
openRedefinedSchema(redefineDecl, fSchemaInfoListRoot);
if(!fRedefineSucceeded)
return;
fCurrentSchemaInfo = fSchemaInfoListRoot.getNext();
fNamespacesScope = (NamespacesScope)saveNSScope.clone();
renameRedefinedComponents(redefineDecl,fSchemaInfoListRoot.getNext().getRoot(), fSchemaInfoListRoot.getNext());
} else {
// may have a chain here; need to be wary!
SchemaInfo curr = fSchemaInfoListRoot;
for(; curr.getNext() != null; curr = curr.getNext());
fCurrentSchemaInfo = curr;
fCurrentSchemaInfo.restore();
openRedefinedSchema(redefineDecl, fCurrentSchemaInfo);
if(!fRedefineSucceeded)
return;
fNamespacesScope = (NamespacesScope)saveNSScope.clone();
renameRedefinedComponents(redefineDecl,fCurrentSchemaInfo.getRoot(), fCurrentSchemaInfo);
}
// Now we have to march through our nicely-renamed schemas from the
// bottom up. When we do these traversals other <redefine>'s may
// perhaps be encountered; we leave recursion to sort this out.
fCurrentSchemaInfo.restore();
traverseIncludedSchema(fSchemaRootElement);
fNamespacesScope = (NamespacesScope)saveNSScope.clone();
// and last but not least: traverse our own <redefine>--the one all
// this labour has been expended upon.
for (Element child = XUtil.getFirstChildElement(redefineDecl); child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
// annotations can occur anywhere in <redefine>s!
if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) {
traverseAnnotationDecl(child);
} else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) {
traverseSimpleTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) {
traverseComplexTypeDecl(child);
} else if (name.equals(SchemaSymbols.ELT_GROUP)) {
String dName = child.getAttribute(SchemaSymbols.ATT_NAME);
if(fGroupNameRegistry.get(fTargetNSURIString +","+ dName) == null ||
((fRestrictedRedefinedGroupRegistry.get(fTargetNSURIString+","+dName) != null) &&
!((Boolean)fRestrictedRedefinedGroupRegistry.get(fTargetNSURIString+","+dName)).booleanValue())) { // extension!
traverseGroupDecl(child);
continue;
}
traverseGroupDecl(child);
Integer bCSIndexObj = null;
try {
bCSIndexObj = (Integer)fGroupNameRegistry.get(fTargetNSURIString +","+ dName+redefIdentifier);
} catch(ClassCastException c) {
// if it's still a String, then we mustn't have found a corresponding attributeGroup in the redefined schema.
// REVISIT: localize
reportGenericSchemaError("src-redefine.6.2: a <group> within a <redefine> must either have a ref to a <group> with the same name or must restrict such an <group>");
continue;
}
if(bCSIndexObj != null) { // we have something!
int bCSIndex = bCSIndexObj.intValue();
Integer dCSIndexObj;
try {
dCSIndexObj = (Integer)fGroupNameRegistry.get(fTargetNSURIString+","+dName);
} catch (ClassCastException c) {
continue;
}
if(dCSIndexObj == null) // something went wrong...
continue;
int dCSIndex = dCSIndexObj.intValue();
try {
checkParticleDerivationOK(dCSIndex, -1, bCSIndex, -1, null);
}
catch (ParticleRecoverableError e) {
reportGenericSchemaError(e.getMessage());
}
} else
// REVISIT: localize
reportGenericSchemaError("src-redefine.6.2: a <group> within a <redefine> must either have a ref to a <group> with the same name or must restrict such an <group>");
} else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
if(fRedefineAttributeGroupMap != null) {
String dName = child.getAttribute(SchemaSymbols.ATT_NAME);
Object [] bAttGrpStore = null;
try {
bAttGrpStore = (Object [])fRedefineAttributeGroupMap.get(dName);
} catch(ClassCastException c) {
// if it's still a String, then we mustn't have found a corresponding attributeGroup in the redefined schema.
// REVISIT: localize
reportGenericSchemaError("src-redefine.7.2: an <attributeGroup> within a <redefine> must either have a ref to an <attributeGroup> with the same name or must restrict such an <attributeGroup>");
continue;
}
if(bAttGrpStore != null) { // we have something!
ComplexTypeInfo bTypeInfo = (ComplexTypeInfo)bAttGrpStore[0];
SchemaGrammar bSchemaGrammar = (SchemaGrammar)bAttGrpStore[1];
Vector bAnyAttDecls = (Vector)bAttGrpStore[2];
XMLAttributeDecl bAnyAttDecl =
(bAnyAttDecls.size()>0 )? (XMLAttributeDecl)bAnyAttDecls.elementAt(0):null;
ComplexTypeInfo dTypeInfo = new ComplexTypeInfo();
int templateElementNameIndex = fStringPool.addSymbol("$"+dName);
int dTypeNameIndex = fStringPool.addSymbol("%"+dName);
dTypeInfo.scopeDefined = -2;
dTypeInfo.contentSpecHandle = -1;
dTypeInfo.contentType = XMLElementDecl.TYPE_SIMPLE;
dTypeInfo.datatypeValidator = null;
dTypeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(
new QName(-1, templateElementNameIndex,dTypeNameIndex,fTargetNSURI),
(fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : -2, dTypeInfo.scopeDefined,
dTypeInfo.contentType,
dTypeInfo.contentSpecHandle, -1, dTypeInfo.datatypeValidator);
Vector dAnyAttDecls = new Vector();
XMLAttributeDecl dAnyAttDecl =
(dAnyAttDecls.size()>0 )? (XMLAttributeDecl)dAnyAttDecls.elementAt(0):null;
traverseAttributeGroupDecl(child, dTypeInfo, dAnyAttDecls);
dTypeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(
dTypeInfo.templateElementIndex);
try {
checkAttributesDerivationOKRestriction(dTypeInfo.attlistHead,fSchemaGrammar,
dAnyAttDecl,bTypeInfo.attlistHead,bSchemaGrammar,bAnyAttDecl);
}
catch (ComplexTypeRecoverableError e) {
String message = e.getMessage();
reportGenericSchemaError("src-redefine.7.2: redefinition failed because of " + message);
}
continue;
}
}
traverseAttributeGroupDecl(child, null, null);
} // no else; error reported in the previous traversal
} //for
// and restore the original globals
fCurrentSchemaInfo = fCurrentSchemaInfo.getPrev();
fCurrentSchemaInfo.restore();
} // traverseRedefine
// the purpose of this method is twofold: 1. To find and appropriately modify all information items
// in redefinedSchema with names that are redefined by children of
// redefineDecl. 2. To make sure the redefine element represented by
// redefineDecl is valid as far as content goes and with regard to
// properly referencing components to be redefined. No traversing is done here!
// This method also takes actions to find and, if necessary, modify the names
// of elements in <redefine>'s in the schema that's being redefined.
private void renameRedefinedComponents(Element redefineDecl, Element schemaToRedefine, SchemaInfo currSchemaInfo) throws Exception {
for (Element child = XUtil.getFirstChildElement(redefineDecl);
child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (name.equals(SchemaSymbols.ELT_ANNOTATION) )
continue;
else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
String typeName = child.getAttribute( SchemaSymbols.ATT_NAME );
if(fTraversedRedefineElements.contains(typeName))
continue;
if(validateRedefineNameChange(SchemaSymbols.ELT_SIMPLETYPE, typeName, typeName+redefIdentifier, child)) {
fixRedefinedSchema(SchemaSymbols.ELT_SIMPLETYPE,
typeName, typeName+redefIdentifier,
schemaToRedefine, currSchemaInfo);
}
} else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
String typeName = child.getAttribute( SchemaSymbols.ATT_NAME );
if(fTraversedRedefineElements.contains(typeName))
continue;
if(validateRedefineNameChange(SchemaSymbols.ELT_COMPLEXTYPE, typeName, typeName+redefIdentifier, child)) {
fixRedefinedSchema(SchemaSymbols.ELT_COMPLEXTYPE,
typeName, typeName+redefIdentifier,
schemaToRedefine, currSchemaInfo);
}
} else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
String baseName = child.getAttribute( SchemaSymbols.ATT_NAME );
if(fTraversedRedefineElements.contains(baseName))
continue;
if(validateRedefineNameChange(SchemaSymbols.ELT_ATTRIBUTEGROUP, baseName, baseName+redefIdentifier, child)) {
fixRedefinedSchema(SchemaSymbols.ELT_ATTRIBUTEGROUP,
baseName, baseName+redefIdentifier,
schemaToRedefine, currSchemaInfo);
}
} else if (name.equals(SchemaSymbols.ELT_GROUP)) {
String baseName = child.getAttribute( SchemaSymbols.ATT_NAME );
if(fTraversedRedefineElements.contains(baseName))
continue;
if(validateRedefineNameChange(SchemaSymbols.ELT_GROUP, baseName, baseName+redefIdentifier, child)) {
fixRedefinedSchema(SchemaSymbols.ELT_GROUP,
baseName, baseName+redefIdentifier,
schemaToRedefine, currSchemaInfo);
}
} else {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("invalid top-level content for <redefine>");
return;
}
} // for
} // renameRedefinedComponents
// This function looks among the children of curr for an element of type elementSought.
// If it finds one, it evaluates whether its ref attribute contains a reference
// to originalName. If it does, it returns 1 + the value returned by
// calls to itself on all other children. In all other cases it returns 0 plus
// the sum of the values returned by calls to itself on curr's children.
// It also resets the value of ref so that it will refer to the renamed type from the schema
// being redefined.
private int changeRedefineGroup(QName originalName, String elementSought, String newName, Element curr) throws Exception {
int result = 0;
for (Element child = XUtil.getFirstChildElement(curr);
child != null; child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (!name.equals(elementSought))
result += changeRedefineGroup(originalName, elementSought, newName, child);
else {
String ref = child.getAttribute( SchemaSymbols.ATT_REF );
if (!ref.equals("")) {
String prefix = "";
String localpart = ref;
int colonptr = ref.indexOf(":");
if ( colonptr > 0) {
prefix = ref.substring(0,colonptr);
localpart = ref.substring(colonptr+1);
}
String uriStr = resolvePrefixToURI(prefix);
if(originalName.equals(new QName(-1, fStringPool.addSymbol(localpart), fStringPool.addSymbol(localpart), fStringPool.addSymbol(uriStr)))) {
if(prefix.equals(""))
child.setAttribute(SchemaSymbols.ATT_REF, newName);
else
child.setAttribute(SchemaSymbols.ATT_REF, prefix + ":" + newName);
result++;
if(elementSought.equals(SchemaSymbols.ELT_GROUP)) {
String minOccurs = child.getAttribute( SchemaSymbols.ATT_MINOCCURS );
String maxOccurs = child.getAttribute( SchemaSymbols.ATT_MAXOCCURS );
if(!((maxOccurs.length() == 0 || maxOccurs.equals("1"))
&& (minOccurs.length() == 0 || minOccurs.equals("1")))) {
//REVISIT: localize
reportGenericSchemaError("src-redefine.6.1.2: the group " + ref + " which contains a reference to a group being redefined must have minOccurs = maxOccurs = 1");
}
}
}
} // if ref was null some other stage of processing will flag the error
}
}
return result;
} // changeRedefineGroup
// This simple function looks for the first occurrence of an eltLocalname
// schema information item and appropriately changes the value of
// its name or type attribute from oldName to newName.
// Root contains the root of the schema being operated upon.
// If it turns out that what we're looking for is in a <redefine> though, then we
// just rename it--and it's reference--to be the same and wait until
// renameRedefineDecls can get its hands on it and do it properly.
private void fixRedefinedSchema(String eltLocalname, String oldName, String newName, Element schemaToRedefine,
SchemaInfo currSchema) throws Exception {
boolean foundIt = false;
for (Element child = XUtil.getFirstChildElement(schemaToRedefine);
child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if(name.equals(SchemaSymbols.ELT_REDEFINE)) { // need to search the redefine decl...
for (Element redefChild = XUtil.getFirstChildElement(child);
redefChild != null;
redefChild = XUtil.getNextSiblingElement(redefChild)) {
String redefName = redefChild.getLocalName();
if (redefName.equals(eltLocalname) ) {
String infoItemName = redefChild.getAttribute( SchemaSymbols.ATT_NAME );
if(!infoItemName.equals(oldName))
continue;
else { // found it!
foundIt = true;
openRedefinedSchema(child, currSchema);
if(!fRedefineSucceeded)
return;
NamespacesScope saveNSS = (NamespacesScope)fNamespacesScope.clone();
currSchema.restore();
if (validateRedefineNameChange(eltLocalname, oldName, newName+redefIdentifier, redefChild) &&
(currSchema.getNext() != null)) {
currSchema.getNext().restore();
fixRedefinedSchema(eltLocalname, oldName, newName+redefIdentifier, fSchemaRootElement, currSchema.getNext());
}
fNamespacesScope = saveNSS;
redefChild.setAttribute( SchemaSymbols.ATT_NAME, newName );
// and we now know we will traverse this, so set fTraversedRedefineElements appropriately...
fTraversedRedefineElements.addElement(newName);
currSchema.restore();
fCurrentSchemaInfo = currSchema;
break;
}
}
} //for
if (foundIt) break;
}
else if (name.equals(eltLocalname) ) {
String infoItemName = child.getAttribute( SchemaSymbols.ATT_NAME );
if(!infoItemName.equals(oldName))
continue;
else { // found it!
foundIt = true;
child.setAttribute( SchemaSymbols.ATT_NAME, newName );
break;
}
}
} //for
if(!foundIt) {
fRedefineSucceeded = false;
// REVISIT: localize
reportGenericSchemaError("could not find a declaration in the schema to be redefined corresponding to " + oldName);
}
} // end fixRedefinedSchema
// this method returns true if the redefine component is valid, and if
// it was possible to revise it correctly. The definition of
// correctly will depend on whether renameRedefineDecls
// or fixRedefineSchema is the caller.
// this method also prepends a prefix onto newName if necessary; newName will never contain one.
private boolean validateRedefineNameChange(String eltLocalname, String oldName, String newName, Element child) throws Exception {
if (eltLocalname.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
QName processedTypeName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI);
Element grandKid = XUtil.getFirstChildElement(child);
if (grandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a simpleType child of a <redefine> must have a restriction element as a child");
} else {
String grandKidName = grandKid.getLocalName();
if(grandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) {
grandKid = XUtil.getNextSiblingElement(grandKid);
grandKidName = grandKid.getLocalName();
}
if (grandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a simpleType child of a <redefine> must have a restriction element as a child");
} else if(!grandKidName.equals(SchemaSymbols.ELT_RESTRICTION)) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a simpleType child of a <redefine> must have a restriction element as a child");
} else {
String derivedBase = grandKid.getAttribute( SchemaSymbols.ATT_BASE );
QName processedDerivedBase = parseBase(derivedBase);
if(!processedTypeName.equals(processedDerivedBase)) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("the base attribute of the restriction child of a simpleType child of a redefine must have the same value as the simpleType's type attribute");
} else {
// now we have to do the renaming...
String prefix = "";
int colonptr = derivedBase.indexOf(":");
if ( colonptr > 0)
prefix = derivedBase.substring(0,colonptr) + ":";
grandKid.setAttribute( SchemaSymbols.ATT_BASE, prefix + newName );
return true;
}
}
}
} else if (eltLocalname.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
QName processedTypeName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI);
Element grandKid = XUtil.getFirstChildElement(child);
if (grandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild");
} else {
if(grandKid.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
grandKid = XUtil.getNextSiblingElement(grandKid);
}
if (grandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild");
} else {
// have to go one more level down; let another pass worry whether complexType is valid.
Element greatGrandKid = XUtil.getFirstChildElement(grandKid);
if (greatGrandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild");
} else {
String greatGrandKidName = greatGrandKid.getLocalName();
if(greatGrandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) {
greatGrandKid = XUtil.getNextSiblingElement(greatGrandKid);
greatGrandKidName = greatGrandKid.getLocalName();
}
if (greatGrandKid == null) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild");
} else if(!greatGrandKidName.equals(SchemaSymbols.ELT_RESTRICTION) &&
!greatGrandKidName.equals(SchemaSymbols.ELT_EXTENSION)) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild");
} else {
String derivedBase = greatGrandKid.getAttribute( SchemaSymbols.ATT_BASE );
QName processedDerivedBase = parseBase(derivedBase);
if(!processedTypeName.equals(processedDerivedBase)) {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("the base attribute of the restriction or extension grandchild of a complexType child of a redefine must have the same value as the complexType's type attribute");
} else {
// now we have to do the renaming...
String prefix = "";
int colonptr = derivedBase.indexOf(":");
if ( colonptr > 0)
prefix = derivedBase.substring(0,colonptr) + ":";
greatGrandKid.setAttribute( SchemaSymbols.ATT_BASE, prefix + newName );
return true;
}
}
}
}
}
} else if (eltLocalname.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
QName processedBaseName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI);
int attGroupRefsCount = changeRedefineGroup(processedBaseName, eltLocalname, newName, child);
if(attGroupRefsCount > 1) {
fRedefineSucceeded = false;
// REVISIT: localize
reportGenericSchemaError("if an attributeGroup child of a <redefine> element contains an attributeGroup ref'ing itself, it must have exactly 1; this one has " + attGroupRefsCount);
} else if (attGroupRefsCount == 1) {
return true;
} else
fRedefineAttributeGroupMap.put(oldName, newName);
} else if (eltLocalname.equals(SchemaSymbols.ELT_GROUP)) {
QName processedBaseName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI);
int groupRefsCount = changeRedefineGroup(processedBaseName, eltLocalname, newName, child);
if(!fRedefineSucceeded) {
fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+oldName, new Boolean(false));
}
if(groupRefsCount > 1) {
fRedefineSucceeded = false;
fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+oldName, new Boolean(false));
// REVISIT: localize
reportGenericSchemaError("if a group child of a <redefine> element contains a group ref'ing itself, it must have exactly 1; this one has " + groupRefsCount);
} else if (groupRefsCount == 1) {
fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+oldName, new Boolean(false));
return true;
} else {
fGroupNameRegistry.put(fTargetNSURIString + "," + oldName, newName);
fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+oldName, new Boolean(true));
}
} else {
fRedefineSucceeded = false;
// REVISIT: Localize
reportGenericSchemaError("internal Xerces error; please submit a bug with schema as testcase");
}
// if we get here then we must have reported an error and failed somewhere...
return false;
} // validateRedefineNameChange
private void traverseImport(Element importDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(importDecl, scope);
checkContent(importDecl, XUtil.getFirstChildElement(importDecl), true);
String location = importDecl.getAttribute(SchemaSymbols.ATT_SCHEMALOCATION);
// expand it before passing it to the parser
InputSource source = null;
if (fEntityResolver != null) {
source = fEntityResolver.resolveEntity("", location);
}
if (source == null) {
location = expandSystemId(location, fCurrentSchemaURL);
source = new InputSource(location);
}
else {
// create a string for uniqueness of this imported schema in fImportLocations
if (source.getPublicId () != null)
location = source.getPublicId ();
location += (',' + source.getSystemId ());
}
if (fImportLocations.contains((Object)location)) {
return;
}
fImportLocations.addElement((Object)location);
// check to make sure we're not importing ourselves...
if(source.getSystemId().equals(fCurrentSchemaURL)) {
// REVISIT: localize
return;
}
String namespaceString = importDecl.getAttribute(SchemaSymbols.ATT_NAMESPACE);
if(namespaceString.length() == 0) {
if(fTargetNSURI == StringPool.EMPTY_STRING) {
// REVISIT: localize
reportGenericSchemaError("src-import.1.2: if the namespace attribute on an <import> element is not present, the <import>ing schema must have a targetNamespace");
}
} else {
if(fTargetNSURIString.equals(namespaceString.trim())) {
// REVISIT: localize
reportGenericSchemaError("src-import.1.1: the namespace attribute of an <import> element must not be the same as the targetNamespace of the <import>ing schema");
}
}
SchemaGrammar importedGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(namespaceString);
if (importedGrammar == null) {
importedGrammar = new SchemaGrammar();
}
DOMParser parser = new IgnoreWhitespaceParser();
parser.setEntityResolver( new Resolver() );
parser.setErrorHandler( new ErrorHandler()
{
public void fatalError(SAXParseException ex) throws SAXException {
StringBuffer str = new StringBuffer();
String systemId_ = ex.getSystemId();
if (systemId_ != null) {
int index = systemId_.lastIndexOf('/');
if (index != -1)
systemId_ = systemId_.substring(index + 1);
str.append(systemId_);
}
str.append(':').append(ex.getLineNumber()).append(':').append(ex.getColumnNumber());
String message = ex.getMessage();
if(message.toLowerCase().trim().endsWith("not found.")) {
System.err.println("[Warning] "+
str.toString()+": "+ message);
} else { // do standard thing
System.err.println("[Fatal Error] "+
str.toString()+":"+message);
throw ex;
}
}
});
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}catch( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
}catch( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
try {
parser.parse( source );
}catch( IOException e ) {
e.printStackTrace();
}catch( SAXException e ) {
e.printStackTrace();
}
Document document = parser.getDocument(); //Our Grammar
Element root = null;
if (document != null) {
root = document.getDocumentElement();
}
if (root != null) {
String targetNSURI = getTargetNamespaceString(root);
if (!targetNSURI.equals(namespaceString) ) {
// REVISIT: Localize
reportGenericSchemaError("imported schema '"+location+"' has a different targetNameSpace '"
+targetNSURI+"' from what is declared '"+namespaceString+"'.");
}
else {
TraverseSchema impSchema = new TraverseSchema(root, fStringPool, importedGrammar, fGrammarResolver, fErrorReporter, location, fEntityResolver, fFullConstraintChecking);
Enumeration ics = impSchema.fIdentityConstraints.keys();
while(ics.hasMoreElements()) {
Object icsKey = ics.nextElement();
fIdentityConstraints.put(icsKey, impSchema.fIdentityConstraints.get(icsKey));
}
Enumeration icNames = impSchema.fIdentityConstraintNames.keys();
while(icNames.hasMoreElements()) {
String icsNameKey = (String)icNames.nextElement();
fIdentityConstraintNames.put(icsNameKey, impSchema.fIdentityConstraintNames.get(icsNameKey));
}
}
}
else {
reportGenericSchemaError("Could not get the doc root for imported Schema file: "+location);
}
}
// utility method for finding the targetNamespace (and flagging errors if they occur)
private String getTargetNamespaceString( Element root) throws Exception {
String targetNSURI = "";
Attr targetNSAttr = root.getAttributeNode(SchemaSymbols.ATT_TARGETNAMESPACE);
if(targetNSAttr != null) {
targetNSURI=targetNSAttr.getValue();
if(targetNSURI.length() == 0) {
// REVISIT: localize
reportGenericSchemaError("sch-prop-correct.1: \"\" is not a legal value for the targetNamespace attribute; the attribute must either be absent or contain a nonempty value");
}
}
return targetNSURI;
} // end getTargetNamespaceString(Element)
/**
* <annotation>(<appinfo> | <documentation>)*</annotation>
*
* @param annotationDecl: the DOM node corresponding to the <annotation> info item
*/
private void traverseAnnotationDecl(Element annotationDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(annotationDecl, scope);
for(Element child = XUtil.getFirstChildElement(annotationDecl); child != null;
child = XUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if(!((name.equals(SchemaSymbols.ELT_APPINFO)) ||
(name.equals(SchemaSymbols.ELT_DOCUMENTATION)))) {
// REVISIT: Localize
reportGenericSchemaError("an <annotation> can only contain <appinfo> and <documentation> elements");
}
// General Attribute Checking
attrValues = fGeneralAttrCheck.checkAttributes(child, scope);
}
}
//
// Evaluates content of Annotation if present.
//
// @param: elm - top element
// @param: content - content must be annotation? or some other simple content
// @param: isEmpty: -- true if the content allowed is (annotation?) only
// false if must have some element (with possible preceding <annotation?>)
//
//REVISIT: this function should be used in all traverse* methods!
private Element checkContent( Element elm, Element content, boolean isEmpty ) throws Exception {
//isEmpty = true-> means content can be null!
if ( content == null) {
if (!isEmpty) {
reportSchemaError(SchemaMessageProvider.ContentError,
new Object [] { elm.getAttribute( SchemaSymbols.ATT_NAME )});
}
return null;
}
if (content.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
traverseAnnotationDecl( content );
content = XUtil.getNextSiblingElement(content);
if (content == null ) { //must be followed by <simpleType?>
if (!isEmpty) {
reportSchemaError(SchemaMessageProvider.ContentError,
new Object [] { elm.getAttribute( SchemaSymbols.ATT_NAME )});
}
return null;
}
if (content.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
reportSchemaError(SchemaMessageProvider.AnnotationError,
new Object [] { elm.getAttribute( SchemaSymbols.ATT_NAME )});
return null;
}
//return null if expected only annotation?, else returns updated content
}
return content;
}
//@param: elm - top element
//@param: baseTypeStr - type (base/itemType/memberTypes)
//@param: baseRefContext: whether the caller is using this type as a base for restriction, union or list
//return DatatypeValidator available for the baseTypeStr, null if not found or disallowed.
// also throws an error if the base type won't allow itself to be used in this context.
//REVISIT: this function should be used in some|all traverse* methods!
private DatatypeValidator findDTValidator (Element elm, String baseTypeStr, int baseRefContext ) throws Exception{
int baseType = fStringPool.addSymbol( baseTypeStr );
String prefix = "";
DatatypeValidator baseValidator = null;
String localpart = baseTypeStr;
int colonptr = baseTypeStr.indexOf(":");
if ( colonptr > 0) {
prefix = baseTypeStr.substring(0,colonptr);
localpart = baseTypeStr.substring(colonptr+1);
}
String uri = resolvePrefixToURI(prefix);
baseValidator = getDatatypeValidator(uri, localpart);
if (baseValidator == null) {
Element baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (baseTypeNode != null) {
traverseSimpleTypeDecl( baseTypeNode );
baseValidator = getDatatypeValidator(uri, localpart);
}
}
Integer finalValue;
if ( baseValidator == null ) {
reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype,
new Object [] { elm.getAttribute( SchemaSymbols.ATT_BASE ),
elm.getAttribute(SchemaSymbols.ATT_NAME)});
} else {
finalValue = (uri.equals("")?
((Integer)fSimpleTypeFinalRegistry.get(localpart)):
((Integer)fSimpleTypeFinalRegistry.get(uri + "," +localpart)));
if((finalValue != null) &&
((finalValue.intValue() & baseRefContext) != 0)) {
//REVISIT: localize
reportGenericSchemaError("the base type " + baseTypeStr + " does not allow itself to be used as the base for a restriction and/or as a type in a list and/or union");
return baseValidator;
}
}
return baseValidator;
}
private void checkEnumerationRequiredNotation(String name, String type) throws Exception{
String localpart = type;
int colonptr = type.indexOf(":");
if ( colonptr > 0) {
localpart = type.substring(colonptr+1);
}
if (localpart.equals("NOTATION")) {
reportGenericSchemaError("[enumeration-required-notation] It is an error for NOTATION to be used "+
"directly in a schema in element/attribute '"+name+"'");
}
}
// @used in traverseSimpleType
// on return we need to pop the last simpleType name from
// the name stack
private int resetSimpleTypeNameStack(int returnValue){
if (!fSimpleTypeNameStack.empty()) {
fSimpleTypeNameStack.pop();
}
return returnValue;
}
// @used in traverseSimpleType
// report an error cos-list-of-atomic and reset the last name of the list datatype we traversing
private void reportCosListOfAtomic () throws Exception{
reportGenericSchemaError("cos-list-of-atomic: The itemType must have a {variety} of atomic or union (in which case all the {member type definitions} must be atomic)");
fListName="";
}
// @used in traverseSimpleType
// find if union datatype validator has list datatype member.
private boolean isListDatatype (DatatypeValidator validator){
if (validator instanceof UnionDatatypeValidator) {
Vector temp = ((UnionDatatypeValidator)validator).getBaseValidators();
for (int i=0;i<temp.size();i++) {
if (temp.elementAt(i) instanceof ListDatatypeValidator) {
return true;
}
if (temp.elementAt(i) instanceof UnionDatatypeValidator) {
if (isListDatatype((DatatypeValidator)temp.elementAt(i))) {
return true;
}
}
}
}
return false;
}
/**
* Traverse SimpleType declaration:
* <simpleType
* final = #all | list of (restriction, union or list)
* id = ID
* name = NCName>
* Content: (annotation? , ((list | restriction | union)))
* </simpleType>
* traverse <list>|<restriction>|<union>
*
* @param simpleTypeDecl
* @return
*/
private int traverseSimpleTypeDecl( Element simpleTypeDecl ) throws Exception {
// General Attribute Checking
int scope = isTopLevel(simpleTypeDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(simpleTypeDecl, scope);
String nameProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME );
String qualifiedName = nameProperty;
//---------------------------------------------------
// set qualified name
//---------------------------------------------------
if ( nameProperty.length() == 0) { // anonymous simpleType
qualifiedName = "#S#"+(fSimpleTypeAnonCount++);
fStringPool.addSymbol(qualifiedName);
}
else {
if (fTargetNSURIString.length () != 0) {
qualifiedName = fTargetNSURIString+","+qualifiedName;
}
fStringPool.addSymbol( nameProperty );
}
//----------------------------------------------------------------------
//check if we have already traversed the same simpleType decl
//----------------------------------------------------------------------
if (fDatatypeRegistry.getDatatypeValidator(qualifiedName)!=null) {
return resetSimpleTypeNameStack(fStringPool.addSymbol(qualifiedName));
}
else {
if (fSimpleTypeNameStack.search(qualifiedName) != -1 ){
// cos-no-circular-unions && no circular definitions
reportGenericSchemaError("cos-no-circular-unions: no circular definitions are allowed for an element '"+ nameProperty+"'");
return resetSimpleTypeNameStack(-1);
}
}
//----------------------------------------------------------
// update _final_ registry
//----------------------------------------------------------
Attr finalAttr = simpleTypeDecl.getAttributeNode(SchemaSymbols.ATT_FINAL);
int finalProperty = 0;
if(finalAttr != null)
finalProperty = parseFinalSet(finalAttr.getValue());
else
finalProperty = parseFinalSet(null);
// if we have a nonzero final , store it in the hash...
if(finalProperty != 0)
fSimpleTypeFinalRegistry.put(qualifiedName, new Integer(finalProperty));
// -------------------------------
// remember name being traversed to
// avoid circular definitions in union
// -------------------------------
fSimpleTypeNameStack.push(qualifiedName);
//----------------------------------------------------------------------
//annotation?,(list|restriction|union)
//----------------------------------------------------------------------
Element content = XUtil.getFirstChildElement(simpleTypeDecl);
content = checkContent(simpleTypeDecl, content, false);
if (content == null) {
return resetSimpleTypeNameStack(-1);
}
// General Attribute Checking
scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable contentAttrs = fGeneralAttrCheck.checkAttributes(content, scope);
//----------------------------------------------------------------------
//use content.getLocalName for the cases there "xsd:" is a prefix, ei. "xsd:list"
//----------------------------------------------------------------------
String varietyProperty = content.getLocalName();
String baseTypeQNameProperty = null;
Vector dTValidators = null;
int size = 0;
StringTokenizer unionMembers = null;
boolean list = false;
boolean union = false;
boolean restriction = false;
int numOfTypes = 0; //list/restriction = 1, union = "+"
if (varietyProperty.equals(SchemaSymbols.ELT_LIST)) { //traverse List
baseTypeQNameProperty = content.getAttribute( SchemaSymbols.ATT_ITEMTYPE );
list = true;
if (fListName.length() != 0) { // parent is <list> datatype
reportCosListOfAtomic();
return resetSimpleTypeNameStack(-1);
}
else {
fListName = qualifiedName;
}
}
else if (varietyProperty.equals(SchemaSymbols.ELT_RESTRICTION)) { //traverse Restriction
baseTypeQNameProperty = content.getAttribute( SchemaSymbols.ATT_BASE );
restriction= true;
}
else if (varietyProperty.equals(SchemaSymbols.ELT_UNION)) { //traverse union
union = true;
baseTypeQNameProperty = content.getAttribute( SchemaSymbols.ATT_MEMBERTYPES);
if (baseTypeQNameProperty.length() != 0) {
unionMembers = new StringTokenizer( baseTypeQNameProperty );
size = unionMembers.countTokens();
}
else {
size = 1; //at least one must be seen as <simpleType> decl
}
dTValidators = new Vector (size, 2);
}
else {
reportSchemaError(SchemaMessageProvider.FeatureUnsupported,
new Object [] { varietyProperty });
return -1;
}
if(XUtil.getNextSiblingElement(content) != null) {
// REVISIT: Localize
reportGenericSchemaError("error in content of simpleType");
}
int typeNameIndex;
DatatypeValidator baseValidator = null;
if ( baseTypeQNameProperty.length() == 0 ) {
//---------------------------
//must 'see' <simpleType>
//---------------------------
//content = {annotation?,simpleType?...}
content = XUtil.getFirstChildElement(content);
//check content (annotation?, ...)
content = checkContent(simpleTypeDecl, content, false);
if (content == null) {
return resetSimpleTypeNameStack(-1);
}
if (content.getLocalName().equals( SchemaSymbols.ELT_SIMPLETYPE )) {
typeNameIndex = traverseSimpleTypeDecl(content);
if (typeNameIndex!=-1) {
baseValidator=fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex));
if (baseValidator !=null && union) {
dTValidators.addElement((DatatypeValidator)baseValidator);
}
}
if ( typeNameIndex == -1 || baseValidator == null) {
reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype,
new Object [] { content.getAttribute( SchemaSymbols.ATT_BASE ),
content.getAttribute(SchemaSymbols.ATT_NAME) });
return resetSimpleTypeNameStack(-1);
}
}
else {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
return resetSimpleTypeNameStack(-1);
}
} //end - must see simpleType?
else {
//-----------------------------
//base was provided - get proper validator.
//-----------------------------
numOfTypes = 1;
if (union) {
numOfTypes= size;
}
//--------------------------------------------------------------------
// this loop is also where we need to find out whether the type being used as
// a base (or itemType or whatever) allows such things.
//--------------------------------------------------------------------
int baseRefContext = (restriction? SchemaSymbols.RESTRICTION:0);
baseRefContext = baseRefContext | (union? SchemaSymbols.UNION:0);
baseRefContext = baseRefContext | (list ? SchemaSymbols.LIST:0);
for (int i=0; i<numOfTypes; i++) { //find all validators
if (union) {
baseTypeQNameProperty = unionMembers.nextToken();
}
baseValidator = findDTValidator ( simpleTypeDecl, baseTypeQNameProperty, baseRefContext);
if ( baseValidator == null) {
return resetSimpleTypeNameStack(-1);
}
// ------------------------------
// (variety is list)cos-list-of-atomic
// ------------------------------
if (fListName.length() != 0 ) {
if (baseValidator instanceof ListDatatypeValidator) {
reportCosListOfAtomic();
return resetSimpleTypeNameStack(-1);
}
//-----------------------------------------------------
// if baseValidator is of type (union) need to look
// at Union validators to make sure that List is not one of them
//-----------------------------------------------------
if (isListDatatype(baseValidator)) {
reportCosListOfAtomic();
return resetSimpleTypeNameStack(-1);
}
}
if (union) {
dTValidators.addElement((DatatypeValidator)baseValidator); //add validator to structure
}
//REVISIT: Should we raise exception here?
// if baseValidator.isInstanceOf(LIST) and UNION
if ( list && (baseValidator instanceof UnionDatatypeValidator)) {
reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE ),
simpleTypeDecl.getAttribute(SchemaSymbols.ATT_NAME)});
return -1;
}
}
} //end - base is available
// ------------------------------------------
// move to next child
// <base==empty)->[simpleType]->[facets] OR
// <base!=empty)->[facets]
// ------------------------------------------
if (baseTypeQNameProperty.length() == 0) {
content = XUtil.getNextSiblingElement( content );
}
else {
content = XUtil.getFirstChildElement(content);
}
// ------------------------------------------
//get more types for union if any
// ------------------------------------------
if (union) {
int index=size;
if (baseTypeQNameProperty.length() != 0 ) {
content = checkContent(simpleTypeDecl, content, true);
}
while (content!=null) {
typeNameIndex = traverseSimpleTypeDecl(content);
if (typeNameIndex!=-1) {
baseValidator=fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex));
if (baseValidator != null) {
if (fListName.length() != 0 && baseValidator instanceof ListDatatypeValidator) {
reportCosListOfAtomic();
return resetSimpleTypeNameStack(-1);
}
dTValidators.addElement((DatatypeValidator)baseValidator);
}
}
if ( baseValidator == null || typeNameIndex == -1) {
reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE ),
simpleTypeDecl.getAttribute(SchemaSymbols.ATT_NAME)});
return (-1);
}
content = XUtil.getNextSiblingElement( content );
}
} // end - traverse Union
if (fListName.length() != 0) {
// reset fListName, meaning that we are done with
// traversing <list> and its itemType resolves to atomic value
if (fListName.equals(qualifiedName)) {
fListName = "";
}
}
int numFacets=0;
fFacetData.clear();
if (restriction && content != null) {
short flags = 0; // flag facets that have fixed="true"
int numEnumerationLiterals = 0;
Vector enumData = new Vector();
content = checkContent(simpleTypeDecl, content , true);
StringBuffer pattern = null;
String facet;
while (content != null) {
if (content.getNodeType() == Node.ELEMENT_NODE) {
// General Attribute Checking
contentAttrs = fGeneralAttrCheck.checkAttributes(content, scope);
numFacets++;
facet =content.getLocalName();
if (facet.equals(SchemaSymbols.ELT_ENUMERATION)) {
numEnumerationLiterals++;
String enumVal = content.getAttribute(SchemaSymbols.ATT_VALUE);
String localName;
if (baseValidator instanceof NOTATIONDatatypeValidator) {
String prefix = "";
String localpart = enumVal;
int colonptr = enumVal.indexOf(":");
if ( colonptr > 0) {
prefix = enumVal.substring(0,colonptr);
localpart = enumVal.substring(colonptr+1);
}
String uriStr = (prefix.length() != 0)?resolvePrefixToURI(prefix):fTargetNSURIString;
nameProperty=uriStr + ":" + localpart;
localName = (String)fNotationRegistry.get(nameProperty);
if(localName == null){
localName = traverseNotationFromAnotherSchema( localpart, uriStr);
if (localName == null) {
reportGenericSchemaError("Notation '" + localpart +
"' not found in the grammar "+ uriStr);
}
}
enumVal=nameProperty;
}
enumData.addElement(enumVal);
checkContent(simpleTypeDecl, XUtil.getFirstChildElement( content ), true);
}
else if (facet.equals(SchemaSymbols.ELT_ANNOTATION) || facet.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
}
else if (facet.equals(SchemaSymbols.ELT_PATTERN)) {
if (pattern == null) {
pattern = new StringBuffer (content.getAttribute( SchemaSymbols.ATT_VALUE ));
}
else {
// ---------------------------------------------
//datatypes: 5.2.4 pattern: src-multiple-pattern
// ---------------------------------------------
pattern.append("|");
pattern.append(content.getAttribute( SchemaSymbols.ATT_VALUE ));
checkContent(simpleTypeDecl, XUtil.getFirstChildElement( content ), true);
}
}
else {
if ( fFacetData.containsKey(facet) )
reportSchemaError(SchemaMessageProvider.DatatypeError,
new Object [] {"The facet '" + facet + "' is defined more than once."} );
fFacetData.put(facet,content.getAttribute( SchemaSymbols.ATT_VALUE ));
if (content.getAttribute( SchemaSymbols.ATT_FIXED).equals("true") ||
content.getAttribute( SchemaSymbols.ATT_FIXED).equals("1")){
// --------------------------------------------
// set fixed facet flags
// length - must remain const through derivation
// thus we don't care if it fixed
// --------------------------------------------
if ( facet.equals(SchemaSymbols.ELT_MINLENGTH) ) {
flags |= DatatypeValidator.FACET_MINLENGTH;
}
else if (facet.equals(SchemaSymbols.ELT_MAXLENGTH)) {
flags |= DatatypeValidator.FACET_MAXLENGTH;
}
else if (facet.equals(SchemaSymbols.ELT_MAXEXCLUSIVE)) {
flags |= DatatypeValidator.FACET_MAXEXCLUSIVE;
}
else if (facet.equals(SchemaSymbols.ELT_MAXINCLUSIVE)) {
flags |= DatatypeValidator.FACET_MAXINCLUSIVE;
}
else if (facet.equals(SchemaSymbols.ELT_MINEXCLUSIVE)) {
flags |= DatatypeValidator.FACET_MINEXCLUSIVE;
}
else if (facet.equals(SchemaSymbols.ELT_MININCLUSIVE)) {
flags |= DatatypeValidator.FACET_MININCLUSIVE;
}
else if (facet.equals(SchemaSymbols.ELT_TOTALDIGITS)) {
flags |= DatatypeValidator.FACET_TOTALDIGITS;
}
else if (facet.equals(SchemaSymbols.ELT_FRACTIONDIGITS)) {
flags |= DatatypeValidator.FACET_FRACTIONDIGITS;
}
else if (facet.equals(SchemaSymbols.ELT_WHITESPACE) &&
baseValidator instanceof StringDatatypeValidator) {
flags |= DatatypeValidator.FACET_WHITESPACE;
}
}
checkContent(simpleTypeDecl, XUtil.getFirstChildElement( content ), true);
}
}
content = XUtil.getNextSiblingElement(content);
}
if (numEnumerationLiterals > 0) {
fFacetData.put(SchemaSymbols.ELT_ENUMERATION, enumData);
}
if (pattern !=null) {
fFacetData.put(SchemaSymbols.ELT_PATTERN, pattern.toString());
}
if (flags != 0) {
fFacetData.put(DatatypeValidator.FACET_FIXED, new Short(flags));
}
}
else if (list && content!=null) {
// report error - must not have any children!
if (baseTypeQNameProperty.length() != 0) {
content = checkContent(simpleTypeDecl, content, true);
if (content!=null) {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
}
}
else {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
//REVISIT: should we return?
}
}
else if (union && content!=null) {
//report error - must not have any children!
if (baseTypeQNameProperty.length() != 0) {
content = checkContent(simpleTypeDecl, content, true);
if (content!=null) {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
}
}
else {
reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError,
new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )});
//REVISIT: should we return?
}
}
// ----------------------------------------------------------------------
// create & register validator for "generated" type if it doesn't exist
// ----------------------------------------------------------------------
try {
DatatypeValidator newValidator =
fDatatypeRegistry.getDatatypeValidator( qualifiedName );
if( newValidator == null ) { // not previously registered
if (list) {
fDatatypeRegistry.createDatatypeValidator( qualifiedName, baseValidator,
fFacetData,true);
}
else if (restriction) {
fDatatypeRegistry.createDatatypeValidator( qualifiedName, baseValidator,
fFacetData,false);
}
else { //union
fDatatypeRegistry.createDatatypeValidator( qualifiedName, dTValidators);
}
}
} catch (Exception e) {
reportSchemaError(SchemaMessageProvider.DatatypeError,new Object [] { e.getMessage() });
}
return resetSimpleTypeNameStack(fStringPool.addSymbol(qualifiedName));
}
/*
* <any
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* namespace = (##any | ##other) | List of (anyURI | (##targetNamespace | ##local))
* processContents = lax | skip | strict>
* Content: (annotation?)
* </any>
*/
private int traverseAny(Element child) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(child, scope);
Element annotation = checkContent( child, XUtil.getFirstChildElement(child), true );
if(annotation != null ) {
// REVISIT: Localize
reportGenericSchemaError("<any> elements can contain at most one <annotation> element in their children");
}
int anyIndex = -1;
String namespace = child.getAttribute(SchemaSymbols.ATT_NAMESPACE).trim();
String processContents = child.getAttribute("processContents").trim();
int processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY;
int processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER;
int processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_NS;
if (processContents.length() > 0 && !processContents.equals("strict")) {
if (processContents.equals("lax")) {
processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY_LAX;
processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_LAX;
processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_NS_LAX;
}
else if (processContents.equals("skip")) {
processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY_SKIP;
processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_SKIP;
processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_NS_SKIP;
}
}
if (namespace.length() == 0 || namespace.equals("##any")) {
anyIndex = fSchemaGrammar.addContentSpecNode(processContentsAny, -1, StringPool.EMPTY_STRING, false);
}
else if (namespace.equals("##other")) {
String uri = fTargetNSURIString;
int uriIndex = fStringPool.addSymbol(uri);
anyIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyOther, -1, uriIndex, false);
}
else if (namespace.length() > 0) {
int uriIndex, leafIndex, choiceIndex;
StringTokenizer tokenizer = new StringTokenizer(namespace);
String token = tokenizer.nextToken();
if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDLOCAL)) {
choiceIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, StringPool.EMPTY_STRING, false);
} else {
if (token.equals("##targetNamespace"))
token = fTargetNSURIString;
uriIndex = fStringPool.addSymbol(token);
choiceIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, uriIndex, false);
}
while (tokenizer.hasMoreElements()) {
token = tokenizer.nextToken();
if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDLOCAL)) {
leafIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, StringPool.EMPTY_STRING, false);
} else {
if (token.equals("##targetNamespace"))
token = fTargetNSURIString;
uriIndex = fStringPool.addSymbol(token);
leafIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, uriIndex, false);
}
choiceIndex = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_CHOICE, choiceIndex, leafIndex, false);
}
anyIndex = choiceIndex;
}
else {
// REVISIT: Localize
reportGenericSchemaError("Empty namespace attribute for any element");
}
return anyIndex;
}
public DatatypeValidator getDatatypeValidator(String uri, String localpart) {
DatatypeValidator dv = null;
if (uri.length()==0 || uri.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)) {
dv = fDatatypeRegistry.getDatatypeValidator( localpart );
}
else {
dv = fDatatypeRegistry.getDatatypeValidator( uri+","+localpart );
}
return dv;
}
/*
* <anyAttribute
* id = ID
* namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace}>
* Content: (annotation?)
* </anyAttribute>
*/
private XMLAttributeDecl traverseAnyAttribute(Element anyAttributeDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(anyAttributeDecl, scope);
Element annotation = checkContent( anyAttributeDecl, XUtil.getFirstChildElement(anyAttributeDecl), true );
if(annotation != null ) {
// REVISIT: Localize
reportGenericSchemaError("<anyAttribute> elements can contain at most one <annotation> element in their children");
}
XMLAttributeDecl anyAttDecl = new XMLAttributeDecl();
String processContents = anyAttributeDecl.getAttribute(SchemaSymbols.ATT_PROCESSCONTENTS).trim();
String namespace = anyAttributeDecl.getAttribute(SchemaSymbols.ATT_NAMESPACE).trim();
// simplify! NG
//String curTargetUri = anyAttributeDecl.getOwnerDocument().getDocumentElement().getAttribute("targetNamespace");
String curTargetUri = fTargetNSURIString;
if ( namespace.length() == 0 || namespace.equals(SchemaSymbols.ATTVAL_TWOPOUNDANY) ) {
anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_ANY;
}
else if (namespace.equals(SchemaSymbols.ATTVAL_TWOPOUNDOTHER)) {
anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_OTHER;
anyAttDecl.name.uri = fStringPool.addSymbol(curTargetUri);
}
else if (namespace.length() > 0){
anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_LIST;
StringTokenizer tokenizer = new StringTokenizer(namespace);
int aStringList = fStringPool.startStringList();
Vector tokens = new Vector();
int tokenStr;
while (tokenizer.hasMoreElements()) {
String token = tokenizer.nextToken();
if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDLOCAL)) {
tokenStr = fStringPool.EMPTY_STRING;
} else {
if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDTARGETNS))
token = curTargetUri;
tokenStr = fStringPool.addSymbol(token);
}
if (!fStringPool.addStringToList(aStringList, tokenStr)){
reportGenericSchemaError("Internal StringPool error when reading the "+
"namespace attribute for anyattribute declaration");
}
}
fStringPool.finishStringList(aStringList);
anyAttDecl.enumeration = aStringList;
}
else {
// REVISIT: Localize
reportGenericSchemaError("Empty namespace attribute for anyattribute declaration");
}
// default processContents is "strict";
if (processContents.equals(SchemaSymbols.ATTVAL_SKIP)){
anyAttDecl.defaultType |= XMLAttributeDecl.PROCESSCONTENTS_SKIP;
}
else if (processContents.equals(SchemaSymbols.ATTVAL_LAX)) {
anyAttDecl.defaultType |= XMLAttributeDecl.PROCESSCONTENTS_LAX;
}
else {
anyAttDecl.defaultType |= XMLAttributeDecl.PROCESSCONTENTS_STRICT;
}
return anyAttDecl;
}
// Schema Component Constraint: Attribute Wildcard Intersection
// For a wildcard's {namespace constraint} value to be the intensional intersection of two other such values (call them O1 and O2): the appropriate case among the following must be true:
// 1 If O1 and O2 are the same value, then that value must be the value.
// 2 If either O1 or O2 is any, then the other must be the value.
// 3 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or absent), then that set, minus the negated namespace name if it was in the set, must be the value.
// 4 If both O1 and O2 are sets of (namespace names or absent), then the intersection of those sets must be the value.
// 5 If the two are negations of different namespace names, then the intersection is not expressible.
// In the case where there are more than two values, the intensional intersection is determined by identifying the intensional intersection of two of the values as above, then the intensional intersection of that value with the third (providing the first intersection was expressible), and so on as required.
private XMLAttributeDecl AWildCardIntersection(XMLAttributeDecl oneAny, XMLAttributeDecl anotherAny) {
// if either one is not expressible, the result is still not expressible
if (oneAny.type == -1) {
return oneAny;
}
if (anotherAny.type == -1) {
return anotherAny;
}
// 1 If O1 and O2 are the same value, then that value must be the value.
// this one is dealt with in different branches
// 2 If either O1 or O2 is any, then the other must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return anotherAny;
}
if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return oneAny;
}
// 3 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or absent), then that set, minus the negated namespace name if it was in the set, must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST ||
oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
XMLAttributeDecl anyList, anyOther;
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
anyList = oneAny;
anyOther = anotherAny;
} else {
anyList = anotherAny;
anyOther = oneAny;
}
int[] uriList = fStringPool.stringListAsIntArray(anyList.enumeration);
if (elementInSet(anyOther.name.uri, uriList)) {
int newList = fStringPool.startStringList();
for (int i=0; i< uriList.length; i++) {
if (uriList[i] != anyOther.name.uri ) {
fStringPool.addStringToList(newList, uriList[i]);
}
}
fStringPool.finishStringList(newList);
anyList.enumeration = newList;
}
return anyList;
}
// 4 If both O1 and O2 are sets of (namespace names or absent), then the intersection of those sets must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
int[] result = intersect2sets(fStringPool.stringListAsIntArray(oneAny.enumeration),
fStringPool.stringListAsIntArray(anotherAny.enumeration));
int newList = fStringPool.startStringList();
for (int i=0; i<result.length; i++) {
fStringPool.addStringToList(newList, result[i]);
}
fStringPool.finishStringList(newList);
oneAny.enumeration = newList;
return oneAny;
}
// 5 If the two are negations of different namespace names, then the intersection is not expressible.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
if (oneAny.name.uri == anotherAny.name.uri) {
return oneAny;
} else {
oneAny.type = -1;
return oneAny;
}
}
// should never go there;
return oneAny;
}
// Schema Component Constraint: Attribute Wildcard Union
// For a wildcard's {namespace constraint} value to be the intensional union of two other such values (call them O1 and O2): the appropriate case among the following must be true:
// 1 If O1 and O2 are the same value, then that value must be the value.
// 2 If either O1 or O2 is any, then any must be the value.
// 3 If both O1 and O2 are sets of (namespace names or absent), then the union of those sets must be the value.
// 4 If the two are negations of different namespace names, then any must be the value.
// 5 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or absent), then The appropriate case among the following must be true:
// 5.1 If the set includes the negated namespace name, then any must be the value.
// 5.2 If the set does not include the negated namespace name, then whichever of O1 or O2 is a pair of not and a namespace name must be the value.
// In the case where there are more than two values, the intensional union is determined by identifying the intensional union of two of the values as above, then the intensional union of that value with the third, and so on as required.
private XMLAttributeDecl AWildCardUnion(XMLAttributeDecl oneAny, XMLAttributeDecl anotherAny) {
// if either one is not expressible, the result is still not expressible
if (oneAny.type == -1) {
return oneAny;
}
if (anotherAny.type == -1) {
return anotherAny;
}
// 1 If O1 and O2 are the same value, then that value must be the value.
// this one is dealt with in different branches
// 2 If either O1 or O2 is any, then any must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return oneAny;
}
if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return anotherAny;
}
// 3 If both O1 and O2 are sets of (namespace names or absent), then the union of those sets must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
int[] result = union2sets(fStringPool.stringListAsIntArray(oneAny.enumeration),
fStringPool.stringListAsIntArray(anotherAny.enumeration));
int newList = fStringPool.startStringList();
for (int i=0; i<result.length; i++) {
fStringPool.addStringToList(newList, result[i]);
}
fStringPool.finishStringList(newList);
oneAny.enumeration = newList;
return oneAny;
}
// 4 If the two are negations of different namespace names, then any must be the value.
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
if (oneAny.name.uri == anotherAny.name.uri) {
return oneAny;
} else {
oneAny.type = XMLAttributeDecl.TYPE_ANY_ANY;
return oneAny;
}
}
// 5 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or absent), then The appropriate case among the following must be true:
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST ||
oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST &&
anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
XMLAttributeDecl anyList, anyOther;
if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
anyList = oneAny;
anyOther = anotherAny;
} else {
anyList = anotherAny;
anyOther = oneAny;
}
// 5.1 If the set includes the negated namespace name, then any must be the value.
if (elementInSet(anyOther.name.uri,
fStringPool.stringListAsIntArray(anyList.enumeration))) {
anyOther.type = XMLAttributeDecl.TYPE_ANY_ANY;
}
// 5.2 If the set does not include the negated namespace name, then whichever of O1 or O2 is a pair of not and a namespace name must be the value.
return anyOther;
}
// should never go there;
return oneAny;
}
// Schema Component Constraint: Wildcard Subset
// For a namespace constraint (call it sub) to be an intensional subset of another namespace constraint (call it super) one of the following must be true:
// 1 super must be any.
// 2 All of the following must be true:
// 2.1 sub must be a pair of not and a namespace name or absent.
// 2.2 super must be a pair of not and the same value.
// 3 All of the following must be true:
// 3.1 sub must be a set whose members are either namespace names or absent.
// 3.2 One of the following must be true:
// 3.2.1 super must be the same set or a superset thereof.
// 3.2.2 super must be a pair of not and a namespace name or absent and that value must not be in sub's set.
private boolean AWildCardSubset(XMLAttributeDecl subAny, XMLAttributeDecl superAny) {
// if either one is not expressible, it can't be a subset
if (subAny.type == -1 || superAny.type == -1)
return false;
// 1 super must be any.
if (superAny.type == XMLAttributeDecl.TYPE_ANY_ANY)
return true;
// 2 All of the following must be true:
// 2.1 sub must be a pair of not and a namespace name or absent.
if (subAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
// 2.2 super must be a pair of not and the same value.
if (superAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
subAny.name.uri == superAny.name.uri) {
return true;
}
}
// 3 All of the following must be true:
// 3.1 sub must be a set whose members are either namespace names or absent.
if (subAny.type == XMLAttributeDecl.TYPE_ANY_LIST) {
// 3.2 One of the following must be true:
// 3.2.1 super must be the same set or a superset thereof.
if (superAny.type == XMLAttributeDecl.TYPE_ANY_LIST &&
subset2sets(fStringPool.stringListAsIntArray(subAny.enumeration),
fStringPool.stringListAsIntArray(superAny.enumeration))) {
return true;
}
// 3.2.2 super must be a pair of not and a namespace name or absent and that value must not be in sub's set.
if (superAny.type == XMLAttributeDecl.TYPE_ANY_OTHER &&
!elementInSet(superAny.name.uri, fStringPool.stringListAsIntArray(superAny.enumeration))) {
return true;
}
}
return false;
}
// Validation Rule: Wildcard allows Namespace Name
// For a value which is either a namespace name or absent to be valid with respect to a wildcard constraint (the value of a {namespace constraint}) one of the following must be true:
// 1 The constraint must be any.
// 2 All of the following must be true:
// 2.1 The constraint is a pair of not and a namespace name or absent ([Definition:] call this the namespace test).
// 2.2 The value must not be identical to the namespace test.
// 2.3 The value must not be absent.
// 3 The constraint is a set, and the value is identical to one of the members of the set.
private boolean AWildCardAllowsNameSpace(XMLAttributeDecl wildcard, String uri) {
// if the constrain is not expressible, then nothing is allowed
if (wildcard.type == -1)
return false;
// 1 The constraint must be any.
if (wildcard.type == XMLAttributeDecl.TYPE_ANY_ANY)
return true;
int uriStr = fStringPool.addString(uri);
// 2 All of the following must be true:
// 2.1 The constraint is a pair of not and a namespace name or absent ([Definition:] call this the namespace test).
if (wildcard.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
// 2.2 The value must not be identical to the namespace test.
// 2.3 The value must not be absent.
if (uriStr != wildcard.name.uri && uriStr != StringPool.EMPTY_STRING)
return true;
}
// 3 The constraint is a set, and the value is identical to one of the members of the set.
if (wildcard.type == XMLAttributeDecl.TYPE_ANY_LIST) {
if (elementInSet(uriStr, fStringPool.stringListAsIntArray(wildcard.enumeration)))
return true;
}
return false;
}
private boolean isAWildCard(XMLAttributeDecl a) {
if (a.type == XMLAttributeDecl.TYPE_ANY_ANY
||a.type == XMLAttributeDecl.TYPE_ANY_LIST
||a.type == XMLAttributeDecl.TYPE_ANY_OTHER )
return true;
else
return false;
}
int[] intersect2sets(int[] one, int[] theOther){
int[] result = new int[(one.length>theOther.length?one.length:theOther.length)];
// simple implemention,
int count = 0;
for (int i=0; i<one.length; i++) {
if (elementInSet(one[i], theOther))
result[count++] = one[i];
}
int[] result2 = new int[count];
System.arraycopy(result, 0, result2, 0, count);
return result2;
}
int[] union2sets(int[] one, int[] theOther){
int[] result1 = new int[one.length];
// simple implemention,
int count = 0;
for (int i=0; i<one.length; i++) {
if (!elementInSet(one[i], theOther))
result1[count++] = one[i];
}
int[] result2 = new int[count+theOther.length];
System.arraycopy(result1, 0, result2, 0, count);
System.arraycopy(theOther, 0, result2, count, theOther.length);
return result2;
}
boolean subset2sets(int[] subSet, int[] superSet){
for (int i=0; i<subSet.length; i++) {
if (!elementInSet(subSet[i], superSet))
return false;
}
return true;
}
boolean elementInSet(int ele, int[] set){
boolean found = false;
for (int i=0; i<set.length && !found; i++) {
if (ele==set[i])
found = true;
}
return found;
}
// wrapper traverseComplexTypeDecl method
private int traverseComplexTypeDecl( Element complexTypeDecl ) throws Exception {
return traverseComplexTypeDecl (complexTypeDecl, false);
}
/**
* Traverse ComplexType Declaration - Rec Implementation.
*
* <complexType
* abstract = boolean
* block = #all or (possibly empty) subset of {extension, restriction}
* final = #all or (possibly empty) subset of {extension, restriction}
* id = ID
* mixed = boolean : false
* name = NCName>
* Content: (annotation? , (simpleContent | complexContent |
* ( (group | all | choice | sequence)? ,
* ( (attribute | attributeGroup)* , anyAttribute?))))
* </complexType>
* @param complexTypeDecl
* @param forwardRef
* @return
*/
private int traverseComplexTypeDecl( Element complexTypeDecl, boolean forwardRef)
throws Exception {
// General Attribute Checking
int scope = isTopLevel(complexTypeDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(complexTypeDecl, scope);
// ------------------------------------------------------------------
// Get the attributes of the type
// ------------------------------------------------------------------
String isAbstract = complexTypeDecl.getAttribute( SchemaSymbols.ATT_ABSTRACT );
String blockSet = null;
Attr blockAttr = complexTypeDecl.getAttributeNode( SchemaSymbols.ATT_BLOCK );
if (blockAttr != null)
blockSet = blockAttr.getValue();
String finalSet = null;
Attr finalAttr = complexTypeDecl.getAttributeNode( SchemaSymbols.ATT_FINAL );
if (finalAttr != null)
finalSet = finalAttr.getValue();
String typeId = complexTypeDecl.getAttribute( SchemaSymbols.ATTVAL_ID );
String typeName = complexTypeDecl.getAttribute(SchemaSymbols.ATT_NAME);
String mixed = complexTypeDecl.getAttribute(SchemaSymbols.ATT_MIXED);
boolean isNamedType = false;
// ------------------------------------------------------------------
// Generate a type name, if one wasn't specified
// ------------------------------------------------------------------
if (typeName.equals("")) { // gensym a unique name
typeName = genAnonTypeName(complexTypeDecl);
}
if ( DEBUGGING )
System.out.println("traversing complex Type : " + typeName);
fCurrentTypeNameStack.push(typeName);
int typeNameIndex = fStringPool.addSymbol(typeName);
// ------------------------------------------------------------------
// Check if the type has already been registered
// ------------------------------------------------------------------
if (isTopLevel(complexTypeDecl)) {
String fullName = fTargetNSURIString+","+typeName;
ComplexTypeInfo temp = (ComplexTypeInfo) fComplexTypeRegistry.get(fullName);
if (temp != null ) {
// check for duplicate declarations
if (!forwardRef) {
if (temp.declSeen())
reportGenericSchemaError("sch-props-correct: Duplicate declaration for complexType " +
typeName);
else
temp.setDeclSeen();
}
return fStringPool.addSymbol(fullName);
}
else {
// check if the type is the name of a simple type
if (getDatatypeValidator(fTargetNSURIString,typeName)!=null)
reportGenericSchemaError("sch-props-correct: Duplicate type declaration - type is " +
typeName);
}
}
int scopeDefined = fScopeCount++;
int previousScope = fCurrentScope;
fCurrentScope = scopeDefined;
Element child = null;
ComplexTypeInfo typeInfo = new ComplexTypeInfo();
try {
// ------------------------------------------------------------------
// First, handle any ANNOTATION declaration and get next child
// ------------------------------------------------------------------
child = checkContent(complexTypeDecl,XUtil.getFirstChildElement(complexTypeDecl),
true);
// ------------------------------------------------------------------
// Process the content of the complex type declaration
// ------------------------------------------------------------------
if (child==null) {
//
// EMPTY complexType with complexContent
//
processComplexContent(typeNameIndex, child, typeInfo, null, false);
}
else {
String childName = child.getLocalName();
int index = -2;
if (childName.equals(SchemaSymbols.ELT_SIMPLECONTENT)) {
//
// SIMPLE CONTENT element
//
traverseSimpleContentDecl(typeNameIndex, child, typeInfo);
if (XUtil.getNextSiblingElement(child) != null)
throw new ComplexTypeRecoverableError(
"Invalid child following the simpleContent child in the complexType");
}
else if (childName.equals(SchemaSymbols.ELT_COMPLEXCONTENT)) {
//
// COMPLEX CONTENT element
//
traverseComplexContentDecl(typeNameIndex, child, typeInfo,
mixed.equals(SchemaSymbols.ATTVAL_TRUE) ? true:false);
if (XUtil.getNextSiblingElement(child) != null)
throw new ComplexTypeRecoverableError(
"Invalid child following the complexContent child in the complexType");
}
else {
//
// We must have ....
// GROUP, ALL, SEQUENCE or CHOICE, followed by optional attributes
// Note that it's possible that only attributes are specified.
//
processComplexContent(typeNameIndex, child, typeInfo, null,
mixed.equals(SchemaSymbols.ATTVAL_TRUE) ? true:false);
}
}
typeInfo.blockSet = parseBlockSet(blockSet);
// make sure block's value was absent, #all or in {extension, restriction}
if( (blockSet != null ) && !blockSet.equals("") &&
(!blockSet.equals(SchemaSymbols.ATTVAL_POUNDALL) &&
(((typeInfo.blockSet & SchemaSymbols.RESTRICTION) == 0) &&
((typeInfo.blockSet & SchemaSymbols.EXTENSION) == 0))))
throw new ComplexTypeRecoverableError("The values of the 'block' attribute of a complexType must be either #all or a list of 'restriction' and 'extension'; " + blockSet + " was found");
typeInfo.finalSet = parseFinalSet(finalSet);
// make sure final's value was absent, #all or in {extension, restriction}
if( (finalSet != null ) && !finalSet.equals("") &&
(!finalSet.equals(SchemaSymbols.ATTVAL_POUNDALL) &&
(((typeInfo.finalSet & SchemaSymbols.RESTRICTION) == 0) &&
((typeInfo.finalSet & SchemaSymbols.EXTENSION) == 0))))
throw new ComplexTypeRecoverableError("The values of the 'final' attribute of a complexType must be either #all or a list of 'restriction' and 'extension'; " + finalSet + " was found");
}
catch (ComplexTypeRecoverableError e) {
String message = e.getMessage();
handleComplexTypeError(message,typeNameIndex,typeInfo);
}
// ------------------------------------------------------------------
// Finish the setup of the typeInfo and register the type
// ------------------------------------------------------------------
typeInfo.scopeDefined = scopeDefined;
if (isAbstract.equals(SchemaSymbols.ATTVAL_TRUE))
typeInfo.setIsAbstractType();
if (!forwardRef)
typeInfo.setDeclSeen();
typeName = fTargetNSURIString + "," + typeName;
typeInfo.typeName = new String(typeName);
if ( DEBUGGING )
System.out.println(">>>add complex Type to Registry: " + typeName +
" baseDTValidator=" + typeInfo.baseDataTypeValidator +
" baseCTInfo=" + typeInfo.baseComplexTypeInfo +
" derivedBy=" + typeInfo.derivedBy +
" contentType=" + typeInfo.contentType +
" contentSpecHandle=" + typeInfo.contentSpecHandle +
" datatypeValidator=" + typeInfo.datatypeValidator +
" scopeDefined=" + typeInfo.scopeDefined);
fComplexTypeRegistry.put(typeName,typeInfo);
// ------------------------------------------------------------------
// Before exiting, restore the scope, mainly for nested anonymous types
// ------------------------------------------------------------------
fCurrentScope = previousScope;
fCurrentTypeNameStack.pop();
checkRecursingComplexType();
//set template element's typeInfo
fSchemaGrammar.setElementComplexTypeInfo(typeInfo.templateElementIndex, typeInfo);
typeNameIndex = fStringPool.addSymbol(typeName);
return typeNameIndex;
} // end traverseComplexTypeDecl
/**
* Traverse SimpleContent Declaration
*
* <simpleContent
* id = ID
* {any attributes with non-schema namespace...}>
*
* Content: (annotation? , (restriction | extension))
* </simpleContent>
*
* <restriction
* base = QNAME
* id = ID
* {any attributes with non-schema namespace...}>
*
* Content: (annotation?,(simpleType?, (minExclusive|minInclusive|maxExclusive
* | maxInclusive | totalDigits | fractionDigits | length | minLength
* | maxLength | encoding | period | duration | enumeration
* | pattern | whiteSpace)*) ? ,
* ((attribute | attributeGroup)* , anyAttribute?))
* </restriction>
*
* <extension
* base = QNAME
* id = ID
* {any attributes with non-schema namespace...}>
* Content: (annotation? , ((attribute | attributeGroup)* , anyAttribute?))
* </extension>
*
* @param typeNameIndex
* @param simpleContentTypeDecl
* @param typeInfo
* @return
*/
private void traverseSimpleContentDecl(int typeNameIndex,
Element simpleContentDecl, ComplexTypeInfo typeInfo)
throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(simpleContentDecl, scope);
String typeName = fStringPool.toString(typeNameIndex);
// -----------------------------------------------------------------------
// Get attributes.
// -----------------------------------------------------------------------
String simpleContentTypeId = simpleContentDecl.getAttribute(SchemaSymbols.ATTVAL_ID);
// -----------------------------------------------------------------------
// Set the content type to be simple, and initialize content spec handle
// -----------------------------------------------------------------------
typeInfo.contentType = XMLElementDecl.TYPE_SIMPLE;
typeInfo.contentSpecHandle = -1;
Element simpleContent = checkContent(simpleContentDecl,
XUtil.getFirstChildElement(simpleContentDecl),false);
// If there are no children, return
if (simpleContent==null) {
throw new ComplexTypeRecoverableError();
}
// General Attribute Checking
attrValues = fGeneralAttrCheck.checkAttributes(simpleContent, scope);
// -----------------------------------------------------------------------
// The content should be either "restriction" or "extension"
// -----------------------------------------------------------------------
String simpleContentName = simpleContent.getLocalName();
if (simpleContentName.equals(SchemaSymbols.ELT_RESTRICTION))
typeInfo.derivedBy = SchemaSymbols.RESTRICTION;
else if (simpleContentName.equals(SchemaSymbols.ELT_EXTENSION))
typeInfo.derivedBy = SchemaSymbols.EXTENSION;
else {
throw new ComplexTypeRecoverableError(
"The content of the simpleContent element is invalid. The " +
"content must be RESTRICTION or EXTENSION");
}
// -----------------------------------------------------------------------
// Get the attributes of the restriction/extension element
// -----------------------------------------------------------------------
String base = simpleContent.getAttribute(SchemaSymbols.ATT_BASE);
String typeId = simpleContent.getAttribute(SchemaSymbols.ATTVAL_ID);
// -----------------------------------------------------------------------
// Skip over any annotations in the restriction or extension elements
// -----------------------------------------------------------------------
Element content = checkContent(simpleContent,
XUtil.getFirstChildElement(simpleContent),true);
// -----------------------------------------------------------------------
// Handle the base type name
// -----------------------------------------------------------------------
if (base.length() == 0) {
throw new ComplexTypeRecoverableError(
"The BASE attribute must be specified for the " +
"RESTRICTION or EXTENSION element");
}
QName baseQName = parseBase(base);
// check if we're extending a simpleType which has a "final" setting which precludes this
Integer finalValue = (baseQName.uri == StringPool.EMPTY_STRING?
((Integer)fSimpleTypeFinalRegistry.get(fStringPool.toString(baseQName.localpart))):
((Integer)fSimpleTypeFinalRegistry.get(fStringPool.toString(baseQName.uri) + "," +fStringPool.toString(baseQName.localpart))));
if(finalValue != null &&
(finalValue.intValue() == typeInfo.derivedBy))
throw new ComplexTypeRecoverableError(
"The simpleType " + base + " that " + typeName + " uses has a value of \"final\" which does not permit extension");
processBaseTypeInfo(baseQName,typeInfo);
// check that the base isn't a complex type with complex content
if (typeInfo.baseComplexTypeInfo != null) {
if (typeInfo.baseComplexTypeInfo.contentType != XMLElementDecl.TYPE_SIMPLE) {
throw new ComplexTypeRecoverableError(
"The type '"+ base +"' specified as the " +
"base in the simpleContent element must not have complexContent");
}
}
// -----------------------------------------------------------------------
// Process the content of the derivation
// -----------------------------------------------------------------------
Element attrNode = null;
//
// RESTRICTION
//
if (typeInfo.derivedBy==SchemaSymbols.RESTRICTION) {
//
//Schema Spec : Complex Type Definition Properties Correct : 2
//
if (typeInfo.baseDataTypeValidator != null) {
throw new ComplexTypeRecoverableError(
"ct-props-correct.2: The type '" + base +"' is a simple type. It cannot be used in a "+
"derivation by RESTRICTION for a complexType");
}
else {
typeInfo.baseDataTypeValidator = typeInfo.baseComplexTypeInfo.datatypeValidator;
}
//
// Check that the base's final set does not include RESTRICTION
//
if((typeInfo.baseComplexTypeInfo.finalSet & SchemaSymbols.RESTRICTION) != 0) {
throw new ComplexTypeRecoverableError("Derivation by restriction is forbidden by either the base type " + base + " or the schema");
}
// -----------------------------------------------------------------------
// There may be a simple type definition in the restriction element
// The data type validator will be based on it, if specified
// -----------------------------------------------------------------------
if (content.getLocalName().equals(SchemaSymbols.ELT_SIMPLETYPE )) {
int simpleTypeNameIndex = traverseSimpleTypeDecl(content);
if (simpleTypeNameIndex!=-1) {
DatatypeValidator dv=fDatatypeRegistry.getDatatypeValidator(
fStringPool.toString(simpleTypeNameIndex));
//check that this datatype validator is validly derived from the base
//according to derivation-ok-restriction 5.1.1
if (!checkSimpleTypeDerivationOK(dv,typeInfo.baseDataTypeValidator)) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.5.1.1: The content type is not a valid restriction of the content type of the base");
}
typeInfo.baseDataTypeValidator = dv;
content = XUtil.getNextSiblingElement(content);
}
else {
throw new ComplexTypeRecoverableError();
}
}
//
// Build up facet information
//
int numEnumerationLiterals = 0;
int numFacets = 0;
Hashtable facetData = new Hashtable();
Vector enumData = new Vector();
Element child;
// General Attribute Checking
scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable contentAttrs;
//REVISIT: there is a better way to do this,
for (child = content;
child != null && (child.getLocalName().equals(SchemaSymbols.ELT_MINEXCLUSIVE) ||
child.getLocalName().equals(SchemaSymbols.ELT_MININCLUSIVE) ||
child.getLocalName().equals(SchemaSymbols.ELT_MAXEXCLUSIVE) ||
child.getLocalName().equals(SchemaSymbols.ELT_MAXINCLUSIVE) ||
child.getLocalName().equals(SchemaSymbols.ELT_TOTALDIGITS) ||
child.getLocalName().equals(SchemaSymbols.ELT_FRACTIONDIGITS) ||
child.getLocalName().equals(SchemaSymbols.ELT_LENGTH) ||
child.getLocalName().equals(SchemaSymbols.ELT_MINLENGTH) ||
child.getLocalName().equals(SchemaSymbols.ELT_MAXLENGTH) ||
child.getLocalName().equals(SchemaSymbols.ELT_PERIOD) ||
child.getLocalName().equals(SchemaSymbols.ELT_DURATION) ||
child.getLocalName().equals(SchemaSymbols.ELT_ENUMERATION) ||
child.getLocalName().equals(SchemaSymbols.ELT_PATTERN) ||
child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION));
child = XUtil.getNextSiblingElement(child))
{
if ( child.getNodeType() == Node.ELEMENT_NODE ) {
Element facetElt = (Element) child;
// General Attribute Checking
contentAttrs = fGeneralAttrCheck.checkAttributes(facetElt, scope);
numFacets++;
if (facetElt.getLocalName().equals(SchemaSymbols.ELT_ENUMERATION)) {
numEnumerationLiterals++;
enumData.addElement(facetElt.getAttribute(SchemaSymbols.ATT_VALUE));
//Enumerations can have annotations ? ( 0 | 1 )
Element enumContent = XUtil.getFirstChildElement( facetElt );
if( enumContent != null &&
enumContent.getLocalName().equals
( SchemaSymbols.ELT_ANNOTATION )){
traverseAnnotationDecl( child );
}
// TO DO: if Jeff check in new changes to TraverseSimpleType, copy them over
}
else {
facetData.put(facetElt.getLocalName(),
facetElt.getAttribute( SchemaSymbols.ATT_VALUE ));
}
}
} // end of for loop thru facets
if (numEnumerationLiterals > 0) {
facetData.put(SchemaSymbols.ELT_ENUMERATION, enumData);
}
//
// If there were facets, create a new data type validator, otherwise
// the data type validator is from the base
//
if (numFacets > 0) {
try{
typeInfo.datatypeValidator = fDatatypeRegistry.createDatatypeValidator(
typeName,
typeInfo.baseDataTypeValidator, facetData, false);
} catch (Exception e) {
throw new ComplexTypeRecoverableError(e.getMessage());
}
}
else
typeInfo.datatypeValidator =
typeInfo.baseDataTypeValidator;
if (child != null) {
//
// Check that we have attributes
//
if (!isAttrOrAttrGroup(child)) {
throw new ComplexTypeRecoverableError(
"Invalid child in the RESTRICTION element of simpleContent");
}
else
attrNode = child;
}
} // end RESTRICTION
//
// EXTENSION
//
else {
if (typeInfo.baseComplexTypeInfo != null) {
typeInfo.baseDataTypeValidator = typeInfo.baseComplexTypeInfo.datatypeValidator;
//
// Check that the base's final set does not include EXTENSION
//
if((typeInfo.baseComplexTypeInfo.finalSet &
SchemaSymbols.EXTENSION) != 0) {
throw new ComplexTypeRecoverableError("Derivation by extension is forbidden by either the base type " + base + " or the schema");
}
}
typeInfo.datatypeValidator = typeInfo.baseDataTypeValidator;
//
// Look for attributes
//
if (content != null) {
//
// Check that we have attributes
//
if (!isAttrOrAttrGroup(content)) {
throw new ComplexTypeRecoverableError(
"Only annotations and attributes are allowed in the " +
"content of an EXTENSION element for a complexType with simpleContent");
}
else {
attrNode = content;
}
}
}
// -----------------------------------------------------------------------
// add a template element to the grammar element decl pool for the type
// -----------------------------------------------------------------------
int templateElementNameIndex = fStringPool.addSymbol("$"+typeName);
typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(
new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI),
(fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : fCurrentScope, typeInfo.scopeDefined,
typeInfo.contentType,
typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator);
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(
typeInfo.templateElementIndex);
// -----------------------------------------------------------------------
// Process attributes
// -----------------------------------------------------------------------
processAttributes(attrNode,baseQName,typeInfo);
if (XUtil.getNextSiblingElement(simpleContent) != null)
throw new ComplexTypeRecoverableError(
"Invalid child following the RESTRICTION or EXTENSION element in the " +
"complex type definition");
} // end traverseSimpleContentDecl
/**
* Traverse complexContent Declaration
*
* <complexContent
* id = ID
* mixed = boolean
* {any attributes with non-schema namespace...}>
*
* Content: (annotation? , (restriction | extension))
* </complexContent>
*
* <restriction
* base = QNAME
* id = ID
* {any attributes with non-schema namespace...}>
*
* Content: (annotation? , (group | all | choice | sequence)?,
* ((attribute | attributeGroup)* , anyAttribute?))
* </restriction>
*
* <extension
* base = QNAME
* id = ID
* {any attributes with non-schema namespace...}>
* Content: (annotation? , (group | all | choice | sequence)?,
* ((attribute | attributeGroup)* , anyAttribute?))
* </extension>
*
* @param typeNameIndex
* @param simpleContentTypeDecl
* @param typeInfo
* @param mixedOnComplexTypeDecl
* @return
*/
private void traverseComplexContentDecl(int typeNameIndex,
Element complexContentDecl, ComplexTypeInfo typeInfo,
boolean mixedOnComplexTypeDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(complexContentDecl, scope);
String typeName = fStringPool.toString(typeNameIndex);
// -----------------------------------------------------------------------
// Get the attributes
// -----------------------------------------------------------------------
String typeId = complexContentDecl.getAttribute(SchemaSymbols.ATTVAL_ID);
String mixed = complexContentDecl.getAttribute(SchemaSymbols.ATT_MIXED);
// -----------------------------------------------------------------------
// Determine whether the content is mixed, or element-only
// Setting here overrides any setting on the complex type decl
// -----------------------------------------------------------------------
boolean isMixed = mixedOnComplexTypeDecl;
if (mixed.equals(SchemaSymbols.ATTVAL_TRUE))
isMixed = true;
else if (mixed.equals(SchemaSymbols.ATTVAL_FALSE))
isMixed = false;
// -----------------------------------------------------------------------
// Since the type must have complex content, set the simple type validators
// to null
// -----------------------------------------------------------------------
typeInfo.datatypeValidator = null;
typeInfo.baseDataTypeValidator = null;
Element complexContent = checkContent(complexContentDecl,
XUtil.getFirstChildElement(complexContentDecl),false);
// If there are no children, return
if (complexContent==null) {
throw new ComplexTypeRecoverableError();
}
// -----------------------------------------------------------------------
// The content should be either "restriction" or "extension"
// -----------------------------------------------------------------------
String complexContentName = complexContent.getLocalName();
if (complexContentName.equals(SchemaSymbols.ELT_RESTRICTION))
typeInfo.derivedBy = SchemaSymbols.RESTRICTION;
else if (complexContentName.equals(SchemaSymbols.ELT_EXTENSION))
typeInfo.derivedBy = SchemaSymbols.EXTENSION;
else {
throw new ComplexTypeRecoverableError(
"The content of the complexContent element is invalid. " +
"The content must be RESTRICTION or EXTENSION");
}
// Get the attributes of the restriction/extension element
String base = complexContent.getAttribute(SchemaSymbols.ATT_BASE);
String complexContentTypeId=complexContent.getAttribute(SchemaSymbols.ATTVAL_ID);
// Skip over any annotations in the restriction or extension elements
Element content = checkContent(complexContent,
XUtil.getFirstChildElement(complexContent),true);
// -----------------------------------------------------------------------
// Handle the base type name
// -----------------------------------------------------------------------
if (base.length() == 0) {
throw new ComplexTypeRecoverableError(
"The BASE attribute must be specified for the " +
"RESTRICTION or EXTENSION element");
}
QName baseQName = parseBase(base);
// -------------------------------------------------------------
// check if the base is "anyType"
// -------------------------------------------------------------
String baseTypeURI = fStringPool.toString(baseQName.uri);
String baseLocalName = fStringPool.toString(baseQName.localpart);
if (!(baseTypeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) &&
baseLocalName.equals("anyType"))) {
processBaseTypeInfo(baseQName,typeInfo);
//Check that the base is a complex type
if (typeInfo.baseComplexTypeInfo == null) {
throw new ComplexTypeRecoverableError(
"The base type specified in the complexContent element must be a complexType");
}
}
// -----------------------------------------------------------------------
// Process the elements that make up the content
// -----------------------------------------------------------------------
processComplexContent(typeNameIndex,content,typeInfo,baseQName,isMixed);
if (XUtil.getNextSiblingElement(complexContent) != null)
throw new ComplexTypeRecoverableError(
"Invalid child following the RESTRICTION or EXTENSION element in the " +
"complex type definition");
} // end traverseComplexContentDecl
/**
* Handle complexType error
*
* @param message
* @param typeNameIndex
* @param typeInfo
* @return
*/
private void handleComplexTypeError(String message, int typeNameIndex,
ComplexTypeInfo typeInfo) throws Exception {
String typeName = fStringPool.toString(typeNameIndex);
if (message != null) {
if (typeName.startsWith("#"))
reportGenericSchemaError("Anonymous complexType: " + message);
else
reportGenericSchemaError("ComplexType '" + typeName + "': " + message);
}
//
// Mock up the typeInfo structure so that there won't be problems during
// validation
//
typeInfo.contentType = XMLElementDecl.TYPE_ANY; // this should match anything
typeInfo.contentSpecHandle = -1;
typeInfo.derivedBy = 0;
typeInfo.datatypeValidator = null;
typeInfo.attlistHead = -1;
int templateElementNameIndex = fStringPool.addSymbol("$"+typeName);
typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(
new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI),
(fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : fCurrentScope, typeInfo.scopeDefined,
typeInfo.contentType,
typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator);
return;
}
/**
* Generate a name for an anonymous type
*
* @param Element
* @return String
*/
private String genAnonTypeName(Element complexTypeDecl) throws Exception {
String typeName;
// If the anonymous type is not nested within another type, we can
// simply assign the type a numbered name
//
if (fCurrentTypeNameStack.empty())
typeName = "#"+fAnonTypeCount++;
// Otherwise, we must generate a name that can be looked up later
// Do this by concatenating outer type names with the name of the parent
// element
else {
String parentName = ((Element)complexTypeDecl.getParentNode()).getAttribute(
SchemaSymbols.ATT_NAME);
typeName = parentName + "_AnonType";
int index=fCurrentTypeNameStack.size() -1;
for (int i = index; i > -1; i--) {
String parentType = (String)fCurrentTypeNameStack.elementAt(i);
typeName = parentType + "_" + typeName;
if (!(parentType.startsWith("#")))
break;
}
typeName = "#" + typeName;
}
return typeName;
}
/**
* Parse base string
*
* @param base
* @return QName
*/
private QName parseBase(String base) throws Exception {
String prefix = "";
String localpart = base;
int colonptr = base.indexOf(":");
if ( colonptr > 0) {
prefix = base.substring(0,colonptr);
localpart = base.substring(colonptr+1);
}
int nameIndex = fStringPool.addSymbol(base);
int prefixIndex = fStringPool.addSymbol(prefix);
int localpartIndex = fStringPool.addSymbol(localpart);
int URIindex = fStringPool.addSymbol(resolvePrefixToURI(prefix));
return new QName(prefixIndex,localpartIndex,nameIndex,URIindex);
}
/**
* Check if base is from another schema
*
* @param baseName
* @return boolean
*/
private boolean baseFromAnotherSchema(QName baseName) throws Exception {
String typeURI = fStringPool.toString(baseName.uri);
if ( ! typeURI.equals(fTargetNSURIString)
&& ! typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& typeURI.length() != 0 )
//REVISIT, !!!! a hack: for schema that has no
//target namespace, e.g. personal-schema.xml
return true;
else
return false;
}
/**
* Process "base" information for a complexType
*
* @param baseTypeInfo
* @param baseName
* @param typeInfo
* @return
*/
private void processBaseTypeInfo(QName baseName, ComplexTypeInfo typeInfo) throws Exception {
ComplexTypeInfo baseComplexTypeInfo = null;
DatatypeValidator baseDTValidator = null;
String typeURI = fStringPool.toString(baseName.uri);
String localpart = fStringPool.toString(baseName.localpart);
String base = fStringPool.toString(baseName.rawname);
// -------------------------------------------------------------
// check if the base type is from another schema
// -------------------------------------------------------------
if (baseFromAnotherSchema(baseName)) {
baseComplexTypeInfo = getTypeInfoFromNS(typeURI, localpart);
if (baseComplexTypeInfo == null) {
baseDTValidator = getTypeValidatorFromNS(typeURI, localpart);
if (baseDTValidator == null) {
throw new ComplexTypeRecoverableError(
"Could not find base type " +localpart
+ " in schema " + typeURI);
}
}
}
// -------------------------------------------------------------
// type must be from same schema
// -------------------------------------------------------------
else {
String fullBaseName = typeURI+","+localpart;
// assume the base is a complexType and try to locate the base type first
baseComplexTypeInfo= (ComplexTypeInfo) fComplexTypeRegistry.get(fullBaseName);
// if not found, 2 possibilities:
// 1: ComplexType in question has not been compiled yet;
// 2: base is SimpleTYpe;
if (baseComplexTypeInfo == null) {
baseDTValidator = getDatatypeValidator(typeURI, localpart);
if (baseDTValidator == null) {
int baseTypeSymbol;
Element baseTypeNode = getTopLevelComponentByName(
SchemaSymbols.ELT_COMPLEXTYPE,localpart);
if (baseTypeNode != null) {
// Before traversing the base, make sure we're not already
// doing so..
// ct-props-correct 3
if (fCurrentTypeNameStack.search((Object)localpart) > - 1) {
throw new ComplexTypeRecoverableError(
"ct-props-correct.3: Recursive type definition");
}
baseTypeSymbol = traverseComplexTypeDecl( baseTypeNode, true );
baseComplexTypeInfo = (ComplexTypeInfo)
fComplexTypeRegistry.get(fStringPool.toString(baseTypeSymbol));
//REVISIT: should it be fullBaseName;
}
else {
baseTypeNode = getTopLevelComponentByName(
SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (baseTypeNode != null) {
baseTypeSymbol = traverseSimpleTypeDecl( baseTypeNode );
baseDTValidator = getDatatypeValidator(typeURI, localpart);
if (baseDTValidator == null) {
//TO DO: signal error here.
}
}
else {
throw new ComplexTypeRecoverableError(
"Base type could not be found : " + base);
}
}
}
}
} // end else (type must be from same schema)
typeInfo.baseComplexTypeInfo = baseComplexTypeInfo;
typeInfo.baseDataTypeValidator = baseDTValidator;
} // end processBaseTypeInfo
/**
* Process content which is complex
*
* (group | all | choice | sequence) ? ,
* ((attribute | attributeGroup)* , anyAttribute?))
*
* @param typeNameIndex
* @param complexContentChild
* @param typeInfo
* @return
*/
private void processComplexContent(int typeNameIndex,
Element complexContentChild, ComplexTypeInfo typeInfo, QName baseName,
boolean isMixed) throws Exception {
Element attrNode = null;
int index=-2;
String typeName = fStringPool.toString(typeNameIndex);
if (complexContentChild != null) {
// -------------------------------------------------------------
// GROUP, ALL, SEQUENCE or CHOICE, followed by attributes, if specified.
// Note that it's possible that only attributes are specified.
// -------------------------------------------------------------
String childName = complexContentChild.getLocalName();
if (childName.equals(SchemaSymbols.ELT_GROUP)) {
int groupIndex = traverseGroupDecl(complexContentChild);
index = handleOccurrences(groupIndex,
complexContentChild,
hasAllContent(groupIndex) ? GROUP_REF_WITH_ALL :
NOT_ALL_CONTEXT);
attrNode = XUtil.getNextSiblingElement(complexContentChild);
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = handleOccurrences(traverseSequence(complexContentChild),
complexContentChild);
attrNode = XUtil.getNextSiblingElement(complexContentChild);
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = handleOccurrences(traverseChoice(complexContentChild),
complexContentChild);
attrNode = XUtil.getNextSiblingElement(complexContentChild);
}
else if (childName.equals(SchemaSymbols.ELT_ALL)) {
index = handleOccurrences(traverseAll(complexContentChild),
complexContentChild, PROCESSING_ALL);
attrNode = XUtil.getNextSiblingElement(complexContentChild);
}
else if (isAttrOrAttrGroup(complexContentChild)) {
// reset the contentType
typeInfo.contentType = XMLElementDecl.TYPE_ANY;
attrNode = complexContentChild;
}
else {
throw new ComplexTypeRecoverableError(
"Invalid child '"+ childName +"' in the complex type");
}
}
typeInfo.contentSpecHandle = index;
// -----------------------------------------------------------------------
// Merge in information from base, if it exists
// -----------------------------------------------------------------------
if (typeInfo.baseComplexTypeInfo != null) {
int baseContentSpecHandle = typeInfo.baseComplexTypeInfo.contentSpecHandle;
//-------------------------------------------------------------
// RESTRICTION
//-------------------------------------------------------------
if (typeInfo.derivedBy == SchemaSymbols.RESTRICTION) {
// check to see if the baseType permits derivation by restriction
if((typeInfo.baseComplexTypeInfo.finalSet & SchemaSymbols.RESTRICTION) != 0)
throw new ComplexTypeRecoverableError("Derivation by restriction is forbidden by either the base type " + fStringPool.toString(baseName.localpart) + " or the schema");
// if the content is EMPTY, check that the base is correct
// according to derivation-ok-restriction 5.2
if (typeInfo.contentSpecHandle==-2) {
if (!(typeInfo.baseComplexTypeInfo.contentType==XMLElementDecl.TYPE_EMPTY ||
particleEmptiable(baseContentSpecHandle))) {
throw new ComplexTypeRecoverableError("derivation-ok-restrictoin.5.2 Content type of complexType is EMPTY but base is not EMPTY or does not have a particle which is emptiable");
}
}
//
// The hairy derivation by restriction particle constraints
// derivation-ok-restriction 5.3
//
else {
try {
checkParticleDerivationOK(typeInfo.contentSpecHandle,fCurrentScope,
baseContentSpecHandle,typeInfo.baseComplexTypeInfo.scopeDefined,
typeInfo.baseComplexTypeInfo);
}
catch (ParticleRecoverableError e) {
String message = e.getMessage();
throw new ComplexTypeRecoverableError(message);
}
}
}
//-------------------------------------------------------------
// EXTENSION
//-------------------------------------------------------------
else {
// check to see if the baseType permits derivation by extension
if((typeInfo.baseComplexTypeInfo.finalSet & SchemaSymbols.EXTENSION) != 0)
throw new ComplexTypeRecoverableError("cos-ct-extends.1.1: Derivation by extension is forbidden by either the base type " + fStringPool.toString(baseName.localpart) + " or the schema");
//
// Check if the contentType of the base is consistent with the new type
// cos-ct-extends.1.4.2.2
if (typeInfo.baseComplexTypeInfo.contentType != XMLElementDecl.TYPE_EMPTY) {
if (((typeInfo.baseComplexTypeInfo.contentType == XMLElementDecl.TYPE_CHILDREN) &&
isMixed) ||
((typeInfo.baseComplexTypeInfo.contentType == XMLElementDecl.TYPE_MIXED_COMPLEX) &&
!isMixed)) {
throw new ComplexTypeRecoverableError("cos-ct-extends.1.4.2.2.2.1: The content type of the base type " +
fStringPool.toString(baseName.localpart) + " and derived type " +
typeName + " must both be mixed or element-only");
}
}
//
// Compose the final content model by concatenating the base and the
// current in sequence
//
if (baseFromAnotherSchema(baseName)) {
String baseSchemaURI = fStringPool.toString(baseName.uri);
SchemaGrammar aGrammar= (SchemaGrammar) fGrammarResolver.getGrammar(
baseSchemaURI);
baseContentSpecHandle = importContentSpec(aGrammar, baseContentSpecHandle);
}
if (typeInfo.contentSpecHandle == -2) {
typeInfo.contentSpecHandle = baseContentSpecHandle;
}
else if (baseContentSpecHandle > -1) {
if (typeInfo.contentSpecHandle > -1 &&
(hasAllContent(typeInfo.contentSpecHandle) ||
hasAllContent(baseContentSpecHandle))) {
throw new ComplexTypeRecoverableError("cos-all-limited: An \"all\" model group that is part of a complex type definition must constitute the entire {content type} of the definition.");
}
typeInfo.contentSpecHandle =
fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ,
baseContentSpecHandle,
typeInfo.contentSpecHandle,
false);
}
//
// Check that there is a particle in the final content
// cos-ct-extends.1.4.2.1
// LM - commented out until I get a clarification from HT
//
if (typeInfo.contentSpecHandle <0) {
throw new ComplexTypeRecoverableError("cos-ct-extends.1.4.2.1: The content of a type derived by EXTENSION must contain a particle");
}
}
}
else {
typeInfo.derivedBy = 0;
}
// -------------------------------------------------------------
// Set the content type
// -------------------------------------------------------------
if (isMixed) {
// if there are no children, detect an error
// See the definition of content type in Structures 3.4.1
if (typeInfo.contentSpecHandle == -2) {
throw new ComplexTypeRecoverableError("Type '" + typeName + "': The content of a mixed complexType must not be empty");
}
else
typeInfo.contentType = XMLElementDecl.TYPE_MIXED_COMPLEX;
}
else if (typeInfo.contentSpecHandle == -2)
typeInfo.contentType = XMLElementDecl.TYPE_EMPTY;
else
typeInfo.contentType = XMLElementDecl.TYPE_CHILDREN;
// -------------------------------------------------------------
// add a template element to the grammar element decl pool.
// -------------------------------------------------------------
int templateElementNameIndex = fStringPool.addSymbol("$"+typeName);
typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl(
new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI),
(fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : fCurrentScope, typeInfo.scopeDefined,
typeInfo.contentType,
typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator);
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex(
typeInfo.templateElementIndex);
// -------------------------------------------------------------
// Now, check attributes and handle
// -------------------------------------------------------------
if (attrNode !=null) {
if (!isAttrOrAttrGroup(attrNode)) {
throw new ComplexTypeRecoverableError(
"Invalid child "+ attrNode.getLocalName() + " in the complexType or complexContent");
}
else
processAttributes(attrNode,baseName,typeInfo);
}
else if (typeInfo.baseComplexTypeInfo != null)
processAttributes(null,baseName,typeInfo);
} // end processComplexContent
/**
* Process attributes of a complex type
*
* @param attrNode
* @param typeInfo
* @return
*/
private void processAttributes(Element attrNode, QName baseName,
ComplexTypeInfo typeInfo) throws Exception {
XMLAttributeDecl attWildcard = null;
Vector anyAttDecls = new Vector();
Element child;
for (child = attrNode;
child != null;
child = XUtil.getNextSiblingElement(child)) {
String childName = child.getLocalName();
if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE)) {
traverseAttributeDecl(child, typeInfo, false);
}
else if ( childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) {
traverseAttributeGroupDecl(child,typeInfo,anyAttDecls);
}
else if ( childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) {
attWildcard = traverseAnyAttribute(child);
}
else {
throw new ComplexTypeRecoverableError( "Invalid child among the children of the complexType definition");
}
}
if (attWildcard != null) {
XMLAttributeDecl fromGroup = null;
final int count = anyAttDecls.size();
if ( count > 0) {
fromGroup = (XMLAttributeDecl) anyAttDecls.elementAt(0);
for (int i=1; i<count; i++) {
fromGroup = AWildCardIntersection(
fromGroup,(XMLAttributeDecl)anyAttDecls.elementAt(i));
}
}
if (fromGroup != null) {
int saveProcessContents = attWildcard.defaultType;
attWildcard = AWildCardIntersection(attWildcard, fromGroup);
attWildcard.defaultType = saveProcessContents;
}
}
else {
//REVISIT: unclear in the Scheme Structures 4.3.3 what to do in this case
if (anyAttDecls.size()>0) {
attWildcard = (XMLAttributeDecl)anyAttDecls.elementAt(0);
}
}
//
// merge in base type's attribute decls
//
XMLAttributeDecl baseAttWildcard = null;
ComplexTypeInfo baseTypeInfo = typeInfo.baseComplexTypeInfo;
SchemaGrammar aGrammar=null;
if (baseTypeInfo != null && baseTypeInfo.attlistHead > -1 ) {
int attDefIndex = baseTypeInfo.attlistHead;
aGrammar = fSchemaGrammar;
String baseTypeSchemaURI = baseFromAnotherSchema(baseName)?
fStringPool.toString(baseName.uri):null;
if (baseTypeSchemaURI != null) {
aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(baseTypeSchemaURI);
}
if (aGrammar == null) {
//reportGenericSchemaError("In complexType "+typeName+", can NOT find the grammar "+
// "with targetNamespace" + baseTypeSchemaURI+
// "for the base type");
}
else
while ( attDefIndex > -1 ) {
fTempAttributeDecl.clear();
aGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl);
if (fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_ANY
||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LIST
||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER ) {
if (attWildcard == null) {
baseAttWildcard = fTempAttributeDecl;
}
attDefIndex = aGrammar.getNextAttributeDeclIndex(attDefIndex);
continue;
}
// if found a duplicate, if it is derived by restriction,
// then skip the one from the base type
int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, fTempAttributeDecl.name);
if ( temp > -1) {
if (typeInfo.derivedBy==SchemaSymbols.EXTENSION) {
reportGenericSchemaError("Attribute that appeared in the base should nnot appear in a derivation by extension");
}
else {
attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex);
continue;
}
}
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
fTempAttributeDecl.name, fTempAttributeDecl.type,
fTempAttributeDecl.enumeration, fTempAttributeDecl.defaultType,
fTempAttributeDecl.defaultValue,
fTempAttributeDecl.datatypeValidator,
fTempAttributeDecl.list);
attDefIndex = aGrammar.getNextAttributeDeclIndex(attDefIndex);
}
}
// att wildcard will inserted after all attributes were processed
if (attWildcard != null) {
if (attWildcard.type != -1) {
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
attWildcard.name, attWildcard.type,
attWildcard.enumeration, attWildcard.defaultType,
attWildcard.defaultValue,
attWildcard.datatypeValidator,
attWildcard.list);
}
else {
//REVISIT: unclear in Schema spec if should report error here.
reportGenericSchemaError("The intensional intersection for {attribute wildcard}s must be expressible");
}
}
else if (baseAttWildcard != null) {
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
baseAttWildcard.name, baseAttWildcard.type,
baseAttWildcard.enumeration, baseAttWildcard.defaultType,
baseAttWildcard.defaultValue,
baseAttWildcard.datatypeValidator,
baseAttWildcard.list);
}
typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex
(typeInfo.templateElementIndex);
// For derivation by restriction, ensure that the resulting attribute list
// satisfies the constraints in derivation-ok-restriction 2,3,4
if ((typeInfo.derivedBy==SchemaSymbols.RESTRICTION) &&
(typeInfo.attlistHead>-1 && baseTypeInfo != null)) {
checkAttributesDerivationOKRestriction(typeInfo.attlistHead,fSchemaGrammar,
attWildcard,baseTypeInfo.attlistHead,aGrammar,baseAttWildcard);
}
} // end processAttributes
// Check that the attributes of a type derived by restriction satisfy the
// constraints of derivation-ok-restriction
private void checkAttributesDerivationOKRestriction(int dAttListHead, SchemaGrammar dGrammar, XMLAttributeDecl dAttWildCard, int bAttListHead, SchemaGrammar bGrammar, XMLAttributeDecl bAttWildCard) throws ComplexTypeRecoverableError {
int attDefIndex = dAttListHead;
if (bAttListHead < 0) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.2: Base type definition does not have any attributes");
}
// Loop thru the attributes
while ( attDefIndex > -1 ) {
fTempAttributeDecl.clear();
dGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl);
if (isAWildCard(fTempAttributeDecl)) {
attDefIndex = dGrammar.getNextAttributeDeclIndex(attDefIndex);
continue;
}
int bAttDefIndex = bGrammar.findAttributeDecl(bAttListHead, fTempAttributeDecl.name);
if (bAttDefIndex > -1) {
fTemp2AttributeDecl.clear();
bGrammar.getAttributeDecl(bAttDefIndex, fTemp2AttributeDecl);
// derivation-ok-restriction. Constraint 2.1.1
if ((fTemp2AttributeDecl.defaultType &
XMLAttributeDecl.DEFAULT_TYPE_REQUIRED) > 0 &&
(fTempAttributeDecl.defaultType &
XMLAttributeDecl.DEFAULT_TYPE_REQUIRED) <= 0) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.1.1: Attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' in derivation has an inconsistent REQUIRED setting to that of attribute in base");
}
//
// derivation-ok-restriction. Constraint 2.1.2
//
if (!(checkSimpleTypeDerivationOK(
fTempAttributeDecl.datatypeValidator,
fTemp2AttributeDecl.datatypeValidator))) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.1.2: Type of attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' in derivation must be a restriction of type of attribute in base");
}
//
// derivation-ok-restriction. Constraint 2.1.3
//
if ((fTemp2AttributeDecl.defaultType &
XMLAttributeDecl.DEFAULT_TYPE_FIXED) > 0) {
if (!((fTempAttributeDecl.defaultType &
XMLAttributeDecl.DEFAULT_TYPE_FIXED) > 0) ||
!fTempAttributeDecl.defaultValue.equals(fTemp2AttributeDecl.defaultValue)) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.1.3: Attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' is either not fixed, or is not fixed with the same value as the attribute in the base");
}
}
}
else {
//
// derivation-ok-restriction. Constraint 2.2
//
if ((bAttWildCard==null) ||
!AWildCardAllowsNameSpace(bAttWildCard, dGrammar.getTargetNamespaceURI())) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.2: Attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' has a target namespace which is not valid with respect to a base type definition's wildcard or, the base does not contain a wildcard");
}
}
attDefIndex = dGrammar.getNextAttributeDeclIndex(attDefIndex);
}
// derivation-ok-restriction. Constraint 4
if (dAttWildCard!=null) {
if (bAttWildCard==null) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.4.1: An attribute wildcard is present in the derived type, but not the base");
}
if (!AWildCardSubset(dAttWildCard,bAttWildCard)) {
throw new ComplexTypeRecoverableError("derivation-ok-restriction.4.2: The attribute wildcard in the derived type is not a valid subset of that in the base");
}
}
}
private boolean isAttrOrAttrGroup(Element e)
{
String elementName = e.getLocalName();
if (elementName.equals(SchemaSymbols.ELT_ATTRIBUTE) ||
elementName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ||
elementName.equals(SchemaSymbols.ELT_ANYATTRIBUTE))
return true;
else
return false;
}
private void checkRecursingComplexType() throws Exception {
if ( fCurrentTypeNameStack.empty() ) {
if (! fElementRecurseComplex.isEmpty() ) {
int count= fElementRecurseComplex.size();
for (int i = 0; i<count; i++) {
ElementInfo eobj = (ElementInfo)fElementRecurseComplex.elementAt(i);
int elementIndex = eobj.elementIndex;
String typeName = eobj.typeName;
ComplexTypeInfo typeInfo =
(ComplexTypeInfo) fComplexTypeRegistry.get(fTargetNSURIString+","+typeName);
if (typeInfo==null) {
throw new Exception ( "Internal Error in void checkRecursingComplexType(). " );
}
else {
// update the element decl with info from the type
fSchemaGrammar.getElementDecl(elementIndex, fTempElementDecl);
fTempElementDecl.type = typeInfo.contentType;
fTempElementDecl.contentSpecIndex = typeInfo.contentSpecHandle;
fTempElementDecl.datatypeValidator = typeInfo.datatypeValidator;
fSchemaGrammar.setElementDecl(elementIndex, fTempElementDecl);
fSchemaGrammar.setFirstAttributeDeclIndex(elementIndex,
typeInfo.attlistHead);
fSchemaGrammar.setElementComplexTypeInfo(elementIndex,typeInfo);
}
}
fElementRecurseComplex.clear();
}
}
}
// Check that the particle defined by the derived ct tree is a valid restriction of
// that specified by baseContentSpecIndex. derivedScope and baseScope are the
// scopes of the particles, respectively. bInfo is supplied when the base particle
// is from a base type definition, and may be null - it helps determine other scopes
// that elements should be looked up in.
private void checkParticleDerivationOK(int derivedContentSpecIndex, int derivedScope, int baseContentSpecIndex, int baseScope, ComplexTypeInfo bInfo) throws Exception {
// Only do this if full checking is enabled
if (!fFullConstraintChecking)
return;
// Check for pointless occurrences of all, choice, sequence. The result is the
// contentspec which is not pointless. If the result is a non-pointless
// group, Vector is filled in with the children of interest
int csIndex1 = derivedContentSpecIndex;
fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1);
int csIndex2 = baseContentSpecIndex;
fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2);
Vector tempVector1 = new Vector();
Vector tempVector2 = new Vector();
if (tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_SEQ ||
tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_CHOICE ||
tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_ALL) {
csIndex1 = checkForPointlessOccurrences(csIndex1,tempVector1);
}
if (tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_SEQ ||
tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_CHOICE ||
tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_ALL) {
csIndex2 = checkForPointlessOccurrences(csIndex2,tempVector2);
}
fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1);
fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2);
switch (tempContentSpec1.type & 0x0f) {
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
switch (tempContentSpec2.type & 0x0f) {
// Elt:Elt NameAndTypeOK
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
checkNameAndTypeOK(csIndex1, derivedScope, csIndex2, baseScope, bInfo);
return;
}
// Elt:Any NSCompat
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_NS:
{
checkNSCompat(csIndex1, derivedScope, csIndex2);
return;
}
// Elt:All RecurseAsIfGroup
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
case XMLContentSpec.CONTENTSPECNODE_SEQ:
case XMLContentSpec.CONTENTSPECNODE_ALL:
{
checkRecurseAsIfGroup(csIndex1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
default:
{
throw new ParticleRecoverableError("internal Xerces error");
}
}
}
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_NS:
{
switch (tempContentSpec2.type & 0x0f) {
// Any:Any NSSubset
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_NS:
{
checkNSSubset(csIndex1, csIndex2);
return;
}
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
case XMLContentSpec.CONTENTSPECNODE_SEQ:
case XMLContentSpec.CONTENTSPECNODE_ALL:
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: Any: Choice,Seq,All,Elt");
}
default:
{
throw new ParticleRecoverableError("internal Xerces error");
}
}
}
case XMLContentSpec.CONTENTSPECNODE_ALL:
{
switch (tempContentSpec2.type & 0x0f) {
// All:Any NSRecurseCheckCardinality
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_NS:
{
checkNSRecurseCheckCardinality(csIndex1, tempVector1, derivedScope, csIndex2);
return;
}
case XMLContentSpec.CONTENTSPECNODE_ALL:
{
checkRecurse(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
case XMLContentSpec.CONTENTSPECNODE_SEQ:
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: All:Choice,Seq,Elt");
}
default:
{
throw new ParticleRecoverableError("internal Xerces error");
}
}
}
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
{
switch (tempContentSpec2.type & 0x0f) {
// Choice:Any NSRecurseCheckCardinality
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_NS:
{
checkNSRecurseCheckCardinality(csIndex1, tempVector1, derivedScope, csIndex2);
return;
}
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
{
checkRecurseLax(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
case XMLContentSpec.CONTENTSPECNODE_ALL:
case XMLContentSpec.CONTENTSPECNODE_SEQ:
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: Choice:All,Seq,Leaf");
}
default:
{
throw new ParticleRecoverableError("internal Xerces error");
}
}
}
case XMLContentSpec.CONTENTSPECNODE_SEQ:
{
switch (tempContentSpec2.type & 0x0f) {
// Choice:Any NSRecurseCheckCardinality
case XMLContentSpec.CONTENTSPECNODE_ANY:
case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER:
case XMLContentSpec.CONTENTSPECNODE_ANY_NS:
{
checkNSRecurseCheckCardinality(csIndex1, tempVector1, derivedScope, csIndex2);
return;
}
case XMLContentSpec.CONTENTSPECNODE_ALL:
{
checkRecurseUnordered(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
case XMLContentSpec.CONTENTSPECNODE_SEQ:
{
checkRecurse(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
case XMLContentSpec.CONTENTSPECNODE_CHOICE:
{
checkMapAndSum(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo);
return;
}
case XMLContentSpec.CONTENTSPECNODE_LEAF:
{
throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: Seq:Elt");
}
default:
{
throw new ParticleRecoverableError("internal Xerces error");
}
}
}
}
}
private int checkForPointlessOccurrences(int csIndex, Vector tempVector) {
// Note: instead of using a Vector, we should use a growable array of int.
// To be cleaned up in release 1.4.1. (LM)
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
if (tempContentSpec1.otherValue == -2) {
gatherChildren(tempContentSpec1.type,tempContentSpec1.value,tempVector);
if (tempVector.size() == 1) {
Integer returnVal = (Integer)(tempVector.elementAt(0));
return returnVal.intValue();
}
}
int type = tempContentSpec1.type;
int value = tempContentSpec1.value;
int otherValue = tempContentSpec1.otherValue;
gatherChildren(type,value, tempVector);
gatherChildren(type,otherValue, tempVector);
return csIndex;
}
private void gatherChildren(int parentType, int csIndex, Vector tempVector) {
fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1);
int min = fSchemaGrammar.getContentSpecMinOccurs(csIndex);
int max = fSchemaGrammar.getContentSpecMaxOccurs(csIndex);
int left = tempContentSpec1.value;
int right = tempContentSpec1.otherValue;
int type = tempContentSpec1.type;
if (type == XMLContentSpec.CONTENTSPECNODE_LEAF ||
(type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY ||
(type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY_NS ||
(type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER ) {
tempVector.addElement(new Integer(csIndex));
}
else if (! (min==1 && max==1)) {
tempVector.addElement(new Integer(csIndex));
}
else if (right == -2) {
gatherChildren(type,left,tempVector);
}
else if (parentType == type) {
gatherChildren(type,left,tempVector);
gatherChildren(type,right,tempVector);
}
else {
tempVector.addElement(new Integer(csIndex));
}
}
private void checkNameAndTypeOK(int csIndex1, int derivedScope, int csIndex2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1);
fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2);
int localpart1 = tempContentSpec1.value;
int uri1 = tempContentSpec1.otherValue;
int localpart2 = tempContentSpec2.value;
int uri2 = tempContentSpec2.otherValue;
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
//start the checking...
if (!(localpart1==localpart2 && uri1==uri2)) {
// we have non-matching names. Check substitution groups.
if (fSComp == null)
fSComp = new SubstitutionGroupComparator(fGrammarResolver,fStringPool,fErrorReporter);
if (!checkSubstitutionGroups(localpart1,uri1,localpart2,uri2))
throw new ParticleRecoverableError("rcase-nameAndTypeOK.1: Element name/uri in restriction does not match that of corresponding base element");
}
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.3: Element occurrence range not a restriction of base element's range: element is " + fStringPool.toString(localpart1));
}
SchemaGrammar aGrammar = fSchemaGrammar;
// get the element decl indices for the remainder...
String schemaURI = fStringPool.toString(uri1);
if ( !schemaURI.equals(fTargetNSURIString)
&& schemaURI.length() != 0 )
aGrammar= (SchemaGrammar) fGrammarResolver.getGrammar(schemaURI);
int eltndx1 = findElement(derivedScope, localpart1, aGrammar, null);
if (eltndx1 < 0)
return;
int eltndx2 = findElement(baseScope, localpart2, aGrammar, bInfo);
if (eltndx2 < 0)
return;
int miscFlags1 = ((SchemaGrammar) aGrammar).getElementDeclMiscFlags(eltndx1);
int miscFlags2 = ((SchemaGrammar) aGrammar).getElementDeclMiscFlags(eltndx2);
boolean element1IsNillable = (miscFlags1 & SchemaSymbols.NILLABLE) !=0;
boolean element2IsNillable = (miscFlags2 & SchemaSymbols.NILLABLE) !=0;
boolean element2IsFixed = (miscFlags2 & SchemaSymbols.FIXED) !=0;
boolean element1IsFixed = (miscFlags1 & SchemaSymbols.FIXED) !=0;
String element1Value = aGrammar.getElementDefaultValue(eltndx1);
String element2Value = aGrammar.getElementDefaultValue(eltndx2);
if (! (element2IsNillable || !element1IsNillable)) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.2: Element " +fStringPool.toString(localpart1) + " is nillable in the restriction but not the base");
}
if (! (element2Value == null || !element2IsFixed ||
(element1IsFixed && element1Value.equals(element2Value)))) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.4: Element " +fStringPool.toString(localpart1) + " is either not fixed, or is not fixed with the same value as in the base");
}
// check disallowed substitutions
int blockSet1 = ((SchemaGrammar) aGrammar).getElementDeclBlockSet(eltndx1);
int blockSet2 = ((SchemaGrammar) aGrammar).getElementDeclBlockSet(eltndx2);
if (((blockSet1 & blockSet2)!=blockSet2) ||
(blockSet1==0 && blockSet2!=0))
throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Element " +fStringPool.toString(localpart1) + "'s disallowed subsitutions are not a superset of those of the base element's");
// Need element decls for the remainder of the checks
aGrammar.getElementDecl(eltndx1, fTempElementDecl);
aGrammar.getElementDecl(eltndx2, fTempElementDecl2);
// check identity constraints
checkIDConstraintRestriction(fTempElementDecl, fTempElementDecl2, aGrammar, localpart1, localpart2);
// check that the derived element's type is derived from the base's. - TO BE DONE
checkTypesOK(fTempElementDecl,fTempElementDecl2,eltndx1,eltndx2,aGrammar,fStringPool.toString(localpart1));
}
private void checkTypesOK(XMLElementDecl derived, XMLElementDecl base, int dndx, int bndx, SchemaGrammar aGrammar, String elementName) throws Exception {
ComplexTypeInfo tempType=((SchemaGrammar)aGrammar).getElementComplexTypeInfo(dndx);
if (derived.type == XMLElementDecl.TYPE_SIMPLE ) {
if (base.type != XMLElementDecl.TYPE_SIMPLE)
throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derive from that of the base");
if (tempType == null) {
if (!(checkSimpleTypeDerivationOK(derived.datatypeValidator,
base.datatypeValidator)))
throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derives from that of the base");
return;
}
}
ComplexTypeInfo bType=((SchemaGrammar)aGrammar).getElementComplexTypeInfo(bndx);
for(; tempType != null; tempType = tempType.baseComplexTypeInfo) {
if (tempType.derivedBy != SchemaSymbols.RESTRICTION) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derives from that of the base");
}
if (tempType.typeName.equals(bType.typeName))
break;
}
if(tempType == null) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derives from that of the base");
}
}
private void checkIDConstraintRestriction(XMLElementDecl derivedElemDecl, XMLElementDecl baseElemDecl,
SchemaGrammar grammar, int derivedElemName, int baseElemName) throws Exception {
// this method throws no errors if the ID constraints on
// the derived element are a logical subset of those on the
// base element--that is, those that are present are
// identical to ones in the base element.
Vector derivedUnique = derivedElemDecl.unique;
Vector baseUnique = baseElemDecl.unique;
if(derivedUnique.size() > baseUnique.size()) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has fewer <unique> Identity Constraints than the base element"+
fStringPool.toString(baseElemName));
} else {
boolean found = true;
for(int i=0; i<derivedUnique.size() && found; i++) {
Unique id = (Unique)derivedUnique.elementAt(i);
found = false;
for(int j=0; j<baseUnique.size(); j++) {
if(id.equals((Unique)baseUnique.elementAt(j))) {
found = true;
break;
}
}
}
if(!found) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has a <unique> Identity Constraint that does not appear on the base element"+
fStringPool.toString(baseElemName));
}
}
Vector derivedKey = derivedElemDecl.key;
Vector baseKey = baseElemDecl.key;
if(derivedKey.size() > baseKey.size()) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has fewer <key> Identity Constraints than the base element"+
fStringPool.toString(baseElemName));
} else {
boolean found = true;
for(int i=0; i<derivedKey.size() && found; i++) {
Key id = (Key)derivedKey.elementAt(i);
found = false;
for(int j=0; j<baseKey.size(); j++) {
if(id.equals((Key)baseKey.elementAt(j))) {
found = true;
break;
}
}
}
if(!found) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has a <key> Identity Constraint that does not appear on the base element"+
fStringPool.toString(baseElemName));
}
}
Vector derivedKeyRef = derivedElemDecl.keyRef;
Vector baseKeyRef = baseElemDecl.keyRef;
if(derivedKeyRef.size() > baseKeyRef.size()) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has fewer <keyref> Identity Constraints than the base element"+
fStringPool.toString(baseElemName));
} else {
boolean found = true;
for(int i=0; i<derivedKeyRef.size() && found; i++) {
KeyRef id = (KeyRef)derivedKeyRef.elementAt(i);
found = false;
for(int j=0; j<baseKeyRef.size(); j++) {
if(id.equals((KeyRef)baseKeyRef.elementAt(j))) {
found = true;
break;
}
}
}
if(!found) {
throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " +
fStringPool.toString(derivedElemName) +
" has a <keyref> Identity Constraint that does not appear on the base element"+
fStringPool.toString(baseElemName));
}
}
} // checkIDConstraintRestriction
private boolean checkSubstitutionGroups(int local1, int uri1, int local2, int uri2)
throws Exception {
// check if either name is in the other's substitution group
QName name1 = new QName(-1,local1,local1,uri1);
QName name2 = new QName(-1,local2,local2,uri2);
if (fSComp.isEquivalentTo(name1,name2) ||
fSComp.isEquivalentTo(name2,name1))
return true;
else
return false;
}
private boolean checkOccurrenceRange(int min1, int max1, int min2, int max2) {
if ((min1 >= min2) &&
((max2==SchemaSymbols.OCCURRENCE_UNBOUNDED) || (max1!=SchemaSymbols.OCCURRENCE_UNBOUNDED && max1<=max2)))
return true;
else
return false;
}
private int findElement(int scope, int nameIndex, SchemaGrammar gr, ComplexTypeInfo bInfo) {
// check for element at given scope first
int elementDeclIndex = gr.getElementDeclIndex(nameIndex,scope);
// if not found, check at global scope
if (elementDeclIndex == -1) {
elementDeclIndex = gr.getElementDeclIndex(nameIndex, -1);
// if still not found, and base is specified, look it up there
if (elementDeclIndex == -1 && bInfo != null) {
ComplexTypeInfo baseInfo = bInfo;
while (baseInfo != null) {
elementDeclIndex = gr.getElementDeclIndex(nameIndex,baseInfo.scopeDefined);
if (elementDeclIndex > -1)
break;
baseInfo = baseInfo.baseComplexTypeInfo;
}
}
}
return elementDeclIndex;
}
private void checkNSCompat(int csIndex1, int derivedScope, int csIndex2) throws Exception {
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-NSCompat.2: Element occurrence range not a restriction of base any element's range");
}
fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1);
int uri = tempContentSpec1.otherValue;
// check wildcard subset
if (!wildcardEltAllowsNamespace(csIndex2, uri))
throw new ParticleRecoverableError("rcase-NSCompat.1: Element's namespace not allowed by wildcard in base");
}
private boolean wildcardEltAllowsNamespace(int wildcardNode, int uriIndex) {
fSchemaGrammar.getContentSpec(wildcardNode, tempContentSpec1);
if ((tempContentSpec1.type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY)
return true;
if ((tempContentSpec1.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_NS) {
if (uriIndex == tempContentSpec1.otherValue)
return true;
}
else { // must be ANY_OTHER
if (uriIndex != tempContentSpec1.otherValue && uriIndex != StringPool.EMPTY_STRING)
return true;
}
return false;
}
private void checkNSSubset(int csIndex1, int csIndex2) throws Exception {
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-NSSubset.2: Wildcard's occurrence range not a restriction of base wildcard's range");
}
if (!wildcardEltSubset(csIndex1, csIndex2))
throw new ParticleRecoverableError("rcase-NSSubset.1: Wildcard is not a subset of corresponding wildcard in base");
}
private boolean wildcardEltSubset(int wildcardNode, int wildcardBaseNode) {
fSchemaGrammar.getContentSpec(wildcardNode, tempContentSpec1);
fSchemaGrammar.getContentSpec(wildcardBaseNode, tempContentSpec2);
if ((tempContentSpec2.type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY)
return true;
if ((tempContentSpec1.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_OTHER) {
if ((tempContentSpec2.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_OTHER &&
tempContentSpec1.otherValue == tempContentSpec2.otherValue)
return true;
}
if ((tempContentSpec1.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_NS) {
if ((tempContentSpec2.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_NS &&
tempContentSpec1.otherValue == tempContentSpec2.otherValue)
return true;
if ((tempContentSpec2.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_OTHER &&
tempContentSpec1.otherValue != tempContentSpec2.otherValue)
return true;
}
return false;
}
private void checkRecurseAsIfGroup(int csIndex1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2);
// Treat the element as if it were in a group of the same type as csindex2
int indexOfGrp=fSchemaGrammar.addContentSpecNode(tempContentSpec2.type,
csIndex1,-2, false);
Vector tmpVector = new Vector();
tmpVector.addElement(new Integer(csIndex1));
if (tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_ALL ||
tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_SEQ)
checkRecurse(indexOfGrp, tmpVector, derivedScope, csIndex2,
tempVector2, baseScope, bInfo);
else
checkRecurseLax(indexOfGrp, tmpVector, derivedScope, csIndex2,
tempVector2, baseScope, bInfo);
tmpVector = null;
}
private void checkNSRecurseCheckCardinality(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2) throws Exception {
// Implement total range check
int min1 = minEffectiveTotalRange(csIndex1);
int max1 = maxEffectiveTotalRange(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-NSSubset.2: Wildcard's occurrence range not a restriction of base wildcard's range");
}
if (!wildcardEltSubset(csIndex1, csIndex2))
throw new ParticleRecoverableError("rcase-NSSubset.1: Wildcard is not a subset of corresponding wildcard in base");
// Check that each member of the group is a valid restriction of the wildcard
int count = tempVector1.size();
for (int i = 0; i < count; i++) {
Integer particle1 = (Integer)tempVector1.elementAt(i);
checkParticleDerivationOK(particle1.intValue(),derivedScope,csIndex2,-1,null);
}
}
private void checkRecurse(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-Recurse.1: Occurrence range of group is not a valid restriction of occurence range of base group");
}
int count1= tempVector1.size();
int count2= tempVector2.size();
int current = 0;
label: for (int i = 0; i<count1; i++) {
Integer particle1 = (Integer)tempVector1.elementAt(i);
for (int j = current; j<count2; j++) {
Integer particle2 = (Integer)tempVector2.elementAt(j);
current +=1;
try {
checkParticleDerivationOK(particle1.intValue(),derivedScope,
particle2.intValue(), baseScope, bInfo);
continue label;
}
catch (ParticleRecoverableError e) {
if (!particleEmptiable(particle2.intValue()))
throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles");
}
}
throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles");
}
// Now, see if there are some elements in the base we didn't match up
for (int j=current; j < count2; j++) {
Integer particle2 = (Integer)tempVector2.elementAt(j);
if (!particleEmptiable(particle2.intValue())) {
throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles");
}
}
}
private void checkRecurseUnordered(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-RecurseUnordered.1: Occurrence range of group is not a valid restriction of occurence range of base group");
}
int count1= tempVector1.size();
int count2 = tempVector2.size();
boolean foundIt[] = new boolean[count2];
label: for (int i = 0; i<count1; i++) {
Integer particle1 = (Integer)tempVector1.elementAt(i);
for (int j = 0; j<count2; j++) {
Integer particle2 = (Integer)tempVector2.elementAt(j);
try {
checkParticleDerivationOK(particle1.intValue(),derivedScope,
particle2.intValue(), baseScope, bInfo);
if (foundIt[j])
throw new ParticleRecoverableError("rcase-RecurseUnordered.2: There is not a complete functional mapping between the particles");
else
foundIt[j]=true;
continue label;
}
catch (ParticleRecoverableError e) {
}
}
// didn't find a match. Detect an error
throw new ParticleRecoverableError("rcase-RecurseUnordered.2: There is not a complete functional mapping between the particles");
}
}
private void checkRecurseLax(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1);
int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1);
int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2);
int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2);
// check Occurrence ranges
if (!checkOccurrenceRange(min1,max1,min2,max2)) {
throw new ParticleRecoverableError("rcase-RecurseLax.1: Occurrence range of group is not a valid restriction of occurence range of base group");
}
int count1= tempVector1.size();
int count2 = tempVector2.size();
int current = 0;
label: for (int i = 0; i<count1; i++) {
Integer particle1 = (Integer)tempVector1.elementAt(i);
for (int j = current; j<count2; j++) {
Integer particle2 = (Integer)tempVector2.elementAt(j);
current +=1;
try {
checkParticleDerivationOK(particle1.intValue(),derivedScope,
particle2.intValue(), baseScope, bInfo);
continue label;
}
catch (ParticleRecoverableError e) {
}
}
// didn't find a match. Detect an error
throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles");
}
}
private void checkMapAndSum(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception {
// See if the sequence group particle is a valid restriction of one of the particles
// of the choice
// This isn't what the spec says, but I can't make heads or tails of the
// algorithm in structures
int count2 = tempVector2.size();
boolean foundit = false;
for (int i=0; i<count2; i++) {
Integer particle = (Integer)tempVector2.elementAt(i);
fSchemaGrammar.getContentSpec(particle.intValue(),tempContentSpec1);
if (tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_SEQ)
try {
checkParticleDerivationOK(csIndex1,derivedScope,particle.intValue(),
baseScope, bInfo);
foundit = true;
break;
}
catch (ParticleRecoverableError e) {
}
}
if (!foundit)
throw new ParticleRecoverableError("rcase-MapAndSum: There is not a complete functional mapping between the particles");
}
private int importContentSpec(SchemaGrammar aGrammar, int contentSpecHead ) throws Exception {
XMLContentSpec ctsp = new XMLContentSpec();
aGrammar.getContentSpec(contentSpecHead, ctsp);
int left = -1;
int right = -1;
if ( ctsp.type == ctsp.CONTENTSPECNODE_LEAF
|| (ctsp.type & 0x0f) == ctsp.CONTENTSPECNODE_ANY
|| (ctsp.type & 0x0f) == ctsp.CONTENTSPECNODE_ANY_NS
|| (ctsp.type & 0x0f) == ctsp.CONTENTSPECNODE_ANY_OTHER ) {
return fSchemaGrammar.addContentSpecNode(ctsp.type, ctsp.value, ctsp.otherValue, false);
}
else if (ctsp.type == -1)
// case where type being extended has no content
return -2;
else {
if ( ctsp.value == -1 ) {
left = -1;
}
else {
left = importContentSpec(aGrammar, ctsp.value);
}
if ( ctsp.otherValue == -1 ) {
right = -1;
}
else {
right = importContentSpec(aGrammar, ctsp.otherValue);
}
return fSchemaGrammar.addContentSpecNode(ctsp.type, left, right, false);
}
}
private int handleOccurrences(int index,
Element particle) throws Exception {
// Pass through, indicating we're not processing an <all>
return handleOccurrences(index, particle, NOT_ALL_CONTEXT);
}
// Checks constraints for minOccurs, maxOccurs and expands content model
// accordingly
private int handleOccurrences(int index, Element particle,
int allContextFlags) throws Exception {
// if index is invalid, return
if (index < 0)
return index;
String minOccurs =
particle.getAttribute(SchemaSymbols.ATT_MINOCCURS).trim();
String maxOccurs =
particle.getAttribute(SchemaSymbols.ATT_MAXOCCURS).trim();
boolean processingAll = ((allContextFlags & PROCESSING_ALL) != 0);
boolean groupRefWithAll = ((allContextFlags & GROUP_REF_WITH_ALL) != 0);
boolean isGroupChild = ((allContextFlags & CHILD_OF_GROUP) != 0);
// Neither minOccurs nor maxOccurs may be specified
// for the child of a model group definition.
if (isGroupChild && (!minOccurs.equals("") || !maxOccurs.equals(""))) {
reportSchemaError(SchemaMessageProvider.MinMaxOnGroupChild, null);
minOccurs = (maxOccurs = "1");
}
// If minOccurs=maxOccurs=0, no component is specified
if(minOccurs.equals("0") && maxOccurs.equals("0")){
return -2;
}
int min=1, max=1;
if (minOccurs.equals("")) {
minOccurs = "1";
}
if (maxOccurs.equals("")) {
maxOccurs = "1";
}
// For the elements referenced in an <all>, minOccurs attribute
// must be zero or one, and maxOccurs attribute must be one.
if (processingAll || groupRefWithAll) {
if ((groupRefWithAll || !minOccurs.equals("0")) &&
!minOccurs.equals("1")) {
int minMsg = processingAll ?
SchemaMessageProvider.BadMinMaxForAll :
SchemaMessageProvider.BadMinMaxForGroupWithAll;
reportSchemaError(minMsg, new Object [] { "minOccurs",
minOccurs });
minOccurs = "1";
}
if (!maxOccurs.equals("1")) {
int maxMsg = processingAll ?
SchemaMessageProvider.BadMinMaxForAll :
SchemaMessageProvider.BadMinMaxForGroupWithAll;
reportSchemaError(maxMsg, new Object [] { "maxOccurs",
maxOccurs });
maxOccurs = "1";
}
}
try {
min = Integer.parseInt(minOccurs);
}
catch (Exception e){
reportSchemaError(SchemaMessageProvider.GenericError,
new Object [] { "illegal value for minOccurs or maxOccurs : '" +e.getMessage()+ "' "});
}
if (maxOccurs.equals("unbounded")) {
max = SchemaSymbols.OCCURRENCE_UNBOUNDED;
}
else {
try {
max = Integer.parseInt(maxOccurs);
}
catch (Exception e){
reportSchemaError(SchemaMessageProvider.GenericError,
new Object [] { "illegal value for minOccurs or maxOccurs : '" +e.getMessage()+ "' "});
}
// Check that minOccurs isn't greater than maxOccurs.
// p-props-correct 2.1
if (min > max) {
reportGenericSchemaError("p-props-correct:2.1 Value of minOccurs '" + minOccurs + "' must not be greater than value of maxOccurs '" + maxOccurs +"'");
}
if (max < 1) {
reportGenericSchemaError("p-props-correct:2.2 Value of maxOccurs " + maxOccurs + " is invalid. It must be greater than or equal to 1");
}
}
if (fSchemaGrammar.getDeferContentSpecExpansion()) {
fSchemaGrammar.setContentSpecMinOccurs(index,min);
fSchemaGrammar.setContentSpecMaxOccurs(index,max);
return index;
}
else {
return fSchemaGrammar.expandContentModel(index,min,max);
}
}
/**
* Traverses Schema attribute declaration.
*
* <attribute
* default = string
* fixed = string
* form = (qualified | unqualified)
* id = ID
* name = NCName
* ref = QName
* type = QName
* use = (optional | prohibited | required) : optional
* {any attributes with non-schema namespace ...}>
* Content: (annotation? , simpleType?)
* <attribute/>
*
* @param attributeDecl: the declaration of the attribute under
* consideration
* @param typeInfo: Contains the index of the element to which
* the attribute declaration is attached.
* @param referredTo: true iff traverseAttributeDecl was called because
* of encountering a ``ref''property (used
* to suppress error-reporting).
* @return 0 if the attribute schema is validated successfully, otherwise -1
* @exception Exception
*/
private int traverseAttributeDecl( Element attrDecl, ComplexTypeInfo typeInfo, boolean referredTo ) throws Exception {
// General Attribute Checking
int scope = isTopLevel(attrDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(attrDecl, scope);
////// Get declared fields of the attribute
String defaultStr = attrDecl.getAttribute(SchemaSymbols.ATT_DEFAULT);
String fixedStr = attrDecl.getAttribute(SchemaSymbols.ATT_FIXED);
String formStr = attrDecl.getAttribute(SchemaSymbols.ATT_FORM);//form attribute
String attNameStr = attrDecl.getAttribute(SchemaSymbols.ATT_NAME);
String refStr = attrDecl.getAttribute(SchemaSymbols.ATT_REF);
String datatypeStr = attrDecl.getAttribute(SchemaSymbols.ATT_TYPE);
String useStr = attrDecl.getAttribute(SchemaSymbols.ATT_USE);
Element simpleTypeChild = findAttributeSimpleType(attrDecl);
Attr defaultAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_DEFAULT);
Attr fixedAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_FIXED);
Attr formAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_FORM);
Attr attNameAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_NAME);
Attr refAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_REF);
Attr datatypeAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_TYPE);
Attr useAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_USE);
checkEnumerationRequiredNotation(attNameStr, datatypeStr);
////// define attribute declaration Schema components
int attName; // attribute name indexed in the string pool
int uriIndex; // indexed for target namespace uri
QName attQName; // QName combining attName and uriIndex
// attribute type
int attType;
boolean attIsList = false;
int dataTypeSymbol = -1;
String localpart = null;
// validator
DatatypeValidator dv;
boolean dvIsDerivedFromID = false;
// value constraints and use type
int attValueAndUseType = 0;
int attValueConstraint = -1; // indexed value in a string pool
////// Check W3C's PR-Structure 3.2.3
// --- Constraints on XML Representations of Attribute Declarations
boolean isAttrTopLevel = isTopLevel(attrDecl);
boolean isOptional = false;
boolean isProhibited = false;
boolean isRequired = false;
StringBuffer errorContext = new StringBuffer(30);
errorContext.append(" -- ");
if(typeInfo == null) {
errorContext.append("(global attribute) ");
}
else if(typeInfo.typeName == null) {
errorContext.append("(local attribute) ");
}
else {
errorContext.append("(attribute) ").append(typeInfo.typeName).append("/");
}
errorContext.append(attNameStr).append(' ').append(refStr);
if(useStr.equals("") || useStr.equals(SchemaSymbols.ATTVAL_OPTIONAL)) {
attValueAndUseType |= XMLAttributeDecl.USE_TYPE_OPTIONAL;
isOptional = true;
}
else if(useStr.equals(SchemaSymbols.ATTVAL_PROHIBITED)) {
attValueAndUseType |= XMLAttributeDecl.USE_TYPE_PROHIBITED;
isProhibited = true;
}
else if(useStr.equals(SchemaSymbols.ATTVAL_REQUIRED)) {
attValueAndUseType |= XMLAttributeDecl.USE_TYPE_REQUIRED;
isRequired = true;
}
else {
reportGenericSchemaError("An attribute cannot declare \"" +
SchemaSymbols.ATT_USE + "\" as \"" + useStr + "\"" + errorContext);
}
if(defaultAtt != null && fixedAtt != null) {
reportGenericSchemaError("src-attribute.1: \"" + SchemaSymbols.ATT_DEFAULT +
"\" and \"" + SchemaSymbols.ATT_FIXED +
"\" cannot be both present" + errorContext);
}
else if(defaultAtt != null && !isOptional) {
reportGenericSchemaError("src-attribute.2: If both \"" + SchemaSymbols.ATT_DEFAULT +
"\" and \"" + SchemaSymbols.ATT_USE + "\" " +
"are present for an attribute declaration, \"" +
SchemaSymbols.ATT_USE + "\" can only be \"" +
SchemaSymbols.ATTVAL_OPTIONAL + "\", not \"" + useStr + "\"." + errorContext);
}
if(!isAttrTopLevel) {
if((refAtt == null) == (attNameAtt == null)) {
reportGenericSchemaError("src-attribute.3.1: When the attribute's parent is not <schema> , one of \"" +
SchemaSymbols.ATT_REF + "\" and \"" + SchemaSymbols.ATT_NAME +
"\" should be declared, but not both."+ errorContext);
return -1;
}
else if((refAtt != null) && (simpleTypeChild != null || formAtt != null || datatypeAtt != null)) {
reportGenericSchemaError("src-attribute.3.2: When the attribute's parent is not <schema> and \"" +
SchemaSymbols.ATT_REF + "\" is present, " +
"all of <" + SchemaSymbols.ELT_SIMPLETYPE + ">, " +
SchemaSymbols.ATT_FORM + " and " + SchemaSymbols.ATT_TYPE +
" must be absent."+ errorContext);
}
}
if(datatypeAtt != null && simpleTypeChild != null) {
reportGenericSchemaError("src-attribute.4: \"" + SchemaSymbols.ATT_TYPE + "\" and <" +
SchemaSymbols.ELT_SIMPLETYPE + "> cannot both be present"+ errorContext);
}
////// Check W3C's PR-Structure 3.2.2
// --- XML Representation of Attribute Declaration Schema Components
// check case-dependent attribute declaration schema components
if (isAttrTopLevel) {
//// global attributes
// set name component
attName = fStringPool.addSymbol(attNameStr);
if(fTargetNSURIString.length() == 0) {
uriIndex = StringPool.EMPTY_STRING;
}
else {
uriIndex = fTargetNSURI;
}
// attQName = new QName(-1,attName,attName,uriIndex);
// Above line replaced by following 2 to work around a JIT problem.
attQName = new QName();
attQName.setValues(-1,attName,attName,uriIndex);
}
else if(refAtt == null) {
//// local attributes
// set name component
attName = fStringPool.addSymbol(attNameStr);
if((formStr.length() > 0 && formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)) ||
(formStr.length() == 0 && fAttributeDefaultQualified)) {
uriIndex = fTargetNSURI;
}
else {
uriIndex = StringPool.EMPTY_STRING;
}
// attQName = new QName(-1,attName,attName,uriIndex);
// Above line replaced by following 2 to work around a JIT problem.
attQName = new QName();
attQName.setValues(-1,attName,attName,uriIndex);
}
else {
//// locally referenced global attributes
String prefix;
int colonptr = refStr.indexOf(":");
if ( colonptr > 0) {
prefix = refStr.substring(0,colonptr);
localpart = refStr.substring(colonptr+1);
}
else {
prefix = "";
localpart = refStr;
}
String uriStr = resolvePrefixToURI(prefix);
if (!uriStr.equals(fTargetNSURIString)) {
addAttributeDeclFromAnotherSchema(localpart, uriStr, typeInfo);
return 0;
}
Element referredAttribute = getTopLevelComponentByName(SchemaSymbols.ELT_ATTRIBUTE,localpart);
if (referredAttribute != null) {
// don't need to traverse ref'd attribute if we're global; just make sure it's there...
traverseAttributeDecl(referredAttribute, typeInfo, true);
Attr referFixedAttr = referredAttribute.getAttributeNode(SchemaSymbols.ATT_FIXED);
String referFixed = referFixedAttr == null ? null : referFixedAttr.getValue();
if (referFixed != null && (defaultAtt != null || fixedAtt != null && !referFixed.equals(fixedStr))) {
reportGenericSchemaError("au-props-correct.2: If the {attribute declaration} has a fixed {value constraint}, then if the attribute use itself has a {value constraint}, it must also be fixed and its value must match that of the {attribute declaration}'s {value constraint}" + errorContext);
}
// this nasty hack needed to ``override'' the
// global attribute with "use" and "fixed" on the ref'ing attribute
if(!isOptional || fixedStr.length() > 0) {
int referredAttName = fStringPool.addSymbol(referredAttribute.getAttribute(SchemaSymbols.ATT_NAME));
uriIndex = StringPool.EMPTY_STRING;
if ( fTargetNSURIString.length() > 0) {
uriIndex = fTargetNSURI;
}
QName referredAttQName = new QName(-1,referredAttName,referredAttName,uriIndex);
int tempIndex = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, referredAttQName);
XMLAttributeDecl referredAttrDecl = new XMLAttributeDecl();
fSchemaGrammar.getAttributeDecl(tempIndex, referredAttrDecl);
boolean updated = false;
int useDigits = XMLAttributeDecl.USE_TYPE_OPTIONAL |
XMLAttributeDecl.USE_TYPE_PROHIBITED |
XMLAttributeDecl.USE_TYPE_REQUIRED;
int valueDigits = XMLAttributeDecl.VALUE_CONSTRAINT_DEFAULT |
XMLAttributeDecl.VALUE_CONSTRAINT_FIXED;
if(!isOptional &&
(referredAttrDecl.defaultType & useDigits) !=
(attValueAndUseType & useDigits))
{
if(referredAttrDecl.defaultType != XMLAttributeDecl.USE_TYPE_PROHIBITED) {
referredAttrDecl.defaultType |= useDigits;
referredAttrDecl.defaultType ^= useDigits; // clear the use
referredAttrDecl.defaultType |= (attValueAndUseType & useDigits);
updated = true;
}
}
if(fixedStr.length() > 0) {
if((referredAttrDecl.defaultType & XMLAttributeDecl.VALUE_CONSTRAINT_FIXED) == 0) {
referredAttrDecl.defaultType |= valueDigits;
referredAttrDecl.defaultType ^= valueDigits; // clear the value
referredAttrDecl.defaultType |= XMLAttributeDecl.VALUE_CONSTRAINT_FIXED;
referredAttrDecl.defaultValue = fixedStr;
updated = true;
}
}
if(updated) {
fSchemaGrammar.setAttributeDecl(typeInfo.templateElementIndex, tempIndex, referredAttrDecl);
}
}
}
else if (fAttributeDeclRegistry.get(localpart) != null) {
addAttributeDeclFromAnotherSchema(localpart, uriStr, typeInfo);
}
else {
// REVISIT: Localize
reportGenericSchemaError ( "Couldn't find top level attribute " + refStr + errorContext);
}
return 0;
}
if (uriIndex == fXsiURI) {
reportGenericSchemaError("no-xsi: The {target namespace} of an attribute declaration must not match " + SchemaSymbols.URI_XSI + errorContext);
}
// validation of attribute type is same for each case of declaration
if (simpleTypeChild != null) {
attType = XMLAttributeDecl.TYPE_SIMPLE;
dataTypeSymbol = traverseSimpleTypeDecl(simpleTypeChild);
localpart = fStringPool.toString(dataTypeSymbol);
dv = fDatatypeRegistry.getDatatypeValidator(localpart);
}
else if (datatypeStr.length() != 0) {
dataTypeSymbol = fStringPool.addSymbol(datatypeStr);
String prefix;
int colonptr = datatypeStr.indexOf(":");
if ( colonptr > 0) {
prefix = datatypeStr.substring(0,colonptr);
localpart = datatypeStr.substring(colonptr+1);
}
else {
prefix = "";
localpart = datatypeStr;
}
String typeURI = resolvePrefixToURI(prefix);
if ( typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
|| typeURI.length()==0) {
dv = getDatatypeValidator("", localpart);
if (localpart.equals("ID")) {
attType = XMLAttributeDecl.TYPE_ID;
} else if (localpart.equals("IDREF")) {
attType = XMLAttributeDecl.TYPE_IDREF;
} else if (localpart.equals("IDREFS")) {
attType = XMLAttributeDecl.TYPE_IDREF;
attIsList = true;
} else if (localpart.equals("ENTITY")) {
attType = XMLAttributeDecl.TYPE_ENTITY;
} else if (localpart.equals("ENTITIES")) {
attType = XMLAttributeDecl.TYPE_ENTITY;
attIsList = true;
} else if (localpart.equals("NMTOKEN")) {
attType = XMLAttributeDecl.TYPE_NMTOKEN;
} else if (localpart.equals("NMTOKENS")) {
attType = XMLAttributeDecl.TYPE_NMTOKEN;
attIsList = true;
} else if (localpart.equals(SchemaSymbols.ELT_NOTATION)) {
attType = XMLAttributeDecl.TYPE_NOTATION;
}
else {
attType = XMLAttributeDecl.TYPE_SIMPLE;
if (dv == null && typeURI.length() == 0) {
Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (topleveltype != null) {
traverseSimpleTypeDecl( topleveltype );
dv = getDatatypeValidator(typeURI, localpart);
}else if (!referredTo) {
// REVISIT: Localize
reportGenericSchemaError("simpleType not found : " + "("+typeURI+":"+localpart+")"+ errorContext);
}
}
}
} else { //isn't of the schema for schemas namespace...
attType = XMLAttributeDecl.TYPE_SIMPLE;
// check if the type is from the same Schema
dv = getDatatypeValidator(typeURI, localpart);
if (dv == null && typeURI.equals(fTargetNSURIString) ) {
Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (topleveltype != null) {
traverseSimpleTypeDecl( topleveltype );
dv = getDatatypeValidator(typeURI, localpart);
}else if (!referredTo) {
// REVISIT: Localize
reportGenericSchemaError("simpleType not found : " + "("+typeURI+":"+ localpart+")"+ errorContext);
}
}
}
}
else {
attType = XMLAttributeDecl.TYPE_SIMPLE;
localpart = "string";
dataTypeSymbol = fStringPool.addSymbol(localpart);
dv = fDatatypeRegistry.getDatatypeValidator(localpart);
} // if(...Type)
// validation of data constraint is same for each case of declaration
if(defaultStr.length() > 0) {
attValueAndUseType |= XMLAttributeDecl.VALUE_CONSTRAINT_DEFAULT;
attValueConstraint = fStringPool.addString(defaultStr);
}
else if(fixedStr.length() > 0) {
attValueAndUseType |= XMLAttributeDecl.VALUE_CONSTRAINT_FIXED;
attValueConstraint = fStringPool.addString(fixedStr);
}
////// Check W3C's PR-Structure 3.2.6
// --- Constraints on Attribute Declaration Schema Components
// check default value is valid for the datatype.
if (attType == XMLAttributeDecl.TYPE_SIMPLE && attValueConstraint != -1) {
try {
if (dv != null) {
if(defaultStr.length() > 0) {
//REVISIT
dv.validate(defaultStr, null);
}
else {
dv.validate(fixedStr, null);
}
}
else if (!referredTo)
reportSchemaError(SchemaMessageProvider.NoValidatorFor,
new Object [] { datatypeStr });
} catch (InvalidDatatypeValueException idve) {
if (!referredTo)
reportSchemaError(SchemaMessageProvider.IncorrectDefaultType,
new Object [] { attrDecl.getAttribute(SchemaSymbols.ATT_NAME), idve.getMessage() }); //a-props-correct.2
} catch (Exception e) {
e.printStackTrace();
System.out.println("Internal error in attribute datatype validation");
}
}
// check the coexistence of ID and value constraint
dvIsDerivedFromID =
((dv != null) && dv instanceof IDDatatypeValidator);
if (dvIsDerivedFromID && attValueConstraint != -1)
{
reportGenericSchemaError("a-props-correct.3: If type definition is or is derived from ID ," +
"there must not be a value constraint" + errorContext);
}
if (attNameStr.equals("xmlns")) {
reportGenericSchemaError("no-xmlns: The {name} of an attribute declaration must not match 'xmlns'" + errorContext);
}
////// every contraints were matched. Now register the attribute declaration
//put the top-levels in the attribute decl registry.
if (isAttrTopLevel) {
fTempAttributeDecl.datatypeValidator = dv;
fTempAttributeDecl.name.setValues(attQName);
fTempAttributeDecl.type = attType;
fTempAttributeDecl.defaultType = attValueAndUseType;
fTempAttributeDecl.list = attIsList;
if (attValueConstraint != -1 ) {
fTempAttributeDecl.defaultValue = fStringPool.toString(attValueConstraint);
}
fAttributeDeclRegistry.put(attNameStr, new XMLAttributeDecl(fTempAttributeDecl));
}
// add attribute to attr decl pool in fSchemaGrammar,
if (typeInfo != null) {
// check that there aren't duplicate attributes
int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, attQName);
if (temp > -1) {
reportGenericSchemaError("ct-props-correct.4: Duplicate attribute " +
fStringPool.toString(attQName.rawname) + " in type definition");
}
// check that there aren't multiple attributes with type derived from ID
if (dvIsDerivedFromID) {
if (typeInfo.containsAttrTypeID()) {
reportGenericSchemaError("ct-props-correct.5: More than one attribute derived from type ID cannot appear in the same complex type definition.");
}
typeInfo.setContainsAttrTypeID();
}
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
attQName, attType,
dataTypeSymbol, attValueAndUseType,
fStringPool.toString( attValueConstraint), dv, attIsList);
}
return 0;
} // end of method traverseAttribute
private int addAttributeDeclFromAnotherSchema( String name, String uriStr, ComplexTypeInfo typeInfo) throws Exception {
SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr);
if (uriStr == null || ! (aGrammar instanceof SchemaGrammar) ) {
// REVISIT: Localize
reportGenericSchemaError( "no attribute named \"" + name
+ "\" was defined in schema : " + uriStr);
return -1;
}
Hashtable attrRegistry = aGrammar.getAttributeDeclRegistry();
if (attrRegistry == null) {
// REVISIT: Localize
reportGenericSchemaError( "no attribute named \"" + name
+ "\" was defined in schema : " + uriStr);
return -1;
}
XMLAttributeDecl tempAttrDecl = (XMLAttributeDecl) attrRegistry.get(name);
if (tempAttrDecl == null) {
// REVISIT: Localize
reportGenericSchemaError( "no attribute named \"" + name
+ "\" was defined in schema : " + uriStr);
return -1;
}
if (typeInfo!= null) {
// check that there aren't duplicate attributes
int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, tempAttrDecl.name);
if (temp > -1) {
reportGenericSchemaError("ct-props-correct.4: Duplicate attribute " +
fStringPool.toString(tempAttrDecl.name.rawname) + " in type definition");
}
// check that there aren't multiple attributes with type derived from ID
if (tempAttrDecl.datatypeValidator != null &&
tempAttrDecl.datatypeValidator instanceof IDDatatypeValidator) {
if (typeInfo.containsAttrTypeID()) {
reportGenericSchemaError("ct-props-correct.5: More than one attribute derived from type ID cannot appear in the same complex type definition");
}
typeInfo.setContainsAttrTypeID();
}
fSchemaGrammar.addAttDef( typeInfo.templateElementIndex,
tempAttrDecl.name, tempAttrDecl.type,
-1, tempAttrDecl.defaultType,
tempAttrDecl.defaultValue,
tempAttrDecl.datatypeValidator,
tempAttrDecl.list);
}
return 0;
}
/*
*
* <attributeGroup
* id = ID
* name = NCName
* ref = QName>
* Content: (annotation?, (attribute|attributeGroup)*, anyAttribute?)
* </>
*
*/
private int traverseAttributeGroupDecl( Element attrGrpDecl, ComplexTypeInfo typeInfo, Vector anyAttDecls ) throws Exception {
// General Attribute Checking
int scope = isTopLevel(attrGrpDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(attrGrpDecl, scope);
// attributeGroup name
String attGrpNameStr = attrGrpDecl.getAttribute(SchemaSymbols.ATT_NAME);
int attGrpName = fStringPool.addSymbol(attGrpNameStr);
String ref = attrGrpDecl.getAttribute(SchemaSymbols.ATT_REF);
Element child = checkContent( attrGrpDecl, XUtil.getFirstChildElement(attrGrpDecl), true );
if (!ref.equals("")) {
if(isTopLevel(attrGrpDecl))
// REVISIT: localize
reportGenericSchemaError ( "An attributeGroup with \"ref\" present must not have <schema> or <redefine> as its parent");
if(!attGrpNameStr.equals(""))
// REVISIT: localize
reportGenericSchemaError ( "attributeGroup " + attGrpNameStr + " cannot refer to another attributeGroup, but it refers to " + ref);
if (XUtil.getFirstChildElement(attrGrpDecl) != null ||
attrGrpDecl.getNodeValue() != null)
// REVISIT: localize
reportGenericSchemaError ( "An attributeGroup with \"ref\" present must be empty");
String prefix = "";
String localpart = ref;
int colonptr = ref.indexOf(":");
if ( colonptr > 0) {
prefix = ref.substring(0,colonptr);
localpart = ref.substring(colonptr+1);
}
String uriStr = resolvePrefixToURI(prefix);
if (!uriStr.equals(fTargetNSURIString)) {
traverseAttributeGroupDeclFromAnotherSchema(localpart, uriStr, typeInfo, anyAttDecls);
return -1;
// TO DO
// REVISIST: different NS, not supported yet.
// REVISIT: Localize
//reportGenericSchemaError("Feature not supported: see an attribute from different NS");
} else {
Element parent = (Element)attrGrpDecl.getParentNode();
if (parent.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) &&
parent.getAttribute(SchemaSymbols.ATT_NAME).equals(localpart)) {
if (!((Element)parent.getParentNode()).getLocalName().equals(SchemaSymbols.ELT_REDEFINE)) {
reportGenericSchemaError("src-attribute_group.3: Circular group reference is disallowed outside <redefine> -- "+ref);
}
return -1;
}
}
if(typeInfo != null) {
// only do this if we're traversing because we were ref'd here; when we come
// upon this decl by itself we're just validating.
Element referredAttrGrp = getTopLevelComponentByName(SchemaSymbols.ELT_ATTRIBUTEGROUP,localpart);
if (referredAttrGrp != null) {
traverseAttributeGroupDecl(referredAttrGrp, typeInfo, anyAttDecls);
}
else {
// REVISIT: Localize
reportGenericSchemaError ( "Couldn't find top level attributeGroup " + ref);
}
return -1;
}
} else if (attGrpNameStr.equals(""))
// REVISIT: localize
reportGenericSchemaError ( "an attributeGroup must have a name or a ref attribute present");
for (;
child != null ; child = XUtil.getNextSiblingElement(child)) {
if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTE) ){
traverseAttributeDecl(child, typeInfo, false);
}
else if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) {
// if(typeInfo != null)
// only do this if we're traversing because we were ref'd here; when we come
// upon this decl by itself we're just validating.
traverseAttributeGroupDecl(child, typeInfo,anyAttDecls);
}
else
break;
}
if (child != null) {
if ( child.getLocalName().equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) {
if (anyAttDecls != null) {
anyAttDecls.addElement(traverseAnyAttribute(child));
}
if (XUtil.getNextSiblingElement(child) != null)
// REVISIT: localize
reportGenericSchemaError ( "src-attribute_group.0: The content of an attributeGroup declaration must match (annotation?, ((attribute | attributeGroup)*, anyAttribute?))");
return -1;
}
else
// REVISIT: localize
reportGenericSchemaError ( "src-attribute_group.0: The content of an attributeGroup declaration must match (annotation?, ((attribute | attributeGroup)*, anyAttribute?))");
}
return -1;
} // end of method traverseAttributeGroup
private int traverseAttributeGroupDeclFromAnotherSchema( String attGrpName , String uriStr,
ComplexTypeInfo typeInfo,
Vector anyAttDecls ) throws Exception {
SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr);
if (uriStr == null || aGrammar == null || ! (aGrammar instanceof SchemaGrammar) ) {
// REVISIT: Localize
reportGenericSchemaError("!!Schema not found in #traverseAttributeGroupDeclFromAnotherSchema, schema uri : " + uriStr);
return -1;
}
// attribute name
Element attGrpDecl = (Element) aGrammar.topLevelAttrGrpDecls.get((Object)attGrpName);
if (attGrpDecl == null) {
// REVISIT: Localize
reportGenericSchemaError( "no attribute group named \"" + attGrpName
+ "\" was defined in schema : " + uriStr);
return -1;
}
NamespacesScope saveNSMapping = fNamespacesScope;
int saveTargetNSUri = fTargetNSURI;
fTargetNSURI = fStringPool.addSymbol(aGrammar.getTargetNamespaceURI());
fNamespacesScope = aGrammar.getNamespacesScope();
// attribute type
int attType = -1;
int enumeration = -1;
Element child = checkContent(attGrpDecl, XUtil.getFirstChildElement(attGrpDecl), true);
for (;
child != null ; child = XUtil.getNextSiblingElement(child)) {
//child attribute couldn't be a top-level attribute DEFINITION,
if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTE) ){
String childAttName = child.getAttribute(SchemaSymbols.ATT_NAME);
if ( childAttName.length() > 0 ) {
Hashtable attDeclRegistry = aGrammar.getAttributeDeclRegistry();
if (attDeclRegistry != null) {
if (attDeclRegistry.get((Object)childAttName) != null ){
addAttributeDeclFromAnotherSchema(childAttName, uriStr, typeInfo);
return -1;
}
}
}
else
traverseAttributeDecl(child, typeInfo, false);
}
else if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) {
traverseAttributeGroupDecl(child, typeInfo, anyAttDecls);
}
else if ( child.getLocalName().equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) {
anyAttDecls.addElement(traverseAnyAttribute(child));
break;
}
else {
// REVISIT: Localize
reportGenericSchemaError("Invalid content for attributeGroup");
}
}
fNamespacesScope = saveNSMapping;
fTargetNSURI = saveTargetNSUri;
if(child != null) {
// REVISIT: Localize
reportGenericSchemaError("Invalid content for attributeGroup");
}
return -1;
} // end of method traverseAttributeGroupFromAnotherSchema
// This simple method takes an attribute declaration as a parameter and
// returns null if there is no simpleType defined or the simpleType
// declaration if one exists. It also throws an error if more than one
// <annotation> or <simpleType> group is present.
private Element findAttributeSimpleType(Element attrDecl) throws Exception {
Element child = checkContent(attrDecl, XUtil.getFirstChildElement(attrDecl), true);
// if there is only a annotatoin, then no simpleType
if (child == null)
return null;
// if the current one is not simpleType, or there are more elements,
// report an error
if (!child.getLocalName().equals(SchemaSymbols.ELT_SIMPLETYPE) ||
XUtil.getNextSiblingElement(child) != null)
//REVISIT: localize
reportGenericSchemaError("src-attribute.0: the content must match (annotation?, (simpleType?)) -- attribute declaration '"+
attrDecl.getAttribute(SchemaSymbols.ATT_NAME)+"'");
if (child.getLocalName().equals(SchemaSymbols.ELT_SIMPLETYPE))
return child;
return null;
} // end findAttributeSimpleType
/**
* Traverse element declaration:
* <element
* abstract = boolean
* block = #all or (possibly empty) subset of {substitutionGroup, extension, restriction}
* default = string
* substitutionGroup = QName
* final = #all or (possibly empty) subset of {extension, restriction}
* fixed = string
* form = qualified | unqualified
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* name = NCName
* nillable = boolean
* ref = QName
* type = QName>
* Content: (annotation? , (simpleType | complexType)? , (unique | key | keyref)*)
* </element>
*
*
* The following are identity-constraint definitions
* <unique
* id = ID
* name = NCName>
* Content: (annotation? , (selector , field+))
* </unique>
*
* <key
* id = ID
* name = NCName>
* Content: (annotation? , (selector , field+))
* </key>
*
* <keyref
* id = ID
* name = NCName
* refer = QName>
* Content: (annotation? , (selector , field+))
* </keyref>
*
* <selector>
* Content: XPathExprApprox : An XPath expression
* </selector>
*
* <field>
* Content: XPathExprApprox : An XPath expression
* </field>
*
*
* @param elementDecl
* @return
* @exception Exception
*/
private QName traverseElementDecl(Element elementDecl) throws Exception {
// General Attribute Checking
int scope = isTopLevel(elementDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(elementDecl, scope);
int contentSpecType = -1;
int contentSpecNodeIndex = -1;
int typeNameIndex = -1;
int scopeDefined = -2; //signal a error if -2 gets gets through
//cause scope can never be -2.
DatatypeValidator dv = null;
String abstractStr = elementDecl.getAttribute(SchemaSymbols.ATT_ABSTRACT);
String blockStr = elementDecl.getAttribute(SchemaSymbols.ATT_BLOCK);
String defaultStr = elementDecl.getAttribute(SchemaSymbols.ATT_DEFAULT);
String finalStr = elementDecl.getAttribute(SchemaSymbols.ATT_FINAL);
String fixedStr = elementDecl.getAttribute(SchemaSymbols.ATT_FIXED);
String formStr = elementDecl.getAttribute(SchemaSymbols.ATT_FORM);
String maxOccursStr = elementDecl.getAttribute(SchemaSymbols.ATT_MAXOCCURS);
String minOccursStr = elementDecl.getAttribute(SchemaSymbols.ATT_MINOCCURS);
String nameStr = elementDecl.getAttribute(SchemaSymbols.ATT_NAME);
String nillableStr = elementDecl.getAttribute(SchemaSymbols.ATT_NILLABLE);
String refStr = elementDecl.getAttribute(SchemaSymbols.ATT_REF);
String substitutionGroupStr = elementDecl.getAttribute(SchemaSymbols.ATT_SUBSTITUTIONGROUP);
String typeStr = elementDecl.getAttribute(SchemaSymbols.ATT_TYPE);
checkEnumerationRequiredNotation(nameStr, typeStr);
if ( DEBUGGING )
System.out.println("traversing element decl : " + nameStr );
Attr abstractAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_ABSTRACT);
Attr blockAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_BLOCK);
Attr defaultAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_DEFAULT);
Attr finalAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FINAL);
Attr fixedAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FIXED);
Attr formAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FORM);
Attr maxOccursAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_MAXOCCURS);
Attr minOccursAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_MINOCCURS);
Attr nameAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_NAME);
Attr nillableAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_NILLABLE);
Attr refAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_REF);
Attr substitutionGroupAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_SUBSTITUTIONGROUP);
Attr typeAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_TYPE);
if(defaultAtt != null && fixedAtt != null)
// REVISIT: localize
reportGenericSchemaError("src-element.1: an element cannot have both \"fixed\" and \"default\" present at the same time");
String fromAnotherSchema = null;
if (isTopLevel(elementDecl)) {
if(nameAtt == null)
// REVISIT: localize
reportGenericSchemaError("globally-declared element must have a name");
else if (refAtt != null)
// REVISIT: localize
reportGenericSchemaError("globally-declared element " + nameStr + " cannot have a ref attribute");
int nameIndex = fStringPool.addSymbol(nameStr);
int eltKey = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, nameIndex,TOP_LEVEL_SCOPE);
if (eltKey > -1 ) {
return new QName(-1,nameIndex,nameIndex,fTargetNSURI);
}
}
// parse out 'block', 'final', 'nillable', 'abstract'
if (blockAtt == null)
blockStr = null;
int blockSet = parseBlockSet(blockStr);
if( (blockStr != null) && !blockStr.equals("") &&
(!blockStr.equals(SchemaSymbols.ATTVAL_POUNDALL) &&
(((blockSet & SchemaSymbols.RESTRICTION) == 0) &&
(((blockSet & SchemaSymbols.EXTENSION) == 0) &&
((blockSet & SchemaSymbols.SUBSTITUTION) == 0)))))
reportGenericSchemaError("The values of the 'block' attribute of an element must be either #all or a list of 'substitution', 'restriction' and 'extension'; " + blockStr + " was found");
if (finalAtt == null)
finalStr = null;
int finalSet = parseFinalSet(finalStr);
if( (finalStr != null) && !finalStr.equals("") &&
(!finalStr.equals(SchemaSymbols.ATTVAL_POUNDALL) &&
(((finalSet & SchemaSymbols.RESTRICTION) == 0) &&
((finalSet & SchemaSymbols.EXTENSION) == 0))))
reportGenericSchemaError("The values of the 'final' attribute of an element must be either #all or a list of 'restriction' and 'extension'; " + finalStr + " was found");
boolean isNillable = nillableStr.equals(SchemaSymbols.ATTVAL_TRUE)? true:false;
boolean isAbstract = abstractStr.equals(SchemaSymbols.ATTVAL_TRUE)? true:false;
int elementMiscFlags = 0;
if (isNillable) {
elementMiscFlags += SchemaSymbols.NILLABLE;
}
if (isAbstract) {
elementMiscFlags += SchemaSymbols.ABSTRACT;
}
// make the property of the element's value being fixed also appear in elementMiscFlags
if(fixedAtt != null)
elementMiscFlags += SchemaSymbols.FIXED;
//if this is a reference to a global element
if (refAtt != null) {
//REVISIT top level check for ref
if (abstractAtt != null || blockAtt != null || defaultAtt != null ||
finalAtt != null || fixedAtt != null || formAtt != null ||
nillableAtt != null || substitutionGroupAtt != null || typeAtt != null)
reportSchemaError(SchemaMessageProvider.BadAttWithRef, null); //src-element.2.2
if (nameAtt != null)
// REVISIT: Localize
reportGenericSchemaError("src-element.2.1: element " + nameStr + " cannot also have a ref attribute");
Element child = XUtil.getFirstChildElement(elementDecl);
if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
if (XUtil.getNextSiblingElement(child) != null)
reportSchemaError(SchemaMessageProvider.NoContentForRef, null);
else
traverseAnnotationDecl(child);
}
else if (child != null)
reportSchemaError(SchemaMessageProvider.NoContentForRef, null);
String prefix = "";
String localpart = refStr;
int colonptr = refStr.indexOf(":");
if ( colonptr > 0) {
prefix = refStr.substring(0,colonptr);
localpart = refStr.substring(colonptr+1);
}
int localpartIndex = fStringPool.addSymbol(localpart);
String uriString = resolvePrefixToURI(prefix);
QName eltName = new QName(prefix != null ? fStringPool.addSymbol(prefix) : -1,
localpartIndex,
fStringPool.addSymbol(refStr),
uriString != null ? fStringPool.addSymbol(uriString) : StringPool.EMPTY_STRING);
//if from another schema, just return the element QName
if (! uriString.equals(fTargetNSURIString) ) {
return eltName;
}
int elementIndex = fSchemaGrammar.getElementDeclIndex(eltName, TOP_LEVEL_SCOPE);
//if not found, traverse the top level element that if referenced
if (elementIndex == -1 ) {
Element targetElement = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT,localpart);
if (targetElement == null ) {
// REVISIT: Localize
reportGenericSchemaError("Element " + localpart + " not found in the Schema");
//REVISIT, for now, the QName anyway
return eltName;
//return new QName(-1,fStringPool.addSymbol(localpart), -1, fStringPool.addSymbol(uriString));
}
else {
// do nothing here, other wise would cause infinite loop for
// <element name="recur"><complexType><element ref="recur"> ...
//eltName= traverseElementDecl(targetElement);
}
}
return eltName;
} else if (nameAtt == null)
// REVISIT: Localize
reportGenericSchemaError("src-element.2.1: a local element must have a name or a ref attribute present");
// Handle the substitutionGroup
Element substitutionGroupElementDecl = null;
int substitutionGroupElementDeclIndex = -1;
boolean noErrorSoFar = true;
String substitutionGroupUri = null;
String substitutionGroupLocalpart = null;
String substitutionGroupFullName = null;
ComplexTypeInfo substitutionGroupEltTypeInfo = null;
DatatypeValidator substitutionGroupEltDV = null;
SchemaGrammar subGrammar = fSchemaGrammar;
if ( substitutionGroupStr.length() > 0 ) {
if(refAtt != null)
// REVISIT: Localize
reportGenericSchemaError("a local element cannot have a substitutionGroup");
substitutionGroupUri = resolvePrefixToURI(getPrefix(substitutionGroupStr));
substitutionGroupLocalpart = getLocalPart(substitutionGroupStr);
substitutionGroupFullName = substitutionGroupUri+","+substitutionGroupLocalpart;
if ( !substitutionGroupUri.equals(fTargetNSURIString) ) {
Grammar grammar = fGrammarResolver.getGrammar(substitutionGroupUri);
if (grammar != null && grammar instanceof SchemaGrammar) {
subGrammar = (SchemaGrammar) grammar;
substitutionGroupElementDeclIndex = subGrammar.getElementDeclIndex(fStringPool.addSymbol(substitutionGroupUri),
fStringPool.addSymbol(substitutionGroupLocalpart),
TOP_LEVEL_SCOPE);
if (substitutionGroupElementDeclIndex<=-1) {
// REVISIT: localize
noErrorSoFar = false;
reportGenericSchemaError("couldn't find substitutionGroup " + substitutionGroupLocalpart + " referenced by element " + nameStr
+ " in the SchemaGrammar "+substitutionGroupUri);
} else {
substitutionGroupEltTypeInfo = getElementDeclTypeInfoFromNS(substitutionGroupUri, substitutionGroupLocalpart);
if (substitutionGroupEltTypeInfo == null) {
substitutionGroupEltDV = getElementDeclTypeValidatorFromNS(substitutionGroupUri, substitutionGroupLocalpart);
if (substitutionGroupEltDV == null) {
//TO DO: report error here;
noErrorSoFar = false;
reportGenericSchemaError("Could not find type for element '" +substitutionGroupLocalpart
+ "' in schema '" + substitutionGroupUri+"'");
}
}
}
} else {
// REVISIT: locallize
noErrorSoFar = false;
reportGenericSchemaError("couldn't find a schema grammar with target namespace " + substitutionGroupUri);
}
}
else {
substitutionGroupElementDecl = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT, substitutionGroupLocalpart);
if (substitutionGroupElementDecl == null) {
substitutionGroupElementDeclIndex =
fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE);
if ( substitutionGroupElementDeclIndex == -1) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("unable to locate substitutionGroup affiliation element "
+substitutionGroupStr
+" in element declaration "
+nameStr);
}
}
else {
substitutionGroupElementDeclIndex =
fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE);
if ( substitutionGroupElementDeclIndex == -1) {
traverseElementDecl(substitutionGroupElementDecl);
substitutionGroupElementDeclIndex =
fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE);
}
}
if (substitutionGroupElementDeclIndex != -1) {
substitutionGroupEltTypeInfo = fSchemaGrammar.getElementComplexTypeInfo( substitutionGroupElementDeclIndex );
if (substitutionGroupEltTypeInfo == null) {
fSchemaGrammar.getElementDecl(substitutionGroupElementDeclIndex, fTempElementDecl);
substitutionGroupEltDV = fTempElementDecl.datatypeValidator;
if (substitutionGroupEltDV == null) {
//TO DO: report error here;
noErrorSoFar = false;
reportGenericSchemaError("Could not find type for element '" +substitutionGroupLocalpart
+ "' in schema '" + substitutionGroupUri+"'");
}
}
}
}
}
//
// resolving the type for this element right here
//
ComplexTypeInfo typeInfo = null;
// element has a single child element, either a datatype or a type, null if primitive
Element child = XUtil.getFirstChildElement(elementDecl);
if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
traverseAnnotationDecl(child);
child = XUtil.getNextSiblingElement(child);
}
if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION))
// REVISIT: Localize
reportGenericSchemaError("element declarations can contain at most one annotation Element Information Item");
boolean haveAnonType = false;
// Handle Anonymous type if there is one
if (child != null) {
String childName = child.getLocalName();
if (childName.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("anonymous complexType in element '" + nameStr +"' has a name attribute");
}
else {
// Determine what the type name will be
String anonTypeName = genAnonTypeName(child);
if (fCurrentTypeNameStack.search((Object)anonTypeName) > - 1) {
// A recursing element using an anonymous type
int uriInd = StringPool.EMPTY_STRING;
if ( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)||
fElementDefaultQualified) {
uriInd = fTargetNSURI;
}
int nameIndex = fStringPool.addSymbol(nameStr);
QName tempQName = new QName(-1, nameIndex, nameIndex, uriInd);
int eltIndex = fSchemaGrammar.addElementDecl(tempQName,
fCurrentScope, fCurrentScope, -1, -1, -1, null);
fElementRecurseComplex.addElement(new ElementInfo(eltIndex,anonTypeName));
return tempQName;
}
else {
typeNameIndex = traverseComplexTypeDecl(child);
if (typeNameIndex != -1 ) {
typeInfo = (ComplexTypeInfo)
fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex));
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("traverse complexType error in element '" + nameStr +"'");
}
}
}
haveAnonType = true;
child = XUtil.getNextSiblingElement(child);
}
else if (childName.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("anonymous simpleType in element '" + nameStr +"' has a name attribute");
}
else
typeNameIndex = traverseSimpleTypeDecl(child);
if (typeNameIndex != -1) {
dv = fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex));
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("traverse simpleType error in element '" + nameStr +"'");
}
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
haveAnonType = true;
child = XUtil.getNextSiblingElement(child);
} else if (typeAtt == null) { // "ur-typed" leaf
contentSpecType = XMLElementDecl.TYPE_ANY;
//REVISIT: is this right?
//contentSpecType = fStringPool.addSymbol("UR_TYPE");
// set occurrence count
contentSpecNodeIndex = -1;
}
// see if there's something here; it had better be key, keyref or unique.
if (child != null)
childName = child.getLocalName();
while ((child != null) && ((childName.equals(SchemaSymbols.ELT_KEY))
|| (childName.equals(SchemaSymbols.ELT_KEYREF))
|| (childName.equals(SchemaSymbols.ELT_UNIQUE)))) {
child = XUtil.getNextSiblingElement(child);
if (child != null) {
childName = child.getLocalName();
}
}
if (child != null) {
// REVISIT: Localize
noErrorSoFar = false;
reportGenericSchemaError("src-element.0: the content of an element information item must match (annotation?, (simpleType | complexType)?, (unique | key | keyref)*)");
}
}
// handle type="" here
if (haveAnonType && (typeAtt != null)) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError( "src-element.3: Element '"+ nameStr +
"' have both a type attribute and a annoymous type child" );
}
// type specified as an attribute and no child is type decl.
else if (typeAtt != null) {
String prefix = "";
String localpart = typeStr;
int colonptr = typeStr.indexOf(":");
if ( colonptr > 0) {
prefix = typeStr.substring(0,colonptr);
localpart = typeStr.substring(colonptr+1);
}
String typeURI = resolvePrefixToURI(prefix);
// check if the type is from the same Schema
if ( !typeURI.equals(fTargetNSURIString)
&& !typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& typeURI.length() != 0) { // REVISIT, only needed because of resolvePrifixToURI.
fromAnotherSchema = typeURI;
typeInfo = getTypeInfoFromNS(typeURI, localpart);
if (typeInfo == null) {
dv = getTypeValidatorFromNS(typeURI, localpart);
if (dv == null) {
//TO DO: report error here;
noErrorSoFar = false;
reportGenericSchemaError("Could not find type " +localpart
+ " in schema " + typeURI);
}
}
}
else {
typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(typeURI+","+localpart);
if (typeInfo == null) {
dv = getDatatypeValidator(typeURI, localpart);
if (dv == null )
if (typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)
&& !fTargetNSURIString.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA))
{
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("type not found : " + typeURI+":"+localpart);
}
else {
Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart);
if (topleveltype != null) {
if (fCurrentTypeNameStack.search((Object)localpart) > - 1) {
//then we found a recursive element using complexType.
// REVISIT: this will be broken when recursing happens between 2 schemas
int uriInd = StringPool.EMPTY_STRING;
if ( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)||
fElementDefaultQualified) {
uriInd = fTargetNSURI;
}
int nameIndex = fStringPool.addSymbol(nameStr);
QName tempQName = new QName(-1, nameIndex, nameIndex, uriInd);
int eltIndex = fSchemaGrammar.addElementDecl(tempQName,
fCurrentScope, fCurrentScope, -1, -1, -1, null);
fElementRecurseComplex.addElement(new ElementInfo(eltIndex,localpart));
return tempQName;
}
else {
typeNameIndex = traverseComplexTypeDecl( topleveltype, true );
typeInfo = (ComplexTypeInfo)
fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex));
}
}
else {
topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart);
if (topleveltype != null) {
typeNameIndex = traverseSimpleTypeDecl( topleveltype );
dv = getDatatypeValidator(typeURI, localpart);
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("type not found : " + typeURI+":"+localpart);
}
}
}
}
}
}
// now we need to make sure that our substitution (if any)
// is valid, now that we have all the requisite type-related info.
if(substitutionGroupStr.length() > 0) {
checkSubstitutionGroupOK(elementDecl, substitutionGroupElementDecl, noErrorSoFar, substitutionGroupElementDeclIndex, subGrammar, typeInfo, substitutionGroupEltTypeInfo, dv, substitutionGroupEltDV);
}
// this element is ur-type, check its substitutionGroup affiliation.
// if there is substitutionGroup affiliation and not type definition found for this element,
// then grab substitutionGroup affiliation's type and give it to this element
if ( noErrorSoFar && typeInfo == null && dv == null ) {
typeInfo = substitutionGroupEltTypeInfo;
dv = substitutionGroupEltDV;
}
if (typeInfo == null && dv==null) {
if (noErrorSoFar) {
// Actually this Element's type definition is ur-type;
contentSpecType = XMLElementDecl.TYPE_ANY;
// REVISIT, need to wait till we have wildcards implementation.
// ADD attribute wildcards here
}
else {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError ("untyped element : " + nameStr );
}
}
// if element belongs to a compelx type
if (typeInfo!=null) {
contentSpecNodeIndex = typeInfo.contentSpecHandle;
contentSpecType = typeInfo.contentType;
scopeDefined = typeInfo.scopeDefined;
dv = typeInfo.datatypeValidator;
}
// if element belongs to a simple type
if (dv!=null) {
contentSpecType = XMLElementDecl.TYPE_SIMPLE;
if (typeInfo == null) {
fromAnotherSchema = null; // not to switch schema in this case
}
}
// Now we can handle validation etc. of default and fixed attributes,
// since we finally have all the type information.
if(fixedAtt != null) defaultStr = fixedStr;
if(!defaultStr.equals("")) {
if(typeInfo != null &&
(typeInfo.contentType != XMLElementDecl.TYPE_MIXED_SIMPLE &&
typeInfo.contentType != XMLElementDecl.TYPE_MIXED_COMPLEX &&
typeInfo.contentType != XMLElementDecl.TYPE_SIMPLE)) {
// REVISIT: Localize
reportGenericSchemaError ("e-props-correct.2.1: element " + nameStr + " has a fixed or default value and must have a mixed or simple content model");
}
if(typeInfo != null &&
(typeInfo.contentType == XMLElementDecl.TYPE_MIXED_SIMPLE ||
typeInfo.contentType == XMLElementDecl.TYPE_MIXED_COMPLEX)) {
if (!particleEmptiable(typeInfo.contentSpecHandle))
reportGenericSchemaError ("e-props-correct.2.2.2: for element " + nameStr + ", the {content type} is mixed, then the {content type}'s particle must be emptiable");
}
try {
if(dv != null) {
dv.validate(defaultStr, null);
}
} catch (InvalidDatatypeValueException ide) {
reportGenericSchemaError ("e-props-correct.2: invalid fixed or default value '" + defaultStr + "' in element " + nameStr);
}
}
if (!defaultStr.equals("") &&
dv != null && dv instanceof IDDatatypeValidator) {
reportGenericSchemaError ("e-props-correct.4: If the {type definition} or {type definition}'s {content type} is or is derived from ID then there must not be a {value constraint} -- element " + nameStr);
}
//
// Create element decl
//
int elementNameIndex = fStringPool.addSymbol(nameStr);
int localpartIndex = elementNameIndex;
int uriIndex = StringPool.EMPTY_STRING;
int enclosingScope = fCurrentScope;
//refer to 4.3.2 in "XML Schema Part 1: Structures"
if ( isTopLevel(elementDecl)) {
uriIndex = fTargetNSURI;
enclosingScope = TOP_LEVEL_SCOPE;
}
else if ( !formStr.equals(SchemaSymbols.ATTVAL_UNQUALIFIED) &&
(( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)||
fElementDefaultQualified ))) {
uriIndex = fTargetNSURI;
}
//There can never be two elements with the same name and different type in the same scope.
int existSuchElementIndex = fSchemaGrammar.getElementDeclIndex(uriIndex, localpartIndex, enclosingScope);
if ( existSuchElementIndex > -1) {
fSchemaGrammar.getElementDecl(existSuchElementIndex, fTempElementDecl);
DatatypeValidator edv = fTempElementDecl.datatypeValidator;
ComplexTypeInfo eTypeInfo = fSchemaGrammar.getElementComplexTypeInfo(existSuchElementIndex);
if ( ((eTypeInfo != null)&&(eTypeInfo!=typeInfo))
|| ((edv != null)&&(edv != dv)) ) {
noErrorSoFar = false;
// REVISIT: Localize
reportGenericSchemaError("duplicate element decl in the same scope : " +
fStringPool.toString(localpartIndex));
}
}
QName eltQName = new QName(-1,localpartIndex,elementNameIndex,uriIndex);
// add element decl to pool
int attrListHead = -1 ;
// copy up attribute decls from type object
if (typeInfo != null) {
attrListHead = typeInfo.attlistHead;
}
int elementIndex = fSchemaGrammar.addElementDecl(eltQName, enclosingScope, scopeDefined,
contentSpecType, contentSpecNodeIndex,
attrListHead, dv);
if ( DEBUGGING ) {
/***/
System.out.println("########elementIndex:"+elementIndex+" ("+fStringPool.toString(eltQName.uri)+","
+ fStringPool.toString(eltQName.localpart) + ")"+
" eltType:"+typeStr+" contentSpecType:"+contentSpecType+
" SpecNodeIndex:"+ contentSpecNodeIndex +" enclosingScope: " +enclosingScope +
" scopeDefined: " +scopeDefined+"\n");
/***/
}
fSchemaGrammar.setElementComplexTypeInfo(elementIndex, typeInfo);
// REVISIT: should we report error if typeInfo was null?
// mark element if its type belongs to different Schema.
fSchemaGrammar.setElementFromAnotherSchemaURI(elementIndex, fromAnotherSchema);
// set BlockSet, FinalSet, Nillable and Abstract for this element decl
fSchemaGrammar.setElementDeclBlockSet(elementIndex, blockSet);
fSchemaGrammar.setElementDeclFinalSet(elementIndex, finalSet);
fSchemaGrammar.setElementDeclMiscFlags(elementIndex, elementMiscFlags);
fSchemaGrammar.setElementDefault(elementIndex, defaultStr);
// setSubstitutionGroupElementFullName
fSchemaGrammar.setElementDeclSubstitutionGroupElementFullName(elementIndex, substitutionGroupFullName);
//
// key/keyref/unique processing
//
Element ic = XUtil.getFirstChildElementNS(elementDecl, IDENTITY_CONSTRAINTS);
if (ic != null) {
Integer elementIndexObj = new Integer(elementIndex);
Vector identityConstraints = (Vector)fIdentityConstraints.get(elementIndexObj);
if (identityConstraints == null) {
identityConstraints = new Vector();
fIdentityConstraints.put(elementIndexObj, identityConstraints);
}
while (ic != null) {
if (DEBUG_IC_DATATYPES) {
System.out.println("<ICD>: adding ic for later traversal: "+ic);
}
identityConstraints.addElement(ic);
ic = XUtil.getNextSiblingElementNS(ic, IDENTITY_CONSTRAINTS);
}
}
return eltQName;
}// end of method traverseElementDecl(Element)
private void traverseIdentityNameConstraintsFor(int elementIndex,
Vector identityConstraints)
throws Exception {
// iterate over identity constraints for this element
int size = identityConstraints != null ? identityConstraints.size() : 0;
if (size > 0) {
// REVISIT: Use cached copy. -Ac
XMLElementDecl edecl = new XMLElementDecl();
fSchemaGrammar.getElementDecl(elementIndex, edecl);
for (int i = 0; i < size; i++) {
Element ic = (Element)identityConstraints.elementAt(i);
String icName = ic.getLocalName();
if ( icName.equals(SchemaSymbols.ELT_KEY) ) {
traverseKey(ic, edecl);
}
else if ( icName.equals(SchemaSymbols.ELT_UNIQUE) ) {
traverseUnique(ic, edecl);
}
fSchemaGrammar.setElementDecl(elementIndex, edecl);
} // loop over vector elements
} // if size > 0
} // traverseIdentityNameConstraints(Vector)
private void traverseIdentityRefConstraintsFor(int elementIndex,
Vector identityConstraints)
throws Exception {
// iterate over identity constraints for this element
int size = identityConstraints != null ? identityConstraints.size() : 0;
if (size > 0) {
// REVISIT: Use cached copy. -Ac
XMLElementDecl edecl = new XMLElementDecl();
fSchemaGrammar.getElementDecl(elementIndex, edecl);
for (int i = 0; i < size; i++) {
Element ic = (Element)identityConstraints.elementAt(i);
String icName = ic.getLocalName();
if ( icName.equals(SchemaSymbols.ELT_KEYREF) ) {
traverseKeyRef(ic, edecl);
}
fSchemaGrammar.setElementDecl(elementIndex, edecl);
} // loop over vector elements
} // if size > 0
} // traverseIdentityRefConstraints(Vector)
private void traverseUnique(Element uElem, XMLElementDecl eDecl)
throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(uElem, scope);
// create identity constraint
String uName = uElem.getAttribute(SchemaSymbols.ATT_NAME);
if (DEBUG_IDENTITY_CONSTRAINTS) {
System.out.println("<IC>: traverseUnique(\""+uElem.getNodeName()+"\") ["+uName+']');
}
String eName = getElementNameFor(uElem);
Unique unique = new Unique(uName, eName);
if(fIdentityConstraintNames.get(fTargetNSURIString+","+uName) != null) {
reportGenericSchemaError("More than one identity constraint named " + uName);
}
fIdentityConstraintNames.put(fTargetNSURIString+","+uName, unique);
// get selector and fields
traverseIdentityConstraint(unique, uElem);
// add to element decl
eDecl.unique.addElement(unique);
} // traverseUnique(Element,XMLElementDecl)
private void traverseKey(Element kElem, XMLElementDecl eDecl)
throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(kElem, scope);
// create identity constraint
String kName = kElem.getAttribute(SchemaSymbols.ATT_NAME);
if (DEBUG_IDENTITY_CONSTRAINTS) {
System.out.println("<IC>: traverseKey(\""+kElem.getNodeName()+"\") ["+kName+']');
}
String eName = getElementNameFor(kElem);
Key key = new Key(kName, eName);
if(fIdentityConstraintNames.get(fTargetNSURIString+","+kName) != null) {
reportGenericSchemaError("More than one identity constraint named " + kName);
}
fIdentityConstraintNames.put(fTargetNSURIString+","+kName, key);
// get selector and fields
traverseIdentityConstraint(key, kElem);
// add to element decl
eDecl.key.addElement(key);
} // traverseKey(Element,XMLElementDecl)
private void traverseKeyRef(Element krElem, XMLElementDecl eDecl)
throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(krElem, scope);
// create identity constraint
String krName = krElem.getAttribute(SchemaSymbols.ATT_NAME);
String kName = krElem.getAttribute(SchemaSymbols.ATT_REFER);
if (DEBUG_IDENTITY_CONSTRAINTS) {
System.out.println("<IC>: traverseKeyRef(\""+krElem.getNodeName()+"\") ["+krName+','+kName+']');
}
if(fIdentityConstraintNames.get(fTargetNSURIString+","+krName) != null) {
reportGenericSchemaError("More than one identity constraint named " + krName);
}
// verify that key reference "refer" attribute is valid
String prefix = "";
String localpart = kName;
int colonptr = kName.indexOf(":");
if ( colonptr > 0) {
prefix = kName.substring(0,colonptr);
localpart = kName.substring(colonptr+1);
}
String uriStr = resolvePrefixToURI(prefix);
IdentityConstraint kId = (IdentityConstraint)fIdentityConstraintNames.get(uriStr+","+localpart);
if (kId== null) {
reportSchemaError(SchemaMessageProvider.KeyRefReferNotFound,
new Object[]{krName,kName});
return;
}
String eName = getElementNameFor(krElem);
KeyRef keyRef = new KeyRef(krName, kId, eName);
// add to element decl
traverseIdentityConstraint(keyRef, krElem);
// add key reference to element decl
eDecl.keyRef.addElement(keyRef);
// store in fIdentityConstraintNames so can flag schemas in which multiple
// keyrefs with the same name are present.
fIdentityConstraintNames.put(fTargetNSURIString+","+krName, keyRef);
} // traverseKeyRef(Element,XMLElementDecl)
private void traverseIdentityConstraint(IdentityConstraint ic,
Element icElem) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(icElem, scope);
// check for <annotation> and get selector
Element sElem = XUtil.getFirstChildElement(icElem);
if(sElem == null) {
// REVISIT: localize
reportGenericSchemaError("The content of an identity constraint must match (annotation?, selector, field+)");
return;
}
sElem = checkContent( icElem, sElem, false);
// General Attribute Checking
attrValues = fGeneralAttrCheck.checkAttributes(sElem, scope);
if(!sElem.getLocalName().equals(SchemaSymbols.ELT_SELECTOR)) {
// REVISIT: localize
reportGenericSchemaError("The content of an identity constraint must match (annotation?, selector, field+)");
}
// and make sure <selector>'s content is fine:
checkContent(icElem, XUtil.getFirstChildElement(sElem), true);
String sText = sElem.getAttribute(SchemaSymbols.ATT_XPATH);
sText = sText.trim();
Selector.XPath sXpath = null;
try {
// REVISIT: Must get ruling from XML Schema working group
// regarding whether steps in the XPath must be
// fully qualified if the grammar has a target
// namespace. -Ac
// RESOLUTION: Yes.
sXpath = new Selector.XPath(sText, fStringPool,
fNamespacesScope);
Selector selector = new Selector(sXpath, ic);
if (DEBUG_IDENTITY_CONSTRAINTS) {
System.out.println("<IC>: selector: "+selector);
}
ic.setSelector(selector);
}
catch (XPathException e) {
// REVISIT: Add error message.
reportGenericSchemaError(e.getMessage());
return;
}
// get fields
Element fElem = XUtil.getNextSiblingElement(sElem);
if(fElem == null) {
// REVISIT: localize
reportGenericSchemaError("The content of an identity constraint must match (annotation?, selector, field+)");
}
while (fElem != null) {
// General Attribute Checking
attrValues = fGeneralAttrCheck.checkAttributes(fElem, scope);
if(!fElem.getLocalName().equals(SchemaSymbols.ELT_FIELD))
// REVISIT: localize
reportGenericSchemaError("The content of an identity constraint must match (annotation?, selector, field+)");
// and make sure <field>'s content is fine:
checkContent(icElem, XUtil.getFirstChildElement(fElem), true);
String fText = fElem.getAttribute(SchemaSymbols.ATT_XPATH);
fText = fText.trim();
try {
// REVISIT: Must get ruling from XML Schema working group
// regarding whether steps in the XPath must be
// fully qualified if the grammar has a target
// namespace. -Ac
// RESOLUTION: Yes.
Field.XPath fXpath = new Field.XPath(fText, fStringPool,
fNamespacesScope);
// REVISIT: Get datatype validator. -Ac
// cannot statically determine type of field; not just because of descendant/union
// but because of <any> and <anyAttribute>. - NG
// DatatypeValidator validator = getDatatypeValidatorFor(parent, sXpath, fXpath);
// if (DEBUG_IC_DATATYPES) {
// System.out.println("<ICD>: datatype validator: "+validator);
// }
// must find DatatypeValidator in the Validator...
Field field = new Field(fXpath, ic);
if (DEBUG_IDENTITY_CONSTRAINTS) {
System.out.println("<IC>: field: "+field);
}
ic.addField(field);
}
catch (XPathException e) {
// REVISIT: Add error message.
reportGenericSchemaError(e.getMessage());
return;
}
fElem = XUtil.getNextSiblingElement(fElem);
}
} // traverseIdentityConstraint(IdentityConstraint,Element)
/* This code is no longer used because datatypes can't be found statically for ID constraints.
private DatatypeValidator getDatatypeValidatorFor(Element element,
Selector.XPath sxpath,
Field.XPath fxpath)
throws Exception {
// variables
String ename = element.getAttribute("name");
if (DEBUG_IC_DATATYPES) {
System.out.println("<ICD>: XMLValidator#getDatatypeValidatorFor("+
ename+','+sxpath+','+fxpath+')');
}
int localpart = fStringPool.addSymbol(ename);
String targetNamespace = fSchemaRootElement.getAttribute("targetNamespace");
int uri = fStringPool.addSymbol(targetNamespace);
int edeclIndex = fSchemaGrammar.getElementDeclIndex(uri, localpart,
Grammar.TOP_LEVEL_SCOPE);
// walk selector
XPath.LocationPath spath = sxpath.getLocationPath();
XPath.Step[] ssteps = spath.steps;
for (int i = 0; i < ssteps.length; i++) {
XPath.Step step = ssteps[i];
XPath.Axis axis = step.axis;
XPath.NodeTest nodeTest = step.nodeTest;
switch (axis.type) {
case XPath.Axis.ATTRIBUTE: {
// REVISIT: Add message. -Ac
reportGenericSchemaError("not allowed to select attribute");
return null;
}
case XPath.Axis.CHILD: {
int index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, edeclIndex);
if (index == -1) {
index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, Grammar.TOP_LEVEL_SCOPE);
}
if (index == -1) {
// REVISIT: Add message. -Ac
reportGenericSchemaError("no such element \""+fStringPool.toString(nodeTest.name.rawname)+'"');
return null;
}
edeclIndex = index;
break;
}
case XPath.Axis.SELF: {
// no-op
break;
}
default: {
// REVISIT: Add message. -Ac
reportGenericSchemaError("invalid selector axis");
return null;
}
}
}
// walk field
XPath.LocationPath fpath = fxpath.getLocationPath();
XPath.Step[] fsteps = fpath.steps;
for (int i = 0; i < fsteps.length; i++) {
XPath.Step step = fsteps[i];
XPath.Axis axis = step.axis;
XPath.NodeTest nodeTest = step.nodeTest;
switch (axis.type) {
case XPath.Axis.ATTRIBUTE: {
if (i != fsteps.length - 1) {
// REVISIT: Add message. -Ac
reportGenericSchemaError("attribute must be last step");
return null;
}
// look up validator
int adeclIndex = fSchemaGrammar.getAttributeDeclIndex(edeclIndex, nodeTest.name);
if (adeclIndex == -1) {
// REVISIT: Add message. -Ac
reportGenericSchemaError("no such attribute \""+fStringPool.toString(nodeTest.name.rawname)+'"');
}
XMLAttributeDecl adecl = new XMLAttributeDecl();
fSchemaGrammar.getAttributeDecl(adeclIndex, adecl);
DatatypeValidator validator = adecl.datatypeValidator;
return validator;
}
case XPath.Axis.CHILD: {
int index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, edeclIndex);
if (index == -1) {
index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, Grammar.TOP_LEVEL_SCOPE);
}
if (index == -1) {
// REVISIT: Add message. -Ac
reportGenericSchemaError("no such element \""+fStringPool.toString(nodeTest.name.rawname)+'"');
return null;
}
edeclIndex = index;
if (i < fsteps.length - 1) {
break;
}
// NOTE: Let fall through to self case so that we
// avoid duplicating code. -Ac
}
case XPath.Axis.SELF: {
// look up validator, if needed
if (i == fsteps.length - 1) {
XMLElementDecl edecl = new XMLElementDecl();
fSchemaGrammar.getElementDecl(edeclIndex, edecl);
if (edecl.type != XMLElementDecl.TYPE_SIMPLE) {
// REVISIT: Add message. -Ac
reportGenericSchemaError("selected element is not of simple type");
return null;
}
DatatypeValidator validator = edecl.datatypeValidator;
if (validator == null) validator = new StringDatatypeValidator();
return validator;
}
break;
}
default: {
// REVISIT: Add message. -Ac
reportGenericSchemaError("invalid selector axis");
return null;
}
}
}
// no validator!
// REVISIT: Add message. -Ac
reportGenericSchemaError("No datatype validator for field "+fxpath+
" of element "+ename);
return null;
} // getDatatypeValidatorFor(XPath):DatatypeValidator
*/ // back in to live code...
private String getElementNameFor(Element icnode) {
Element enode = (Element)icnode.getParentNode();
String ename = enode.getAttribute("name");
if (ename.length() == 0) {
ename = enode.getAttribute("ref");
}
return ename;
} // getElementNameFor(Element):String
int getLocalPartIndex(String fullName){
int colonAt = fullName.indexOf(":");
String localpart = fullName;
if ( colonAt > -1 ) {
localpart = fullName.substring(colonAt+1);
}
return fStringPool.addSymbol(localpart);
}
String getLocalPart(String fullName){
int colonAt = fullName.indexOf(":");
String localpart = fullName;
if ( colonAt > -1 ) {
localpart = fullName.substring(colonAt+1);
}
return localpart;
}
int getPrefixIndex(String fullName){
int colonAt = fullName.indexOf(":");
String prefix = "";
if ( colonAt > -1 ) {
prefix = fullName.substring(0,colonAt);
}
return fStringPool.addSymbol(prefix);
}
String getPrefix(String fullName){
int colonAt = fullName.indexOf(":");
String prefix = "";
if ( colonAt > -1 ) {
prefix = fullName.substring(0,colonAt);
}
return prefix;
}
private void checkSubstitutionGroupOK(Element elementDecl, Element substitutionGroupElementDecl,
boolean noErrorSoFar, int substitutionGroupElementDeclIndex, SchemaGrammar substitutionGroupGrammar, ComplexTypeInfo typeInfo,
ComplexTypeInfo substitutionGroupEltTypeInfo, DatatypeValidator dv,
DatatypeValidator substitutionGroupEltDV) throws Exception {
// here we must do two things:
// 1. Make sure there actually *is* a relation between the types of
// the element being nominated and the element doing the nominating;
// (see PR 3.3.6 point #3 in the first tableau, for instance; this
// and the corresponding tableaux from 3.4.6 and 3.14.6 rule out the nominated
// element having an anonymous type declaration.
// 2. Make sure the nominated element allows itself to be nominated by
// an element with the given type-relation.
// Note: we assume that (complex|simple)Type processing checks
// whether the type in question allows itself to
// be modified as this element desires.
// Check for type relationship;
// that is, make sure that the type we're deriving has some relationship
// to substitutionGroupElt's type.
if (typeInfo != null) {
int derivationMethod = typeInfo.derivedBy;
if(typeInfo.baseComplexTypeInfo == null) {
if (typeInfo.baseDataTypeValidator != null) { // take care of complexType based on simpleType case...
DatatypeValidator dTemp = typeInfo.baseDataTypeValidator;
for(; dTemp != null; dTemp = dTemp.getBaseValidator()) {
// WARNING!!! This uses comparison by reference andTemp is thus inherently suspect!
if(dTemp == substitutionGroupEltDV) break;
}
if (dTemp == null) {
if(substitutionGroupEltDV instanceof UnionDatatypeValidator) {
// dv must derive from one of its members...
Vector subUnionMemberDV = ((UnionDatatypeValidator)substitutionGroupEltDV).getBaseValidators();
int subUnionSize = subUnionMemberDV.size();
boolean found = false;
for (int i=0; i<subUnionSize && !found; i++) {
DatatypeValidator dTempSub = (DatatypeValidator)subUnionMemberDV.elementAt(i);
DatatypeValidator dTempOrig = typeInfo.baseDataTypeValidator;
for(; dTempOrig != null; dTempOrig = dTempOrig.getBaseValidator()) {
// WARNING!!! This uses comparison by reference andTemp is thus inherently suspect!
if(dTempSub == dTempOrig) {
found = true;
break;
}
}
}
if(!found) {
// REVISIT: localize
reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type which does not derive from the type of the element at the head of the substitution group");
noErrorSoFar = false;
}
} else {
// REVISIT: localize
reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type which does not derive from the type of the element at the head of the substitution group");
noErrorSoFar = false;
}
} else { // now let's see if substitutionGroup element allows this:
if((derivationMethod & substitutionGroupGrammar.getElementDeclFinalSet(substitutionGroupElementDeclIndex)) != 0) {
noErrorSoFar = false;
// REVISIT: localize
reportGenericSchemaError("element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME)
+ " cannot be part of the substitution group headed by "
+ substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME));
}
}
} else {
// REVISIT: localize
reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " which is part of a substitution must have a type which derives from the type of the element at the head of the substitution group");
noErrorSoFar = false;
}
} else {
String eltBaseName = typeInfo.baseComplexTypeInfo.typeName;
ComplexTypeInfo subTypeInfo = substitutionGroupEltTypeInfo;
for (; subTypeInfo != null && !subTypeInfo.typeName.equals(eltBaseName); subTypeInfo = subTypeInfo.baseComplexTypeInfo);
if (subTypeInfo == null) { // then this type isn't in the chain...
// REVISIT: localize
reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type whose base is " + eltBaseName + "; this basetype does not derive from the type of the element at the head of the substitution group");
noErrorSoFar = false;
} else { // type is fine; does substitutionElement allow this?
if((derivationMethod & substitutionGroupGrammar.getElementDeclFinalSet(substitutionGroupElementDeclIndex)) != 0) {
noErrorSoFar = false;
// REVISIT: localize
reportGenericSchemaError("element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME)
+ " cannot be part of the substitution group headed by "
+ substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME));
}
}
}
} else if (dv != null) { // do simpleType case...
// first, check for type relation.
if (!(checkSimpleTypeDerivationOK(dv,substitutionGroupEltDV))) {
// REVISIT: localize
reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type which does not derive from the type of the element at the head of the substitution group");
noErrorSoFar = false;
}
else { // now let's see if substitutionGroup element allows this:
if((SchemaSymbols.RESTRICTION & substitutionGroupGrammar.getElementDeclFinalSet(substitutionGroupElementDeclIndex)) != 0) {
noErrorSoFar = false;
// REVISIT: localize
reportGenericSchemaError("element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME)
+ " cannot be part of the substitution group headed by "
+ substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME));
}
}
}
}
//
// A utility method to check whether a particular datatypevalidator d, was validly
// derived from another datatypevalidator, b
//
private boolean checkSimpleTypeDerivationOK(DatatypeValidator d, DatatypeValidator b) {
DatatypeValidator dTemp = d;
for(; dTemp != null; dTemp = dTemp.getBaseValidator()) {
// WARNING!!! This uses comparison by reference andTemp is thus inherently suspect!
if(dTemp == b) break;
}
if (dTemp == null) {
// now if b is a union, then we can
// derive from it if we derive from any of its members' types.
if(b instanceof UnionDatatypeValidator) {
// d must derive from one of its members...
Vector subUnionMemberDV = ((UnionDatatypeValidator)b).getBaseValidators();
int subUnionSize = subUnionMemberDV.size();
boolean found = false;
for (int i=0; i<subUnionSize && !found; i++) {
DatatypeValidator dTempSub = (DatatypeValidator)subUnionMemberDV.elementAt(i);
DatatypeValidator dTempOrig = d;
for(; dTempOrig != null; dTempOrig = dTempOrig.getBaseValidator()) {
// WARNING!!! This uses comparison by reference andTemp is thus inherently suspect!
if(dTempSub == dTempOrig) {
found = true;
break;
}
}
}
if(!found) {
return false;
}
} else {
return false;
}
}
return true;
}
// this originally-simple method is much -complicated by the fact that, when we're
// redefining something, we've not only got to look at the space of the thing
// we're redefining but at the original schema too.
// The idea is to start from the top, then go down through
// our list of schemas until we find what we aant.
// This should not often be necessary, because we've processed
// all redefined schemas, but three are conditions in which
// not all elements so redefined may have been promoted to
// the topmost level.
private Element getTopLevelComponentByName(String componentCategory, String name) throws Exception {
Element child = null;
SchemaInfo curr = fSchemaInfoListRoot;
for (; curr != null || curr == fSchemaInfoListRoot; curr = curr.getNext()) {
if (curr != null) curr.restore();
if ( componentCategory.equals(SchemaSymbols.ELT_GROUP) ) {
child = (Element) fSchemaGrammar.topLevelGroupDecls.get(name);
}
else if ( componentCategory.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP ) ) {
child = (Element) fSchemaGrammar.topLevelAttrGrpDecls.get(name);
}
else if ( componentCategory.equals(SchemaSymbols.ELT_ATTRIBUTE ) ) {
child = (Element) fSchemaGrammar.topLevelAttrDecls.get(name);
}
if (child != null ) {
break;
}
child = XUtil.getFirstChildElement(fSchemaRootElement);
if (child == null) {
continue;
}
while (child != null ){
if ( child.getLocalName().equals(componentCategory)) {
if (child.getAttribute(SchemaSymbols.ATT_NAME).equals(name)) {
break;
}
} else if (fRedefineSucceeded && child.getLocalName().equals(SchemaSymbols.ELT_REDEFINE)) {
Element gChild = XUtil.getFirstChildElement(child);
while (gChild != null ){
if (gChild.getLocalName().equals(componentCategory)) {
if (gChild.getAttribute(SchemaSymbols.ATT_NAME).equals(name)) {
break;
}
}
gChild = XUtil.getNextSiblingElement(gChild);
}
if (gChild != null) {
child = gChild;
break;
}
}
child = XUtil.getNextSiblingElement(child);
}
if (child != null || fSchemaInfoListRoot == null) break;
}
// have to reset fSchemaInfoList
if(curr != null)
curr.restore();
else
if (fSchemaInfoListRoot != null)
fSchemaInfoListRoot.restore();
return child;
}
private boolean isTopLevel(Element component) {
String parentName = component.getParentNode().getLocalName();
return (parentName.endsWith(SchemaSymbols.ELT_SCHEMA))
|| (parentName.endsWith(SchemaSymbols.ELT_REDEFINE)) ;
}
DatatypeValidator getTypeValidatorFromNS(String newSchemaURI, String localpart) throws Exception {
// The following impl is for the case where every Schema Grammar has its own instance of DatatypeRegistry.
// Now that we have only one DataTypeRegistry used by all schemas. this is not needed.
/*****
Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI);
if (grammar != null && grammar instanceof SchemaGrammar) {
SchemaGrammar sGrammar = (SchemaGrammar) grammar;
DatatypeValidator dv = (DatatypeValidator) fSchemaGrammar.getDatatypeRegistry().getDatatypeValidator(localpart);
return dv;
}
else {
reportGenericSchemaError("could not resolve URI : " + newSchemaURI + " to a SchemaGrammar in getTypeValidatorFromNS");
}
return null;
/*****/
return getDatatypeValidator(newSchemaURI, localpart);
}
ComplexTypeInfo getTypeInfoFromNS(String newSchemaURI, String localpart) throws Exception {
Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI);
if (grammar != null && grammar instanceof SchemaGrammar) {
SchemaGrammar sGrammar = (SchemaGrammar) grammar;
ComplexTypeInfo typeInfo = (ComplexTypeInfo) sGrammar.getComplexTypeRegistry().get(newSchemaURI+","+localpart);
return typeInfo;
}
else {
reportGenericSchemaError("could not resolve URI : " + newSchemaURI + " to a SchemaGrammar in getTypeInfoFromNS");
}
return null;
}
DatatypeValidator getElementDeclTypeValidatorFromNS(String newSchemaURI, String localpart) throws Exception {
Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI);
if (grammar != null && grammar instanceof SchemaGrammar) {
SchemaGrammar sGrammar = (SchemaGrammar) grammar;
int eltIndex = sGrammar.getElementDeclIndex(fStringPool.addSymbol(newSchemaURI),
fStringPool.addSymbol(localpart),
TOP_LEVEL_SCOPE);
DatatypeValidator dv = null;
if (eltIndex>-1) {
sGrammar.getElementDecl(eltIndex, fTempElementDecl);
dv = fTempElementDecl.datatypeValidator;
}
else {
reportGenericSchemaError("could not find global element : '" + localpart
+ " in the SchemaGrammar "+newSchemaURI);
}
return dv;
}
else {
reportGenericSchemaError("could not resolve URI : " + newSchemaURI
+ " to a SchemaGrammar in getELementDeclTypeValidatorFromNS");
}
return null;
}
ComplexTypeInfo getElementDeclTypeInfoFromNS(String newSchemaURI, String localpart) throws Exception {
Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI);
if (grammar != null && grammar instanceof SchemaGrammar) {
SchemaGrammar sGrammar = (SchemaGrammar) grammar;
int eltIndex = sGrammar.getElementDeclIndex(fStringPool.addSymbol(newSchemaURI),
fStringPool.addSymbol(localpart),
TOP_LEVEL_SCOPE);
ComplexTypeInfo typeInfo = null;
if (eltIndex>-1) {
typeInfo = sGrammar.getElementComplexTypeInfo(eltIndex);
}
else {
reportGenericSchemaError("could not find global element : '" + localpart
+ " in the SchemaGrammar "+newSchemaURI);
}
return typeInfo;
}
else {
reportGenericSchemaError("could not resolve URI : " + newSchemaURI
+ " to a SchemaGrammar in getElementDeclTypeInfoFromNS");
}
return null;
}
/**
* Traverses notation declaration
* and saves it in a registry.
* Notations are stored in registry with the following
* key: "uri:localname"
*
* @param notation child <notation>
* @return local name of notation
* @exception Exception
*/
private String traverseNotationDecl( Element notation ) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(notation, scope);
String name = notation.getAttribute(SchemaSymbols.ATT_NAME);
String qualifiedName =name;
if (fTargetNSURIString.length () != 0) {
qualifiedName = fTargetNSURIString+":"+name;
}
if (fNotationRegistry.get(qualifiedName)!=null) {
return name;
}
String publicId = notation.getAttribute(SchemaSymbols.ATT_PUBLIC);
String systemId = notation.getAttribute(SchemaSymbols.ATT_SYSTEM);
if (publicId.length() == 0 && systemId.length() == 0) {
//REVISIT: update error messages
reportGenericSchemaError("<notation> declaration is invalid");
}
if (name.equals("")) {
//REVISIT: update error messages
reportGenericSchemaError("<notation> declaration does not have a name");
}
fNotationRegistry.put(qualifiedName, name);
//we don't really care if something inside <notation> is wrong..
checkContent( notation, XUtil.getFirstChildElement(notation), true );
//REVISIT: wait for DOM L3 APIs to pass info to application
//REVISIT: SAX2 does not support notations. API should be changed.
return name;
}
/**
* This methods will traverse notation from current schema,
* as well as from included or imported schemas
*
* @param notationName
* localName of notation
* @param uriStr uriStr for schema grammar
* @return return local name for Notation (if found), otherwise
* return empty string;
* @exception Exception
*/
private String traverseNotationFromAnotherSchema( String notationName , String uriStr ) throws Exception {
SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr);
if (uriStr == null || aGrammar==null ||! (aGrammar instanceof SchemaGrammar) ) {
// REVISIT: Localize
reportGenericSchemaError("!!Schema not found in #traverseNotationDeclFromAnotherSchema, "+
"schema uri: " + uriStr
+", groupName: " + notationName);
return "";
}
String savedNSURIString = fTargetNSURIString;
fTargetNSURIString = fStringPool.toString(fStringPool.addSymbol(aGrammar.getTargetNamespaceURI()));
if (DEBUGGING) {
System.out.println("[traverseFromAnotherSchema]: " + fTargetNSURIString);
}
String qualifiedName = fTargetNSURIString + ":" + notationName;
String localName = (String)fNotationRegistry.get(qualifiedName);
if(localName != null ) // we've already traversed this notation
return localName;
//notation decl has not been traversed yet
Element notationDecl = (Element) aGrammar.topLevelNotationDecls.get((Object)notationName);
if (notationDecl == null) {
// REVISIT: Localize
reportGenericSchemaError( "no notation named \"" + notationName
+ "\" was defined in schema : " + uriStr);
return "";
}
localName = traverseNotationDecl(notationDecl);
fTargetNSURIString = savedNSURIString;
return localName;
} // end of method traverseNotationFromAnotherSchema
/**
* Traverse Group Declaration.
*
* <group
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger
* name = NCName
* ref = QName>
* Content: (annotation? , (all | choice | sequence)?)
* <group/>
*
* @param elementDecl
* @return
* @exception Exception
*/
private int traverseGroupDecl( Element groupDecl ) throws Exception {
// General Attribute Checking
int scope = isTopLevel(groupDecl)?
GeneralAttrCheck.ELE_CONTEXT_GLOBAL:
GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(groupDecl, scope);
String groupName = groupDecl.getAttribute(SchemaSymbols.ATT_NAME);
String ref = groupDecl.getAttribute(SchemaSymbols.ATT_REF);
Element child = checkContent( groupDecl, XUtil.getFirstChildElement(groupDecl), true );
if (!ref.equals("")) {
if (isTopLevel(groupDecl))
// REVISIT: localize
reportGenericSchemaError ( "A group with \"ref\" present must not have <schema> or <redefine> as its parent");
if (!groupName.equals(""))
// REVISIT: localize
reportGenericSchemaError ( "group " + groupName + " cannot refer to another group, but it refers to " + ref);
// there should be no children for <group ref="...">
if (XUtil.getFirstChildElement(groupDecl)!=null)
reportGenericSchemaError ( "A group with \"ref\" present must not have children");
String prefix = "";
String localpart = ref;
int colonptr = ref.indexOf(":");
if ( colonptr > 0) {
prefix = ref.substring(0,colonptr);
localpart = ref.substring(colonptr+1);
}
int localpartIndex = fStringPool.addSymbol(localpart);
String uriStr = resolvePrefixToURI(prefix);
if (!uriStr.equals(fTargetNSURIString)) {
return traverseGroupDeclFromAnotherSchema(localpart, uriStr);
}
Object contentSpecHolder = fGroupNameRegistry.get(uriStr + "," + localpart);
if(contentSpecHolder != null ) { // we may have already traversed this group
boolean fail = false;
int contentSpecHolderIndex = 0;
try {
contentSpecHolderIndex = ((Integer)contentSpecHolder).intValue();
} catch (ClassCastException c) {
fail = true;
}
if(!fail) {
return contentSpecHolderIndex;
}
}
// Check if we are in the middle of traversing this group (i.e. circular references)
if (fCurrentGroupNameStack.search((Object)localpart) > - 1) {
reportGenericSchemaError("mg-props-correct: Circular definition for group " + localpart);
return -2;
}
int contentSpecIndex = -1;
Element referredGroup = getTopLevelComponentByName(SchemaSymbols.ELT_GROUP,localpart);
if (referredGroup == null) {
// REVISIT: Localize
reportGenericSchemaError("Group " + localpart + " not found in the Schema");
//REVISIT, this should be some custom Exception
//throw new RuntimeException("Group " + localpart + " not found in the Schema");
}
else {
contentSpecIndex = traverseGroupDecl(referredGroup);
}
return contentSpecIndex;
} else if (groupName.equals(""))
// REVISIT: Localize
reportGenericSchemaError("a <group> must have a name or a ref present");
String qualifiedGroupName = fTargetNSURIString + "," + groupName;
Object contentSpecHolder = fGroupNameRegistry.get(qualifiedGroupName);
if(contentSpecHolder != null ) { // we may have already traversed this group
boolean fail = false;
int contentSpecHolderIndex = 0;
try {
contentSpecHolderIndex = ((Integer)contentSpecHolder).intValue();
} catch (ClassCastException c) {
fail = true;
}
if(!fail) {
return contentSpecHolderIndex;
}
}
// if we're here then we're traversing a top-level group that we've never seen before.
// Push the group name onto a stack, so that we can check for circular groups
fCurrentGroupNameStack.push(groupName);
// Save the scope and set the current scope to -1
int savedScope = fCurrentScope;
fCurrentScope = -1;
int index = -2;
boolean illegalChild = false;
String childName =
(child != null) ? child.getLocalName() : "";
if (childName.equals(SchemaSymbols.ELT_ALL)) {
index = traverseAll(child);
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
}
else if (!childName.equals("") || (child != null && XUtil.getNextSiblingElement(child) != null)) {
illegalChild = true;
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "group", childName });
}
//Must have all or choice or sequence child.
if (child == null) {
reportGenericSchemaError("Named group must contain an 'all', 'choice' or 'sequence' child");
}
else if (XUtil.getNextSiblingElement(child) != null) {
illegalChild = true;
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "group", childName });
}
if ( ! illegalChild && child != null) {
index = handleOccurrences(index, child, CHILD_OF_GROUP);
}
contentSpecHolder = new Integer(index);
fCurrentGroupNameStack.pop();
fCurrentScope = savedScope;
fGroupNameRegistry.put(qualifiedGroupName, contentSpecHolder);
return index;
}
private int traverseGroupDeclFromAnotherSchema( String groupName , String uriStr ) throws Exception {
SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr);
if (uriStr == null || aGrammar==null ||! (aGrammar instanceof SchemaGrammar) ) {
// REVISIT: Localize
reportGenericSchemaError("!!Schema not found in #traverseGroupDeclFromAnotherSchema, "+
"schema uri: " + uriStr
+", groupName: " + groupName);
return -1;
}
Element groupDecl = (Element) aGrammar.topLevelGroupDecls.get((Object)groupName);
if (groupDecl == null) {
// REVISIT: Localize
reportGenericSchemaError( "no group named \"" + groupName
+ "\" was defined in schema : " + uriStr);
return -1;
}
NamespacesScope saveNSMapping = fNamespacesScope;
int saveTargetNSUri = fTargetNSURI;
fTargetNSURI = fStringPool.addSymbol(aGrammar.getTargetNamespaceURI());
fNamespacesScope = aGrammar.getNamespacesScope();
Element child = checkContent( groupDecl, XUtil.getFirstChildElement(groupDecl), true );
String qualifiedGroupName = fTargetNSURIString + "," + groupName;
Object contentSpecHolder = fGroupNameRegistry.get(qualifiedGroupName);
if(contentSpecHolder != null ) { // we may have already traversed this group
boolean fail = false;
int contentSpecHolderIndex = 0;
try {
contentSpecHolderIndex = ((Integer)contentSpecHolder).intValue();
} catch (ClassCastException c) {
fail = true;
}
if(!fail) {
return contentSpecHolderIndex;
}
}
// ------------------------------------
// if we're here then we're traversing a top-level group that we've never seen before.
int index = -2;
boolean illegalChild = false;
String childName = (child != null) ? child.getLocalName() : "";
if (childName.equals(SchemaSymbols.ELT_ALL)) {
index = traverseAll(child);
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
}
else if (!childName.equals("") || (child != null && XUtil.getNextSiblingElement(child) != null)) {
illegalChild = true;
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "group", childName });
}
if ( ! illegalChild && child != null) {
index = handleOccurrences( index, child);
}
contentSpecHolder = new Integer(index);
fGroupNameRegistry.put(qualifiedGroupName, contentSpecHolder);
fNamespacesScope = saveNSMapping;
fTargetNSURI = saveTargetNSUri;
return index;
} // end of method traverseGroupDeclFromAnotherSchema
/**
*
* Traverse the Sequence declaration
*
* <sequence
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger>
* Content: (annotation? , (element | group | choice | sequence | any)*)
* </sequence>
*
**/
int traverseSequence (Element sequenceDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(sequenceDecl, scope);
Element child = checkContent(sequenceDecl, XUtil.getFirstChildElement(sequenceDecl), true);
int csnType = XMLContentSpec.CONTENTSPECNODE_SEQ;
int left = -2;
int right = -2;
boolean hadContent = false;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
boolean seeParticle = false;
String childName = child.getLocalName();
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_GROUP)) {
index = traverseGroupDecl(child);
// A content type of all can only appear
// as the content type of a complex type definition.
if (hasAllContent(index)) {
reportSchemaError(SchemaMessageProvider.AllContentLimited,
new Object [] { "sequence" });
continue;
}
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ANY)) {
index = traverseAny(child);
seeParticle = true;
}
else {
reportSchemaError(
SchemaMessageProvider.SeqChoiceContentRestricted,
new Object [] { "sequence", childName });
continue;
}
if (index != -2)
hadContent = true;
if (seeParticle) {
index = handleOccurrences( index, child);
}
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
right = index;
}
}
if (hadContent) {
if (right != -2 || fSchemaGrammar.getDeferContentSpecExpansion())
left = fSchemaGrammar.addContentSpecNode(csnType, left, right,
false);
}
return left;
}
/**
*
* Traverse the Choice declaration
*
* <choice
* id = ID
* maxOccurs = string
* minOccurs = nonNegativeInteger>
* Content: (annotation? , (element | group | choice | sequence | any)*)
* </choice>
*
**/
int traverseChoice (Element choiceDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(choiceDecl, scope);
// REVISIT: traverseChoice, traverseSequence can be combined
Element child = checkContent(choiceDecl, XUtil.getFirstChildElement(choiceDecl), true);
int csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE;
int left = -2;
int right = -2;
boolean hadContent = false;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
boolean seeParticle = false;
String childName = child.getLocalName();
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_GROUP)) {
index = traverseGroupDecl(child);
// A model group whose {compositor} is "all" can only appear
// as the {content type} of a complex type definition.
if (hasAllContent(index)) {
reportSchemaError(SchemaMessageProvider.AllContentLimited,
new Object [] { "choice" });
continue;
}
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_CHOICE)) {
index = traverseChoice(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) {
index = traverseSequence(child);
seeParticle = true;
}
else if (childName.equals(SchemaSymbols.ELT_ANY)) {
index = traverseAny(child);
seeParticle = true;
}
else {
reportSchemaError(
SchemaMessageProvider.SeqChoiceContentRestricted,
new Object [] { "choice", childName });
continue;
}
if (index != -2)
hadContent = true;
if (seeParticle) {
index = handleOccurrences( index, child);
}
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false);
right = index;
}
}
if (hadContent) {
if (right != -2 || fSchemaGrammar.getDeferContentSpecExpansion())
left = fSchemaGrammar.addContentSpecNode(csnType, left, right,
false);
}
return left;
}
/**
*
* Traverse the "All" declaration
*
* <all
* id = ID
* maxOccurs = 1 : 1
* minOccurs = (0 | 1) : 1>
* Content: (annotation? , element*)
* </all>
**/
int traverseAll(Element allDecl) throws Exception {
// General Attribute Checking
int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL;
Hashtable attrValues = fGeneralAttrCheck.checkAttributes(allDecl, scope);
Element child = checkContent(allDecl,
XUtil.getFirstChildElement(allDecl), true);
int csnType = XMLContentSpec.CONTENTSPECNODE_ALL;
int left = -2;
int right = -2;
boolean hadContent = false;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
String childName = child.getLocalName();
// Only elements are allowed in <all>
if (childName.equals(SchemaSymbols.ELT_ELEMENT)) {
QName eltQName = traverseElementDecl(child);
index = fSchemaGrammar.addContentSpecNode(
XMLContentSpec.CONTENTSPECNODE_LEAF,
eltQName.localpart,
eltQName.uri,
false);
index = handleOccurrences(index, child, PROCESSING_ALL);
}
else {
reportSchemaError(SchemaMessageProvider.AllContentRestricted,
new Object [] { childName });
continue;
}
hadContent = true;
if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fSchemaGrammar.addContentSpecNode(csnType, left, right,
false);
right = index;
}
}
if (hadContent) {
if (right != -2 || fSchemaGrammar.getDeferContentSpecExpansion())
left = fSchemaGrammar.addContentSpecNode(csnType, left, right,
false);
}
return left;
}
// Determines whether a content spec tree represents an "all" content model
private boolean hasAllContent(int contentSpecIndex) {
// If the content is not empty, is the top node ALL?
if (contentSpecIndex > -1) {
XMLContentSpec content = new XMLContentSpec();
fSchemaGrammar.getContentSpec(contentSpecIndex, content);
// An ALL node could be optional, so we have to be prepared
// to look one level below a ZERO_OR_ONE node for an ALL.
if (content.type == XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE) {
fSchemaGrammar.getContentSpec(content.value, content);
}
return (content.type == XMLContentSpec.CONTENTSPECNODE_ALL);
}
return false;
}
// utilities from Tom Watson's SchemaParser class
// TO DO: Need to make this more conformant with Schema int type parsing
private int parseInt (String intString) throws Exception
{
if ( intString.equals("*") ) {
return SchemaSymbols.INFINITY;
} else {
return Integer.parseInt (intString);
}
}
private int parseSimpleFinal (String finalString) throws Exception
{
if ( finalString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) {
return SchemaSymbols.ENUMERATION+SchemaSymbols.RESTRICTION+SchemaSymbols.LIST;
} else {
int enumerate = 0;
int restrict = 0;
int list = 0;
StringTokenizer t = new StringTokenizer (finalString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ("restriction in set twice");
}
} else if ( token.equals (SchemaSymbols.ELT_LIST) ) {
if ( list == 0 ) {
list = SchemaSymbols.LIST;
} else {
// REVISIT: Localize
reportGenericSchemaError ("list in set twice");
}
}
else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid value (" +
finalString +
")" );
}
}
return enumerate+list;
}
}
private int parseDerivationSet (String finalString) throws Exception
{
if ( finalString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) {
return SchemaSymbols.EXTENSION+SchemaSymbols.RESTRICTION;
} else {
int extend = 0;
int restrict = 0;
StringTokenizer t = new StringTokenizer (finalString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.EXTENSION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "extension already in set" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "restriction already in set" );
}
} else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid final value (" + finalString + ")" );
}
}
return extend+restrict;
}
}
private int parseBlockSet (String blockString) throws Exception
{
if( blockString == null)
return fBlockDefault;
else if ( blockString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) {
return SchemaSymbols.SUBSTITUTION+SchemaSymbols.EXTENSION+SchemaSymbols.RESTRICTION;
} else {
int extend = 0;
int restrict = 0;
int substitute = 0;
StringTokenizer t = new StringTokenizer (blockString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ATTVAL_SUBSTITUTION) ) {
if ( substitute == 0 ) {
substitute = SchemaSymbols.SUBSTITUTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'substitution' already in the list" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.EXTENSION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'extension' is already in the list" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'restriction' is already in the list" );
}
} else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid block value (" + blockString + ")" );
}
}
int defaultVal = extend+restrict+substitute;
return (defaultVal == 0 ? fBlockDefault : defaultVal);
}
}
private int parseFinalSet (String finalString) throws Exception
{
if( finalString == null) {
return fFinalDefault;
}
else if ( finalString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) {
return SchemaSymbols.EXTENSION+SchemaSymbols.LIST+SchemaSymbols.RESTRICTION+SchemaSymbols.UNION;
} else {
int extend = 0;
int restrict = 0;
int list = 0;
int union = 0;
StringTokenizer t = new StringTokenizer (finalString, " ");
while (t.hasMoreTokens()) {
String token = t.nextToken ();
if ( token.equals (SchemaSymbols.ELT_UNION) ) {
if ( union == 0 ) {
union = SchemaSymbols.UNION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'union' is already in the list" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) {
if ( extend == 0 ) {
extend = SchemaSymbols.EXTENSION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'extension' is already in the list" );
}
} else if ( token.equals (SchemaSymbols.ELT_LIST) ) {
if ( list == 0 ) {
list = SchemaSymbols.LIST;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'list' is already in the list" );
}
} else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) {
if ( restrict == 0 ) {
restrict = SchemaSymbols.RESTRICTION;
} else {
// REVISIT: Localize
reportGenericSchemaError ( "The value 'restriction' is already in the list" );
}
} else {
// REVISIT: Localize
reportGenericSchemaError ( "Invalid final value (" + finalString + ")" );
}
}
int defaultVal = extend+restrict+list+union;
return (defaultVal == 0 ? fFinalDefault : defaultVal);
}
}
private void reportGenericSchemaError (String error) throws Exception {
if (fErrorReporter == null) {
System.err.println("__TraverseSchemaError__ : " + error);
}
else {
reportSchemaError (SchemaMessageProvider.GenericError, new Object[] { error });
}
}
private void reportSchemaError(int major, Object args[]) throws Exception {
if (fErrorReporter == null) {
System.out.println("__TraverseSchemaError__ : " + SchemaMessageProvider.fgMessageKeys[major]);
for (int i=0; i< args.length ; i++) {
System.out.println((String)args[i]);
}
}
else {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
major,
SchemaMessageProvider.MSG_NONE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
/** Don't check the following code in because it creates a dependency on
the serializer, preventing to package the parser without the serializer
//Unit Test here
public static void main(String args[] ) {
if( args.length != 1 ) {
System.out.println( "Error: Usage java TraverseSchema yourFile.xsd" );
System.exit(0);
}
DOMParser parser = new IgnoreWhitespaceParser();
parser.setEntityResolver( new Resolver() );
parser.setErrorHandler( new ErrorHandler() );
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
}catch( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
}catch( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
try {
parser.parse( args[0]);
}catch( IOException e ) {
e.printStackTrace();
}catch( SAXException e ) {
e.printStackTrace();
}
Document document = parser.getDocument(); //Our Grammar
OutputFormat format = new OutputFormat( document );
java.io.StringWriter outWriter = new java.io.StringWriter();
XMLSerializer serial = new XMLSerializer( outWriter,format);
TraverseSchema tst = null;
try {
Element root = document.getDocumentElement();// This is what we pass to TraverserSchema
//serial.serialize( root );
//System.out.println(outWriter.toString());
tst = new TraverseSchema( root, new StringPool(), new SchemaGrammar(), (GrammarResolver) new GrammarResolverImpl() );
}
catch (Exception e) {
e.printStackTrace(System.err);
}
parser.getDocument();
}
**/
static class Resolver implements EntityResolver {
private static final String SYSTEM[] = {
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/structures.dtd",
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/datatypes.dtd",
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/versionInfo.ent",
};
private static final String PATH[] = {
"structures.dtd",
"datatypes.dtd",
"versionInfo.ent",
};
public InputSource resolveEntity(String publicId, String systemId)
throws IOException {
// looking for the schema DTDs?
for (int i = 0; i < SYSTEM.length; i++) {
if (systemId.equals(SYSTEM[i])) {
InputSource source = new InputSource(getClass().getResourceAsStream(PATH[i]));
source.setPublicId(publicId);
source.setSystemId(systemId);
return source;
}
}
// use default resolution
return null;
} // resolveEntity(String,String):InputSource
} // class Resolver
static class ErrorHandler implements org.xml.sax.ErrorHandler {
/** Warning. */
public void warning(SAXParseException ex) {
System.err.println("[Warning] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Error. */
public void error(SAXParseException ex) {
System.err.println("[Error] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Fatal error. */
public void fatalError(SAXParseException ex) throws SAXException {
System.err.println("[Fatal Error] "+
getLocationString(ex)+": "+
ex.getMessage());
throw ex;
}
//
// Private methods
//
/** Returns a string of the location. */
private String getLocationString(SAXParseException ex) {
StringBuffer str = new StringBuffer();
String systemId_ = ex.getSystemId();
if (systemId_ != null) {
int index = systemId_.lastIndexOf('/');
if (index != -1)
systemId_ = systemId_.substring(index + 1);
str.append(systemId_);
}
str.append(':');
str.append(ex.getLineNumber());
str.append(':');
str.append(ex.getColumnNumber());
return str.toString();
} // getLocationString(SAXParseException):String
}
static class IgnoreWhitespaceParser
extends DOMParser {
public void ignorableWhitespace(char ch[], int start, int length) {}
public void ignorableWhitespace(int dataIdx) {}
} // class IgnoreWhitespaceParser
// When in a <redefine>, type definitions being used (and indeed
// refs to <group>'s and <attributeGroup>'s) may refer to info
// items either in the schema being redefined, in the <redefine>,
// or else in the schema doing the redefining. Because of this
// latter we have to be prepared sometimes to look for our type
// definitions outside the schema stored in fSchemaRootElement.
// This simple class does this; it's just a linked list that
// lets us look at the <schema>'s on the queue; note also that this
// should provide us with a mechanism to handle nested <redefine>'s.
// It's also a handy way of saving schema info when importing/including; saves some code.
public class SchemaInfo {
private Element saveRoot;
private SchemaInfo nextRoot;
private SchemaInfo prevRoot;
private String savedSchemaURL = fCurrentSchemaURL;
private boolean saveElementDefaultQualified = fElementDefaultQualified;
private boolean saveAttributeDefaultQualified = fAttributeDefaultQualified;
private int saveScope = fCurrentScope;
private int saveBlockDefault = fBlockDefault;
private int saveFinalDefault = fFinalDefault;
private NamespacesScope saveNamespacesScope = fNamespacesScope;
public SchemaInfo ( boolean saveElementDefaultQualified, boolean saveAttributeDefaultQualified,
int saveBlockDefault, int saveFinalDefault,
int saveScope, String savedSchemaURL, Element saveRoot,
NamespacesScope saveNamespacesScope, SchemaInfo nextRoot, SchemaInfo prevRoot) {
this.saveElementDefaultQualified = saveElementDefaultQualified;
this.saveAttributeDefaultQualified = saveAttributeDefaultQualified;
this.saveBlockDefault = saveBlockDefault;
this.saveFinalDefault = saveFinalDefault;
this.saveScope = saveScope ;
this.savedSchemaURL = savedSchemaURL;
this.saveRoot = saveRoot ;
if(saveNamespacesScope != null)
this.saveNamespacesScope = (NamespacesScope)saveNamespacesScope.clone();
this.nextRoot = nextRoot;
this.prevRoot = prevRoot;
}
public void setNext (SchemaInfo next) {
nextRoot = next;
}
public SchemaInfo getNext () {
return nextRoot;
}
public void setPrev (SchemaInfo prev) {
prevRoot = prev;
}
public String getCurrentSchemaURL() { return savedSchemaURL; }
public SchemaInfo getPrev () {
return prevRoot;
}
public Element getRoot() { return saveRoot; }
// NOTE: this has side-effects!!!
public void restore() {
fCurrentSchemaURL = savedSchemaURL;
fCurrentScope = saveScope;
fElementDefaultQualified = saveElementDefaultQualified;
fAttributeDefaultQualified = saveAttributeDefaultQualified;
fBlockDefault = saveBlockDefault;
fFinalDefault = saveFinalDefault;
fNamespacesScope = (NamespacesScope)saveNamespacesScope.clone();
fSchemaRootElement = saveRoot;
}
} // class SchemaInfo
} // class TraverseSchema
| fixes for <redefine> bugs
git-svn-id: 21df804813e9d3638e43477f308dd0be51e5f30f@317222 13f79535-47bb-0310-9956-ffa450edef68
| src/org/apache/xerces/validators/schema/TraverseSchema.java | fixes for <redefine> bugs | <ide><path>rc/org/apache/xerces/validators/schema/TraverseSchema.java
<ide> String bName = (String)fRedefineAttributeGroupMap.get(dName);
<ide> if(bName != null) {
<ide> child.setAttribute(SchemaSymbols.ATT_NAME, bName);
<add> // and make sure we wipe this out of the grammar!
<add> fSchemaGrammar.topLevelAttrGrpDecls.remove(dName);
<ide> // Now we reuse this location in the array to store info we'll need for validation...
<ide> ComplexTypeInfo typeInfo = new ComplexTypeInfo();
<ide> int templateElementNameIndex = fStringPool.addSymbol("$"+bName);
<ide> }
<ide> }
<ide> traverseAttributeGroupDecl(child, null, null);
<add>// fSchemaGrammar.topLevelAttrGrpDecls.remove(child.getAttribute("name"));
<ide> } else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) {
<ide> traverseAttributeDecl( child, null , false);
<ide> } else if (name.equals(SchemaSymbols.ELT_GROUP)) {
<ide> } else if (eltLocalname.equals(SchemaSymbols.ELT_GROUP)) {
<ide> QName processedBaseName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI);
<ide> int groupRefsCount = changeRedefineGroup(processedBaseName, eltLocalname, newName, child);
<add> String restrictedName = newName.substring(0, newName.length()-redefIdentifier.length());
<ide> if(!fRedefineSucceeded) {
<del> fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+oldName, new Boolean(false));
<add> fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+restrictedName, new Boolean(false));
<ide> }
<ide> if(groupRefsCount > 1) {
<ide> fRedefineSucceeded = false;
<del> fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+oldName, new Boolean(false));
<add> fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+restrictedName, new Boolean(false));
<ide> // REVISIT: localize
<ide> reportGenericSchemaError("if a group child of a <redefine> element contains a group ref'ing itself, it must have exactly 1; this one has " + groupRefsCount);
<ide> } else if (groupRefsCount == 1) {
<del> fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+oldName, new Boolean(false));
<add> fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+restrictedName, new Boolean(false));
<ide> return true;
<ide> } else {
<ide> fGroupNameRegistry.put(fTargetNSURIString + "," + oldName, newName);
<del> fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+oldName, new Boolean(true));
<add> fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+restrictedName, new Boolean(true));
<ide> }
<ide> } else {
<ide> fRedefineSucceeded = false;
<ide>
<ide> return -1;
<ide> // TO DO
<del> // REVISIST: different NS, not supported yet.
<add> // REVISIT: different NS, not supported yet.
<ide> // REVISIT: Localize
<ide> //reportGenericSchemaError("Feature not supported: see an attribute from different NS");
<ide> } else {
<ide> traverseAttributeDecl(child, typeInfo, false);
<ide> }
<ide> else if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) {
<del>// if(typeInfo != null)
<add> NamespacesScope currScope = (NamespacesScope)fNamespacesScope.clone();
<add> // if(typeInfo != null)
<ide> // only do this if we're traversing because we were ref'd here; when we come
<ide> // upon this decl by itself we're just validating.
<ide> traverseAttributeGroupDecl(child, typeInfo,anyAttDecls);
<add> fNamespacesScope = currScope;
<ide> }
<ide> else
<ide> break;
<ide> if ( componentCategory.equals(SchemaSymbols.ELT_GROUP) ) {
<ide> child = (Element) fSchemaGrammar.topLevelGroupDecls.get(name);
<ide> }
<del> else if ( componentCategory.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP ) ) {
<add> else if ( componentCategory.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP ) && fSchemaInfoListRoot == null ) {
<ide> child = (Element) fSchemaGrammar.topLevelAttrGrpDecls.get(name);
<ide> }
<ide> else if ( componentCategory.equals(SchemaSymbols.ELT_ATTRIBUTE ) ) { |
|
Java | mit | afabb66a8f33343852ae24e00b9d2f377d921c5f | 0 | om3g4zell/CityBuilderJSFML | package graphics;
import org.jsfml.system.Vector2i;
/*
* Represents a tile
*/
public class Tile {
// Enum of each tileType
public static enum TileType {
TERRAIN_GRASS,
BUILDING_HOUSE,
BUILDING_SUPERMARKET,
BUILDING_ROAD,
BUILDING_GENERATOR
}
// Track the last id.
protected static int lastId = 0;
// Attributes.
protected TileType tileType;
protected int id;
protected Vector2i position;
// Constructor.
public Tile(TileType tileType, Vector2i position) {
this.tileType = tileType;
this.id = Tile.lastId;
this.position = position;
// Increment the last id.
Tile.lastId++;
}
// Set the tileType
public void setTileType(TileType tileType) {
this.tileType = tileType;
}
// Return the tileType
public TileType getTileType() {
return this.tileType;
}
// Set the tile ID
public void setId(int id) {
this.id = id;
}
// Return the tile ID
public int getId() {
return this.id;
}
// Set the position of the tile with Vector2i
public void setPosition(Vector2i a) {
this.position = a;
}
// Set the position of the tile with int
public void setPosition(int x, int y) {
setPosition(new Vector2i(x,y));
}
// Return the position of the tile
public Vector2i getPosition() {
return this.position;
}
}
| CityBuilderJSFML/src/graphics/Tile.java | package graphics;
import org.jsfml.system.Vector2i;
/*
* Represents a tile
*/
public class Tile {
// Enum of each tileType
public static enum TileType {
TERRAIN_GRASS,
BUILDING_HOUSE,
BUILDING_SUPERMARKET,
BUILDING_ROAD,
BUILDING_GENERATOR
}
// Attributes.
protected TileType tileType;
protected int id;
protected Vector2i position;
// Set the tileType
public void setTileType(TileType tileType) {
this.tileType = tileType;
}
// Return the tileType
public TileType getTileType() {
return this.tileType;
}
// Set the tile ID
public void setId(int id) {
this.id = id;
}
// Return the tile ID
public int getId() {
return this.id;
}
// Set the position of the tile with Vector2i
public void setPosition(Vector2i a) {
this.position = a;
}
// Set the position of the tile with int
public void setPosition(int x, int y) {
setPosition(new Vector2i(x,y));
}
// Return the position of the tile
public Vector2i getPosition() {
return this.position;
}
}
| Ajout d'un constructeur à la classe Tile. | CityBuilderJSFML/src/graphics/Tile.java | Ajout d'un constructeur à la classe Tile. | <ide><path>ityBuilderJSFML/src/graphics/Tile.java
<ide> BUILDING_ROAD,
<ide> BUILDING_GENERATOR
<ide> }
<add>
<add> // Track the last id.
<add> protected static int lastId = 0;
<ide>
<ide> // Attributes.
<ide> protected TileType tileType;
<ide> protected int id;
<ide> protected Vector2i position;
<add>
<add> // Constructor.
<add> public Tile(TileType tileType, Vector2i position) {
<add> this.tileType = tileType;
<add> this.id = Tile.lastId;
<add> this.position = position;
<add>
<add> // Increment the last id.
<add> Tile.lastId++;
<add> }
<ide>
<ide> // Set the tileType
<ide> public void setTileType(TileType tileType) { |
|
Java | apache-2.0 | 903e4c14a32d17e4479c6b19cca99f01414b980a | 0 | jjhaggar/ninja-trials | /*
* Ninja Trials is an old school style Android Game developed for OUYA & using
* AndEngine. It features several minigames with simple gameplay.
* Copyright 2013 Mad Gear Games <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.madgear.ninjatrials.managers;
import org.andengine.audio.music.Music;
import org.andengine.audio.sound.Sound;
public class SFXManager {
private static float soundVolume = 0.7f;
private static float musicVolume = 0.7f;
// Sound control ------------------------------
public static void playSound(Sound s) {
if(s != null && s.isLoaded()) {
s.setVolume(getSoundVolume());
s.play();
}
}
public static void playSoundLoop(Sound s) {
if(s != null && s.isLoaded()) {
s.setVolume(getSoundVolume());
s.setLooping(true);
s.play();
}
}
public static void stopSound(Sound s) {
if(s != null && s.isLoaded()) {
s.stop();
}
}
public static float getSoundVolume() {
return soundVolume;
}
public static void setSoundVolume(float v) {
soundVolume = v;
}
public static void addSoundVolume(float v) {
soundVolume += v;
if(soundVolume > 1) soundVolume = 1;
if(soundVolume < 0) soundVolume = 0;
}
// Music Control --------------------------------
/**
* Begins playing music.
* @param m
*/
public static void playMusic(Music m) {
if(m != null && !m.isPlaying()) {
m.setVolume(getMusicVolume());
m.play();
}
}
/**
* Play music in looping.
* @param m
*/
public static void playMusicLoop(Music m) {
if(m != null && !m.isPlaying()) {
m.setVolume(getMusicVolume());
m.setLooping(true);
m.play();
}
}
public static boolean isPlaying(Music m) {
return m.isPlaying();
}
/**
* Pause music. May be resumed.
* @param m
*/
public static void pauseMusic(Music m) {
if(m != null && m.isPlaying())
m.pause();
}
/**
* Stops music and sets the tune to the begining.
* @param m
*/
public static void stopMusic(Music m) {
if(m != null && m.isPlaying()) {
m.pause();
m.seekTo(0);
}
}
/**
* Resume Music (works with pauseMusic).
* @param m
*/
public static void resumeMusic(Music m) {
m.setVolume(getMusicVolume());
m.resume();
}
public static float getMusicVolume() {
return musicVolume;
}
public static void setMusicVolume(float v) {
musicVolume = v;
}
public static void addMusicVolume(float v) {
musicVolume += v;
if(musicVolume > 1) musicVolume = 1;
if(musicVolume < 0) musicVolume = 0;
}
}
| src/com/madgear/ninjatrials/managers/SFXManager.java | /*
* Ninja Trials is an old school style Android Game developed for OUYA & using
* AndEngine. It features several minigames with simple gameplay.
* Copyright 2013 Mad Gear Games <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.madgear.ninjatrials.managers;
import org.andengine.audio.music.Music;
import org.andengine.audio.sound.Sound;
public class SFXManager {
private static float soundVolume = 0.7f;
private static float musicVolume = 0.7f;
// Sound control ------------------------------
public static void playSound(Sound s) {
if(s != null && s.isLoaded()) {
s.setVolume(getSoundVolume());
s.play();
}
}
public static void playSoundLoop(Sound s) {
if(s != null && s.isLoaded()) {
s.setVolume(getSoundVolume());
s.setLooping(true);
s.play();
}
}
public static void stopSound(Sound s) {
if(s != null && s.isLoaded()) {
s.stop();
}
}
public static float getSoundVolume() {
return soundVolume;
}
public static void setSoundVolume(float v) {
soundVolume = v;
}
public static void addSoundVolume(float v) {
soundVolume += v;
if(soundVolume > 1) soundVolume = 1;
if(soundVolume < 0) soundVolume = 0;
}
// Music Control --------------------------------
public static void playMusic(Music m) {
if(m != null && !m.isPlaying()) {
m.setVolume(getMusicVolume());
m.play();
}
}
public static boolean isPlaying(Music m) {
return m.isPlaying();
}
public static void pauseMusic(Music m) {
if(m != null && m.isPlaying())
m.pause();
}
public static void resumeMusic(Music m) {
m.setVolume(getMusicVolume());
m.resume();
}
public static float getMusicVolume() {
return musicVolume;
}
public static void setMusicVolume(float v) {
musicVolume = v;
}
public static void addMusicVolume(float v) {
musicVolume += v;
if(musicVolume > 1) musicVolume = 1;
if(musicVolume < 0) musicVolume = 0;
}
}
| Added playMusicLoop method and stopMusic.
| src/com/madgear/ninjatrials/managers/SFXManager.java | Added playMusicLoop method and stopMusic. | <ide><path>rc/com/madgear/ninjatrials/managers/SFXManager.java
<ide>
<ide> // Music Control --------------------------------
<ide>
<add> /**
<add> * Begins playing music.
<add> * @param m
<add> */
<ide> public static void playMusic(Music m) {
<ide> if(m != null && !m.isPlaying()) {
<ide> m.setVolume(getMusicVolume());
<add> m.play();
<add> }
<add> }
<add>
<add> /**
<add> * Play music in looping.
<add> * @param m
<add> */
<add> public static void playMusicLoop(Music m) {
<add> if(m != null && !m.isPlaying()) {
<add> m.setVolume(getMusicVolume());
<add> m.setLooping(true);
<ide> m.play();
<ide> }
<ide> }
<ide> return m.isPlaying();
<ide> }
<ide>
<add> /**
<add> * Pause music. May be resumed.
<add> * @param m
<add> */
<ide> public static void pauseMusic(Music m) {
<ide> if(m != null && m.isPlaying())
<ide> m.pause();
<ide> }
<ide>
<add> /**
<add> * Stops music and sets the tune to the begining.
<add> * @param m
<add> */
<add> public static void stopMusic(Music m) {
<add> if(m != null && m.isPlaying()) {
<add> m.pause();
<add> m.seekTo(0);
<add> }
<add> }
<add>
<add> /**
<add> * Resume Music (works with pauseMusic).
<add> * @param m
<add> */
<ide> public static void resumeMusic(Music m) {
<ide> m.setVolume(getMusicVolume());
<ide> m.resume(); |
|
Java | mit | f08ccefd55a70754b197eaea5f7de43b94d5696b | 0 | TVPT/VoxelGunsmith,Featherblade/VoxelGunsmith | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 The Voxel Plugineering Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.voxelplugineering.voxelsniper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.voxelplugineering.voxelsniper.api.event.EventHandler;
import com.voxelplugineering.voxelsniper.api.event.EventPriority;
import com.voxelplugineering.voxelsniper.api.event.EventThreadingPolicy;
import com.voxelplugineering.voxelsniper.api.event.EventThreadingPolicy.ThreadingPolicy;
import com.voxelplugineering.voxelsniper.api.event.bus.EventBus;
import com.voxelplugineering.voxelsniper.event.DeadEvent;
import com.voxelplugineering.voxelsniper.event.Event;
import com.voxelplugineering.voxelsniper.event.bus.AsyncEventBus;
import com.voxelplugineering.voxelsniper.logging.PrintStreamLogger;
/**
* Tests for the {@link AsyncEventBus} implementation.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(Gunsmith.class)
public class EventBusTest
{
/**
*
*/
@BeforeClass
public static void setupClass()
{
PrintStreamLogger logger = new PrintStreamLogger(System.out);
PowerMockito.mockStatic(Gunsmith.class);
Mockito.when(Gunsmith.getLogger()).thenReturn(logger);
}
/**
*
*/
@Test
public void basicTest()
{
EventBus bus = new AsyncEventBus();
TestHandler handler = new TestHandler();
bus.register(handler);
bus.post(new TestEvent());
assertEquals(true, handler.found);
bus.unregister(handler);
}
/**
*
*/
@Test
public void priorityTest()
{
EventBus bus = new AsyncEventBus();
PriorityHandler handler = new PriorityHandler();
bus.register(handler);
bus.post(new TestEvent());
assertEquals("abcde", handler.order);
bus.unregister(handler);
}
/**
*
*/
@Test
public void superEventhandling()
{
EventBus bus = new AsyncEventBus();
SuperHandler handler = new SuperHandler();
bus.register(handler);
bus.post(new SubEvent());
assertEquals(3, handler.count);
bus.unregister(handler);
}
/**
*
*/
@Test
public void superEventhandling2()
{
EventBus bus = new AsyncEventBus();
SuperHandler handler = new SuperHandler();
bus.register(handler);
bus.post(new TestEvent());
assertEquals(2, handler.count);
bus.unregister(handler);
}
/**
* @throws InterruptedException
*/
@Test
public void testDeadEvent() throws InterruptedException
{
EventBus bus = new AsyncEventBus();
DeadEventHandler handler = new DeadEventHandler();
bus.register(handler);
bus.post(new TestEvent());
//This timeout is required as AsyncEventBus#post will return immediately upon posting the dead event,
//so we must wait for the dead event to be handled.
long timeout = 1000;
while (timeout > 0 && !handler.dead)
{
Thread.sleep(50);
timeout -= 50;
}
assertEquals(true, handler.dead);
bus.unregister(handler);
}
/**
*
*/
@Test
public void testNotAsync()
{
EventBus bus = new AsyncEventBus();
SyncHandler handler = new SyncHandler();
bus.register(handler);
SyncEvent e = new SyncEvent();
bus.post(e);
assertEquals(Thread.currentThread(), handler.thread);
bus.unregister(handler);
}
/**
*
*/
@Test
public void testAsync()
{
EventBus bus = new AsyncEventBus();
AsyncHandler handler = new AsyncHandler();
bus.register(handler);
bus.post(new AsyncEvent());
assertNotEquals(Thread.currentThread(), handler.thread);
bus.unregister(handler);
}
//=======================================================================
/**
*
*/
public static class TestHandler
{
protected boolean found = false;
/**
* @param event The event
*/
@EventHandler
public void onTestEvent(TestEvent event)
{
this.found = true;
}
}
/**
*
*/
public static class AsyncHandler
{
protected Thread thread = null;
/**
* @param event The event
*/
@EventHandler
public void onTestEvent(AsyncEvent event)
{
this.thread = Thread.currentThread();
}
}
/**
*
*/
public static class SyncHandler
{
protected Thread thread = null;
/**
* @param event The event
*/
@EventHandler
public void onTestEvent(SyncEvent event)
{
this.thread = Thread.currentThread();
}
}
/**
*
*/
public static class PriorityHandler
{
protected String order = "";
/**
* @param event The event
*/
@EventHandler(EventPriority.HIGHEST)
public void onTestEventa(TestEvent event)
{
this.order += "a";
}
/**
* @param event The event
*/
@EventHandler(EventPriority.HIGH)
public void onTestEventb(TestEvent event)
{
this.order += "b";
}
/**
* @param event The event
*/
@EventHandler
public void onTestEventc(TestEvent event)
{
this.order += "c";
}
/**
* @param event The event
*/
@EventHandler(EventPriority.LOW)
public void onTestEventd(TestEvent event)
{
this.order += "d";
}
/**
* @param event The event
*/
@EventHandler(EventPriority.LOWEST)
public void onTestEvente(TestEvent event)
{
this.order += "e";
}
}
/**
*
*/
public static class SuperHandler
{
protected int count = 0;
/**
* @param event The event
*/
@EventHandler
public void onTestEvent(SubEvent event)
{
this.count++;
}
/**
* @param event The event
*/
@EventHandler
public void onTestEvent(TestEvent event)
{
this.count++;
}
/**
* @param event The event
*/
@EventHandler
public void onTestEvent(Event event)
{
this.count++;
}
}
/**
*
*/
public static class DeadEventHandler
{
protected boolean dead = false;
/**
* @param event The event
*/
@EventHandler
public void onDeadEvent(DeadEvent event)
{
this.dead = true;
}
}
/**
*
*/
public static class TestEvent extends Event
{
}
/**
*
*/
public static class SubEvent extends TestEvent
{
}
/**
*
*/
@EventThreadingPolicy(ThreadingPolicy.ASYNCHRONOUS)
public static class AsyncEvent extends Event
{
}
/**
*
*/
@EventThreadingPolicy(ThreadingPolicy.SYNCHRONIZED)
public static class SyncEvent extends Event
{
}
}
| src/test/java/com/voxelplugineering/voxelsniper/EventBusTest.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 The Voxel Plugineering Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.voxelplugineering.voxelsniper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.voxelplugineering.voxelsniper.api.event.EventHandler;
import com.voxelplugineering.voxelsniper.api.event.EventPriority;
import com.voxelplugineering.voxelsniper.api.event.EventThreadingPolicy;
import com.voxelplugineering.voxelsniper.api.event.EventThreadingPolicy.ThreadingPolicy;
import com.voxelplugineering.voxelsniper.api.event.bus.EventBus;
import com.voxelplugineering.voxelsniper.event.DeadEvent;
import com.voxelplugineering.voxelsniper.event.Event;
import com.voxelplugineering.voxelsniper.event.bus.AsyncEventBus;
import com.voxelplugineering.voxelsniper.logging.PrintStreamLogger;
/**
* Tests for the {@link AsyncEventBus} implementation.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(Gunsmith.class)
public class EventBusTest
{
/**
*
*/
@BeforeClass
public static void setupClass()
{
PrintStreamLogger logger = new PrintStreamLogger(System.out);
PowerMockito.mockStatic(Gunsmith.class);
Mockito.when(Gunsmith.getLogger()).thenReturn(logger);
}
/**
*
*/
@Test
public void basicTest()
{
EventBus bus = new AsyncEventBus();
TestHandler handler = new TestHandler();
bus.register(handler);
bus.post(new TestEvent());
assertEquals(true, handler.found);
bus.unregister(handler);
}
/**
*
*/
@Test
public void priorityTest()
{
EventBus bus = new AsyncEventBus();
PriorityHandler handler = new PriorityHandler();
bus.register(handler);
bus.post(new TestEvent());
assertEquals("abcde", handler.order);
bus.unregister(handler);
}
/**
*
*/
@Test
public void superEventhandling()
{
EventBus bus = new AsyncEventBus();
SuperHandler handler = new SuperHandler();
bus.register(handler);
bus.post(new SubEvent());
assertEquals(3, handler.count);
bus.unregister(handler);
}
/**
*
*/
@Test
public void superEventhandling2()
{
EventBus bus = new AsyncEventBus();
SuperHandler handler = new SuperHandler();
bus.register(handler);
bus.post(new TestEvent());
assertEquals(2, handler.count);
bus.unregister(handler);
}
/**
* @throws InterruptedException
*/
@Test
public void testDeadEvent() throws InterruptedException
{
EventBus bus = new AsyncEventBus();
DeadEventHandler handler = new DeadEventHandler();
bus.register(handler);
bus.post(new TestEvent());
long timeout = 1000;
while(timeout > 0 && !handler.dead)
{
Thread.sleep(100);
timeout -= 100;
}
assertEquals(true, handler.dead);
bus.unregister(handler);
}
/**
*
*/
@Test
public void testNotAsync()
{
EventBus bus = new AsyncEventBus();
SyncHandler handler = new SyncHandler();
bus.register(handler);
SyncEvent e = new SyncEvent();
bus.post(e);
assertEquals(Thread.currentThread(), handler.thread);
bus.unregister(handler);
}
/**
*
*/
@Test
public void testAsync()
{
EventBus bus = new AsyncEventBus();
AsyncHandler handler = new AsyncHandler();
bus.register(handler);
bus.post(new AsyncEvent());
assertNotEquals(Thread.currentThread(), handler.thread);
bus.unregister(handler);
}
//=======================================================================
/**
*
*/
public static class TestHandler
{
protected boolean found = false;
/**
* @param event The event
*/
@EventHandler
public void onTestEvent(TestEvent event)
{
this.found = true;
}
}
/**
*
*/
public static class AsyncHandler
{
protected Thread thread = null;
/**
* @param event The event
*/
@EventHandler
public void onTestEvent(AsyncEvent event)
{
this.thread = Thread.currentThread();
}
}
/**
*
*/
public static class SyncHandler
{
protected Thread thread = null;
/**
* @param event The event
*/
@EventHandler
public void onTestEvent(SyncEvent event)
{
this.thread = Thread.currentThread();
}
}
/**
*
*/
public static class PriorityHandler
{
protected String order = "";
/**
* @param event The event
*/
@EventHandler(EventPriority.HIGHEST)
public void onTestEventa(TestEvent event)
{
this.order += "a";
}
/**
* @param event The event
*/
@EventHandler(EventPriority.HIGH)
public void onTestEventb(TestEvent event)
{
this.order += "b";
}
/**
* @param event The event
*/
@EventHandler
public void onTestEventc(TestEvent event)
{
this.order += "c";
}
/**
* @param event The event
*/
@EventHandler(EventPriority.LOW)
public void onTestEventd(TestEvent event)
{
this.order += "d";
}
/**
* @param event The event
*/
@EventHandler(EventPriority.LOWEST)
public void onTestEvente(TestEvent event)
{
this.order += "e";
}
}
/**
*
*/
public static class SuperHandler
{
protected int count = 0;
/**
* @param event The event
*/
@EventHandler
public void onTestEvent(SubEvent event)
{
this.count++;
}
/**
* @param event The event
*/
@EventHandler
public void onTestEvent(TestEvent event)
{
this.count++;
}
/**
* @param event The event
*/
@EventHandler
public void onTestEvent(Event event)
{
this.count++;
}
}
/**
*
*/
public static class DeadEventHandler
{
protected boolean dead = false;
/**
* @param event The event
*/
@EventHandler
public void onDeadEvent(DeadEvent event)
{
this.dead = true;
}
}
/**
*
*/
public static class TestEvent extends Event
{
}
/**
*
*/
public static class SubEvent extends TestEvent
{
}
/**
*
*/
@EventThreadingPolicy(ThreadingPolicy.ASYNCHRONOUS)
public static class AsyncEvent extends Event
{
}
/**
*
*/
@EventThreadingPolicy(ThreadingPolicy.SYNCHRONIZED)
public static class SyncEvent extends Event
{
}
}
| dead event test documentation
| src/test/java/com/voxelplugineering/voxelsniper/EventBusTest.java | dead event test documentation | <ide><path>rc/test/java/com/voxelplugineering/voxelsniper/EventBusTest.java
<ide> DeadEventHandler handler = new DeadEventHandler();
<ide> bus.register(handler);
<ide> bus.post(new TestEvent());
<add> //This timeout is required as AsyncEventBus#post will return immediately upon posting the dead event,
<add> //so we must wait for the dead event to be handled.
<ide> long timeout = 1000;
<del> while(timeout > 0 && !handler.dead)
<del> {
<del> Thread.sleep(100);
<del> timeout -= 100;
<add> while (timeout > 0 && !handler.dead)
<add> {
<add> Thread.sleep(50);
<add> timeout -= 50;
<ide> }
<ide> assertEquals(true, handler.dead);
<ide> bus.unregister(handler); |
|
Java | apache-2.0 | e3a488f41c22321cc5e48738a2ff684eb36354ea | 0 | golfstream83/JavaCourse | package calculator;
public class Calculator {
public double result;
/*
сложение двух чисел
*/
public void add (double first, double second) {
this.result = first + second;
}
/*
вычитание из числа first числа second
*/
public void substruct (double first, double second) {
this.result = first - second;
}
/*
деление числа first на число second
*/
public void div (double first, double second) {
this.result = first / second;
}
/*
умножение числа first на число second
*/
public void multiple (double first, double second) {
this.result = first * second;
}
public void showResult() {
System.out.printf("%s%f%n" ,"Result : ", this.result);
}
} | calculator/Calculator.java | package calculator;
public class Calculator {
public double result;
/*
сложение двух чисел
*/
public void add (double first, double second) {
this.result = first + second;
}
/*
вычитание из числа first числа second
*/
public void substruct (double first, double second) {
this.result = first - second;
}
/*
деление числа first на число second
*/
public void div (double first, double second) {
this.result = first / second;
}
/*
умножение числа first на число second
*/
public void multiple (double first, double second) {
this.result = first * second;
}
public void showResult() {
System.out.println("Result : " + this.result);
}
} | Update Calulator.java
| calculator/Calculator.java | Update Calulator.java | <ide><path>alculator/Calculator.java
<ide> }
<ide>
<ide> public void showResult() {
<del> System.out.println("Result : " + this.result);
<add> System.out.printf("%s%f%n" ,"Result : ", this.result);
<ide> }
<ide> } |
|
Java | apache-2.0 | 988b99160e012318c165092271c79421cbc45152 | 0 | googleinterns/step87-2020,googleinterns/step87-2020,googleinterns/step87-2020,googleinterns/step87-2020 | package com.google.sps.servlets;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.EmbeddedEntity;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilter;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.datastore.TransactionOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import com.google.sps.ApplicationDefaults;
import com.google.sps.firebase.FirebaseAppManager;
import com.google.sps.workspace.Workspace;
import com.google.sps.workspace.WorkspaceFactory;
import java.io.IOException;
import java.time.Clock;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/enterqueue")
public final class EnterQueue extends HttpServlet {
private FirebaseAuth authInstance;
private DatastoreService datastore;
private WorkspaceFactory workspaceFactory;
private Clock clock;
@Override
public void init(ServletConfig config) throws ServletException {
workspaceFactory = WorkspaceFactory.getInstance();
try {
authInstance = FirebaseAuth.getInstance(FirebaseAppManager.getApp());
clock = Clock.systemUTC();
} catch (IOException e) {
throw new ServletException(e);
}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Get the input from the form.
datastore = DatastoreServiceFactory.getDatastoreService();
try {
String classCode = request.getParameter("classCode").trim();
String idToken = request.getParameter("idToken");
FirebaseToken decodedToken = authInstance.verifyIdToken(idToken);
String userID = decodedToken.getUid();
String userEmail = decodedToken.getEmail();
Entity userEntity =
datastore
.prepare(
new Query("User")
.setFilter(new FilterPredicate("userEmail", FilterOperator.EQUAL, userEmail)))
.asSingleEntity();
Key classKey = KeyFactory.stringToKey(classCode);
List<Key> registered = (List<Key>) userEntity.getProperty("registeredClasses");
List<Key> ta = (List<Key>) userEntity.getProperty("taClasses");
List<Key> owned = (List<Key>) userEntity.getProperty("ownedClasses");
if (registered.contains(classKey)) {
int retries = 10;
while (true) {
TransactionOptions options = TransactionOptions.Builder.withXG(true);
Transaction txn = datastore.beginTransaction(options);
try {
Entity classEntity = datastore.get(txn, classKey);
// Get date
LocalDate localDate = LocalDate.now(clock);
ZoneId defaultZoneId = ZoneId.systemDefault();
Date currDate = Date.from(localDate.atStartOfDay(defaultZoneId).toInstant());
// Get time
LocalDateTime localTime = LocalDateTime.now(clock);
Date currTime = Date.from(localTime.atZone(defaultZoneId).toInstant());
// Query visit entity for particular day
Filter classVisitFilter =
new FilterPredicate("classKey", FilterOperator.EQUAL, classKey);
Filter dateVisitFilter = new FilterPredicate("date", FilterOperator.EQUAL, currDate);
CompositeFilter visitFilter =
CompositeFilterOperator.and(dateVisitFilter, classVisitFilter);
PreparedQuery query = datastore.prepare(new Query("Visit").setFilter(visitFilter));
// Get visit entity for particular day
Entity visitEntity;
if (query.countEntities() == 0) {
visitEntity = new Entity("Visit");
visitEntity.setProperty("classKey", classKey);
visitEntity.setProperty("date", currDate);
visitEntity.setProperty("numVisits", (long) 0);
} else {
visitEntity = query.asSingleEntity();
}
long numVisits = (long) visitEntity.getProperty("numVisits");
List<EmbeddedEntity> updatedQueue =
(List<EmbeddedEntity>) classEntity.getProperty("studentQueue");
// Update studentQueue and numVisit properties if student not already in queue
if (!updatedQueue.stream()
.filter(elem -> elem.hasProperty(userID))
.findFirst()
.isPresent()) {
// create new student entity to add to queue
EmbeddedEntity queueInfo = new EmbeddedEntity();
EmbeddedEntity studentInfo = new EmbeddedEntity();
studentInfo.setProperty("timeEntered", currTime);
Workspace w = workspaceFactory.create(classCode);
w.setStudentUID(userID);
studentInfo.setProperty("workspaceID", w.getWorkspaceID());
queueInfo.setProperty(userID, studentInfo);
updatedQueue.add(queueInfo);
numVisits++;
}
visitEntity.setProperty("numVisits", numVisits);
datastore.put(txn, visitEntity);
classEntity.setProperty("studentQueue", updatedQueue);
datastore.put(txn, classEntity);
txn.commit();
break;
} catch (ConcurrentModificationException e) {
if (retries == 0) {
throw e;
}
// Allow retry to occur
--retries;
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
response.addHeader("Location", ApplicationDefaults.STUDENT_QUEUE + classCode);
} else if (owned.contains(classKey) || ta.contains(classKey)) {
response.addHeader("Location", ApplicationDefaults.TA_QUEUE + classCode);
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
} catch (EntityNotFoundException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (IllegalArgumentException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
} catch (FirebaseAuthException e) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
} catch (InterruptedException | ExecutionException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
}
| src/main/java/com/google/sps/servlets/EnterQueue.java | package com.google.sps.servlets;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.EmbeddedEntity;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilter;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.datastore.TransactionOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import com.google.firebase.auth.UserRecord;
import com.google.sps.ApplicationDefaults;
import com.google.sps.firebase.FirebaseAppManager;
import com.google.sps.workspace.Workspace;
import com.google.sps.workspace.WorkspaceFactory;
import java.io.IOException;
import java.time.Clock;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/enterqueue")
public final class EnterQueue extends HttpServlet {
private FirebaseAuth authInstance;
private DatastoreService datastore;
private WorkspaceFactory workspaceFactory;
private Clock clock;
@Override
public void init(ServletConfig config) throws ServletException {
workspaceFactory = WorkspaceFactory.getInstance();
try {
authInstance = FirebaseAuth.getInstance(FirebaseAppManager.getApp());
clock = Clock.systemUTC();
} catch (IOException e) {
throw new ServletException(e);
}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Get the input from the form.
datastore = DatastoreServiceFactory.getDatastoreService();
try {
String classCode = request.getParameter("classCode").trim();
String idToken = request.getParameter("idToken");
FirebaseToken decodedToken = authInstance.verifyIdToken(idToken);
String userID = decodedToken.getUid();
String userEmail = decodedToken.getEmail();
Entity userEntity =
datastore
.prepare(
new Query("User")
.setFilter(new FilterPredicate("userEmail", FilterOperator.EQUAL, userEmail)))
.asSingleEntity();
Key classKey = KeyFactory.stringToKey(classCode);
List<Key> registered = (List<Key>) userEntity.getProperty("registeredClasses");
List<Key> ta = (List<Key>) userEntity.getProperty("taClasses");
List<Key> owned = (List<Key>) userEntity.getProperty("ownedClasses");
if (registered.contains(classKey)) {
int retries = 10;
while (true) {
TransactionOptions options = TransactionOptions.Builder.withXG(true);
Transaction txn = datastore.beginTransaction(options);
try {
Entity classEntity = datastore.get(txn, classKey);
// Get date
LocalDate localDate = LocalDate.now(clock);
ZoneId defaultZoneId = ZoneId.systemDefault();
Date currDate = Date.from(localDate.atStartOfDay(defaultZoneId).toInstant());
// Get time
LocalDateTime localTime = LocalDateTime.now(clock);
Date currTime = Date.from(localTime.atZone(defaultZoneId).toInstant());
// Query visit entity for particular day
Filter classVisitFilter =
new FilterPredicate("classKey", FilterOperator.EQUAL, classKey);
Filter dateVisitFilter = new FilterPredicate("date", FilterOperator.EQUAL, currDate);
CompositeFilter visitFilter =
CompositeFilterOperator.and(dateVisitFilter, classVisitFilter);
PreparedQuery query = datastore.prepare(new Query("Visit").setFilter(visitFilter));
// Get visit entity for particular day
Entity visitEntity;
if (query.countEntities() == 0) {
visitEntity = new Entity("Visit");
visitEntity.setProperty("classKey", classKey);
visitEntity.setProperty("date", currDate);
visitEntity.setProperty("numVisits", (long) 0);
} else {
visitEntity = query.asSingleEntity();
}
long numVisits = (long) visitEntity.getProperty("numVisits");
List<EmbeddedEntity> updatedQueue =
(List<EmbeddedEntity>) classEntity.getProperty("studentQueue");
// Update studentQueue and numVisit properties if student not already in queue
if (!updatedQueue.stream()
.filter(elem -> elem.hasProperty(userID))
.findFirst()
.isPresent()) {
// create new student entity to add to queue
EmbeddedEntity queueInfo = new EmbeddedEntity();
EmbeddedEntity studentInfo = new EmbeddedEntity();
studentInfo.setProperty("timeEntered", currTime);
Workspace w = workspaceFactory.create(classCode);
w.setStudentUID(userID);
studentInfo.setProperty("workspaceID", w.getWorkspaceID());
queueInfo.setProperty(userID, studentInfo);
updatedQueue.add(queueInfo);
numVisits++;
}
visitEntity.setProperty("numVisits", numVisits);
datastore.put(txn, visitEntity);
classEntity.setProperty("studentQueue", updatedQueue);
datastore.put(txn, classEntity);
txn.commit();
break;
} catch (ConcurrentModificationException e) {
if (retries == 0) {
throw e;
}
// Allow retry to occur
--retries;
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
response.addHeader("Location", ApplicationDefaults.STUDENT_QUEUE + classCode);
} else if (owned.contains(classKey) || ta.contains(classKey)) {
response.addHeader("Location", ApplicationDefaults.TA_QUEUE + classCode);
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
} catch (EntityNotFoundException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (IllegalArgumentException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
} catch (FirebaseAuthException e) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
} catch (InterruptedException | ExecutionException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
}
| Remove unused import.
| src/main/java/com/google/sps/servlets/EnterQueue.java | Remove unused import. | <ide><path>rc/main/java/com/google/sps/servlets/EnterQueue.java
<ide> import com.google.firebase.auth.FirebaseAuth;
<ide> import com.google.firebase.auth.FirebaseAuthException;
<ide> import com.google.firebase.auth.FirebaseToken;
<del>import com.google.firebase.auth.UserRecord;
<ide> import com.google.sps.ApplicationDefaults;
<ide> import com.google.sps.firebase.FirebaseAppManager;
<ide> import com.google.sps.workspace.Workspace; |
|
Java | apache-2.0 | error: pathspec 'src/com/strobel/core/Fences.java' did not match any file(s) known to git
| eaf3db3e5fea8c9d2ece1975e718eb0c8eaad87c | 1 | Thog/Procyon | package com.strobel.core;
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
/**
* A set of methods providing fine-grained control over happens-before
* and synchronization order relations among reads and/or writes. The
* methods of this class are designed for use in uncommon situations
* where declaring variables {@code volatile} or {@code final}, using
* instances of atomic classes, using {@code synchronized} blocks or
* methods, or using other synchronization facilities are not possible
* or do not provide the desired control.
*
* <p><b>Memory Ordering.</b> There are three methods for controlling
* ordering relations among memory accesses (i.e., reads and
* writes). Method {@code orderWrites} is typically used to enforce
* order between two writes, and {@code orderAccesses} between a write
* and a read. Method {@code orderReads} is used to enforce order
* between two reads with respect to other {@code orderWrites} and/or
* {@code orderAccesses} invocations. The formally specified
* properties of these methods described below provide
* platform-independent guarantees that are honored by all levels of a
* platform (compilers, systems, processors). The use of these
* methods may result in the suppression of otherwise valid compiler
* transformations and optimizations that could visibly violate the
* specified orderings, and may or may not entail the use of
* processor-level "memory barrier" instructions.
*
* <p>Each ordering method accepts a {@code ref} argument, and
* controls ordering among accesses with respect to this reference.
* Invocations must be placed <em>between</em> accesses performed in
* expression evaluations and assignment statements to control the
* orderings of prior versus subsequent accesses appearing in program
* order. These methods also return their arguments to simplify
* correct usage in these contexts.
*
* <p>Usages of ordering methods almost always take one of the forms
* illustrated in the examples below. These idioms arrange some of
* the ordering properties associated with {@code volatile} and
* related language-based constructions, but without other
* compile-time and runtime benefits that make language-based
* constructions far better choices when they are applicable. Usages
* should be restricted to the control of strictly internal
* implementation matters inside a class or package, and must either
* avoid or document any consequent violations of ordering or safety
* properties expected by users of a class employing them.
*
* <p><b>Reachability.</b> Method {@code reachabilityFence}
* establishes an ordering for strong reachability (as defined in the
* {@link java.lang.ref} package specification) with respect to
* garbage collection. Method {@code reachabilityFence} differs from
* the others in that it controls relations that are otherwise only
* implicit in a program -- the reachability conditions triggering
* garbage collection. As illustrated in the sample usages below,
* this method is applicable only when reclamation may have visible
* effects, which is possible for objects with finalizers (see Section
* 12.6 of the Java Language Specification) that are implemented in
* ways that rely on ordering control for correctness.
*
* <p><b>Sample Usages</b>
*
* <p><b>Safe publication.</b> With care, method {@code orderWrites}
* may be used to obtain the memory safety effects of {@code final}
* for a field that cannot be declared as {@code final}, because its
* primary initialization cannot be performed in a constructor, in
* turn because it is used in a framework requiring that all classes
* have a no-argument constructor; as in:
*
* <pre>
* class WidgetHolder {
* private Widget widget;
* public WidgetHolder() {}
* public static WidgetHolder newWidgetHolder(Params params) {
* WidgetHolder h = new WidgetHolder();
* h.widget = new Widget(params);
* return Fences.orderWrites(h);
* }
* }
* </pre>
*
* Here, the invocation of {@code orderWrites} ensures that the
* effects of the widget assignment are ordered before those of any
* (unknown) subsequent stores of {@code h} in other variables that
* make {@code h} available for use by other objects. Initialization
* sequences using {@code orderWrites} require more care than those
* involving {@code final} fields. When {@code final} is not used,
* compilers cannot help you to ensure that the field is set correctly
* across all usages. You must fully initialize objects
* <em>before</em> the {@code orderWrites} invocation that makes
* references to them safe to assign to accessible variables. Further,
* initialization sequences must not internally "leak" the reference
* by using it as an argument to a callback method or adding it to a
* static data structure. If less constrained usages were required,
* it may be possible to cope using more extensive sets of fences, or
* as a normally better choice, using synchronization (locking).
* Conversely, if it were possible to do so, the best option would be
* to rewrite class {@code WidgetHolder} to use {@code final}.
*
* <p>An alternative approach is to place similar mechanics in the
* (sole) method that makes such objects available for use by others.
* Here is a stripped-down example illustrating the essentials. In
* practice, among other changes, you would use access methods instead
* of a public field.
*
* <pre>
* class AnotherWidgetHolder {
* public Widget widget;
* void publish(Widget w) {
* this.widget = Fences.orderWrites(w);
* }
* // ...
* }
* </pre>
*
* In this case, the {@code orderWrites} invocation occurs before the
* store making the object available. Correctness again relies on
* ensuring that there are no leaks prior to invoking this method, and
* that it really is the <em>only</em> means of accessing the
* published object. This approach is not often applicable --
* normally you would publish objects using a thread-safe collection
* that itself guarantees the expected ordering relations. However, it
* may come into play in the construction of such classes themselves.
*
* <p><b>Safely updating fields.</b> Outside of the initialization
* idioms illustrated above, Fence methods ordering writes must be
* paired with those ordering reads. To illustrate, suppose class
* {@code c} contains an accessible variable {@code data} that should
* have been declared as {@code volatile} but wasn't:
*
* <pre>
* class C {
* Object data; // need volatile access but not volatile
* // ...
* }
*
* class App {
* Object getData(C c) {
* return Fences.orderReads(c).data;
* }
*
* void setData(C c) {
* Object newValue = ...;
* c.data = Fences.orderWrites(newValue);
* Fences.orderAccesses(c);
* }
* // ...
* }
* </pre>
*
* Method {@code getData} provides an emulation of {@code volatile}
* reads of (non-long/double) fields by ensuring that the read of
* {@code c} obtained as an argument is ordered before subsequent
* reads using this reference, and then performs the read of its
* field. Method {@code setData} provides an emulation of volatile
* writes, ensuring that all other relevant writes have completed,
* then performing the assignment, and then ensuring that the write is
* ordered before any other access. These techniques may apply even
* when fields are not directly accessible, in which case calls to
* fence methods would surround calls to methods such as {@code
* c.getData()}. However, these techniques cannot be applied to
* {@code long} or {@code double} fields because reads and writes of
* fields of these types are not guaranteed to be
* atomic. Additionally, correctness may require that all accesses of
* such data use these kinds of wrapper methods, which you would need
* to manually ensure.
*
* <p>More generally, Fence methods can be used in this way to achieve
* the safety properties of {@code volatile}. However their use does
* not necessarily guarantee the full sequential consistency
* properties specified in the Java Language Specification chapter 17
* for programs using {@code volatile}. In particular, emulation using
* Fence methods is not guaranteed to maintain the property that
* {@code volatile} operations performed by different threads are
* observed in the same order by all observer threads.
*
* <p><b>Acquire/Release management of thread safe objects</b>. It may
* be possible to use weaker conventions for volatile-like variables
* when they are used to keep track of objects that fully manage their
* own thread-safety and synchronization. Here, an acquiring read
* operation remains the same as a volatile-read, but a releasing
* write differs by virtue of not itself ensuring an ordering of its
* write with subsequent reads, because the required effects are
* already ensured by the referenced objects.
* For example:
*
* <pre>
* class Item {
* synchronized f(); // ALL methods are synchronized
* // ...
* }
*
* class ItemHolder {
* private Item item;
* Item acquireItem() {
* return Fences.orderReads(item);
* }
*
* void releaseItem(Item x) {
* item = Fences.orderWrites(x);
* }
*
* // ...
* }
* </pre>
*
* Because this construction avoids use of {@code orderAccesses},
* which is typically more costly than the other fence methods, it may
* result in better performance than using {@code volatile} or its
* emulation. However, as is the case with most applications of fence
* methods, correctness relies on the usage context -- here, the
* thread safety of {@code Item}, as well as the lack of need for full
* volatile semantics inside this class itself. However, the second
* concern means that it can be difficult to extend the {@code
* ItemHolder} class in this example to be more useful.
*
* <p><b>Avoiding premature finalization.</b> Finalization may occur
* whenever a Java Virtual Machine detects that no reference to an
* object will ever be stored in the heap: A garbage collector may
* reclaim an object even if the fields of that object are still in
* use, so long as the object has otherwise become unreachable. This
* may have surprising and undesirable effects in cases such as the
* following example in which the bookkeeping associated with a class
* is managed through array indices. Here, method {@code action}
* uses a {@code reachabilityFence} to ensure that the Resource
* object is not reclaimed before bookkeeping on an associated
* ExternalResource has been performed; in particular here, to ensure
* that the array slot holding the ExternalResource is not nulled out
* in method {@link Object#finalize}, which may otherwise run
* concurrently.
*
* <pre>
* class Resource {
* private static ExternalResource[] externalResourceArray = ...
*
* int myIndex;
* Resource(...) {
* myIndex = ...
* externalResourceArray[myIndex] = ...;
* ...
* }
* protected void finalize() {
* externalResourceArray[myIndex] = null;
* ...
* }
* public void action() {
* try {
* // ...
* int i = myIndex;
* Resource.update(externalResourceArray[i]);
* } finally {
* Fences.reachabilityFence(this);
* }
* }
* private static void update(ExternalResource ext) {
* ext.status = ...;
* }
* }
* </pre>
*
* Here, the call to {@code reachabilityFence} is unintuitively
* placed <em>after</em> the call to {@code update}, to ensure that
* the array slot is not nulled out by {@link Object#finalize} before
* the update, even if the call to {@code action} was the last use of
* this object. This might be the case if for example a usage in a
* user program had the form {@code new Resource().action();} which
* retains no other reference to this Resource. While probably
* overkill here, {@code reachabilityFence} is placed in a {@code
* finally} block to ensure that it is invoked across all paths in the
* method. In a method with more complex control paths, you might
* need further precautions to ensure that {@code reachabilityFence}
* is encountered along all of them.
*
* <p>It is sometimes possible to better encapsulate use of
* {@code reachabilityFence}. Continuing the above example, if it
* were OK for the call to method update to proceed even if the
* finalizer had already executed (nulling out slot), then you could
* localize use of {@code reachabilityFence}:
*
* <pre>
* public void action2() {
* // ...
* Resource.update(getExternalResource());
* }
* private ExternalResource getExternalResource() {
* ExternalResource ext = externalResourceArray[myIndex];
* Fences.reachabilityFence(this);
* return ext;
* }
* </pre>
*
* <p>Method {@code reachabilityFence} is not required in
* constructions that themselves ensure reachability. For example,
* because objects that are locked cannot in general be reclaimed, it
* would suffice if all accesses of the object, in all methods of
* class Resource (including {@code finalize}) were enclosed in {@code
* synchronized (this)} blocks. (Further, such blocks must not include
* infinite loops, or themselves be unreachable, which fall into the
* corner case exceptions to the "in general" disclaimer.) However,
* method {@code reachabilityFence} remains a better option in cases
* where this approach is not as efficient, desirable, or possible;
* for example because it would encounter deadlock.
*
* <p><b>Formal Properties.</b>
*
* <p>Using the terminology of The Java Language Specification chapter
* 17, the rules governing the semantics of the methods of this class
* are as follows:
*
* <p> The following is still under construction.
*
* <dl>
*
* <dt><b>[Definitions]</b>
* <dd>
* <ul>
*
* <li>Define <em>sequenced(a, b)</em> to be true if <em>a</em>
* occurs before <em>b</em> in <em>program order</em>.
*
* <li>Define <em>accesses(a, p)</em> to be true if
* <em>a</em> is a read or write of a field (or if an array, an
* element) of the object referenced by <em>p</em>.
*
* <li>Define <em>deeplyAccesses(a, p)</em> to be true if either
* <em>accesses(a, p)</em> or <em>deeplyAccesses(a, q)</em> where
* <em>q</em> is the value seen by some read <em>r</em>
* such that <em>accesses(r, p)</em>.
*
* </ul>
* <p>
* <dt><b>[Matching]</b>
* <dd> Given:
*
* <ul>
*
* <li><em>p</em>, a reference to an object
*
* <li><em>wf</em>, an invocation of {@code orderWrites(p)} or
* {@code orderAccesses(p)}
*
* <li><em>w</em>, a write of value <em>p</em>
*
* <li> <em>rf</em>, an invocation of {@code orderReads(p)} or
* {@code orderAccesses(p)}
*
* <li> <em>r</em>, a read returning value <em>p</em>
*
* </ul>
* If:
* <ul>
* <li>sequenced(wf, w)
* <li>read <em>r</em> sees write <em>w</em>
* <li>sequenced(r, rf)
* </ul>
* Then:
* <ul>
*
* <li> <em>wf happens-before rf</em>
*
* <li> <em>wf</em> precedes <em>rf</em> in the
* <em>synchronization order</em>
*
* <li> If (<em>r1</em>, <em>w1</em>) and (<em>r2</em>,
* <em>w2</em>) are two pairs of reads and writes, both
* respectively satisfying the above conditions for <em>p</em>,
* and sequenced(r1, r2) then it is not the case that <em>w2
* happens-before w1</em>.
*
* </ul>
* <p>
* <dt><b>[Initial Reads]</b>
* <dd> Given:
*
* <ul>
*
* <li><em>p</em>, a reference to an object
*
* <li> <em>a</em>, an access where deeplyAccesses(a, p)
*
* <li><em>wf</em>, an invocation of {@code orderWrites(p)} or
* {@code orderAccesses(p)}
*
* <li><em>w</em>, a write of value <em>p</em>
*
* <li> <em>r</em>, a read returning value <em>p</em>
*
* <li> <em>b</em>, an access where accesses(b, p)
*
* </ul>
* If:
* <ul>
* <li>sequenced(a, wf);
* <li>sequenced(wf, w)
* <li>read <em>r</em> sees write <em>w</em>, and
* <em>r</em> is the first read by some thread
* <em>t</em> that sees value <em>p</em>
* <li>sequenced(r, b)
* </ul>
* Then:
* <ul>
* <li> the effects of <em>b</em> are constrained
* by the relation <em>a happens-before b</em>.
* </ul>
* <p>
* <dt><b>[orderAccesses]</b>
* <dd> Given:
*
* <ul>
* <li><em>p</em>, a reference to an object
* <li><em>f</em>, an invocation of {@code orderAccesses(p)}
* </ul>
* If:
* <ul>
* <li>sequenced(f, w)
* </ul>
*
* Then:
*
* <ul>
*
* <li> <em>f</em> is an element of the <em>synchronization order</em>.
*
* </ul>
* <p>
* <dt><b>[Reachability]</b>
* <dd> Given:
*
* <ul>
*
* <li><em>p</em>, a reference to an object
*
* <li><em>f</em>, an invocation of {@code reachabilityFence(p)}
*
* <li><em>a</em>, an access where accesses(a, p)
*
* <li><em>b</em>, an action (by a garbage collector) taking
* the form of an invocation of {@code
* p.finalize()} or of enqueuing any {@link
* java.lang.ref.Reference} constructed with argument <em>p</em>
*
* </ul>
*
* If:
* <ul>
* <li>sequenced(a, f)
* </ul>
*
* Then:
*
* <ul>
*
* <li> <em>a happens-before b</em>.
*
* </ul>
*
* </dl>
*
* @since 1.7
* @author Doug Lea
*/
@SuppressWarnings("UnusedDeclaration")
public class Fences {
private Fences() {} // Non-instantiable
/*
* The methods of this class are intended to be intrinisified by a
* JVM. However, we provide correct but inefficient Java-level
* code that simply reads and writes a static volatile
* variable. Without JVM support, the consistency effects are
* stronger than necessary, and the memory contention effects can
* be a serious performance issue.
*/
private static volatile int theVolatile;
/**
* Informally: Ensures that a read of the given reference prior to
* the invocation of this method occurs before a subsequent use of
* the given reference with the effect of reading or writing a
* field (or if an array, element) of the referenced object. The
* use of this method is sensible only when paired with other
* invocations of {@link #orderWrites} and/or {@link
* #orderAccesses} for the given reference. For details, see the
* class documentation for this class.
*
* @param ref the reference. If null, this method has no effect.
* @return the given ref, to simplify usage
*/
public static <T> T orderReads(final T ref) {
final int ignore = theVolatile;
return ref;
}
/**
* Informally: Ensures that a use of the given reference with the
* effect of reading or writing a field (or if an array, element)
* of the referenced object, prior to the invocation of this
* method occur before a subsequent write of the reference. For
* details, see the class documentation for this class.
*
* @param ref the reference. If null, this method has no effect.
* @return the given ref, to simplify usage
*/
public static <T> T orderWrites(final T ref) {
theVolatile = 0;
return ref;
}
/**
* Informally: Ensures that accesses (reads or writes) using the
* given reference prior to the invocation of this method occur
* before subsequent accesses. For details, see the class
* documentation for this class.
*
* @param ref the reference. If null, this method has no effect.
* @return the given ref, to simplify usage
*/
public static <T> T orderAccesses(final T ref) {
theVolatile = 0;
return ref;
}
/**
* Ensures that the object referenced by the given reference
* remains <em>strongly reachable</em> (as defined in the {@link
* java.lang.ref} package documentation), regardless of any prior
* actions of the program that might otherwise cause the object to
* become unreachable; thus, the referenced object is not
* reclaimable by garbage collection at least until after the
* invocation of this method. Invocation of this method does not
* itself initiate garbage collection or finalization.
*
* <p>See the class-level documentation for further explanation
* and usage examples.
*
* @param ref the reference. If null, this method has no effect.
*/
public static void reachabilityFence(final Object ref) {
if (ref != null) {
synchronized (ref) {}
}
}
}
| src/com/strobel/core/Fences.java | More work on class metadata loading.
--HG--
branch : assembler
| src/com/strobel/core/Fences.java | More work on class metadata loading. | <ide><path>rc/com/strobel/core/Fences.java
<add>package com.strobel.core;
<add>
<add>/*
<add> * Written by Doug Lea with assistance from members of JCP JSR-166
<add> * Expert Group and released to the public domain, as explained at
<add> * http://creativecommons.org/publicdomain/zero/1.0/
<add> */
<add>
<add>/**
<add> * A set of methods providing fine-grained control over happens-before
<add> * and synchronization order relations among reads and/or writes. The
<add> * methods of this class are designed for use in uncommon situations
<add> * where declaring variables {@code volatile} or {@code final}, using
<add> * instances of atomic classes, using {@code synchronized} blocks or
<add> * methods, or using other synchronization facilities are not possible
<add> * or do not provide the desired control.
<add> *
<add> * <p><b>Memory Ordering.</b> There are three methods for controlling
<add> * ordering relations among memory accesses (i.e., reads and
<add> * writes). Method {@code orderWrites} is typically used to enforce
<add> * order between two writes, and {@code orderAccesses} between a write
<add> * and a read. Method {@code orderReads} is used to enforce order
<add> * between two reads with respect to other {@code orderWrites} and/or
<add> * {@code orderAccesses} invocations. The formally specified
<add> * properties of these methods described below provide
<add> * platform-independent guarantees that are honored by all levels of a
<add> * platform (compilers, systems, processors). The use of these
<add> * methods may result in the suppression of otherwise valid compiler
<add> * transformations and optimizations that could visibly violate the
<add> * specified orderings, and may or may not entail the use of
<add> * processor-level "memory barrier" instructions.
<add> *
<add> * <p>Each ordering method accepts a {@code ref} argument, and
<add> * controls ordering among accesses with respect to this reference.
<add> * Invocations must be placed <em>between</em> accesses performed in
<add> * expression evaluations and assignment statements to control the
<add> * orderings of prior versus subsequent accesses appearing in program
<add> * order. These methods also return their arguments to simplify
<add> * correct usage in these contexts.
<add> *
<add> * <p>Usages of ordering methods almost always take one of the forms
<add> * illustrated in the examples below. These idioms arrange some of
<add> * the ordering properties associated with {@code volatile} and
<add> * related language-based constructions, but without other
<add> * compile-time and runtime benefits that make language-based
<add> * constructions far better choices when they are applicable. Usages
<add> * should be restricted to the control of strictly internal
<add> * implementation matters inside a class or package, and must either
<add> * avoid or document any consequent violations of ordering or safety
<add> * properties expected by users of a class employing them.
<add> *
<add> * <p><b>Reachability.</b> Method {@code reachabilityFence}
<add> * establishes an ordering for strong reachability (as defined in the
<add> * {@link java.lang.ref} package specification) with respect to
<add> * garbage collection. Method {@code reachabilityFence} differs from
<add> * the others in that it controls relations that are otherwise only
<add> * implicit in a program -- the reachability conditions triggering
<add> * garbage collection. As illustrated in the sample usages below,
<add> * this method is applicable only when reclamation may have visible
<add> * effects, which is possible for objects with finalizers (see Section
<add> * 12.6 of the Java Language Specification) that are implemented in
<add> * ways that rely on ordering control for correctness.
<add> *
<add> * <p><b>Sample Usages</b>
<add> *
<add> * <p><b>Safe publication.</b> With care, method {@code orderWrites}
<add> * may be used to obtain the memory safety effects of {@code final}
<add> * for a field that cannot be declared as {@code final}, because its
<add> * primary initialization cannot be performed in a constructor, in
<add> * turn because it is used in a framework requiring that all classes
<add> * have a no-argument constructor; as in:
<add> *
<add> * <pre>
<add> * class WidgetHolder {
<add> * private Widget widget;
<add> * public WidgetHolder() {}
<add> * public static WidgetHolder newWidgetHolder(Params params) {
<add> * WidgetHolder h = new WidgetHolder();
<add> * h.widget = new Widget(params);
<add> * return Fences.orderWrites(h);
<add> * }
<add> * }
<add> * </pre>
<add> *
<add> * Here, the invocation of {@code orderWrites} ensures that the
<add> * effects of the widget assignment are ordered before those of any
<add> * (unknown) subsequent stores of {@code h} in other variables that
<add> * make {@code h} available for use by other objects. Initialization
<add> * sequences using {@code orderWrites} require more care than those
<add> * involving {@code final} fields. When {@code final} is not used,
<add> * compilers cannot help you to ensure that the field is set correctly
<add> * across all usages. You must fully initialize objects
<add> * <em>before</em> the {@code orderWrites} invocation that makes
<add> * references to them safe to assign to accessible variables. Further,
<add> * initialization sequences must not internally "leak" the reference
<add> * by using it as an argument to a callback method or adding it to a
<add> * static data structure. If less constrained usages were required,
<add> * it may be possible to cope using more extensive sets of fences, or
<add> * as a normally better choice, using synchronization (locking).
<add> * Conversely, if it were possible to do so, the best option would be
<add> * to rewrite class {@code WidgetHolder} to use {@code final}.
<add> *
<add> * <p>An alternative approach is to place similar mechanics in the
<add> * (sole) method that makes such objects available for use by others.
<add> * Here is a stripped-down example illustrating the essentials. In
<add> * practice, among other changes, you would use access methods instead
<add> * of a public field.
<add> *
<add> * <pre>
<add> * class AnotherWidgetHolder {
<add> * public Widget widget;
<add> * void publish(Widget w) {
<add> * this.widget = Fences.orderWrites(w);
<add> * }
<add> * // ...
<add> * }
<add> * </pre>
<add> *
<add> * In this case, the {@code orderWrites} invocation occurs before the
<add> * store making the object available. Correctness again relies on
<add> * ensuring that there are no leaks prior to invoking this method, and
<add> * that it really is the <em>only</em> means of accessing the
<add> * published object. This approach is not often applicable --
<add> * normally you would publish objects using a thread-safe collection
<add> * that itself guarantees the expected ordering relations. However, it
<add> * may come into play in the construction of such classes themselves.
<add> *
<add> * <p><b>Safely updating fields.</b> Outside of the initialization
<add> * idioms illustrated above, Fence methods ordering writes must be
<add> * paired with those ordering reads. To illustrate, suppose class
<add> * {@code c} contains an accessible variable {@code data} that should
<add> * have been declared as {@code volatile} but wasn't:
<add> *
<add> * <pre>
<add> * class C {
<add> * Object data; // need volatile access but not volatile
<add> * // ...
<add> * }
<add> *
<add> * class App {
<add> * Object getData(C c) {
<add> * return Fences.orderReads(c).data;
<add> * }
<add> *
<add> * void setData(C c) {
<add> * Object newValue = ...;
<add> * c.data = Fences.orderWrites(newValue);
<add> * Fences.orderAccesses(c);
<add> * }
<add> * // ...
<add> * }
<add> * </pre>
<add> *
<add> * Method {@code getData} provides an emulation of {@code volatile}
<add> * reads of (non-long/double) fields by ensuring that the read of
<add> * {@code c} obtained as an argument is ordered before subsequent
<add> * reads using this reference, and then performs the read of its
<add> * field. Method {@code setData} provides an emulation of volatile
<add> * writes, ensuring that all other relevant writes have completed,
<add> * then performing the assignment, and then ensuring that the write is
<add> * ordered before any other access. These techniques may apply even
<add> * when fields are not directly accessible, in which case calls to
<add> * fence methods would surround calls to methods such as {@code
<add> * c.getData()}. However, these techniques cannot be applied to
<add> * {@code long} or {@code double} fields because reads and writes of
<add> * fields of these types are not guaranteed to be
<add> * atomic. Additionally, correctness may require that all accesses of
<add> * such data use these kinds of wrapper methods, which you would need
<add> * to manually ensure.
<add> *
<add> * <p>More generally, Fence methods can be used in this way to achieve
<add> * the safety properties of {@code volatile}. However their use does
<add> * not necessarily guarantee the full sequential consistency
<add> * properties specified in the Java Language Specification chapter 17
<add> * for programs using {@code volatile}. In particular, emulation using
<add> * Fence methods is not guaranteed to maintain the property that
<add> * {@code volatile} operations performed by different threads are
<add> * observed in the same order by all observer threads.
<add> *
<add> * <p><b>Acquire/Release management of thread safe objects</b>. It may
<add> * be possible to use weaker conventions for volatile-like variables
<add> * when they are used to keep track of objects that fully manage their
<add> * own thread-safety and synchronization. Here, an acquiring read
<add> * operation remains the same as a volatile-read, but a releasing
<add> * write differs by virtue of not itself ensuring an ordering of its
<add> * write with subsequent reads, because the required effects are
<add> * already ensured by the referenced objects.
<add> * For example:
<add> *
<add> * <pre>
<add> * class Item {
<add> * synchronized f(); // ALL methods are synchronized
<add> * // ...
<add> * }
<add> *
<add> * class ItemHolder {
<add> * private Item item;
<add> * Item acquireItem() {
<add> * return Fences.orderReads(item);
<add> * }
<add> *
<add> * void releaseItem(Item x) {
<add> * item = Fences.orderWrites(x);
<add> * }
<add> *
<add> * // ...
<add> * }
<add> * </pre>
<add> *
<add> * Because this construction avoids use of {@code orderAccesses},
<add> * which is typically more costly than the other fence methods, it may
<add> * result in better performance than using {@code volatile} or its
<add> * emulation. However, as is the case with most applications of fence
<add> * methods, correctness relies on the usage context -- here, the
<add> * thread safety of {@code Item}, as well as the lack of need for full
<add> * volatile semantics inside this class itself. However, the second
<add> * concern means that it can be difficult to extend the {@code
<add> * ItemHolder} class in this example to be more useful.
<add> *
<add> * <p><b>Avoiding premature finalization.</b> Finalization may occur
<add> * whenever a Java Virtual Machine detects that no reference to an
<add> * object will ever be stored in the heap: A garbage collector may
<add> * reclaim an object even if the fields of that object are still in
<add> * use, so long as the object has otherwise become unreachable. This
<add> * may have surprising and undesirable effects in cases such as the
<add> * following example in which the bookkeeping associated with a class
<add> * is managed through array indices. Here, method {@code action}
<add> * uses a {@code reachabilityFence} to ensure that the Resource
<add> * object is not reclaimed before bookkeeping on an associated
<add> * ExternalResource has been performed; in particular here, to ensure
<add> * that the array slot holding the ExternalResource is not nulled out
<add> * in method {@link Object#finalize}, which may otherwise run
<add> * concurrently.
<add> *
<add> * <pre>
<add> * class Resource {
<add> * private static ExternalResource[] externalResourceArray = ...
<add> *
<add> * int myIndex;
<add> * Resource(...) {
<add> * myIndex = ...
<add> * externalResourceArray[myIndex] = ...;
<add> * ...
<add> * }
<add> * protected void finalize() {
<add> * externalResourceArray[myIndex] = null;
<add> * ...
<add> * }
<add> * public void action() {
<add> * try {
<add> * // ...
<add> * int i = myIndex;
<add> * Resource.update(externalResourceArray[i]);
<add> * } finally {
<add> * Fences.reachabilityFence(this);
<add> * }
<add> * }
<add> * private static void update(ExternalResource ext) {
<add> * ext.status = ...;
<add> * }
<add> * }
<add> * </pre>
<add> *
<add> * Here, the call to {@code reachabilityFence} is unintuitively
<add> * placed <em>after</em> the call to {@code update}, to ensure that
<add> * the array slot is not nulled out by {@link Object#finalize} before
<add> * the update, even if the call to {@code action} was the last use of
<add> * this object. This might be the case if for example a usage in a
<add> * user program had the form {@code new Resource().action();} which
<add> * retains no other reference to this Resource. While probably
<add> * overkill here, {@code reachabilityFence} is placed in a {@code
<add> * finally} block to ensure that it is invoked across all paths in the
<add> * method. In a method with more complex control paths, you might
<add> * need further precautions to ensure that {@code reachabilityFence}
<add> * is encountered along all of them.
<add> *
<add> * <p>It is sometimes possible to better encapsulate use of
<add> * {@code reachabilityFence}. Continuing the above example, if it
<add> * were OK for the call to method update to proceed even if the
<add> * finalizer had already executed (nulling out slot), then you could
<add> * localize use of {@code reachabilityFence}:
<add> *
<add> * <pre>
<add> * public void action2() {
<add> * // ...
<add> * Resource.update(getExternalResource());
<add> * }
<add> * private ExternalResource getExternalResource() {
<add> * ExternalResource ext = externalResourceArray[myIndex];
<add> * Fences.reachabilityFence(this);
<add> * return ext;
<add> * }
<add> * </pre>
<add> *
<add> * <p>Method {@code reachabilityFence} is not required in
<add> * constructions that themselves ensure reachability. For example,
<add> * because objects that are locked cannot in general be reclaimed, it
<add> * would suffice if all accesses of the object, in all methods of
<add> * class Resource (including {@code finalize}) were enclosed in {@code
<add> * synchronized (this)} blocks. (Further, such blocks must not include
<add> * infinite loops, or themselves be unreachable, which fall into the
<add> * corner case exceptions to the "in general" disclaimer.) However,
<add> * method {@code reachabilityFence} remains a better option in cases
<add> * where this approach is not as efficient, desirable, or possible;
<add> * for example because it would encounter deadlock.
<add> *
<add> * <p><b>Formal Properties.</b>
<add> *
<add> * <p>Using the terminology of The Java Language Specification chapter
<add> * 17, the rules governing the semantics of the methods of this class
<add> * are as follows:
<add> *
<add> * <p> The following is still under construction.
<add> *
<add> * <dl>
<add> *
<add> * <dt><b>[Definitions]</b>
<add> * <dd>
<add> * <ul>
<add> *
<add> * <li>Define <em>sequenced(a, b)</em> to be true if <em>a</em>
<add> * occurs before <em>b</em> in <em>program order</em>.
<add> *
<add> * <li>Define <em>accesses(a, p)</em> to be true if
<add> * <em>a</em> is a read or write of a field (or if an array, an
<add> * element) of the object referenced by <em>p</em>.
<add> *
<add> * <li>Define <em>deeplyAccesses(a, p)</em> to be true if either
<add> * <em>accesses(a, p)</em> or <em>deeplyAccesses(a, q)</em> where
<add> * <em>q</em> is the value seen by some read <em>r</em>
<add> * such that <em>accesses(r, p)</em>.
<add> *
<add> * </ul>
<add> * <p>
<add> * <dt><b>[Matching]</b>
<add> * <dd> Given:
<add> *
<add> * <ul>
<add> *
<add> * <li><em>p</em>, a reference to an object
<add> *
<add> * <li><em>wf</em>, an invocation of {@code orderWrites(p)} or
<add> * {@code orderAccesses(p)}
<add> *
<add> * <li><em>w</em>, a write of value <em>p</em>
<add> *
<add> * <li> <em>rf</em>, an invocation of {@code orderReads(p)} or
<add> * {@code orderAccesses(p)}
<add> *
<add> * <li> <em>r</em>, a read returning value <em>p</em>
<add> *
<add> * </ul>
<add> * If:
<add> * <ul>
<add> * <li>sequenced(wf, w)
<add> * <li>read <em>r</em> sees write <em>w</em>
<add> * <li>sequenced(r, rf)
<add> * </ul>
<add> * Then:
<add> * <ul>
<add> *
<add> * <li> <em>wf happens-before rf</em>
<add> *
<add> * <li> <em>wf</em> precedes <em>rf</em> in the
<add> * <em>synchronization order</em>
<add> *
<add> * <li> If (<em>r1</em>, <em>w1</em>) and (<em>r2</em>,
<add> * <em>w2</em>) are two pairs of reads and writes, both
<add> * respectively satisfying the above conditions for <em>p</em>,
<add> * and sequenced(r1, r2) then it is not the case that <em>w2
<add> * happens-before w1</em>.
<add> *
<add> * </ul>
<add> * <p>
<add> * <dt><b>[Initial Reads]</b>
<add> * <dd> Given:
<add> *
<add> * <ul>
<add> *
<add> * <li><em>p</em>, a reference to an object
<add> *
<add> * <li> <em>a</em>, an access where deeplyAccesses(a, p)
<add> *
<add> * <li><em>wf</em>, an invocation of {@code orderWrites(p)} or
<add> * {@code orderAccesses(p)}
<add> *
<add> * <li><em>w</em>, a write of value <em>p</em>
<add> *
<add> * <li> <em>r</em>, a read returning value <em>p</em>
<add> *
<add> * <li> <em>b</em>, an access where accesses(b, p)
<add> *
<add> * </ul>
<add> * If:
<add> * <ul>
<add> * <li>sequenced(a, wf);
<add> * <li>sequenced(wf, w)
<add> * <li>read <em>r</em> sees write <em>w</em>, and
<add> * <em>r</em> is the first read by some thread
<add> * <em>t</em> that sees value <em>p</em>
<add> * <li>sequenced(r, b)
<add> * </ul>
<add> * Then:
<add> * <ul>
<add> * <li> the effects of <em>b</em> are constrained
<add> * by the relation <em>a happens-before b</em>.
<add> * </ul>
<add> * <p>
<add> * <dt><b>[orderAccesses]</b>
<add> * <dd> Given:
<add> *
<add> * <ul>
<add> * <li><em>p</em>, a reference to an object
<add> * <li><em>f</em>, an invocation of {@code orderAccesses(p)}
<add> * </ul>
<add> * If:
<add> * <ul>
<add> * <li>sequenced(f, w)
<add> * </ul>
<add> *
<add> * Then:
<add> *
<add> * <ul>
<add> *
<add> * <li> <em>f</em> is an element of the <em>synchronization order</em>.
<add> *
<add> * </ul>
<add> * <p>
<add> * <dt><b>[Reachability]</b>
<add> * <dd> Given:
<add> *
<add> * <ul>
<add> *
<add> * <li><em>p</em>, a reference to an object
<add> *
<add> * <li><em>f</em>, an invocation of {@code reachabilityFence(p)}
<add> *
<add> * <li><em>a</em>, an access where accesses(a, p)
<add> *
<add> * <li><em>b</em>, an action (by a garbage collector) taking
<add> * the form of an invocation of {@code
<add> * p.finalize()} or of enqueuing any {@link
<add> * java.lang.ref.Reference} constructed with argument <em>p</em>
<add> *
<add> * </ul>
<add> *
<add> * If:
<add> * <ul>
<add> * <li>sequenced(a, f)
<add> * </ul>
<add> *
<add> * Then:
<add> *
<add> * <ul>
<add> *
<add> * <li> <em>a happens-before b</em>.
<add> *
<add> * </ul>
<add> *
<add> * </dl>
<add> *
<add> * @since 1.7
<add> * @author Doug Lea
<add> */
<add>@SuppressWarnings("UnusedDeclaration")
<add>public class Fences {
<add> private Fences() {} // Non-instantiable
<add>
<add> /*
<add> * The methods of this class are intended to be intrinisified by a
<add> * JVM. However, we provide correct but inefficient Java-level
<add> * code that simply reads and writes a static volatile
<add> * variable. Without JVM support, the consistency effects are
<add> * stronger than necessary, and the memory contention effects can
<add> * be a serious performance issue.
<add> */
<add> private static volatile int theVolatile;
<add>
<add> /**
<add> * Informally: Ensures that a read of the given reference prior to
<add> * the invocation of this method occurs before a subsequent use of
<add> * the given reference with the effect of reading or writing a
<add> * field (or if an array, element) of the referenced object. The
<add> * use of this method is sensible only when paired with other
<add> * invocations of {@link #orderWrites} and/or {@link
<add> * #orderAccesses} for the given reference. For details, see the
<add> * class documentation for this class.
<add> *
<add> * @param ref the reference. If null, this method has no effect.
<add> * @return the given ref, to simplify usage
<add> */
<add> public static <T> T orderReads(final T ref) {
<add> final int ignore = theVolatile;
<add> return ref;
<add> }
<add>
<add> /**
<add> * Informally: Ensures that a use of the given reference with the
<add> * effect of reading or writing a field (or if an array, element)
<add> * of the referenced object, prior to the invocation of this
<add> * method occur before a subsequent write of the reference. For
<add> * details, see the class documentation for this class.
<add> *
<add> * @param ref the reference. If null, this method has no effect.
<add> * @return the given ref, to simplify usage
<add> */
<add> public static <T> T orderWrites(final T ref) {
<add> theVolatile = 0;
<add> return ref;
<add> }
<add>
<add> /**
<add> * Informally: Ensures that accesses (reads or writes) using the
<add> * given reference prior to the invocation of this method occur
<add> * before subsequent accesses. For details, see the class
<add> * documentation for this class.
<add> *
<add> * @param ref the reference. If null, this method has no effect.
<add> * @return the given ref, to simplify usage
<add> */
<add> public static <T> T orderAccesses(final T ref) {
<add> theVolatile = 0;
<add> return ref;
<add> }
<add>
<add> /**
<add> * Ensures that the object referenced by the given reference
<add> * remains <em>strongly reachable</em> (as defined in the {@link
<add> * java.lang.ref} package documentation), regardless of any prior
<add> * actions of the program that might otherwise cause the object to
<add> * become unreachable; thus, the referenced object is not
<add> * reclaimable by garbage collection at least until after the
<add> * invocation of this method. Invocation of this method does not
<add> * itself initiate garbage collection or finalization.
<add> *
<add> * <p>See the class-level documentation for further explanation
<add> * and usage examples.
<add> *
<add> * @param ref the reference. If null, this method has no effect.
<add> */
<add> public static void reachabilityFence(final Object ref) {
<add> if (ref != null) {
<add> synchronized (ref) {}
<add> }
<add> }
<add>} |
|
Java | apache-2.0 | 8d019822b02f5bd294af7a633617a30efa2dfd05 | 0 | liquibase/liquibase,fossamagna/liquibase,dbmanul/dbmanul,NSIT/liquibase,mattbertolini/liquibase,jimmycd/liquibase,jimmycd/liquibase,NSIT/liquibase,mattbertolini/liquibase,jimmycd/liquibase,dbmanul/dbmanul,mattbertolini/liquibase,fossamagna/liquibase,jimmycd/liquibase,NSIT/liquibase,dbmanul/dbmanul,liquibase/liquibase,NSIT/liquibase,fossamagna/liquibase,dbmanul/dbmanul,liquibase/liquibase,mattbertolini/liquibase | package liquibase;
import liquibase.util.StringUtils;
import java.util.*;
/**
* List of contexts Liquibase is running under.
*/
public class Contexts {
private HashSet<String> contextStore = new HashSet<>();
public Contexts() {
}
public Contexts(String... contexts) {
if (contexts.length == 1) {
parseContextString(contexts[0]);
} else {
for (String context : contexts) {
this.contextStore.add(context.toLowerCase());
}
}
}
public Contexts(String contexts) {
parseContextString(contexts);
}
public Contexts(Collection<String> contexts) {
if (contexts != null) {
for (String context : contexts) {
this.contextStore.add(context.toLowerCase());
}
}
}
private void parseContextString(String contexts) {
contexts = StringUtils.trimToNull(contexts);
if (contexts == null) {
return;
}
for (String context : StringUtils.splitAndTrim(contexts, ",")) {
this.contextStore.add(context.toLowerCase());
}
}
public boolean add(String context) {
return this.contextStore.add(context.toLowerCase());
}
public boolean remove(String context) {
return this.contextStore.remove(context.toLowerCase());
}
@Override
public String toString() {
return StringUtils.join(new TreeSet<String>(this.contextStore), ",");
}
public boolean isEmpty() {
return (this.contextStore == null) || this.contextStore.isEmpty();
}
public Set<String> getContexts() {
return Collections.unmodifiableSet(contextStore);
}
}
| liquibase-core/src/main/java/liquibase/Contexts.java | package liquibase;
import liquibase.util.StringUtils;
import java.util.*;
/**
* List of contexts Liquibase is running under.
*/
public class Contexts {
private HashSet<String> contexts = new HashSet<>();
public Contexts() {
}
public Contexts(String... contexts) {
if (contexts.length == 1) {
parseContextString(contexts[0]);
} else {
for (String context : contexts) {
this.contexts.add(context.toLowerCase());
}
}
}
public Contexts(String contexts) {
parseContextString(contexts);
}
private void parseContextString(String contexts) {
contexts = StringUtils.trimToNull(contexts);
if (contexts == null) {
return;
}
for (String context : StringUtils.splitAndTrim(contexts, ",")) {
this.contexts.add(context.toLowerCase());
}
}
public Contexts(Collection<String> contexts) {
if (contexts != null) {
for (String context : contexts) {
this.contexts.add(context.toLowerCase());
}
}
}
public boolean add(String context) {
return this.contexts.add(context.toLowerCase());
}
public boolean remove(String context) {
return this.contexts.remove(context.toLowerCase());
}
@Override
public String toString() {
return StringUtils.join(new TreeSet<String>(this.contexts), ",");
}
public boolean isEmpty() {
return (this.contexts == null) || this.contexts.isEmpty();
}
public Set<String> getContexts() {
return Collections.unmodifiableSet(contexts);
}
}
| SONAR: Minor Cleanups
| liquibase-core/src/main/java/liquibase/Contexts.java | SONAR: Minor Cleanups | <ide><path>iquibase-core/src/main/java/liquibase/Contexts.java
<ide> */
<ide> public class Contexts {
<ide>
<del> private HashSet<String> contexts = new HashSet<>();
<add> private HashSet<String> contextStore = new HashSet<>();
<ide>
<ide> public Contexts() {
<ide> }
<ide> parseContextString(contexts[0]);
<ide> } else {
<ide> for (String context : contexts) {
<del> this.contexts.add(context.toLowerCase());
<add> this.contextStore.add(context.toLowerCase());
<ide> }
<ide> }
<ide> }
<ide>
<ide> public Contexts(String contexts) {
<ide> parseContextString(contexts);
<add> }
<add>
<add> public Contexts(Collection<String> contexts) {
<add> if (contexts != null) {
<add> for (String context : contexts) {
<add> this.contextStore.add(context.toLowerCase());
<add> }
<add>
<add> }
<ide> }
<ide>
<ide> private void parseContextString(String contexts) {
<ide> return;
<ide> }
<ide> for (String context : StringUtils.splitAndTrim(contexts, ",")) {
<del> this.contexts.add(context.toLowerCase());
<add> this.contextStore.add(context.toLowerCase());
<ide> }
<ide>
<ide> }
<ide>
<del> public Contexts(Collection<String> contexts) {
<del> if (contexts != null) {
<del> for (String context : contexts) {
<del> this.contexts.add(context.toLowerCase());
<del> }
<del>
<del> }
<del> }
<del>
<ide> public boolean add(String context) {
<del> return this.contexts.add(context.toLowerCase());
<add> return this.contextStore.add(context.toLowerCase());
<ide> }
<ide>
<ide> public boolean remove(String context) {
<del> return this.contexts.remove(context.toLowerCase());
<add> return this.contextStore.remove(context.toLowerCase());
<ide> }
<ide>
<ide> @Override
<ide> public String toString() {
<del> return StringUtils.join(new TreeSet<String>(this.contexts), ",");
<add> return StringUtils.join(new TreeSet<String>(this.contextStore), ",");
<ide> }
<ide>
<ide>
<ide> public boolean isEmpty() {
<del> return (this.contexts == null) || this.contexts.isEmpty();
<add> return (this.contextStore == null) || this.contextStore.isEmpty();
<ide> }
<ide>
<ide> public Set<String> getContexts() {
<del> return Collections.unmodifiableSet(contexts);
<add> return Collections.unmodifiableSet(contextStore);
<ide> }
<ide> } |
|
JavaScript | mpl-2.0 | 87ee95887591326ed9bc297c1615e66cf6aed25c | 0 | bbondy/khan-academy-fxos,bbondy/khan-academy-fxos | import APIClient from "./apiclient";
import {getId, getDuration, getPoints, getYoutubeId} from "./data/topic-tree-helper";
import _ from "underscore";
import Util from "./util";
import {editorForPath} from "./renderer";
import Immutable from "immutable";
const userInfoLocalStorageName = "userInfo-3";
export const signIn = () => APIClient.signIn();
export const signOut = (editUser) => {
localStorage.removeItem(userInfoLocalStorageName);
editUser((user) => user.merge({
userInfo: null,
startedEntityIds: [],
completedEntityIds: [],
}));
return APIClient.signOut();
};
export const isSignedIn = () =>
APIClient.isSignedIn();
const getLocalStorageName = (base, userInfo) =>
base + "-uid-" + (userInfo.get("nickname") || userInfo.get("username"));
const completedEntityIdsLocalStorageName = _.partial(getLocalStorageName, "completed");
const startedEntityIdsLocalStorageName = _.partial(getLocalStorageName, "started");
const userVideosLocalStorageName = _.partial(getLocalStorageName, "userVideos");
const userExercisesLocalStorageName = _.partial(getLocalStorageName, "userExercises");
const saveUserInfo = (userInfo) => {
localStorage.removeItem(userInfoLocalStorageName);
localStorage.setItem(userInfoLocalStorageName, JSON.stringify(userInfo));
};
const saveStarted = (userInfo, startedEntityIds) => {
localStorage.removeItem(startedEntityIdsLocalStorageName(userInfo));
localStorage.setItem(startedEntityIdsLocalStorageName(userInfo), JSON.stringify(startedEntityIds));
};
const saveCompleted = (userInfo, completedEntityIds) => {
localStorage.removeItem(completedEntityIdsLocalStorageName(userInfo));
localStorage.setItem(completedEntityIdsLocalStorageName(userInfo), JSON.stringify(completedEntityIds));
};
const saveUserVideos = (userInfo, userVideos) => {
userVideos = userVideos.map((userVideo) => {
return {
duration: userVideo.duration,
last_second_watched: userVideo.last_second_watched,
points: userVideo.points,
video: {
id: userVideo.id
}
};
});
localStorage.removeItem(userVideosLocalStorageName(userInfo));
localStorage.setItem(userVideosLocalStorageName(userInfo), JSON.stringify(userVideos));
};
const saveUserExercises = (userInfo, userExercises) => {
userExercises = userExercises.map((exercise) => {
return {
streak: exercise.streak,
total_correct: exercise.total_correct,
total_done: exercise.total_done,
exercise_model: {
content_id: exercise.exercise_model.content_id
}
};
});
// The extra removeItem calls before the setItem calls help in case local storage is almost full
localStorage.removeItem(userExercisesLocalStorageName(userInfo));
localStorage.setItem(userExercisesLocalStorageName(userInfo), JSON.stringify(userExercises));
};
const loadLocalStorageData = (userInfo) => {
var result = {};
var completedEntityIds = localStorage.getItem(completedEntityIdsLocalStorageName(userInfo));
if (completedEntityIds) {
result.completedEntityIds = JSON.parse(completedEntityIds);
}
var startedEntityIds = localStorage.getItem(startedEntityIdsLocalStorageName(userInfo));
if (startedEntityIds) {
result.startedEntityIds = JSON.parse(startedEntityIds);
}
var userVideos = localStorage.getItem(userVideosLocalStorageName(userInfo));
if (userVideos) {
result.userVideos = JSON.parse(userVideos);
}
var userExercises = localStorage.getItem(userExercisesLocalStorageName(userInfo));
if (userExercises) {
result.userExercises = JSON.parse(userExercises);
}
return result;
};
export const reportVideoProgress = (user, topicTreeNode, secondsWatched, lastSecondWatched, editVideo, editUser) => {
return new Promise((resolve, reject) => {
const youTubeId = getYoutubeId(topicTreeNode),
videoId = getId(topicTreeNode),
duration = getDuration(topicTreeNode),
editCompletedEntityIds = editorForPath(editUser, "completedEntityIds"),
editStartedEntityIds = editorForPath(editUser, "startedEntityIds"),
editUserInfo = editorForPath(editUser, "userInfo"),
editUserVideos = editorForPath(editUser, "userVideos");
let completedEntityIds = user.get("completedEntityIds"),
startedEntityIds = user.get("startedEntityIds"),
userVideos = user.get("userVideos");
APIClient.reportVideoProgress(videoId, youTubeId, secondsWatched, lastSecondWatched).then((result) => {
if (!result) {
Util.warn("Video progress report returned null results!");
return;
}
Util.log("reportVideoProgress result: %o", result);
var lastPoints = getPoints(topicTreeNode);
var newPoints = lastPoints + result.points_earned;
if (newPoints > 750) {
newPoints = 750;
}
// If they've watched some part of the video, and it's not almost the end
// Otherwise check if we already have video progress for this item and we
// therefore no longer need it.
var lastSecondWatched;
if (result.last_second_watched > 10 &&
duration - result.last_second_watched > 10) {
lastSecondWatched = result.last_second_watched;
}
// If we're just getting a completion of a video update
// the user's overall points locally.
if (result.points_earned > 0) {
var userInfo = user.get("userInfo");
userInfo = userInfo.set("points",
userInfo.get("points") + result.points_earned);
editUserInfo(() => userInfo);
saveUserInfo(userInfo);
}
editVideo((video) =>
video.merge({
points: newPoints,
completed: result.is_video_completed,
started: !result.is_video_completed,
lastSecondWatched: lastSecondWatched
}));
// Update locally stored cached info
if (result.is_video_completed) {
if (startedEntityIds.contains(getId(topicTreeNode))) {
startedEntityIds = startedEntityIds.remove(startedEntityIds.indexOf(getId(topicTreeNode)));
editStartedEntityIds(() => startedEntityIds);
}
if (!completedEntityIds.contains(getId(topicTreeNode))) {
completedEntityIds = completedEntityIds.unshift(getId(topicTreeNode));
editCompletedEntityIds(() => completedEntityIds);
}
} else {
if (!startedEntityIds.contains(getId(topicTreeNode))) {
startedEntityIds = startedEntityIds.unshift(getId(topicTreeNode));
editStartedEntityIds(() => startedEntityIds);
}
}
var foundUserVideo = userVideos.find((info) =>
info.getIn(["video", "id"]) === getId(topicTreeNode));
if (foundUserVideo) {
foundUserVideo = foundUserVideo.toJS();
}
var isNew = !foundUserVideo;
foundUserVideo = foundUserVideo || {
video: {
id: getId(topicTreeNode)
},
duration: getDuration(topicTreeNode)
};
foundUserVideo["points"] = newPoints;
foundUserVideo["last_second_watched"] = lastSecondWatched;
if (isNew) {
userVideos = userVideos.unshift(Immutable.fromJS(foundUserVideo));
editUserVideos(() => userVideos);
}
saveStarted(user.get("userInfo"), startedEntityIds);
saveCompleted(user.get("userInfo"), completedEntityIds);
saveUserVideos(user.get("userInfo"), userVideos);
resolve({
completed: result.is_video_completed,
lastSecondWatched: result.last_second_watched,
pointsEarned: result.points_earned,
youtubeId: result.youtube_id,
videoId,
id: getId(topicTreeNode)
});
}).catch(() => {
reject();
});
});
};
export const reportArticleRead = (user, topicTreeNode, editUser) => {
return new Promise((resolve, reject) => {
if (!isSignedIn()) {
return setTimeout(resolve, 0);
}
APIClient.reportArticleRead(getId(topicTreeNode)).then((result) => {
Util.log("reported article complete: %o", result);
let completedEntityIds = user.get("completedEntityIds");
if (!completedEntityIds.contains(getId(topicTreeNode))) {
completedEntityIds = completedEntityIds.unshift(getId(topicTreeNode));
const editCompletedEntityIds = editorForPath(editUser, "completedEntityIds");
editCompletedEntityIds(() => completedEntityIds);
}
saveCompleted(user.get("userInfo"), completedEntityIds);
resolve(result);
}).catch(() => {
reject();
});
});
};
export const refreshLoggedInInfo = (user, editUser, forceRefreshAllInfo) => {
return new Promise((resolve, reject) => {
if (!isSignedIn()) {
return resolve();
}
// Get the user profile info
APIClient.getUserInfo().then((result) => {
Util.log("getUserInfo: %o", result);
const userInfo = Immutable.fromJS({
avatarUrl: result.avatar_url,
joined: result.joined,
nickname: result.nickname,
username: result.username,
points: result.points,
badgeCounts: result.badge_counts
});
editUser((user) => user.set("userInfo", userInfo));
saveUserInfo(userInfo.toJS());
var result = loadLocalStorageData(userInfo);
if (!forceRefreshAllInfo && result.completedEntityIds) {
Util.log("User info only obtained. Not obtaining user data because we have it cached already!");
return result;
}
// The call is needed for completed/in progress status of content items
// Unlike getUserVideos, this includes both articles and videos.
return APIClient.getUserProgress();
}).then((data) => {
Util.log("getUserProgress: %o", data);
// data.complete will be returned from the API but not when loaded
// directly from localStorage. When loaded directly from localstorage
// you'll already have result.startedEntityIds.
if (data.complete) {
// Get rid of the 'a' and 'v' prefixes, and set the completed / started
// attributes accordingly.
data.startedEntityIds = _.map(data.started, function(e) {
return e.substring(1);
});
data.completedEntityIds = _.map(data.complete, function(e) {
return e.substring(1);
});
// Save to local storage
saveStarted(user.get("userInfo"), data.startedEntityIds);
saveCompleted(user.get("userInfo"), data.completedEntityIds);
}
editUser((user) => user.merge({
startedEntityIds: data.startedEntityIds,
completedEntityIds: data.completedEntityIds,
}));
return APIClient.getUserVideos();
}).then((userVideosResults) => {
saveUserVideos(user.get("userInfo"), userVideosResults);
return APIClient.getUserExercises();
}).then((userExercisesResults) => {
saveUserExercises(user.get("userInfo"), userExercisesResults);
resolve();
}).catch(() => {
reject();
});
});
};
| src/user.js | import APIClient from "./apiclient";
import {getId, getDuration, getPoints, getYoutubeId} from "./data/topic-tree-helper";
import _ from "underscore";
import Util from "./util";
import {editorForPath} from "./renderer";
import Immutable from "immutable";
const userInfoLocalStorageName = "userInfo-3";
export const signIn = () => APIClient.signIn();
export const signOut = (editUser) => {
localStorage.removeItem(userInfoLocalStorageName);
editUser((user) => user.merge({
userInfo: null,
startedEntityIds: [],
completedEntityIds: [],
}));
return APIClient.signOut();
};
export const isSignedIn = () =>
APIClient.isSignedIn();
const getLocalStorageName = (base, userInfo) =>
base + "-uid-" + (userInfo.get("nickname") || userInfo.get("username"));
const completedEntityIdsLocalStorageName = _.partial(getLocalStorageName, "completed");
const startedEntityIdsLocalStorageName = _.partial(getLocalStorageName, "started");
const userVideosLocalStorageName = _.partial(getLocalStorageName, "userVideos");
const userExercisesLocalStorageName = _.partial(getLocalStorageName, "userExercises");
const saveUserInfo = (userInfo) => {
localStorage.removeItem(userInfoLocalStorageName);
localStorage.setItem(userInfoLocalStorageName, JSON.stringify(userInfo));
};
const saveStarted = (userInfo, startedEntityIds) => {
localStorage.removeItem(startedEntityIdsLocalStorageName(userInfo));
localStorage.setItem(startedEntityIdsLocalStorageName(userInfo), JSON.stringify(startedEntityIds));
};
const saveCompleted = (userInfo, completedEntityIds) => {
localStorage.removeItem(completedEntityIdsLocalStorageName(userInfo));
localStorage.setItem(completedEntityIdsLocalStorageName(userInfo), JSON.stringify(completedEntityIds));
};
const saveUserVideos = (userInfo, userVideos) => {
userVideos = userVideos.map((userVideo) => {
return {
duration: userVideo.duration,
last_second_watched: userVideo.last_second_watched,
points: userVideo.points,
video: {
id: userVideo.id
}
};
});
localStorage.removeItem(userVideosLocalStorageName(userInfo));
localStorage.setItem(userVideosLocalStorageName(userInfo), JSON.stringify(userVideos));
};
const saveUserExercises = (userInfo, userExercises) => {
userExercises = userExercises.map((exercise) => {
return {
streak: exercise.streak,
total_correct: exercise.total_correct,
total_done: exercise.total_done,
exercise_model: {
content_id: exercise.exercise_model.content_id
}
};
});
// The extra removeItem calls before the setItem calls help in case local storage is almost full
localStorage.removeItem(userExercisesLocalStorageName(userInfo));
localStorage.setItem(userExercisesLocalStorageName(userInfo), JSON.stringify(userExercises));
};
const loadLocalStorageData = (userInfo) => {
var result = {};
var completedEntityIds = localStorage.getItem(completedEntityIdsLocalStorageName(userInfo));
if (completedEntityIds) {
result.completedEntityIds = JSON.parse(completedEntityIds);
}
var startedEntityIds = localStorage.getItem(startedEntityIdsLocalStorageName(userInfo));
if (startedEntityIds) {
result.startedEntityIds = JSON.parse(startedEntityIds);
}
var userVideos = localStorage.getItem(userVideosLocalStorageName(userInfo));
if (userVideos) {
result.userVideos = JSON.parse(userVideos);
}
var userExercises = localStorage.getItem(userExercisesLocalStorageName(userInfo));
if (userExercises) {
result.userExercises = JSON.parse(userExercises);
}
return result;
};
export const reportVideoProgress = (user, topicTreeNode, secondsWatched, lastSecondWatched, editVideo, editUser) => {
return new Promise((resolve, reject) => {
const youTubeId = getYoutubeId(topicTreeNode),
videoId = getId(topicTreeNode),
duration = getDuration(topicTreeNode),
editCompletedEntityIds = editorForPath(editUser, "completedEntityIds"),
editStartedEntityIds = editorForPath(editUser, "startedEntityIds"),
editUserInfo = editorForPath(editUser, "userInfo"),
editUserVideos = editorForPath(editUser, "userVideos");
let completedEntityIds = user.get("completedEntityIds"),
startedEntityIds = user.get("startedEntityIds"),
userVideos = user.get("userVideos");
APIClient.reportVideoProgress(videoId, youTubeId, secondsWatched, lastSecondWatched).then((result) => {
if (!result) {
Util.warn("Video progress report returned null results!");
return;
}
Util.log("reportVideoProgress result: %o", result);
var lastPoints = getPoints(topicTreeNode);
var newPoints = lastPoints + result.points_earned;
if (newPoints > 750) {
newPoints = 750;
}
// If they've watched some part of the video, and it's not almost the end
// Otherwise check if we already have video progress for this item and we
// therefore no longer need it.
var lastSecondWatched;
if (result.last_second_watched > 10 &&
duration - result.last_second_watched > 10) {
lastSecondWatched = result.last_second_watched;
}
// If we're just getting a completion of a video update
// the user's overall points locally.
if (result.points_earned > 0) {
// TODO: It would be better to store userInfo properties directly
// That way notificaitons will go out automatically.
// var userInfo = CurrentUser.get("userInfo");
// userInfo.points += result.points_earned;
saveUserInfo(user.get("userInfo"));
}
editVideo((video) =>
video.merge({
points: newPoints,
completed: result.is_video_completed,
started: !result.is_video_completed,
lastSecondWatched: lastSecondWatched
}));
// Update locally stored cached info
if (result.is_video_completed) {
if (startedEntityIds.contains(getId(topicTreeNode))) {
startedEntityIds = startedEntityIds.remove(startedEntityIds.indexOf(getId(topicTreeNode)));
editStartedEntityIds(() => startedEntityIds);
}
if (!completedEntityIds.contains(getId(topicTreeNode))) {
completedEntityIds = completedEntityIds.unshift(getId(topicTreeNode));
editCompletedEntityIds(() => completedEntityIds);
}
} else {
if (!startedEntityIds.contains(getId(topicTreeNode))) {
startedEntityIds = startedEntityIds.unshift(getId(topicTreeNode));
editStartedEntityIds(() => startedEntityIds);
}
}
var foundUserVideo = userVideos.find((info) =>
info.getIn(["video", "id"]) === getId(topicTreeNode));
if (foundUserVideo) {
foundUserVideo = foundUserVideo.toJS();
}
var isNew = !foundUserVideo;
foundUserVideo = foundUserVideo || {
video: {
id: getId(topicTreeNode)
},
duration: getDuration(topicTreeNode)
};
foundUserVideo["points"] = newPoints;
foundUserVideo["last_second_watched"] = lastSecondWatched;
if (isNew) {
userVideos = userVideos.unshift(Immutable.fromJS(foundUserVideo));
editUserVideos(() => userVideos);
}
saveStarted(user.get("userInfo"), startedEntityIds);
saveCompleted(user.get("userInfo"), completedEntityIds);
saveUserVideos(user.get("userInfo"), userVideos);
resolve({
completed: result.is_video_completed,
lastSecondWatched: result.last_second_watched,
pointsEarned: result.points_earned,
youtubeId: result.youtube_id,
videoId,
id: getId(topicTreeNode)
});
}).catch(() => {
reject();
});
});
};
export const reportArticleRead = (user, topicTreeNode, editUser) => {
return new Promise((resolve, reject) => {
if (!isSignedIn()) {
return setTimeout(resolve, 0);
}
APIClient.reportArticleRead(getId(topicTreeNode)).then((result) => {
Util.log("reported article complete: %o", result);
let completedEntityIds = user.get("completedEntityIds");
if (!completedEntityIds.contains(getId(topicTreeNode))) {
completedEntityIds = completedEntityIds.unshift(getId(topicTreeNode));
const editCompletedEntityIds = editorForPath(editUser, "completedEntityIds");
editCompletedEntityIds(() => completedEntityIds);
}
saveCompleted(user.get("userInfo"), completedEntityIds);
resolve(result);
}).catch(() => {
reject();
});
});
};
export const refreshLoggedInInfo = (user, editUser, forceRefreshAllInfo) => {
return new Promise((resolve, reject) => {
if (!isSignedIn()) {
return resolve();
}
// Get the user profile info
APIClient.getUserInfo().then((result) => {
Util.log("getUserInfo: %o", result);
const userInfo = Immutable.fromJS({
avatarUrl: result.avatar_url,
joined: result.joined,
nickname: result.nickname,
username: result.username,
points: result.points,
badgeCounts: result.badge_counts
});
editUser((user) => user.set("userInfo", userInfo));
saveUserInfo(userInfo.toJS());
var result = loadLocalStorageData(userInfo);
if (!forceRefreshAllInfo && result.completedEntityIds) {
Util.log("User info only obtained. Not obtaining user data because we have it cached already!");
return result;
}
// The call is needed for completed/in progress status of content items
// Unlike getUserVideos, this includes both articles and videos.
return APIClient.getUserProgress();
}).then((data) => {
Util.log("getUserProgress: %o", data);
// data.complete will be returned from the API but not when loaded
// directly from localStorage. When loaded directly from localstorage
// you'll already have result.startedEntityIds.
if (data.complete) {
// Get rid of the 'a' and 'v' prefixes, and set the completed / started
// attributes accordingly.
data.startedEntityIds = _.map(data.started, function(e) {
return e.substring(1);
});
data.completedEntityIds = _.map(data.complete, function(e) {
return e.substring(1);
});
// Save to local storage
saveStarted(user.get("userInfo"), data.startedEntityIds);
saveCompleted(user.get("userInfo"), data.completedEntityIds);
}
editUser((user) => user.merge({
startedEntityIds: data.startedEntityIds,
completedEntityIds: data.completedEntityIds,
}));
return APIClient.getUserVideos();
}).then((userVideosResults) => {
saveUserVideos(user.get("userInfo"), userVideosResults);
return APIClient.getUserExercises();
}).then((userExercisesResults) => {
saveUserExercises(user.get("userInfo"), userExercisesResults);
resolve();
}).catch(() => {
reject();
});
});
};
| Fix locally updating user points as video progress is made
| src/user.js | Fix locally updating user points as video progress is made | <ide><path>rc/user.js
<ide> // If we're just getting a completion of a video update
<ide> // the user's overall points locally.
<ide> if (result.points_earned > 0) {
<del> // TODO: It would be better to store userInfo properties directly
<del> // That way notificaitons will go out automatically.
<del> // var userInfo = CurrentUser.get("userInfo");
<del> // userInfo.points += result.points_earned;
<del> saveUserInfo(user.get("userInfo"));
<add> var userInfo = user.get("userInfo");
<add> userInfo = userInfo.set("points",
<add> userInfo.get("points") + result.points_earned);
<add> editUserInfo(() => userInfo);
<add> saveUserInfo(userInfo);
<ide> }
<ide>
<ide> editVideo((video) => |
|
Java | apache-2.0 | 063205affa3dd5f7fc99965d76d63246f23843b0 | 0 | HiromuHota/pentaho-kettle,pminutillo/pentaho-kettle,SergeyTravin/pentaho-kettle,ddiroma/pentaho-kettle,marcoslarsen/pentaho-kettle,tmcsantos/pentaho-kettle,skofra0/pentaho-kettle,pminutillo/pentaho-kettle,ddiroma/pentaho-kettle,matthewtckr/pentaho-kettle,flbrino/pentaho-kettle,skofra0/pentaho-kettle,wseyler/pentaho-kettle,rmansoor/pentaho-kettle,roboguy/pentaho-kettle,mkambol/pentaho-kettle,graimundo/pentaho-kettle,SergeyTravin/pentaho-kettle,tmcsantos/pentaho-kettle,dkincade/pentaho-kettle,dkincade/pentaho-kettle,bmorrise/pentaho-kettle,flbrino/pentaho-kettle,lgrill-pentaho/pentaho-kettle,rmansoor/pentaho-kettle,HiromuHota/pentaho-kettle,emartin-pentaho/pentaho-kettle,matthewtckr/pentaho-kettle,mdamour1976/pentaho-kettle,flbrino/pentaho-kettle,e-cuellar/pentaho-kettle,SergeyTravin/pentaho-kettle,DFieldFL/pentaho-kettle,tmcsantos/pentaho-kettle,pedrofvteixeira/pentaho-kettle,kurtwalker/pentaho-kettle,bmorrise/pentaho-kettle,graimundo/pentaho-kettle,pentaho/pentaho-kettle,pentaho/pentaho-kettle,e-cuellar/pentaho-kettle,lgrill-pentaho/pentaho-kettle,SergeyTravin/pentaho-kettle,lgrill-pentaho/pentaho-kettle,ddiroma/pentaho-kettle,mbatchelor/pentaho-kettle,emartin-pentaho/pentaho-kettle,HiromuHota/pentaho-kettle,mdamour1976/pentaho-kettle,bmorrise/pentaho-kettle,roboguy/pentaho-kettle,mbatchelor/pentaho-kettle,mkambol/pentaho-kettle,bmorrise/pentaho-kettle,skofra0/pentaho-kettle,pminutillo/pentaho-kettle,lgrill-pentaho/pentaho-kettle,marcoslarsen/pentaho-kettle,mkambol/pentaho-kettle,roboguy/pentaho-kettle,marcoslarsen/pentaho-kettle,mdamour1976/pentaho-kettle,HiromuHota/pentaho-kettle,dkincade/pentaho-kettle,ccaspanello/pentaho-kettle,marcoslarsen/pentaho-kettle,pedrofvteixeira/pentaho-kettle,tmcsantos/pentaho-kettle,ddiroma/pentaho-kettle,graimundo/pentaho-kettle,tkafalas/pentaho-kettle,pedrofvteixeira/pentaho-kettle,tkafalas/pentaho-kettle,kurtwalker/pentaho-kettle,dkincade/pentaho-kettle,mbatchelor/pentaho-kettle,pminutillo/pentaho-kettle,kurtwalker/pentaho-kettle,pedrofvteixeira/pentaho-kettle,wseyler/pentaho-kettle,e-cuellar/pentaho-kettle,rmansoor/pentaho-kettle,graimundo/pentaho-kettle,skofra0/pentaho-kettle,kurtwalker/pentaho-kettle,wseyler/pentaho-kettle,tkafalas/pentaho-kettle,DFieldFL/pentaho-kettle,pentaho/pentaho-kettle,mkambol/pentaho-kettle,flbrino/pentaho-kettle,DFieldFL/pentaho-kettle,pentaho/pentaho-kettle,rmansoor/pentaho-kettle,wseyler/pentaho-kettle,tkafalas/pentaho-kettle,ccaspanello/pentaho-kettle,emartin-pentaho/pentaho-kettle,e-cuellar/pentaho-kettle,ccaspanello/pentaho-kettle,mbatchelor/pentaho-kettle,matthewtckr/pentaho-kettle,mdamour1976/pentaho-kettle,emartin-pentaho/pentaho-kettle,DFieldFL/pentaho-kettle,ccaspanello/pentaho-kettle,roboguy/pentaho-kettle,matthewtckr/pentaho-kettle | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.core;
import java.math.BigDecimal;
import java.util.Date;
import org.pentaho.di.core.exception.KettlePluginException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.injection.InjectionTypeConverter;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaFactory;
import org.pentaho.di.core.row.value.ValueMetaNone;
import org.pentaho.di.repository.LongObjectId;
import org.pentaho.di.repository.ObjectId;
public class RowMetaAndData implements Cloneable {
private RowMetaInterface rowMeta;
private Object[] data;
public RowMetaAndData() {
clear();
}
/**
* @param rowMeta
* @param data
*/
public RowMetaAndData( RowMetaInterface rowMeta, Object... data ) {
this.rowMeta = rowMeta;
this.data = data;
}
@Override
public RowMetaAndData clone() {
RowMetaAndData c = new RowMetaAndData();
c.rowMeta = rowMeta.clone();
try {
c.data = rowMeta.cloneRow( data );
} catch ( KettleValueException e ) {
throw new RuntimeException( "Problem with clone row detected in RowMetaAndData", e );
}
return c;
}
@Override
public String toString() {
try {
return rowMeta.getString( data );
} catch ( KettleValueException e ) {
return rowMeta.toString() + ", error presenting data: " + e.toString();
}
}
/**
* @return the data
*/
public Object[] getData() {
return data;
}
/**
* @param data
* the data to set
*/
public void setData( Object[] data ) {
this.data = data;
}
/**
* @return the rowMeta
*/
public RowMetaInterface getRowMeta() {
return rowMeta;
}
/**
* @param rowMeta
* the rowMeta to set
*/
public void setRowMeta( RowMetaInterface rowMeta ) {
this.rowMeta = rowMeta;
}
@Override
public int hashCode() {
try {
return rowMeta.hashCode( data );
} catch ( KettleValueException e ) {
throw new RuntimeException(
"Row metadata and data: unable to calculate hashcode because of a data conversion problem", e );
}
}
@Override
public boolean equals( Object obj ) {
try {
return rowMeta.compare( data, ( (RowMetaAndData) obj ).getData() ) == 0;
} catch ( KettleValueException e ) {
throw new RuntimeException(
"Row metadata and data: unable to compare rows because of a data conversion problem", e );
}
}
public void addValue( ValueMetaInterface valueMeta, Object valueData ) {
if ( valueMeta.isInteger() && ( valueData instanceof ObjectId ) ) {
valueData = new LongObjectId( (ObjectId) valueData ).longValue();
}
data = RowDataUtil.addValueData( data, rowMeta.size(), valueData );
rowMeta.addValueMeta( valueMeta );
}
public void addValue( String valueName, int valueType, Object valueData ) {
ValueMetaInterface v;
try {
v = ValueMetaFactory.createValueMeta( valueName, valueType );
} catch ( KettlePluginException e ) {
v = new ValueMetaNone( valueName );
}
addValue( v, valueData );
}
public void clear() {
rowMeta = new RowMeta();
data = new Object[] {};
}
public long getInteger( String valueName, long def ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return getInteger( idx, def );
}
public long getInteger( int index, long def ) throws KettleValueException {
Long number = rowMeta.getInteger( data, index );
if ( number == null ) {
return def;
}
return number.longValue();
}
public Long getInteger( String valueName ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return rowMeta.getInteger( data, idx );
}
public Long getInteger( int index ) throws KettleValueException {
return rowMeta.getInteger( data, index );
}
public double getNumber( String valueName, double def ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return getNumber( idx, def );
}
public double getNumber( int index, double def ) throws KettleValueException {
Double number = rowMeta.getNumber( data, index );
if ( number == null ) {
return def;
}
return number.doubleValue();
}
public Date getDate( String valueName, Date def ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return getDate( idx, def );
}
public Date getDate( int index, Date def ) throws KettleValueException {
Date date = rowMeta.getDate( data, index );
if ( date == null ) {
return def;
}
return date;
}
public BigDecimal getBigNumber( String valueName, BigDecimal def ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return getBigNumber( idx, def );
}
public BigDecimal getBigNumber( int index, BigDecimal def ) throws KettleValueException {
BigDecimal number = rowMeta.getBigNumber( data, index );
if ( number == null ) {
return def;
}
return number;
}
public boolean getBoolean( String valueName, boolean def ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return getBoolean( idx, def );
}
public boolean getBoolean( int index, boolean def ) throws KettleValueException {
Boolean b = rowMeta.getBoolean( data, index );
if ( b == null ) {
return def;
}
return b.booleanValue();
}
public String getString( String valueName, String def ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return getString( idx, def );
}
public String getString( int index, String def ) throws KettleValueException {
String string = rowMeta.getString( data, index );
if ( string == null ) {
return def;
}
return string;
}
public byte[] getBinary( String valueName, byte[] def ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return getBinary( idx, def );
}
public byte[] getBinary( int index, byte[] def ) throws KettleValueException {
byte[] bin = rowMeta.getBinary( data, index );
if ( bin == null ) {
return def;
}
return bin;
}
public int compare( RowMetaAndData compare, int[] is, boolean[] bs ) throws KettleValueException {
return rowMeta.compare( data, compare.getData(), is );
}
public boolean isNumeric( int index ) {
return rowMeta.getValueMeta( index ).isNumeric();
}
public int size() {
return rowMeta.size();
}
public ValueMetaInterface getValueMeta( int index ) {
return rowMeta.getValueMeta( index );
}
public boolean isEmptyValue( String valueName ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
ValueMetaInterface metaType = rowMeta.getValueMeta( idx );
// find by source value type
switch ( metaType.getType() ) {
case ValueMetaInterface.TYPE_STRING:
return rowMeta.getString( data, idx ) == null;
case ValueMetaInterface.TYPE_BOOLEAN:
return rowMeta.getBoolean( data, idx ) == null;
case ValueMetaInterface.TYPE_INTEGER:
return rowMeta.getInteger( data, idx ) == null;
case ValueMetaInterface.TYPE_NUMBER:
return rowMeta.getNumber( data, idx ) == null;
case ValueMetaInterface.TYPE_BIGNUMBER:
return rowMeta.getBigNumber( data, idx ) == null;
case ValueMetaInterface.TYPE_BINARY:
return rowMeta.getBinary( data, idx ) == null;
case ValueMetaInterface.TYPE_DATE:
case ValueMetaInterface.TYPE_TIMESTAMP:
return rowMeta.getDate( data, idx ) == null;
case ValueMetaInterface.TYPE_INET:
return rowMeta.getString( data, idx ) == null;
}
throw new KettleValueException( "Unknown source type: " + metaType.getTypeDesc() );
}
/**
* Converts string value into specified type. Used for constant injection.
*/
public static Object getStringAsJavaType( String vs, Class<?> destinationType, InjectionTypeConverter converter )
throws KettleValueException {
if ( String.class.isAssignableFrom( destinationType ) ) {
return converter.string2string( vs );
} else if ( int.class.isAssignableFrom( destinationType ) ) {
return converter.string2intPrimitive( vs );
} else if ( Integer.class.isAssignableFrom( destinationType ) ) {
return converter.string2integer( vs );
} else if ( long.class.isAssignableFrom( destinationType ) ) {
return converter.string2longPrimitive( vs );
} else if ( Long.class.isAssignableFrom( destinationType ) ) {
return converter.string2long( vs );
} else if ( boolean.class.isAssignableFrom( destinationType ) ) {
return converter.string2booleanPrimitive( vs );
} else if ( Boolean.class.isAssignableFrom( destinationType ) ) {
return converter.string2boolean( vs );
} else if ( destinationType.isEnum() ) {
return converter.string2enum( destinationType, vs );
} else {
throw new RuntimeException( "Wrong value conversion to " + destinationType );
}
}
/**
* Returns value as specified java type using converter. Used for metadata injection.
*/
public Object getAsJavaType( String valueName, Class<?> destinationType, InjectionTypeConverter converter )
throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
ValueMetaInterface metaType = rowMeta.getValueMeta( idx );
// find by source value type
switch ( metaType.getType() ) {
case ValueMetaInterface.TYPE_STRING:
String vs = rowMeta.getString( data, idx );
return getStringAsJavaType( vs, destinationType, converter );
case ValueMetaInterface.TYPE_BOOLEAN:
Boolean vb = rowMeta.getBoolean( data, idx );
if ( String.class.isAssignableFrom( destinationType ) ) {
return converter.boolean2string( vb );
} else if ( int.class.isAssignableFrom( destinationType ) ) {
return converter.boolean2intPrimitive( vb );
} else if ( Integer.class.isAssignableFrom( destinationType ) ) {
return converter.boolean2integer( vb );
} else if ( long.class.isAssignableFrom( destinationType ) ) {
return converter.boolean2longPrimitive( vb );
} else if ( Long.class.isAssignableFrom( destinationType ) ) {
return converter.boolean2long( vb );
} else if ( boolean.class.isAssignableFrom( destinationType ) ) {
return converter.boolean2booleanPrimitive( vb );
} else if ( Boolean.class.isAssignableFrom( destinationType ) ) {
return converter.boolean2boolean( vb );
} else if ( destinationType.isEnum() ) {
return converter.boolean2enum( destinationType, vb );
} else {
throw new RuntimeException( "Wrong value conversion to " + destinationType );
}
case ValueMetaInterface.TYPE_INTEGER:
Long vi = rowMeta.getInteger( data, idx );
if ( String.class.isAssignableFrom( destinationType ) ) {
return converter.integer2string( vi );
} else if ( int.class.isAssignableFrom( destinationType ) ) {
return converter.integer2intPrimitive( vi );
} else if ( Integer.class.isAssignableFrom( destinationType ) ) {
return converter.integer2integer( vi );
} else if ( long.class.isAssignableFrom( destinationType ) ) {
return converter.integer2longPrimitive( vi );
} else if ( Long.class.isAssignableFrom( destinationType ) ) {
return converter.integer2long( vi );
} else if ( boolean.class.isAssignableFrom( destinationType ) ) {
return converter.integer2booleanPrimitive( vi );
} else if ( Boolean.class.isAssignableFrom( destinationType ) ) {
return converter.integer2boolean( vi );
} else if ( destinationType.isEnum() ) {
return converter.integer2enum( destinationType, vi );
} else {
throw new RuntimeException( "Wrong value conversion to " + destinationType );
}
case ValueMetaInterface.TYPE_NUMBER:
Double vn = rowMeta.getNumber( data, idx );
if ( String.class.isAssignableFrom( destinationType ) ) {
return converter.number2string( vn );
} else if ( int.class.isAssignableFrom( destinationType ) ) {
return converter.number2intPrimitive( vn );
} else if ( Integer.class.isAssignableFrom( destinationType ) ) {
return converter.number2integer( vn );
} else if ( long.class.isAssignableFrom( destinationType ) ) {
return converter.number2longPrimitive( vn );
} else if ( Long.class.isAssignableFrom( destinationType ) ) {
return converter.number2long( vn );
} else if ( boolean.class.isAssignableFrom( destinationType ) ) {
return converter.number2booleanPrimitive( vn );
} else if ( Boolean.class.isAssignableFrom( destinationType ) ) {
return converter.number2boolean( vn );
} else if ( destinationType.isEnum() ) {
return converter.number2enum( destinationType, vn );
} else {
throw new RuntimeException( "Wrong value conversion to " + destinationType );
}
}
throw new KettleValueException( "Unknown conversion from " + metaType.getTypeDesc() + " into " + destinationType );
}
public void removeValue( String valueName ) throws KettleValueException {
int index = rowMeta.indexOfValue( valueName );
if ( index < 0 ) {
throw new KettleValueException( "Unable to find '" + valueName + "' in the row" );
}
removeValue( index );
}
public void removeValue( int index ) {
rowMeta.removeValueMeta( index );
data = RowDataUtil.removeItem( data, index );
}
public void mergeRowMetaAndData( RowMetaAndData rowMetaAndData, String originStepName ) {
int originalMetaSize = rowMeta.size();
rowMeta.mergeRowMeta( rowMetaAndData.getRowMeta(), originStepName );
data = RowDataUtil.addRowData( data, originalMetaSize, rowMetaAndData.getData() );
}
}
| core/src/main/java/org/pentaho/di/core/RowMetaAndData.java | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.core;
import java.math.BigDecimal;
import java.util.Date;
import org.pentaho.di.core.exception.KettlePluginException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.injection.InjectionTypeConverter;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaFactory;
import org.pentaho.di.core.row.value.ValueMetaNone;
import org.pentaho.di.repository.LongObjectId;
import org.pentaho.di.repository.ObjectId;
public class RowMetaAndData implements Cloneable {
private RowMetaInterface rowMeta;
private Object[] data;
public RowMetaAndData() {
clear();
}
/**
* @param rowMeta
* @param data
*/
public RowMetaAndData( RowMetaInterface rowMeta, Object... data ) {
this.rowMeta = rowMeta;
this.data = data;
}
@Override
public RowMetaAndData clone() {
RowMetaAndData c = new RowMetaAndData();
c.rowMeta = rowMeta.clone();
try {
c.data = rowMeta.cloneRow( data );
} catch ( KettleValueException e ) {
throw new RuntimeException( "Problem with clone row detected in RowMetaAndData", e );
}
return c;
}
@Override
public String toString() {
try {
return rowMeta.getString( data );
} catch ( KettleValueException e ) {
return rowMeta.toString() + ", error presenting data: " + e.toString();
}
}
/**
* @return the data
*/
public Object[] getData() {
return data;
}
/**
* @param data
* the data to set
*/
public void setData( Object[] data ) {
this.data = data;
}
/**
* @return the rowMeta
*/
public RowMetaInterface getRowMeta() {
return rowMeta;
}
/**
* @param rowMeta
* the rowMeta to set
*/
public void setRowMeta( RowMetaInterface rowMeta ) {
this.rowMeta = rowMeta;
}
@Override
public int hashCode() {
try {
return rowMeta.hashCode( data );
} catch ( KettleValueException e ) {
throw new RuntimeException(
"Row metadata and data: unable to calculate hashcode because of a data conversion problem", e );
}
}
@Override
public boolean equals( Object obj ) {
try {
return rowMeta.compare( data, ( (RowMetaAndData) obj ).getData() ) == 0;
} catch ( KettleValueException e ) {
throw new RuntimeException(
"Row metadata and data: unable to compare rows because of a data conversion problem", e );
}
}
public void addValue( ValueMetaInterface valueMeta, Object valueData ) {
if ( valueMeta.isInteger() && ( valueData instanceof ObjectId ) ) {
valueData = new LongObjectId( (ObjectId) valueData ).longValue();
}
data = RowDataUtil.addValueData( data, rowMeta.size(), valueData );
rowMeta.addValueMeta( valueMeta );
}
public void addValue( String valueName, int valueType, Object valueData ) {
ValueMetaInterface v;
try {
v = ValueMetaFactory.createValueMeta( valueName, valueType );
} catch ( KettlePluginException e ) {
v = new ValueMetaNone( valueName );
}
addValue( v, valueData );
}
public void clear() {
rowMeta = new RowMeta();
data = new Object[] {};
}
public long getInteger( String valueName, long def ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return getInteger( idx, def );
}
public long getInteger( int index, long def ) throws KettleValueException {
Long number = rowMeta.getInteger( data, index );
if ( number == null ) {
return def;
}
return number.longValue();
}
public Long getInteger( String valueName ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return rowMeta.getInteger( data, idx );
}
public Long getInteger( int index ) throws KettleValueException {
return rowMeta.getInteger( data, index );
}
public double getNumber( String valueName, double def ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return getNumber( idx, def );
}
public double getNumber( int index, double def ) throws KettleValueException {
Double number = rowMeta.getNumber( data, index );
if ( number == null ) {
return def;
}
return number.doubleValue();
}
public Date getDate( String valueName, Date def ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return getDate( idx, def );
}
public Date getDate( int index, Date def ) throws KettleValueException {
Date date = rowMeta.getDate( data, index );
if ( date == null ) {
return def;
}
return date;
}
public BigDecimal getBigNumber( String valueName, BigDecimal def ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return getBigNumber( idx, def );
}
public BigDecimal getBigNumber( int index, BigDecimal def ) throws KettleValueException {
BigDecimal number = rowMeta.getBigNumber( data, index );
if ( number == null ) {
return def;
}
return number;
}
public boolean getBoolean( String valueName, boolean def ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return getBoolean( idx, def );
}
public boolean getBoolean( int index, boolean def ) throws KettleValueException {
Boolean b = rowMeta.getBoolean( data, index );
if ( b == null ) {
return def;
}
return b.booleanValue();
}
public String getString( String valueName, String def ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return getString( idx, def );
}
public String getString( int index, String def ) throws KettleValueException {
String string = rowMeta.getString( data, index );
if ( string == null ) {
return def;
}
return string;
}
public byte[] getBinary( String valueName, byte[] def ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
return getBinary( idx, def );
}
public byte[] getBinary( int index, byte[] def ) throws KettleValueException {
byte[] bin = rowMeta.getBinary( data, index );
if ( bin == null ) {
return def;
}
return bin;
}
public int compare( RowMetaAndData compare, int[] is, boolean[] bs ) throws KettleValueException {
return rowMeta.compare( data, compare.getData(), is );
}
public boolean isNumeric( int index ) {
return rowMeta.getValueMeta( index ).isNumeric();
}
public int size() {
return rowMeta.size();
}
public ValueMetaInterface getValueMeta( int index ) {
return rowMeta.getValueMeta( index );
}
public boolean isEmptyValue( String valueName ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
ValueMetaInterface metaType = rowMeta.getValueMeta( idx );
// find by source value type
switch ( metaType.getType() ) {
case ValueMetaInterface.TYPE_STRING:
return rowMeta.getString( data, idx ) == null;
case ValueMetaInterface.TYPE_BOOLEAN:
return rowMeta.getBoolean( data, idx ) == null;
case ValueMetaInterface.TYPE_INTEGER:
return rowMeta.getInteger( data, idx ) == null;
case ValueMetaInterface.TYPE_NUMBER:
return rowMeta.getNumber( data, idx ) == null;
case ValueMetaInterface.TYPE_BIGNUMBER:
return rowMeta.getBigNumber( data, idx ) == null;
case ValueMetaInterface.TYPE_BINARY:
return rowMeta.getBinary( data, idx ) == null;
case ValueMetaInterface.TYPE_DATE:
case ValueMetaInterface.TYPE_TIMESTAMP:
return rowMeta.getDate( data, idx ) == null;
case ValueMetaInterface.TYPE_INET:
return rowMeta.getString( data, idx ) == null;
}
throw new KettleValueException( "Unknown source type: " + metaType.getTypeDesc() );
}
/**
* Converts string value into specified type. Used for constant injection.
*/
public static Object getStringAsJavaType( String vs, Class<?> destinationType, InjectionTypeConverter converter )
throws KettleValueException {
if ( String.class.isAssignableFrom( destinationType ) ) {
return converter.string2string( vs );
} else if ( int.class.isAssignableFrom( destinationType ) ) {
return converter.string2intPrimitive( vs );
} else if ( Integer.class.isAssignableFrom( destinationType ) ) {
return converter.string2integer( vs );
} else if ( long.class.isAssignableFrom( destinationType ) ) {
return converter.string2longPrimitive( vs );
} else if ( Long.class.isAssignableFrom( destinationType ) ) {
return converter.string2long( vs );
} else if ( boolean.class.isAssignableFrom( destinationType ) ) {
return converter.string2booleanPrimitive( vs );
} else if ( Boolean.class.isAssignableFrom( destinationType ) ) {
return converter.string2boolean( vs );
} else if ( destinationType.isEnum() ) {
return converter.string2enum( destinationType, vs );
} else {
throw new RuntimeException( "Wrong value conversion to " + destinationType );
}
}
/**
* Returns value as specified java type using converter. Used for metadata injection.
*/
public Object getAsJavaType( String valueName, Class<?> destinationType, InjectionTypeConverter converter )
throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
ValueMetaInterface metaType = rowMeta.getValueMeta( idx );
// find by source value type
switch ( metaType.getType() ) {
case ValueMetaInterface.TYPE_STRING:
String vs = rowMeta.getString( data, idx );
return getStringAsJavaType( vs, destinationType, converter );
case ValueMetaInterface.TYPE_BOOLEAN:
Boolean vb = rowMeta.getBoolean( data, idx );
if ( String.class.isAssignableFrom( destinationType ) ) {
return converter.boolean2string( vb );
} else if ( int.class.isAssignableFrom( destinationType ) ) {
return converter.boolean2intPrimitive( vb );
} else if ( Integer.class.isAssignableFrom( destinationType ) ) {
return converter.boolean2integer( vb );
} else if ( long.class.isAssignableFrom( destinationType ) ) {
return converter.boolean2longPrimitive( vb );
} else if ( Long.class.isAssignableFrom( destinationType ) ) {
return converter.boolean2long( vb );
} else if ( boolean.class.isAssignableFrom( destinationType ) ) {
return converter.boolean2booleanPrimitive( vb );
} else if ( Boolean.class.isAssignableFrom( destinationType ) ) {
return converter.boolean2boolean( vb );
} else if ( destinationType.isEnum() ) {
return converter.boolean2enum( destinationType, vb );
} else {
throw new RuntimeException( "Wrong value conversion to " + destinationType );
}
case ValueMetaInterface.TYPE_INTEGER:
Long vi = rowMeta.getInteger( data, idx );
if ( String.class.isAssignableFrom( destinationType ) ) {
return converter.integer2string( vi );
} else if ( int.class.isAssignableFrom( destinationType ) ) {
return converter.integer2intPrimitive( vi );
} else if ( Integer.class.isAssignableFrom( destinationType ) ) {
return converter.integer2integer( vi );
} else if ( long.class.isAssignableFrom( destinationType ) ) {
return converter.integer2longPrimitive( vi );
} else if ( Long.class.isAssignableFrom( destinationType ) ) {
return converter.integer2long( vi );
} else if ( boolean.class.isAssignableFrom( destinationType ) ) {
return converter.integer2booleanPrimitive( vi );
} else if ( Boolean.class.isAssignableFrom( destinationType ) ) {
return converter.integer2boolean( vi );
} else if ( destinationType.isEnum() ) {
return converter.integer2enum( destinationType, vi );
} else {
throw new RuntimeException( "Wrong value conversion to " + destinationType );
}
case ValueMetaInterface.TYPE_NUMBER:
Double vn = rowMeta.getNumber( data, idx );
if ( String.class.isAssignableFrom( destinationType ) ) {
return converter.number2string( vn );
} else if ( int.class.isAssignableFrom( destinationType ) ) {
return converter.number2intPrimitive( vn );
} else if ( Integer.class.isAssignableFrom( destinationType ) ) {
return converter.number2integer( vn );
} else if ( long.class.isAssignableFrom( destinationType ) ) {
return converter.number2longPrimitive( vn );
} else if ( Long.class.isAssignableFrom( destinationType ) ) {
return converter.number2long( vn );
} else if ( boolean.class.isAssignableFrom( destinationType ) ) {
return converter.number2booleanPrimitive( vn );
} else if ( Boolean.class.isAssignableFrom( destinationType ) ) {
return converter.number2boolean( vn );
} else if ( destinationType.isEnum() ) {
return converter.number2enum( destinationType, vn );
} else {
throw new RuntimeException( "Wrong value conversion to " + destinationType );
}
}
throw new KettleValueException( "Unknown conversion from " + metaType.getTypeDesc() + " into " + destinationType );
}
public void removeValue( String valueName ) throws KettleValueException {
int index = rowMeta.indexOfValue( valueName );
if ( index < 0 ) {
throw new KettleValueException( "Unable to find '" + valueName + "' in the row" );
}
removeValue( index );
}
public void removeValue( int index ) {
rowMeta.removeValueMeta( index );
data = RowDataUtil.removeItem( data, index );
}
}
| [BACKLOG-21321] Avro Streaming enhancments ( pass fields from prior step, handle multiple rows containing avro content, add seperator bar and fix Mac UI )
| core/src/main/java/org/pentaho/di/core/RowMetaAndData.java | [BACKLOG-21321] Avro Streaming enhancments ( pass fields from prior step, handle multiple rows containing avro content, add seperator bar and fix Mac UI ) | <ide><path>ore/src/main/java/org/pentaho/di/core/RowMetaAndData.java
<ide> rowMeta.removeValueMeta( index );
<ide> data = RowDataUtil.removeItem( data, index );
<ide> }
<add>
<add> public void mergeRowMetaAndData( RowMetaAndData rowMetaAndData, String originStepName ) {
<add> int originalMetaSize = rowMeta.size();
<add> rowMeta.mergeRowMeta( rowMetaAndData.getRowMeta(), originStepName );
<add> data = RowDataUtil.addRowData( data, originalMetaSize, rowMetaAndData.getData() );
<add> }
<ide> } |
|
JavaScript | mit | a7dbce88aceca898c578a7fee62644feb9e07fd2 | 0 | code42day/google-polyline | var polyline = require( '..' )
var assert = require( 'assert' )
suite( 'Google Polyline Example', function() {
test( 'encode', function() {
var points = [
[ 38.5, -120.2 ],
[ 40.7, -120.95 ],
[ 43.252, -126.453 ]
]
var encoded = polyline.encode( points )
assert.equal( encoded, '_p~iF~ps|U_ulLnnqC_mqNvxq`@' )
})
test( 'decode', function() {
var points = polyline.decode( '_p~iF~ps|U_ulLnnqC_mqNvxq`@' )
var decoded = [
[ 38.5, -120.2 ],
[ 40.7, -120.95 ],
[ 43.252, -126.453 ]
]
assert.deepEqual( points, decoded )
})
})
| test/examples.js | var polyline = require( '..' )
var assert = require( 'assert' )
suite( 'Google Polyline Example', function() {
test( 'encode', function() {
var points = [
[ 38.5, -120.2 ],
[ 40.7, -120.95 ],
[ 43.252, -126.453 ]
]
var encoded = polyline.encode( points )
assert.equal( encoded, '_p~iF~ps|U_ulLnnqC_mqNvxq`@' )
})
test( 'decode' )
})
| Update test: Add decoding test
| test/examples.js | Update test: Add decoding test | <ide><path>est/examples.js
<ide>
<ide> })
<ide>
<del> test( 'decode' )
<add> test( 'decode', function() {
<add>
<add> var points = polyline.decode( '_p~iF~ps|U_ulLnnqC_mqNvxq`@' )
<add> var decoded = [
<add> [ 38.5, -120.2 ],
<add> [ 40.7, -120.95 ],
<add> [ 43.252, -126.453 ]
<add> ]
<add>
<add> assert.deepEqual( points, decoded )
<add>
<add> })
<ide>
<ide> }) |
|
Java | mit | 0f72e87378669fbd8437a8a4ac00d9e79d523e86 | 0 | thorinside/StandOut,loulousky/StandOut,917386389/StandOut,juoni/StandOut,lokesht/StandOut,omegasoft7/StandOut,pingpongboss/StandOut,Ringares/StandOut,gregko/StandOut,mandrigin/StandOut,sherpya/StandOut,0xD34D/StandOut,thorinside/StandOut,leasual/StandOut,wklin8607/StandOut | package wei.mark.standout;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Extend this class to easily create and manage floating StandOut windows.
*
* @author Mark Wei <[email protected]>
*
*/
public abstract class StandOutWindow extends Service {
private static final String TAG = "StandOutWindow";
/**
* StandOut window id: You may use this sample id for your first window.
*/
public static final int DEFAULT_ID = 0;
/**
* Special StandOut window id: You may NOT use this id for any windows.
*/
public static final int ONGOING_NOTIFICATION_ID = -1;
/**
* StandOut window id: You may use this id when you want it to be
* disregarded. The system makes no distinction for this id; it is only used
* to improve code readability.
*/
public static final int DISREGARD_ID = -2;
/**
* Intent action: Show a new window corresponding to the id.
*/
public static final String ACTION_SHOW = "SHOW";
/**
* Intent action: Restore a previously hidden window corresponding to the
* id. The window should be previously hidden with {@link #ACTION_HIDE}.
*/
public static final String ACTION_RESTORE = "RESTORE";
/**
* Intent action: Close an existing window with an existing id.
*/
public static final String ACTION_CLOSE = "CLOSE";
/**
* Intent action: Close all existing windows.
*/
public static final String ACTION_CLOSE_ALL = "CLOSE_ALL";
/**
* Intent action: Send data to a new or existing window.
*/
public static final String ACTION_SEND_DATA = "SEND_DATA";
/**
* Intent action: Hide an existing window with an existing id. To enable the
* ability to restore this window, make sure you implement
* {@link #getHiddenNotification(int)}.
*/
public static final String ACTION_HIDE = "HIDE";
/**
* Flags to be returned from {@link StandOutWindow#getFlags(int)}. This
* class was created to avoid polluting the flags namespace.
*
* @author Mark Wei <[email protected]>
*
*/
public static class StandOutFlags {
private static int flag_counter = 0;
/**
* This default flag indicates that the window requires no window
* decorations (titlebar, hide/close buttons, resize handle, etc).
*/
public static final int FLAG_DECORATION_NONE = 0x00000000;
/**
* Setting this flag indicates that the window wants the system provided
* window decorations (titlebar, hide/close buttons, resize handle,
* etc).
*/
public static final int FLAG_DECORATION_SYSTEM = 1 << flag_counter++;
/**
* If {@link #FLAG_DECORATION_SYSTEM} is set, setting this flag
* indicates that the window decorator should NOT provide a close
* button.
*/
public static final int FLAG_DECORATION_CLOSE_DISABLE = 1 << flag_counter++;
/**
* If {@link #FLAG_DECORATION_SYSTEM} is set, setting this flag
* indicates that the window decorator should NOT provide a resize
* handle.
*/
public static final int FLAG_DECORATION_RESIZE_DISABLE = 1 << flag_counter++;
/**
* If {@link #FLAG_DECORATION_SYSTEM} is set, setting this flag
* indicates that the window decorator should NOT provide a resize
* handle.
*/
public static final int FLAG_DECORATION_MOVE_DISABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that the window can be moved by dragging
* the body.
*
* <p>
* Note that if {@link #FLAG_DECORATION_SYSTEM} is set, the window can
* always be moved by dragging the titlebar.
*/
public static final int FLAG_BODY_MOVE_ENABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that windows are able to be hidden, that
* {@link StandOutWindow#getHiddenIcon(int)},
* {@link StandOutWindow#getHiddenTitle(int)}, and
* {@link StandOutWindow#getHiddenMessage(int)} are implemented, and
* that the system window decorator should provide a hide button if
* {@link #FLAG_DECORATION_SYSTEM} is set.
*/
public static final int FLAG_WINDOW_HIDE_ENABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that the window should be brought to the
* front upon user interaction.
*
* <p>
* Note that if you set this flag, there is a noticeable flashing of the
* window during {@link MotionEvent#ACTION_UP}. This the hack that
* allows the system to bring the window to the front.
*/
public static final int FLAG_WINDOW_BRING_TO_FRONT_ON_TOUCH = 1 << flag_counter++;
/**
* Setting this flag indicates that the window should be brought to the
* front upon user tap.
*
* <p>
* Note that if you set this flag, there is a noticeable flashing of the
* window during {@link MotionEvent#ACTION_UP}. This the hack that
* allows the system to bring the window to the front.
*/
public static final int FLAG_WINDOW_BRING_TO_FRONT_ON_TAP = 1 << flag_counter++;
/**
* Setting this flag indicates that the system should keep the window's
* position within the edges of the screen. If this flag is not set, the
* window will be able to be dragged off of the screen.
*
* <p>
* If this flag is set, the window's {@link Gravity} is recommended to
* be {@link Gravity#TOP} | {@link Gravity#LEFT}. If the gravity is
* anything other than TOP|LEFT, then even though the window will be
* displayed within the edges, it will behave as if the user can drag it
* off the screen.
*
*/
public static final int FLAG_WINDOW_EDGE_LIMITS_ENABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that the window does not need focus. If
* this flag is set, the system will not take care of setting and
* unsetting the focus of windows based on user touch and key events.
*
* <p>
* You will most likely need focus if your window contains any of the
* following: Button, ListView, EditText.
*
* <p>
* The benefit of disabling focus is that your window will not consume
* any key events. Normally, focused windows will consume the Back and
* Menu keys.
*
* @see {@link StandOutWindow#focus(int)}
* @see {@link StandOutWindow#unfocus(int)}
*
*/
public static final int FLAG_WINDOW_FOCUSABLE_DISABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that the system should not change the
* window's visual state when focus is changed. If this flag is set, the
* implementation can choose to change the visual state in
* {@link StandOutWindow#onFocusChange(int, Window, boolean)}.
*
* @see {@link StandOutWindow.Window#onFocus(boolean)}
*
*/
public static final int FLAG_WINDOW_FOCUS_INDICATOR_DISABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that the system should disable all
* compatibility workarounds. The default behavior is to run
* {@link StandOutWindow#fixCompatibility(View, int)} on the view
* returned by the implementation.
*
* @see {@link StandOutWindow#fixCompatibility(View, int)}
*/
public static final int FLAG_FIX_COMPATIBILITY_ALL_DISABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that the system should disable all
* additional functionality. The default behavior is to run
* {@link StandOutWindow#addFunctionality(View, int)} on the view
* returned by the implementation.
*
* @see {@link StandOutWindow#addFunctionality(View, int)}
*/
public static final int FLAG_ADD_FUNCTIONALITY_ALL_DISABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that the system should disable adding the
* resize handle additional functionality.
*
* @see {@link StandOutWindow#addFunctionality(View, int)}
*/
public static final int FLAG_ADD_FUNCTIONALITY_RESIZE_DISABLE = 1 << flag_counter++;
}
/**
* Show a new window corresponding to the id, or restore a previously hidden
* window.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that will be used
* to create and manage the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
*
* @see #show(int)
*/
public static void show(Context context,
Class<? extends StandOutWindow> cls, int id) {
context.startService(getShowIntent(context, cls, id));
}
/**
* Hide the existing window corresponding to the id. To enable the ability
* to restore this window, make sure you implement
* {@link #getHiddenNotification(int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. The window must previously be
* shown.
* @see #hide(int)
*/
public static void hide(Context context,
Class<? extends StandOutWindow> cls, int id) {
context.startService(getShowIntent(context, cls, id));
}
/**
* Close an existing window with an existing id.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. The window must previously be
* shown.
* @see #close(int)
*/
public static void close(Context context,
Class<? extends StandOutWindow> cls, int id) {
context.startService(getCloseIntent(context, cls, id));
}
/**
* Close all existing windows.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @see #closeAll()
*/
public static void closeAll(Context context,
Class<? extends StandOutWindow> cls) {
context.startService(getCloseAllIntent(context, cls));
}
/**
* This allows windows of different applications to communicate with each
* other.
*
* <p>
* Send {@link Parceleable} data in a {@link Bundle} to a new or existing
* windows. The implementation of the recipient window can handle what to do
* with the data. To receive a result, provide the class and id of the
* sender.
*
* @param context
* A Context of the application package implementing the class of
* the sending window.
* @param toCls
* The Service's class extending {@link StandOutWindow} that is
* managing the receiving window.
* @param toId
* The id of the receiving window, or DISREGARD_ID.
* @param requestCode
* Provide a request code to declare what kind of data is being
* sent.
* @param data
* A bundle of parceleable data to be sent to the receiving
* window.
* @param fromCls
* Provide the class of the sending window if you want a result.
* @param fromId
* Provide the id of the sending window if you want a result.
* @see #sendData(int, Class, int, int, Bundle)
*/
public static void sendData(Context context,
Class<? extends StandOutWindow> toCls, int toId, int requestCode,
Bundle data, Class<? extends StandOutWindow> fromCls, int fromId) {
context.startService(getSendDataIntent(context, toCls, toId,
requestCode, data, fromCls, fromId));
}
/**
* See {@link #show(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that will be used
* to create and manage the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getShowIntent(Context context,
Class<? extends StandOutWindow> cls, int id) {
boolean cached = isCached(id, cls);
String action = cached ? ACTION_RESTORE : ACTION_SHOW;
Uri uri = cached ? Uri.parse("standout://" + cls + '/' + id) : null;
return new Intent(context, cls).putExtra("id", id).setAction(action)
.setData(uri);
}
/**
* See {@link #hide(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getHideIntent(Context context,
Class<? extends StandOutWindow> cls, int id) {
return new Intent(context, cls).putExtra("id", id).setAction(
ACTION_HIDE);
}
/**
* See {@link #close(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getCloseIntent(Context context,
Class<? extends StandOutWindow> cls, int id) {
return new Intent(context, cls).putExtra("id", id).setAction(
ACTION_CLOSE);
}
/**
* See {@link #closeAll(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getCloseAllIntent(Context context,
Class<? extends StandOutWindow> cls) {
return new Intent(context, cls).setAction(ACTION_CLOSE_ALL);
}
/**
* See {@link #sendData(Context, Class, int, int, Bundle, Class, int)}.
*
* @param context
* A Context of the application package implementing the class of
* the sending window.
* @param toCls
* The Service's class extending {@link StandOutWindow} that is
* managing the receiving window.
* @param toId
* The id of the receiving window.
* @param requestCode
* Provide a request code to declare what kind of data is being
* sent.
* @param data
* A bundle of parceleable data to be sent to the receiving
* window.
* @param fromCls
* If the sending window wants a result, provide the class of the
* sending window.
* @param fromId
* If the sending window wants a result, provide the id of the
* sending window.
* @return An {@link Intnet} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getSendDataIntent(Context context,
Class<? extends StandOutWindow> toCls, int toId, int requestCode,
Bundle data, Class<? extends StandOutWindow> fromCls, int fromId) {
return new Intent(context, toCls).putExtra("id", toId)
.putExtra("requestCode", requestCode)
.putExtra("wei.mark.standout.data", data)
.putExtra("wei.mark.standout.fromCls", fromCls)
.putExtra("fromId", fromId).setAction(ACTION_SEND_DATA);
}
// internal map of ids to shown/hidden views
private static Map<Class<? extends StandOutWindow>, Map<Integer, Window>> sWindows;
private static Window sFocusedWindow;
// static constructors
static {
sWindows = new HashMap<Class<? extends StandOutWindow>, Map<Integer, Window>>();
sFocusedWindow = null;
}
/**
* Returns whether the window corresponding to the class and id exists in
* the {@link #sWindows} cache.
*
* @param id
* The id representing the window.
* @param cls
* Class corresponding to the window.
* @return True if the window corresponding to the class and id exists in
* the cache, or false if it does not exist.
*/
private static boolean isCached(int id, Class<? extends StandOutWindow> cls) {
return getCache(id, cls) != null;
}
/**
* Returns the window corresponding to the id from the {@link #sWindows}
* cache.
*
* @param id
* The id representing the window.
* @param cls
* The class of the implementation of the window.
* @return The window corresponding to the id if it exists in the cache, or
* null if it does not.
*/
private static Window getCache(int id, Class<? extends StandOutWindow> cls) {
HashMap<Integer, Window> l2 = (HashMap<Integer, Window>) sWindows
.get(cls);
if (l2 == null) {
return null;
}
return l2.get(id);
}
/**
* Add the window corresponding to the id in the {@link #sWindows} cache.
*
* @param id
* The id representing the window.
* @param cls
* The class of the implementation of the window.
* @param window
* The window to be put in the cache.
*/
private static void putCache(int id, Class<? extends StandOutWindow> cls,
Window window) {
HashMap<Integer, Window> l2 = (HashMap<Integer, Window>) sWindows
.get(cls);
if (l2 == null) {
l2 = new HashMap<Integer, Window>();
sWindows.put(cls, l2);
}
l2.put(id, window);
}
/**
* Remove the window corresponding to the id from the {@link #sWindows}
* cache.
*
* @param id
* The id representing the window.
* @param cls
* The class of the implementation of the window.
*/
private static void removeCache(int id, Class<? extends StandOutWindow> cls) {
HashMap<Integer, Window> l2 = (HashMap<Integer, Window>) sWindows
.get(cls);
if (l2 != null) {
l2.remove(id);
if (l2.isEmpty()) {
sWindows.remove(cls);
}
}
}
/**
* Returns the size of the {@link #sWindows} cache.
*
* @return True if the cache corresponding to this class is empty, false if
* it is not empty.
* @param cls
* The class of the implementation of the window.
*/
private static int getCacheSize(Class<? extends StandOutWindow> cls) {
HashMap<Integer, Window> l2 = (HashMap<Integer, Window>) sWindows
.get(cls);
if (l2 == null) {
return 0;
}
return l2.size();
}
/**
* Returns the ids in the {@link #sWindows} cache.
*
* @param cls
* The class of the implementation of the window.
* @return The ids representing the cached windows.
*/
private static Set<Integer> getCacheIds(Class<? extends StandOutWindow> cls) {
HashMap<Integer, Window> l2 = (HashMap<Integer, Window>) sWindows
.get(cls);
if (l2 == null) {
return new HashSet<Integer>();
}
return l2.keySet();
}
// internal system services
private WindowManager mWindowManager;
private NotificationManager mNotificationManager;
private LayoutInflater mLayoutInflater;
// internal state variables
private boolean startedForeground;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
startedForeground = false;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// intent should be created with
// getShowIntent(), getHideIntent(), getCloseIntent()
if (intent != null) {
String action = intent.getAction();
int id = intent.getIntExtra("id", DEFAULT_ID);
// this will interfere with getPersistentNotification()
if (id == ONGOING_NOTIFICATION_ID) {
throw new RuntimeException(
"ID cannot equals StandOutWindow.ONGOING_NOTIFICATION_ID");
}
if (ACTION_SHOW.equals(action) || ACTION_RESTORE.equals(action)) {
show(id);
} else if (ACTION_HIDE.equals(action)) {
hide(id);
} else if (ACTION_CLOSE.equals(action)) {
close(id);
} else if (ACTION_CLOSE_ALL.equals(action)) {
closeAll();
} else if (ACTION_SEND_DATA.equals(action)) {
if (isExistingId(id) || id == DISREGARD_ID) {
Bundle data = intent
.getBundleExtra("wei.mark.standout.data");
int requestCode = intent.getIntExtra("requestCode", 0);
@SuppressWarnings("unchecked")
Class<? extends StandOutWindow> fromCls = (Class<? extends StandOutWindow>) intent
.getSerializableExtra("wei.mark.standout.fromCls");
int fromId = intent.getIntExtra("fromId", DEFAULT_ID);
onReceiveData(id, requestCode, data, fromCls, fromId);
} else {
Log.w(TAG,
"Failed to send data to non-existant window. Make sure toId is either an existing window's id, or is DISREGARD_ID.");
}
}
} else {
Log.w(TAG, "Tried to onStartCommand() with a null intent.");
}
// the service is started in foreground in show()
// so we don't expect Android to kill this service
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
// closes all windows
closeAll();
}
/**
* Return the name of every window in this implementation. The name will
* appear in the default implementations of the system window decoration
* title and notification titles.
*
* @return The name.
*/
protected abstract String getAppName();
/**
* Return the icon resource for every window in this implementation. The
* icon will appear in the default implementations of the system window
* decoration and notifications.
*
* @return The icon.
*/
protected abstract int getAppIcon();
/**
* Create a new {@link View} corresponding to the id, and add it as a child
* to the frame. The view will become the contents of this StandOut window.
* The view MUST be newly created, and you MUST attach it to the frame.
*
* <p>
* If you are inflating your view from XML, make sure you use
* {@link LayoutInflater#inflate(int, ViewGroup, boolean)} to attach your
* view to frame. Set the ViewGroup to be frame, and the boolean to true.
*
* <p>
* If you are creating your view programmatically, make sure you use
* {@link FrameLayout#addView(View)} to add your view to the frame.
*
* @param id
* The id representing the window.
* @param frame
* The {@link FrameLayout} to attach your view as a child to.
*/
protected abstract void createAndAttachView(int id, FrameLayout frame);
/**
* Return the {@link StandOutWindow#LayoutParams} for the corresponding id.
* The system will set the layout params on the view for this StandOut
* window. The layout params may be reused.
*
*
* @param id
* The id of the window.
* @param window
* The window corresponding to the id. Given as courtesy, so you
* may get the existing layout params.
* @return The {@link StandOutWindow#LayoutParams} corresponding to the id.
* The layout params will be set on the window. The layout params
* returned will be reused whenever possible, minimizing the number
* of times getParams() will be called.
*/
protected abstract LayoutParams getParams(int id, Window window);
/**
* Implement this method to change modify the behavior and appearance of the
* window corresponding to the id.
*
* <p>
* You may use any of the flags defined in {@link StandOutFlags}. This
* method will be called many times, so keep it fast.
*
* <p>
* Use bitwise OR (|) to set flags, and bitwise XOR (^) to unset flags. To
* test if a flag is set, use {@link Utils#isSet(int, int)}.
*
* @param id
* The id of the window.
* @return A combination of flags.
*/
protected int getFlags(int id) {
return StandOutFlags.FLAG_DECORATION_NONE;
}
/**
* Return the title for the persistent notification. This is called every
* time {@link #show(int)} is called.
*
* @param id
* The id of the window shown.
* @return The title for the persistent notification.
*/
protected String getPersistentNotificationTitle(int id) {
return getAppName() + " Running";
}
/**
* Return the message for the persistent notification. This is called every
* time {@link #show(int)} is called.
*
* @param id
* The id of the window shown.
* @return The message for the persistent notification.
*/
protected String getPersistentNotificationMessage(int id) {
return "";
}
/**
* Return the intent for the persistent notification. This is called every
* time {@link #show(int)} is called.
*
* <p>
* The returned intent will be packaged into a {@link PendingIntent} to be
* invoked when the user clicks the notification.
*
* @param id
* The id of the window shown.
* @return The intent for the persistent notification.
*/
protected Intent getPersistentNotificationIntent(int id) {
return null;
}
/**
* Return the icon resource for every hidden window in this implementation.
* The icon will appear in the default implementations of the hidden
* notifications.
*
* @return The icon.
*/
protected int getHiddenIcon() {
return getAppIcon();
}
/**
* Return the title for the hidden notification corresponding to the window
* being hidden.
*
* @param id
* The id of the hidden window.
* @return The title for the hidden notification.
*/
protected String getHiddenNotificationTitle(int id) {
return getAppName() + " Hidden";
}
/**
* Return the message for the hidden notification corresponding to the
* window being hidden.
*
* @param id
* The id of the hidden window.
* @return The message for the hidden notification.
*/
protected String getHiddenNotificationMessage(int id) {
return "";
}
/**
* Return the intent for the hidden notification corresponding to the window
* being hidden.
*
* <p>
* The returned intent will be packaged into a {@link PendingIntent} to be
* invoked when the user clicks the notification.
*
* @param id
* The id of the hidden window.
* @return The intent for the hidden notification.
*/
protected Intent getHiddenNotificationIntent(int id) {
return null;
}
/**
* Return a persistent {@link Notification} for the corresponding id. You
* must return a notification for AT LEAST the first id to be requested.
* Once the persistent notification is shown, further calls to
* {@link #getPersistentNotification(int)} may return null. This way Android
* can start the StandOut window service in the foreground and will not kill
* the service on low memory.
*
* <p>
* As a courtesy, the system will request a notification for every new id
* shown. Your implementation is encouraged to include the
* {@link PendingIntent#FLAG_UPDATE_CURRENT} flag in the notification so
* that there is only one system-wide persistent notification.
*
* <p>
* See the StandOutExample project for an implementation of
* {@link #getPersistentNotification(int)} that keeps one system-wide
* persistent notification that creates a new window on every click.
*
* @param id
* The id of the window.
* @return The {@link Notification} corresponding to the id, or null if
* you've previously returned a notification.
*/
protected Notification getPersistentNotification(int id) {
// basic notification stuff
// http://developer.android.com/guide/topics/ui/notifiers/notifications.html
int icon = getAppIcon();
long when = System.currentTimeMillis();
Context c = getApplicationContext();
String contentTitle = getPersistentNotificationTitle(id);
String contentText = getPersistentNotificationMessage(id);
String tickerText = String.format("%s: %s", contentTitle, contentText);
// getPersistentNotification() is called for every new window
// so we replace the old notification with a new one that has
// a bigger id
Intent notificationIntent = getPersistentNotificationIntent(id);
PendingIntent contentIntent = null;
if (notificationIntent != null) {
contentIntent = PendingIntent.getService(this, 0,
notificationIntent,
// flag updates existing persistent notification
PendingIntent.FLAG_UPDATE_CURRENT);
}
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(c, contentTitle, contentText,
contentIntent);
return notification;
}
/**
* Return a hidden {@link Notification} for the corresponding id. The system
* will request a notification for every id that is hidden.
*
* <p>
* If null is returned, StandOut will assume you do not wish to support
* hiding this window, and will {@link #close(int)} it for you.
*
* <p>
* See the StandOutExample project for an implementation of
* {@link #getHiddenNotification(int)} that for every hidden window keeps a
* notification which restores that window upon user's click.
*
* @param id
* The id of the window.
* @return The {@link Notification} corresponding to the id or null.
*/
protected Notification getHiddenNotification(int id) {
// same basics as getPersistentNotification()
int icon = getHiddenIcon();
long when = System.currentTimeMillis();
Context c = getApplicationContext();
String contentTitle = getHiddenNotificationTitle(id);
String contentText = getHiddenNotificationMessage(id);
String tickerText = String.format("%s: %s", contentTitle, contentText);
// the difference here is we are providing the same id
Intent notificationIntent = getHiddenNotificationIntent(id);
PendingIntent contentIntent = null;
if (notificationIntent != null) {
contentIntent = PendingIntent.getService(this, 0,
notificationIntent,
// flag updates existing persistent notification
PendingIntent.FLAG_UPDATE_CURRENT);
}
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(c, contentTitle, contentText,
contentIntent);
return notification;
}
/**
* Return the animation to play when the window corresponding to the id is
* shown.
*
* @param id
* The id of the window.
* @return The animation to play or null.
*/
protected Animation getShowAnimation(int id) {
return AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
}
/**
* Return the animation to play when the window corresponding to the id is
* hidden.
*
* @param id
* The id of the window.
* @return The animation to play or null.
*/
protected Animation getHideAnimation(int id) {
return AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
}
/**
* Return the animation to play when the window corresponding to the id is
* closed.
*
* @param id
* The id of the window.
* @return The animation to play or null.
*/
protected Animation getCloseAnimation(int id) {
return AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
}
/**
* Implement this method to be alerted to touch events in the body of the
* window corresponding to the id.
*
* <p>
* Note that even if you set {@link #FLAG_DECORATION_SYSTEM}, you will not
* receive touch events from the system window decorations.
*
* @see {@link View.OnTouchListener#onTouch(View, MotionEvent)}
* @param id
* The id of the view, provided as a courtesy.
* @param window
* The window corresponding to the id, provided as a courtesy.
* @param view
* The view where the event originated from.
* @param event
* See linked method.
*/
protected boolean onTouchBody(int id, Window window, View view,
MotionEvent event) {
return false;
}
/**
* Implement this method to be alerted to when the window corresponding to
* the id is moved.
*
* @see {@link View.OnTouchListener#onTouch(View, MotionEvent)}
* @param id
* The id of the view, provided as a courtesy.
* @param window
* The window corresponding to the id, provided as a courtesy.
* @param view
* The view where the event originated from.
* @param event
* See linked method.
*/
protected void onMove(int id, Window window, View view, MotionEvent event) {
}
/**
* Implement this method to be alerted to when the window corresponding to
* the id is resized.
*
* @see {@link View.OnTouchListener#onTouch(View, MotionEvent)}
* @param id
* The id of the view, provided as a courtesy.
* @param window
* The window corresponding to the id, provided as a courtesy.
* @param view
* The view where the event originated from.
* @param event
* See linked method.
*/
protected void onResize(int id, Window window, View view, MotionEvent event) {
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be shown. This callback will occur before the view is
* added to the window manager.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be shown.
* @return Return true to cancel the view from being shown, or false to
* continue.
* @see #show(int)
*/
protected boolean onShow(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be hidden. This callback will occur before the view is
* removed from the window manager and {@link #getHiddenNotification(int)}
* is called.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be hidden.
* @return Return true to cancel the view from being hidden, or false to
* continue.
* @see #hide(int)
*/
protected boolean onHide(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be closed. This callback will occur before the view is
* removed from the window manager.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be closed.
* @return Return true to cancel the view from being closed, or false to
* continue.
* @see #close(int)
*/
protected boolean onClose(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when all windows are about to be
* closed. This callback will occur before any views are removed from the
* window manager.
*
* @return Return true to cancel the views from being closed, or false to
* continue.
* @see #closeAll()
*/
protected boolean onCloseAll() {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id has received some data. The sender is described by fromCls and fromId
* if the sender wants a result. To send a result, use
* {@link #sendData(int, Class, int, int, Bundle)}.
*
* @param id
* The id of your receiving window.
* @param requestCode
* The sending window provided this request code to declare what
* kind of data is being sent.
* @param data
* A bundle of parceleable data that was sent to your receiving
* window.
* @param fromCls
* The sending window's class. Provided if the sender wants a
* result.
* @param fromId
* The sending window's id. Provided if the sender wants a
* result.
*/
protected void onReceiveData(int id, int requestCode, Bundle data,
Class<? extends StandOutWindow> fromCls, int fromId) {
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be updated in the layout. This callback will occur before
* the view is updated by the window manager.
*
* @param id
* The id of the window, provided as a courtesy.
* @param view
* The window about to be updated.
* @param params
* The updated layout params.
* @return Return true to cancel the window from being updated, or false to
* continue.
* @see #updateViewLayout(int, Window, LayoutParams)
*/
protected boolean onUpdate(int id, Window window,
StandOutWindow.LayoutParams params) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be bought to the front. This callback will occur before
* the window is brought to the front by the window manager.
*
* @param id
* The id of the window, provided as a courtesy.
* @param view
* The window about to be brought to the front.
* @return Return true to cancel the window from being brought to the front,
* or false to continue.
* @see #bringToFront(int)
*/
protected boolean onBringToFront(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to have its focus changed. This callback will occur before
* the window's focus is changed.
*
* @param id
* The id of the window, provided as a courtesy.
* @param view
* The window about to be brought to the front.
* @param focus
* Whether the window is gaining or losing focus.
* @return Return true to cancel the window's focus from being changed, or
* false to continue.
* @see #focus(int)
*/
protected boolean onFocusChange(int id, Window window, boolean focus) {
return false;
}
/**
* Show or restore a window corresponding to the id. Return the window that
* was shown/restored.
*
* @param id
* The id of the window.
* @return The window shown.
*/
protected final synchronized Window show(int id) {
// get the window corresponding to the id
Window cachedWindow = getWindow(id);
final Window window;
// check cache first
if (cachedWindow != null) {
window = cachedWindow;
} else {
window = new Window(id);
}
// alert callbacks and cancel if instructed
if (onShow(id, window)) {
Log.d(TAG, "Window " + id + " show cancelled by implementation.");
return null;
}
// get animation
Animation animation = getShowAnimation(id);
window.shown = true;
// get the params corresponding to the id
LayoutParams params = window.getLayoutParams();
try {
// add the view to the window manager
mWindowManager.addView(window, params);
// animate
if (animation != null) {
window.getChildAt(0).startAnimation(animation);
}
} catch (Exception ex) {
ex.printStackTrace();
}
// add view to internal map
putCache(id, getClass(), window);
// get the persistent notification
Notification notification = getPersistentNotification(id);
// show the notification
if (notification != null) {
notification.flags = notification.flags
| Notification.FLAG_NO_CLEAR;
// only show notification if not shown before
if (!startedForeground) {
// tell Android system to show notification
startForeground(
getClass().hashCode() + ONGOING_NOTIFICATION_ID,
notification);
startedForeground = true;
} else {
// update notification if shown before
mNotificationManager.notify(getClass().hashCode()
+ ONGOING_NOTIFICATION_ID, notification);
}
} else {
// notification can only be null if it was provided before
if (!startedForeground) {
throw new RuntimeException("Your StandOutWindow service must"
+ "provide a persistent notification."
+ "The notification prevents Android"
+ "from killing your service in low"
+ "memory situations.");
}
}
focus(id);
return window;
}
/**
* Hide a window corresponding to the id. Show a notification for the hidden
* window.
*
* @param id
* The id of the window.
*/
protected final synchronized void hide(int id) {
int flags = getFlags(id);
// check if hide enabled
if (Utils.isSet(flags, StandOutFlags.FLAG_WINDOW_HIDE_ENABLE)) {
// get the hidden notification for this view
Notification notification = getHiddenNotification(id);
// get the view corresponding to the id
final Window window = getWindow(id);
if (window == null) {
Log.w(TAG, "Tried to hide(" + id + ") a null window.");
return;
}
// alert callbacks and cancel if instructed
if (onHide(id, window)) {
Log.w(TAG, "Window " + id
+ " hide cancelled by implementation.");
return;
}
// get animation
Animation animation = getHideAnimation(id);
window.shown = false;
try {
// animate
if (animation != null) {
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
// remove the window from the window manager
mWindowManager.removeView(window);
}
});
window.getChildAt(0).startAnimation(animation);
} else {
// remove the window from the window manager
mWindowManager.removeView(window);
}
} catch (Exception ex) {
ex.printStackTrace();
}
// display the notification
notification.flags = notification.flags
| Notification.FLAG_NO_CLEAR
| Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(getClass().hashCode() + id,
notification);
} else {
// if hide not enabled, close window
close(id);
}
}
/**
* Close a window corresponding to the id.
*
* @param id
* The id of the window.
*/
protected final synchronized void close(int id) {
// get the view corresponding to the id
final Window window = getWindow(id);
if (window == null) {
Log.w(TAG, "Tried to close(" + id + ") a null window.");
return;
}
// alert callbacks and cancel if instructed
if (onClose(id, window)) {
Log.w(TAG, "Window " + id + " close cancelled by implementation.");
return;
}
// remove view from internal map
removeCache(id, getClass());
// get animation
Animation animation = getCloseAnimation(id);
if (window.shown) {
try {
// animate
if (animation != null) {
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
// remove the window from the window manager
mWindowManager.removeView(window);
}
});
window.getChildAt(0).startAnimation(animation);
} else {
// remove the window from the window manager
mWindowManager.removeView(window);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
window.shown = false;
// cancel hidden notification
mNotificationManager.cancel(id);
}
// if we just released the last window, quit
if (getCacheSize(getClass()) == 0) {
// tell Android to remove the persistent notification
// the Service will be shutdown by the system on low memory
startedForeground = false;
stopForeground(true);
}
}
/**
* Close all existing windows.
*/
protected final synchronized void closeAll() {
// alert callbacks and cancel if instructed
if (onCloseAll()) {
Log.w(TAG, "Windows close all cancelled by implementation.");
return;
}
// add ids to temporary set to avoid concurrent modification
LinkedList<Integer> ids = new LinkedList<Integer>();
for (int id : getExistingIds()) {
ids.add(id);
}
// close each window
for (int id : ids) {
close(id);
}
}
/**
* Send {@link Parceleable} data in a {@link Bundle} to a new or existing
* windows. The implementation of the recipient window can handle what to do
* with the data. To receive a result, provide the id of the sender.
*
* @param fromId
* Provide the id of the sending window if you want a result.
* @param toCls
* The Service's class extending {@link StandOutWindow} that is
* managing the receiving window.
* @param toId
* The id of the receiving window.
* @param requestCode
* Provide a request code to declare what kind of data is being
* sent.
* @param data
* A bundle of parceleable data to be sent to the receiving
* window.
*/
protected final void sendData(int fromId,
Class<? extends StandOutWindow> toCls, int toId, int requestCode,
Bundle data) {
StandOutWindow.sendData(this, toCls, toId, requestCode, data,
getClass(), fromId);
}
/**
* Update the window corresponding to this id with the given params.
*
* @param id
* The id of the window.
* @param window
* The window to update.
* @param params
* The updated layout params to apply.
*/
protected final void updateViewLayout(int id, Window window,
LayoutParams params) {
// alert callbacks and cancel if instructed
if (onUpdate(id, window, params)) {
Log.w(TAG, "Window " + id + " update cancelled by implementation.");
return;
}
if (window == null) {
Log.w(TAG, "Tried to updateViewLayout() a null window.");
return;
}
try {
window.setLayoutParams(params);
mWindowManager.updateViewLayout(window, params);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Bring the window corresponding to this id in front of all other windows.
* The window may flicker as it is removed and restored by the system.
*
* @param id
* The id of the window to bring to the front.
*/
protected final synchronized void bringToFront(int id) {
Window window = getWindow(id);
if (window == null) {
Log.w(TAG, "Tried to bringToFront() a null window.");
return;
}
// alert callbacks and cancel if instructed
if (onBringToFront(id, window)) {
Log.w(TAG, "Window " + id
+ " bring to front cancelled by implementation.");
return;
}
LayoutParams params = window.getLayoutParams();
// remove from window manager then add back
try {
mWindowManager.removeView(window);
} catch (Exception ex) {
ex.printStackTrace();
}
try {
mWindowManager.addView(window, params);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Request focus for the window corresponding to this id. A maximum of one
* window can have focus, and that window will receive all key events,
* including Back and Menu.
*
* @param id
* The id of the window.
* @return True if focus changed successfully, false if it failed.
*/
protected final synchronized boolean focus(int id) {
int flags = getFlags(id);
// check if that window is focusable
if (!Utils.isSet(flags, StandOutFlags.FLAG_WINDOW_FOCUSABLE_DISABLE)) {
final Window window = getWindow(id);
if (window != null) {
// remove focus from previously focused window
unfocus(sFocusedWindow);
return window.onFocus(true);
}
}
return false;
}
/**
* Remove focus for the window corresponding to this id. Once a window is
* unfocused, it will stop receiving key events.
*
* @param id
* The id of the window.
* @return True if focus changed successfully, false if it failed.
*/
protected final synchronized boolean unfocus(int id) {
Window window = getWindow(id);
return unfocus(window);
}
/**
* Remove focus for the window, which could belong to another application.
* Since we don't allow windows from different applications to directly
* interact with each other, except for
* {@link #sendData(Context, Class, int, int, Bundle, Class, int)}, this
* method is private.
*
* @param window
* The window to unfocus.
* @return True if focus changed successfully, false if it failed.
*/
private synchronized boolean unfocus(Window window) {
if (window != null) {
return window.onFocus(false);
}
return false;
}
/**
* Courtesy method for your implementation to use if you want to. Gets a
* unique id to assign to a new window.
*
* @return The unique id.
*/
protected final int getUniqueId() {
Map<Integer, Window> l2 = sWindows.get(getClass());
if (l2 == null) {
l2 = new HashMap<Integer, Window>();
sWindows.put(getClass(), l2);
}
int unique = DEFAULT_ID;
for (int id : l2.keySet()) {
unique = Math.max(unique, id + 1);
}
return unique;
}
/**
* Return whether the window corresponding to the id exists. This is useful
* for testing if the id is being restored (return true) or shown for the
* first time (return false).
*
* @param id
* The id of the window.
* @return True if the window corresponding to the id is either shown or
* hidden, or false if it has never been shown or was previously
* closed.
*/
protected final boolean isExistingId(int id) {
return isCached(id, getClass());
}
/**
* Return the ids of all shown or hidden windows.
*
* @return A set of ids, or an empty set.
*/
protected final Set<Integer> getExistingIds() {
return getCacheIds(getClass());
}
/**
* Return the window corresponding to the id, if it exists in cache. The
* window will not be created with
* {@link #createAndAttachView(int, ViewGroup)}. This means the returned
* value will be null if the window is not shown or hidden.
*
* @param id
* The id of the window.
* @return The window if it is shown/hidden, or null if it is closed.
*/
protected final Window getWindow(int id) {
return getCache(id, getClass());
}
/**
* Implement StandOut specific additional functionalities.
*
* <p>
* Currently, this method does the following:
*
* <p>
* Attach resize handles: For every View found to have id R.id.corner,
* attach an OnTouchListener that implements resizing the window.
*
* @param root
* The view hierarchy that is part of the window.
* @param id
* The id of the window.
*/
private void addFunctionality(View root, final int id) {
int flags = getFlags(id);
if (!Utils.isSet(flags,
StandOutFlags.FLAG_ADD_FUNCTIONALITY_RESIZE_DISABLE)) {
View corner = root.findViewById(R.id.corner);
if (corner != null) {
corner.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Window window = getWindow(id);
if (window != null) {
// handle dragging to move
boolean consumed = onTouchHandleResize(id, window,
v, event);
return consumed;
}
return false;
}
});
}
}
}
/**
* Iterate through each View in the view hiearchy and implement StandOut
* specific compatibility workarounds.
*
* <p>
* Currently, this method does the following:
*
* <p>
* Nothing yet.
*
* @param root
* The root view hierarchy to iterate through and check.
* @param id
* The id of the window.
*/
private void fixCompatibility(View root, final int id) {
Queue<View> queue = new LinkedList<View>();
queue.add(root);
View view = null;
while ((view = queue.poll()) != null) {
// do nothing yet
// iterate through children
if (view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view;
for (int i = 0; i < group.getChildCount(); i++) {
queue.add(group.getChildAt(i));
}
}
}
}
/**
* Returns the system window decorations if the implementation sets
* {@link #FLAG_DECORATION_SYSTEM}.
*
* <p>
* The system window decorations support hiding, closing, moving, and
* resizing.
*
* @param id
* The id of the window.
* @return The frame view containing the system window decorations.
*/
private View getSystemWindowDecorations(final int id) {
final View decorations = mLayoutInflater.inflate(
R.layout.system_window_decorators, null);
// icon
ImageView icon = (ImageView) decorations.findViewById(R.id.icon);
icon.setImageResource(getAppIcon());
// title
TextView title = (TextView) decorations.findViewById(R.id.title);
title.setText(getAppName());
// hide
View hide = decorations.findViewById(R.id.hide);
hide.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
hide(id);
}
});
hide.setVisibility(View.GONE);
// close
View close = decorations.findViewById(R.id.close);
close.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
close(id);
}
});
// move
View titlebar = decorations.findViewById(R.id.titlebar);
titlebar.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Window window = getWindow(id);
// handle dragging to move
boolean consumed = onTouchHandleMove(id, window, v, event);
return consumed;
}
});
// resize
View corner = decorations.findViewById(R.id.corner);
corner.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Window window = getWindow(id);
// handle dragging to move
boolean consumed = onTouchHandleResize(id, window, v, event);
return consumed;
}
});
// set window appearance and behavior based on flags
int flags = getFlags(id);
if (Utils.isSet(flags, StandOutFlags.FLAG_WINDOW_HIDE_ENABLE)) {
hide.setVisibility(View.VISIBLE);
}
if (Utils.isSet(flags, StandOutFlags.FLAG_DECORATION_CLOSE_DISABLE)) {
close.setVisibility(View.GONE);
}
if (Utils.isSet(flags, StandOutFlags.FLAG_DECORATION_MOVE_DISABLE)) {
titlebar.setOnTouchListener(null);
}
if (Utils.isSet(flags, StandOutFlags.FLAG_DECORATION_RESIZE_DISABLE)) {
corner.setVisibility(View.GONE);
}
return decorations;
}
/**
* Internal touch handler for handling moving the window.
*
* @see {@link View#onTouchEvent(MotionEvent)}
*
* @param id
* @param window
* @param view
* @param event
* @return
*/
private boolean onTouchHandleMove(int id, Window window, View view,
MotionEvent event) {
LayoutParams params = window.getLayoutParams();
int flags = getFlags(id);
// how much you have to move in either direction in order for the
// gesture to be a move and not tap
int threshold = 20;
int totalDeltaX = window.touchInfo.lastX - window.touchInfo.firstX;
int totalDeltaY = window.touchInfo.lastY - window.touchInfo.firstY;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
window.touchInfo.lastX = (int) event.getRawX();
window.touchInfo.lastY = (int) event.getRawY();
window.touchInfo.firstX = window.touchInfo.lastX;
window.touchInfo.firstY = window.touchInfo.lastY;
break;
case MotionEvent.ACTION_MOVE:
int deltaX = (int) event.getRawX() - window.touchInfo.lastX;
int deltaY = (int) event.getRawY() - window.touchInfo.lastY;
window.touchInfo.lastX = (int) event.getRawX();
window.touchInfo.lastY = (int) event.getRawY();
if (window.touchInfo.moving
|| Math.abs(totalDeltaX) >= threshold
|| Math.abs(totalDeltaY) >= threshold) {
window.touchInfo.moving = true;
// update the position of the window
params.x += deltaX;
params.y += deltaY;
updateViewLayout(id, window, params);
}
break;
case MotionEvent.ACTION_UP:
window.touchInfo.moving = false;
// keep window within edges
if (Utils.isSet(flags,
StandOutFlags.FLAG_WINDOW_EDGE_LIMITS_ENABLE)) {
if (params.gravity == (Gravity.TOP | Gravity.LEFT)) {
// only do this if gravity is TOP|LEFT
Display display = mWindowManager.getDefaultDisplay();
int displayWidth = display.getWidth();
int displayHeight = display.getHeight();
params.x = Math.min(Math.max(params.x, 0), displayWidth
- params.width);
params.y = Math.min(Math.max(params.y, 0),
displayHeight - params.height);
}
}
// bring to front on tap
boolean tap = Math.abs(totalDeltaX) < threshold
&& Math.abs(totalDeltaY) < threshold;
if (tap
&& Utils.isSet(flags,
StandOutFlags.FLAG_WINDOW_BRING_TO_FRONT_ON_TAP)) {
StandOutWindow.this.bringToFront(id);
}
// bring to front on touch
else if (Utils.isSet(flags,
StandOutFlags.FLAG_WINDOW_BRING_TO_FRONT_ON_TOUCH)) {
StandOutWindow.this.bringToFront(id);
}
break;
}
onMove(id, window, view, event);
return true;
}
/**
* Internal touch handler for handling resizing the window.
*
* @see {@link View#onTouchEvent(MotionEvent)}
*
* @param id
* @param window
* @param view
* @param event
* @return
*/
private boolean onTouchHandleResize(int id, Window window, View view,
MotionEvent event) {
StandOutWindow.LayoutParams params = (LayoutParams) window
.getLayoutParams();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
window.touchInfo.lastX = (int) event.getRawX();
window.touchInfo.lastY = (int) event.getRawY();
window.touchInfo.firstX = window.touchInfo.lastX;
window.touchInfo.firstY = window.touchInfo.lastY;
break;
case MotionEvent.ACTION_MOVE:
int deltaX = (int) event.getRawX() - window.touchInfo.lastX;
int deltaY = (int) event.getRawY() - window.touchInfo.lastY;
window.touchInfo.lastX = (int) event.getRawX();
window.touchInfo.lastY = (int) event.getRawY();
// update the size of the window
params.width += deltaX;
params.height += deltaY;
// keep window larger than 0 px
params.width = Math.max(params.width, 0);
params.height = Math.max(params.height, 0);
updateViewLayout(id, window, params);
break;
case MotionEvent.ACTION_UP:
break;
}
onResize(id, window, view, event);
return true;
}
public class Window extends FrameLayout {
/**
* Context of the window.
*/
StandOutWindow context;
/**
* Class of the window, indicating which application the window belongs
* to.
*/
public Class<? extends StandOutWindow> cls;
/**
* Id of the window.
*/
public int id;
/**
* Whether the window is shown or hidden/closed.
*/
public boolean shown;
/**
* Touch information of the window.
*/
public TouchInfo touchInfo;
/**
* Data attached to the window.
*/
public Bundle data;
public Window(int id) {
super(StandOutWindow.this);
this.context = StandOutWindow.this;
this.cls = context.getClass();
this.id = id;
this.touchInfo = new TouchInfo();
this.data = new Bundle();
// create the window contents
View content;
FrameLayout body;
final int flags = getFlags(id);
if (Utils.isSet(flags, StandOutFlags.FLAG_DECORATION_SYSTEM)) {
// requested system window decorations
content = getSystemWindowDecorations(id);
body = (FrameLayout) content.findViewById(R.id.body);
} else {
// did not request decorations. will provide own implementation
content = new FrameLayout(context);
content.setId(R.id.content);
body = (FrameLayout) content;
}
addView(content);
body.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// pass all touch events to the implementation
boolean consumed = false;
// if set FLAG_BODY_MOVE_ENABLE, move the window
if (Utils.isSet(flags, StandOutFlags.FLAG_BODY_MOVE_ENABLE)) {
consumed = onTouchHandleMove(Window.this.id,
Window.this, v, event) || consumed;
}
consumed = onTouchBody(Window.this.id, Window.this, v,
event) || consumed;
return consumed;
}
});
// attach the view corresponding to the id from the
// implementation
createAndAttachView(id, body);
// make sure the implementation attached the view
if (body.getChildCount() == 0) {
throw new RuntimeException(
"You must attach your view to the given frame in createAndAttachView()");
}
// implement StandOut specific workarounds
if (!Utils.isSet(flags,
StandOutFlags.FLAG_FIX_COMPATIBILITY_ALL_DISABLE)) {
fixCompatibility(body, id);
}
// implement StandOut specific additional functionality
if (!Utils.isSet(flags,
StandOutFlags.FLAG_ADD_FUNCTIONALITY_ALL_DISABLE)) {
addFunctionality(body, id);
}
// attach the existing tag from the frame to the window
setTag(body.getTag());
}
@Override
public void setLayoutParams(ViewGroup.LayoutParams params) {
if (params instanceof StandOutWindow.LayoutParams) {
super.setLayoutParams(params);
} else {
throw new IllegalArgumentException(
"Window: LayoutParams must be an instance of StandOutWindow.LayoutParams.");
}
}
@Override
public StandOutWindow.LayoutParams getLayoutParams() {
StandOutWindow.LayoutParams params = (StandOutWindow.LayoutParams) super
.getLayoutParams();
if (params == null) {
params = getParams(id, this);
}
return params;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// focus window
if (sFocusedWindow != this) {
focus(id);
}
break;
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_OUTSIDE:
// unfocus window
if (sFocusedWindow == this) {
unfocus(this);
}
// notify implementation that ACTION_OUTSIDE occurred
onTouchBody(id, this, this, event);
break;
}
return true;
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
Log.d(TAG, "event: " + event);
if (event.getAction() == KeyEvent.ACTION_UP) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BACK:
unfocus(this);
return true;
}
}
return super.dispatchKeyEvent(event);
}
/**
* Request or remove the focus from this window.
*
* @param focus
* Whether we want to gain or lose focus.
* @return True if focus changed successfully, false if it failed.
*/
public boolean onFocus(boolean focus) {
int flags = getFlags(id);
if (!Utils
.isSet(flags, StandOutFlags.FLAG_WINDOW_FOCUSABLE_DISABLE)) {
// window is focusable
// alert callbacks and cancel if instructed
if (context.onFocusChange(id, this, focus)) {
Log.d(TAG, "Window " + id + " focus change "
+ (focus ? "(true)" : "(false)")
+ " cancelled by implementation.");
return false;
}
if (!Utils.isSet(flags,
StandOutFlags.FLAG_WINDOW_FOCUS_INDICATOR_DISABLE)) {
// change visual state
View content = findViewById(R.id.content);
if (focus) {
// gaining focus
content.setBackgroundResource(R.drawable.border_focused);
} else {
// losing focus
if (Utils.isSet(flags,
StandOutFlags.FLAG_DECORATION_SYSTEM)) {
// system decorations
content.setBackgroundResource(R.drawable.border);
} else {
// no decorations
content.setBackgroundResource(0);
}
}
}
// set window manager params
StandOutWindow.LayoutParams params = getLayoutParams();
params.setFocus(focus);
context.updateViewLayout(id, this, params);
if (focus) {
sFocusedWindow = this;
} else {
if (sFocusedWindow == this) {
sFocusedWindow = null;
}
}
return true;
}
return false;
}
/**
* This class holds temporal touch and gesture information.
*
* @author Mark Wei <[email protected]>
*
*/
public class TouchInfo {
/**
* The state of the window.
*/
public int firstX, firstY, lastX, lastY, lastWidth, lastHeight;
/**
* Whether we're past the threshold already.
*/
public boolean moving;
@Override
public String toString() {
return String
.format("WindowTouchInfo { firstX=%d, firstY=%d,lastX=%d, lastY=%d, lastWidth=%d, lastHeight=%d }",
firstX, firstY, lastX, lastY, lastWidth,
lastHeight);
}
}
}
/**
* LayoutParams specific to floating StandOut windows.
*
* @author Mark Wei <[email protected]>
*
*/
protected class LayoutParams extends WindowManager.LayoutParams {
public LayoutParams(int id) {
super(200, 200, TYPE_PHONE, LayoutParams.FLAG_NOT_TOUCH_MODAL
| LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
setFocus(false);
int windowFlags = getFlags(id);
if (Utils.isSet(windowFlags,
StandOutFlags.FLAG_WINDOW_EDGE_LIMITS_ENABLE)) {
// windows stay within edges
} else {
// windows may be moved beyond edges
flags |= FLAG_LAYOUT_NO_LIMITS;
}
x = getX(id, width);
y = getY(id, height);
gravity = Gravity.TOP | Gravity.LEFT;
}
public LayoutParams(int id, int w, int h) {
this(id);
width = w;
height = h;
}
public LayoutParams(int id, int w, int h, int xpos, int ypos) {
this(id, w, h);
x = xpos;
y = ypos;
}
public LayoutParams(int id, int w, int h, int xpos, int ypos,
int gravityFlag) {
this(id, w, h, xpos, ypos);
gravity = gravityFlag;
if (!Utils.isSet(flags, FLAG_LAYOUT_NO_LIMITS)) {
if (gravity != (Gravity.TOP | Gravity.LEFT)) {
// windows stay within edges AND gravity is not normal
Log.w(TAG,
String.format(
"Window #%d set flag FLAG_WINDOW_EDGE_LIMITS_ENABLE. Gravity TOP|LEFT is recommended for best behavior.",
id));
}
}
}
private int getX(int id, int width) {
Display display = mWindowManager.getDefaultDisplay();
int displayWidth = display.getWidth();
int types = sWindows.size();
int initialX = 100 * types;
int variableX = 100 * id;
int rawX = initialX + variableX;
return rawX % (displayWidth - width);
}
private int getY(int id, int height) {
Display display = mWindowManager.getDefaultDisplay();
int displayWidth = display.getWidth();
int displayHeight = display.getHeight();
int types = sWindows.size();
int initialY = 100 * types;
int variableY = x + 200 * (100 * id) / (displayWidth - width);
int rawY = initialY + variableY;
return rawY % (displayHeight - height);
}
private void setFocus(boolean focused) {
if (focused) {
flags = flags ^ LayoutParams.FLAG_NOT_FOCUSABLE;
} else {
flags = flags | LayoutParams.FLAG_NOT_FOCUSABLE;
}
}
}
}
| library/src/wei/mark/standout/StandOutWindow.java | package wei.mark.standout;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Extend this class to easily create and manage floating StandOut windows.
*
* @author Mark Wei <[email protected]>
*
*/
public abstract class StandOutWindow extends Service {
private static final String TAG = "StandOutWindow";
/**
* StandOut window id: You may use this sample id for your first window.
*/
public static final int DEFAULT_ID = 0;
/**
* Special StandOut window id: You may NOT use this id for any windows.
*/
public static final int ONGOING_NOTIFICATION_ID = -1;
/**
* StandOut window id: You may use this id when you want it to be
* disregarded. The system makes no distinction for this id; it is only used
* to improve code readability.
*/
public static final int DISREGARD_ID = -2;
/**
* Intent action: Show a new window corresponding to the id.
*/
public static final String ACTION_SHOW = "SHOW";
/**
* Intent action: Restore a previously hidden window corresponding to the
* id. The window should be previously hidden with {@link #ACTION_HIDE}.
*/
public static final String ACTION_RESTORE = "RESTORE";
/**
* Intent action: Close an existing window with an existing id.
*/
public static final String ACTION_CLOSE = "CLOSE";
/**
* Intent action: Close all existing windows.
*/
public static final String ACTION_CLOSE_ALL = "CLOSE_ALL";
/**
* Intent action: Send data to a new or existing window.
*/
public static final String ACTION_SEND_DATA = "SEND_DATA";
/**
* Intent action: Hide an existing window with an existing id. To enable the
* ability to restore this window, make sure you implement
* {@link #getHiddenNotification(int)}.
*/
public static final String ACTION_HIDE = "HIDE";
/**
* Flags to be returned from {@link StandOutWindow#getFlags(int)}. This
* class was created to avoid polluting the flags namespace.
*
* @author Mark Wei <[email protected]>
*
*/
public static class StandOutFlags {
private static int flag_counter = 0;
/**
* This default flag indicates that the window requires no window
* decorations (titlebar, hide/close buttons, resize handle, etc).
*/
public static final int FLAG_DECORATION_NONE = 0x00000000;
/**
* Setting this flag indicates that the window wants the system provided
* window decorations (titlebar, hide/close buttons, resize handle,
* etc).
*/
public static final int FLAG_DECORATION_SYSTEM = 1 << flag_counter++;
/**
* If {@link #FLAG_DECORATION_SYSTEM} is set, setting this flag
* indicates that the window decorator should NOT provide a close
* button.
*/
public static final int FLAG_DECORATION_CLOSE_DISABLE = 1 << flag_counter++;
/**
* If {@link #FLAG_DECORATION_SYSTEM} is set, setting this flag
* indicates that the window decorator should NOT provide a resize
* handle.
*/
public static final int FLAG_DECORATION_RESIZE_DISABLE = 1 << flag_counter++;
/**
* If {@link #FLAG_DECORATION_SYSTEM} is set, setting this flag
* indicates that the window decorator should NOT provide a resize
* handle.
*/
public static final int FLAG_DECORATION_MOVE_DISABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that the window can be moved by dragging
* the body.
*
* <p>
* Note that if {@link #FLAG_DECORATION_SYSTEM} is set, the window can
* always be moved by dragging the titlebar.
*/
public static final int FLAG_BODY_MOVE_ENABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that windows are able to be hidden, that
* {@link StandOutWindow#getHiddenIcon(int)},
* {@link StandOutWindow#getHiddenTitle(int)}, and
* {@link StandOutWindow#getHiddenMessage(int)} are implemented, and
* that the system window decorator should provide a hide button if
* {@link #FLAG_DECORATION_SYSTEM} is set.
*/
public static final int FLAG_WINDOW_HIDE_ENABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that the window should be brought to the
* front upon user interaction.
*
* <p>
* Note that if you set this flag, there is a noticeable flashing of the
* window during {@link MotionEvent#ACTION_UP}. This the hack that
* allows the system to bring the window to the front.
*/
public static final int FLAG_WINDOW_BRING_TO_FRONT_ON_TOUCH = 1 << flag_counter++;
/**
* Setting this flag indicates that the window should be brought to the
* front upon user tap.
*
* <p>
* Note that if you set this flag, there is a noticeable flashing of the
* window during {@link MotionEvent#ACTION_UP}. This the hack that
* allows the system to bring the window to the front.
*/
public static final int FLAG_WINDOW_BRING_TO_FRONT_ON_TAP = 1 << flag_counter++;
/**
* Setting this flag indicates that the system should keep the window's
* position within the edges of the screen. If this flag is not set, the
* window will be able to be dragged off of the screen.
*
* <p>
* If this flag is set, the window's {@link Gravity} is recommended to
* be {@link Gravity#TOP} | {@link Gravity#LEFT}. If the gravity is
* anything other than TOP|LEFT, then even though the window will be
* displayed within the edges, it will behave as if the user can drag it
* off the screen.
*
*/
public static final int FLAG_WINDOW_EDGE_LIMITS_ENABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that the window does not need focus. If
* this flag is set, the system will not take care of setting and
* unsetting the focus of windows based on user touch and key events.
*
* <p>
* You will most likely need focus if your window contains any of the
* following: Button, ListView, EditText.
*
* <p>
* The benefit of disabling focus is that your window will not consume
* any key events. Normally, focused windows will consume the Back and
* Menu keys.
*
* @see {@link StandOutWindow#focus(int)}
* @see {@link StandOutWindow#unfocus(int)}
*
*/
public static final int FLAG_WINDOW_FOCUSABLE_DISABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that the system should not change the
* window's visual state when focus is changed. If this flag is set, the
* implementation can choose to change the visual state in
* {@link StandOutWindow#onFocusChange(int, Window, boolean)}.
*
* @see {@link StandOutWindow.Window#onFocus(boolean)}
*
*/
public static final int FLAG_WINDOW_FOCUS_INDICATOR_DISABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that the system should disable all
* compatibility workarounds. The default behavior is to run
* {@link StandOutWindow#fixCompatibility(View, int)} on the view
* returned by the implementation.
*
* @see {@link StandOutWindow#fixCompatibility(View, int)}
*/
public static final int FLAG_FIX_COMPATIBILITY_ALL_DISABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that the system should disable all
* additional functionality. The default behavior is to run
* {@link StandOutWindow#addFunctionality(View, int)} on the view
* returned by the implementation.
*
* @see {@link StandOutWindow#addFunctionality(View, int)}
*/
public static final int FLAG_ADD_FUNCTIONALITY_ALL_DISABLE = 1 << flag_counter++;
/**
* Setting this flag indicates that the system should disable adding the
* resize handle additional functionality.
*
* @see {@link StandOutWindow#addFunctionality(View, int)}
*/
public static final int FLAG_ADD_FUNCTIONALITY_RESIZE_DISABLE = 1 << flag_counter++;
}
/**
* Show a new window corresponding to the id, or restore a previously hidden
* window.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that will be used
* to create and manage the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
*
* @see #show(int)
*/
public static void show(Context context,
Class<? extends StandOutWindow> cls, int id) {
context.startService(getShowIntent(context, cls, id));
}
/**
* Hide the existing window corresponding to the id. To enable the ability
* to restore this window, make sure you implement
* {@link #getHiddenNotification(int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. The window must previously be
* shown.
* @see #hide(int)
*/
public static void hide(Context context,
Class<? extends StandOutWindow> cls, int id) {
context.startService(getShowIntent(context, cls, id));
}
/**
* Close an existing window with an existing id.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. The window must previously be
* shown.
* @see #close(int)
*/
public static void close(Context context,
Class<? extends StandOutWindow> cls, int id) {
context.startService(getCloseIntent(context, cls, id));
}
/**
* Close all existing windows.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @see #closeAll()
*/
public static void closeAll(Context context,
Class<? extends StandOutWindow> cls) {
context.startService(getCloseAllIntent(context, cls));
}
/**
* This allows windows of different applications to communicate with each
* other.
*
* <p>
* Send {@link Parceleable} data in a {@link Bundle} to a new or existing
* windows. The implementation of the recipient window can handle what to do
* with the data. To receive a result, provide the class and id of the
* sender.
*
* @param context
* A Context of the application package implementing the class of
* the sending window.
* @param toCls
* The Service's class extending {@link StandOutWindow} that is
* managing the receiving window.
* @param toId
* The id of the receiving window, or DISREGARD_ID.
* @param requestCode
* Provide a request code to declare what kind of data is being
* sent.
* @param data
* A bundle of parceleable data to be sent to the receiving
* window.
* @param fromCls
* Provide the class of the sending window if you want a result.
* @param fromId
* Provide the id of the sending window if you want a result.
* @see #sendData(int, Class, int, int, Bundle)
*/
public static void sendData(Context context,
Class<? extends StandOutWindow> toCls, int toId, int requestCode,
Bundle data, Class<? extends StandOutWindow> fromCls, int fromId) {
context.startService(getSendDataIntent(context, toCls, toId,
requestCode, data, fromCls, fromId));
}
/**
* See {@link #show(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that will be used
* to create and manage the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getShowIntent(Context context,
Class<? extends StandOutWindow> cls, int id) {
boolean cached = isCached(id, cls);
String action = cached ? ACTION_RESTORE : ACTION_SHOW;
Uri uri = cached ? Uri.parse("standout://" + cls + '/' + id) : null;
return new Intent(context, cls).putExtra("id", id).setAction(action)
.setData(uri);
}
/**
* See {@link #hide(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getHideIntent(Context context,
Class<? extends StandOutWindow> cls, int id) {
return new Intent(context, cls).putExtra("id", id).setAction(
ACTION_HIDE);
}
/**
* See {@link #close(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getCloseIntent(Context context,
Class<? extends StandOutWindow> cls, int id) {
return new Intent(context, cls).putExtra("id", id).setAction(
ACTION_CLOSE);
}
/**
* See {@link #closeAll(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getCloseAllIntent(Context context,
Class<? extends StandOutWindow> cls) {
return new Intent(context, cls).setAction(ACTION_CLOSE_ALL);
}
/**
* See {@link #sendData(Context, Class, int, int, Bundle, Class, int)}.
*
* @param context
* A Context of the application package implementing the class of
* the sending window.
* @param toCls
* The Service's class extending {@link StandOutWindow} that is
* managing the receiving window.
* @param toId
* The id of the receiving window.
* @param requestCode
* Provide a request code to declare what kind of data is being
* sent.
* @param data
* A bundle of parceleable data to be sent to the receiving
* window.
* @param fromCls
* If the sending window wants a result, provide the class of the
* sending window.
* @param fromId
* If the sending window wants a result, provide the id of the
* sending window.
* @return An {@link Intnet} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getSendDataIntent(Context context,
Class<? extends StandOutWindow> toCls, int toId, int requestCode,
Bundle data, Class<? extends StandOutWindow> fromCls, int fromId) {
return new Intent(context, toCls).putExtra("id", toId)
.putExtra("requestCode", requestCode)
.putExtra("wei.mark.standout.data", data)
.putExtra("wei.mark.standout.fromCls", fromCls)
.putExtra("fromId", fromId).setAction(ACTION_SEND_DATA);
}
// internal map of ids to shown/hidden views
private static Map<Class<? extends StandOutWindow>, Map<Integer, Window>> sWindows;
private static Window sFocusedWindow;
// static constructors
static {
sWindows = new HashMap<Class<? extends StandOutWindow>, Map<Integer, Window>>();
sFocusedWindow = null;
}
/**
* Returns whether the window corresponding to the class and id exists in
* the {@link #sWindows} cache.
*
* @param id
* The id representing the window.
* @param cls
* Class corresponding to the window.
* @return True if the window corresponding to the class and id exists in
* the cache, or false if it does not exist.
*/
private static boolean isCached(int id, Class<? extends StandOutWindow> cls) {
return getCache(id, cls) != null;
}
/**
* Returns the window corresponding to the id from the {@link #sWindows}
* cache.
*
* @param id
* The id representing the window.
* @param cls
* The class of the implementation of the window.
* @return The window corresponding to the id if it exists in the cache, or
* null if it does not.
*/
private static Window getCache(int id, Class<? extends StandOutWindow> cls) {
HashMap<Integer, Window> l2 = (HashMap<Integer, Window>) sWindows
.get(cls);
if (l2 == null) {
return null;
}
return l2.get(id);
}
/**
* Add the window corresponding to the id in the {@link #sWindows} cache.
*
* @param id
* The id representing the window.
* @param cls
* The class of the implementation of the window.
* @param window
* The window to be put in the cache.
*/
private static void putCache(int id, Class<? extends StandOutWindow> cls,
Window window) {
HashMap<Integer, Window> l2 = (HashMap<Integer, Window>) sWindows
.get(cls);
if (l2 == null) {
l2 = new HashMap<Integer, Window>();
sWindows.put(cls, l2);
}
l2.put(id, window);
}
/**
* Remove the window corresponding to the id from the {@link #sWindows}
* cache.
*
* @param id
* The id representing the window.
* @param cls
* The class of the implementation of the window.
*/
private static void removeCache(int id, Class<? extends StandOutWindow> cls) {
HashMap<Integer, Window> l2 = (HashMap<Integer, Window>) sWindows
.get(cls);
if (l2 != null) {
l2.remove(id);
if (l2.isEmpty()) {
sWindows.remove(cls);
}
}
}
/**
* Returns the size of the {@link #sWindows} cache.
*
* @return True if the cache corresponding to this class is empty, false if
* it is not empty.
* @param cls
* The class of the implementation of the window.
*/
private static int getCacheSize(Class<? extends StandOutWindow> cls) {
HashMap<Integer, Window> l2 = (HashMap<Integer, Window>) sWindows
.get(cls);
if (l2 == null) {
return 0;
}
return l2.size();
}
/**
* Returns the ids in the {@link #sWindows} cache.
*
* @param cls
* The class of the implementation of the window.
* @return The ids representing the cached windows.
*/
private static Set<Integer> getCacheIds(Class<? extends StandOutWindow> cls) {
HashMap<Integer, Window> l2 = (HashMap<Integer, Window>) sWindows
.get(cls);
if (l2 == null) {
return new HashSet<Integer>();
}
return l2.keySet();
}
// internal system services
private WindowManager mWindowManager;
private NotificationManager mNotificationManager;
private LayoutInflater mLayoutInflater;
// internal state variables
private boolean startedForeground;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
startedForeground = false;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// intent should be created with
// getShowIntent(), getHideIntent(), getCloseIntent()
if (intent != null) {
String action = intent.getAction();
int id = intent.getIntExtra("id", DEFAULT_ID);
// this will interfere with getPersistentNotification()
if (id == ONGOING_NOTIFICATION_ID) {
throw new RuntimeException(
"ID cannot equals StandOutWindow.ONGOING_NOTIFICATION_ID");
}
if (ACTION_SHOW.equals(action) || ACTION_RESTORE.equals(action)) {
show(id);
} else if (ACTION_HIDE.equals(action)) {
hide(id);
} else if (ACTION_CLOSE.equals(action)) {
close(id);
} else if (ACTION_CLOSE_ALL.equals(action)) {
closeAll();
} else if (ACTION_SEND_DATA.equals(action)) {
if (isExistingId(id) || id == DISREGARD_ID) {
Bundle data = intent
.getBundleExtra("wei.mark.standout.data");
int requestCode = intent.getIntExtra("requestCode", 0);
@SuppressWarnings("unchecked")
Class<? extends StandOutWindow> fromCls = (Class<? extends StandOutWindow>) intent
.getSerializableExtra("wei.mark.standout.fromCls");
int fromId = intent.getIntExtra("fromId", DEFAULT_ID);
onReceiveData(id, requestCode, data, fromCls, fromId);
} else {
Log.w(TAG,
"Failed to send data to non-existant window. Make sure toId is either an existing window's id, or is DISREGARD_ID.");
}
}
} else {
Log.w(TAG, "Tried to onStartCommand() with a null intent.");
}
// the service is started in foreground in show()
// so we don't expect Android to kill this service
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
// closes all windows
closeAll();
}
/**
* Return the name of every window in this implementation. The name will
* appear in the default implementations of the system window decoration
* title and notification titles.
*
* @return The name.
*/
protected abstract String getAppName();
/**
* Return the icon resource for every window in this implementation. The
* icon will appear in the default implementations of the system window
* decoration and notifications.
*
* @return The icon.
*/
protected abstract int getAppIcon();
/**
* Create a new {@link View} corresponding to the id, and add it as a child
* to the frame. The view will become the contents of this StandOut window.
* The view MUST be newly created, and you MUST attach it to the frame.
*
* <p>
* If you are inflating your view from XML, make sure you use
* {@link LayoutInflater#inflate(int, ViewGroup, boolean)} to attach your
* view to frame. Set the ViewGroup to be frame, and the boolean to true.
*
* <p>
* If you are creating your view programmatically, make sure you use
* {@link FrameLayout#addView(View)} to add your view to the frame.
*
* @param id
* The id representing the window.
* @param frame
* The {@link FrameLayout} to attach your view as a child to.
*/
protected abstract void createAndAttachView(int id, FrameLayout frame);
/**
* Return the {@link StandOutWindow#LayoutParams} for the corresponding id.
* The system will set the layout params on the view for this StandOut
* window. The layout params may be reused.
*
*
* @param id
* The id of the window.
* @param window
* The window corresponding to the id. Given as courtesy, so you
* may get the existing layout params.
* @return The {@link StandOutWindow#LayoutParams} corresponding to the id.
* The layout params will be set on the window. The layout params
* returned will be reused whenever possible, minimizing the number
* of times getParams() will be called.
*/
protected abstract LayoutParams getParams(int id, Window window);
/**
* Implement this method to change modify the behavior and appearance of the
* window corresponding to the id.
*
* <p>
* You may use any of the flags defined in {@link StandOutFlags}. This
* method will be called many times, so keep it fast.
*
* <p>
* Use bitwise OR (|) to set flags, and bitwise XOR (^) to unset flags. To
* test if a flag is set, use {@link Utils#isSet(int, int)}.
*
* @param id
* The id of the window.
* @return A combination of flags.
*/
protected int getFlags(int id) {
return StandOutFlags.FLAG_DECORATION_NONE;
}
/**
* Return the title for the persistent notification. This is called every
* time {@link #show(int)} is called.
*
* @param id
* The id of the window shown.
* @return The title for the persistent notification.
*/
protected String getPersistentNotificationTitle(int id) {
return getAppName() + " Running";
}
/**
* Return the message for the persistent notification. This is called every
* time {@link #show(int)} is called.
*
* @param id
* The id of the window shown.
* @return The message for the persistent notification.
*/
protected String getPersistentNotificationMessage(int id) {
return "";
}
/**
* Return the intent for the persistent notification. This is called every
* time {@link #show(int)} is called.
*
* <p>
* The returned intent will be packaged into a {@link PendingIntent} to be
* invoked when the user clicks the notification.
*
* @param id
* The id of the window shown.
* @return The intent for the persistent notification.
*/
protected Intent getPersistentNotificationIntent(int id) {
return null;
}
/**
* Return the icon resource for every hidden window in this implementation.
* The icon will appear in the default implementations of the hidden
* notifications.
*
* @return The icon.
*/
protected int getHiddenIcon() {
return getAppIcon();
}
/**
* Return the title for the hidden notification corresponding to the window
* being hidden.
*
* @param id
* The id of the hidden window.
* @return The title for the hidden notification.
*/
protected String getHiddenNotificationTitle(int id) {
return getAppName() + " Hidden";
}
/**
* Return the message for the hidden notification corresponding to the
* window being hidden.
*
* @param id
* The id of the hidden window.
* @return The message for the hidden notification.
*/
protected String getHiddenNotificationMessage(int id) {
return "";
}
/**
* Return the intent for the hidden notification corresponding to the window
* being hidden.
*
* <p>
* The returned intent will be packaged into a {@link PendingIntent} to be
* invoked when the user clicks the notification.
*
* @param id
* The id of the hidden window.
* @return The intent for the hidden notification.
*/
protected Intent getHiddenNotificationIntent(int id) {
return null;
}
/**
* Return a persistent {@link Notification} for the corresponding id. You
* must return a notification for AT LEAST the first id to be requested.
* Once the persistent notification is shown, further calls to
* {@link #getPersistentNotification(int)} may return null. This way Android
* can start the StandOut window service in the foreground and will not kill
* the service on low memory.
*
* <p>
* As a courtesy, the system will request a notification for every new id
* shown. Your implementation is encouraged to include the
* {@link PendingIntent#FLAG_UPDATE_CURRENT} flag in the notification so
* that there is only one system-wide persistent notification.
*
* <p>
* See the StandOutExample project for an implementation of
* {@link #getPersistentNotification(int)} that keeps one system-wide
* persistent notification that creates a new window on every click.
*
* @param id
* The id of the window.
* @return The {@link Notification} corresponding to the id, or null if
* you've previously returned a notification.
*/
protected Notification getPersistentNotification(int id) {
// basic notification stuff
// http://developer.android.com/guide/topics/ui/notifiers/notifications.html
int icon = getAppIcon();
long when = System.currentTimeMillis();
Context c = getApplicationContext();
String contentTitle = getPersistentNotificationTitle(id);
String contentText = getPersistentNotificationMessage(id);
String tickerText = String.format("%s: %s", contentTitle, contentText);
// getPersistentNotification() is called for every new window
// so we replace the old notification with a new one that has
// a bigger id
Intent notificationIntent = getPersistentNotificationIntent(id);
PendingIntent contentIntent = null;
if (notificationIntent != null) {
contentIntent = PendingIntent.getService(this, 0,
notificationIntent,
// flag updates existing persistent notification
PendingIntent.FLAG_UPDATE_CURRENT);
}
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(c, contentTitle, contentText,
contentIntent);
return notification;
}
/**
* Return a hidden {@link Notification} for the corresponding id. The system
* will request a notification for every id that is hidden.
*
* <p>
* If null is returned, StandOut will assume you do not wish to support
* hiding this window, and will {@link #close(int)} it for you.
*
* <p>
* See the StandOutExample project for an implementation of
* {@link #getHiddenNotification(int)} that for every hidden window keeps a
* notification which restores that window upon user's click.
*
* @param id
* The id of the window.
* @return The {@link Notification} corresponding to the id or null.
*/
protected Notification getHiddenNotification(int id) {
// same basics as getPersistentNotification()
int icon = getHiddenIcon();
long when = System.currentTimeMillis();
Context c = getApplicationContext();
String contentTitle = getHiddenNotificationTitle(id);
String contentText = getHiddenNotificationMessage(id);
String tickerText = String.format("%s: %s", contentTitle, contentText);
// the difference here is we are providing the same id
Intent notificationIntent = getHiddenNotificationIntent(id);
PendingIntent contentIntent = null;
if (notificationIntent != null) {
contentIntent = PendingIntent.getService(this, 0,
notificationIntent,
// flag updates existing persistent notification
PendingIntent.FLAG_UPDATE_CURRENT);
}
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(c, contentTitle, contentText,
contentIntent);
return notification;
}
/**
* Return the animation to play when the window corresponding to the id is
* shown.
*
* @param id
* The id of the window.
* @return The animation to play or null.
*/
protected Animation getShowAnimation(int id) {
return AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
}
/**
* Return the animation to play when the window corresponding to the id is
* hidden.
*
* @param id
* The id of the window.
* @return The animation to play or null.
*/
protected Animation getHideAnimation(int id) {
return AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
}
/**
* Return the animation to play when the window corresponding to the id is
* closed.
*
* @param id
* The id of the window.
* @return The animation to play or null.
*/
protected Animation getCloseAnimation(int id) {
return AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
}
/**
* Implement this method to be alerted to touch events in the body of the
* window corresponding to the id.
*
* <p>
* Note that even if you set {@link #FLAG_DECORATION_SYSTEM}, you will not
* receive touch events from the system window decorations.
*
* @see {@link View.OnTouchListener#onTouch(View, MotionEvent)}
* @param id
* The id of the view, provided as a courtesy.
* @param window
* The window corresponding to the id, provided as a courtesy.
* @param view
* The view where the event originated from.
* @param event
* See linked method.
*/
protected boolean onTouchBody(int id, Window window, View view,
MotionEvent event) {
return false;
}
/**
* Implement this method to be alerted to when the window corresponding to
* the id is moved.
*
* @see {@link View.OnTouchListener#onTouch(View, MotionEvent)}
* @param id
* The id of the view, provided as a courtesy.
* @param window
* The window corresponding to the id, provided as a courtesy.
* @param view
* The view where the event originated from.
* @param event
* See linked method.
*/
protected void onMove(int id, Window window, View view, MotionEvent event) {
}
/**
* Implement this method to be alerted to when the window corresponding to
* the id is resized.
*
* @see {@link View.OnTouchListener#onTouch(View, MotionEvent)}
* @param id
* The id of the view, provided as a courtesy.
* @param window
* The window corresponding to the id, provided as a courtesy.
* @param view
* The view where the event originated from.
* @param event
* See linked method.
*/
protected void onResize(int id, Window window, View view, MotionEvent event) {
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be shown. This callback will occur before the view is
* added to the window manager.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be shown.
* @return Return true to cancel the view from being shown, or false to
* continue.
* @see #show(int)
*/
protected boolean onShow(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be hidden. This callback will occur before the view is
* removed from the window manager and {@link #getHiddenNotification(int)}
* is called.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be hidden.
* @return Return true to cancel the view from being hidden, or false to
* continue.
* @see #hide(int)
*/
protected boolean onHide(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be closed. This callback will occur before the view is
* removed from the window manager.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be closed.
* @return Return true to cancel the view from being closed, or false to
* continue.
* @see #close(int)
*/
protected boolean onClose(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when all windows are about to be
* closed. This callback will occur before any views are removed from the
* window manager.
*
* @return Return true to cancel the views from being closed, or false to
* continue.
* @see #closeAll()
*/
protected boolean onCloseAll() {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id has received some data. The sender is described by fromCls and fromId
* if the sender wants a result. To send a result, use
* {@link #sendData(int, Class, int, int, Bundle)}.
*
* @param id
* The id of your receiving window.
* @param requestCode
* The sending window provided this request code to declare what
* kind of data is being sent.
* @param data
* A bundle of parceleable data that was sent to your receiving
* window.
* @param fromCls
* The sending window's class. Provided if the sender wants a
* result.
* @param fromId
* The sending window's id. Provided if the sender wants a
* result.
*/
protected void onReceiveData(int id, int requestCode, Bundle data,
Class<? extends StandOutWindow> fromCls, int fromId) {
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be updated in the layout. This callback will occur before
* the view is updated by the window manager.
*
* @param id
* The id of the window, provided as a courtesy.
* @param view
* The window about to be updated.
* @param params
* The updated layout params.
* @return Return true to cancel the window from being updated, or false to
* continue.
* @see #updateViewLayout(int, Window, LayoutParams)
*/
protected boolean onUpdate(int id, Window window,
StandOutWindow.LayoutParams params) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be bought to the front. This callback will occur before
* the window is brought to the front by the window manager.
*
* @param id
* The id of the window, provided as a courtesy.
* @param view
* The window about to be brought to the front.
* @return Return true to cancel the window from being brought to the front,
* or false to continue.
* @see #bringToFront(int)
*/
protected boolean onBringToFront(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to have its focus changed. This callback will occur before
* the window's focus is changed.
*
* @param id
* The id of the window, provided as a courtesy.
* @param view
* The window about to be brought to the front.
* @param focus
* Whether the window is gaining or losing focus.
* @return Return true to cancel the window's focus from being changed, or
* false to continue.
* @see #focus(int)
*/
protected boolean onFocusChange(int id, Window window, boolean focus) {
return false;
}
/**
* Show or restore a window corresponding to the id. Return the window that
* was shown/restored.
*
* @param id
* The id of the window.
* @return The window shown.
*/
protected final synchronized Window show(int id) {
// get the window corresponding to the id
Window cachedWindow = getWindow(id);
final Window window;
// check cache first
if (cachedWindow != null) {
window = cachedWindow;
} else {
window = new Window(id);
}
// alert callbacks and cancel if instructed
if (onShow(id, window)) {
Log.d(TAG, "Window " + id + " show cancelled by implementation.");
return null;
}
// get animation
Animation animation = getShowAnimation(id);
window.shown = true;
// get the params corresponding to the id
LayoutParams params = window.getLayoutParams();
try {
// add the view to the window manager
mWindowManager.addView(window, params);
// animate
if (animation != null) {
window.getChildAt(0).startAnimation(animation);
}
} catch (Exception ex) {
ex.printStackTrace();
}
// add view to internal map
putCache(id, getClass(), window);
// get the persistent notification
Notification notification = getPersistentNotification(id);
// show the notification
if (notification != null) {
notification.flags = notification.flags
| Notification.FLAG_NO_CLEAR;
// only show notification if not shown before
if (!startedForeground) {
// tell Android system to show notification
startForeground(
getClass().hashCode() + ONGOING_NOTIFICATION_ID,
notification);
startedForeground = true;
} else {
// update notification if shown before
mNotificationManager.notify(getClass().hashCode()
+ ONGOING_NOTIFICATION_ID, notification);
}
} else {
// notification can only be null if it was provided before
if (!startedForeground) {
throw new RuntimeException("Your StandOutWindow service must"
+ "provide a persistent notification."
+ "The notification prevents Android"
+ "from killing your service in low"
+ "memory situations.");
}
}
focus(id);
return window;
}
/**
* Hide a window corresponding to the id. Show a notification for the hidden
* window.
*
* @param id
* The id of the window.
*/
protected final synchronized void hide(int id) {
int flags = getFlags(id);
// check if hide enabled
if (Utils.isSet(flags, StandOutFlags.FLAG_WINDOW_HIDE_ENABLE)) {
// get the hidden notification for this view
Notification notification = getHiddenNotification(id);
// get the view corresponding to the id
final Window window = getWindow(id);
if (window == null) {
Log.w(TAG, "Tried to hide(" + id + ") a null window.");
return;
}
// alert callbacks and cancel if instructed
if (onHide(id, window)) {
Log.w(TAG, "Window " + id
+ " hide cancelled by implementation.");
return;
}
// get animation
Animation animation = getHideAnimation(id);
window.shown = false;
try {
// animate
if (animation != null) {
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
// remove the window from the window manager
mWindowManager.removeView(window);
}
});
window.getChildAt(0).startAnimation(animation);
} else {
// remove the window from the window manager
mWindowManager.removeView(window);
}
} catch (Exception ex) {
ex.printStackTrace();
}
// display the notification
notification.flags = notification.flags
| Notification.FLAG_NO_CLEAR
| Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(getClass().hashCode() + id,
notification);
} else {
// if hide not enabled, close window
close(id);
}
}
/**
* Close a window corresponding to the id.
*
* @param id
* The id of the window.
*/
protected final synchronized void close(int id) {
// get the view corresponding to the id
final Window window = getWindow(id);
if (window == null) {
Log.w(TAG, "Tried to close(" + id + ") a null window.");
return;
}
// alert callbacks and cancel if instructed
if (onClose(id, window)) {
Log.w(TAG, "Window " + id + " close cancelled by implementation.");
return;
}
// remove view from internal map
removeCache(id, getClass());
// get animation
Animation animation = getCloseAnimation(id);
if (window.shown) {
try {
// animate
if (animation != null) {
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
// remove the window from the window manager
mWindowManager.removeView(window);
}
});
window.getChildAt(0).startAnimation(animation);
} else {
// remove the window from the window manager
mWindowManager.removeView(window);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
window.shown = false;
// cancel hidden notification
mNotificationManager.cancel(id);
}
// if we just released the last window, quit
if (getCacheSize(getClass()) == 0) {
// tell Android to remove the persistent notification
// the Service will be shutdown by the system on low memory
startedForeground = false;
stopForeground(true);
}
}
/**
* Close all existing windows.
*/
protected final synchronized void closeAll() {
// alert callbacks and cancel if instructed
if (onCloseAll()) {
Log.w(TAG, "Windows close all cancelled by implementation.");
return;
}
// add ids to temporary set to avoid concurrent modification
LinkedList<Integer> ids = new LinkedList<Integer>();
for (int id : getExistingIds()) {
ids.add(id);
}
// close each window
for (int id : ids) {
close(id);
}
}
/**
* Send {@link Parceleable} data in a {@link Bundle} to a new or existing
* windows. The implementation of the recipient window can handle what to do
* with the data. To receive a result, provide the id of the sender.
*
* @param fromId
* Provide the id of the sending window if you want a result.
* @param toCls
* The Service's class extending {@link StandOutWindow} that is
* managing the receiving window.
* @param toId
* The id of the receiving window.
* @param requestCode
* Provide a request code to declare what kind of data is being
* sent.
* @param data
* A bundle of parceleable data to be sent to the receiving
* window.
*/
protected final void sendData(int fromId,
Class<? extends StandOutWindow> toCls, int toId, int requestCode,
Bundle data) {
StandOutWindow.sendData(this, toCls, toId, requestCode, data,
getClass(), fromId);
}
/**
* Update the window corresponding to this id with the given params.
*
* @param id
* The id of the window.
* @param window
* The window to update.
* @param params
* The updated layout params to apply.
*/
protected final void updateViewLayout(int id, Window window,
LayoutParams params) {
// alert callbacks and cancel if instructed
if (onUpdate(id, window, params)) {
Log.w(TAG, "Window " + id + " update cancelled by implementation.");
return;
}
if (window == null) {
Log.w(TAG, "Tried to updateViewLayout() a null window.");
return;
}
try {
window.setLayoutParams(params);
mWindowManager.updateViewLayout(window, params);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Bring the window corresponding to this id in front of all other windows.
* The window may flicker as it is removed and restored by the system.
*
* @param id
* The id of the window to bring to the front.
*/
protected final synchronized void bringToFront(int id) {
Window window = getWindow(id);
if (window == null) {
Log.w(TAG, "Tried to bringToFront() a null window.");
return;
}
// alert callbacks and cancel if instructed
if (onBringToFront(id, window)) {
Log.w(TAG, "Window " + id
+ " bring to front cancelled by implementation.");
return;
}
LayoutParams params = window.getLayoutParams();
// remove from window manager then add back
try {
mWindowManager.removeView(window);
} catch (Exception ex) {
ex.printStackTrace();
}
try {
mWindowManager.addView(window, params);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Request focus for the window corresponding to this id. A maximum of one
* window can have focus, and that window will receive all key events,
* including Back and Menu.
*
* @param id
* The id of the window.
* @return True if focus changed successfully, false if it failed.
*/
protected final synchronized boolean focus(int id) {
int flags = getFlags(id);
if (!Utils.isSet(flags, StandOutFlags.FLAG_WINDOW_FOCUSABLE_DISABLE)) {
final Window window = getWindow(id);
if (window != null) {
// remove focus from previously focused window
unfocus(sFocusedWindow);
return window.onFocus(true);
}
}
return false;
}
/**
* Remove focus for the window corresponding to this id. Once a window is
* unfocused, it will stop receiving key events.
*
* @param id
* The id of the window.
* @return True if focus changed successfully, false if it failed.
*/
protected final synchronized boolean unfocus(int id) {
Window window = getWindow(id);
return unfocus(window);
}
/**
* Remove focus for the window, which could belong to another application.
* Since we don't allow windows from different applications to directly
* interact with each other, except for
* {@link #sendData(Context, Class, int, int, Bundle, Class, int)}, this
* method is private.
*
* @param window
* The window to unfocus.
* @return True if focus changed successfully, false if it failed.
*/
private synchronized boolean unfocus(Window window) {
if (window != null) {
return window.onFocus(false);
}
return false;
}
/**
* Courtesy method for your implementation to use if you want to. Gets a
* unique id to assign to a new window.
*
* @return The unique id.
*/
protected final int getUniqueId() {
Map<Integer, Window> l2 = sWindows.get(getClass());
if (l2 == null) {
l2 = new HashMap<Integer, Window>();
sWindows.put(getClass(), l2);
}
int unique = DEFAULT_ID;
for (int id : l2.keySet()) {
unique = Math.max(unique, id + 1);
}
return unique;
}
/**
* Return whether the window corresponding to the id exists. This is useful
* for testing if the id is being restored (return true) or shown for the
* first time (return false).
*
* @param id
* The id of the window.
* @return True if the window corresponding to the id is either shown or
* hidden, or false if it has never been shown or was previously
* closed.
*/
protected final boolean isExistingId(int id) {
return isCached(id, getClass());
}
/**
* Return the ids of all shown or hidden windows.
*
* @return A set of ids, or an empty set.
*/
protected final Set<Integer> getExistingIds() {
return getCacheIds(getClass());
}
/**
* Return the window corresponding to the id, if it exists in cache. The
* window will not be created with
* {@link #createAndAttachView(int, ViewGroup)}. This means the returned
* value will be null if the window is not shown or hidden.
*
* @param id
* The id of the window.
* @return The window if it is shown/hidden, or null if it is closed.
*/
protected final Window getWindow(int id) {
return getCache(id, getClass());
}
/**
* Implement StandOut specific additional functionalities.
*
* <p>
* Currently, this method does the following:
*
* <p>
* Attach resize handles: For every View found to have id R.id.corner,
* attach an OnTouchListener that implements resizing the window.
*
* @param root
* The view hierarchy that is part of the window.
* @param id
* The id of the window.
*/
private void addFunctionality(View root, final int id) {
int flags = getFlags(id);
if (!Utils.isSet(flags,
StandOutFlags.FLAG_ADD_FUNCTIONALITY_RESIZE_DISABLE)) {
View corner = root.findViewById(R.id.corner);
if (corner != null) {
corner.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Window window = getWindow(id);
if (window != null) {
// handle dragging to move
boolean consumed = onTouchHandleResize(id, window,
v, event);
return consumed;
}
return false;
}
});
}
}
}
/**
* Iterate through each View in the view hiearchy and implement StandOut
* specific compatibility workarounds.
*
* <p>
* Currently, this method does the following:
*
* <p>
* Nothing yet.
*
* @param root
* The root view hierarchy to iterate through and check.
* @param id
* The id of the window.
*/
private void fixCompatibility(View root, final int id) {
Queue<View> queue = new LinkedList<View>();
queue.add(root);
View view = null;
while ((view = queue.poll()) != null) {
// do nothing yet
// iterate through children
if (view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view;
for (int i = 0; i < group.getChildCount(); i++) {
queue.add(group.getChildAt(i));
}
}
}
}
/**
* Returns the system window decorations if the implementation sets
* {@link #FLAG_DECORATION_SYSTEM}.
*
* <p>
* The system window decorations support hiding, closing, moving, and
* resizing.
*
* @param id
* The id of the window.
* @return The frame view containing the system window decorations.
*/
private View getSystemWindowDecorations(final int id) {
final View decorations = mLayoutInflater.inflate(
R.layout.system_window_decorators, null);
// icon
ImageView icon = (ImageView) decorations.findViewById(R.id.icon);
icon.setImageResource(getAppIcon());
// title
TextView title = (TextView) decorations.findViewById(R.id.title);
title.setText(getAppName());
// hide
View hide = decorations.findViewById(R.id.hide);
hide.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
hide(id);
}
});
hide.setVisibility(View.GONE);
// close
View close = decorations.findViewById(R.id.close);
close.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
close(id);
}
});
// move
View titlebar = decorations.findViewById(R.id.titlebar);
titlebar.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Window window = getWindow(id);
// handle dragging to move
boolean consumed = onTouchHandleMove(id, window, v, event);
return consumed;
}
});
// resize
View corner = decorations.findViewById(R.id.corner);
corner.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Window window = getWindow(id);
// handle dragging to move
boolean consumed = onTouchHandleResize(id, window, v, event);
return consumed;
}
});
// set window appearance and behavior based on flags
int flags = getFlags(id);
if (Utils.isSet(flags, StandOutFlags.FLAG_WINDOW_HIDE_ENABLE)) {
hide.setVisibility(View.VISIBLE);
}
if (Utils.isSet(flags, StandOutFlags.FLAG_DECORATION_CLOSE_DISABLE)) {
close.setVisibility(View.GONE);
}
if (Utils.isSet(flags, StandOutFlags.FLAG_DECORATION_MOVE_DISABLE)) {
titlebar.setOnTouchListener(null);
}
if (Utils.isSet(flags, StandOutFlags.FLAG_DECORATION_RESIZE_DISABLE)) {
corner.setVisibility(View.GONE);
}
return decorations;
}
/**
* Internal touch handler for handling moving the window.
*
* @see {@link View#onTouchEvent(MotionEvent)}
*
* @param id
* @param window
* @param view
* @param event
* @return
*/
private boolean onTouchHandleMove(int id, Window window, View view,
MotionEvent event) {
LayoutParams params = window.getLayoutParams();
int flags = getFlags(id);
// how much you have to move in either direction in order for the
// gesture to be a move and not tap
int threshold = 20;
int totalDeltaX = window.touchInfo.lastX - window.touchInfo.firstX;
int totalDeltaY = window.touchInfo.lastY - window.touchInfo.firstY;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
window.touchInfo.lastX = (int) event.getRawX();
window.touchInfo.lastY = (int) event.getRawY();
window.touchInfo.firstX = window.touchInfo.lastX;
window.touchInfo.firstY = window.touchInfo.lastY;
break;
case MotionEvent.ACTION_MOVE:
int deltaX = (int) event.getRawX() - window.touchInfo.lastX;
int deltaY = (int) event.getRawY() - window.touchInfo.lastY;
window.touchInfo.lastX = (int) event.getRawX();
window.touchInfo.lastY = (int) event.getRawY();
if (window.touchInfo.moving
|| Math.abs(totalDeltaX) >= threshold
|| Math.abs(totalDeltaY) >= threshold) {
window.touchInfo.moving = true;
// update the position of the window
params.x += deltaX;
params.y += deltaY;
updateViewLayout(id, window, params);
}
break;
case MotionEvent.ACTION_UP:
window.touchInfo.moving = false;
// keep window within edges
if (Utils.isSet(flags,
StandOutFlags.FLAG_WINDOW_EDGE_LIMITS_ENABLE)) {
if (params.gravity == (Gravity.TOP | Gravity.LEFT)) {
// only do this if gravity is TOP|LEFT
Display display = mWindowManager.getDefaultDisplay();
int displayWidth = display.getWidth();
int displayHeight = display.getHeight();
params.x = Math.min(Math.max(params.x, 0), displayWidth
- params.width);
params.y = Math.min(Math.max(params.y, 0),
displayHeight - params.height);
}
}
// bring to front on tap
boolean tap = Math.abs(totalDeltaX) < threshold
&& Math.abs(totalDeltaY) < threshold;
if (tap
&& Utils.isSet(flags,
StandOutFlags.FLAG_WINDOW_BRING_TO_FRONT_ON_TAP)) {
StandOutWindow.this.bringToFront(id);
}
// bring to front on touch
else if (Utils.isSet(flags,
StandOutFlags.FLAG_WINDOW_BRING_TO_FRONT_ON_TOUCH)) {
StandOutWindow.this.bringToFront(id);
}
break;
}
onMove(id, window, view, event);
return true;
}
/**
* Internal touch handler for handling resizing the window.
*
* @see {@link View#onTouchEvent(MotionEvent)}
*
* @param id
* @param window
* @param view
* @param event
* @return
*/
private boolean onTouchHandleResize(int id, Window window, View view,
MotionEvent event) {
StandOutWindow.LayoutParams params = (LayoutParams) window
.getLayoutParams();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
window.touchInfo.lastX = (int) event.getRawX();
window.touchInfo.lastY = (int) event.getRawY();
window.touchInfo.firstX = window.touchInfo.lastX;
window.touchInfo.firstY = window.touchInfo.lastY;
break;
case MotionEvent.ACTION_MOVE:
int deltaX = (int) event.getRawX() - window.touchInfo.lastX;
int deltaY = (int) event.getRawY() - window.touchInfo.lastY;
window.touchInfo.lastX = (int) event.getRawX();
window.touchInfo.lastY = (int) event.getRawY();
// update the size of the window
params.width += deltaX;
params.height += deltaY;
// keep window larger than 0 px
params.width = Math.max(params.width, 0);
params.height = Math.max(params.height, 0);
updateViewLayout(id, window, params);
break;
case MotionEvent.ACTION_UP:
break;
}
onResize(id, window, view, event);
return true;
}
public class Window extends FrameLayout {
/**
* Context of the window.
*/
StandOutWindow context;
/**
* Class of the window, indicating which application the window belongs
* to.
*/
public Class<? extends StandOutWindow> cls;
/**
* Id of the window.
*/
public int id;
/**
* Whether the window is shown or hidden/closed.
*/
public boolean shown;
/**
* Touch information of the window.
*/
public TouchInfo touchInfo;
/**
* Data attached to the window.
*/
public Bundle data;
public Window(int id) {
super(StandOutWindow.this);
this.context = StandOutWindow.this;
this.cls = context.getClass();
this.id = id;
this.touchInfo = new TouchInfo();
this.data = new Bundle();
// create the window contents
View content;
FrameLayout body;
final int flags = getFlags(id);
if (Utils.isSet(flags, StandOutFlags.FLAG_DECORATION_SYSTEM)) {
// requested system window decorations
content = getSystemWindowDecorations(id);
body = (FrameLayout) content.findViewById(R.id.body);
} else {
// did not request decorations. will provide own implementation
content = new FrameLayout(context);
content.setId(R.id.content);
body = (FrameLayout) content;
}
addView(content);
body.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// pass all touch events to the implementation
boolean consumed = false;
// if set FLAG_BODY_MOVE_ENABLE, move the window
if (Utils.isSet(flags, StandOutFlags.FLAG_BODY_MOVE_ENABLE)) {
consumed = onTouchHandleMove(Window.this.id,
Window.this, v, event) || consumed;
}
consumed = onTouchBody(Window.this.id, Window.this, v,
event) || consumed;
return consumed;
}
});
// attach the view corresponding to the id from the
// implementation
createAndAttachView(id, body);
// make sure the implementation attached the view
if (body.getChildCount() == 0) {
throw new RuntimeException(
"You must attach your view to the given frame in createAndAttachView()");
}
// implement StandOut specific workarounds
if (!Utils.isSet(flags,
StandOutFlags.FLAG_FIX_COMPATIBILITY_ALL_DISABLE)) {
fixCompatibility(body, id);
}
// implement StandOut specific additional functionality
if (!Utils.isSet(flags,
StandOutFlags.FLAG_ADD_FUNCTIONALITY_ALL_DISABLE)) {
addFunctionality(body, id);
}
// attach the existing tag from the frame to the window
setTag(body.getTag());
}
@Override
public void setLayoutParams(ViewGroup.LayoutParams params) {
if (params instanceof StandOutWindow.LayoutParams) {
super.setLayoutParams(params);
} else {
throw new IllegalArgumentException(
"Window: LayoutParams must be an instance of StandOutWindow.LayoutParams.");
}
}
@Override
public StandOutWindow.LayoutParams getLayoutParams() {
StandOutWindow.LayoutParams params = (StandOutWindow.LayoutParams) super
.getLayoutParams();
if (params == null) {
params = getParams(id, this);
}
return params;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// focus window
if (sFocusedWindow != this) {
focus(id);
}
break;
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_OUTSIDE:
// unfocus window
if (sFocusedWindow == this) {
unfocus(this);
}
// notify implementation that ACTION_OUTSIDE occurred
onTouchBody(id, this, this, event);
break;
}
return true;
}
/**
* Request or remove the focus from this window.
*
* @param focus
* Whether we want to gain or lose focus.
* @return True if focus changed successfully, false if it failed.
*/
public boolean onFocus(boolean focus) {
int flags = getFlags(id);
if (!Utils
.isSet(flags, StandOutFlags.FLAG_WINDOW_FOCUSABLE_DISABLE)) {
// window is focusable
// alert callbacks and cancel if instructed
if (context.onFocusChange(id, this, focus)) {
Log.d(TAG, "Window " + id + " focus change "
+ (focus ? "(true)" : "(false)")
+ " cancelled by implementation.");
return false;
}
if (!Utils.isSet(flags,
StandOutFlags.FLAG_WINDOW_FOCUS_INDICATOR_DISABLE)) {
// change visual state
View content = findViewById(R.id.content);
if (focus) {
// gaining focus
content.setBackgroundResource(R.drawable.border_focused);
} else {
// losing focus
if (Utils.isSet(flags,
StandOutFlags.FLAG_DECORATION_SYSTEM)) {
// system decorations
content.setBackgroundResource(R.drawable.border);
} else {
// no decorations
content.setBackgroundResource(0);
}
}
}
// set window manager params
StandOutWindow.LayoutParams params = getLayoutParams();
params.setFocus(focus);
context.updateViewLayout(id, this, params);
if (focus) {
sFocusedWindow = this;
} else {
if (sFocusedWindow == this) {
sFocusedWindow = null;
}
}
return true;
}
return false;
}
/**
* This class holds temporal touch and gesture information.
*
* @author Mark Wei <[email protected]>
*
*/
public class TouchInfo {
/**
* The state of the window.
*/
public int firstX, firstY, lastX, lastY, lastWidth, lastHeight;
/**
* Whether we're past the threshold already.
*/
public boolean moving;
@Override
public String toString() {
return String
.format("WindowTouchInfo { firstX=%d, firstY=%d,lastX=%d, lastY=%d, lastWidth=%d, lastHeight=%d }",
firstX, firstY, lastX, lastY, lastWidth,
lastHeight);
}
}
}
/**
* LayoutParams specific to floating StandOut windows.
*
* @author Mark Wei <[email protected]>
*
*/
protected class LayoutParams extends WindowManager.LayoutParams {
public LayoutParams(int id) {
super(200, 200, TYPE_PHONE, LayoutParams.FLAG_NOT_TOUCH_MODAL
| LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
setFocus(false);
int windowFlags = getFlags(id);
if (Utils.isSet(windowFlags,
StandOutFlags.FLAG_WINDOW_EDGE_LIMITS_ENABLE)) {
// windows stay within edges
} else {
// windows may be moved beyond edges
flags |= FLAG_LAYOUT_NO_LIMITS;
}
x = getX(id, width);
y = getY(id, height);
gravity = Gravity.TOP | Gravity.LEFT;
}
public LayoutParams(int id, int w, int h) {
this(id);
width = w;
height = h;
}
public LayoutParams(int id, int w, int h, int xpos, int ypos) {
this(id, w, h);
x = xpos;
y = ypos;
}
public LayoutParams(int id, int w, int h, int xpos, int ypos,
int gravityFlag) {
this(id, w, h, xpos, ypos);
gravity = gravityFlag;
if (!Utils.isSet(flags, FLAG_LAYOUT_NO_LIMITS)) {
if (gravity != (Gravity.TOP | Gravity.LEFT)) {
// windows stay within edges AND gravity is not normal
Log.w(TAG,
String.format(
"Window #%d set flag FLAG_WINDOW_EDGE_LIMITS_ENABLE. Gravity TOP|LEFT is recommended for best behavior.",
id));
}
}
}
private int getX(int id, int width) {
Display display = mWindowManager.getDefaultDisplay();
int displayWidth = display.getWidth();
int types = sWindows.size();
int initialX = 100 * types;
int variableX = 100 * id;
int rawX = initialX + variableX;
return rawX % (displayWidth - width);
}
private int getY(int id, int height) {
Display display = mWindowManager.getDefaultDisplay();
int displayWidth = display.getWidth();
int displayHeight = display.getHeight();
int types = sWindows.size();
int initialY = 100 * types;
int variableY = x + 200 * (100 * id) / (displayWidth - width);
int rawY = initialY + variableY;
return rawY % (displayHeight - height);
}
private void setFocus(boolean focused) {
if (focused) {
flags = flags ^ LayoutParams.FLAG_NOT_FOCUSABLE;
} else {
flags = flags | LayoutParams.FLAG_NOT_FOCUSABLE;
}
}
}
}
| Back key unfocuses
| library/src/wei/mark/standout/StandOutWindow.java | Back key unfocuses | <ide><path>ibrary/src/wei/mark/standout/StandOutWindow.java
<ide> import android.util.Log;
<ide> import android.view.Display;
<ide> import android.view.Gravity;
<add>import android.view.KeyEvent;
<ide> import android.view.LayoutInflater;
<ide> import android.view.MotionEvent;
<ide> import android.view.View;
<ide> protected final synchronized boolean focus(int id) {
<ide> int flags = getFlags(id);
<ide>
<add> // check if that window is focusable
<ide> if (!Utils.isSet(flags, StandOutFlags.FLAG_WINDOW_FOCUSABLE_DISABLE)) {
<ide> final Window window = getWindow(id);
<ide> if (window != null) {
<ide> }
<ide>
<ide> return true;
<add> }
<add>
<add> @Override
<add> public boolean dispatchKeyEvent(KeyEvent event) {
<add> Log.d(TAG, "event: " + event);
<add>
<add> if (event.getAction() == KeyEvent.ACTION_UP) {
<add> switch (event.getKeyCode()) {
<add> case KeyEvent.KEYCODE_BACK:
<add> unfocus(this);
<add> return true;
<add> }
<add> }
<add>
<add> return super.dispatchKeyEvent(event);
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | a0534d8d9c80fd03719ab8f369b5626bb7e652f6 | 0 | rabix/bunny,rabix/bunny,rabix/bunny,rabix/bunny,rabix/bunny | package org.rabix.bindings;
public enum ProtocolType {
CWL("org.rabix.bindings.cwl.CWLBindings", 3, "v1.0"),
DRAFT2("org.rabix.bindings.draft2.Draft2Bindings", 4, null),
SB("org.rabix.bindings.sb.SBBindings", 1, null),
DRAFT3("org.rabix.bindings.draft3.Draft3Bindings", 2, "cwl:draft-3");
public final int order;
public final String bindingsClass;
public final String appVersion;
private ProtocolType(String bindingsClass, int order, String appVersion) {
this.order = order;
this.appVersion = appVersion;
this.bindingsClass = bindingsClass;
}
public static ProtocolType create(String type) {
for (ProtocolType protocolType : ProtocolType.values()) {
if (protocolType.name().equalsIgnoreCase(type)) {
return protocolType;
}
}
return null;
}
}
| rabix-bindings/src/main/java/org/rabix/bindings/ProtocolType.java | package org.rabix.bindings;
public enum ProtocolType {
CWL("org.rabix.bindings.cwl.CWLBindings", 1, "v1.0"),
DRAFT2("org.rabix.bindings.draft2.Draft2Bindings", 4, null),
SB("org.rabix.bindings.sb.SBBindings", 3, null),
DRAFT3("org.rabix.bindings.draft3.Draft3Bindings", 2, "cwl:draft-3");
public final int order;
public final String bindingsClass;
public final String appVersion;
private ProtocolType(String bindingsClass, int order, String appVersion) {
this.order = order;
this.appVersion = appVersion;
this.bindingsClass = bindingsClass;
}
public static ProtocolType create(String type) {
for (ProtocolType protocolType : ProtocolType.values()) {
if (protocolType.name().equalsIgnoreCase(type)) {
return protocolType;
}
}
return null;
}
}
| reorder priorities
| rabix-bindings/src/main/java/org/rabix/bindings/ProtocolType.java | reorder priorities | <ide><path>abix-bindings/src/main/java/org/rabix/bindings/ProtocolType.java
<ide>
<ide>
<ide> public enum ProtocolType {
<del> CWL("org.rabix.bindings.cwl.CWLBindings", 1, "v1.0"),
<add> CWL("org.rabix.bindings.cwl.CWLBindings", 3, "v1.0"),
<ide> DRAFT2("org.rabix.bindings.draft2.Draft2Bindings", 4, null),
<del> SB("org.rabix.bindings.sb.SBBindings", 3, null),
<add> SB("org.rabix.bindings.sb.SBBindings", 1, null),
<ide> DRAFT3("org.rabix.bindings.draft3.Draft3Bindings", 2, "cwl:draft-3");
<ide>
<ide> public final int order; |
|
Java | mit | 17349253757e93e6284d9520cbe34a017a32bd24 | 0 | KiiPlatform/thing-if-AndroidSDK,KiiPlatform/thing-if-AndroidSDK | package com.kii.iotcloud.trigger;
import android.os.Parcel;
import android.support.annotation.NonNull;
public class StatePredicate extends Predicate {
private Condition condition;
private TriggersWhen triggersWhen;
public StatePredicate(@NonNull Condition condition, @NonNull TriggersWhen triggersWhen) {
if (condition == null) {
throw new IllegalArgumentException("condition is null");
}
if (triggersWhen == null) {
throw new IllegalArgumentException("triggersWhen is null");
}
this.condition = condition;
this.triggersWhen = triggersWhen;
}
public EventSource getEventSource() {
return EventSource.STATES;
}
public Condition getCondition() {
return this.condition;
}
public void setCondition(@NonNull Condition condition) {
if (condition == null) {
throw new IllegalArgumentException("condition is null");
}
this.condition = condition;
}
public TriggersWhen getTriggersWhen() {
return this.triggersWhen;
}
public void setTriggersWhen(@NonNull TriggersWhen triggersWhen) {
if (triggersWhen == null) {
throw new IllegalArgumentException("triggersWhen is null");
}
this.triggersWhen = triggersWhen;
}
// Implementation of Parcelable
protected StatePredicate(Parcel in) {
this.condition = in.readParcelable(Condition.class.getClassLoader());
this.triggersWhen = (TriggersWhen)in.readSerializable();
}
public static final Creator<StatePredicate> CREATOR = new Creator<StatePredicate>() {
@Override
public StatePredicate createFromParcel(Parcel in) {
return new StatePredicate(in);
}
@Override
public StatePredicate[] newArray(int size) {
return new StatePredicate[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(this.condition, flags);
dest.writeSerializable(this.triggersWhen);
}
}
| iotcloudsdk/src/main/java/com/kii/iotcloud/trigger/StatePredicate.java | package com.kii.iotcloud.trigger;
import android.os.Parcel;
import android.support.annotation.NonNull;
public class StatePredicate extends Predicate {
private Condition condition;
private TriggersWhen triggersWhen;
public StatePredicate(@NonNull Condition condition, @NonNull TriggersWhen triggersWhen) {
if (condition == null) {
throw new IllegalArgumentException("condition is null");
}
if (triggersWhen == null) {
throw new IllegalArgumentException("triggersWhen is null");
}
this.condition = condition;
this.triggersWhen = triggersWhen;
}
public EventSource getEventSource() {
return EventSource.STATES;
}
public Condition getCondition() {
return this.condition;
}
public TriggersWhen getTriggersWhen() {
return this.triggersWhen;
}
// Implementation of Parcelable
protected StatePredicate(Parcel in) {
this.condition = in.readParcelable(Condition.class.getClassLoader());
this.triggersWhen = (TriggersWhen)in.readSerializable();
}
public static final Creator<StatePredicate> CREATOR = new Creator<StatePredicate>() {
@Override
public StatePredicate createFromParcel(Parcel in) {
return new StatePredicate(in);
}
@Override
public StatePredicate[] newArray(int size) {
return new StatePredicate[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(this.condition, flags);
dest.writeSerializable(this.triggersWhen);
}
}
| added setter to StatePredicate
| iotcloudsdk/src/main/java/com/kii/iotcloud/trigger/StatePredicate.java | added setter to StatePredicate | <ide><path>otcloudsdk/src/main/java/com/kii/iotcloud/trigger/StatePredicate.java
<ide> public Condition getCondition() {
<ide> return this.condition;
<ide> }
<add> public void setCondition(@NonNull Condition condition) {
<add> if (condition == null) {
<add> throw new IllegalArgumentException("condition is null");
<add> }
<add> this.condition = condition;
<add> }
<ide> public TriggersWhen getTriggersWhen() {
<ide> return this.triggersWhen;
<ide> }
<del>
<add> public void setTriggersWhen(@NonNull TriggersWhen triggersWhen) {
<add> if (triggersWhen == null) {
<add> throw new IllegalArgumentException("triggersWhen is null");
<add> }
<add> this.triggersWhen = triggersWhen;
<add> }
<ide>
<ide> // Implementation of Parcelable
<ide> protected StatePredicate(Parcel in) { |
|
Java | apache-2.0 | e8005b053007e391de37feb8244aba599c442195 | 0 | royalrangers-ck/rr-api,royalrangers-ck/rr-api | package com.royalrangers.model;
public enum AuthorityName {
ROLE_USER,
ROLE_ADMIN,
ROLE_SUPER_ADMIN,
ROLE_TEST
} | src/main/java/com/royalrangers/model/AuthorityName.java | package com.royalrangers.model;
public enum AuthorityName {
ROLE_USER,
ROLE_ADMIN,
ROLE_SUPER_ADMIN
} | Test role is added.
| src/main/java/com/royalrangers/model/AuthorityName.java | Test role is added. | <ide><path>rc/main/java/com/royalrangers/model/AuthorityName.java
<ide> public enum AuthorityName {
<ide> ROLE_USER,
<ide> ROLE_ADMIN,
<del> ROLE_SUPER_ADMIN
<add> ROLE_SUPER_ADMIN,
<add> ROLE_TEST
<ide> } |
|
Java | apache-2.0 | error: pathspec 'src/main/java/six/com/crawler/schedule/consts/DownloadContants.java' did not match any file(s) known to git
| db9b60b2cde6f8b617e9530d157ae9cf0d5e1acb | 1 | lvjk/excrawler,lvjk/excrawler,lvjk/excrawler,lvjk/excrawler | package six.com.crawler.schedule.consts;
/**
* 下载状态
* @author [email protected]
*
*/
public class DownloadContants {
public static final int DOWN_LOAD_NOT_RUNNING=0;
public static final int DOWN_LOAD_FINISHED = 1;
public static final int DOWN_LOAD_RUNNING = 2;
public static final int DOWN_LAOD_STOP = 3;
public static final int DOWN_LOAD_EXCEPTION = 4;
}
| src/main/java/six/com/crawler/schedule/consts/DownloadContants.java | 添加下载常亮类 | src/main/java/six/com/crawler/schedule/consts/DownloadContants.java | 添加下载常亮类 | <ide><path>rc/main/java/six/com/crawler/schedule/consts/DownloadContants.java
<add>package six.com.crawler.schedule.consts;
<add>
<add>/**
<add> * 下载状态
<add> * @author [email protected]
<add> *
<add> */
<add>public class DownloadContants {
<add>
<add> public static final int DOWN_LOAD_NOT_RUNNING=0;
<add>
<add> public static final int DOWN_LOAD_FINISHED = 1;
<add>
<add> public static final int DOWN_LOAD_RUNNING = 2;
<add>
<add> public static final int DOWN_LAOD_STOP = 3;
<add>
<add> public static final int DOWN_LOAD_EXCEPTION = 4;
<add>} |
|
Java | apache-2.0 | ecd2198bf0beed44eb3769e78708b7ed2771c447 | 0 | genericsystem/genericsystem2015,genericsystem/genericsystem2015,genericsystem/genericsystem2015,genericsystem/genericsystem2015,genericsystem/genericsystem2015 | package org.genericsystem.distributed.cacheonserver;
import java.io.Serializable;
import java.util.List;
import org.genericsystem.api.core.Snapshot;
import org.genericsystem.api.core.exceptions.ConcurrencyControlException;
import org.genericsystem.api.core.exceptions.RollbackException;
import org.genericsystem.common.AbstractCache;
import org.genericsystem.common.Generic;
import org.genericsystem.defaults.DefaultCache;
public class LightClientCache extends AbstractCache implements DefaultCache<Generic> {
private final long cacheId;
private LightClientTransaction transaction;
public void shiftTs() throws RollbackException {
getRoot().getServer().shiftTs(cacheId);
this.transaction = new LightClientTransaction(getRoot(), cacheId);
}
public LightClientTransaction getTransaction() {
return transaction;
}
protected LightClientCache(LightClientEngine root) {
super(root);
cacheId = getRoot().getServer().newCacheId();
System.out.println("Create LightCache : " + cacheId);
this.transaction = new LightClientTransaction(root, cacheId);
}
@Override
public LightClientEngine getRoot() {
return (LightClientEngine) super.getRoot();
}
@Override
public Snapshot<Generic> getDependencies(Generic vertex) {
return transaction.getDependencies(vertex);
}
@Override
public void tryFlush() throws ConcurrencyControlException {
getRoot().getServer().tryFlush(cacheId);
}
@Override
public void flush() {
try {
getRoot().getServer().flush(cacheId);
} catch (Exception e) {
System.out.println("Change Client Transaction");
transaction = new LightClientTransaction(getRoot(), cacheId);
throw e;
}
}
public void clear() {
getRoot().getServer().clear(cacheId);
transaction = new LightClientTransaction(getRoot(), cacheId);
}
public void mount() {
getRoot().getServer().mount(cacheId);
// transaction = new LightClientTransaction(getRoot(), cacheId);
}
public void unmount() {
getRoot().getServer().unmount(cacheId);
transaction = new LightClientTransaction(getRoot(), cacheId);
}
@Override
public void discardWithException(Throwable exception) throws RollbackException {
try {
clear();
} catch (Exception e) {
throw new RollbackException(exception);
}
}
public int getCacheLevel() {
return transaction.getCacheLevel();
}
@Override
public Generic setInstance(Generic meta, List<Generic> overrides, Serializable value, List<Generic> components) {
return transaction.setInstance(meta, overrides, value, components);
}
@Override
public Generic addInstance(Generic meta, List<Generic> overrides, Serializable value, List<Generic> components) {
return transaction.addInstance(meta, overrides, value, components);
}
@Override
public Generic update(Generic update, List<Generic> overrides, Serializable value, List<Generic> components) {
return transaction.update(update, overrides, value, components);
}
@Override
public Generic merge(Generic update, List<Generic> overrides, Serializable value, List<Generic> components) {
return transaction.merge(update, overrides, value, components);
}
@Override
public void forceRemove(Generic generic) {
transaction.forceRemove(generic, computeDependencies(generic));
}
@Override
public void remove(Generic generic) {
transaction.remove(generic, computeDependencies(generic));
// transaction = new LightClientTransaction(getRoot(), cacheId);
}
@Override
public void conserveRemove(Generic generic) {
transaction.conserveRemove(generic, computeDependencies(generic));
}
}
| gs-kernel/src/main/java/org/genericsystem/distributed/cacheonserver/LightClientCache.java | package org.genericsystem.distributed.cacheonserver;
import java.io.Serializable;
import java.util.List;
import org.genericsystem.api.core.Snapshot;
import org.genericsystem.api.core.exceptions.ConcurrencyControlException;
import org.genericsystem.api.core.exceptions.RollbackException;
import org.genericsystem.common.AbstractCache;
import org.genericsystem.common.Generic;
import org.genericsystem.defaults.DefaultCache;
import org.genericsystem.kernel.Statics;
public class LightClientCache extends AbstractCache implements DefaultCache<Generic> {
private final long cacheId;
private LightClientTransaction transaction;
public void shiftTs() throws RollbackException {
getRoot().getServer().shiftTs(cacheId);
this.transaction = new LightClientTransaction(getRoot(), cacheId);
}
public LightClientTransaction getTransaction() {
return transaction;
}
protected LightClientCache(LightClientEngine root) {
super(root);
cacheId = getRoot().getServer().newCacheId();
System.out.println("Create LightCache : " + cacheId);
this.transaction = new LightClientTransaction(root, cacheId);
}
@Override
public LightClientEngine getRoot() {
return (LightClientEngine) super.getRoot();
}
@Override
public Snapshot<Generic> getDependencies(Generic vertex) {
return transaction.getDependencies(vertex);
}
@Override
public void tryFlush() throws ConcurrencyControlException {
getRoot().getServer().tryFlush(cacheId);
}
@Override
public void flush() {
long result = getRoot().getServer().flush(cacheId);
if (Statics.CONCURRENCY_CONTROL_EXCEPTION == result) {
System.out.println("Change Client Transaction");
transaction = new LightClientTransaction(getRoot(), cacheId);
}
}
public void clear() {
getRoot().getServer().clear(cacheId);
transaction = new LightClientTransaction(getRoot(), cacheId);
}
public void mount() {
getRoot().getServer().mount(cacheId);
// transaction = new LightClientTransaction(getRoot(), cacheId);
}
public void unmount() {
getRoot().getServer().unmount(cacheId);
transaction = new LightClientTransaction(getRoot(), cacheId);
}
@Override
public void discardWithException(Throwable exception) throws RollbackException {
try {
clear();
} catch (Exception e) {
throw new RollbackException(exception);
}
}
public int getCacheLevel() {
return transaction.getCacheLevel();
}
@Override
public Generic setInstance(Generic meta, List<Generic> overrides, Serializable value, List<Generic> components) {
return transaction.setInstance(meta, overrides, value, components);
}
@Override
public Generic addInstance(Generic meta, List<Generic> overrides, Serializable value, List<Generic> components) {
return transaction.addInstance(meta, overrides, value, components);
}
@Override
public Generic update(Generic update, List<Generic> overrides, Serializable value, List<Generic> components) {
return transaction.update(update, overrides, value, components);
}
@Override
public Generic merge(Generic update, List<Generic> overrides, Serializable value, List<Generic> components) {
return transaction.merge(update, overrides, value, components);
}
@Override
public void forceRemove(Generic generic) {
transaction.forceRemove(generic, computeDependencies(generic));
}
@Override
public void remove(Generic generic) {
transaction.remove(generic, computeDependencies(generic));
// transaction = new LightClientTransaction(getRoot(), cacheId);
}
@Override
public void conserveRemove(Generic generic) {
transaction.conserveRemove(generic, computeDependencies(generic));
}
}
| catch and throw exceptions in flush | gs-kernel/src/main/java/org/genericsystem/distributed/cacheonserver/LightClientCache.java | catch and throw exceptions in flush | <ide><path>s-kernel/src/main/java/org/genericsystem/distributed/cacheonserver/LightClientCache.java
<ide> import org.genericsystem.common.AbstractCache;
<ide> import org.genericsystem.common.Generic;
<ide> import org.genericsystem.defaults.DefaultCache;
<del>import org.genericsystem.kernel.Statics;
<ide>
<ide> public class LightClientCache extends AbstractCache implements DefaultCache<Generic> {
<ide>
<ide>
<ide> @Override
<ide> public void flush() {
<del> long result = getRoot().getServer().flush(cacheId);
<del> if (Statics.CONCURRENCY_CONTROL_EXCEPTION == result) {
<add> try {
<add> getRoot().getServer().flush(cacheId);
<add> } catch (Exception e) {
<ide> System.out.println("Change Client Transaction");
<ide> transaction = new LightClientTransaction(getRoot(), cacheId);
<add> throw e;
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | error: pathspec 'src/test/java/org/apache/commons/compress/compressors/CompressorStreamFactoryRoundtripTest.java' did not match any file(s) known to git
| 6c8345bff9b68598903a05f702ec15e969478cb9 | 1 | krosenvold/commons-compress,lookout/commons-compress,apache/commons-compress,krosenvold/commons-compress,krosenvold/commons-compress,apache/commons-compress,apache/commons-compress,lookout/commons-compress,lookout/commons-compress | package org.apache.commons.compress.compressors;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class CompressorStreamFactoryRoundtripTest {
@Parameters(name = "{0}")
public static String[] data() {
return new String[] { //
CompressorStreamFactory.BZIP2, //
CompressorStreamFactory.DEFLATE, //
CompressorStreamFactory.GZIP, //
// CompressorStreamFactory.LZMA, // Not implemented yet
// CompressorStreamFactory.PACK200, // Bug
// CompressorStreamFactory.SNAPPY_FRAMED, // Not implemented yet
// CompressorStreamFactory.SNAPPY_RAW, // Not implemented yet
CompressorStreamFactory.XZ, //
// CompressorStreamFactory.Z, // Not implemented yet
};
}
private final String compressorName;
public CompressorStreamFactoryRoundtripTest(final String compressorName) {
this.compressorName = compressorName;
}
@Test
public void testCompressorStreamFactoryRoundtrip() throws Exception {
final CompressorStreamFactory factory = new CompressorStreamFactory();
final ByteArrayOutputStream compressedOs = new ByteArrayOutputStream();
final CompressorOutputStream compressorOutputStream = factory.createCompressorOutputStream(compressorName,
compressedOs);
final String fixture = "The quick brown fox jumps over the lazy dog";
compressorOutputStream.write(fixture.getBytes("UTF-8"));
compressorOutputStream.flush();
compressorOutputStream.close();
final ByteArrayInputStream is = new ByteArrayInputStream(compressedOs.toByteArray());
final CompressorInputStream compressorInputStream = factory.createCompressorInputStream(compressorName, is);
final ByteArrayOutputStream decompressedOs = new ByteArrayOutputStream();
IOUtils.copy(compressorInputStream, decompressedOs);
compressorInputStream.close();
decompressedOs.flush();
decompressedOs.close();
Assert.assertEquals(fixture, decompressedOs.toString("UTF-8"));
}
}
| src/test/java/org/apache/commons/compress/compressors/CompressorStreamFactoryRoundtripTest.java | Tests for [COMPRESS-359] Pack200 is broken. | src/test/java/org/apache/commons/compress/compressors/CompressorStreamFactoryRoundtripTest.java | Tests for [COMPRESS-359] Pack200 is broken. | <ide><path>rc/test/java/org/apache/commons/compress/compressors/CompressorStreamFactoryRoundtripTest.java
<add>package org.apache.commons.compress.compressors;
<add>
<add>import java.io.ByteArrayInputStream;
<add>import java.io.ByteArrayOutputStream;
<add>
<add>import org.apache.commons.compress.utils.IOUtils;
<add>import org.junit.Assert;
<add>import org.junit.Test;
<add>import org.junit.runner.RunWith;
<add>import org.junit.runners.Parameterized;
<add>import org.junit.runners.Parameterized.Parameters;
<add>
<add>@RunWith(Parameterized.class)
<add>public class CompressorStreamFactoryRoundtripTest {
<add>
<add> @Parameters(name = "{0}")
<add> public static String[] data() {
<add> return new String[] { //
<add> CompressorStreamFactory.BZIP2, //
<add> CompressorStreamFactory.DEFLATE, //
<add> CompressorStreamFactory.GZIP, //
<add> // CompressorStreamFactory.LZMA, // Not implemented yet
<add> // CompressorStreamFactory.PACK200, // Bug
<add> // CompressorStreamFactory.SNAPPY_FRAMED, // Not implemented yet
<add> // CompressorStreamFactory.SNAPPY_RAW, // Not implemented yet
<add> CompressorStreamFactory.XZ, //
<add> // CompressorStreamFactory.Z, // Not implemented yet
<add> };
<add> }
<add>
<add> private final String compressorName;
<add>
<add> public CompressorStreamFactoryRoundtripTest(final String compressorName) {
<add> this.compressorName = compressorName;
<add> }
<add>
<add> @Test
<add> public void testCompressorStreamFactoryRoundtrip() throws Exception {
<add> final CompressorStreamFactory factory = new CompressorStreamFactory();
<add> final ByteArrayOutputStream compressedOs = new ByteArrayOutputStream();
<add> final CompressorOutputStream compressorOutputStream = factory.createCompressorOutputStream(compressorName,
<add> compressedOs);
<add> final String fixture = "The quick brown fox jumps over the lazy dog";
<add> compressorOutputStream.write(fixture.getBytes("UTF-8"));
<add> compressorOutputStream.flush();
<add> compressorOutputStream.close();
<add> final ByteArrayInputStream is = new ByteArrayInputStream(compressedOs.toByteArray());
<add> final CompressorInputStream compressorInputStream = factory.createCompressorInputStream(compressorName, is);
<add> final ByteArrayOutputStream decompressedOs = new ByteArrayOutputStream();
<add> IOUtils.copy(compressorInputStream, decompressedOs);
<add> compressorInputStream.close();
<add> decompressedOs.flush();
<add> decompressedOs.close();
<add> Assert.assertEquals(fixture, decompressedOs.toString("UTF-8"));
<add> }
<add>
<add>} |
|
Java | apache-2.0 | 89856fa58f003c36a6ef67b7d9b2eabb53cf78bd | 0 | Danyzzz/cordova_ringtone_default,Danyzzz/cordova_ringtone_default,Danyzzz/cordova_ringtone_default,Danyzzz/cordova_ringtone_default | /*
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.cordova.dialogs;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.media.AudioManager;
import android.net.Uri;
import android.widget.EditText;
import android.widget.TextView;
/**
* This class provides access to notifications on the device.
*
* Be aware that this implementation gets called on
* navigator.notification.{alert|confirm|prompt}, and that there is a separate
* implementation in org.apache.cordova.CordovaChromeClient that gets
* called on a simple window.{alert|confirm|prompt}.
*/
public class Notification extends CordovaPlugin {
private static final String LOG_TAG = "Notification";
public int confirmResult = -1;
public ProgressDialog spinnerDialog = null;
public ProgressDialog progressDialog = null;
/**
* Constructor.
*/
public Notification() {
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArray of arguments for the plugin.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return True when the action was valid, false otherwise.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
/*
* Don't run any of these if the current activity is finishing
* in order to avoid android.view.WindowManager$BadTokenException
* crashing the app. Just return true here since false should only
* be returned in the event of an invalid action.
*/
if(this.cordova.getActivity().isFinishing()) return true;
if (action.equals("beep")) {
this.beep(args.getLong(0));
}
else if (action.equals("alert")) {
this.alert(args.getString(0), args.getString(1), args.getString(2), callbackContext);
return true;
}
else if (action.equals("confirm")) {
this.confirm(args.getString(0), args.getString(1), args.getJSONArray(2), callbackContext);
return true;
}
else if (action.equals("prompt")) {
this.prompt(args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), callbackContext);
return true;
}
else if (action.equals("activityStart")) {
this.activityStart(args.getString(0), args.getString(1));
}
else if (action.equals("activityStop")) {
this.activityStop();
}
else if (action.equals("progressStart")) {
this.progressStart(args.getString(0), args.getString(1));
}
else if (action.equals("progressValue")) {
this.progressValue(args.getInt(0));
}
else if (action.equals("progressStop")) {
this.progressStop();
}
else {
return false;
}
// Only alert and confirm are async.
callbackContext.success();
return true;
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Beep plays the default notification ringtone.
*
* @param count Number of times to play notification
*/
public void beep(final long count) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
Ringtone notification = RingtoneManager.getRingtone(cordova.getActivity().getBaseContext(), ringtone);
if(count == 1){
// If phone is not set to silent mode
if (notification != null) {
for (long i = 0; i < count; ++i) {
notification.play();
long timeout = 5000;
while (notification.isPlaying() && (timeout > 0)) {
timeout = timeout - 100;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}
if(count == 2){
AudioManager aM = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
aM.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
}
});
}
/**
* Builds and shows a native Android alert with given Strings
* @param message The message the alert should display
* @param title The title of the alert
* @param buttonLabel The label of the button
* @param callbackContext The callback context
*/
public synchronized void alert(final String message, final String title, final String buttonLabel, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(true);
dlg.setPositiveButton(buttonLabel,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
});
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog)
{
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
});
changeTextDirection(dlg);
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Builds and shows a native Android confirm dialog with given title, message, buttons.
* This dialog only shows up to 3 buttons. Any labels after that will be ignored.
* The index of the button pressed will be returned to the JavaScript callback identified by callbackId.
*
* @param message The message the dialog should display
* @param title The title of the dialog
* @param buttonLabels A comma separated list of button labels (Up to 3 buttons)
* @param callbackContext The callback context.
*/
public synchronized void confirm(final String message, final String title, final JSONArray buttonLabels, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(true);
// First button
if (buttonLabels.length() > 0) {
try {
dlg.setNegativeButton(buttonLabels.getString(0),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 1));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on first button.");
}
}
// Second button
if (buttonLabels.length() > 1) {
try {
dlg.setNeutralButton(buttonLabels.getString(1),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 2));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on second button.");
}
}
// Third button
if (buttonLabels.length() > 2) {
try {
dlg.setPositiveButton(buttonLabels.getString(2),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 3));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on third button.");
}
}
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog)
{
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
});
changeTextDirection(dlg);
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Builds and shows a native Android prompt dialog with given title, message, buttons.
* This dialog only shows up to 3 buttons. Any labels after that will be ignored.
* The following results are returned to the JavaScript callback identified by callbackId:
* buttonIndex Index number of the button selected
* input1 The text entered in the prompt dialog box
*
* @param message The message the dialog should display
* @param title The title of the dialog
* @param buttonLabels A comma separated list of button labels (Up to 3 buttons)
* @param callbackContext The callback context.
*/
public synchronized void prompt(final String message, final String title, final JSONArray buttonLabels, final String defaultText, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
final EditText promptInput = new EditText(cordova.getActivity());
promptInput.setHint(defaultText);
AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(true);
dlg.setView(promptInput);
final JSONObject result = new JSONObject();
// First button
if (buttonLabels.length() > 0) {
try {
dlg.setNegativeButton(buttonLabels.getString(0),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
result.put("buttonIndex",1);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on first button.", e);
}
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on first button.");
}
}
// Second button
if (buttonLabels.length() > 1) {
try {
dlg.setNeutralButton(buttonLabels.getString(1),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
result.put("buttonIndex",2);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on second button.", e);
}
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on second button.");
}
}
// Third button
if (buttonLabels.length() > 2) {
try {
dlg.setPositiveButton(buttonLabels.getString(2),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
result.put("buttonIndex",3);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on third button.", e);
}
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on third button.");
}
}
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog){
dialog.dismiss();
try {
result.put("buttonIndex",0);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) { e.printStackTrace(); }
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
changeTextDirection(dlg);
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Show the spinner.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public synchronized void activityStart(final String title, final String message) {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
final Notification notification = this;
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
notification.spinnerDialog = createProgressDialog(cordova); // new ProgressDialog(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
notification.spinnerDialog.setTitle(title);
notification.spinnerDialog.setMessage(message);
notification.spinnerDialog.setCancelable(true);
notification.spinnerDialog.setIndeterminate(true);
notification.spinnerDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
notification.spinnerDialog = null;
}
});
notification.spinnerDialog.show();
}
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Stop spinner.
*/
public synchronized void activityStop() {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
}
/**
* Show the progress dialog.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public synchronized void progressStart(final String title, final String message) {
if (this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
final Notification notification = this;
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
notification.progressDialog = createProgressDialog(cordova); // new ProgressDialog(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
notification.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
notification.progressDialog.setTitle(title);
notification.progressDialog.setMessage(message);
notification.progressDialog.setCancelable(true);
notification.progressDialog.setMax(100);
notification.progressDialog.setProgress(0);
notification.progressDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
notification.progressDialog = null;
}
});
notification.progressDialog.show();
}
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Set value of progress bar.
*
* @param value 0-100
*/
public synchronized void progressValue(int value) {
if (this.progressDialog != null) {
this.progressDialog.setProgress(value);
}
}
/**
* Stop progress dialog.
*/
public synchronized void progressStop() {
if (this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
}
@SuppressLint("NewApi")
private AlertDialog.Builder createDialog(CordovaInterface cordova) {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB) {
return new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
} else {
return new AlertDialog.Builder(cordova.getActivity());
}
}
@SuppressLint("InlinedApi")
private ProgressDialog createProgressDialog(CordovaInterface cordova) {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return new ProgressDialog(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
} else {
return new ProgressDialog(cordova.getActivity());
}
}
@SuppressLint("NewApi")
private void changeTextDirection(Builder dlg){
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
dlg.create();
AlertDialog dialog = dlg.show();
if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
TextView messageview = (TextView)dialog.findViewById(android.R.id.message);
messageview.setTextDirection(android.view.View.TEXT_DIRECTION_LOCALE);
}
}
}
| src/android/Notification.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.cordova.dialogs;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.widget.EditText;
import android.widget.TextView;
/**
* This class provides access to notifications on the device.
*
* Be aware that this implementation gets called on
* navigator.notification.{alert|confirm|prompt}, and that there is a separate
* implementation in org.apache.cordova.CordovaChromeClient that gets
* called on a simple window.{alert|confirm|prompt}.
*/
public class Notification extends CordovaPlugin {
private static final String LOG_TAG = "Notification";
public int confirmResult = -1;
public ProgressDialog spinnerDialog = null;
public ProgressDialog progressDialog = null;
/**
* Constructor.
*/
public Notification() {
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArray of arguments for the plugin.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return True when the action was valid, false otherwise.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
/*
* Don't run any of these if the current activity is finishing
* in order to avoid android.view.WindowManager$BadTokenException
* crashing the app. Just return true here since false should only
* be returned in the event of an invalid action.
*/
if(this.cordova.getActivity().isFinishing()) return true;
if (action.equals("beep")) {
this.beep(args.getLong(0));
}
else if (action.equals("alert")) {
this.alert(args.getString(0), args.getString(1), args.getString(2), callbackContext);
return true;
}
else if (action.equals("confirm")) {
this.confirm(args.getString(0), args.getString(1), args.getJSONArray(2), callbackContext);
return true;
}
else if (action.equals("prompt")) {
this.prompt(args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), callbackContext);
return true;
}
else if (action.equals("activityStart")) {
this.activityStart(args.getString(0), args.getString(1));
}
else if (action.equals("activityStop")) {
this.activityStop();
}
else if (action.equals("progressStart")) {
this.progressStart(args.getString(0), args.getString(1));
}
else if (action.equals("progressValue")) {
this.progressValue(args.getInt(0));
}
else if (action.equals("progressStop")) {
this.progressStop();
}
else {
return false;
}
// Only alert and confirm are async.
callbackContext.success();
return true;
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Beep plays the default notification ringtone.
*
* @param count Number of times to play notification
*/
public void beep(final long count) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
Ringtone notification = RingtoneManager.getRingtone(cordova.getActivity().getBaseContext(), ringtone);
// If phone is not set to silent mode
if (notification != null) {
for (long i = 0; i < count; ++i) {
notification.play();
long timeout = 5000;
while (notification.isPlaying() && (timeout > 0)) {
timeout = timeout - 100;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}
});
}
/**
* Builds and shows a native Android alert with given Strings
* @param message The message the alert should display
* @param title The title of the alert
* @param buttonLabel The label of the button
* @param callbackContext The callback context
*/
public synchronized void alert(final String message, final String title, final String buttonLabel, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(true);
dlg.setPositiveButton(buttonLabel,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
});
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog)
{
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
});
changeTextDirection(dlg);
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Builds and shows a native Android confirm dialog with given title, message, buttons.
* This dialog only shows up to 3 buttons. Any labels after that will be ignored.
* The index of the button pressed will be returned to the JavaScript callback identified by callbackId.
*
* @param message The message the dialog should display
* @param title The title of the dialog
* @param buttonLabels A comma separated list of button labels (Up to 3 buttons)
* @param callbackContext The callback context.
*/
public synchronized void confirm(final String message, final String title, final JSONArray buttonLabels, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(true);
// First button
if (buttonLabels.length() > 0) {
try {
dlg.setNegativeButton(buttonLabels.getString(0),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 1));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on first button.");
}
}
// Second button
if (buttonLabels.length() > 1) {
try {
dlg.setNeutralButton(buttonLabels.getString(1),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 2));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on second button.");
}
}
// Third button
if (buttonLabels.length() > 2) {
try {
dlg.setPositiveButton(buttonLabels.getString(2),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 3));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on third button.");
}
}
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog)
{
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
});
changeTextDirection(dlg);
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Builds and shows a native Android prompt dialog with given title, message, buttons.
* This dialog only shows up to 3 buttons. Any labels after that will be ignored.
* The following results are returned to the JavaScript callback identified by callbackId:
* buttonIndex Index number of the button selected
* input1 The text entered in the prompt dialog box
*
* @param message The message the dialog should display
* @param title The title of the dialog
* @param buttonLabels A comma separated list of button labels (Up to 3 buttons)
* @param callbackContext The callback context.
*/
public synchronized void prompt(final String message, final String title, final JSONArray buttonLabels, final String defaultText, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
final EditText promptInput = new EditText(cordova.getActivity());
promptInput.setHint(defaultText);
AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(true);
dlg.setView(promptInput);
final JSONObject result = new JSONObject();
// First button
if (buttonLabels.length() > 0) {
try {
dlg.setNegativeButton(buttonLabels.getString(0),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
result.put("buttonIndex",1);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on first button.", e);
}
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on first button.");
}
}
// Second button
if (buttonLabels.length() > 1) {
try {
dlg.setNeutralButton(buttonLabels.getString(1),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
result.put("buttonIndex",2);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on second button.", e);
}
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on second button.");
}
}
// Third button
if (buttonLabels.length() > 2) {
try {
dlg.setPositiveButton(buttonLabels.getString(2),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
result.put("buttonIndex",3);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on third button.", e);
}
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on third button.");
}
}
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog){
dialog.dismiss();
try {
result.put("buttonIndex",0);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) { e.printStackTrace(); }
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
changeTextDirection(dlg);
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Show the spinner.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public synchronized void activityStart(final String title, final String message) {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
final Notification notification = this;
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
notification.spinnerDialog = createProgressDialog(cordova); // new ProgressDialog(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
notification.spinnerDialog.setTitle(title);
notification.spinnerDialog.setMessage(message);
notification.spinnerDialog.setCancelable(true);
notification.spinnerDialog.setIndeterminate(true);
notification.spinnerDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
notification.spinnerDialog = null;
}
});
notification.spinnerDialog.show();
}
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Stop spinner.
*/
public synchronized void activityStop() {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
}
/**
* Show the progress dialog.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public synchronized void progressStart(final String title, final String message) {
if (this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
final Notification notification = this;
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
notification.progressDialog = createProgressDialog(cordova); // new ProgressDialog(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
notification.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
notification.progressDialog.setTitle(title);
notification.progressDialog.setMessage(message);
notification.progressDialog.setCancelable(true);
notification.progressDialog.setMax(100);
notification.progressDialog.setProgress(0);
notification.progressDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
notification.progressDialog = null;
}
});
notification.progressDialog.show();
}
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Set value of progress bar.
*
* @param value 0-100
*/
public synchronized void progressValue(int value) {
if (this.progressDialog != null) {
this.progressDialog.setProgress(value);
}
}
/**
* Stop progress dialog.
*/
public synchronized void progressStop() {
if (this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
}
@SuppressLint("NewApi")
private AlertDialog.Builder createDialog(CordovaInterface cordova) {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB) {
return new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
} else {
return new AlertDialog.Builder(cordova.getActivity());
}
}
@SuppressLint("InlinedApi")
private ProgressDialog createProgressDialog(CordovaInterface cordova) {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return new ProgressDialog(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
} else {
return new ProgressDialog(cordova.getActivity());
}
}
@SuppressLint("NewApi")
private void changeTextDirection(Builder dlg){
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
dlg.create();
AlertDialog dialog = dlg.show();
if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
TextView messageview = (TextView)dialog.findViewById(android.R.id.message);
messageview.setTextDirection(android.view.View.TEXT_DIRECTION_LOCALE);
}
}
}
| Update Notification.java | src/android/Notification.java | Update Notification.java | <ide><path>rc/android/Notification.java
<ide> import org.json.JSONArray;
<ide> import org.json.JSONException;
<ide> import org.json.JSONObject;
<add>import android.content.Context;
<ide>
<ide> import android.annotation.SuppressLint;
<ide> import android.app.AlertDialog;
<ide> import android.content.DialogInterface;
<ide> import android.media.Ringtone;
<ide> import android.media.RingtoneManager;
<add>import android.media.AudioManager;
<ide> import android.net.Uri;
<ide> import android.widget.EditText;
<ide> import android.widget.TextView;
<ide> Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
<ide> Ringtone notification = RingtoneManager.getRingtone(cordova.getActivity().getBaseContext(), ringtone);
<ide>
<del> // If phone is not set to silent mode
<del> if (notification != null) {
<del> for (long i = 0; i < count; ++i) {
<del> notification.play();
<del> long timeout = 5000;
<del> while (notification.isPlaying() && (timeout > 0)) {
<del> timeout = timeout - 100;
<del> try {
<del> Thread.sleep(100);
<del> } catch (InterruptedException e) {
<del> Thread.currentThread().interrupt();
<add> if(count == 1){
<add> // If phone is not set to silent mode
<add> if (notification != null) {
<add> for (long i = 0; i < count; ++i) {
<add> notification.play();
<add> long timeout = 5000;
<add> while (notification.isPlaying() && (timeout > 0)) {
<add> timeout = timeout - 100;
<add> try {
<add> Thread.sleep(100);
<add> } catch (InterruptedException e) {
<add> Thread.currentThread().interrupt();
<add> }
<ide> }
<ide> }
<ide> }
<ide> }
<add> if(count == 2){
<add> AudioManager aM = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
<add> aM.setRingerMode(AudioManager.RINGER_MODE_SILENT);
<add> }
<add>
<ide> }
<ide> });
<ide> } |
|
Java | apache-2.0 | d37071008aa60a56b5abbb21497841b6d723d33b | 0 | sotorrent/so-posthistory-extractor | package de.unitrier.st.soposthistory.tests;
import com.google.common.collect.Sets;
import de.unitrier.st.soposthistory.blocks.CodeBlockVersion;
import de.unitrier.st.soposthistory.blocks.PostBlockVersion;
import de.unitrier.st.soposthistory.blocks.TextBlockVersion;
import de.unitrier.st.soposthistory.gt.*;
import de.unitrier.st.soposthistory.version.PostVersion;
import de.unitrier.st.soposthistory.version.PostVersionList;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.csv.QuoteMode;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.junit.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.*;
class BlockLifeSpanAndGroundTruthTest {
private static Path pathToPostIdList = Paths.get("testdata", "postIds.csv");
private static Path pathToPostHistory = Paths.get("testdata");
private static Path pathToGroundTruth = Paths.get("testdata", "gt");
private static Path outputDir = Paths.get("testdata", "metrics comparison");
@Test
void testReadFromDirectory() {
List<PostGroundTruth> postGroundTruthList = PostGroundTruth.readFromDirectory(pathToGroundTruth);
try {
assertEquals(Files.list(pathToGroundTruth).filter(
file -> PostGroundTruth.fileNamePattern.matcher(file.toFile().getName()).matches())
.count(),
postGroundTruthList.size());
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
void testPostBlockLifeSpanVersionsEqual(){
// compare two PostBlockLifeSpanVersions
PostBlockLifeSpanVersion original = new PostBlockLifeSpanVersion(4711, 42, 1, 0, 0, 0, "");
PostBlockLifeSpanVersion differentPostId = new PostBlockLifeSpanVersion(4712, 42, 1, 0, 0, 0, "");
PostBlockLifeSpanVersion differentPostHistoryId = new PostBlockLifeSpanVersion(4711, 43, 1, 0, 0, 0, "");
PostBlockLifeSpanVersion differentPostBlockTypeId = new PostBlockLifeSpanVersion(4711, 42, 2, 0, 0, 0, "");
PostBlockLifeSpanVersion differentLocalId = new PostBlockLifeSpanVersion(4711, 42, 1, 1, 0, 0, "");
PostBlockLifeSpanVersion differentPredId = new PostBlockLifeSpanVersion(4711, 42, 1, 0, 1, 0,"");
PostBlockLifeSpanVersion differentSuccId = new PostBlockLifeSpanVersion(4711, 42, 1, 0, 0, 1, "");
assertTrue(original.equals(original));
assertFalse(original.equals(differentPostId));
assertFalse(original.equals(differentPostHistoryId));
assertFalse(original.equals(differentPostBlockTypeId));
assertFalse(original.equals(differentLocalId));
assertTrue(original.equals(differentPredId));
assertTrue(original.equals(differentSuccId));
}
@Test
void testPostBlockLifeSpanExtraction() {
int postId = 22037280;
PostVersionList a_22037280 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2);
PostGroundTruth a_22037280_gt = PostGroundTruth.readFromCSV(pathToGroundTruth, postId);
List<PostBlockLifeSpan> lifeSpans = a_22037280.getPostBlockLifeSpans();
List<PostBlockLifeSpan> lifeSpansGT = a_22037280_gt.getPostBlockLifeSpans();
assertEquals(lifeSpans.size(), lifeSpansGT.size());
assertEquals(5, lifeSpans.size());
for (int i=0; i<lifeSpans.size(); i++) {
assertTrue(lifeSpans.get(i).equals(lifeSpansGT.get(i)));
}
}
@Test
void testPostBlockLifeSpanExtractionFilter() {
int postId = 22037280;
PostVersionList a_22037280 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2);
PostGroundTruth a_22037280_gt = PostGroundTruth.readFromCSV(pathToGroundTruth, postId);
// text
List<PostBlockLifeSpan> textBlockLifeSpans = a_22037280.getPostBlockLifeSpans(
TextBlockVersion.getPostBlockTypeIdFilter()
);
List<PostBlockLifeSpan> textLifeSpansGT = a_22037280_gt.getPostBlockLifeSpans(
TextBlockVersion.getPostBlockTypeIdFilter()
);
assertEquals(textBlockLifeSpans.size(), textLifeSpansGT.size());
assertEquals(3, textBlockLifeSpans.size());
for (int i=0; i<textBlockLifeSpans.size(); i++) {
assertTrue(textBlockLifeSpans.get(i).equals(textLifeSpansGT.get(i)));
}
// code
List<PostBlockLifeSpan> codeBlockLifeSpans = a_22037280.getPostBlockLifeSpans(
CodeBlockVersion.getPostBlockTypeIdFilter()
);
List<PostBlockLifeSpan> codeLifeSpansGT = a_22037280_gt.getPostBlockLifeSpans(
CodeBlockVersion.getPostBlockTypeIdFilter()
);
assertEquals(codeBlockLifeSpans.size(), codeLifeSpansGT.size());
assertEquals(2, codeBlockLifeSpans.size());
for (int i=0; i<codeBlockLifeSpans.size(); i++) {
assertTrue(codeBlockLifeSpans.get(i).equals(codeLifeSpansGT.get(i)));
}
}
@Test
void testPostBlockConnectionExtraction() {
int postId = 22037280;
PostVersionList a_22037280 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2);
PostGroundTruth a_22037280_gt = PostGroundTruth.readFromCSV(pathToGroundTruth, postId);
List<PostBlockLifeSpan> lifeSpans = a_22037280.getPostBlockLifeSpans();
List<PostBlockLifeSpan> lifeSpansGT = a_22037280_gt.getPostBlockLifeSpans();
Set<PostBlockConnection> connections = PostBlockLifeSpan.toPostBlockConnections(lifeSpans);
Set<PostBlockConnection> connectionsGT = PostBlockLifeSpan.toPostBlockConnections(lifeSpansGT);
assertEquals(connections.size(), connectionsGT.size());
assertTrue(PostBlockConnection.equals(connections, connectionsGT));
assertTrue(PostBlockConnection.equals(
PostBlockConnection.intersection(connections, connectionsGT),
connections)
);
assertTrue(PostBlockConnection.equals(
PostBlockConnection.union(connections, connectionsGT),
connections)
);
assertEquals(0, PostBlockConnection.difference(connections, connectionsGT).size());
}
@Test
void testPostBlockPossibleConnectionsComparison() {
int postId = 22037280;
PostVersionList a_22037280 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2);
PostGroundTruth a_22037280_gt = PostGroundTruth.readFromCSV(pathToGroundTruth, postId);
assertEquals(78, a_22037280.getPossibleConnections());
assertEquals(a_22037280.getPossibleConnections(), a_22037280_gt.getPossibleConnections());
}
@Test
void testPostBlockConnectionEquals() {
PostBlockLifeSpanVersion v1_1 = new PostBlockLifeSpanVersion(1, 1, 1, 1);
PostBlockLifeSpanVersion v1_2 = new PostBlockLifeSpanVersion(1, 1, 1, 1);
PostBlockLifeSpanVersion v2 = new PostBlockLifeSpanVersion(1, 2, 1, 1);
PostBlockLifeSpanVersion v3 = new PostBlockLifeSpanVersion(1, 3, 1, 1);
PostBlockLifeSpanVersion v4 = new PostBlockLifeSpanVersion(1, 4, 1, 1);
// test equality of PostBlockLifeSpanVersions
assertEquals(v1_1.getPostId(), v1_2.getPostId());
assertEquals(v1_1.getPostHistoryId(), v1_2.getPostHistoryId());
assertEquals(v1_1.getPostBlockTypeId(), v1_2.getPostBlockTypeId());
assertEquals(v1_1.getLocalId(), v1_2.getLocalId());
// test equality of PostBlockConnections
PostBlockConnection connection1 = new PostBlockConnection(v1_1, v2);
PostBlockConnection connection2 = new PostBlockConnection(v1_2, v2);
assertTrue(connection1.equals(connection2));
// test equaliy of a set of PostBlockConnections
PostBlockConnection connection3 = new PostBlockConnection(v1_2, v2);
PostBlockConnection connection4 = new PostBlockConnection(v3, v4);
assertTrue(PostBlockConnection.equals(
Sets.newHashSet(connection1, connection2, connection3, connection4),
Sets.newHashSet(connection1, connection2, connection3, connection4))
);
}
@Test
void testGetConnections(){
int postId = 22037280;
PostVersionList a_22037280 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2);
PostGroundTruth a_22037280_gt = PostGroundTruth.readFromCSV(pathToGroundTruth, postId);
List<Integer> postVersionListPostHistoryIds = a_22037280.getPostHistoryIds();
List<Integer> groundTruthPostHistoryIds = a_22037280_gt.getPostHistoryIds();
assertEquals(postVersionListPostHistoryIds, groundTruthPostHistoryIds);
for (Integer postHistoryId : groundTruthPostHistoryIds) {
Set<PostBlockConnection> postBlockConnections = a_22037280.getPostVersion(postHistoryId).getConnections();
Set<PostBlockConnection> postBlockConnectionsGT = a_22037280_gt.getConnections(postHistoryId);
assertTrue(PostBlockConnection.equals(postBlockConnections, postBlockConnectionsGT));
}
}
@Test
void testProcessVersionHistoryWithIntermediateResetting() {
int postId = 22037280;
PostVersionList a_22037280 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2, false);
testPostBlockVersionHistoryReset(a_22037280);
a_22037280.processVersionHistory();
testPostBlockVersionHistoryProcessed(a_22037280);
a_22037280.resetPostBlockVersionHistory();
testPostBlockVersionHistoryReset(a_22037280);
a_22037280.processVersionHistory();
testPostBlockVersionHistoryProcessed(a_22037280);
}
private void testPostBlockVersionHistoryReset(PostVersionList postVersionList) {
for (PostVersion currentPostVersion : postVersionList) {
for (PostBlockVersion currentPostBlockVersion : currentPostVersion.getPostBlocks()) {
assertNull(currentPostBlockVersion.getRootPostBlockId());
assertNull(currentPostBlockVersion.getPredPostBlockId());
assertNull(currentPostBlockVersion.getPredEqual());
assertNull(currentPostBlockVersion.getPredSimilarity());
assertEquals(0, currentPostBlockVersion.getPredCount());
assertEquals(0, currentPostBlockVersion.getSuccCount());
assertNull(currentPostBlockVersion.getPred());
assertNull(currentPostBlockVersion.getSucc());
assertNull(currentPostBlockVersion.getRootPostBlock());
assertNull(currentPostBlockVersion.getPredDiff());
assertTrue(currentPostBlockVersion.isAvailable());
assertEquals(0, currentPostBlockVersion.getMatchingPredecessors().size());
assertEquals(0, currentPostBlockVersion.getPredecessorSimilarities().size());
assertEquals(-1.0, currentPostBlockVersion.getMaxSimilarity());
assertEquals(-1.0, currentPostBlockVersion.getSimilarityThreshold());
assertFalse(currentPostBlockVersion.isLifeSpanExtracted());
}
}
}
private void testPostBlockVersionHistoryProcessed(PostVersionList postVersionList) {
for (PostVersion currentPostVersion : postVersionList) {
for (PostBlockVersion currentPostBlockVersion : currentPostVersion.getPostBlocks()) {
assertNotNull(currentPostBlockVersion.getRootPostBlockId());
assertNotNull(currentPostBlockVersion.getRootPostBlock());
}
}
}
@Test
void testMetricComparisonManager() {
MetricComparisonManager manager = MetricComparisonManager.create(
"TestManager", pathToPostIdList, pathToPostHistory, pathToGroundTruth, false
);
assertEquals(manager.getPostVersionLists().size(), manager.getPostGroundTruth().size());
assertThat(manager.getPostVersionLists().keySet(), is(manager.getPostGroundTruth().keySet()));
manager.addSimilarityMetric(
"fourGramOverlap",
de.unitrier.st.stringsimilarity.set.Variants::fourGramOverlap
);
manager.addSimilarityThreshold(0.6);
manager.compareMetrics();
List<Integer> postHistoryIds_3758880 = manager.getPostGroundTruth().get(3758880).getPostHistoryIds();
MetricComparison comparison_a_3758880 = manager.getMetricComparison(3758880, "fourGramOverlap", 0.6);
/* compare a 3758880 */
// first version has never predecessors
int version_1_id = postHistoryIds_3758880.get(0);
assertEquals(new Integer(0), comparison_a_3758880.getTruePositivesText().get(version_1_id));
assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesText().get(version_1_id));
assertEquals(new Integer(0), comparison_a_3758880.getTrueNegativesText().get(version_1_id));
assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesText().get(version_1_id));
assertEquals(new Integer(0), comparison_a_3758880.getTruePositivesCode().get(version_1_id));
assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesCode().get(version_1_id));
assertEquals(new Integer(0), comparison_a_3758880.getTrueNegativesCode().get(version_1_id));
assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesCode().get(version_1_id));
// second version
int version_id = postHistoryIds_3758880.get(1);
assertEquals(new Integer(1), comparison_a_3758880.getTruePositivesText().get(version_id));
assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesText().get(version_id));
assertEquals(new Integer(5), comparison_a_3758880.getTrueNegativesText().get(version_id));
assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesText().get(version_id));
assertEquals(new Integer(2), comparison_a_3758880.getTruePositivesCode().get(version_id));
assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesCode().get(version_id));
assertEquals(new Integer(4), comparison_a_3758880.getTrueNegativesCode().get(version_id));
assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesCode().get(version_id));
// version 3 to 10 only for text blocks (they don't differ)
for(int i=2; i<10; i++){
int version_2_to_11_id_text = postHistoryIds_3758880.get(i);
assertEquals(new Integer(2), comparison_a_3758880.getTruePositivesText().get(version_2_to_11_id_text));
assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesText().get(version_2_to_11_id_text));
assertEquals(new Integer(2), comparison_a_3758880.getTrueNegativesText().get(version_2_to_11_id_text));
assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesText().get(version_2_to_11_id_text));
}
int version_11_id_text = postHistoryIds_3758880.get(10);
assertEquals(new Integer(2), comparison_a_3758880.getTruePositivesText().get(version_11_id_text));
assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesText().get(version_11_id_text));
assertEquals(new Integer(4), comparison_a_3758880.getTrueNegativesText().get(version_11_id_text));
assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesText().get(version_11_id_text));
// version 3 and 6 for code
List<Integer> versionsOfType1 = Arrays.asList(2,5);
for (Integer version : versionsOfType1) {
int version_3_or_6_id = postHistoryIds_3758880.get(version);
assertEquals(new Integer(1), comparison_a_3758880.getTruePositivesCode().get(version_3_or_6_id));
assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesCode().get(version_3_or_6_id));
assertEquals(new Integer(2), comparison_a_3758880.getTrueNegativesCode().get(version_3_or_6_id));
assertEquals(new Integer(1), comparison_a_3758880.getFalseNegativesCode().get(version_3_or_6_id));
}
// version 4,5,7,8,9,10,11 for code
List<Integer> versionsOfType2 = Arrays.asList(3,4,6,7,8,9,10);
for (Integer version : versionsOfType2) {
int version_i_id = postHistoryIds_3758880.get(version);
assertEquals(new Integer(2), comparison_a_3758880.getTruePositivesCode().get(version_i_id));
assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesCode().get(version_i_id));
assertEquals(new Integer(2), comparison_a_3758880.getTrueNegativesCode().get(version_i_id));
assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesCode().get(version_i_id));
}
/* compare a 22037280 */
List<Integer> postHistoryIds_22037280 = manager.getPostGroundTruth().get(22037280).getPostHistoryIds();
MetricComparison comparison_a_22037280 = manager.getMetricComparison(22037280, "fourGramOverlap", 0.6);
version_1_id = postHistoryIds_22037280.get(0);
assertEquals(new Integer(0), comparison_a_22037280.getTruePositivesText().get(version_1_id));
assertEquals(new Integer(0), comparison_a_22037280.getFalsePositivesText().get(version_1_id));
assertEquals(new Integer(0), comparison_a_22037280.getTrueNegativesText().get(version_1_id));
assertEquals(new Integer(0), comparison_a_22037280.getFalseNegativesText().get(version_1_id));
assertEquals(new Integer(0), comparison_a_22037280.getTruePositivesCode().get(version_1_id));
assertEquals(new Integer(0), comparison_a_22037280.getFalsePositivesCode().get(version_1_id));
assertEquals(new Integer(0), comparison_a_22037280.getTrueNegativesCode().get(version_1_id));
assertEquals(new Integer(0), comparison_a_22037280.getFalseNegativesCode().get(version_1_id));
for(int i=1; i<postHistoryIds_22037280.size(); i++) {
version_id = postHistoryIds_22037280.get(i);
assertEquals(new Integer(3), comparison_a_22037280.getTruePositivesText().get(version_id));
assertEquals(new Integer(0), comparison_a_22037280.getFalsePositivesText().get(version_id));
assertEquals(new Integer(6), comparison_a_22037280.getTrueNegativesText().get(version_id));
assertEquals(new Integer(0), comparison_a_22037280.getFalseNegativesText().get(version_id));
assertEquals(new Integer(2), comparison_a_22037280.getTruePositivesCode().get(version_id));
assertEquals(new Integer(0), comparison_a_22037280.getFalsePositivesCode().get(version_id));
assertEquals(new Integer(2), comparison_a_22037280.getTrueNegativesCode().get(version_id));
assertEquals(new Integer(0), comparison_a_22037280.getFalseNegativesCode().get(version_id));
}
manager.writeToCSV(outputDir);
}
@Test
void testCompareMetricComparisonManagerWithComparisonFromOldProject() {
MetricComparisonManager manager = MetricComparisonManager.create(
"TestManager", pathToPostIdList, pathToPostHistory, pathToGroundTruth, true
);
List<Integer> postHistoryIds_3758880 = new LinkedList<>();
postHistoryIds_3758880.add(7873162);
postHistoryIds_3758880.add(7873319);
postHistoryIds_3758880.add(7873489);
postHistoryIds_3758880.add(7873581);
postHistoryIds_3758880.add(7874248);
postHistoryIds_3758880.add(7874570);
postHistoryIds_3758880.add(7874704);
postHistoryIds_3758880.add(7875126);
postHistoryIds_3758880.add(15577610);
postHistoryIds_3758880.add(24534909);
postHistoryIds_3758880.add(130380462);
// List<Integer> postHistoryIds_22037280 = manager.getPostVersionLists().get(1).getPostHistoryIds();
assertEquals(manager.getPostVersionLists().size(), manager.getPostGroundTruth().size());
assertThat(manager.getPostVersionLists().keySet(), is(manager.getPostGroundTruth().keySet()));
manager.compareMetrics();
manager.writeToCSV(Paths.get("aaa"));
CSVParser csvParser = null;
try {
csvParser = CSVParser.parse(
Paths.get("testdata", "metrics comparison", "resultsMetricComparisonOldProject.csv").toFile(),
StandardCharsets.UTF_8,
CSVFormat.DEFAULT.withHeader("sample", "metric", "threshold", "postid", "posthistoryid", "runtimetext", "#truepositivestext", "#truenegativestext",
"#falsepositivestext", "#falsenegativestext", "#runtimecode", "#truepositivescode", "#truenegativescode",
"#falsepositivescode", "#falsenegativescode").withDelimiter(';')
.withQuote('"')
.withQuoteMode(QuoteMode.MINIMAL)
.withEscape('\\')
.withFirstRecordAsHeader()
);
csvParser.getHeaderMap();
List<CSVRecord> records = csvParser.getRecords();
for(CSVRecord record : records){
String metric = record.get("metric");
Double threshold = Double.valueOf(record.get("threshold"));
Integer postId = Integer.valueOf(record.get("postid"));
Integer postHistoryId = null;
Integer truePositivesText = null;
Integer trueNegativesText = null;
Integer falsePositivesText = null;
Integer falseNegativesText = null;
Integer truePositivesCode = null;
Integer trueNegativesCode = null;
Integer falsePositivesCode = null;
Integer falseNegativesCode = null;
try{
postHistoryId = Integer.valueOf(record.get("posthistoryid"));
truePositivesText = Integer.valueOf(record.get("#truepositivestext"));
trueNegativesText = Integer.valueOf(record.get("#truenegativestext"));
falsePositivesText = Integer.valueOf(record.get("#falsepositivestext"));
falseNegativesText = Integer.valueOf(record.get("#falsenegativestext"));
truePositivesCode = Integer.valueOf(record.get("#truepositivescode"));
trueNegativesCode = Integer.valueOf(record.get("#truenegativescode"));
falsePositivesCode = Integer.valueOf(record.get("#falsepositivescode"));
falseNegativesCode = Integer.valueOf(record.get("#falsenegativescode"));
}catch (NumberFormatException e){}
MetricComparison tmpMetricComparison = manager.getMetricComparison(postId, metric, threshold);
if(postHistoryId != null) {
int tmpPostHistoryId = -1;
if (postId == 3758880) {
for (int i = 0; i < postHistoryIds_3758880.size(); i++) {
if (Objects.equals(postHistoryIds_3758880.get(i), postHistoryId)) {
tmpPostHistoryId = postHistoryIds_3758880.get(i + 1);
}
}
assertEquals(tmpMetricComparison.getTruePositivesText().get(tmpPostHistoryId), truePositivesText);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
void testGetPossibleConnections() {
int postId = 22037280;
PostVersionList a_22037280 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2);
PostGroundTruth a_22037280_gt = PostGroundTruth.readFromCSV(pathToGroundTruth, postId);
assertEquals(7, a_22037280.size());
assertEquals(a_22037280.getPossibleConnections(), a_22037280_gt.getPossibleConnections());
for (PostVersion postVersion : a_22037280) {
assertEquals(3, postVersion.getTextBlocks().size());
assertEquals(2, postVersion.getCodeBlocks().size());
}
Set<Integer> set = new HashSet<>();
assertEquals(0, a_22037280.getPossibleConnections(set));
int possibleTextConnections = a_22037280.getPossibleConnections(TextBlockVersion.getPostBlockTypeIdFilter());
assertEquals(6 * 9, possibleTextConnections); // 6 versions with each 9=3*3 possible text connections
int possibleCodeConnections = a_22037280.getPossibleConnections(CodeBlockVersion.getPostBlockTypeIdFilter());
assertEquals(6 * 4, possibleCodeConnections); // 6 versions with each 4=2*2 possible code connections
int possibleConnections = a_22037280.getPossibleConnections(PostBlockVersion.getAllPostBlockTypeIdFilters());
assertEquals(6 * 4 + 6 * 9, possibleConnections); // 6 versions with each 4=2*2 and 9=3*3 possible connections
// compare results of getPossibleConnections() for PostVersion and PostVersionList
possibleConnections = 0;
for (PostVersion current : a_22037280) {
possibleConnections += current.getPossibleConnections();
}
assertEquals(a_22037280.getPossibleConnections(), possibleConnections);
// check if post version pred and succ assignments are also set in case post history has not been processed yet
possibleConnections = 0;
for (PostVersion current : a_22037280) {
possibleConnections += current.getPossibleConnections();
}
assertEquals(a_22037280.getPossibleConnections(), possibleConnections);
}
// @Test
// void testNumberOfPredecessorsOfOnePost() {
// int postId = 3758880;
// PostVersionList a_3758880 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2, false);
// PostGroundTruth a_3758880_gt = PostGroundTruth.readFromCSV(pathToGroundTruth, postId);
//
// postVersionsListManagement.getPostVersionListWithID(postId).processVersionHistory(
// PostVersionList.PostBlockTypeFilter.TEXT,
// Config.DEFAULT.withTextSimilarityMetric(de.unitrier.st.stringsimilarity.set.Variants::twoGramDice));
//
// List<TextBlockVersion> textBlocks = postVersionsListManagement.getPostVersionListWithID(postId).get(postVersionsListManagement.getPostVersionListWithID(postId).size() - 1).getTextBlocks();
// assertEquals(new Integer(1), textBlocks.get(0).getPred().getLocalId());
// assertEquals(new Integer(1), textBlocks.get(0).getLocalId());
//
// assertEquals(new Integer(3), textBlocks.get(1).getPred().getLocalId());
// assertEquals(new Integer(3), textBlocks.get(1).getLocalId());
//
// assertEquals(null, textBlocks.get(2).getPred());
// assertEquals(new Integer(5), textBlocks.get(2).getLocalId());
// }
// @Test
// void testGroundTruthExtractionOfCSV(){
//
// // testing text
// assertNull(groundTruthExtractionOfCSVs.getAllConnectionsOfAllConsecutiveVersions_text(4711)); // post with id 4711 is not listed in ground truth
// assertEquals(2, groundTruthExtractionOfCSVs.getGroundTruthText().size());
//
// ConnectionsOfAllVersions connectionsOfAllVersions_text = groundTruthExtractionOfCSVs.getGroundTruthText().getFirst();
// assertEquals(connectionsOfAllVersions_text, groundTruthExtractionOfCSVs.getAllConnectionsOfAllConsecutiveVersions_text(3758880));
// assertEquals(10, connectionsOfAllVersions_text.size()); // post version list has 11 versions and therefore 10 comparisons for adjacent versions
//
// assertEquals(new Integer(1), connectionsOfAllVersions_text.get(0).get(0).getLeftLocalId());
// assertEquals(new Integer(1), connectionsOfAllVersions_text.get(0).get(0).getRightLocalId());
// assertEquals(1, connectionsOfAllVersions_text.get(0).get(0).getPostBlockTypeId());
// assertNull(connectionsOfAllVersions_text.get(0).get(1).getLeftLocalId());
// assertEquals(new Integer(3),connectionsOfAllVersions_text.get(0).get(1).getRightLocalId());
//
// assertEquals(new Integer(3), connectionsOfAllVersions_text.get(7).get(1).getLeftLocalId());
// assertEquals(new Integer(3), connectionsOfAllVersions_text.get(7).get(1).getRightLocalId());
//
//
// // testing code
// ConnectionsOfAllVersions connectionsOfAllVersions_code = groundTruthExtractionOfCSVs.getGroundTruthCode().getFirst();
// assertEquals(10, connectionsOfAllVersions_code.size()); // post version list has 11 versions and therefore 10 comparisons for adjacent versions
//
// assertEquals(new Integer(6), connectionsOfAllVersions_code.get(0).get(1).getLeftLocalId()); // compares always from right to left
// assertEquals(new Integer(4), connectionsOfAllVersions_code.get(0).get(1).getRightLocalId());
//
// assertEquals(2, connectionsOfAllVersions_code.get(2).get(1).getPostBlockTypeId());
// assertEquals(new Integer(4),connectionsOfAllVersions_code.get(2).get(1).getLeftLocalId());
// assertEquals(new Integer(4),connectionsOfAllVersions_code.get(2).get(1).getRightLocalId());
// }
//
// @Test
// void testNumberOfPredecessorsComputedMetric() {
//
// PostVersionsListManagement postVersionsListManagement = new PostVersionsListManagement(pathToCSVs);
//
// for (PostVersionList postVersionList : postVersionsListManagement.postVersionLists) {
// postVersionList.processVersionHistory(Config.DEFAULT.withTextSimilarityMetric(de.unitrier.st.stringsimilarity.set.Variants::twoGramDice));
//
// for (PostVersion postVersion : postVersionList) {
// List<PostBlockVersion> postBlocks = postVersion.getPostBlocks();
//
// for (int i = 0; i < postBlocks.size(); i++) {
// if (postBlocks.get(i).getPred() == null)
// continue;
//
// for (int j = i + 1; j < postBlocks.size(); j++) {
// if (postBlocks.get(j).getPred() == null || postBlocks.get(i) instanceof TextBlockVersion != postBlocks.get(j) instanceof TextBlockVersion)
// continue;
//
// assertNotEquals(postBlocks.get(i).getPred().getLocalId(), postBlocks.get(j).getPred().getLocalId());
// }
// }
//
// }
// }
// }
//
// @Test
// void testNumberOfPredecessorsGroundTruth() {
//
// GroundTruthExtractionOfCSVs groundTruthExtractionOfCSVs = new GroundTruthExtractionOfCSVs(Paths.get("testdata","Samples_test", "representative CSVs").toString());
//
// for (ConnectionsOfAllVersions connectionsOfAllVersions : groundTruthExtractionOfCSVs.getPostGroundTruth()) {
// for (ConnectionsOfTwoVersions connectionsOfTwoVersions : connectionsOfAllVersions) {
//
// for (int i = 0; i < connectionsOfTwoVersions.size(); i++) {
// if (connectionsOfTwoVersions.get(i).getLeftLocalId() == null)
// continue;
//
// for (int j = i + 1; j < connectionsOfTwoVersions.size(); j++) {
// if (connectionsOfTwoVersions.get(j).getLeftLocalId() == null ||
// connectionsOfTwoVersions.get(i).getPostBlockTypeId() != connectionsOfTwoVersions.get(j).getPostBlockTypeId())
// continue;
//
// assertNotEquals(connectionsOfTwoVersions.get(i).getLeftLocalId(), connectionsOfTwoVersions.get(j).getLeftLocalId());
// }
// }
//
// }
// }
// }
//
// @Test
// void checkWhetherPostVersionListConnectionsWillBeResetRight() {
// int postId = 3758880;
// //TextBlockVersion.similarityMetric = de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTokenDiceVariant;
//
// PostVersionsListManagement postVersionsListManagement = new PostVersionsListManagement(pathToCSVs);
// postVersionsListManagement.getPostVersionListWithID(postId).processVersionHistory(PostVersionList.PostBlockTypeFilter.TEXT);
//
//
// // This sets predecessors
// ConnectionsOfAllVersions connectionsOfAllVersionsComputedMetric_text = postVersionsListManagement.getAllConnectionsOfAllConsecutiveVersions_text(postId);
//
// // This resets the predecessors again
// postVersionsListManagement = new PostVersionsListManagement(pathToCSVs);
// connectionsOfAllVersionsComputedMetric_text = postVersionsListManagement.getAllConnectionsOfAllConsecutiveVersions_text(postId);
// for (ConnectionsOfTwoVersions connections : connectionsOfAllVersionsComputedMetric_text) {
// for (ConnectedBlocks connection : connections) {
// assertNull(connection.getLeftLocalId());
// assertNotNull(connection.getRightLocalId());
// }
// }
// }
}
| src/de/unitrier/st/soposthistory/tests/BlockLifeSpanAndGroundTruthTest.java | package de.unitrier.st.soposthistory.tests;
import com.google.common.collect.Sets;
import de.unitrier.st.soposthistory.blocks.CodeBlockVersion;
import de.unitrier.st.soposthistory.blocks.PostBlockVersion;
import de.unitrier.st.soposthistory.blocks.TextBlockVersion;
import de.unitrier.st.soposthistory.gt.*;
import de.unitrier.st.soposthistory.version.PostVersion;
import de.unitrier.st.soposthistory.version.PostVersionList;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.junit.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.*;
class BlockLifeSpanAndGroundTruthTest {
private static Path pathToPostIdList = Paths.get("testdata", "postIds.csv");
private static Path pathToPostHistory = Paths.get("testdata");
private static Path pathToGroundTruth = Paths.get("testdata", "gt");
private static Path outputDir = Paths.get("testdata", "metrics comparison");
@Test
void testReadFromDirectory() {
List<PostGroundTruth> postGroundTruthList = PostGroundTruth.readFromDirectory(pathToGroundTruth);
try {
assertEquals(Files.list(pathToGroundTruth).filter(
file -> PostGroundTruth.fileNamePattern.matcher(file.toFile().getName()).matches())
.count(),
postGroundTruthList.size());
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
void testPostBlockLifeSpanVersionsEqual(){
// compare two PostBlockLifeSpanVersions
PostBlockLifeSpanVersion original = new PostBlockLifeSpanVersion(4711, 42, 1, 0, 0, 0, "");
PostBlockLifeSpanVersion differentPostId = new PostBlockLifeSpanVersion(4712, 42, 1, 0, 0, 0, "");
PostBlockLifeSpanVersion differentPostHistoryId = new PostBlockLifeSpanVersion(4711, 43, 1, 0, 0, 0, "");
PostBlockLifeSpanVersion differentPostBlockTypeId = new PostBlockLifeSpanVersion(4711, 42, 2, 0, 0, 0, "");
PostBlockLifeSpanVersion differentLocalId = new PostBlockLifeSpanVersion(4711, 42, 1, 1, 0, 0, "");
PostBlockLifeSpanVersion differentPredId = new PostBlockLifeSpanVersion(4711, 42, 1, 0, 1, 0,"");
PostBlockLifeSpanVersion differentSuccId = new PostBlockLifeSpanVersion(4711, 42, 1, 0, 0, 1, "");
assertTrue(original.equals(original));
assertFalse(original.equals(differentPostId));
assertFalse(original.equals(differentPostHistoryId));
assertFalse(original.equals(differentPostBlockTypeId));
assertFalse(original.equals(differentLocalId));
assertTrue(original.equals(differentPredId));
assertTrue(original.equals(differentSuccId));
}
@Test
void testPostBlockLifeSpanExtraction() {
int postId = 22037280;
PostVersionList a_22037280 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2);
PostGroundTruth a_22037280_gt = PostGroundTruth.readFromCSV(pathToGroundTruth, postId);
List<PostBlockLifeSpan> lifeSpans = a_22037280.getPostBlockLifeSpans();
List<PostBlockLifeSpan> lifeSpansGT = a_22037280_gt.getPostBlockLifeSpans();
assertEquals(lifeSpans.size(), lifeSpansGT.size());
assertEquals(5, lifeSpans.size());
for (int i=0; i<lifeSpans.size(); i++) {
assertTrue(lifeSpans.get(i).equals(lifeSpansGT.get(i)));
}
}
@Test
void testPostBlockLifeSpanExtractionFilter() {
int postId = 22037280;
PostVersionList a_22037280 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2);
PostGroundTruth a_22037280_gt = PostGroundTruth.readFromCSV(pathToGroundTruth, postId);
// text
List<PostBlockLifeSpan> textBlockLifeSpans = a_22037280.getPostBlockLifeSpans(
TextBlockVersion.getPostBlockTypeIdFilter()
);
List<PostBlockLifeSpan> textLifeSpansGT = a_22037280_gt.getPostBlockLifeSpans(
TextBlockVersion.getPostBlockTypeIdFilter()
);
assertEquals(textBlockLifeSpans.size(), textLifeSpansGT.size());
assertEquals(3, textBlockLifeSpans.size());
for (int i=0; i<textBlockLifeSpans.size(); i++) {
assertTrue(textBlockLifeSpans.get(i).equals(textLifeSpansGT.get(i)));
}
// code
List<PostBlockLifeSpan> codeBlockLifeSpans = a_22037280.getPostBlockLifeSpans(
CodeBlockVersion.getPostBlockTypeIdFilter()
);
List<PostBlockLifeSpan> codeLifeSpansGT = a_22037280_gt.getPostBlockLifeSpans(
CodeBlockVersion.getPostBlockTypeIdFilter()
);
assertEquals(codeBlockLifeSpans.size(), codeLifeSpansGT.size());
assertEquals(2, codeBlockLifeSpans.size());
for (int i=0; i<codeBlockLifeSpans.size(); i++) {
assertTrue(codeBlockLifeSpans.get(i).equals(codeLifeSpansGT.get(i)));
}
}
@Test
void testPostBlockConnectionExtraction() {
int postId = 22037280;
PostVersionList a_22037280 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2);
PostGroundTruth a_22037280_gt = PostGroundTruth.readFromCSV(pathToGroundTruth, postId);
List<PostBlockLifeSpan> lifeSpans = a_22037280.getPostBlockLifeSpans();
List<PostBlockLifeSpan> lifeSpansGT = a_22037280_gt.getPostBlockLifeSpans();
Set<PostBlockConnection> connections = PostBlockLifeSpan.toPostBlockConnections(lifeSpans);
Set<PostBlockConnection> connectionsGT = PostBlockLifeSpan.toPostBlockConnections(lifeSpansGT);
assertEquals(connections.size(), connectionsGT.size());
assertTrue(PostBlockConnection.equals(connections, connectionsGT));
assertTrue(PostBlockConnection.equals(
PostBlockConnection.intersection(connections, connectionsGT),
connections)
);
assertTrue(PostBlockConnection.equals(
PostBlockConnection.union(connections, connectionsGT),
connections)
);
assertEquals(0, PostBlockConnection.difference(connections, connectionsGT).size());
}
@Test
void testPostBlockPossibleConnectionsComparison() {
int postId = 22037280;
PostVersionList a_22037280 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2);
PostGroundTruth a_22037280_gt = PostGroundTruth.readFromCSV(pathToGroundTruth, postId);
assertEquals(78, a_22037280.getPossibleConnections());
assertEquals(a_22037280.getPossibleConnections(), a_22037280_gt.getPossibleConnections());
}
@Test
void testPostBlockConnectionEquals() {
PostBlockLifeSpanVersion v1_1 = new PostBlockLifeSpanVersion(1, 1, 1, 1);
PostBlockLifeSpanVersion v1_2 = new PostBlockLifeSpanVersion(1, 1, 1, 1);
PostBlockLifeSpanVersion v2 = new PostBlockLifeSpanVersion(1, 2, 1, 1);
PostBlockLifeSpanVersion v3 = new PostBlockLifeSpanVersion(1, 3, 1, 1);
PostBlockLifeSpanVersion v4 = new PostBlockLifeSpanVersion(1, 4, 1, 1);
// test equality of PostBlockLifeSpanVersions
assertEquals(v1_1.getPostId(), v1_2.getPostId());
assertEquals(v1_1.getPostHistoryId(), v1_2.getPostHistoryId());
assertEquals(v1_1.getPostBlockTypeId(), v1_2.getPostBlockTypeId());
assertEquals(v1_1.getLocalId(), v1_2.getLocalId());
// test equality of PostBlockConnections
PostBlockConnection connection1 = new PostBlockConnection(v1_1, v2);
PostBlockConnection connection2 = new PostBlockConnection(v1_2, v2);
assertTrue(connection1.equals(connection2));
// test equaliy of a set of PostBlockConnections
PostBlockConnection connection3 = new PostBlockConnection(v1_2, v2);
PostBlockConnection connection4 = new PostBlockConnection(v3, v4);
assertTrue(PostBlockConnection.equals(
Sets.newHashSet(connection1, connection2, connection3, connection4),
Sets.newHashSet(connection1, connection2, connection3, connection4))
);
}
@Test
void testGetConnections(){
int postId = 22037280;
PostVersionList a_22037280 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2);
PostGroundTruth a_22037280_gt = PostGroundTruth.readFromCSV(pathToGroundTruth, postId);
List<Integer> postVersionListPostHistoryIds = a_22037280.getPostHistoryIds();
List<Integer> groundTruthPostHistoryIds = a_22037280_gt.getPostHistoryIds();
assertEquals(postVersionListPostHistoryIds, groundTruthPostHistoryIds);
for (Integer postHistoryId : groundTruthPostHistoryIds) {
Set<PostBlockConnection> postBlockConnections = a_22037280.getPostVersion(postHistoryId).getConnections();
Set<PostBlockConnection> postBlockConnectionsGT = a_22037280_gt.getConnections(postHistoryId);
assertTrue(PostBlockConnection.equals(postBlockConnections, postBlockConnectionsGT));
}
}
@Test
void testProcessVersionHistoryWithIntermediateResetting() {
int postId = 22037280;
PostVersionList a_22037280 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2, false);
testPostBlockVersionHistoryReset(a_22037280);
a_22037280.processVersionHistory();
testPostBlockVersionHistoryProcessed(a_22037280);
a_22037280.resetPostBlockVersionHistory();
testPostBlockVersionHistoryReset(a_22037280);
a_22037280.processVersionHistory();
testPostBlockVersionHistoryProcessed(a_22037280);
}
private void testPostBlockVersionHistoryReset(PostVersionList postVersionList) {
for (PostVersion currentPostVersion : postVersionList) {
for (PostBlockVersion currentPostBlockVersion : currentPostVersion.getPostBlocks()) {
assertNull(currentPostBlockVersion.getRootPostBlockId());
assertNull(currentPostBlockVersion.getPredPostBlockId());
assertNull(currentPostBlockVersion.getPredEqual());
assertNull(currentPostBlockVersion.getPredSimilarity());
assertEquals(0, currentPostBlockVersion.getPredCount());
assertEquals(0, currentPostBlockVersion.getSuccCount());
assertNull(currentPostBlockVersion.getPred());
assertNull(currentPostBlockVersion.getSucc());
assertNull(currentPostBlockVersion.getRootPostBlock());
assertNull(currentPostBlockVersion.getPredDiff());
assertTrue(currentPostBlockVersion.isAvailable());
assertEquals(0, currentPostBlockVersion.getMatchingPredecessors().size());
assertEquals(0, currentPostBlockVersion.getPredecessorSimilarities().size());
assertEquals(-1.0, currentPostBlockVersion.getMaxSimilarity());
assertEquals(-1.0, currentPostBlockVersion.getSimilarityThreshold());
assertFalse(currentPostBlockVersion.isLifeSpanExtracted());
}
}
}
private void testPostBlockVersionHistoryProcessed(PostVersionList postVersionList) {
for (PostVersion currentPostVersion : postVersionList) {
for (PostBlockVersion currentPostBlockVersion : currentPostVersion.getPostBlocks()) {
assertNotNull(currentPostBlockVersion.getRootPostBlockId());
assertNotNull(currentPostBlockVersion.getRootPostBlock());
}
}
}
@Test
void testMetricComparisonManager() {
MetricComparisonManager manager = MetricComparisonManager.create(
"TestManager", pathToPostIdList, pathToPostHistory, pathToGroundTruth, false
);
assertEquals(manager.getPostVersionLists().size(), manager.getPostGroundTruth().size());
assertThat(manager.getPostVersionLists().keySet(), is(manager.getPostGroundTruth().keySet()));
manager.addSimilarityMetric(
"fourGramOverlap",
de.unitrier.st.stringsimilarity.set.Variants::fourGramOverlap
);
manager.addSimilarityThreshold(0.6);
manager.compareMetrics();
List<Integer> postHistoryIds_3758880 = manager.getPostGroundTruth().get(3758880).getPostHistoryIds();
MetricComparison comparison_a_3758880 = manager.getMetricComparison(3758880, "fourGramOverlap", 0.6);
int version_2_id = postHistoryIds_3758880.get(1);
assertEquals(new Integer(1), comparison_a_3758880.getTruePositivesText().get(version_2_id));
assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesText().get(version_2_id));
assertEquals(new Integer(5), comparison_a_3758880.getTrueNegativesText().get(version_2_id));
assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesText().get(version_2_id));
assertEquals(new Integer(2), comparison_a_3758880.getTruePositivesCode().get(version_2_id));
assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesCode().get(version_2_id));
assertEquals(new Integer(4), comparison_a_3758880.getTrueNegativesCode().get(version_2_id));
assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesCode().get(version_2_id));
List<Integer> postHistoryIds_22037280 = manager.getPostGroundTruth().get(22037280).getPostHistoryIds();
MetricComparison comparison_a_22037280 = manager.getMetricComparison(22037280, "fourGramOverlap", 0.6);
version_2_id = postHistoryIds_22037280.get(1);
assertEquals(new Integer(3), comparison_a_22037280.getTruePositivesText().get(version_2_id));
assertEquals(new Integer(0), comparison_a_22037280.getFalsePositivesText().get(version_2_id));
assertEquals(new Integer(6), comparison_a_22037280.getTrueNegativesText().get(version_2_id));
assertEquals(new Integer(0), comparison_a_22037280.getFalseNegativesText().get(version_2_id));
assertEquals(new Integer(2), comparison_a_22037280.getTruePositivesCode().get(version_2_id));
assertEquals(new Integer(0), comparison_a_22037280.getFalsePositivesCode().get(version_2_id));
assertEquals(new Integer(2), comparison_a_22037280.getTrueNegativesCode().get(version_2_id));
assertEquals(new Integer(0), comparison_a_22037280.getFalseNegativesCode().get(version_2_id));
manager.writeToCSV(outputDir);
}
@Test
void testGetPossibleConnections() {
int postId = 22037280;
PostVersionList a_22037280 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2);
PostGroundTruth a_22037280_gt = PostGroundTruth.readFromCSV(pathToGroundTruth, postId);
assertEquals(7, a_22037280.size());
assertEquals(a_22037280.getPossibleConnections(), a_22037280_gt.getPossibleConnections());
for (PostVersion postVersion : a_22037280) {
assertEquals(3, postVersion.getTextBlocks().size());
assertEquals(2, postVersion.getCodeBlocks().size());
}
Set<Integer> set = new HashSet<>();
assertEquals(0, a_22037280.getPossibleConnections(set));
int possibleTextConnections = a_22037280.getPossibleConnections(TextBlockVersion.getPostBlockTypeIdFilter());
assertEquals(6 * 9, possibleTextConnections); // 6 versions with each 9=3*3 possible text connections
int possibleCodeConnections = a_22037280.getPossibleConnections(CodeBlockVersion.getPostBlockTypeIdFilter());
assertEquals(6 * 4, possibleCodeConnections); // 6 versions with each 4=2*2 possible code connections
int possibleConnections = a_22037280.getPossibleConnections(PostBlockVersion.getAllPostBlockTypeIdFilters());
assertEquals(6 * 4 + 6 * 9, possibleConnections); // 6 versions with each 4=2*2 and 9=3*3 possible connections
// compare results of getPossibleConnections() for PostVersion and PostVersionList
possibleConnections = 0;
for (PostVersion current : a_22037280) {
possibleConnections += current.getPossibleConnections();
}
assertEquals(a_22037280.getPossibleConnections(), possibleConnections);
// check if post version pred and succ assignments are also set in case post history has not been processed yet
possibleConnections = 0;
for (PostVersion current : a_22037280) {
possibleConnections += current.getPossibleConnections();
}
assertEquals(a_22037280.getPossibleConnections(), possibleConnections);
}
// @Test
// void testNumberOfPredecessorsOfOnePost() {
// int postId = 3758880;
// PostVersionList a_3758880 = PostVersionList.readFromCSV(pathToPostHistory, postId, 2, false);
// PostGroundTruth a_3758880_gt = PostGroundTruth.readFromCSV(pathToGroundTruth, postId);
//
// postVersionsListManagement.getPostVersionListWithID(postId).processVersionHistory(
// PostVersionList.PostBlockTypeFilter.TEXT,
// Config.DEFAULT.withTextSimilarityMetric(de.unitrier.st.stringsimilarity.set.Variants::twoGramDice));
//
// List<TextBlockVersion> textBlocks = postVersionsListManagement.getPostVersionListWithID(postId).get(postVersionsListManagement.getPostVersionListWithID(postId).size() - 1).getTextBlocks();
// assertEquals(new Integer(1), textBlocks.get(0).getPred().getLocalId());
// assertEquals(new Integer(1), textBlocks.get(0).getLocalId());
//
// assertEquals(new Integer(3), textBlocks.get(1).getPred().getLocalId());
// assertEquals(new Integer(3), textBlocks.get(1).getLocalId());
//
// assertEquals(null, textBlocks.get(2).getPred());
// assertEquals(new Integer(5), textBlocks.get(2).getLocalId());
// }
// @Test
// void testGroundTruthExtractionOfCSV(){
//
// // testing text
// assertNull(groundTruthExtractionOfCSVs.getAllConnectionsOfAllConsecutiveVersions_text(4711)); // post with id 4711 is not listed in ground truth
// assertEquals(2, groundTruthExtractionOfCSVs.getGroundTruthText().size());
//
// ConnectionsOfAllVersions connectionsOfAllVersions_text = groundTruthExtractionOfCSVs.getGroundTruthText().getFirst();
// assertEquals(connectionsOfAllVersions_text, groundTruthExtractionOfCSVs.getAllConnectionsOfAllConsecutiveVersions_text(3758880));
// assertEquals(10, connectionsOfAllVersions_text.size()); // post version list has 11 versions and therefore 10 comparisons for adjacent versions
//
// assertEquals(new Integer(1), connectionsOfAllVersions_text.get(0).get(0).getLeftLocalId());
// assertEquals(new Integer(1), connectionsOfAllVersions_text.get(0).get(0).getRightLocalId());
// assertEquals(1, connectionsOfAllVersions_text.get(0).get(0).getPostBlockTypeId());
// assertNull(connectionsOfAllVersions_text.get(0).get(1).getLeftLocalId());
// assertEquals(new Integer(3),connectionsOfAllVersions_text.get(0).get(1).getRightLocalId());
//
// assertEquals(new Integer(3), connectionsOfAllVersions_text.get(7).get(1).getLeftLocalId());
// assertEquals(new Integer(3), connectionsOfAllVersions_text.get(7).get(1).getRightLocalId());
//
//
// // testing code
// ConnectionsOfAllVersions connectionsOfAllVersions_code = groundTruthExtractionOfCSVs.getGroundTruthCode().getFirst();
// assertEquals(10, connectionsOfAllVersions_code.size()); // post version list has 11 versions and therefore 10 comparisons for adjacent versions
//
// assertEquals(new Integer(6), connectionsOfAllVersions_code.get(0).get(1).getLeftLocalId()); // compares always from right to left
// assertEquals(new Integer(4), connectionsOfAllVersions_code.get(0).get(1).getRightLocalId());
//
// assertEquals(2, connectionsOfAllVersions_code.get(2).get(1).getPostBlockTypeId());
// assertEquals(new Integer(4),connectionsOfAllVersions_code.get(2).get(1).getLeftLocalId());
// assertEquals(new Integer(4),connectionsOfAllVersions_code.get(2).get(1).getRightLocalId());
// }
//
// @Test
// void testNumberOfPredecessorsComputedMetric() {
//
// PostVersionsListManagement postVersionsListManagement = new PostVersionsListManagement(pathToCSVs);
//
// for (PostVersionList postVersionList : postVersionsListManagement.postVersionLists) {
// postVersionList.processVersionHistory(Config.DEFAULT.withTextSimilarityMetric(de.unitrier.st.stringsimilarity.set.Variants::twoGramDice));
//
// for (PostVersion postVersion : postVersionList) {
// List<PostBlockVersion> postBlocks = postVersion.getPostBlocks();
//
// for (int i = 0; i < postBlocks.size(); i++) {
// if (postBlocks.get(i).getPred() == null)
// continue;
//
// for (int j = i + 1; j < postBlocks.size(); j++) {
// if (postBlocks.get(j).getPred() == null || postBlocks.get(i) instanceof TextBlockVersion != postBlocks.get(j) instanceof TextBlockVersion)
// continue;
//
// assertNotEquals(postBlocks.get(i).getPred().getLocalId(), postBlocks.get(j).getPred().getLocalId());
// }
// }
//
// }
// }
// }
//
// @Test
// void testNumberOfPredecessorsGroundTruth() {
//
// GroundTruthExtractionOfCSVs groundTruthExtractionOfCSVs = new GroundTruthExtractionOfCSVs(Paths.get("testdata","Samples_test", "representative CSVs").toString());
//
// for (ConnectionsOfAllVersions connectionsOfAllVersions : groundTruthExtractionOfCSVs.getPostGroundTruth()) {
// for (ConnectionsOfTwoVersions connectionsOfTwoVersions : connectionsOfAllVersions) {
//
// for (int i = 0; i < connectionsOfTwoVersions.size(); i++) {
// if (connectionsOfTwoVersions.get(i).getLeftLocalId() == null)
// continue;
//
// for (int j = i + 1; j < connectionsOfTwoVersions.size(); j++) {
// if (connectionsOfTwoVersions.get(j).getLeftLocalId() == null ||
// connectionsOfTwoVersions.get(i).getPostBlockTypeId() != connectionsOfTwoVersions.get(j).getPostBlockTypeId())
// continue;
//
// assertNotEquals(connectionsOfTwoVersions.get(i).getLeftLocalId(), connectionsOfTwoVersions.get(j).getLeftLocalId());
// }
// }
//
// }
// }
// }
//
// @Test
// void checkWhetherPostVersionListConnectionsWillBeResetRight() {
// int postId = 3758880;
// //TextBlockVersion.similarityMetric = de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTokenDiceVariant;
//
// PostVersionsListManagement postVersionsListManagement = new PostVersionsListManagement(pathToCSVs);
// postVersionsListManagement.getPostVersionListWithID(postId).processVersionHistory(PostVersionList.PostBlockTypeFilter.TEXT);
//
//
// // This sets predecessors
// ConnectionsOfAllVersions connectionsOfAllVersionsComputedMetric_text = postVersionsListManagement.getAllConnectionsOfAllConsecutiveVersions_text(postId);
//
// // This resets the predecessors again
// postVersionsListManagement = new PostVersionsListManagement(pathToCSVs);
// connectionsOfAllVersionsComputedMetric_text = postVersionsListManagement.getAllConnectionsOfAllConsecutiveVersions_text(postId);
// for (ConnectionsOfTwoVersions connections : connectionsOfAllVersionsComputedMetric_text) {
// for (ConnectedBlocks connection : connections) {
// assertNull(connection.getLeftLocalId());
// assertNotNull(connection.getRightLocalId());
// }
// }
// }
}
| edited test case testMetricComparisonManager:
* now all blocks of all versions of the two posts are compared
| src/de/unitrier/st/soposthistory/tests/BlockLifeSpanAndGroundTruthTest.java | edited test case testMetricComparisonManager: * now all blocks of all versions of the two posts are compared | <ide><path>rc/de/unitrier/st/soposthistory/tests/BlockLifeSpanAndGroundTruthTest.java
<ide> import de.unitrier.st.soposthistory.gt.*;
<ide> import de.unitrier.st.soposthistory.version.PostVersion;
<ide> import de.unitrier.st.soposthistory.version.PostVersionList;
<add>import org.apache.commons.csv.CSVFormat;
<add>import org.apache.commons.csv.CSVParser;
<add>import org.apache.commons.csv.CSVRecord;
<add>import org.apache.commons.csv.QuoteMode;
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> import java.io.IOException;
<add>import java.nio.charset.StandardCharsets;
<ide> import java.nio.file.Files;
<ide> import java.nio.file.Path;
<ide> import java.nio.file.Paths;
<del>import java.util.HashSet;
<del>import java.util.List;
<del>import java.util.Set;
<add>import java.util.*;
<ide>
<ide> import static org.hamcrest.Matchers.is;
<ide> import static org.hamcrest.junit.MatcherAssert.assertThat;
<ide>
<ide> List<Integer> postHistoryIds_3758880 = manager.getPostGroundTruth().get(3758880).getPostHistoryIds();
<ide> MetricComparison comparison_a_3758880 = manager.getMetricComparison(3758880, "fourGramOverlap", 0.6);
<del> int version_2_id = postHistoryIds_3758880.get(1);
<del>
<del> assertEquals(new Integer(1), comparison_a_3758880.getTruePositivesText().get(version_2_id));
<del> assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesText().get(version_2_id));
<del> assertEquals(new Integer(5), comparison_a_3758880.getTrueNegativesText().get(version_2_id));
<del> assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesText().get(version_2_id));
<del>
<del> assertEquals(new Integer(2), comparison_a_3758880.getTruePositivesCode().get(version_2_id));
<del> assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesCode().get(version_2_id));
<del> assertEquals(new Integer(4), comparison_a_3758880.getTrueNegativesCode().get(version_2_id));
<del> assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesCode().get(version_2_id));
<del>
<del>
<add>
<add>
<add> /* compare a 3758880 */
<add> // first version has never predecessors
<add> int version_1_id = postHistoryIds_3758880.get(0);
<add> assertEquals(new Integer(0), comparison_a_3758880.getTruePositivesText().get(version_1_id));
<add> assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesText().get(version_1_id));
<add> assertEquals(new Integer(0), comparison_a_3758880.getTrueNegativesText().get(version_1_id));
<add> assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesText().get(version_1_id));
<add>
<add> assertEquals(new Integer(0), comparison_a_3758880.getTruePositivesCode().get(version_1_id));
<add> assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesCode().get(version_1_id));
<add> assertEquals(new Integer(0), comparison_a_3758880.getTrueNegativesCode().get(version_1_id));
<add> assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesCode().get(version_1_id));
<add>
<add>
<add> // second version
<add> int version_id = postHistoryIds_3758880.get(1);
<add> assertEquals(new Integer(1), comparison_a_3758880.getTruePositivesText().get(version_id));
<add> assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesText().get(version_id));
<add> assertEquals(new Integer(5), comparison_a_3758880.getTrueNegativesText().get(version_id));
<add> assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesText().get(version_id));
<add>
<add> assertEquals(new Integer(2), comparison_a_3758880.getTruePositivesCode().get(version_id));
<add> assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesCode().get(version_id));
<add> assertEquals(new Integer(4), comparison_a_3758880.getTrueNegativesCode().get(version_id));
<add> assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesCode().get(version_id));
<add>
<add> // version 3 to 10 only for text blocks (they don't differ)
<add> for(int i=2; i<10; i++){
<add> int version_2_to_11_id_text = postHistoryIds_3758880.get(i);
<add> assertEquals(new Integer(2), comparison_a_3758880.getTruePositivesText().get(version_2_to_11_id_text));
<add> assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesText().get(version_2_to_11_id_text));
<add> assertEquals(new Integer(2), comparison_a_3758880.getTrueNegativesText().get(version_2_to_11_id_text));
<add> assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesText().get(version_2_to_11_id_text));
<add> }
<add>
<add> int version_11_id_text = postHistoryIds_3758880.get(10);
<add> assertEquals(new Integer(2), comparison_a_3758880.getTruePositivesText().get(version_11_id_text));
<add> assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesText().get(version_11_id_text));
<add> assertEquals(new Integer(4), comparison_a_3758880.getTrueNegativesText().get(version_11_id_text));
<add> assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesText().get(version_11_id_text));
<add>
<add> // version 3 and 6 for code
<add> List<Integer> versionsOfType1 = Arrays.asList(2,5);
<add> for (Integer version : versionsOfType1) {
<add> int version_3_or_6_id = postHistoryIds_3758880.get(version);
<add> assertEquals(new Integer(1), comparison_a_3758880.getTruePositivesCode().get(version_3_or_6_id));
<add> assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesCode().get(version_3_or_6_id));
<add> assertEquals(new Integer(2), comparison_a_3758880.getTrueNegativesCode().get(version_3_or_6_id));
<add> assertEquals(new Integer(1), comparison_a_3758880.getFalseNegativesCode().get(version_3_or_6_id));
<add> }
<add>
<add> // version 4,5,7,8,9,10,11 for code
<add> List<Integer> versionsOfType2 = Arrays.asList(3,4,6,7,8,9,10);
<add> for (Integer version : versionsOfType2) {
<add> int version_i_id = postHistoryIds_3758880.get(version);
<add> assertEquals(new Integer(2), comparison_a_3758880.getTruePositivesCode().get(version_i_id));
<add> assertEquals(new Integer(0), comparison_a_3758880.getFalsePositivesCode().get(version_i_id));
<add> assertEquals(new Integer(2), comparison_a_3758880.getTrueNegativesCode().get(version_i_id));
<add> assertEquals(new Integer(0), comparison_a_3758880.getFalseNegativesCode().get(version_i_id));
<add> }
<add>
<add>
<add>
<add> /* compare a 22037280 */
<ide> List<Integer> postHistoryIds_22037280 = manager.getPostGroundTruth().get(22037280).getPostHistoryIds();
<ide> MetricComparison comparison_a_22037280 = manager.getMetricComparison(22037280, "fourGramOverlap", 0.6);
<del> version_2_id = postHistoryIds_22037280.get(1);
<del>
<del> assertEquals(new Integer(3), comparison_a_22037280.getTruePositivesText().get(version_2_id));
<del> assertEquals(new Integer(0), comparison_a_22037280.getFalsePositivesText().get(version_2_id));
<del> assertEquals(new Integer(6), comparison_a_22037280.getTrueNegativesText().get(version_2_id));
<del> assertEquals(new Integer(0), comparison_a_22037280.getFalseNegativesText().get(version_2_id));
<del>
<del> assertEquals(new Integer(2), comparison_a_22037280.getTruePositivesCode().get(version_2_id));
<del> assertEquals(new Integer(0), comparison_a_22037280.getFalsePositivesCode().get(version_2_id));
<del> assertEquals(new Integer(2), comparison_a_22037280.getTrueNegativesCode().get(version_2_id));
<del> assertEquals(new Integer(0), comparison_a_22037280.getFalseNegativesCode().get(version_2_id));
<add>
<add> version_1_id = postHistoryIds_22037280.get(0);
<add>
<add> assertEquals(new Integer(0), comparison_a_22037280.getTruePositivesText().get(version_1_id));
<add> assertEquals(new Integer(0), comparison_a_22037280.getFalsePositivesText().get(version_1_id));
<add> assertEquals(new Integer(0), comparison_a_22037280.getTrueNegativesText().get(version_1_id));
<add> assertEquals(new Integer(0), comparison_a_22037280.getFalseNegativesText().get(version_1_id));
<add>
<add> assertEquals(new Integer(0), comparison_a_22037280.getTruePositivesCode().get(version_1_id));
<add> assertEquals(new Integer(0), comparison_a_22037280.getFalsePositivesCode().get(version_1_id));
<add> assertEquals(new Integer(0), comparison_a_22037280.getTrueNegativesCode().get(version_1_id));
<add> assertEquals(new Integer(0), comparison_a_22037280.getFalseNegativesCode().get(version_1_id));
<add>
<add> for(int i=1; i<postHistoryIds_22037280.size(); i++) {
<add> version_id = postHistoryIds_22037280.get(i);
<add>
<add> assertEquals(new Integer(3), comparison_a_22037280.getTruePositivesText().get(version_id));
<add> assertEquals(new Integer(0), comparison_a_22037280.getFalsePositivesText().get(version_id));
<add> assertEquals(new Integer(6), comparison_a_22037280.getTrueNegativesText().get(version_id));
<add> assertEquals(new Integer(0), comparison_a_22037280.getFalseNegativesText().get(version_id));
<add>
<add> assertEquals(new Integer(2), comparison_a_22037280.getTruePositivesCode().get(version_id));
<add> assertEquals(new Integer(0), comparison_a_22037280.getFalsePositivesCode().get(version_id));
<add> assertEquals(new Integer(2), comparison_a_22037280.getTrueNegativesCode().get(version_id));
<add> assertEquals(new Integer(0), comparison_a_22037280.getFalseNegativesCode().get(version_id));
<add> }
<ide>
<ide> manager.writeToCSV(outputDir);
<add> }
<add>
<add> @Test
<add> void testCompareMetricComparisonManagerWithComparisonFromOldProject() {
<add> MetricComparisonManager manager = MetricComparisonManager.create(
<add> "TestManager", pathToPostIdList, pathToPostHistory, pathToGroundTruth, true
<add> );
<add>
<add> List<Integer> postHistoryIds_3758880 = new LinkedList<>();
<add> postHistoryIds_3758880.add(7873162);
<add> postHistoryIds_3758880.add(7873319);
<add> postHistoryIds_3758880.add(7873489);
<add> postHistoryIds_3758880.add(7873581);
<add> postHistoryIds_3758880.add(7874248);
<add> postHistoryIds_3758880.add(7874570);
<add> postHistoryIds_3758880.add(7874704);
<add> postHistoryIds_3758880.add(7875126);
<add> postHistoryIds_3758880.add(15577610);
<add> postHistoryIds_3758880.add(24534909);
<add> postHistoryIds_3758880.add(130380462);
<add>
<add>// List<Integer> postHistoryIds_22037280 = manager.getPostVersionLists().get(1).getPostHistoryIds();
<add>
<add> assertEquals(manager.getPostVersionLists().size(), manager.getPostGroundTruth().size());
<add> assertThat(manager.getPostVersionLists().keySet(), is(manager.getPostGroundTruth().keySet()));
<add>
<add> manager.compareMetrics();
<add> manager.writeToCSV(Paths.get("aaa"));
<add>
<add> CSVParser csvParser = null;
<add>
<add> try {
<add> csvParser = CSVParser.parse(
<add> Paths.get("testdata", "metrics comparison", "resultsMetricComparisonOldProject.csv").toFile(),
<add> StandardCharsets.UTF_8,
<add> CSVFormat.DEFAULT.withHeader("sample", "metric", "threshold", "postid", "posthistoryid", "runtimetext", "#truepositivestext", "#truenegativestext",
<add> "#falsepositivestext", "#falsenegativestext", "#runtimecode", "#truepositivescode", "#truenegativescode",
<add> "#falsepositivescode", "#falsenegativescode").withDelimiter(';')
<add> .withQuote('"')
<add> .withQuoteMode(QuoteMode.MINIMAL)
<add> .withEscape('\\')
<add> .withFirstRecordAsHeader()
<add> );
<add>
<add> csvParser.getHeaderMap();
<add> List<CSVRecord> records = csvParser.getRecords();
<add> for(CSVRecord record : records){
<add> String metric = record.get("metric");
<add> Double threshold = Double.valueOf(record.get("threshold"));
<add> Integer postId = Integer.valueOf(record.get("postid"));
<add>
<add> Integer postHistoryId = null;
<add>
<add> Integer truePositivesText = null;
<add> Integer trueNegativesText = null;
<add> Integer falsePositivesText = null;
<add> Integer falseNegativesText = null;
<add>
<add> Integer truePositivesCode = null;
<add> Integer trueNegativesCode = null;
<add> Integer falsePositivesCode = null;
<add> Integer falseNegativesCode = null;
<add>
<add> try{
<add> postHistoryId = Integer.valueOf(record.get("posthistoryid"));
<add>
<add> truePositivesText = Integer.valueOf(record.get("#truepositivestext"));
<add> trueNegativesText = Integer.valueOf(record.get("#truenegativestext"));
<add> falsePositivesText = Integer.valueOf(record.get("#falsepositivestext"));
<add> falseNegativesText = Integer.valueOf(record.get("#falsenegativestext"));
<add>
<add> truePositivesCode = Integer.valueOf(record.get("#truepositivescode"));
<add> trueNegativesCode = Integer.valueOf(record.get("#truenegativescode"));
<add> falsePositivesCode = Integer.valueOf(record.get("#falsepositivescode"));
<add> falseNegativesCode = Integer.valueOf(record.get("#falsenegativescode"));
<add> }catch (NumberFormatException e){}
<add>
<add> MetricComparison tmpMetricComparison = manager.getMetricComparison(postId, metric, threshold);
<add>
<add> if(postHistoryId != null) {
<add> int tmpPostHistoryId = -1;
<add> if (postId == 3758880) {
<add> for (int i = 0; i < postHistoryIds_3758880.size(); i++) {
<add> if (Objects.equals(postHistoryIds_3758880.get(i), postHistoryId)) {
<add> tmpPostHistoryId = postHistoryIds_3758880.get(i + 1);
<add> }
<add> }
<add> assertEquals(tmpMetricComparison.getTruePositivesText().get(tmpPostHistoryId), truePositivesText);
<add> }
<add> }
<add> }
<add>
<add>
<add>
<add> } catch (IOException e) {
<add> e.printStackTrace();
<add> }
<ide> }
<ide>
<ide> @Test |
|
Java | apache-2.0 | 124ea5eee327643fd23104915d9844a3c9365366 | 0 | HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.master;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableName;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.hadoop.hbase.quotas.QuotaObserverChore;
import org.apache.hadoop.hbase.quotas.SpaceQuotaSnapshot;
import org.apache.hadoop.hbase.zookeeper.ZKWatcher;
/**
* Impl for exposing HMaster Information through JMX
*/
@InterfaceAudience.Private
public class MetricsMasterWrapperImpl implements MetricsMasterWrapper {
private final HMaster master;
public MetricsMasterWrapperImpl(final HMaster master) {
this.master = master;
}
@Override
public double getAverageLoad() {
return master.getAverageLoad();
}
@Override
public long getSplitPlanCount() {
if (master.getRegionNormalizerManager() == null) {
return 0;
}
return master.getRegionNormalizerManager().getSplitPlanCount();
}
@Override
public long getMergePlanCount() {
if (master.getRegionNormalizerManager() == null) {
return 0;
}
return master.getRegionNormalizerManager().getMergePlanCount();
}
@Override
public long getMasterInitializationTime() {
return master.getMasterFinishedInitializationTime();
}
@Override
public String getClusterId() {
return master.getClusterId();
}
@Override
public String getZookeeperQuorum() {
ZKWatcher zk = master.getZooKeeper();
if (zk == null) {
return "";
}
return zk.getQuorum();
}
@Override
public String[] getCoprocessors() {
return master.getMasterCoprocessors();
}
@Override
public long getStartTime() {
return master.getMasterStartTime();
}
@Override
public long getActiveTime() {
return master.getMasterActiveTime();
}
@Override
public String getRegionServers() {
ServerManager serverManager = this.master.getServerManager();
if (serverManager == null) {
return "";
}
return StringUtils.join(serverManager.getOnlineServers().keySet(), ";");
}
@Override
public int getNumRegionServers() {
ServerManager serverManager = this.master.getServerManager();
if (serverManager == null) {
return 0;
}
return serverManager.getOnlineServers().size();
}
@Override
public String getDeadRegionServers() {
ServerManager serverManager = this.master.getServerManager();
if (serverManager == null) {
return "";
}
return StringUtils.join(serverManager.getDeadServers().copyServerNames(), ";");
}
@Override
public int getNumDeadRegionServers() {
ServerManager serverManager = this.master.getServerManager();
if (serverManager == null) {
return 0;
}
return serverManager.getDeadServers().size();
}
@Override public boolean isRunning() {
return !(master.isStopped() || master.isStopping());
}
@Override
public String getDrainingRegionServers() {
ServerManager serverManager = this.master.getServerManager();
if (serverManager == null) {
return "";
}
return StringUtils.join(serverManager.getDrainingServersList() , ";");
}
@Override
public int getNumDrainingRegionServers() {
ServerManager serverManager = this.master.getServerManager();
if (serverManager == null) {
return 0;
}
return serverManager.getDrainingServersList().size();
}
@Override
public String getServerName() {
ServerName serverName = master.getServerName();
if (serverName == null) {
return "";
}
return serverName.getServerName();
}
@Override
public boolean getIsActiveMaster() {
return master.isActiveMaster();
}
@Override
public long getNumWALFiles() {
return master.getNumWALFiles();
}
@Override
public Map<String,Entry<Long,Long>> getTableSpaceUtilization() {
if (master == null) {
return Collections.emptyMap();
}
QuotaObserverChore quotaChore = master.getQuotaObserverChore();
if (quotaChore == null) {
return Collections.emptyMap();
}
Map<TableName,SpaceQuotaSnapshot> tableSnapshots = quotaChore.getTableQuotaSnapshots();
Map<String,Entry<Long,Long>> convertedData = new HashMap<>();
for (Entry<TableName,SpaceQuotaSnapshot> entry : tableSnapshots.entrySet()) {
convertedData.put(entry.getKey().toString(), convertSnapshot(entry.getValue()));
}
return convertedData;
}
@Override
public Map<String,Entry<Long,Long>> getNamespaceSpaceUtilization() {
QuotaObserverChore quotaChore = master.getQuotaObserverChore();
if (quotaChore == null) {
return Collections.emptyMap();
}
Map<String,SpaceQuotaSnapshot> namespaceSnapshots = quotaChore.getNamespaceQuotaSnapshots();
Map<String,Entry<Long,Long>> convertedData = new HashMap<>();
for (Entry<String,SpaceQuotaSnapshot> entry : namespaceSnapshots.entrySet()) {
convertedData.put(entry.getKey(), convertSnapshot(entry.getValue()));
}
return convertedData;
}
Entry<Long,Long> convertSnapshot(SpaceQuotaSnapshot snapshot) {
return new SimpleImmutableEntry<Long,Long>(snapshot.getUsage(), snapshot.getLimit());
}
}
| hbase-server/src/main/java/org/apache/hadoop/hbase/master/MetricsMasterWrapperImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.master;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableName;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.hadoop.hbase.quotas.QuotaObserverChore;
import org.apache.hadoop.hbase.quotas.SpaceQuotaSnapshot;
import org.apache.hadoop.hbase.zookeeper.ZKWatcher;
/**
* Impl for exposing HMaster Information through JMX
*/
@InterfaceAudience.Private
public class MetricsMasterWrapperImpl implements MetricsMasterWrapper {
private final HMaster master;
public MetricsMasterWrapperImpl(final HMaster master) {
this.master = master;
}
@Override
public double getAverageLoad() {
return master.getAverageLoad();
}
@Override
public long getSplitPlanCount() {
return master.getRegionNormalizerManager().getSplitPlanCount();
}
@Override
public long getMergePlanCount() {
return master.getRegionNormalizerManager().getMergePlanCount();
}
@Override
public long getMasterInitializationTime() {
return master.getMasterFinishedInitializationTime();
}
@Override
public String getClusterId() {
return master.getClusterId();
}
@Override
public String getZookeeperQuorum() {
ZKWatcher zk = master.getZooKeeper();
if (zk == null) {
return "";
}
return zk.getQuorum();
}
@Override
public String[] getCoprocessors() {
return master.getMasterCoprocessors();
}
@Override
public long getStartTime() {
return master.getMasterStartTime();
}
@Override
public long getActiveTime() {
return master.getMasterActiveTime();
}
@Override
public String getRegionServers() {
ServerManager serverManager = this.master.getServerManager();
if (serverManager == null) {
return "";
}
return StringUtils.join(serverManager.getOnlineServers().keySet(), ";");
}
@Override
public int getNumRegionServers() {
ServerManager serverManager = this.master.getServerManager();
if (serverManager == null) {
return 0;
}
return serverManager.getOnlineServers().size();
}
@Override
public String getDeadRegionServers() {
ServerManager serverManager = this.master.getServerManager();
if (serverManager == null) {
return "";
}
return StringUtils.join(serverManager.getDeadServers().copyServerNames(), ";");
}
@Override
public int getNumDeadRegionServers() {
ServerManager serverManager = this.master.getServerManager();
if (serverManager == null) {
return 0;
}
return serverManager.getDeadServers().size();
}
@Override public boolean isRunning() {
return !(master.isStopped() || master.isStopping());
}
@Override
public String getDrainingRegionServers() {
ServerManager serverManager = this.master.getServerManager();
if (serverManager == null) {
return "";
}
return StringUtils.join(serverManager.getDrainingServersList() , ";");
}
@Override
public int getNumDrainingRegionServers() {
ServerManager serverManager = this.master.getServerManager();
if (serverManager == null) {
return 0;
}
return serverManager.getDrainingServersList().size();
}
@Override
public String getServerName() {
ServerName serverName = master.getServerName();
if (serverName == null) {
return "";
}
return serverName.getServerName();
}
@Override
public boolean getIsActiveMaster() {
return master.isActiveMaster();
}
@Override
public long getNumWALFiles() {
return master.getNumWALFiles();
}
@Override
public Map<String,Entry<Long,Long>> getTableSpaceUtilization() {
if (master == null) {
return Collections.emptyMap();
}
QuotaObserverChore quotaChore = master.getQuotaObserverChore();
if (quotaChore == null) {
return Collections.emptyMap();
}
Map<TableName,SpaceQuotaSnapshot> tableSnapshots = quotaChore.getTableQuotaSnapshots();
Map<String,Entry<Long,Long>> convertedData = new HashMap<>();
for (Entry<TableName,SpaceQuotaSnapshot> entry : tableSnapshots.entrySet()) {
convertedData.put(entry.getKey().toString(), convertSnapshot(entry.getValue()));
}
return convertedData;
}
@Override
public Map<String,Entry<Long,Long>> getNamespaceSpaceUtilization() {
QuotaObserverChore quotaChore = master.getQuotaObserverChore();
if (quotaChore == null) {
return Collections.emptyMap();
}
Map<String,SpaceQuotaSnapshot> namespaceSnapshots = quotaChore.getNamespaceQuotaSnapshots();
Map<String,Entry<Long,Long>> convertedData = new HashMap<>();
for (Entry<String,SpaceQuotaSnapshot> entry : namespaceSnapshots.entrySet()) {
convertedData.put(entry.getKey(), convertSnapshot(entry.getValue()));
}
return convertedData;
}
Entry<Long,Long> convertSnapshot(SpaceQuotaSnapshot snapshot) {
return new SimpleImmutableEntry<Long,Long>(snapshot.getUsage(), snapshot.getLimit());
}
}
| HBASE-25693 NPE getting metrics from standby masters (MetricsMasterWrapperImpl.getMergePlanCount) (#3091)
Signed-off-by: Duo Zhang <[email protected]>
Signed-off-by: Nick Dimiduk <[email protected]> | hbase-server/src/main/java/org/apache/hadoop/hbase/master/MetricsMasterWrapperImpl.java | HBASE-25693 NPE getting metrics from standby masters (MetricsMasterWrapperImpl.getMergePlanCount) (#3091) | <ide><path>base-server/src/main/java/org/apache/hadoop/hbase/master/MetricsMasterWrapperImpl.java
<ide>
<ide> @Override
<ide> public long getSplitPlanCount() {
<add> if (master.getRegionNormalizerManager() == null) {
<add> return 0;
<add> }
<ide> return master.getRegionNormalizerManager().getSplitPlanCount();
<ide> }
<ide>
<ide> @Override
<ide> public long getMergePlanCount() {
<add> if (master.getRegionNormalizerManager() == null) {
<add> return 0;
<add> }
<ide> return master.getRegionNormalizerManager().getMergePlanCount();
<ide> }
<ide> |
|
JavaScript | mit | bff8dc0d9650ae8892352d351c5886697cb17695 | 0 | Raynos/jsig,Raynos/jsig,Raynos/jsig | 'use strict';
/* Verifiers take an AST & a meta
They return the type defn of the node.
*/
var assert = require('assert');
var path = require('path');
var JsigAST = require('../ast/');
var serialize = require('../serialize.js');
var Errors = require('./errors.js');
var isSameType = require('./lib/is-same-type.js');
var getUnionWithoutBool = require('./lib/get-union-without-bool.js');
var updateObject = require('./lib/update-object.js');
var cloneJSIG = require('./lib/clone-ast.js');
var ARRAY_KEY_TYPE = JsigAST.literal('Number');
module.exports = ASTVerifier;
function ASTVerifier(meta, checker, fileName) {
this.meta = meta;
this.checker = checker;
this.fileName = fileName;
this.folderName = path.dirname(fileName);
}
/*eslint complexity: [2, 30] */
ASTVerifier.prototype.verifyNode = function verifyNode(node) {
if (node.type === 'Program') {
return this.verifyProgram(node);
} else if (node.type === 'FunctionDeclaration') {
return this.verifyFunctionDeclaration(node);
} else if (node.type === 'BlockStatement') {
return this.verifyBlockStatement(node);
} else if (node.type === 'ExpressionStatement') {
return this.verifyExpressionStatement(node);
} else if (node.type === 'AssignmentExpression') {
return this.verifyAssignmentExpression(node);
} else if (node.type === 'MemberExpression') {
return this.verifyMemberExpression(node);
} else if (node.type === 'ThisExpression') {
return this.verifyThisExpression(node);
} else if (node.type === 'Identifier') {
return this.verifyIdentifier(node);
} else if (node.type === 'Literal') {
return this.verifyLiteral(node);
} else if (node.type === 'ArrayExpression') {
return this.verifyArrayExpression(node);
} else if (node.type === 'CallExpression') {
return this.verifyCallExpression(node);
} else if (node.type === 'BinaryExpression') {
return this.verifyBinaryExpression(node);
} else if (node.type === 'ReturnStatement') {
return this.verifyReturnStatement(node);
} else if (node.type === 'NewExpression') {
return this.verifyNewExpression(node);
} else if (node.type === 'VariableDeclaration') {
return this.verifyVariableDeclaration(node);
} else if (node.type === 'ForStatement') {
return this.verifyForStatement(node);
} else if (node.type === 'UpdateExpression') {
return this.verifyUpdateExpression(node);
} else if (node.type === 'ObjectExpression') {
return this.verifyObjectExpression(node);
} else if (node.type === 'IfStatement') {
return this.verifyIfStatement(node);
} else if (node.type === 'UnaryExpression') {
return this.verifyUnaryExpression(node);
} else if (node.type === 'LogicalExpression') {
return this.verifyLogicalExpression(node);
} else if (node.type === 'FunctionExpression') {
return this.verifyFunctionExpression(node);
} else if (node.type === 'ContinueStatement') {
return this.verifyContinueStatement(node);
} else if (node.type === 'ThrowStatement') {
return this.verifyThrowStatement(node);
} else if (node.type === 'ConditionalExpression') {
return this.verifyConditionalExpression(node);
} else if (node.type === 'WhileStatement') {
return this.verifyWhileStatement(node);
} else {
throw new Error('!! skipping verifyNode: ' + node.type);
}
};
ASTVerifier.prototype.verifyProgram =
function verifyProgram(node) {
var parts = splitFunctionDeclaration(node.body);
var i = 0;
for (i = 0; i < parts.functions.length; i++) {
var name = parts.functions[i].id.name;
if (!this.meta.currentScope.getVar(name)) {
this.meta.currentScope.addFunction(name, parts.functions[i]);
}
}
for (i = 0; i < parts.statements.length; i++) {
this.meta.verifyNode(parts.statements[i], null);
}
var functions = parts.functions;
do {
var unknownFuncs = [];
for (i = 0; i < functions.length; i++) {
var func = functions[i];
if (!this.meta.currentScope.getVar(func.id.name)) {
unknownFuncs.push(func);
continue;
}
this.meta.verifyNode(func, null);
}
var gotSmaller = unknownFuncs.length < functions.length;
functions = unknownFuncs;
} while (gotSmaller);
for (i = 0; i < functions.length; i++) {
this.meta.verifyNode(functions[i], null);
}
/* If a module.exports type exists, but it has not been assigned */
if (this.meta.hasExportDefined() &&
!this.meta.hasFullyExportedType()
) {
var exportType = this.meta.getModuleExportsType();
var actualType = JsigAST.literal('<MissingType>', true);
if (this.meta.getExportedFields().length > 0) {
var fields = this.meta.getExportedFields();
actualType = cloneJSIG(exportType);
actualType.keyValues = [];
for (i = 0; i < exportType.keyValues.length; i++) {
var pair = exportType.keyValues[i];
if (fields.indexOf(pair.key) >= 0) {
actualType.keyValues.push(pair);
}
}
}
this.meta.addError(Errors.MissingExports({
expected: this.meta.serializeType(exportType),
actual: this.meta.serializeType(actualType)
}));
}
};
ASTVerifier.prototype.verifyFunctionDeclaration =
function verifyFunctionDeclaration(node) {
var funcName = node.id.name;
// console.log('verifyFunctionDeclaration', funcName);
var err;
if (this.meta.currentScope.getFunction(funcName)) {
// console.log('found untyped');
err = Errors.UnTypedFunctionFound({
funcName: funcName,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
var token;
if (this.meta.currentScope.getKnownFunctionInfo(funcName)) {
// console.log('found known function info', funcName);
// throw new Error('has getKnownFunctionInfo');
token = this.meta.currentScope.getVar(funcName);
assert(token, 'must have var for function');
this._checkFunctionType(node, token.defn);
return token.defn;
}
token = this.meta.currentScope.getVar(funcName);
if (!token) {
err = Errors.UnTypedFunctionFound({
funcName: funcName,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
var isFunction = token.defn.type === 'function';
if (!isFunction && token.defn.type !== 'intersectionType') {
err = Errors.UnexpectedFunction({
funcName: funcName,
expected: this.meta.serializeType(token.defn),
actual: this.meta.serializeType(JsigAST.literal('Function')),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
if (token.defn.type !== 'intersectionType') {
this._checkFunctionType(node, token.defn);
return token.defn;
}
var allTypes = token.defn.intersections;
var anyFunction = false;
for (var i = 0; i < allTypes.length; i++) {
var currType = allTypes[i];
isFunction = currType.type === 'function';
if (!isFunction) {
continue;
}
anyFunction = true;
this._checkFunctionOverloadType(node, currType);
}
if (!anyFunction) {
// TODO: actually show branches & originalErrors
err = Errors.UnexpectedFunction({
funcName: funcName,
expected: this.meta.serializeType(currType),
actual: this.meta.serializeType(JsigAST.literal('Function')),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
return token.defn;
};
ASTVerifier.prototype.verifyBlockStatement =
function verifyBlockStatement(node) {
for (var i = 0; i < node.body.length; i++) {
this.meta.verifyNode(node.body[i], null);
}
};
ASTVerifier.prototype.verifyExpressionStatement =
function verifyExpressionStatement(node) {
return this.meta.verifyNode(node.expression, null);
};
/*eslint max-statements: [2, 80]*/
ASTVerifier.prototype.verifyAssignmentExpression =
function verifyAssignmentExpression(node) {
this.meta.currentScope.setWritableTokenLookup();
var beforeError = this.meta.countErrors();
var leftType = this.meta.verifyNode(node.left, null);
var afterError = this.meta.countErrors();
this.meta.currentScope.unsetWritableTokenLookup();
if (!leftType) {
if (afterError === beforeError) {
assert(false, '!!! could not find leftType: ',
this.meta.serializeAST(node));
}
return null;
}
var rightType;
if (node.right.type === 'Identifier' &&
this.meta.currentScope.getFunction(node.right.name)
) {
if (leftType.name === '%Export%%ModuleExports') {
this.meta.addError(Errors.UnknownModuleExports({
funcName: node.right.name,
loc: node.loc,
line: node.loc.start.line
}));
return null;
}
if (!this.meta.tryUpdateFunction(node.right.name, leftType)) {
return null;
}
rightType = leftType;
} else {
rightType = this.meta.verifyNode(node.right, leftType);
}
if (!rightType) {
return null;
}
var isNullDefault = (
leftType.type === 'typeLiteral' &&
leftType.builtin && leftType.name === '%Null%%Default'
);
var isOpenField = (
leftType.type === 'typeLiteral' &&
leftType.builtin && leftType.name === '%Mixed%%OpenField'
);
var canGrow = isNullDefault || isOpenField;
if (!canGrow) {
this.meta.checkSubType(node, leftType, rightType);
}
if (node.left.type === 'Identifier' && isNullDefault) {
this.meta.currentScope.forceUpdateVar(node.left.name, rightType);
}
if (isOpenField && node.left.type === 'MemberExpression' &&
node.left.property.type === 'Identifier'
) {
var propertyName = node.left.property.name;
assert(node.left.object.type === 'Identifier');
var targetType = this.meta.verifyNode(node.left.object, null);
var newObjType = updateObject(
targetType, [propertyName], rightType
);
newObjType.open = targetType.open;
newObjType.brand = targetType.brand;
this.meta.currentScope.forceUpdateVar(
node.left.object.name, newObjType
);
}
if (leftType.name === '%Export%%ModuleExports') {
assert(rightType, 'must have an export type');
if (this.meta.hasExportDefined()) {
var expectedType = this.meta.getModuleExportsType();
this.meta.checkSubType(node, expectedType, rightType);
this.meta.setHasModuleExports(true);
} else {
this.meta.setModuleExportsType(rightType, node.right);
}
}
if (leftType.name !== '%Mixed%%UnknownExportsField' &&
node.left.type === 'MemberExpression' &&
node.left.object.type === 'Identifier' &&
node.left.property.type === 'Identifier' &&
node.left.object.name === 'exports' &&
this.meta.hasExportDefined()
) {
var exportsType = this.meta.verifyNode(node.left.object, null);
if (exportsType.type === 'typeLiteral' &&
exportsType.builtin && exportsType.name === '%Export%%ExportsObject'
) {
var fieldName = node.left.property.name;
this.meta.addExportedField(fieldName);
}
}
var funcScope = this.meta.currentScope.getFunctionScope();
if (funcScope && funcScope.isConstructor &&
node.left.type === 'MemberExpression' &&
node.left.object.type === 'ThisExpression'
) {
funcScope.addKnownField(node.left.property.name);
}
if (node.left.type === 'MemberExpression' &&
node.left.object.type === 'MemberExpression' &&
node.left.object.property.name === 'prototype'
) {
assert(node.left.object.object.type === 'Identifier',
'expected identifier');
var funcName = node.left.object.object.name;
fieldName = node.left.property.name;
assert(this.meta.currentScope.type === 'file',
'expected to be in file scope');
this.meta.currentScope.addPrototypeField(
funcName, fieldName, rightType
);
}
return rightType;
};
ASTVerifier.prototype.verifyMemberExpression =
function verifyMemberExpression(node) {
var objType = this.meta.verifyNode(node.object, null);
var propName = node.property.name;
if (objType === null) {
return null;
}
var valueType;
if (!node.computed) {
valueType = this._findPropertyInType(node, objType, propName);
} else {
var propType = this.meta.verifyNode(node.property, null);
if (!propType) {
return null;
}
valueType = this._findTypeInContainer(node, objType, propType);
}
return valueType;
};
ASTVerifier.prototype.verifyThisExpression =
function verifyThisExpression(node) {
var thisType = this.meta.currentScope.getThisType();
if (!thisType) {
var funcName = this.meta.currentScope.funcName;
var funcType = this.meta.currentScope.funcType;
this.meta.addError(Errors.NonExistantThis({
funcName: funcName,
funcType: funcType ?
this.meta.serializeType(funcType) : null,
loc: node.loc,
line: node.loc.start.line
}));
return null;
}
return thisType;
};
ASTVerifier.prototype.verifyIdentifier =
function verifyIdentifier(node) {
// FFFF--- javascript. undefined is a value, not an identifier
if (node.name === 'undefined') {
return JsigAST.value('undefined');
}
var token = this.meta.currentScope.getVar(node.name);
if (token) {
return token.defn;
}
if (node.name === 'global') {
return this.meta.currentScope.getGlobalType();
}
if (this.meta.currentExpressionType &&
this.meta.currentExpressionType.type === 'function' &&
this.meta.currentScope.getFunction(node.name)
) {
var exprType = this.meta.currentExpressionType;
var bool = this.meta.tryUpdateFunction(node.name, exprType);
if (bool) {
return exprType;
}
}
var isUnknown = Boolean(this.meta.currentScope.getUnknownVar(node.name));
if (isUnknown) {
this.meta.addError(Errors.UnTypedIdentifier({
tokenName: node.name,
line: node.loc.start.line,
loc: node.loc
}));
} else {
this.meta.addError(Errors.UnknownIdentifier({
tokenName: node.name,
line: node.loc.start.line,
loc: node.loc
}));
}
return null;
};
ASTVerifier.prototype.verifyLiteral =
function verifyLiteral(node) {
return this.meta.inferType(node);
};
ASTVerifier.prototype.verifyArrayExpression =
function verifyArrayExpression(node) {
return this.meta.inferType(node);
};
ASTVerifier.prototype._getTypeFromFunctionCall =
function _getTypeFromFunctionCall(node) {
var token;
var defn;
if (node.callee.type === 'Identifier') {
token = this.meta.currentScope.getVar(node.callee.name);
if (token) {
defn = token.defn;
} else {
defn = this.meta.inferType(node);
}
if (!defn) {
var err = Errors.UnTypedFunctionCall({
funcName: node.callee.name,
callExpression: this.meta.serializeAST(node.callee),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
} else {
defn = this.verifyNode(node.callee, null);
if (!defn) {
return null;
}
}
return defn;
};
ASTVerifier.prototype.verifyCallExpression =
function verifyCallExpression(node) {
var err;
if (node.callee.type === 'Identifier' &&
node.callee.name === 'require'
) {
return this._getTypeFromRequire(node);
}
var defn = this._getTypeFromFunctionCall(node);
if (!defn) {
return null;
}
if (defn.type !== 'function' && defn.type !== 'intersectionType') {
err = Errors.CallingNonFunctionObject({
objType: this.meta.serializeType(defn),
callExpression: this.meta.serializeAST(node.callee),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
if (defn.type === 'function') {
return this._checkFunctionCallExpr(node, defn, false);
}
var allErrors = [];
var result = null;
for (var i = 0; i < defn.intersections.length; i++) {
var possibleFn = defn.intersections[i];
var prevErrors = this.meta.getErrors();
var beforeErrors = this.meta.countErrors();
var possibleReturn = this._checkFunctionCallExpr(
node, possibleFn, true
);
var afterErrors = this.meta.countErrors();
if (beforeErrors === afterErrors && possibleReturn) {
result = possibleReturn;
break;
} else {
var currErrors = this.meta.getErrors();
for (var j = beforeErrors; j < afterErrors; j++) {
currErrors[j].branchType = this.meta.serializeType(possibleFn);
allErrors.push(currErrors[j]);
}
this.meta.setErrors(prevErrors);
}
}
if (result === null) {
var args = [];
for (i = 0; i < node.arguments.length; i++) {
var argType = this.meta.verifyNode(node.arguments[i], null);
if (!argType) {
argType = JsigAST.literal('<TypeError for js expr `' +
this.meta.serializeAST(node.arguments[i]) + '`>');
}
args.push(argType);
}
var finalErr = Errors.FunctionOverloadCallMisMatch({
expected: serialize(defn),
actual: serialize(JsigAST.tuple(args)),
funcName: this.meta.serializeAST(node.callee),
loc: node.loc,
line: node.loc.start.line
});
finalErr.originalErrors = allErrors;
this.meta.addError(finalErr);
}
return result;
};
ASTVerifier.prototype._checkFunctionCallExpr =
function _checkFunctionCallExpr(node, defn, isOverload) {
var err;
if (defn.generics.length > 0) {
// TODO: resolve generics
defn = this.meta.resolveGeneric(defn, node);
if (!defn) {
return null;
}
}
var minArgs = defn.args.length;
for (var i = 0; i < defn.args.length; i++) {
if (defn.args[i].optional) {
minArgs--;
}
}
if (node.arguments.length < minArgs) {
err = Errors.TooFewArgsInCall({
funcName: this.meta.serializeAST(node.callee),
actualArgs: node.arguments.length,
expectedArgs: minArgs,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
} else if (node.arguments.length > defn.args.length) {
err = Errors.TooManyArgsInCall({
funcName: this.meta.serializeAST(node.callee),
actualArgs: node.arguments.length,
expectedArgs: defn.args.length,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
}
var minLength = Math.min(defn.args.length, node.arguments.length);
for (i = 0; i < minLength; i++) {
var wantedType = defn.args[i];
var actualType;
if (node.arguments[i].type === 'Identifier' &&
this.meta.currentScope.getFunction(node.arguments[i].name)
) {
var funcName = node.arguments[i].name;
if (!this.meta.tryUpdateFunction(funcName, wantedType)) {
return null;
}
actualType = wantedType;
} else {
actualType = this.meta.verifyNode(node.arguments[i], wantedType);
}
/* If a literal string value is expected AND
A literal string value is passed as an argument
a.k.a not an alias or field.
Then convert the TypeLiteral into a ValueLiteral
*/
if (wantedType.type === 'valueLiteral' &&
wantedType.name === 'string' &&
node.arguments[i].type === 'Literal' &&
actualType.type === 'typeLiteral' &&
actualType.builtin &&
actualType.name === 'String' &&
typeof actualType.concreteValue === 'string'
) {
actualType = JsigAST.value(actualType.concreteValue, 'string');
}
if (!actualType) {
return null;
}
this.meta.checkSubType(node.arguments[i], wantedType, actualType);
}
// TODO: figure out thisType in call verification
if (defn.thisArg) {
assert(node.callee.type === 'MemberExpression',
'must be a method call expression');
// TODO: This could be wrong...
var obj = this.meta.verifyNode(node.callee.object, null);
assert(obj, 'object of method call must have a type');
// Try to late-bound a concrete instance of a free variable
// in a generic.
if (defn.generics.length > 0 && obj.type === 'genericLiteral') {
var hasFreeLiteral = obj.generics[0].type === 'freeLiteral';
assert(defn.thisArg.type === 'genericLiteral');
if (hasFreeLiteral) {
assert(!isOverload,
'cannot resolve free literal in overloaded function'
);
var newGenerics = [];
assert(obj.generics.length === defn.thisArg.generics.length,
'expected same number of generics');
for (i = 0; i < obj.generics.length; i++) {
newGenerics[i] = defn.thisArg.generics[i];
}
var newType = JsigAST.generic(
obj.value, newGenerics, obj.label
);
assert(node.callee.object.type === 'Identifier',
'object must be variable reference');
this.meta.currentScope.forceUpdateVar(
node.callee.object.name, newType
);
obj = newType;
}
}
this.meta.checkSubType(node.callee.object, defn.thisArg, obj);
}
return defn.result;
};
ASTVerifier.prototype.verifyBinaryExpression =
function verifyBinaryExpression(node) {
var leftType = this.meta.verifyNode(node.left, null);
if (!leftType) {
return null;
}
var rightType = this.meta.verifyNode(node.right, null);
if (!rightType) {
return null;
}
var token = this.meta.getOperator(node.operator);
assert(token, 'do not support unknown operators: ' + node.operator);
var intersections = token.defn.type === 'intersectionType' ?
token.defn.intersections : [token.defn];
var defn;
var correctDefn = intersections[0];
var isBad = true;
var errors = [];
for (var i = 0; i < intersections.length; i++) {
defn = intersections[i];
assert(defn.args.length === 2,
'expected type defn args to be two');
var leftError = this.meta.checkSubTypeRaw(
node.left, defn.args[0], leftType
);
var rightError = this.meta.checkSubTypeRaw(
node.right, defn.args[1], rightType
);
if (!leftError && !rightError) {
correctDefn = defn;
isBad = false;
} else {
if (leftError) {
leftError.branchType = this.meta.serializeType(defn);
errors.push(leftError);
}
if (rightError) {
rightError.branchType = this.meta.serializeType(defn);
errors.push(rightError);
}
}
}
// TODO: better error message UX
if (isBad && intersections.length === 1) {
for (var j = 0; j < errors.length; j++) {
this.meta.addError(errors[j]);
}
} else if (isBad && intersections.length > 1) {
var finalErr = Errors.IntersectionOperatorCallMismatch({
expected: serialize(token.defn),
actual: serialize(JsigAST.tuple([leftType, rightType])),
operator: node.operator,
loc: node.loc,
line: node.loc.start.line
});
finalErr.originalErrors = errors;
this.meta.addError(finalErr);
}
return correctDefn.result;
};
ASTVerifier.prototype.verifyReturnStatement =
function verifyReturnStatement(node) {
var funcScope = this.meta.currentScope.getFunctionScope();
assert(funcScope, 'return must be within a function scope');
var defn;
if (node.argument === null) {
defn = JsigAST.literal('void');
} else {
defn = this.meta.verifyNode(node.argument, null);
}
if (defn) {
funcScope.markReturnType(defn, node);
}
return defn;
};
ASTVerifier.prototype.verifyNewExpression =
function verifyNewExpression(node) {
var beforeError = this.meta.countErrors();
var fnType = this.meta.verifyNode(node.callee, null);
var afterError = this.meta.countErrors();
if (!fnType) {
if (beforeError === afterError) {
assert(false, '!!! cannot call new on unknown function');
}
return null;
}
assert(fnType.type === 'function', 'only support defined constructors');
var err;
if (!fnType.thisArg) {
err = Errors.CallingNewOnPlainFunction({
funcName: node.callee.name,
funcType: serialize(fnType),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
if (fnType.thisArg.type !== 'object' ||
fnType.thisArg.keyValues.length === 0
) {
err = Errors.ConstructorThisTypeMustBeObject({
funcName: node.callee.name,
thisType: serialize(fnType.thisArg),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
if (fnType.result.type !== 'typeLiteral' ||
fnType.result.name !== 'void'
) {
err = Errors.ConstructorMustReturnVoid({
funcName: node.callee.name,
returnType: serialize(fnType.result),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
var isConstructor = /[A-Z]/.test(getCalleeName(node)[0]);
if (!isConstructor) {
err = Errors.ConstructorMustBePascalCase({
funcName: node.callee.name,
funcType: serialize(fnType),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
var minArgs = fnType.args.length;
for (var i = 0; i < fnType.args.length; i++) {
if (fnType.args[i].optional) {
minArgs--;
}
}
if (node.arguments.length > fnType.args.length) {
err = Errors.TooManyArgsInNewExpression({
funcName: node.callee.name,
actualArgs: node.arguments.length,
expectedArgs: fnType.args.length,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
} else if (node.arguments.length < minArgs) {
err = Errors.TooFewArgsInNewExpression({
funcName: node.callee.name,
actualArgs: node.arguments.length,
expectedArgs: minArgs,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
}
var minLength = Math.min(fnType.args.length, node.arguments.length);
for (i = 0; i < minLength; i++) {
var wantedType = fnType.args[i];
var actualType = this.meta.verifyNode(node.arguments[i], null);
if (!actualType) {
return null;
}
this.meta.checkSubType(node.arguments[i], wantedType, actualType);
}
var thisArg = fnType.thisArg;
thisArg = cloneJSIG(thisArg);
thisArg.brand = fnType.brand;
thisArg._raw = fnType.thisArg._raw;
return thisArg;
};
function getCalleeName(node) {
if (node.callee.type === 'Identifier') {
return node.callee.name;
} else if (node.callee.type === 'MemberExpression' &&
node.callee.property.type === 'Identifier'
) {
return node.callee.property.name;
} else {
assert(false, 'Cannot get callee name');
}
}
ASTVerifier.prototype.verifyVariableDeclaration =
function verifyVariableDeclaration(node) {
assert(node.declarations.length === 1,
'only support single declaration');
var decl = node.declarations[0];
var id = decl.id.name;
var token = this.meta.currentScope.getOwnVar(id);
if (token) {
assert(token.preloaded, 'cannot declare variable twice');
}
var type;
if (decl.init) {
type = this.meta.verifyNode(decl.init, null);
if (!type) {
this.meta.currentScope.addUnknownVar(id);
return null;
}
if (token) {
this.meta.checkSubType(node, token.defn, type);
type = token.defn;
}
} else {
type = token ? token.defn :
JsigAST.literal('%Void%%Uninitialized', true);
}
if (type.type === 'valueLiteral' && type.name === 'null') {
type = JsigAST.literal('%Null%%Default', true);
}
this.meta.currentScope.addVar(id, type);
return null;
};
ASTVerifier.prototype.verifyForStatement =
function verifyForStatement(node) {
this.meta.verifyNode(node.init, null);
var testType = this.meta.verifyNode(node.test, null);
assert(!testType || (
testType.type === 'typeLiteral' && testType.name === 'Boolean'
), 'for loop condition statement must be a Boolean expression');
this.meta.verifyNode(node.update, null);
this.meta.verifyNode(node.body, null);
};
ASTVerifier.prototype.verifyUpdateExpression =
function verifyUpdateExpression(node) {
var firstType = this.meta.verifyNode(node.argument, null);
if (!firstType) {
return null;
}
var token = this.meta.getOperator(node.operator);
assert(token, 'do not support unknown operators: ' + node.operator);
var defn = token.defn;
assert(defn.args.length === 1,
'expecteted type defn args to be one');
this.meta.checkSubType(node.argument, defn.args[0], firstType);
return defn.result;
};
ASTVerifier.prototype.verifyObjectExpression =
function verifyObjectExpression(node) {
return this.meta.inferType(node);
};
/*
check test expression
Allocate if branch scope ; Allocate else branch scope;
narrowType(node, ifBranch, elseBranch);
check if within ifBranch scope
check else within elseBranch scope
For each restriction that exists in both if & else.
change the type of that identifier in function scope.
*/
ASTVerifier.prototype.verifyIfStatement =
function verifyIfStatement(node) {
this.meta.verifyNode(node.test, null);
var ifBranch = this.meta.allocateBranchScope();
var elseBranch = this.meta.allocateBranchScope();
// TODO: check things ?
this.meta.narrowType(node.test, ifBranch, elseBranch);
if (node.consequent) {
this.meta.enterBranchScope(ifBranch);
this.meta.verifyNode(node.consequent, null);
this.meta.exitBranchScope();
}
if (node.alternative) {
this.meta.enterBranchScope(elseBranch);
this.meta.verifyNode(node.alternative, null);
this.meta.exitBranchScope();
}
var keys = Object.keys(ifBranch.typeRestrictions);
for (var i = 0; i < keys.length; i++) {
var name = keys[i];
var ifType = ifBranch.typeRestrictions[name];
var elseType = elseBranch.typeRestrictions[name];
if (!ifType || !elseType) {
continue;
}
if (isSameType(ifType.defn, elseType.defn)) {
this.meta.currentScope.restrictType(name, ifType.defn);
}
}
// TODO create unions based on typeRestrictions & mutations...
};
ASTVerifier.prototype.verifyUnaryExpression =
function verifyUnaryExpression(node) {
if (node.operator === 'delete') {
this.meta.verifyNode(node.argument, null);
var objectType = this.meta.verifyNode(node.argument.object, null);
assert(objectType.type === 'genericLiteral',
'delete must operate on generic objects');
assert(objectType.value.type === 'typeLiteral' &&
objectType.value.name === 'Object',
'delete must operate on objects');
return null;
}
var firstType = this.meta.verifyNode(node.argument, null);
if (!firstType) {
return null;
}
var token = this.meta.getOperator(node.operator);
assert(token, 'do not support unknown operators: ' + node.operator);
var defn = token.defn;
assert(defn.args.length === 1,
'expecteted type defn args to be one');
this.meta.checkSubType(node.argument, defn.args[0], firstType);
return defn.result;
};
ASTVerifier.prototype.verifyLogicalExpression =
function verifyLogicalExpression(node) {
assert(node.operator === '||' || node.operator === '&&',
'only || and && are supported as logical operators');
var ifBranch = this.meta.allocateBranchScope();
var elseBranch = this.meta.allocateBranchScope();
var leftType = this.meta.verifyNode(node.left, null);
if (!leftType) {
return null;
}
this.meta.narrowType(node.left, ifBranch, elseBranch);
if (node.operator === '&&') {
this.meta.enterBranchScope(ifBranch);
} else if (node.operator === '||') {
this.meta.enterBranchScope(elseBranch);
} else {
assert(false, 'unsupported logical operator');
}
var exprType = null;
if (node.operator === '||') {
exprType = this.meta.currentExpressionType;
}
var rightType = this.meta.verifyNode(node.right, exprType);
this.meta.exitBranchScope();
if (!rightType) {
return null;
}
var t1;
var t2;
if (node.operator === '||') {
t1 = getUnionWithoutBool(leftType, true);
t2 = rightType;
} else if (node.operator === '&&') {
t1 = getUnionWithoutBool(leftType, false);
t2 = rightType;
} else {
assert(false, 'unimplemented operator');
}
return this._computeSmallestUnion(node, t1, t2);
};
ASTVerifier.prototype.verifyFunctionExpression =
function verifyFunctionExpression(node) {
var potentialType = this.meta.currentExpressionType;
if (!potentialType) {
var err = Errors.UnTypedFunctionFound({
funcName: node.id.name,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
// If we are assigning onto a Mixed%%OpenField then
// skip checking this function expression
if (potentialType.type === 'typeLiteral' &&
potentialType.builtin &&
(
potentialType.name === '%Mixed%%OpenField' ||
potentialType.name === '%Mixed%%UnknownExportsField' ||
potentialType.name === '%Export%%ModuleExports'
)
) {
var funcName = node.id ? node.id.name : '(anonymous)';
err = Errors.UnTypedFunctionFound({
funcName: funcName,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
this._checkFunctionType(node, potentialType);
return potentialType;
};
ASTVerifier.prototype.verifyContinueStatement =
function verifyContinueStatement(node) {
assert(node.label === null, 'do not support goto');
return null;
};
ASTVerifier.prototype.verifyThrowStatement =
function verifyThrowStatement(node) {
var argType = this.meta.verifyNode(node.argument, null);
if (argType === null) {
return null;
}
if (argType.brand !== 'Error') {
this.meta.addError(Errors.InvalidThrowStatement({
expected: 'Error',
actual: this.meta.serializeType(argType),
loc: node.loc,
line: node.loc.start.line
}));
}
return null;
};
ASTVerifier.prototype.verifyConditionalExpression =
function verifyConditionalExpression(node) {
this.meta.verifyNode(node.test, null);
var left = this.meta.verifyNode(node.consequent, null);
if (!left) {
return null;
}
var right = this.meta.verifyNode(node.alternate, null);
if (!right) {
return null;
}
if (isSameType(left, right)) {
return left;
}
return JsigAST.union([left, right]);
};
ASTVerifier.prototype.verifyWhileStatement =
function verifyWhileStatement(node) {
this.meta.verifyNode(node.test, null);
var ifBranch = this.meta.allocateBranchScope();
var elseBranch = this.meta.allocateBranchScope();
// TODO: check things ?
this.meta.narrowType(node.test, ifBranch, elseBranch);
this.meta.enterBranchScope(ifBranch);
this.meta.verifyNode(node.body, null);
this.meta.exitBranchScope();
};
ASTVerifier.prototype._checkFunctionOverloadType =
function _checkFunctionOverloadType(node, defn) {
this.meta.enterFunctionOverloadScope(node, defn);
this._verifyFunctionType(node, defn);
this.meta.exitFunctionScope();
};
ASTVerifier.prototype._checkFunctionType =
function _checkFunctionType(node, defn) {
this.meta.enterFunctionScope(node, defn);
this._verifyFunctionType(node, defn);
this.meta.exitFunctionScope();
};
ASTVerifier.prototype._verifyFunctionType =
function _verifyFunctionType(node, defn) {
var err;
if (node.params.length > defn.args.length) {
err = Errors.TooManyArgsInFunc({
funcName: node.id.name,
actualArgs: node.params.length,
expectedArgs: defn.args.length,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return;
} else if (node.params.length < defn.args.length) {
err = Errors.TooFewArgsInFunc({
funcName: node.id.name,
actualArgs: node.params.length,
expectedArgs: defn.args.length,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return;
}
var statements = node.body.body;
for (var i = 0; i < statements.length; i++) {
if (statements[i].type === 'FunctionDeclaration') {
var name = statements[i].id.name;
this.meta.currentScope.addFunction(name, statements[i]);
}
}
this.meta.verifyNode(node.body, null);
if (this.meta.currentScope.isConstructor) {
this._checkHiddenClass(node);
this._checkVoidReturnType(node);
} else {
// TODO: verify return.
this._checkReturnType(node);
}
};
ASTVerifier.prototype._checkHiddenClass =
function _checkHiddenClass(node) {
var thisType = this.meta.currentScope.getThisType();
var knownFields = this.meta.currentScope.knownFields;
var protoFields = this.meta.currentScope.getPrototypeFields();
var err;
if (!thisType || thisType.type !== 'object') {
err = Errors.ConstructorThisTypeMustBeObject({
funcName: this.meta.currentScope.funcName,
thisType: thisType ? serialize(thisType) : 'void',
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return;
}
assert(thisType && thisType.type === 'object', 'this field must be object');
for (var i = 0; i < thisType.keyValues.length; i++) {
var key = thisType.keyValues[i].key;
if (
knownFields[i] !== key &&
!(protoFields && protoFields[key])
) {
err = Errors.MissingFieldInConstr({
fieldName: key,
funcName: this.meta.currentScope.funcName,
otherField: knownFields[i] || 'no-field',
loc: node.loc,
line: node.loc.start.line
});// new Error('missing field: ' + key);
this.meta.addError(err);
}
}
};
ASTVerifier.prototype._checkReturnType =
function _checkReturnType(node) {
var expected = this.meta.currentScope.returnValueType;
var actual = this.meta.currentScope.knownReturnType;
var returnNode = this.meta.currentScope.returnStatementASTNode;
var err;
// If we never inferred the return type then it may or may not return
if (expected.type === 'typeLiteral' &&
expected.name === '%Void%%UnknownReturn'
) {
return;
}
if (expected.type === 'typeLiteral' && expected.name === 'void') {
if (actual !== null && !(
actual.type === 'typeLiteral' && actual.name === 'void'
)) {
err = Errors.NonVoidReturnType({
expected: 'void',
actual: serialize(actual),
funcName: this.meta.currentScope.funcName,
loc: returnNode.loc,
line: returnNode.loc.start.line
});
this.meta.addError(err);
}
return;
}
if (actual === null && returnNode === null) {
var funcNode = this.meta.currentScope.funcASTNode;
err = Errors.MissingReturnStatement({
expected: serialize(expected),
actual: 'void',
funcName: this.meta.currentScope.funcName,
loc: funcNode.loc,
line: funcNode.loc.start.line
});
this.meta.addError(err);
return;
}
this.meta.checkSubType(returnNode, expected, actual);
};
ASTVerifier.prototype._checkVoidReturnType =
function _checkVoidReturnType(node) {
var returnType = this.meta.currentScope.returnValueType;
var actualReturnType = this.meta.currentScope.knownReturnType;
var returnNode = this.meta.currentScope.returnStatementASTNode;
var err;
if (returnNode || actualReturnType !== null) {
var returnTypeInfo = serialize(actualReturnType);
err = Errors.ReturnStatementInConstructor({
funcName: this.meta.currentScope.funcName,
returnType: returnTypeInfo === 'void' ?
'empty return' : returnTypeInfo,
line: returnNode.loc.start.line,
loc: returnNode.loc
});
this.meta.addError(err);
return;
}
// console.log('?', this.meta.serializeType(returnType));
assert(returnType.type === 'typeLiteral' && (
returnType.name === 'void' ||
returnType.name === '%Void%%UnknownReturn'
), 'expected Constructor to have no return void');
};
ASTVerifier.prototype._findPropertyInType =
function _findPropertyInType(node, jsigType, propertyName) {
if (jsigType.type === 'function' &&
propertyName === 'prototype'
) {
return jsigType.thisArg;
} else if (jsigType.type === 'genericLiteral' &&
jsigType.value.type === 'typeLiteral' &&
jsigType.value.name === 'Array'
) {
jsigType = this.meta.getVirtualType('TArray').defn;
} else if (jsigType.type === 'typeLiteral' &&
jsigType.name === 'String'
) {
jsigType = this.meta.getVirtualType('TString').defn;
} else if (jsigType.type === 'typeLiteral' &&
jsigType.name === 'Number'
) {
jsigType = this.meta.getVirtualType('TNumber').defn;
} else if (jsigType.type === 'genericLiteral' &&
jsigType.value.type === 'typeLiteral' &&
jsigType.value.name === 'Object'
) {
jsigType = this.meta.getVirtualType('TObject').defn;
}
var isExportsObject = false;
if (jsigType.type === 'typeLiteral' &&
jsigType.builtin && jsigType.name === '%Export%%ExportsObject'
) {
isExportsObject = true;
var newType = this.meta.getModuleExportsType();
if (newType) {
jsigType = newType;
}
}
return this._findPropertyInSet(
node, jsigType, propertyName, isExportsObject
);
};
ASTVerifier.prototype._findPropertyInSet =
function _findPropertyInSet(node, jsigType, propertyName, isExportsObject) {
if (jsigType.type === 'unionType') {
this.meta.addError(Errors.UnionFieldAccess({
loc: node.loc,
line: node.loc.start.line,
fieldName: propertyName,
unionType: serialize(jsigType)
}));
return null;
}
if (jsigType.type === 'intersectionType' &&
propertyName === 'prototype'
) {
// Count functions
var funcCount = 0;
var funcType = null;
var intersections = jsigType.intersections;
for (var i = 0; i < intersections.length; i++) {
var possibleType = intersections[i];
if (possibleType.type === 'function') {
funcType = possibleType;
funcCount++;
}
}
assert(funcCount <= 1, 'cannot access prototype fields ' +
'on overloaded constructors...');
if (funcType.thisArg) {
return funcType.thisArg;
}
}
// Naive intersection support, find first object.
if (jsigType.type === 'intersectionType') {
intersections = jsigType.intersections;
for (i = 0; i < intersections.length; i++) {
possibleType = intersections[i];
if (possibleType.type !== 'object') {
continue;
}
for (var j = 0; j < possibleType.keyValues.length; j++) {
var pair = possibleType.keyValues[j];
if (pair.key === propertyName) {
return this._findPropertyInType(
node, possibleType, propertyName
);
}
}
}
}
return this._findPropertyInObject(
node, jsigType, propertyName, isExportsObject
);
};
ASTVerifier.prototype._findPropertyInObject =
function _findPropertyInObject(
node, jsigType, propertyName, isExportsObject
) {
if (jsigType.type !== 'object') {
this.meta.addError(Errors.NonObjectFieldAccess({
loc: node.loc,
line: node.loc.start.line,
fieldName: propertyName,
nonObjectType: serialize(jsigType)
}));
return null;
}
for (var i = 0; i < jsigType.keyValues.length; i++) {
var keyValue = jsigType.keyValues[i];
if (keyValue.key === propertyName) {
// TODO: handle optional fields
return keyValue.value;
}
}
if (jsigType.open) {
return JsigAST.literal('%Mixed%%OpenField', true);
}
if (isExportsObject && this.meta.checkerRules.partialExport) {
return JsigAST.literal('%Mixed%%UnknownExportsField', true);
}
if (this.meta.checkerRules.partialExport) {
// If we are assigning a method to the exported class
if (this.meta.currentScope.type === 'file' &&
node.object.type === 'MemberExpression' &&
node.object.property.name === 'prototype' &&
node.object.object.type === 'Identifier'
) {
var expected = this.meta.currentScope.getExportedIdentifier();
var actual = node.object.object.name;
if (expected === actual) {
return JsigAST.literal('%Mixed%%UnknownExportsField', true);
}
}
}
var err = this._createNonExistantFieldError(node, propertyName);
this.meta.addError(err);
return null;
};
ASTVerifier.prototype._findTypeInContainer =
function _findTypeInContainer(node, objType, propType) {
var valueType;
if (objType.type !== 'genericLiteral') {
this.meta.addError(Errors.NonGenericPropertyLookup({
expected: 'Array<T> | Object<K, V>',
actual: this.meta.serializeType(objType),
propType: this.meta.serializeType(propType),
loc: node.loc,
line: node.loc.start.line
}));
return null;
}
if (objType.value.name === 'Array') {
this.meta.checkSubType(node, ARRAY_KEY_TYPE, propType);
valueType = objType.generics[0];
} else if (objType.value.name === 'Object') {
this.meta.checkSubType(node, objType.generics[0], propType);
valueType = objType.generics[1];
} else {
assert(false, 'Cannot look inside non Array/Object container');
}
assert(valueType, 'expected valueType to exist');
return valueType;
};
ASTVerifier.prototype._createNonExistantFieldError =
function _createNonExistantFieldError(node, propName) {
var objName;
if (node.object.type === 'ThisExpression') {
objName = 'this';
} else if (node.object.type === 'Identifier') {
objName = node.object.name;
} else if (node.object.type === 'MemberExpression') {
objName = this.meta.serializeAST(node.object);
} else if (node.object.type === 'CallExpression') {
objName = this.meta.serializeAST(node.object);
} else {
assert(false, 'unknown object type');
}
var actualType = this.meta.verifyNode(node.object, null);
if (actualType.type === 'typeLiteral' &&
actualType.builtin && actualType.name === '%Export%%ExportsObject'
) {
actualType = this.meta.getModuleExportsType();
}
return Errors.NonExistantField({
fieldName: propName,
objName: objName,
expected: '{ ' + propName + ': T }',
actual: serialize(actualType),
loc: node.loc,
line: node.loc.start.line
});
};
ASTVerifier.prototype._getTypeFromRequire =
function _getTypeFromRequire(node) {
assert(node.callee.name === 'require', 'func name must be require');
var arg = node.arguments[0];
assert(arg.type === 'Literal' && typeof arg.value === 'string',
'arg to require must be a string literal');
var depPath = arg.value;
// Handle pre-defined npm case
var externDefn = this.checker.getDefinition(depPath);
if (externDefn) {
return externDefn.defn;
}
// Resolve a local file name
var fileName = this._resolvePath(node, depPath, this.folderName);
if (!fileName) {
if (this.meta.checkerRules.allowUnknownRequire) {
return JsigAST.literal('%Mixed%%UnknownRequire', true);
}
// TODO: search for type defintions inside node_modules/*
this.meta.addError(Errors.MissingDefinition({
moduleName: depPath,
line: node.loc.start.line,
loc: node.loc
}));
return null;
}
// Handle local case
var otherMeta = this.checker.getOrCreateMeta(fileName);
if (!otherMeta) {
return null;
}
return otherMeta.moduleExportsType;
};
ASTVerifier.prototype._resolvePath =
function resolvePath(node, possiblePath, dirname) {
if (possiblePath[0] === path.sep) {
// is absolute path
return possiblePath;
} else if (possiblePath[0] === '.') {
// is relative path
return path.resolve(dirname, possiblePath);
} else {
return null;
}
};
ASTVerifier.prototype._computeSmallestUnion =
function _computeSmallestUnion(node, t1, t2) {
var parts = [];
addPossibleType(parts, t1);
addPossibleType(parts, t2);
if (parts.length === 0) {
return null;
}
if (parts.length === 1) {
return parts[0];
}
var minimal = this._computeSmallestCommonTypes(node, parts);
// Again, find smallest common type in reverse ??
// var reverseMinimal = parts.slice();
// reverseMinimal.reverse();
// reverseMinimal = this._computeSmallestCommonTypes(node, reverseMinimal);
// // Only use reverse minimal if smaller.
// if (reverseMinimal.length < minimal.length) {
// minimal = reverseMinimal;
// }
if (minimal.length === 1) {
return minimal[0];
}
return JsigAST.union(minimal);
};
ASTVerifier.prototype._computeSmallestCommonTypes =
function _computeSmallestCommonTypes(node, list) {
var minimal = [];
for (var i = 0; i < list.length; i++) {
var sample = list[i];
var toAdd = sample;
for (var j = 0; j < minimal.length; j++) {
if (isSameType(sample, minimal[j])) {
toAdd = null;
break;
}
/* if a super type of the other then remove from union */
// TODO: this seems so naive...
var isSuper = this.meta.isSubType(node, minimal[j], sample);
if (isSuper) {
toAdd = null;
break;
}
}
if (toAdd) {
minimal.push(toAdd);
}
}
return minimal;
};
function addPossibleType(list, maybeType) {
if (!maybeType) {
return;
}
if (maybeType.type !== 'unionType') {
list.push(maybeType);
return;
}
for (var i = 0; i < maybeType.unions.length; i++) {
list.push(maybeType.unions[i]);
}
}
// hoisting function declarations to the bottom makes the tree
// order algorithm simpler
function splitFunctionDeclaration(nodes) {
var result = {
functions: [],
statements: []
};
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].type !== 'FunctionDeclaration') {
result.statements.push(nodes[i]);
}
}
for (i = 0; i < nodes.length; i++) {
if (nodes[i].type === 'FunctionDeclaration') {
result.functions.push(nodes[i]);
}
}
return result;
}
| type-checker/ast-verifier.js | 'use strict';
/* Verifiers take an AST & a meta
They return the type defn of the node.
*/
var assert = require('assert');
var path = require('path');
var JsigAST = require('../ast/');
var serialize = require('../serialize.js');
var Errors = require('./errors.js');
var isSameType = require('./lib/is-same-type.js');
var getUnionWithoutBool = require('./lib/get-union-without-bool.js');
var updateObject = require('./lib/update-object.js');
var cloneJSIG = require('./lib/clone-ast.js');
var ARRAY_KEY_TYPE = JsigAST.literal('Number');
module.exports = ASTVerifier;
function ASTVerifier(meta, checker, fileName) {
this.meta = meta;
this.checker = checker;
this.fileName = fileName;
this.folderName = path.dirname(fileName);
}
/*eslint complexity: [2, 30] */
ASTVerifier.prototype.verifyNode = function verifyNode(node) {
if (node.type === 'Program') {
return this.verifyProgram(node);
} else if (node.type === 'FunctionDeclaration') {
return this.verifyFunctionDeclaration(node);
} else if (node.type === 'BlockStatement') {
return this.verifyBlockStatement(node);
} else if (node.type === 'ExpressionStatement') {
return this.verifyExpressionStatement(node);
} else if (node.type === 'AssignmentExpression') {
return this.verifyAssignmentExpression(node);
} else if (node.type === 'MemberExpression') {
return this.verifyMemberExpression(node);
} else if (node.type === 'ThisExpression') {
return this.verifyThisExpression(node);
} else if (node.type === 'Identifier') {
return this.verifyIdentifier(node);
} else if (node.type === 'Literal') {
return this.verifyLiteral(node);
} else if (node.type === 'ArrayExpression') {
return this.verifyArrayExpression(node);
} else if (node.type === 'CallExpression') {
return this.verifyCallExpression(node);
} else if (node.type === 'BinaryExpression') {
return this.verifyBinaryExpression(node);
} else if (node.type === 'ReturnStatement') {
return this.verifyReturnStatement(node);
} else if (node.type === 'NewExpression') {
return this.verifyNewExpression(node);
} else if (node.type === 'VariableDeclaration') {
return this.verifyVariableDeclaration(node);
} else if (node.type === 'ForStatement') {
return this.verifyForStatement(node);
} else if (node.type === 'UpdateExpression') {
return this.verifyUpdateExpression(node);
} else if (node.type === 'ObjectExpression') {
return this.verifyObjectExpression(node);
} else if (node.type === 'IfStatement') {
return this.verifyIfStatement(node);
} else if (node.type === 'UnaryExpression') {
return this.verifyUnaryExpression(node);
} else if (node.type === 'LogicalExpression') {
return this.verifyLogicalExpression(node);
} else if (node.type === 'FunctionExpression') {
return this.verifyFunctionExpression(node);
} else if (node.type === 'ContinueStatement') {
return this.verifyContinueStatement(node);
} else if (node.type === 'ThrowStatement') {
return this.verifyThrowStatement(node);
} else if (node.type === 'ConditionalExpression') {
return this.verifyConditionalExpression(node);
} else if (node.type === 'WhileStatement') {
return this.verifyWhileStatement(node);
} else {
throw new Error('!! skipping verifyNode: ' + node.type);
}
};
ASTVerifier.prototype.verifyProgram =
function verifyProgram(node) {
var parts = splitFunctionDeclaration(node.body);
var i = 0;
for (i = 0; i < parts.functions.length; i++) {
var name = parts.functions[i].id.name;
if (!this.meta.currentScope.getVar(name)) {
this.meta.currentScope.addFunction(name, parts.functions[i]);
}
}
for (i = 0; i < parts.statements.length; i++) {
this.meta.verifyNode(parts.statements[i], null);
}
var functions = parts.functions;
do {
var unknownFuncs = [];
for (i = 0; i < functions.length; i++) {
var func = functions[i];
if (!this.meta.currentScope.getVar(func.id.name)) {
unknownFuncs.push(func);
continue;
}
this.meta.verifyNode(func, null);
}
var gotSmaller = unknownFuncs.length < functions.length;
functions = unknownFuncs;
} while (gotSmaller);
for (i = 0; i < functions.length; i++) {
this.meta.verifyNode(functions[i], null);
}
/* If a module.exports type exists, but it has not been assigned */
if (this.meta.hasExportDefined() &&
!this.meta.hasFullyExportedType()
) {
var exportType = this.meta.getModuleExportsType();
var actualType = JsigAST.literal('<MissingType>', true);
if (this.meta.getExportedFields().length > 0) {
var fields = this.meta.getExportedFields();
actualType = cloneJSIG(exportType);
actualType.keyValues = [];
for (i = 0; i < exportType.keyValues.length; i++) {
var pair = exportType.keyValues[i];
if (fields.indexOf(pair.key) >= 0) {
actualType.keyValues.push(pair);
}
}
}
this.meta.addError(Errors.MissingExports({
expected: this.meta.serializeType(exportType),
actual: this.meta.serializeType(actualType)
}));
}
};
ASTVerifier.prototype.verifyFunctionDeclaration =
function verifyFunctionDeclaration(node) {
var funcName = node.id.name;
// console.log('verifyFunctionDeclaration', funcName);
var err;
if (this.meta.currentScope.getFunction(funcName)) {
// console.log('found untyped');
err = Errors.UnTypedFunctionFound({
funcName: funcName,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
var token;
if (this.meta.currentScope.getKnownFunctionInfo(funcName)) {
// console.log('found known function info', funcName);
// throw new Error('has getKnownFunctionInfo');
token = this.meta.currentScope.getVar(funcName);
assert(token, 'must have var for function');
this._checkFunctionType(node, token.defn);
return token.defn;
}
token = this.meta.currentScope.getVar(funcName);
if (!token) {
err = Errors.UnTypedFunctionFound({
funcName: funcName,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
var isFunction = token.defn.type === 'function';
if (!isFunction && token.defn.type !== 'intersectionType') {
err = Errors.UnexpectedFunction({
funcName: funcName,
expected: this.meta.serializeType(token.defn),
actual: this.meta.serializeType(JsigAST.literal('Function')),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
if (token.defn.type !== 'intersectionType') {
this._checkFunctionType(node, token.defn);
return token.defn;
}
var allTypes = token.defn.intersections;
var anyFunction = false;
for (var i = 0; i < allTypes.length; i++) {
var currType = allTypes[i];
isFunction = currType.type === 'function';
if (!isFunction) {
continue;
}
anyFunction = true;
this._checkFunctionOverloadType(node, currType);
}
if (!anyFunction) {
// TODO: actually show branches & originalErrors
err = Errors.UnexpectedFunction({
funcName: funcName,
expected: this.meta.serializeType(currType),
actual: this.meta.serializeType(JsigAST.literal('Function')),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
return token.defn;
};
ASTVerifier.prototype.verifyBlockStatement =
function verifyBlockStatement(node) {
for (var i = 0; i < node.body.length; i++) {
this.meta.verifyNode(node.body[i], null);
}
};
ASTVerifier.prototype.verifyExpressionStatement =
function verifyExpressionStatement(node) {
return this.meta.verifyNode(node.expression, null);
};
/*eslint max-statements: [2, 80]*/
ASTVerifier.prototype.verifyAssignmentExpression =
function verifyAssignmentExpression(node) {
this.meta.currentScope.setWritableTokenLookup();
var beforeError = this.meta.countErrors();
var leftType = this.meta.verifyNode(node.left, null);
var afterError = this.meta.countErrors();
this.meta.currentScope.unsetWritableTokenLookup();
if (!leftType) {
if (afterError === beforeError) {
assert(false, '!!! could not find leftType: ',
this.meta.serializeAST(node));
}
return null;
}
var rightType;
if (node.right.type === 'Identifier' &&
this.meta.currentScope.getFunction(node.right.name)
) {
if (leftType.name === '%Export%%ModuleExports') {
this.meta.addError(Errors.UnknownModuleExports({
funcName: node.right.name,
loc: node.loc,
line: node.loc.start.line
}));
return null;
}
if (!this.meta.tryUpdateFunction(node.right.name, leftType)) {
return null;
}
rightType = leftType;
} else {
rightType = this.meta.verifyNode(node.right, leftType);
}
if (!rightType) {
return null;
}
var isNullDefault = (
leftType.type === 'typeLiteral' &&
leftType.builtin && leftType.name === '%Null%%Default'
);
var isOpenField = (
leftType.type === 'typeLiteral' &&
leftType.builtin && leftType.name === '%Mixed%%OpenField'
);
var canGrow = isNullDefault || isOpenField;
if (!canGrow) {
this.meta.checkSubType(node, leftType, rightType);
}
if (node.left.type === 'Identifier' && isNullDefault) {
this.meta.currentScope.forceUpdateVar(node.left.name, rightType);
}
if (isOpenField && node.left.type === 'MemberExpression' &&
node.left.property.type === 'Identifier'
) {
var propertyName = node.left.property.name;
assert(node.left.object.type === 'Identifier');
var targetType = this.meta.verifyNode(node.left.object, null);
var newObjType = updateObject(
targetType, [propertyName], rightType
);
newObjType.open = targetType.open;
newObjType.brand = targetType.brand;
this.meta.currentScope.forceUpdateVar(
node.left.object.name, newObjType
);
}
if (leftType.name === '%Export%%ModuleExports') {
assert(rightType, 'must have an export type');
if (this.meta.hasExportDefined()) {
var expectedType = this.meta.getModuleExportsType();
this.meta.checkSubType(node, expectedType, rightType);
this.meta.setHasModuleExports(true);
} else {
this.meta.setModuleExportsType(rightType, node.right);
}
}
if (leftType.name !== '%Mixed%%UnknownExportsField' &&
node.left.type === 'MemberExpression' &&
node.left.object.type === 'Identifier' &&
node.left.property.type === 'Identifier' &&
node.left.object.name === 'exports' &&
this.meta.hasExportDefined()
) {
var exportsType = this.meta.verifyNode(node.left.object, null);
if (exportsType.type === 'typeLiteral' &&
exportsType.builtin && exportsType.name === '%Export%%ExportsObject'
) {
var fieldName = node.left.property.name;
this.meta.addExportedField(fieldName);
}
}
var funcScope = this.meta.currentScope.getFunctionScope();
if (funcScope && funcScope.isConstructor &&
node.left.type === 'MemberExpression' &&
node.left.object.type === 'ThisExpression'
) {
funcScope.addKnownField(node.left.property.name);
}
if (node.left.type === 'MemberExpression' &&
node.left.object.type === 'MemberExpression' &&
node.left.object.property.name === 'prototype'
) {
assert(node.left.object.object.type === 'Identifier',
'expected identifier');
var funcName = node.left.object.object.name;
fieldName = node.left.property.name;
assert(this.meta.currentScope.type === 'file',
'expected to be in file scope');
this.meta.currentScope.addPrototypeField(
funcName, fieldName, rightType
);
}
return rightType;
};
ASTVerifier.prototype.verifyMemberExpression =
function verifyMemberExpression(node) {
var objType = this.meta.verifyNode(node.object, null);
var propName = node.property.name;
if (objType === null) {
return null;
}
var valueType;
if (!node.computed) {
valueType = this._findPropertyInType(node, objType, propName);
} else {
var propType = this.meta.verifyNode(node.property, null);
if (!propType) {
return null;
}
valueType = this._findTypeInContainer(node, objType, propType);
}
return valueType;
};
ASTVerifier.prototype.verifyThisExpression =
function verifyThisExpression(node) {
var thisType = this.meta.currentScope.getThisType();
if (!thisType) {
var funcName = this.meta.currentScope.funcName;
var funcType = this.meta.currentScope.funcType;
this.meta.addError(Errors.NonExistantThis({
funcName: funcName,
funcType: funcType ?
this.meta.serializeType(funcType) : null,
loc: node.loc,
line: node.loc.start.line
}));
return null;
}
return thisType;
};
ASTVerifier.prototype.verifyIdentifier =
function verifyIdentifier(node) {
// FFFF--- javascript. undefined is a value, not an identifier
if (node.name === 'undefined') {
return JsigAST.value('undefined');
}
var token = this.meta.currentScope.getVar(node.name);
if (token) {
return token.defn;
}
if (node.name === 'global') {
return this.meta.currentScope.getGlobalType();
}
if (this.meta.currentExpressionType &&
this.meta.currentExpressionType.type === 'function' &&
this.meta.currentScope.getFunction(node.name)
) {
var exprType = this.meta.currentExpressionType;
var bool = this.meta.tryUpdateFunction(node.name, exprType);
if (bool) {
return exprType;
}
}
var isUnknown = Boolean(this.meta.currentScope.getUnknownVar(node.name));
if (isUnknown) {
this.meta.addError(Errors.UnTypedIdentifier({
tokenName: node.name,
line: node.loc.start.line,
loc: node.loc
}));
} else {
this.meta.addError(Errors.UnknownIdentifier({
tokenName: node.name,
line: node.loc.start.line,
loc: node.loc
}));
}
return null;
};
ASTVerifier.prototype.verifyLiteral =
function verifyLiteral(node) {
return this.meta.inferType(node);
};
ASTVerifier.prototype.verifyArrayExpression =
function verifyArrayExpression(node) {
return this.meta.inferType(node);
};
ASTVerifier.prototype._getTypeFromFunctionCall =
function _getTypeFromFunctionCall(node) {
var token;
var defn;
if (node.callee.type === 'Identifier') {
token = this.meta.currentScope.getVar(node.callee.name);
if (token) {
defn = token.defn;
} else {
defn = this.meta.inferType(node);
}
if (!defn) {
var err = Errors.UnTypedFunctionCall({
funcName: node.callee.name,
callExpression: this.meta.serializeAST(node.callee),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
} else {
defn = this.verifyNode(node.callee, null);
if (!defn) {
return null;
}
}
return defn;
};
ASTVerifier.prototype.verifyCallExpression =
function verifyCallExpression(node) {
var err;
if (node.callee.type === 'Identifier' &&
node.callee.name === 'require'
) {
return this._getTypeFromRequire(node);
}
var defn = this._getTypeFromFunctionCall(node);
if (!defn) {
return null;
}
if (defn.type !== 'function' && defn.type !== 'intersectionType') {
err = Errors.CallingNonFunctionObject({
objType: this.meta.serializeType(defn),
callExpression: this.meta.serializeAST(node.callee),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
if (defn.type === 'function') {
return this._checkFunctionCallExpr(node, defn, false);
}
var allErrors = [];
var result = null;
for (var i = 0; i < defn.intersections.length; i++) {
var possibleFn = defn.intersections[i];
var prevErrors = this.meta.getErrors();
var beforeErrors = this.meta.countErrors();
var possibleReturn = this._checkFunctionCallExpr(
node, possibleFn, true
);
var afterErrors = this.meta.countErrors();
if (beforeErrors === afterErrors && possibleReturn) {
result = possibleReturn;
break;
} else {
var currErrors = this.meta.getErrors();
for (var j = beforeErrors; j < afterErrors; j++) {
currErrors[j].branchType = this.meta.serializeType(possibleFn);
allErrors.push(currErrors[j]);
}
this.meta.setErrors(prevErrors);
}
}
if (result === null) {
var args = [];
for (i = 0; i < node.arguments.length; i++) {
var argType = this.meta.verifyNode(node.arguments[i], null);
if (!argType) {
argType = JsigAST.literal('<TypeError for js expr `' +
this.meta.serializeAST(node.arguments[i]) + '`>');
}
args.push(argType);
}
var finalErr = Errors.FunctionOverloadCallMisMatch({
expected: serialize(defn),
actual: serialize(JsigAST.tuple(args)),
funcName: this.meta.serializeAST(node.callee),
loc: node.loc,
line: node.loc.start.line
});
finalErr.originalErrors = allErrors;
this.meta.addError(finalErr);
}
return result;
};
ASTVerifier.prototype._checkFunctionCallExpr =
function _checkFunctionCallExpr(node, defn, isOverload) {
var err;
if (defn.generics.length > 0) {
// TODO: resolve generics
defn = this.meta.resolveGeneric(defn, node);
if (!defn) {
return null;
}
}
var minArgs = defn.args.length;
for (var i = 0; i < defn.args.length; i++) {
if (defn.args[i].optional) {
minArgs--;
}
}
if (node.arguments.length < minArgs) {
err = Errors.TooFewArgsInCall({
funcName: this.meta.serializeAST(node.callee),
actualArgs: node.arguments.length,
expectedArgs: minArgs,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
} else if (node.arguments.length > defn.args.length) {
err = Errors.TooManyArgsInCall({
funcName: this.meta.serializeAST(node.callee),
actualArgs: node.arguments.length,
expectedArgs: defn.args.length,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
}
var minLength = Math.min(defn.args.length, node.arguments.length);
for (i = 0; i < minLength; i++) {
var wantedType = defn.args[i];
var actualType;
if (node.arguments[i].type === 'Identifier' &&
this.meta.currentScope.getFunction(node.arguments[i].name)
) {
var funcName = node.arguments[i].name;
if (!this.meta.tryUpdateFunction(funcName, wantedType)) {
return null;
}
actualType = wantedType;
} else {
actualType = this.meta.verifyNode(node.arguments[i], wantedType);
}
/* If a literal string value is expected AND
A literal string value is passed as an argument
a.k.a not an alias or field.
Then convert the TypeLiteral into a ValueLiteral
*/
if (wantedType.type === 'valueLiteral' &&
wantedType.name === 'string' &&
node.arguments[i].type === 'Literal' &&
actualType.type === 'typeLiteral' &&
actualType.builtin &&
actualType.name === 'String' &&
typeof actualType.concreteValue === 'string'
) {
actualType = JsigAST.value(actualType.concreteValue, 'string');
}
if (!actualType) {
return null;
}
this.meta.checkSubType(node.arguments[i], wantedType, actualType);
}
// TODO: figure out thisType in call verification
if (defn.thisArg) {
assert(node.callee.type === 'MemberExpression',
'must be a method call expression');
// TODO: This could be wrong...
var obj = this.meta.verifyNode(node.callee.object, null);
assert(obj, 'object of method call must have a type');
// Try to late-bound a concrete instance of a free variable
// in a generic.
if (defn.generics.length > 0 && obj.type === 'genericLiteral') {
var hasFreeLiteral = obj.generics[0].type === 'freeLiteral';
assert(defn.thisArg.type === 'genericLiteral');
if (hasFreeLiteral) {
assert(!isOverload,
'cannot resolve free literal in overloaded function'
);
var newGenerics = [];
assert(obj.generics.length === defn.thisArg.generics.length,
'expected same number of generics');
for (i = 0; i < obj.generics.length; i++) {
newGenerics[i] = defn.thisArg.generics[i];
}
var newType = JsigAST.generic(
obj.value, newGenerics, obj.label
);
assert(node.callee.object.type === 'Identifier',
'object must be variable reference');
this.meta.currentScope.forceUpdateVar(
node.callee.object.name, newType
);
obj = newType;
}
}
this.meta.checkSubType(node.callee.object, defn.thisArg, obj);
}
return defn.result;
};
ASTVerifier.prototype.verifyBinaryExpression =
function verifyBinaryExpression(node) {
var leftType = this.meta.verifyNode(node.left, null);
if (!leftType) {
return null;
}
var rightType = this.meta.verifyNode(node.right, null);
if (!rightType) {
return null;
}
var token = this.meta.getOperator(node.operator);
assert(token, 'do not support unknown operators: ' + node.operator);
var intersections = token.defn.type === 'intersectionType' ?
token.defn.intersections : [token.defn];
var defn;
var correctDefn = intersections[0];
var isBad = true;
var errors = [];
for (var i = 0; i < intersections.length; i++) {
defn = intersections[i];
assert(defn.args.length === 2,
'expected type defn args to be two');
var leftError = this.meta.checkSubTypeRaw(
node.left, defn.args[0], leftType
);
var rightError = this.meta.checkSubTypeRaw(
node.right, defn.args[1], rightType
);
if (!leftError && !rightError) {
correctDefn = defn;
isBad = false;
} else {
if (leftError) {
leftError.branchType = this.meta.serializeType(defn);
errors.push(leftError);
}
if (rightError) {
rightError.branchType = this.meta.serializeType(defn);
errors.push(rightError);
}
}
}
// TODO: better error message UX
if (isBad && intersections.length === 1) {
for (var j = 0; j < errors.length; j++) {
this.meta.addError(errors[j]);
}
} else if (isBad && intersections.length > 1) {
var finalErr = Errors.IntersectionOperatorCallMismatch({
expected: serialize(token.defn),
actual: serialize(JsigAST.tuple([leftType, rightType])),
operator: node.operator,
loc: node.loc,
line: node.loc.start.line
});
finalErr.originalErrors = errors;
this.meta.addError(finalErr);
}
return correctDefn.result;
};
ASTVerifier.prototype.verifyReturnStatement =
function verifyReturnStatement(node) {
var funcScope = this.meta.currentScope.getFunctionScope();
assert(funcScope, 'return must be within a function scope');
var defn;
if (node.argument === null) {
defn = JsigAST.literal('void');
} else {
defn = this.meta.verifyNode(node.argument, null);
}
if (defn) {
funcScope.markReturnType(defn, node);
}
return defn;
};
ASTVerifier.prototype.verifyNewExpression =
function verifyNewExpression(node) {
var beforeError = this.meta.countErrors();
var fnType = this.meta.verifyNode(node.callee, null);
var afterError = this.meta.countErrors();
if (!fnType) {
if (beforeError === afterError) {
assert(false, '!!! cannot call new on unknown function');
}
return null;
}
assert(fnType.type === 'function', 'only support defined constructors');
var err;
if (!fnType.thisArg) {
err = Errors.CallingNewOnPlainFunction({
funcName: node.callee.name,
funcType: serialize(fnType),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
if (fnType.thisArg.type !== 'object' ||
fnType.thisArg.keyValues.length === 0
) {
err = Errors.ConstructorThisTypeMustBeObject({
funcName: node.callee.name,
thisType: serialize(fnType.thisArg),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
if (fnType.result.type !== 'typeLiteral' ||
fnType.result.name !== 'void'
) {
err = Errors.ConstructorMustReturnVoid({
funcName: node.callee.name,
returnType: serialize(fnType.result),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
var isConstructor = /[A-Z]/.test(getCalleeName(node)[0]);
if (!isConstructor) {
err = Errors.ConstructorMustBePascalCase({
funcName: node.callee.name,
funcType: serialize(fnType),
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
var minArgs = fnType.args.length;
for (var i = 0; i < fnType.args.length; i++) {
if (fnType.args[i].optional) {
minArgs--;
}
}
if (node.arguments.length > fnType.args.length) {
err = Errors.TooManyArgsInNewExpression({
funcName: node.callee.name,
actualArgs: node.arguments.length,
expectedArgs: fnType.args.length,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
} else if (node.arguments.length < minArgs) {
err = Errors.TooFewArgsInNewExpression({
funcName: node.callee.name,
actualArgs: node.arguments.length,
expectedArgs: minArgs,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
}
var minLength = Math.min(fnType.args.length, node.arguments.length);
for (i = 0; i < minLength; i++) {
var wantedType = fnType.args[i];
var actualType = this.meta.verifyNode(node.arguments[i], null);
if (!actualType) {
return null;
}
this.meta.checkSubType(node.arguments[i], wantedType, actualType);
}
var thisArg = fnType.thisArg;
thisArg = cloneJSIG(thisArg);
thisArg.brand = fnType.brand;
thisArg._raw = fnType.thisArg._raw;
return thisArg;
};
function getCalleeName(node) {
if (node.callee.type === 'Identifier') {
return node.callee.name;
} else if (node.callee.type === 'MemberExpression' &&
node.callee.property.type === 'Identifier'
) {
return node.callee.property.name;
} else {
assert(false, 'Cannot get callee name');
}
}
ASTVerifier.prototype.verifyVariableDeclaration =
function verifyVariableDeclaration(node) {
assert(node.declarations.length === 1,
'only support single declaration');
var decl = node.declarations[0];
var id = decl.id.name;
var token = this.meta.currentScope.getOwnVar(id);
if (token) {
assert(token.preloaded, 'cannot declare variable twice');
}
var type;
if (decl.init) {
type = this.meta.verifyNode(decl.init, null);
if (!type) {
this.meta.currentScope.addUnknownVar(id);
return null;
}
if (token) {
this.meta.checkSubType(node, token.defn, type);
type = token.defn;
}
} else {
type = token ? token.defn :
JsigAST.literal('%Void%%Uninitialized', true);
}
if (type.type === 'valueLiteral' && type.name === 'null') {
type = JsigAST.literal('%Null%%Default', true);
}
this.meta.currentScope.addVar(id, type);
return null;
};
ASTVerifier.prototype.verifyForStatement =
function verifyForStatement(node) {
this.meta.verifyNode(node.init, null);
var testType = this.meta.verifyNode(node.test, null);
assert(!testType || (
testType.type === 'typeLiteral' && testType.name === 'Boolean'
), 'for loop condition statement must be a Boolean expression');
this.meta.verifyNode(node.update, null);
this.meta.verifyNode(node.body, null);
};
ASTVerifier.prototype.verifyUpdateExpression =
function verifyUpdateExpression(node) {
var firstType = this.meta.verifyNode(node.argument, null);
if (!firstType) {
return null;
}
var token = this.meta.getOperator(node.operator);
assert(token, 'do not support unknown operators: ' + node.operator);
var defn = token.defn;
assert(defn.args.length === 1,
'expecteted type defn args to be one');
this.meta.checkSubType(node.argument, defn.args[0], firstType);
return defn.result;
};
ASTVerifier.prototype.verifyObjectExpression =
function verifyObjectExpression(node) {
return this.meta.inferType(node);
};
/*
check test expression
Allocate if branch scope ; Allocate else branch scope;
narrowType(node, ifBranch, elseBranch);
check if within ifBranch scope
check else within elseBranch scope
For each restriction that exists in both if & else.
change the type of that identifier in function scope.
*/
ASTVerifier.prototype.verifyIfStatement =
function verifyIfStatement(node) {
this.meta.verifyNode(node.test, null);
var ifBranch = this.meta.allocateBranchScope();
var elseBranch = this.meta.allocateBranchScope();
// TODO: check things ?
this.meta.narrowType(node.test, ifBranch, elseBranch);
if (node.consequent) {
this.meta.enterBranchScope(ifBranch);
this.meta.verifyNode(node.consequent, null);
this.meta.exitBranchScope();
}
if (node.alternative) {
this.meta.enterBranchScope(elseBranch);
this.meta.verifyNode(node.alternative, null);
this.meta.exitBranchScope();
}
var keys = Object.keys(ifBranch.typeRestrictions);
for (var i = 0; i < keys.length; i++) {
var name = keys[i];
var ifType = ifBranch.typeRestrictions[name];
var elseType = elseBranch.typeRestrictions[name];
if (!ifType || !elseType) {
continue;
}
if (isSameType(ifType.defn, elseType.defn)) {
this.meta.currentScope.restrictType(name, ifType.defn);
}
}
// TODO create unions based on typeRestrictions & mutations...
};
ASTVerifier.prototype.verifyUnaryExpression =
function verifyUnaryExpression(node) {
if (node.operator === 'delete') {
this.meta.verifyNode(node.argument, null);
var objectType = this.meta.verifyNode(node.argument.object, null);
assert(objectType.type === 'genericLiteral',
'delete must operate on generic objects');
assert(objectType.value.type === 'typeLiteral' &&
objectType.value.name === 'Object',
'delete must operate on objects');
return null;
}
var firstType = this.meta.verifyNode(node.argument, null);
if (!firstType) {
return null;
}
var token = this.meta.getOperator(node.operator);
assert(token, 'do not support unknown operators: ' + node.operator);
var defn = token.defn;
assert(defn.args.length === 1,
'expecteted type defn args to be one');
this.meta.checkSubType(node.argument, defn.args[0], firstType);
return defn.result;
};
ASTVerifier.prototype.verifyLogicalExpression =
function verifyLogicalExpression(node) {
assert(node.operator === '||' || node.operator === '&&',
'only || and && are supported as logical operators');
var ifBranch = this.meta.allocateBranchScope();
var elseBranch = this.meta.allocateBranchScope();
var leftType = this.meta.verifyNode(node.left, null);
if (!leftType) {
return null;
}
this.meta.narrowType(node.left, ifBranch, elseBranch);
if (node.operator === '&&') {
this.meta.enterBranchScope(ifBranch);
} else if (node.operator === '||') {
this.meta.enterBranchScope(elseBranch);
} else {
assert(false, 'unsupported logical operator');
}
var exprType = null;
if (node.operator === '||') {
exprType = this.meta.currentExpressionType;
}
var rightType = this.meta.verifyNode(node.right, exprType);
this.meta.exitBranchScope();
if (!rightType) {
return null;
}
var t1;
var t2;
if (node.operator === '||') {
t1 = getUnionWithoutBool(leftType, true);
t2 = rightType;
} else if (node.operator === '&&') {
t1 = getUnionWithoutBool(leftType, false);
t2 = rightType;
} else {
assert(false, 'unimplemented operator');
}
return this._computeSmallestUnion(node, t1, t2);
};
ASTVerifier.prototype.verifyFunctionExpression =
function verifyFunctionExpression(node) {
var potentialType = this.meta.currentExpressionType;
if (!potentialType) {
var err = Errors.UnTypedFunctionFound({
funcName: node.id.name,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
// If we are assigning onto a Mixed%%OpenField then
// skip checking this function expression
if (potentialType.type === 'typeLiteral' &&
potentialType.builtin &&
(
potentialType.name === '%Mixed%%OpenField' ||
potentialType.name === '%Mixed%%UnknownExportsField' ||
potentialType.name === '%Export%%ModuleExports'
)
) {
var funcName = node.id ? node.id.name : '(anonymous)';
err = Errors.UnTypedFunctionFound({
funcName: funcName,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return null;
}
this._checkFunctionType(node, potentialType);
return potentialType;
};
ASTVerifier.prototype.verifyContinueStatement =
function verifyContinueStatement(node) {
assert(node.label === null, 'do not support goto');
return null;
};
ASTVerifier.prototype.verifyThrowStatement =
function verifyThrowStatement(node) {
var argType = this.meta.verifyNode(node.argument, null);
if (argType === null) {
return null;
}
if (argType.brand !== 'Error') {
this.meta.addError(Errors.InvalidThrowStatement({
expected: 'Error',
actual: this.meta.serializeType(argType),
loc: node.loc,
line: node.loc.start.line
}));
}
return null;
};
ASTVerifier.prototype.verifyConditionalExpression =
function verifyConditionalExpression(node) {
this.meta.verifyNode(node.test, null);
var left = this.meta.verifyNode(node.consequent, null);
if (!left) {
return null;
}
var right = this.meta.verifyNode(node.alternate, null);
if (!right) {
return null;
}
if (isSameType(left, right)) {
return left;
}
return JsigAST.union([left, right]);
};
ASTVerifier.prototype.verifyWhileStatement =
function verifyWhileStatement(node) {
this.meta.verifyNode(node.test, null);
var ifBranch = this.meta.allocateBranchScope();
var elseBranch = this.meta.allocateBranchScope();
// TODO: check things ?
this.meta.narrowType(node.test, ifBranch, elseBranch);
this.meta.enterBranchScope(ifBranch);
this.meta.verifyNode(node.body, null);
this.meta.exitBranchScope();
};
ASTVerifier.prototype._checkFunctionOverloadType =
function _checkFunctionOverloadType(node, defn) {
this.meta.enterFunctionOverloadScope(node, defn);
this._verifyFunctionType(node, defn);
this.meta.exitFunctionScope();
};
ASTVerifier.prototype._checkFunctionType =
function checkFunctionType(node, defn) {
this.meta.enterFunctionScope(node, defn);
this._verifyFunctionType(node, defn);
this.meta.exitFunctionScope();
};
ASTVerifier.prototype._verifyFunctionType =
function _verifyFunctionType(node, defn) {
var err;
if (node.params.length > defn.args.length) {
err = Errors.TooManyArgsInFunc({
funcName: node.id.name,
actualArgs: node.params.length,
expectedArgs: defn.args.length,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
this.meta.exitFunctionScope();
return;
} else if (node.params.length < defn.args.length) {
err = Errors.TooFewArgsInFunc({
funcName: node.id.name,
actualArgs: node.params.length,
expectedArgs: defn.args.length,
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
this.meta.exitFunctionScope();
return;
}
var statements = node.body.body;
for (var i = 0; i < statements.length; i++) {
if (statements[i].type === 'FunctionDeclaration') {
var name = statements[i].id.name;
this.meta.currentScope.addFunction(name, statements[i]);
}
}
this.meta.verifyNode(node.body, null);
if (this.meta.currentScope.isConstructor) {
this._checkHiddenClass(node);
this._checkVoidReturnType(node);
} else {
// TODO: verify return.
this._checkReturnType(node);
}
};
ASTVerifier.prototype._checkHiddenClass =
function _checkHiddenClass(node) {
var thisType = this.meta.currentScope.getThisType();
var knownFields = this.meta.currentScope.knownFields;
var protoFields = this.meta.currentScope.getPrototypeFields();
var err;
if (!thisType || thisType.type !== 'object') {
err = Errors.ConstructorThisTypeMustBeObject({
funcName: this.meta.currentScope.funcName,
thisType: thisType ? serialize(thisType) : 'void',
loc: node.loc,
line: node.loc.start.line
});
this.meta.addError(err);
return;
}
assert(thisType && thisType.type === 'object', 'this field must be object');
for (var i = 0; i < thisType.keyValues.length; i++) {
var key = thisType.keyValues[i].key;
if (
knownFields[i] !== key &&
!(protoFields && protoFields[key])
) {
err = Errors.MissingFieldInConstr({
fieldName: key,
funcName: this.meta.currentScope.funcName,
otherField: knownFields[i] || 'no-field',
loc: node.loc,
line: node.loc.start.line
});// new Error('missing field: ' + key);
this.meta.addError(err);
}
}
};
ASTVerifier.prototype._checkReturnType =
function _checkReturnType(node) {
var expected = this.meta.currentScope.returnValueType;
var actual = this.meta.currentScope.knownReturnType;
var returnNode = this.meta.currentScope.returnStatementASTNode;
var err;
// If we never inferred the return type then it may or may not return
if (expected.type === 'typeLiteral' &&
expected.name === '%Void%%UnknownReturn'
) {
return;
}
if (expected.type === 'typeLiteral' && expected.name === 'void') {
if (actual !== null && !(
actual.type === 'typeLiteral' && actual.name === 'void'
)) {
err = Errors.NonVoidReturnType({
expected: 'void',
actual: serialize(actual),
funcName: this.meta.currentScope.funcName,
loc: returnNode.loc,
line: returnNode.loc.start.line
});
this.meta.addError(err);
}
return;
}
if (actual === null && returnNode === null) {
var funcNode = this.meta.currentScope.funcASTNode;
err = Errors.MissingReturnStatement({
expected: serialize(expected),
actual: 'void',
funcName: this.meta.currentScope.funcName,
loc: funcNode.loc,
line: funcNode.loc.start.line
});
this.meta.addError(err);
return;
}
this.meta.checkSubType(returnNode, expected, actual);
};
ASTVerifier.prototype._checkVoidReturnType =
function _checkVoidReturnType(node) {
var returnType = this.meta.currentScope.returnValueType;
var actualReturnType = this.meta.currentScope.knownReturnType;
var returnNode = this.meta.currentScope.returnStatementASTNode;
var err;
if (returnNode || actualReturnType !== null) {
var returnTypeInfo = serialize(actualReturnType);
err = Errors.ReturnStatementInConstructor({
funcName: this.meta.currentScope.funcName,
returnType: returnTypeInfo === 'void' ?
'empty return' : returnTypeInfo,
line: returnNode.loc.start.line,
loc: returnNode.loc
});
this.meta.addError(err);
return;
}
// console.log('?', this.meta.serializeType(returnType));
assert(returnType.type === 'typeLiteral' && (
returnType.name === 'void' ||
returnType.name === '%Void%%UnknownReturn'
), 'expected Constructor to have no return void');
};
ASTVerifier.prototype._findPropertyInType =
function _findPropertyInType(node, jsigType, propertyName) {
if (jsigType.type === 'function' &&
propertyName === 'prototype'
) {
return jsigType.thisArg;
} else if (jsigType.type === 'genericLiteral' &&
jsigType.value.type === 'typeLiteral' &&
jsigType.value.name === 'Array'
) {
jsigType = this.meta.getVirtualType('TArray').defn;
} else if (jsigType.type === 'typeLiteral' &&
jsigType.name === 'String'
) {
jsigType = this.meta.getVirtualType('TString').defn;
} else if (jsigType.type === 'typeLiteral' &&
jsigType.name === 'Number'
) {
jsigType = this.meta.getVirtualType('TNumber').defn;
} else if (jsigType.type === 'genericLiteral' &&
jsigType.value.type === 'typeLiteral' &&
jsigType.value.name === 'Object'
) {
jsigType = this.meta.getVirtualType('TObject').defn;
}
var isExportsObject = false;
if (jsigType.type === 'typeLiteral' &&
jsigType.builtin && jsigType.name === '%Export%%ExportsObject'
) {
isExportsObject = true;
var newType = this.meta.getModuleExportsType();
if (newType) {
jsigType = newType;
}
}
return this._findPropertyInSet(
node, jsigType, propertyName, isExportsObject
);
};
ASTVerifier.prototype._findPropertyInSet =
function _findPropertyInSet(node, jsigType, propertyName, isExportsObject) {
if (jsigType.type === 'unionType') {
this.meta.addError(Errors.UnionFieldAccess({
loc: node.loc,
line: node.loc.start.line,
fieldName: propertyName,
unionType: serialize(jsigType)
}));
return null;
}
if (jsigType.type === 'intersectionType' &&
propertyName === 'prototype'
) {
// Count functions
var funcCount = 0;
var funcType = null;
var intersections = jsigType.intersections;
for (var i = 0; i < intersections.length; i++) {
var possibleType = intersections[i];
if (possibleType.type === 'function') {
funcType = possibleType;
funcCount++;
}
}
assert(funcCount <= 1, 'cannot access prototype fields ' +
'on overloaded constructors...');
if (funcType.thisArg) {
return funcType.thisArg;
}
}
// Naive intersection support, find first object.
if (jsigType.type === 'intersectionType') {
intersections = jsigType.intersections;
for (i = 0; i < intersections.length; i++) {
possibleType = intersections[i];
if (possibleType.type !== 'object') {
continue;
}
for (var j = 0; j < possibleType.keyValues.length; j++) {
var pair = possibleType.keyValues[j];
if (pair.key === propertyName) {
return this._findPropertyInType(
node, possibleType, propertyName
);
}
}
}
}
return this._findPropertyInObject(
node, jsigType, propertyName, isExportsObject
);
};
ASTVerifier.prototype._findPropertyInObject =
function _findPropertyInObject(
node, jsigType, propertyName, isExportsObject
) {
if (jsigType.type !== 'object') {
this.meta.addError(Errors.NonObjectFieldAccess({
loc: node.loc,
line: node.loc.start.line,
fieldName: propertyName,
nonObjectType: serialize(jsigType)
}));
return null;
}
for (var i = 0; i < jsigType.keyValues.length; i++) {
var keyValue = jsigType.keyValues[i];
if (keyValue.key === propertyName) {
// TODO: handle optional fields
return keyValue.value;
}
}
if (jsigType.open) {
return JsigAST.literal('%Mixed%%OpenField', true);
}
if (isExportsObject && this.meta.checkerRules.partialExport) {
return JsigAST.literal('%Mixed%%UnknownExportsField', true);
}
if (this.meta.checkerRules.partialExport) {
// If we are assigning a method to the exported class
if (this.meta.currentScope.type === 'file' &&
node.object.type === 'MemberExpression' &&
node.object.property.name === 'prototype' &&
node.object.object.type === 'Identifier'
) {
var expected = this.meta.currentScope.getExportedIdentifier();
var actual = node.object.object.name;
if (expected === actual) {
return JsigAST.literal('%Mixed%%UnknownExportsField', true);
}
}
}
var err = this._createNonExistantFieldError(node, propertyName);
this.meta.addError(err);
return null;
};
ASTVerifier.prototype._findTypeInContainer =
function _findTypeInContainer(node, objType, propType) {
var valueType;
if (objType.type !== 'genericLiteral') {
this.meta.addError(Errors.NonGenericPropertyLookup({
expected: 'Array<T> | Object<K, V>',
actual: this.meta.serializeType(objType),
propType: this.meta.serializeType(propType),
loc: node.loc,
line: node.loc.start.line
}));
return null;
}
if (objType.value.name === 'Array') {
this.meta.checkSubType(node, ARRAY_KEY_TYPE, propType);
valueType = objType.generics[0];
} else if (objType.value.name === 'Object') {
this.meta.checkSubType(node, objType.generics[0], propType);
valueType = objType.generics[1];
} else {
assert(false, 'Cannot look inside non Array/Object container');
}
assert(valueType, 'expected valueType to exist');
return valueType;
};
ASTVerifier.prototype._createNonExistantFieldError =
function _createNonExistantFieldError(node, propName) {
var objName;
if (node.object.type === 'ThisExpression') {
objName = 'this';
} else if (node.object.type === 'Identifier') {
objName = node.object.name;
} else if (node.object.type === 'MemberExpression') {
objName = this.meta.serializeAST(node.object);
} else if (node.object.type === 'CallExpression') {
objName = this.meta.serializeAST(node.object);
} else {
assert(false, 'unknown object type');
}
var actualType = this.meta.verifyNode(node.object, null);
if (actualType.type === 'typeLiteral' &&
actualType.builtin && actualType.name === '%Export%%ExportsObject'
) {
actualType = this.meta.getModuleExportsType();
}
return Errors.NonExistantField({
fieldName: propName,
objName: objName,
expected: '{ ' + propName + ': T }',
actual: serialize(actualType),
loc: node.loc,
line: node.loc.start.line
});
};
ASTVerifier.prototype._getTypeFromRequire =
function _getTypeFromRequire(node) {
assert(node.callee.name === 'require', 'func name must be require');
var arg = node.arguments[0];
assert(arg.type === 'Literal' && typeof arg.value === 'string',
'arg to require must be a string literal');
var depPath = arg.value;
// Handle pre-defined npm case
var externDefn = this.checker.getDefinition(depPath);
if (externDefn) {
return externDefn.defn;
}
// Resolve a local file name
var fileName = this._resolvePath(node, depPath, this.folderName);
if (!fileName) {
if (this.meta.checkerRules.allowUnknownRequire) {
return JsigAST.literal('%Mixed%%UnknownRequire', true);
}
// TODO: search for type defintions inside node_modules/*
this.meta.addError(Errors.MissingDefinition({
moduleName: depPath,
line: node.loc.start.line,
loc: node.loc
}));
return null;
}
// Handle local case
var otherMeta = this.checker.getOrCreateMeta(fileName);
if (!otherMeta) {
return null;
}
return otherMeta.moduleExportsType;
};
ASTVerifier.prototype._resolvePath =
function resolvePath(node, possiblePath, dirname) {
if (possiblePath[0] === path.sep) {
// is absolute path
return possiblePath;
} else if (possiblePath[0] === '.') {
// is relative path
return path.resolve(dirname, possiblePath);
} else {
return null;
}
};
ASTVerifier.prototype._computeSmallestUnion =
function _computeSmallestUnion(node, t1, t2) {
var parts = [];
addPossibleType(parts, t1);
addPossibleType(parts, t2);
if (parts.length === 0) {
return null;
}
if (parts.length === 1) {
return parts[0];
}
var minimal = this._computeSmallestCommonTypes(node, parts);
// Again, find smallest common type in reverse ??
// var reverseMinimal = parts.slice();
// reverseMinimal.reverse();
// reverseMinimal = this._computeSmallestCommonTypes(node, reverseMinimal);
// // Only use reverse minimal if smaller.
// if (reverseMinimal.length < minimal.length) {
// minimal = reverseMinimal;
// }
if (minimal.length === 1) {
return minimal[0];
}
return JsigAST.union(minimal);
};
ASTVerifier.prototype._computeSmallestCommonTypes =
function _computeSmallestCommonTypes(node, list) {
var minimal = [];
for (var i = 0; i < list.length; i++) {
var sample = list[i];
var toAdd = sample;
for (var j = 0; j < minimal.length; j++) {
if (isSameType(sample, minimal[j])) {
toAdd = null;
break;
}
/* if a super type of the other then remove from union */
// TODO: this seems so naive...
var isSuper = this.meta.isSubType(node, minimal[j], sample);
if (isSuper) {
toAdd = null;
break;
}
}
if (toAdd) {
minimal.push(toAdd);
}
}
return minimal;
};
function addPossibleType(list, maybeType) {
if (!maybeType) {
return;
}
if (maybeType.type !== 'unionType') {
list.push(maybeType);
return;
}
for (var i = 0; i < maybeType.unions.length; i++) {
list.push(maybeType.unions[i]);
}
}
// hoisting function declarations to the bottom makes the tree
// order algorithm simpler
function splitFunctionDeclaration(nodes) {
var result = {
functions: [],
statements: []
};
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].type !== 'FunctionDeclaration') {
result.statements.push(nodes[i]);
}
}
for (i = 0; i < nodes.length; i++) {
if (nodes[i].type === 'FunctionDeclaration') {
result.functions.push(nodes[i]);
}
}
return result;
}
| bug: remove double exitFunctionScope()
| type-checker/ast-verifier.js | bug: remove double exitFunctionScope() | <ide><path>ype-checker/ast-verifier.js
<ide> };
<ide>
<ide> ASTVerifier.prototype._checkFunctionType =
<del>function checkFunctionType(node, defn) {
<add>function _checkFunctionType(node, defn) {
<ide> this.meta.enterFunctionScope(node, defn);
<ide>
<ide> this._verifyFunctionType(node, defn);
<ide> line: node.loc.start.line
<ide> });
<ide> this.meta.addError(err);
<del> this.meta.exitFunctionScope();
<ide> return;
<ide> } else if (node.params.length < defn.args.length) {
<ide> err = Errors.TooFewArgsInFunc({
<ide> line: node.loc.start.line
<ide> });
<ide> this.meta.addError(err);
<del> this.meta.exitFunctionScope();
<ide> return;
<ide> }
<ide> |
|
JavaScript | apache-2.0 | 3974e382f97f65e5d3580d8531d49ce32d7e9ab0 | 0 | vingiarrusso/angular,jrote1/angular,TedSander/angular,tkarling/angular,githuya/angular,danielrasmuson/angular,leszczynski-it/angular,jackyxhb/angular,yjbanov/angular,angularbrasil/angular,kwalrath/angular,ochafik/angular,Stivfk/angular,robertmesserle/angular,Mathou54/angular,atcastle/angular,Zagorakiss/angular,pedroha/angular,Jandersoft/angular,UIUXEngineering-Forks/angular,Shawn-Cao/angular,kara/angular,cazacugmihai/angular,vebin/angular,redcom/angular,chrisse27/angular,kevhuang/angular,vandres/angular,gdi2290/angular,Zex/angular,rsy210/angular,rvanmarkus/angular,mrngoitall/angular,kormik/angular,mlynch/angular,skyFi/angular,vebin/angular,gastrodia/angular,StacyGay/angular,Nijikokun/angular,zzo/angular,redcom/angular,ocombe/angular,ttowncompiled/angular,mrngoitall/angular,prakal/angular,joshkurz/angular,opui/angular,PandaJJ5286/angular,ludamad/angular,juristr/angular,totzyuta/angular,mdegoo/angular,markharding/angular,thomaswmanion/angular,ctonerich/angular,nosachamos/angular,pocketmax/angular,Krishna-teja/angular,Mathou54/angular,PascalPrecht/angular,mprobst/angular,jesperronn/angular,getshuvo/angular,Jandersoft/angular,alamgird/angular,UIUXEngineering-Forks/angular,dsebastien/angular,hitesh97/angular-1,weswigham/angular,totzyuta/angular,jackyxhb/angular,bkyarger/angular,emanziano/angular,hswolff/angular,HAMM3R67/angular,lakhvinderit/angular,Zex/angular,caffeinetiger/angular,rixrix/angular,panuruj/angular,kormik/angular,robwormald/angular,HAMM3R67/angular,mgcrea/angular,Bogatinov/angular,dmitriz/angular,arosenberg01/angular,itslenny/angular,hbiao68/angular,Zyzle/angular,synaptek/angular,edwinlin1987/angular,ollie314/angular,shairez/angular,vinagreti/angular,hess-google/angular,naomiblack/angular,vsavkin/angular,ollie314/angular,nosachamos/angular,itamark/angular,tapas4java/angular,abdulsattar/angular,huoxudong125/angular,aboveyou00/angular,souldreamer/angular,Nijikokun/angular,leszczynski-it/angular,Flounn/angular,SekibOmazic/angular,stonegithubs/angular,StacyGay/angular,diestrin/angular,tapas4java/angular,cyrilgandon/angular,caffeinetiger/angular,angular-indonesia/angular,zhangdhu/angular,kevhuang/angular,rainabba/angular,aboveyou00/angular,mzgol/angular,HenriqueLimas/angular,DavidSouther/angular,synaptek/angular,jelbourn/angular,yanivefraim/angular,jesperronn/angular,nishants/angular,gilamran/angular,stevemao/angular,PandaJJ5286/angular,Litor/angular,jiangbophd/angular,MrChristofferson/angular,mdegoo/angular,alexcastillo/angular,UIUXEngineering/angular,alexcastillo/angular,wKoza/angular,ValtoFrameworks/Angular-2,alamgird/angular,thomaswmanion/angular,dmitriz/angular,gfogle/angular,youdz/angular,goderbauer/angular,dejour/angular,abdulsattar/angular,vamsivarikuti/angular,skyFi/angular,rainabba/angular,mgiambalvo/angular,erictsangx/angular,jrote1/angular,jhonmike/angular,royling/angular,hbiao68/angular,chadqueen/angular,rafacm/angular,tamdao/angular,chrisse27/angular,dydek/angular,kegluneq/angular,jack4dev/angular,jesperronn/angular,vebin/angular,vamsivarikuti/angular,dydek/angular,awerlang/angular,lavinjj/angular,willseeyou/angular,rafacm/angular,CarrieKroutil/angular,robertmesserle/angular,SaltyDH/angular,dapperAuteur/angular,pk-karthik/framework-js-angular,micmro/angular,andreloureiro/angular,pedroha/angular,justinfagnani/angular,ochafik/angular,shubham13jain/angular,cironunes/angular,srawlins/angular,rbevers/angular,arosenberg01/angular,lfryc/angular,shahata/angular,MrChristofferson/angular,SaltyDH/angular,devmark/angular,snaptech/angular,phillipalexander/angular,markharding/angular,zolfer/angular,nosovk/angular,gjungb/angular,mbrukman/angular,Mariem-07/angular,LucasSloan/angular,rainabba/angular,ericmartinezr/angular,UIUXEngineering-Forks/angular,mikeybyker/angular,hpinsley/angular,Tragetaschen/angular,devmark/angular,blesh/angular,yjbanov/angular,ScottSWu/angular,wesleycho/angular,lakhvinderit/angular,chrisse27/angular,PascalPrecht/angular,MikeRyan52/angular,SaltyDH/angular,hannahhoward/angular,atcastle/angular,lavinjj/angular,cloud-envy/angular-1,phillipalexander/angular,opui/angular,Brocco/angular,chalin/angular,hbiao68/angular,gastrodia/angular,CarrieKroutil/angular,resalisbury/angular,vicb/angular,souvikbasu/angular,lavinjj/angular,UIUXEngineering/angular,Toxicable/angular,danielrasmuson/angular,markharding/angular,mixed/angular,StacyGay/angular,hansl/angular,getshuvo/angular,robwormald/angular,tamascsaba/angular,zhura/angular,aaron-goshine/angular,hpinsley/angular,nickwhite917/angular,mdegoo/angular,ludonasc/angular,graveto/angular,alexeagle/angular,hdeshev/angular,jiangbophd/angular,shuhei/angular,ericmdantas/angular,tycho01/angular,justinfagnani/angular,sarunint/angular,keertip/angular,ning-github/angular,nosovk/angular,dsebastien/angular,markharding/angular,chadqueen/angular,rjamet/angular,jiangbophd/angular,lfryc/angular,hess-google/angular,ZackBotkin/angular,emanziano/angular,UIUXEngineering/angular,ScottSWu/angular,gnomeontherun/angular,Mariem-07/angular,calcyan/angular,gionkunz/angular,lijianguang/angular,lifus/angular,wKoza/angular,vinagreti/angular,jrote1/angular,mdegoo/angular,rvanmarkus/angular,alexpods/angular,vingiarrusso/angular,ludamad/angular,basvandenheuvel/angular,ning-github/angular,itamar-Cohen/angular,bbss/angular,jasonaden/angular,vebin/angular,Jandersoft/angular,fatooo0116/angular,panuruj/angular,simpulton/angular,meeroslav/angular,wesleycho/angular,GistIcon/angular,hitesh97/angular-1,ludonasc/angular,ajoslin/angular,jeremymwells/angular,zdddrszj/angular,jimgong92/angular,matsko/angular,jteplitz602/angular,matsko/angular,caffeinetiger/angular,kevhuang/angular,boxman0617/angular,ludonasc/angular,zolfer/angular,epotvin/angular,lakhvinderit/angular,justinfagnani/angular,gdi2290/angular,jimgong92/angular,asnowwolf/angular,aboveyou00/angular,zhura/angular,Tragetaschen/angular,stevemao/angular,alexeagle/angular,jack4dev/angular,bartkeizer/angular,ocombe/angular,jhonmike/angular,itamar-Cohen/angular,simpulton/angular,skyFi/angular,souvikbasu/angular,rainabba/angular,rbevers/angular,fatooo0116/angular,danielxiaowxx/angular,nickwhite917/angular,lijianguang/angular,vicb/angular,rjamet/angular,nosachamos/angular,mhevery/angular,hess-g/angular,mohislm/angular,panuruj/angular,smartm0use/angular,rkirov/angular,emanziano/angular,lifus/angular,ericmartinezr/angular,HenriqueLimas/angular,jteplitz602/angular,vamsivarikuti/angular,stonegithubs/angular,danielxiaowxx/angular,alexpods/angular,asnowwolf/angular,shubham13jain/angular,blesh/angular,mwringe/angular,justinfagnani/angular,Alireza-Dezfoolian/angular,opui/angular,trshafer/angular,Nijikokun/angular,willseeyou/angular,bbss/angular,simpulton/angular,Zyzle/angular,danielxiaowxx/angular,Brocco/angular,choeller/angular,ttowncompiled/angular,brandonroberts/angular,hterkelsen/angular,githuya/angular,bartkeizer/angular,emailnitram/angular,tamdao/angular,e-schultz/angular,alfonso-presa/angular,pk-karthik/framework-js-angular,smartm0use/angular,kara/angular,ScottSWu/angular,JanStureNielsen/angular,btford/angular,leszczynski-it/angular,SekibOmazic/angular,sarunint/angular,tapas4java/angular,LucasSloan/angular,pkozlowski-opensource/angular,kegluneq/angular,mhevery/angular,heathkit/angular,hannahhoward/angular,vandres/angular,zdddrszj/angular,andreloureiro/angular,TedSander/angular,erictsangx/angular,prakal/angular,Diaosir/angular,kormik/angular,shirish87/angular,lyip1992/angular,CarrieKroutil/angular,domusofsail/angular,githuya/angular,prakal/angular,angular-indonesia/angular,hswolff/angular,Diaosir/angular,nickwhite917/angular,linlincat/angular,opui/angular,snaptech/angular,alamgird/angular,juristr/angular,mgiambalvo/angular,ocombe/angular,juliemr/angular,ericmdantas/angular,garora/angular,IgorMinar/angular,jelbourn/angular,stephenhuh/angular,matsko/angular,jackyxhb/angular,rsy210/angular,jesperronn/angular,tycho01/angular,calcyan/angular,rsy210/angular,fredericksilva/angular2.0,jrote1/angular,Alireza-Dezfoolian/angular,nishant8BITS/angular,laskoviymishka/angular,juleskremer/angular,Jandersolutions/angular,heathkit/angular,jiangbophd/angular,wKoza/angular,rkirov/angular,ludonasc/angular,mixed/angular,ocombe/angular,simpulton/angular,UIUXEngineering/angular,snidima/angular,royling/angular,robrich/angular,gfogle/angular,itslenny/angular,thomaswmanion/angular,domusofsail/angular,mgechev/angular,Litor/angular,JSMike/angular,snidima/angular,IgorMinar/angular,chajath/angular,hdeshev/angular,hterkelsen/angular,ghetolay/angular,youdz/angular,phillipalexander/angular,asnowwolf/angular,Jandersolutions/angular,alfonso-presa/angular,arosenberg01/angular,vicb/angular,devmark/angular,JSMike/angular,naomiblack/angular,mgol/angular,manekinekko/angular,NathanWalker/angular,mhegazy/angular,micmro/angular,ScottSWu/angular,dydek/angular,nosachamos/angular,IgorMinar/angular,kevinmerckx/angular,hitesh97/angular-1,vsavkin/angular,Krishna-teja/angular,yanivefraim/angular,basvandenheuvel/angular,jack4dev/angular,sarunint/angular,tkarling/angular,ctonerich/angular,juleskremer/angular,awerlang/angular,garora/angular,chadqueen/angular,mixpanel-platform/angular,blesh/angular,lakhvinderit/angular,hswolff/angular,nosovk/angular,tbosch/angular,fanzetao/angular,mgol/angular,ochafik/angular,srawlins/angular,emailnitram/angular,Zex/angular,kormik/angular,nosovk/angular,dtoroshin/n2oDoc,davedx/angular,lfryc/angular,vikerman/angular,totzyuta/angular,mdegoo/angular,microlv/angular,jeremymwells/angular,Litor/angular,skyFi/angular,dapperAuteur/angular,rvanmarkus/angular,laco0416/angular,cexbrayat/angular,amarth1982/angular,vamsivarikuti/angular,SebastianM/angular,wcjohnson11/angular,Alireza-Dezfoolian/angular,githuya/angular,goderbauer/angular,AlmogShaul/angular,petebacondarwin/angular,ultrasonicsoft/angular,jackyxhb/angular,laskoviymishka/angular,arosenberg01/angular,rjamet/angular,sjtrimble/angular,boxman0617/angular,emailnitram/angular,MrChristofferson/angular,thomaswmanion/angular,Shawn-Cao/angular,mgechev/angular,brandonroberts/angular,danielxiaowxx/angular,ScottSWu/angular,Mathou54/angular,shubham13jain/angular,chajath/angular,jeremymwells/angular,HAMM3R67/angular,tapas4java/angular,mlaval/angular,wesleycho/angular,cassand/angular,dsebastien/angular,hterkelsen/angular,dsebastien/angular,martinmcwhorter/angular,bbss/angular,kevinmerckx/angular,itamark/angular,jonrimmer/angular,pk-karthik/framework-js-angular,mlynch/angular,lijianguang/angular,rixrix/angular,simpulton/angular,rixrix/angular,jeremymwells/angular,angularbrasil/angular,danielrasmuson/angular,MetSystem/angular,SekibOmazic/angular,pk-karthik/framework-js-angular,StephenFluin/angular,mlaval/angular,nosachamos/angular,IAPark/angular,Brocco/angular,NathanWalker/angular,mhegazy/angular,jesperronn/angular,itslenny/angular,ollie314/angular,bkyarger/angular,hankduan/angular,kevinmerckx/angular,rafacm/angular,basvandenheuvel/angular,lifus/angular,andreloureiro/angular,hess-g/angular,ollie314/angular,Bogatinov/angular,atcastle/angular,dapperAuteur/angular,basvandenheuvel/angular,gilamran/angular,aaron-goshine/angular,souldreamer/angular,meeroslav/angular,mwringe/angular,chrisse27/angular,fanzetao/angular,cexbrayat/angular,Toxicable/angular,xcaliber-tech/angular,filipesilva/angular,kylecordes/angular,Vam85/angular,laskoviymishka/angular,gionkunz/angular,alexeagle/angular,Jandersoft/angular,nishant8BITS/angular,hdeshev/angular,Zyzle/angular,mzgol/angular,nosovk/angular,basvandenheuvel/angular,itamar-Cohen/angular,hansl/angular,martinmcwhorter/angular,tyleranton/angular,souldreamer/angular,amitevski/angular,hdeshev/angular,Zagorakiss/angular,ludonasc/angular,gjungb/angular,vikerman/angular,calcyan/angular,royling/angular,chajath/angular,boxman0617/angular,MyoungJin/angular,jeremymwells/angular,mohislm/angular,shirish87/angular,atcastle/angular,redcom/angular,petebacondarwin/angular,stephenhuh/angular,cloud-envy/angular-1,manekinekko/angular,awerlang/angular,juristr/angular,mhegazy/angular,ghetolay/angular,epotvin/angular,tyleranton/angular,jeremymwells/angular,cyrilgandon/angular,mikeybyker/angular,ghetolay/angular,Toxicable/angular,LucasSloan/angular,cironunes/angular,metasong/angular,MetSystem/angular,rbevers/angular,Stivfk/angular,cassand/angular,kylecordes/angular,lfryc/angular,jonrimmer/angular,mrngoitall/angular,pocketmax/angular,linginging/angular,pedroha/angular,tbosch/angular,hankduan/angular,dtoroshin/n2oDoc,HenriqueLimas/angular,kevhuang/angular,StacyGay/angular,stevemao/angular,antonmoiseev/angular,aaron-goshine/angular,abdulsattar/angular,yjbanov/angular,mlynch/angular,pkozlowski-opensource/angular,hess-google/angular,xcaliber-tech/angular,cyrilgandon/angular,manekinekko/angular,jteplitz602/angular,gnomeontherun/angular,vsavkin/angular,shahata/angular,wcjohnson11/angular,btford/angular,diestrin/angular,gdi2290/angular,Mariem-07/angular,kevhuang/angular,alexcastillo/angular,cyrilgandon/angular,Stivfk/angular,robwormald/angular,rainabba/angular,robrich/angular,jonrimmer/angular,robwormald/angular,LucasSloan/angular,dsebastien/angular,thomaswmanion/angular,JSMike/angular,kwalrath/angular,Tragetaschen/angular,ericmdantas/angular,stephenhuh/angular,laskoviymishka/angular,gionkunz/angular,vamsivarikuti/angular,weswigham/angular,pedroha/angular,shubham13jain/angular,mzgol/angular,ctonerich/angular,shahata/angular,mgiambalvo/angular,awerlang/angular,angular/angular,shirish87/angular,filipesilva/angular,huoxudong125/angular,ultrasonicsoft/angular,mlaval/angular,mixed/angular,hpinsley/angular,zzo/angular,bkyarger/angular,alfonso-presa/angular,vinagreti/angular,jonrimmer/angular,rkho/angular,Symagic/angular,hansl/angular,chajath/angular,microlv/angular,shuhei/angular,Zagorakiss/angular,mhegazy/angular,huoxudong125/angular,amarth1982/angular,keertip/angular,laco0416/angular,SebastianM/angular,calcyan/angular,PascalPrecht/angular,rsy210/angular,mrngoitall/angular,CarrieKroutil/angular,ghetolay/angular,microlv/angular,Litor/angular,jun880529/angular,yanivefraim/angular,mgiambalvo/angular,danielrasmuson/angular,martinmcwhorter/angular,vingiarrusso/angular,robertmesserle/angular,alxhub/angular,githuya/angular,huoxudong125/angular,vikerman/angular,danielxiaowxx/angular,petebacondarwin/angular,jasonaden/angular,GistIcon/angular,Vam85/angular,oaleynik/angular,UIUXEngineering-Forks/angular,MikeRyan52/angular,trshafer/angular,micmro/angular,jack4dev/angular,cyrilgandon/angular,Bogatinov/angular,cloud-envy/angular-1,skyFi/angular,angularbrasil/angular,jelbourn/angular,tycho01/angular,ning-github/angular,mbrukman/angular,vingiarrusso/angular,resalisbury/angular,Nijikokun/angular,rvanmarkus/angular,zdddrszj/angular,shuhei/angular,sjtrimble/angular,gfogle/angular,jun880529/angular,fanzetao/angular,JSMike/angular,oaleynik/angular,Krishna-teja/angular,kylecordes/angular,Diaosir/angular,petebacondarwin/angular,nishant8BITS/angular,graveto/angular,GistIcon/angular,mgechev/angular,edwinlin1987/angular,chadqueen/angular,dapperAuteur/angular,zzo/angular,wesleycho/angular,kwalrath/angular,royling/angular,royling/angular,mikeybyker/angular,itslenny/angular,kwalrath/angular,andreloureiro/angular,IdeaBlade/angular,emanziano/angular,mhegazy/angular,SebastianM/angular,MyoungJin/angular,PascalPrecht/angular,Zyzle/angular,gfogle/angular,ludamad/angular,wcjohnson11/angular,vinagreti/angular,snaptech/angular,lsobiech/angular,mhevery/angular,srawlins/angular,Jandersolutions/angular,andreloureiro/angular,youdz/angular,JanStureNielsen/angular,Jandersoft/angular,angular/angular,hswolff/angular,boxman0617/angular,sarunint/angular,weswigham/angular,nishant8BITS/angular,mwringe/angular,StacyGay/angular,mohislm/angular,rvanmarkus/angular,domusofsail/angular,MyoungJin/angular,zhura/angular,tycho01/angular,bartkeizer/angular,emailnitram/angular,Litor/angular,Symagic/angular,trshafer/angular,hannahhoward/angular,e-hein/angular,allel/angular,NathanWalker/angular,robwormald/angular,ludamad/angular,Stivfk/angular,vicb/angular,cexbrayat/angular,tkarling/angular,mhevery/angular,shahata/angular,kevinmerckx/angular,angular/angular,getshuvo/angular,hansl/angular,emanziano/angular,DavidSouther/angular,shirish87/angular,hterkelsen/angular,juristr/angular,alfonso-presa/angular,ludonasc/angular,tamdao/angular,TedSander/angular,trshafer/angular,tbosch/angular,jun880529/angular,hess-google/angular,robertmesserle/angular,bbss/angular,graveto/angular,jack4dev/angular,linginging/angular,jabbrass/angular,shirish87/angular,cassand/angular,youdz/angular,gilamran/angular,sjtrimble/angular,alexeagle/angular,ValtoFrameworks/Angular-2,hpinsley/angular,alexpods/angular,Krishna-teja/angular,prakal/angular,angularbrasil/angular,JustinBeaudry/angular,jasonaden/angular,githuya/angular,zolfer/angular,laskoviymishka/angular,ZackBotkin/angular,jhonmike/angular,jonrimmer/angular,petebacondarwin/angular,graveto/angular,shuhei/angular,jack4dev/angular,mhevery/angular,dmitriz/angular,laco0416/angular,Flounn/angular,itamark/angular,juliemr/angular,mixpanel-platform/angular,srawlins/angular,ZackBotkin/angular,mgol/angular,rafacm/angular,zzo/angular,ericmartinezr/angular,e-schultz/angular,ericmdantas/angular,rjamet/angular,templth/angular,juristr/angular,souldreamer/angular,lavinjj/angular,jackyxhb/angular,cassand/angular,Mathou54/angular,microlv/angular,m18/angular,asnowwolf/angular,rixrix/angular,robertmesserle/angular,ZackBotkin/angular,cironunes/angular,rafacm/angular,wesleycho/angular,snidima/angular,mprobst/angular,resalisbury/angular,Litor/angular,atcastle/angular,mixed/angular,davedx/angular,zhangdhu/angular,m18/angular,heathkit/angular,abdulsattar/angular,choeller/angular,chadqueen/angular,yanivefraim/angular,meeroslav/angular,zhangdhu/angular,ning-github/angular,dmitriz/angular,chuckjaz/angular,itamark/angular,angular-indonesia/angular,garora/angular,chalin/angular,jabbrass/angular,yjbanov/angular,juleskremer/angular,shubham13jain/angular,jun880529/angular,CarrieKroutil/angular,IAPark/angular,alexcastillo/angular,alexeagle/angular,juristr/angular,tolemac/angular,ericmartinezr/angular,mixpanel-platform/angular,JanStureNielsen/angular,mgcrea/angular,vandres/angular,micmro/angular,MetSystem/angular,jrote1/angular,jimgong92/angular,TedSander/angular,keertip/angular,edwinlin1987/angular,rixrix/angular,e-schultz/angular,nishant8BITS/angular,hansl/angular,microlv/angular,opui/angular,xcaliber-tech/angular,Symagic/angular,alexeagle/angular,jabbrass/angular,mbrukman/angular,lsobiech/angular,edwinlin1987/angular,yanivefraim/angular,leszczynski-it/angular,pocketmax/angular,lsobiech/angular,emailnitram/angular,zhangdhu/angular,willseeyou/angular,fatooo0116/angular,cazacugmihai/angular,angular-indonesia/angular,Symagic/angular,pkozlowski-opensource/angular,brandonroberts/angular,mprobst/angular,metasong/angular,hankduan/angular,m18/angular,ttowncompiled/angular,cassand/angular,TedSander/angular,mlynch/angular,not-for-me/angular,Flounn/angular,gnomeontherun/angular,rkho/angular,xcaliber-tech/angular,graveto/angular,skyFi/angular,tamascsaba/angular,Bogatinov/angular,Zagorakiss/angular,stephenhuh/angular,gionkunz/angular,nishants/angular,heathkit/angular,boxman0617/angular,Symagic/angular,allel/angular,zolfer/angular,dtoroshin/n2oDoc,mgcrea/angular,heathkit/angular,lyip1992/angular,lyip1992/angular,lsobiech/angular,mgcrea/angular,srawlins/angular,aboveyou00/angular,ochafik/angular,Krishna-teja/angular,caffeinetiger/angular,amitevski/angular,domusofsail/angular,IAPark/angular,IdeaBlade/angular,MikeRyan52/angular,ajoslin/angular,tolemac/angular,mixed/angular,ochafik/angular,wcjohnson11/angular,emanziano/angular,choeller/angular,graveto/angular,mlaval/angular,tolemac/angular,alexcastillo/angular,pkdevbox/angular,vikerman/angular,allel/angular,vinagreti/angular,mprobst/angular,ning-github/angular,Tragetaschen/angular,MrChristofferson/angular,hbiao68/angular,lyip1992/angular,hansl/angular,bkyarger/angular,souvikbasu/angular,rkirov/angular,kevhuang/angular,GistIcon/angular,zhangdhu/angular,kegluneq/angular,pkdevbox/angular,aboveyou00/angular,zdddrszj/angular,fredericksilva/angular2.0,jun880529/angular,smartm0use/angular,meeroslav/angular,cazacugmihai/angular,btford/angular,ericmdantas/angular,hannahhoward/angular,aaron-goshine/angular,gkalpak/angular,zhura/angular,e-schultz/angular,Jandersolutions/angular,tyleranton/angular,willseeyou/angular,laco0416/angular,mgol/angular,kevinmerckx/angular,nishants/angular,ZackBotkin/angular,chuckjaz/angular,lfryc/angular,mgechev/angular,snidima/angular,Alireza-Dezfoolian/angular,juliemr/angular,jabbrass/angular,ajoslin/angular,Shawn-Cao/angular,btford/angular,naomiblack/angular,DavidSouther/angular,mzgol/angular,epotvin/angular,rsy210/angular,brandonroberts/angular,metasong/angular,fredericksilva/angular2.0,robrich/angular,HenriqueLimas/angular,cassand/angular,StacyGay/angular,keertip/angular,chuckjaz/angular,wKoza/angular,zzo/angular,alamgird/angular,ludamad/angular,nishant8BITS/angular,tycho01/angular,gkalpak/angular,tolemac/angular,vikerman/angular,metasong/angular,alexpods/angular,Alireza-Dezfoolian/angular,JiaLiPassion/angular,ocombe/angular,zhura/angular,jhonmike/angular,erictsangx/angular,Toxicable/angular,garora/angular,youdz/angular,gkalpak/angular,mlynch/angular,ValtoFrameworks/Angular-2,alxhub/angular,HenriqueLimas/angular,lifus/angular,MyoungJin/angular,mgol/angular,lfryc/angular,JustinBeaudry/angular,pkozlowski-opensource/angular,Zyzle/angular,garora/angular,SekibOmazic/angular,UIUXEngineering-Forks/angular,hannahhoward/angular,jelbourn/angular,gfogle/angular,prakal/angular,hdeshev/angular,kyroskoh/angular,gkalpak/angular,robrich/angular,JustinBeaudry/angular,ttowncompiled/angular,fatooo0116/angular,MyoungJin/angular,bkyarger/angular,IAPark/angular,erictsangx/angular,cyrilgandon/angular,robertmesserle/angular,jimgong92/angular,mdegoo/angular,lifus/angular,brandonroberts/angular,LucasSloan/angular,Zex/angular,ScottSWu/angular,cexbrayat/angular,rafacm/angular,Flounn/angular,dapperAuteur/angular,aaron-goshine/angular,filipesilva/angular,ctonerich/angular,synaptek/angular,markharding/angular,Stivfk/angular,edwinlin1987/angular,itamar-Cohen/angular,epotvin/angular,not-for-me/angular,stonegithubs/angular,nosachamos/angular,alexpods/angular,pkozlowski-opensource/angular,zhangdhu/angular,nishants/angular,angularbrasil/angular,Diaosir/angular,Tragetaschen/angular,pkdevbox/angular,pocketmax/angular,Zex/angular,gastrodia/angular,NathanWalker/angular,linginging/angular,hterkelsen/angular,rbevers/angular,kyroskoh/angular,dejour/angular,zhura/angular,davedx/angular,matsko/angular,metasong/angular,wcjohnson11/angular,linlincat/angular,MikeRyan52/angular,IgorMinar/angular,weswigham/angular,Toxicable/angular,Alireza-Dezfoolian/angular,pkdevbox/angular,SebastianM/angular,mlaval/angular,zzo/angular,mohislm/angular,kara/angular,StephenFluin/angular,snidima/angular,pedroha/angular,tyleranton/angular,Tragetaschen/angular,nishants/angular,lifus/angular,naomiblack/angular,nickwhite917/angular,hannahhoward/angular,hess-google/angular,robrich/angular,amarth1982/angular,pocketmax/angular,rkirov/angular,hitesh97/angular-1,DavidSouther/angular,NathanWalker/angular,rbevers/angular,dapperAuteur/angular,JustinBeaudry/angular,ericmdantas/angular,Nijikokun/angular,kylecordes/angular,gdi2290/angular,wcjohnson11/angular,ericmartinezr/angular,manekinekko/angular,MetSystem/angular,angular/angular,kylecordes/angular,cloud-envy/angular-1,chuckjaz/angular,choeller/angular,amitevski/angular,andreloureiro/angular,MetSystem/angular,Nijikokun/angular,tbosch/angular,redcom/angular,dejour/angular,jasonaden/angular,not-for-me/angular,garora/angular,TedSander/angular,robrich/angular,GistIcon/angular,tamascsaba/angular,NathanWalker/angular,alamgird/angular,IAPark/angular,mprobst/angular,caffeinetiger/angular,rsy210/angular,goderbauer/angular,gilamran/angular,hbiao68/angular,shairez/angular,vsavkin/angular,dejour/angular,mlynch/angular,IAPark/angular,epotvin/angular,mrngoitall/angular,linlincat/angular,kylecordes/angular,jelbourn/angular,vingiarrusso/angular,gilamran/angular,JiaLiPassion/angular,zdddrszj/angular,juleskremer/angular,getshuvo/angular,allel/angular,jabbrass/angular,ning-github/angular,hbiao68/angular,bartkeizer/angular,alxhub/angular,kyroskoh/angular,cironunes/angular,goderbauer/angular,gjungb/angular,mixed/angular,erictsangx/angular,Vam85/angular,getshuvo/angular,SaltyDH/angular,amarth1982/angular,gjungb/angular,itamar-Cohen/angular,hess-g/angular,jhonmike/angular,alxhub/angular,JiaLiPassion/angular,Mariem-07/angular,robwormald/angular,gastrodia/angular,pkdevbox/angular,vandres/angular,chadqueen/angular,kara/angular,tyleranton/angular,snidima/angular,jackyxhb/angular,tyleranton/angular,fanzetao/angular,mprobst/angular,Zagorakiss/angular,synaptek/angular,chalin/angular,hankduan/angular,youdz/angular,dydek/angular,dydek/angular,kyroskoh/angular,leszczynski-it/angular,Vam85/angular,pk-karthik/framework-js-angular,cloud-envy/angular-1,blesh/angular,vingiarrusso/angular,mwringe/angular,tamdao/angular,juleskremer/angular,manekinekko/angular,souvikbasu/angular,IdeaBlade/angular,amitevski/angular,ghetolay/angular,jhonmike/angular,ttowncompiled/angular,PascalPrecht/angular,joshkurz/angular,Vam85/angular,IgorMinar/angular,wesleycho/angular,snaptech/angular,mbrukman/angular,mixpanel-platform/angular,ochafik/angular,opui/angular,ultrasonicsoft/angular,petebacondarwin/angular,willseeyou/angular,gnomeontherun/angular,kyroskoh/angular,rkho/angular,AlmogShaul/angular,e-schultz/angular,epotvin/angular,jasonaden/angular,chuckjaz/angular,dtoroshin/n2oDoc,JustinBeaudry/angular,amarth1982/angular,wKoza/angular,ultrasonicsoft/angular,Shawn-Cao/angular,mzgol/angular,mikeybyker/angular,shairez/angular,laco0416/angular,naomiblack/angular,templth/angular,hitesh97/angular-1,asnowwolf/angular,kegluneq/angular,lyip1992/angular,blesh/angular,dmitriz/angular,UIUXEngineering-Forks/angular,laco0416/angular,Y-Less/angular,joshkurz/angular,chalin/angular,mzgol/angular,vebin/angular,hess-g/angular,chajath/angular,jimgong92/angular,antonmoiseev/angular,e-hein/angular,e-schultz/angular,JustinBeaudry/angular,mbrukman/angular,snaptech/angular,mwringe/angular,shahata/angular,allel/angular,kegluneq/angular,kevinmerckx/angular,oaleynik/angular,weswigham/angular,synaptek/angular,bartkeizer/angular,hankduan/angular,templth/angular,bartkeizer/angular,StephenFluin/angular,mikeybyker/angular,lyip1992/angular,matsko/angular,hess-google/angular,snaptech/angular,HenriqueLimas/angular,Y-Less/angular,PandaJJ5286/angular,shairez/angular,fatooo0116/angular,tkarling/angular,jrote1/angular,kwalrath/angular,shahata/angular,stevemao/angular,lsobiech/angular,shairez/angular,calcyan/angular,zolfer/angular,Shawn-Cao/angular,mgechev/angular,jiangbophd/angular,sjtrimble/angular,tbosch/angular,IgorMinar/angular,zolfer/angular,Mariem-07/angular,micmro/angular,cazacugmihai/angular,keertip/angular,chuckjaz/angular,davedx/angular,AlmogShaul/angular,sarunint/angular,choeller/angular,fredericksilva/angular2.0,awerlang/angular,mrngoitall/angular,devmark/angular,alexpods/angular,heathkit/angular,smartm0use/angular,StephenFluin/angular,alfonso-presa/angular,ollie314/angular,tamascsaba/angular,lijianguang/angular,meeroslav/angular,Shawn-Cao/angular,vicb/angular,shubham13jain/angular,martinmcwhorter/angular,mixpanel-platform/angular,ultrasonicsoft/angular,devmark/angular,Jandersoft/angular,gdi2290/angular,SekibOmazic/angular,nishants/angular,stonegithubs/angular,mhegazy/angular,abdulsattar/angular,rbevers/angular,jelbourn/angular,antonmoiseev/angular,kyroskoh/angular,antonmoiseev/angular,pkdevbox/angular,vikerman/angular,edwinlin1987/angular,markharding/angular,fredericksilva/angular2.0,microlv/angular,yjbanov/angular,stephenhuh/angular,hess-g/angular,gionkunz/angular,sjtrimble/angular,linginging/angular,oaleynik/angular,linlincat/angular,danielrasmuson/angular,fredericksilva/angular2.0,cazacugmihai/angular,StephenFluin/angular,joshkurz/angular,mgol/angular,huoxudong125/angular,danielrasmuson/angular,lijianguang/angular,souldreamer/angular,Y-Less/angular,kara/angular,jonrimmer/angular,JSMike/angular,JiaLiPassion/angular,ValtoFrameworks/Angular-2,phillipalexander/angular,not-for-me/angular,willseeyou/angular,oaleynik/angular,juliemr/angular,resalisbury/angular,rkirov/angular,SekibOmazic/angular,tapas4java/angular,cazacugmihai/angular,Brocco/angular,linginging/angular,choeller/angular,davedx/angular,tycho01/angular,erictsangx/angular,sarunint/angular,souvikbasu/angular,hpinsley/angular,templth/angular,mohislm/angular,Brocco/angular,juliemr/angular,martinmcwhorter/angular,justinfagnani/angular,Bogatinov/angular,MikeRyan52/angular,panuruj/angular,jteplitz602/angular,trshafer/angular,Stivfk/angular,e-hein/angular,simpulton/angular,aboveyou00/angular,linginging/angular,thomaswmanion/angular,itamar-Cohen/angular,vebin/angular,Y-Less/angular,rixrix/angular,alxhub/angular,rkho/angular,m18/angular,davedx/angular,tamascsaba/angular,m18/angular,getshuvo/angular,JanStureNielsen/angular,Mathou54/angular,dmitriz/angular,ValtoFrameworks/Angular-2,bkyarger/angular,caffeinetiger/angular,antonmoiseev/angular,gjungb/angular,Zyzle/angular,gionkunz/angular,rainabba/angular,tapas4java/angular,kormik/angular,SebastianM/angular,GistIcon/angular,dejour/angular,alexcastillo/angular,arosenberg01/angular,HAMM3R67/angular,brandonroberts/angular,wKoza/angular,weswigham/angular,itamark/angular,amarth1982/angular,phillipalexander/angular,Flounn/angular,arosenberg01/angular,m18/angular,manekinekko/angular,jimgong92/angular,cironunes/angular,xcaliber-tech/angular,PandaJJ5286/angular,e-hein/angular,oaleynik/angular,vandres/angular,aaron-goshine/angular,stevemao/angular,ocombe/angular,tolemac/angular,IdeaBlade/angular,angularbrasil/angular,Diaosir/angular,ludamad/angular,dtoroshin/n2oDoc,redcom/angular,jun880529/angular,lakhvinderit/angular,souldreamer/angular,mhevery/angular,jasonaden/angular,hterkelsen/angular,shuhei/angular,AlmogShaul/angular,MrChristofferson/angular,micmro/angular,lakhvinderit/angular,dsebastien/angular,pocketmax/angular,LucasSloan/angular,rvanmarkus/angular,totzyuta/angular,diestrin/angular,panuruj/angular,DavidSouther/angular,Y-Less/angular,gilamran/angular,btford/angular,martinmcwhorter/angular,rkho/angular,hpinsley/angular,AlmogShaul/angular,jteplitz602/angular,stonegithubs/angular,fanzetao/angular,UIUXEngineering/angular,IdeaBlade/angular,Y-Less/angular,shirish87/angular,yanivefraim/angular,lsobiech/angular,kegluneq/angular,amitevski/angular,emailnitram/angular,nickwhite917/angular,diestrin/angular,itslenny/angular,PandaJJ5286/angular,resalisbury/angular,yjbanov/angular,resalisbury/angular,gastrodia/angular,gdi2290/angular,metasong/angular,JanStureNielsen/angular,joshkurz/angular,kara/angular,tamascsaba/angular,lavinjj/angular,e-hein/angular,rkirov/angular,totzyuta/angular,rkho/angular,not-for-me/angular,Jandersolutions/angular,chrisse27/angular,hitesh97/angular-1,ultrasonicsoft/angular,redcom/angular,vsavkin/angular,vicb/angular,linlincat/angular,HAMM3R67/angular,huoxudong125/angular,tkarling/angular,filipesilva/angular,shuhei/angular,mgcrea/angular,goderbauer/angular,Jandersolutions/angular,Toxicable/angular,ajoslin/angular,ctonerich/angular,domusofsail/angular,mgiambalvo/angular,hdeshev/angular,nickwhite917/angular,hankduan/angular,Brocco/angular,prakal/angular,cexbrayat/angular,trshafer/angular,filipesilva/angular,antonmoiseev/angular,ttowncompiled/angular,jteplitz602/angular,smartm0use/angular,lijianguang/angular,hess-g/angular,SaltyDH/angular,alfonso-presa/angular,templth/angular,bbss/angular,Symagic/angular,itslenny/angular,hswolff/angular,phillipalexander/angular,tolemac/angular,jiangbophd/angular,ericmartinezr/angular,devmark/angular,tamdao/angular,basvandenheuvel/angular,cironunes/angular,jabbrass/angular | var gulp = require('gulp');
var gulpPlugins = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var merge = require('merge');
var gulpTraceur = require('./tools/transpiler/gulp-traceur');
var clean = require('./tools/build/clean');
var transpile = require('./tools/build/transpile');
var html = require('./tools/build/html');
var pubget = require('./tools/build/pubget');
var linknodemodules = require('./tools/build/linknodemodules');
var pubbuild = require('./tools/build/pubbuild');
var dartanalyzer = require('./tools/build/dartanalyzer');
var jsserve = require('./tools/build/jsserve');
var pubserve = require('./tools/build/pubserve');
var rundartpackage = require('./tools/build/rundartpackage');
var copy = require('./tools/build/copy');
var karma = require('karma').server;
var minimist = require('minimist');
var es5build = require('./tools/build/es5build');
var runServerDartTests = require('./tools/build/run_server_dart_tests');
var transformCJSTests = require('./tools/build/transformCJSTests');
var util = require('./tools/build/util');
var DART_SDK = require('./tools/build/dartdetect')(gulp);
// -----------------------
// configuration
var _COMPILER_CONFIG_JS_DEFAULT = {
sourceMaps: true,
annotations: true, // parse annotations
types: true, // parse types
script: false, // parse as a module
memberVariables: true, // parse class fields
modules: 'instantiate'
};
var _HTML_DEFAULT_SCRIPTS_JS = [
{src: gulpTraceur.RUNTIME_PATH, mimeType: 'text/javascript', copy: true},
{src: 'node_modules/es6-module-loader/dist/es6-module-loader-sans-promises.src.js',
mimeType: 'text/javascript', copy: true},
{src: 'node_modules/zone.js/zone.js', mimeType: 'text/javascript', copy: true},
{src: 'node_modules/zone.js/long-stack-trace-zone.js', mimeType: 'text/javascript', copy: true},
{src: 'node_modules/systemjs/dist/system.src.js', mimeType: 'text/javascript', copy: true},
{src: 'node_modules/systemjs/lib/extension-register.js', mimeType: 'text/javascript', copy: true},
{src: 'tools/build/snippets/runtime_paths.js', mimeType: 'text/javascript', copy: true},
{
inline: 'System.import(\'$MODULENAME$\').then(function(m) { m.main(); }, console.error.bind(console))',
mimeType: 'text/javascript'
}
];
var _HTML_DEFAULT_SCRIPTS_DART = [
{src: '$MODULENAME_WITHOUT_PATH$.dart', mimeType: 'application/dart'},
{src: 'packages/browser/dart.js', mimeType: 'text/javascript'}
];
var BASE_PACKAGE_JSON = require('./package.json');
var COMMON_PACKAGE_JSON = {
version: BASE_PACKAGE_JSON.version,
homepage: BASE_PACKAGE_JSON.homepage,
bugs: BASE_PACKAGE_JSON.bugs,
license: BASE_PACKAGE_JSON.license,
contributors: BASE_PACKAGE_JSON.contributors,
dependencies: BASE_PACKAGE_JSON.dependencies,
devDependencies: {
"yargs": BASE_PACKAGE_JSON.devDependencies['yargs'],
"gulp-sourcemaps": BASE_PACKAGE_JSON.devDependencies['gulp-sourcemaps'],
"gulp-traceur": BASE_PACKAGE_JSON.devDependencies['gulp-traceur'],
"gulp": BASE_PACKAGE_JSON.devDependencies['gulp'],
"gulp-rename": BASE_PACKAGE_JSON.devDependencies['gulp-rename'],
"through2": BASE_PACKAGE_JSON.devDependencies['through2']
}
};
var SRC_FOLDER_INSERTION = {
js: {
'**': ''
},
dart: {
'**': 'lib',
'*/test/**': '',
'benchmarks/**': 'web',
'benchmarks/test/**': '',
'benchmarks_external/**': 'web',
'benchmarks_external/test/**': '',
'example*/**': 'web',
'example*/test/**': ''
}
};
var CONFIG = {
dest: {
js: {
all: 'dist/js',
dev: {
es6: 'dist/js/dev/es6',
es5: 'dist/js/dev/es5'
},
prod: {
es6: 'dist/js/prod/es6',
es5: 'dist/js/prod/es5'
},
cjs: 'dist/js/cjs',
dart2js: 'dist/js/dart2js'
},
dart: 'dist/dart',
docs: 'dist/docs'
},
srcFolderInsertion: SRC_FOLDER_INSERTION,
transpile: {
src: {
js: ['modules/**/*.js', 'modules/**/*.es6'],
dart: ['modules/**/*.js']
},
options: {
js: {
dev: merge(true, _COMPILER_CONFIG_JS_DEFAULT, {
typeAssertionModule: 'rtts_assert/rtts_assert',
typeAssertions: true,
outputLanguage: 'es6'
}),
prod: merge(true, _COMPILER_CONFIG_JS_DEFAULT, {
typeAssertions: false,
outputLanguage: 'es6'
}),
cjs: merge(true, _COMPILER_CONFIG_JS_DEFAULT, {
typeAssertionModule: 'rtts_assert/rtts_assert',
typeAssertions: true,
modules: 'commonjs'
})
},
dart: {
sourceMaps: true,
annotations: true, // parse annotations
types: true, // parse types
script: false, // parse as a module
memberVariables: true, // parse class fields
outputLanguage: 'dart'
}
}
},
copy: {
js: {
cjs: {
src: ['modules/**/README.js.md', 'modules/**/package.json', 'modules/**/*.cjs'],
pipes: {
'**/*.cjs': gulpPlugins.rename({extname: '.js'}),
'**/*.js.md': gulpPlugins.rename(function(file) {
file.basename = file.basename.substring(0, file.basename.lastIndexOf('.'));
}),
'**/package.json': gulpPlugins.template({ 'packageJson': COMMON_PACKAGE_JSON })
}
},
dev: {
src: ['modules/**/*.css'],
pipes: {}
},
prod: {
src: ['modules/**/*.css'],
pipes: {}
}
},
dart: {
src: ['modules/**/README.dart.md', 'modules/**/*.dart', 'modules/*/pubspec.yaml', 'modules/**/*.css', '!modules/**/e2e_test/**'],
pipes: {
'**/*.dart': util.insertSrcFolder(gulpPlugins, SRC_FOLDER_INSERTION.dart),
'**/*.dart.md': gulpPlugins.rename(function(file) {
file.basename = file.basename.substring(0, file.basename.lastIndexOf('.'));
}),
'**/pubspec.yaml': gulpPlugins.template({ 'packageJson': COMMON_PACKAGE_JSON })
}
}
},
multicopy: {
js: {
cjs: {
src: [
'LICENSE'
],
pipes: {}
},
dev: {
es6: {
src: ['tools/build/es5build.js'],
pipes: {}
}
},
prod: {
es6: {
src: ['tools/build/es5build.js'],
pipes: {}
}
}
},
dart: {
src: ['LICENSE'],
exclude: ['rtts_assert/'],
pipes: {}
}
},
html: {
src: {
js: ['modules/*/src/**/*.html'],
dart: ['modules/*/src/**/*.html']
},
scriptsPerFolder: {
js: {
'**': _HTML_DEFAULT_SCRIPTS_JS,
'benchmarks/**':
[
{ src: 'tools/build/snippets/url_params_to_form.js', mimeType: 'text/javascript', copy: true }
].concat(_HTML_DEFAULT_SCRIPTS_JS),
'benchmarks_external/**':
[
{ src: 'node_modules/angular/angular.js', mimeType: 'text/javascript', copy: true },
{ src: 'tools/build/snippets/url_params_to_form.js', mimeType: 'text/javascript', copy: true }
].concat(_HTML_DEFAULT_SCRIPTS_JS)
},
dart: {
'**': _HTML_DEFAULT_SCRIPTS_DART,
'benchmarks*/**':
[
{ src: 'tools/build/snippets/url_params_to_form.js', mimeType: 'text/javascript', copy: true }
].concat(_HTML_DEFAULT_SCRIPTS_DART)
}
}
},
formatDart: {
packageName: 'dart_style',
args: ['dart_style:format', '-w', 'dist/dart']
},
test: {
js: {
cjs: [
'/angular2/test/core/compiler/**/*_spec.js',
'/angular2/test/directives/**/*_spec.js',
'/angular2/test/forms/**/*_spec.js'
]
}
}
};
CONFIG.test.js.cjs = CONFIG.test.js.cjs.map(function(s) {return CONFIG.dest.js.cjs + s});
// ------------
// clean
gulp.task('build/clean.js', clean(gulp, gulpPlugins, {
path: CONFIG.dest.js.all
}));
gulp.task('build/clean.dart', clean(gulp, gulpPlugins, {
path: CONFIG.dest.dart
}));
gulp.task('build/clean.docs', clean(gulp, gulpPlugins, {
path: CONFIG.dest.docs
}));
// ------------
// transpile
gulp.task('build/transpile.js.dev.es6', transpile(gulp, gulpPlugins, {
src: CONFIG.transpile.src.js,
dest: CONFIG.dest.js.dev.es6,
outputExt: 'es6',
options: CONFIG.transpile.options.js.dev,
srcFolderInsertion: CONFIG.srcFolderInsertion.js
}));
gulp.task('build/transpile.js.dev.es5', function() {
return es5build({
src: CONFIG.dest.js.dev.es6,
dest: CONFIG.dest.js.dev.es5,
modules: 'instantiate'
});
});
gulp.task('build/transpile.js.dev', function(done) {
runSequence(
'build/transpile.js.dev.es6',
'build/transpile.js.dev.es5',
done
);
});
gulp.task('build/transpile.js.prod.es6', transpile(gulp, gulpPlugins, {
src: CONFIG.transpile.src.js,
dest: CONFIG.dest.js.prod.es6,
outputExt: 'es6',
options: CONFIG.transpile.options.js.prod,
srcFolderInsertion: CONFIG.srcFolderInsertion.js
}));
gulp.task('build/transpile.js.prod.es5', function() {
return es5build({
src: CONFIG.dest.js.prod.es6,
dest: CONFIG.dest.js.prod.es5,
modules: 'instantiate'
});
});
gulp.task('build/transpile.js.prod', function(done) {
runSequence(
'build/transpile.js.prod.es6',
'build/transpile.js.prod.es5',
done
);
});
gulp.task('build/transpile.js.cjs', transpile(gulp, gulpPlugins, {
src: CONFIG.transpile.src.js.concat(['modules/**/*.cjs']),
dest: CONFIG.dest.js.cjs,
outputExt: 'js',
options: CONFIG.transpile.options.js.cjs,
srcFolderInsertion: CONFIG.srcFolderInsertion.js
}));
gulp.task('build/transformCJSTests', function() {
return gulp.src(CONFIG.dest.js.cjs + '/angular2/test/**/*_spec.js').pipe(transformCJSTests()).pipe(gulp.dest(CONFIG.dest.js.cjs + '/angular2/test/'));
});
gulp.task('build/transpile.dart', transpile(gulp, gulpPlugins, {
src: CONFIG.transpile.src.dart,
dest: CONFIG.dest.dart,
outputExt: 'dart',
options: CONFIG.transpile.options.dart,
srcFolderInsertion: CONFIG.srcFolderInsertion.dart
}));
// ------------
// html
gulp.task('build/html.js.dev', html(gulp, gulpPlugins, {
src: CONFIG.html.src.js,
dest: CONFIG.dest.js.dev.es5,
srcFolderInsertion: CONFIG.srcFolderInsertion.js,
scriptsPerFolder: CONFIG.html.scriptsPerFolder.js
}));
gulp.task('build/html.js.prod', html(gulp, gulpPlugins, {
src: CONFIG.html.src.js,
dest: CONFIG.dest.js.prod.es5,
srcFolderInsertion: CONFIG.srcFolderInsertion.js,
scriptsPerFolder: CONFIG.html.scriptsPerFolder.js
}));
gulp.task('build/html.dart', html(gulp, gulpPlugins, {
src: CONFIG.html.src.dart,
dest: CONFIG.dest.dart,
srcFolderInsertion: CONFIG.srcFolderInsertion.dart,
scriptsPerFolder: CONFIG.html.scriptsPerFolder.dart
}));
// ------------
// copy
gulp.task('build/copy.js.cjs', copy.copy(gulp, gulpPlugins, {
src: CONFIG.copy.js.cjs.src,
pipes: CONFIG.copy.js.cjs.pipes,
dest: CONFIG.dest.js.cjs
}));
gulp.task('build/copy.js.dev', copy.copy(gulp, gulpPlugins, {
src: CONFIG.copy.js.dev.src,
pipes: CONFIG.copy.js.dev.pipes,
dest: CONFIG.dest.js.dev.es5
}));
gulp.task('build/copy.js.prod', copy.copy(gulp, gulpPlugins, {
src: CONFIG.copy.js.prod.src,
pipes: CONFIG.copy.js.prod.pipes,
dest: CONFIG.dest.js.prod.es5
}));
gulp.task('build/copy.dart', copy.copy(gulp, gulpPlugins, {
src: CONFIG.copy.dart.src,
pipes: CONFIG.copy.dart.pipes,
dest: CONFIG.dest.dart
}));
// ------------
// multicopy
gulp.task('build/multicopy.js.cjs', copy.multicopy(gulp, gulpPlugins, {
src: CONFIG.multicopy.js.cjs.src,
pipes: CONFIG.multicopy.js.cjs.pipes,
exclude: CONFIG.multicopy.js.cjs.exclude,
dest: CONFIG.dest.js.cjs
}));
gulp.task('build/multicopy.js.dev.es6', copy.multicopy(gulp, gulpPlugins, {
src: CONFIG.multicopy.js.dev.es6.src,
pipes: CONFIG.multicopy.js.dev.es6.pipes,
exclude: CONFIG.multicopy.js.dev.es6.exclude,
dest: CONFIG.dest.js.dev.es6
}));
gulp.task('build/multicopy.js.prod.es6', copy.multicopy(gulp, gulpPlugins, {
src: CONFIG.multicopy.js.prod.es6.src,
pipes: CONFIG.multicopy.js.prod.es6.pipes,
exclude: CONFIG.multicopy.js.prod.es6.exclude,
dest: CONFIG.dest.js.prod.es6
}));
gulp.task('build/multicopy.dart', copy.multicopy(gulp, gulpPlugins, {
src: CONFIG.multicopy.dart.src,
pipes: CONFIG.multicopy.dart.pipes,
exclude: CONFIG.multicopy.dart.exclude,
dest: CONFIG.dest.dart
}));
// ------------
// pubspec
gulp.task('build/pubspec.dart', pubget(gulp, gulpPlugins, {
dir: CONFIG.dest.dart,
command: DART_SDK.PUB
}));
// ------------
// linknodemodules
gulp.task('build/linknodemodules.js.cjs', linknodemodules(gulp, gulpPlugins, {
dir: CONFIG.dest.js.cjs
}));
// ------------
// dartanalyzer
gulp.task('build/analyze.dart', dartanalyzer(gulp, gulpPlugins, {
dest: CONFIG.dest.dart,
command: DART_SDK.ANALYZER
}));
// ------------
// pubbuild
gulp.task('build/pubbuild.dart', pubbuild(gulp, gulpPlugins, {
src: CONFIG.dest.dart,
dest: CONFIG.dest.js.dart2js,
command: DART_SDK.PUB
}));
// ------------
// format dart
gulp.task('build/format.dart', rundartpackage(gulp, gulpPlugins, {
pub: DART_SDK.PUB,
packageName: CONFIG.formatDart.packageName,
args: CONFIG.formatDart.args
}));
// ------------------
// web servers
gulp.task('serve.js.dev', jsserve(gulp, gulpPlugins, {
path: CONFIG.dest.js.dev.es5,
port: 8000
}));
gulp.task('serve.js.prod', jsserve(gulp, gulpPlugins, {
path: CONFIG.dest.js.prod.es5,
port: 8001
}));
gulp.task('serve.js.dart2js', jsserve(gulp, gulpPlugins, {
path: CONFIG.dest.js.dart2js,
port: 8002
}));
gulp.task('serve/examples.dart', pubserve(gulp, gulpPlugins, {
command: DART_SDK.PUB,
path: CONFIG.dest.dart + '/examples'
}));
gulp.task('serve/benchmarks.dart', pubserve(gulp, gulpPlugins, {
command: DART_SDK.PUB,
path: CONFIG.dest.dart + '/benchmarks'
}));
gulp.task('serve/benchmarks_external.dart', pubserve(gulp, gulpPlugins, {
command: DART_SDK.PUB,
path: CONFIG.dest.dart + '/benchmarks_external'
}));
// --------------
// doc generation
var Dgeni = require('dgeni');
gulp.task('docs/dgeni', function() {
try {
var dgeni = new Dgeni([require('./docs/dgeni-package')]);
return dgeni.generate();
} catch(x) {
console.log(x.stack);
throw x;
}
});
var bower = require('bower');
gulp.task('docs/bower', function() {
var bowerTask = bower.commands.install(undefined, undefined, { cwd: 'docs' });
bowerTask.on('log', function (result) {
console.log('bower:', result.id, result.data.endpoint.name);
});
bowerTask.on('error', function(error) {
console.log(error);
});
return bowerTask;
});
gulp.task('docs/assets', ['docs/bower'], function() {
return gulp.src('docs/bower_components/**/*')
.pipe(gulp.dest('dist/docs/lib'));
});
gulp.task('docs/app', function() {
return gulp.src('docs/app/**/*')
.pipe(gulp.dest('dist/docs'));
});
gulp.task('docs', ['docs/assets', 'docs/app', 'docs/dgeni']);
gulp.task('docs/watch', function() {
return gulp.watch('docs/app/**/*', ['docs/app']);
});
var jasmine = require('gulp-jasmine');
gulp.task('docs/test', function () {
return gulp.src('docs/**/*.spec.js')
.pipe(jasmine({
includeStackTrace: true
}));
});
var webserver = require('gulp-webserver');
gulp.task('docs/serve', function() {
gulp.src('dist/docs/')
.pipe(webserver({
fallback: 'index.html'
}));
});
// ------------------
// karma tests
// These tests run in the browser and are allowed to access
// HTML DOM APIs.
function getBrowsersFromCLI() {
var args = minimist(process.argv.slice(2));
return [args.browsers?args.browsers:'DartiumWithWebPlatform']
}
gulp.task('test.unit.js', function (done) {
karma.start({configFile: __dirname + '/karma-js.conf.js'}, done);
});
gulp.task('test.unit.dart', function (done) {
karma.start({configFile: __dirname + '/karma-dart.conf.js'}, done);
});
gulp.task('test.unit.js/ci', function (done) {
karma.start({configFile: __dirname + '/karma-js.conf.js',
singleRun: true, reporters: ['dots'], browsers: getBrowsersFromCLI()}, done);
});
gulp.task('test.unit.dart/ci', function (done) {
karma.start({configFile: __dirname + '/karma-dart.conf.js',
singleRun: true, reporters: ['dots'], browsers: getBrowsersFromCLI()}, done);
});
gulp.task('test.unit.cjs', function (done) {
return gulp.src(CONFIG.test.js.cjs).pipe(jasmine(/*{verbose: true, includeStackTrace: true}*/));
});
// ------------------
// server tests
// These tests run on the VM on the command-line and are
// allowed to access the file system and network.
gulp.task('test.server.dart', runServerDartTests(gulp, gulpPlugins, {
dest: 'dist/dart'
}));
// -----------------
// test builders
gulp.task('test.transpiler.unittest', function (done) {
return gulp.src('tools/transpiler/unittest/**/*.js')
.pipe(jasmine({
includeStackTrace: true
}))
});
// Copy test resources to dist
gulp.task('tests/transform.dart', function() {
return gulp.src('modules/angular2/test/transform/**')
.pipe(gulp.dest('dist/dart/angular2/test/transform'));
});
// -----------------
// orchestrated targets
// Builds all Dart packages, but does not compile them
gulp.task('build/packages.dart', function(done) {
runSequence(
['build/transpile.dart', 'build/html.dart', 'build/copy.dart', 'build/multicopy.dart'],
'tests/transform.dart',
'build/format.dart',
'build/pubspec.dart',
done
);
});
// Builds and compiles all Dart packages
gulp.task('build.dart', function(done) {
runSequence(
'build/packages.dart',
'build/analyze.dart',
'build/pubbuild.dart',
done
);
});
gulp.task('build.js.dev', function(done) {
runSequence(
['build/transpile.js.dev', 'build/html.js.dev', 'build/copy.js.dev', 'build/multicopy.js.dev.es6'],
done
);
});
gulp.task('build.js.prod', function(done) {
runSequence(
['build/transpile.js.prod', 'build/html.js.prod', 'build/copy.js.prod', 'build/multicopy.js.prod.es6'],
done
);
});
gulp.task('build.js.cjs', function(done) {
runSequence(
['build/transpile.js.cjs', 'build/copy.js.cjs', 'build/multicopy.js.cjs'],
['build/linknodemodules.js.cjs'],
'build/transformCJSTests',
done
);
});
gulp.task('build.js', ['build.js.dev', 'build.js.prod', 'build.js.cjs']);
gulp.task('clean', ['build/clean.js', 'build/clean.dart', 'build/clean.docs']);
gulp.task('build', ['build.js', 'build.dart']);
| gulpfile.js | var gulp = require('gulp');
var gulpPlugins = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var merge = require('merge');
var gulpTraceur = require('./tools/transpiler/gulp-traceur');
var clean = require('./tools/build/clean');
var transpile = require('./tools/build/transpile');
var html = require('./tools/build/html');
var pubget = require('./tools/build/pubget');
var linknodemodules = require('./tools/build/linknodemodules');
var pubbuild = require('./tools/build/pubbuild');
var dartanalyzer = require('./tools/build/dartanalyzer');
var jsserve = require('./tools/build/jsserve');
var pubserve = require('./tools/build/pubserve');
var rundartpackage = require('./tools/build/rundartpackage');
var copy = require('./tools/build/copy');
var karma = require('karma').server;
var minimist = require('minimist');
var es5build = require('./tools/build/es5build');
var runServerDartTests = require('./tools/build/run_server_dart_tests');
var transformCJSTests = require('./tools/build/transformCJSTests');
var util = require('./tools/build/util');
var DART_SDK = require('./tools/build/dartdetect')(gulp);
// -----------------------
// configuration
var _COMPILER_CONFIG_JS_DEFAULT = {
sourceMaps: true,
annotations: true, // parse annotations
types: true, // parse types
script: false, // parse as a module
memberVariables: true, // parse class fields
modules: 'instantiate'
};
var _HTLM_DEFAULT_SCRIPTS_JS = [
{src: gulpTraceur.RUNTIME_PATH, mimeType: 'text/javascript', copy: true},
{src: 'node_modules/es6-module-loader/dist/es6-module-loader-sans-promises.src.js',
mimeType: 'text/javascript', copy: true},
{src: 'node_modules/zone.js/zone.js', mimeType: 'text/javascript', copy: true},
{src: 'node_modules/zone.js/long-stack-trace-zone.js', mimeType: 'text/javascript', copy: true},
{src: 'node_modules/systemjs/dist/system.src.js', mimeType: 'text/javascript', copy: true},
{src: 'node_modules/systemjs/lib/extension-register.js', mimeType: 'text/javascript', copy: true},
{src: 'tools/build/snippets/runtime_paths.js', mimeType: 'text/javascript', copy: true},
{
inline: 'System.import(\'$MODULENAME$\').then(function(m) { m.main(); }, console.error.bind(console))',
mimeType: 'text/javascript'
}
];
var _HTML_DEFAULT_SCRIPTS_DART = [
{src: '$MODULENAME_WITHOUT_PATH$.dart', mimeType: 'application/dart'},
{src: 'packages/browser/dart.js', mimeType: 'text/javascript'}
];
var BASE_PACKAGE_JSON = require('./package.json');
var COMMON_PACKAGE_JSON = {
version: BASE_PACKAGE_JSON.version,
homepage: BASE_PACKAGE_JSON.homepage,
bugs: BASE_PACKAGE_JSON.bugs,
license: BASE_PACKAGE_JSON.license,
contributors: BASE_PACKAGE_JSON.contributors,
dependencies: BASE_PACKAGE_JSON.dependencies,
devDependencies: {
"yargs": BASE_PACKAGE_JSON.devDependencies['yargs'],
"gulp-sourcemaps": BASE_PACKAGE_JSON.devDependencies['gulp-sourcemaps'],
"gulp-traceur": BASE_PACKAGE_JSON.devDependencies['gulp-traceur'],
"gulp": BASE_PACKAGE_JSON.devDependencies['gulp'],
"gulp-rename": BASE_PACKAGE_JSON.devDependencies['gulp-rename'],
"through2": BASE_PACKAGE_JSON.devDependencies['through2']
}
};
var SRC_FOLDER_INSERTION = {
js: {
'**': ''
},
dart: {
'**': 'lib',
'*/test/**': '',
'benchmarks/**': 'web',
'benchmarks/test/**': '',
'benchmarks_external/**': 'web',
'benchmarks_external/test/**': '',
'example*/**': 'web',
'example*/test/**': ''
}
};
var CONFIG = {
dest: {
js: {
all: 'dist/js',
dev: {
es6: 'dist/js/dev/es6',
es5: 'dist/js/dev/es5'
},
prod: {
es6: 'dist/js/prod/es6',
es5: 'dist/js/prod/es5'
},
cjs: 'dist/js/cjs',
dart2js: 'dist/js/dart2js'
},
dart: 'dist/dart',
docs: 'dist/docs'
},
srcFolderInsertion: SRC_FOLDER_INSERTION,
transpile: {
src: {
js: ['modules/**/*.js', 'modules/**/*.es6'],
dart: ['modules/**/*.js']
},
options: {
js: {
dev: merge(true, _COMPILER_CONFIG_JS_DEFAULT, {
typeAssertionModule: 'rtts_assert/rtts_assert',
typeAssertions: true,
outputLanguage: 'es6'
}),
prod: merge(true, _COMPILER_CONFIG_JS_DEFAULT, {
typeAssertions: false,
outputLanguage: 'es6'
}),
cjs: merge(true, _COMPILER_CONFIG_JS_DEFAULT, {
typeAssertionModule: 'rtts_assert/rtts_assert',
typeAssertions: true,
modules: 'commonjs'
})
},
dart: {
sourceMaps: true,
annotations: true, // parse annotations
types: true, // parse types
script: false, // parse as a module
memberVariables: true, // parse class fields
outputLanguage: 'dart'
}
}
},
copy: {
js: {
cjs: {
src: ['modules/**/README.js.md', 'modules/**/package.json', 'modules/**/*.cjs'],
pipes: {
'**/*.cjs': gulpPlugins.rename({extname: '.js'}),
'**/*.js.md': gulpPlugins.rename(function(file) {
file.basename = file.basename.substring(0, file.basename.lastIndexOf('.'));
}),
'**/package.json': gulpPlugins.template({ 'packageJson': COMMON_PACKAGE_JSON })
}
},
dev: {
src: ['modules/**/*.css'],
pipes: {}
},
prod: {
src: ['modules/**/*.css'],
pipes: {}
}
},
dart: {
src: ['modules/**/README.dart.md', 'modules/**/*.dart', 'modules/*/pubspec.yaml', 'modules/**/*.css', '!modules/**/e2e_test/**'],
pipes: {
'**/*.dart': util.insertSrcFolder(gulpPlugins, SRC_FOLDER_INSERTION.dart),
'**/*.dart.md': gulpPlugins.rename(function(file) {
file.basename = file.basename.substring(0, file.basename.lastIndexOf('.'));
}),
'**/pubspec.yaml': gulpPlugins.template({ 'packageJson': COMMON_PACKAGE_JSON })
}
}
},
multicopy: {
js: {
cjs: {
src: [
'LICENSE'
],
pipes: {}
},
dev: {
es6: {
src: ['tools/build/es5build.js'],
pipes: {}
}
},
prod: {
es6: {
src: ['tools/build/es5build.js'],
pipes: {}
}
}
},
dart: {
src: ['LICENSE'],
exclude: ['rtts_assert/'],
pipes: {}
}
},
html: {
src: {
js: ['modules/*/src/**/*.html'],
dart: ['modules/*/src/**/*.html']
},
scriptsPerFolder: {
js: {
'**': _HTLM_DEFAULT_SCRIPTS_JS,
'benchmarks/**':
[
{ src: 'tools/build/snippets/url_params_to_form.js', mimeType: 'text/javascript', copy: true }
].concat(_HTLM_DEFAULT_SCRIPTS_JS),
'benchmarks_external/**':
[
{ src: 'node_modules/angular/angular.js', mimeType: 'text/javascript', copy: true },
{ src: 'tools/build/snippets/url_params_to_form.js', mimeType: 'text/javascript', copy: true }
].concat(_HTLM_DEFAULT_SCRIPTS_JS)
},
dart: {
'**': _HTML_DEFAULT_SCRIPTS_DART,
'benchmarks*/**':
[
{ src: 'tools/build/snippets/url_params_to_form.js', mimeType: 'text/javascript', copy: true }
].concat(_HTML_DEFAULT_SCRIPTS_DART)
}
}
},
formatDart: {
packageName: 'dart_style',
args: ['dart_style:format', '-w', 'dist/dart']
},
test: {
js: {
cjs: [
'/angular2/test/core/compiler/**/*_spec.js',
'/angular2/test/directives/**/*_spec.js',
'/angular2/test/forms/**/*_spec.js'
]
}
}
};
CONFIG.test.js.cjs = CONFIG.test.js.cjs.map(function(s) {return CONFIG.dest.js.cjs + s});
// ------------
// clean
gulp.task('build/clean.js', clean(gulp, gulpPlugins, {
path: CONFIG.dest.js.all
}));
gulp.task('build/clean.dart', clean(gulp, gulpPlugins, {
path: CONFIG.dest.dart
}));
gulp.task('build/clean.docs', clean(gulp, gulpPlugins, {
path: CONFIG.dest.docs
}));
// ------------
// transpile
gulp.task('build/transpile.js.dev.es6', transpile(gulp, gulpPlugins, {
src: CONFIG.transpile.src.js,
dest: CONFIG.dest.js.dev.es6,
outputExt: 'es6',
options: CONFIG.transpile.options.js.dev,
srcFolderInsertion: CONFIG.srcFolderInsertion.js
}));
gulp.task('build/transpile.js.dev.es5', function() {
return es5build({
src: CONFIG.dest.js.dev.es6,
dest: CONFIG.dest.js.dev.es5,
modules: 'instantiate'
});
});
gulp.task('build/transpile.js.dev', function(done) {
runSequence(
'build/transpile.js.dev.es6',
'build/transpile.js.dev.es5',
done
);
});
gulp.task('build/transpile.js.prod.es6', transpile(gulp, gulpPlugins, {
src: CONFIG.transpile.src.js,
dest: CONFIG.dest.js.prod.es6,
outputExt: 'es6',
options: CONFIG.transpile.options.js.prod,
srcFolderInsertion: CONFIG.srcFolderInsertion.js
}));
gulp.task('build/transpile.js.prod.es5', function() {
return es5build({
src: CONFIG.dest.js.prod.es6,
dest: CONFIG.dest.js.prod.es5,
modules: 'instantiate'
});
});
gulp.task('build/transpile.js.prod', function(done) {
runSequence(
'build/transpile.js.prod.es6',
'build/transpile.js.prod.es5',
done
);
});
gulp.task('build/transpile.js.cjs', transpile(gulp, gulpPlugins, {
src: CONFIG.transpile.src.js.concat(['modules/**/*.cjs']),
dest: CONFIG.dest.js.cjs,
outputExt: 'js',
options: CONFIG.transpile.options.js.cjs,
srcFolderInsertion: CONFIG.srcFolderInsertion.js
}));
gulp.task('build/transformCJSTests', function() {
return gulp.src(CONFIG.dest.js.cjs + '/angular2/test/**/*_spec.js').pipe(transformCJSTests()).pipe(gulp.dest(CONFIG.dest.js.cjs + '/angular2/test/'));
});
gulp.task('build/transpile.dart', transpile(gulp, gulpPlugins, {
src: CONFIG.transpile.src.dart,
dest: CONFIG.dest.dart,
outputExt: 'dart',
options: CONFIG.transpile.options.dart,
srcFolderInsertion: CONFIG.srcFolderInsertion.dart
}));
// ------------
// html
gulp.task('build/html.js.dev', html(gulp, gulpPlugins, {
src: CONFIG.html.src.js,
dest: CONFIG.dest.js.dev.es5,
srcFolderInsertion: CONFIG.srcFolderInsertion.js,
scriptsPerFolder: CONFIG.html.scriptsPerFolder.js
}));
gulp.task('build/html.js.prod', html(gulp, gulpPlugins, {
src: CONFIG.html.src.js,
dest: CONFIG.dest.js.prod.es5,
srcFolderInsertion: CONFIG.srcFolderInsertion.js,
scriptsPerFolder: CONFIG.html.scriptsPerFolder.js
}));
gulp.task('build/html.dart', html(gulp, gulpPlugins, {
src: CONFIG.html.src.dart,
dest: CONFIG.dest.dart,
srcFolderInsertion: CONFIG.srcFolderInsertion.dart,
scriptsPerFolder: CONFIG.html.scriptsPerFolder.dart
}));
// ------------
// copy
gulp.task('build/copy.js.cjs', copy.copy(gulp, gulpPlugins, {
src: CONFIG.copy.js.cjs.src,
pipes: CONFIG.copy.js.cjs.pipes,
dest: CONFIG.dest.js.cjs
}));
gulp.task('build/copy.js.dev', copy.copy(gulp, gulpPlugins, {
src: CONFIG.copy.js.dev.src,
pipes: CONFIG.copy.js.dev.pipes,
dest: CONFIG.dest.js.dev.es5
}));
gulp.task('build/copy.js.prod', copy.copy(gulp, gulpPlugins, {
src: CONFIG.copy.js.prod.src,
pipes: CONFIG.copy.js.prod.pipes,
dest: CONFIG.dest.js.prod.es5
}));
gulp.task('build/copy.dart', copy.copy(gulp, gulpPlugins, {
src: CONFIG.copy.dart.src,
pipes: CONFIG.copy.dart.pipes,
dest: CONFIG.dest.dart
}));
// ------------
// multicopy
gulp.task('build/multicopy.js.cjs', copy.multicopy(gulp, gulpPlugins, {
src: CONFIG.multicopy.js.cjs.src,
pipes: CONFIG.multicopy.js.cjs.pipes,
exclude: CONFIG.multicopy.js.cjs.exclude,
dest: CONFIG.dest.js.cjs
}));
gulp.task('build/multicopy.js.dev.es6', copy.multicopy(gulp, gulpPlugins, {
src: CONFIG.multicopy.js.dev.es6.src,
pipes: CONFIG.multicopy.js.dev.es6.pipes,
exclude: CONFIG.multicopy.js.dev.es6.exclude,
dest: CONFIG.dest.js.dev.es6
}));
gulp.task('build/multicopy.js.prod.es6', copy.multicopy(gulp, gulpPlugins, {
src: CONFIG.multicopy.js.prod.es6.src,
pipes: CONFIG.multicopy.js.prod.es6.pipes,
exclude: CONFIG.multicopy.js.prod.es6.exclude,
dest: CONFIG.dest.js.prod.es6
}));
gulp.task('build/multicopy.dart', copy.multicopy(gulp, gulpPlugins, {
src: CONFIG.multicopy.dart.src,
pipes: CONFIG.multicopy.dart.pipes,
exclude: CONFIG.multicopy.dart.exclude,
dest: CONFIG.dest.dart
}));
// ------------
// pubspec
gulp.task('build/pubspec.dart', pubget(gulp, gulpPlugins, {
dir: CONFIG.dest.dart,
command: DART_SDK.PUB
}));
// ------------
// linknodemodules
gulp.task('build/linknodemodules.js.cjs', linknodemodules(gulp, gulpPlugins, {
dir: CONFIG.dest.js.cjs
}));
// ------------
// dartanalyzer
gulp.task('build/analyze.dart', dartanalyzer(gulp, gulpPlugins, {
dest: CONFIG.dest.dart,
command: DART_SDK.ANALYZER
}));
// ------------
// pubbuild
gulp.task('build/pubbuild.dart', pubbuild(gulp, gulpPlugins, {
src: CONFIG.dest.dart,
dest: CONFIG.dest.js.dart2js,
command: DART_SDK.PUB
}));
// ------------
// format dart
gulp.task('build/format.dart', rundartpackage(gulp, gulpPlugins, {
pub: DART_SDK.PUB,
packageName: CONFIG.formatDart.packageName,
args: CONFIG.formatDart.args
}));
// ------------------
// web servers
gulp.task('serve.js.dev', jsserve(gulp, gulpPlugins, {
path: CONFIG.dest.js.dev.es5,
port: 8000
}));
gulp.task('serve.js.prod', jsserve(gulp, gulpPlugins, {
path: CONFIG.dest.js.prod.es5,
port: 8001
}));
gulp.task('serve.js.dart2js', jsserve(gulp, gulpPlugins, {
path: CONFIG.dest.js.dart2js,
port: 8002
}));
gulp.task('serve/examples.dart', pubserve(gulp, gulpPlugins, {
command: DART_SDK.PUB,
path: CONFIG.dest.dart + '/examples'
}));
gulp.task('serve/benchmarks.dart', pubserve(gulp, gulpPlugins, {
command: DART_SDK.PUB,
path: CONFIG.dest.dart + '/benchmarks'
}));
gulp.task('serve/benchmarks_external.dart', pubserve(gulp, gulpPlugins, {
command: DART_SDK.PUB,
path: CONFIG.dest.dart + '/benchmarks_external'
}));
// --------------
// doc generation
var Dgeni = require('dgeni');
gulp.task('docs/dgeni', function() {
try {
var dgeni = new Dgeni([require('./docs/dgeni-package')]);
return dgeni.generate();
} catch(x) {
console.log(x.stack);
throw x;
}
});
var bower = require('bower');
gulp.task('docs/bower', function() {
var bowerTask = bower.commands.install(undefined, undefined, { cwd: 'docs' });
bowerTask.on('log', function (result) {
console.log('bower:', result.id, result.data.endpoint.name);
});
bowerTask.on('error', function(error) {
console.log(error);
});
return bowerTask;
});
gulp.task('docs/assets', ['docs/bower'], function() {
return gulp.src('docs/bower_components/**/*')
.pipe(gulp.dest('dist/docs/lib'));
});
gulp.task('docs/app', function() {
return gulp.src('docs/app/**/*')
.pipe(gulp.dest('dist/docs'));
});
gulp.task('docs', ['docs/assets', 'docs/app', 'docs/dgeni']);
gulp.task('docs/watch', function() {
return gulp.watch('docs/app/**/*', ['docs/app']);
});
var jasmine = require('gulp-jasmine');
gulp.task('docs/test', function () {
return gulp.src('docs/**/*.spec.js')
.pipe(jasmine({
includeStackTrace: true
}));
});
var webserver = require('gulp-webserver');
gulp.task('docs/serve', function() {
gulp.src('dist/docs/')
.pipe(webserver({
fallback: 'index.html'
}));
});
// ------------------
// karma tests
// These tests run in the browser and are allowed to access
// HTML DOM APIs.
function getBrowsersFromCLI() {
var args = minimist(process.argv.slice(2));
return [args.browsers?args.browsers:'DartiumWithWebPlatform']
}
gulp.task('test.unit.js', function (done) {
karma.start({configFile: __dirname + '/karma-js.conf.js'}, done);
});
gulp.task('test.unit.dart', function (done) {
karma.start({configFile: __dirname + '/karma-dart.conf.js'}, done);
});
gulp.task('test.unit.js/ci', function (done) {
karma.start({configFile: __dirname + '/karma-js.conf.js',
singleRun: true, reporters: ['dots'], browsers: getBrowsersFromCLI()}, done);
});
gulp.task('test.unit.dart/ci', function (done) {
karma.start({configFile: __dirname + '/karma-dart.conf.js',
singleRun: true, reporters: ['dots'], browsers: getBrowsersFromCLI()}, done);
});
gulp.task('test.unit.cjs', function (done) {
return gulp.src(CONFIG.test.js.cjs).pipe(jasmine(/*{verbose: true, includeStackTrace: true}*/));
});
// ------------------
// server tests
// These tests run on the VM on the command-line and are
// allowed to access the file system and network.
gulp.task('test.server.dart', runServerDartTests(gulp, gulpPlugins, {
dest: 'dist/dart'
}));
// -----------------
// test builders
gulp.task('test.transpiler.unittest', function (done) {
return gulp.src('tools/transpiler/unittest/**/*.js')
.pipe(jasmine({
includeStackTrace: true
}))
});
// Copy test resources to dist
gulp.task('tests/transform.dart', function() {
return gulp.src('modules/angular2/test/transform/**')
.pipe(gulp.dest('dist/dart/angular2/test/transform'));
});
// -----------------
// orchestrated targets
// Builds all Dart packages, but does not compile them
gulp.task('build/packages.dart', function(done) {
runSequence(
['build/transpile.dart', 'build/html.dart', 'build/copy.dart', 'build/multicopy.dart'],
'tests/transform.dart',
'build/format.dart',
'build/pubspec.dart',
done
);
});
// Builds and compiles all Dart packages
gulp.task('build.dart', function(done) {
runSequence(
'build/packages.dart',
'build/analyze.dart',
'build/pubbuild.dart',
done
);
});
gulp.task('build.js.dev', function(done) {
runSequence(
['build/transpile.js.dev', 'build/html.js.dev', 'build/copy.js.dev', 'build/multicopy.js.dev.es6'],
done
);
});
gulp.task('build.js.prod', function(done) {
runSequence(
['build/transpile.js.prod', 'build/html.js.prod', 'build/copy.js.prod', 'build/multicopy.js.prod.es6'],
done
);
});
gulp.task('build.js.cjs', function(done) {
runSequence(
['build/transpile.js.cjs', 'build/copy.js.cjs', 'build/multicopy.js.cjs'],
['build/linknodemodules.js.cjs'],
'build/transformCJSTests',
done
);
});
gulp.task('build.js', ['build.js.dev', 'build.js.prod', 'build.js.cjs']);
gulp.task('clean', ['build/clean.js', 'build/clean.dart', 'build/clean.docs']);
gulp.task('build', ['build.js', 'build.dart']);
| chore(gulp): fix typo HTLM to HTML in a variable name
Closes #920
| gulpfile.js | chore(gulp): fix typo HTLM to HTML in a variable name | <ide><path>ulpfile.js
<ide> modules: 'instantiate'
<ide> };
<ide>
<del>var _HTLM_DEFAULT_SCRIPTS_JS = [
<add>var _HTML_DEFAULT_SCRIPTS_JS = [
<ide> {src: gulpTraceur.RUNTIME_PATH, mimeType: 'text/javascript', copy: true},
<ide> {src: 'node_modules/es6-module-loader/dist/es6-module-loader-sans-promises.src.js',
<ide> mimeType: 'text/javascript', copy: true},
<ide> },
<ide> scriptsPerFolder: {
<ide> js: {
<del> '**': _HTLM_DEFAULT_SCRIPTS_JS,
<add> '**': _HTML_DEFAULT_SCRIPTS_JS,
<ide> 'benchmarks/**':
<ide> [
<ide> { src: 'tools/build/snippets/url_params_to_form.js', mimeType: 'text/javascript', copy: true }
<del> ].concat(_HTLM_DEFAULT_SCRIPTS_JS),
<add> ].concat(_HTML_DEFAULT_SCRIPTS_JS),
<ide> 'benchmarks_external/**':
<ide> [
<ide> { src: 'node_modules/angular/angular.js', mimeType: 'text/javascript', copy: true },
<ide> { src: 'tools/build/snippets/url_params_to_form.js', mimeType: 'text/javascript', copy: true }
<del> ].concat(_HTLM_DEFAULT_SCRIPTS_JS)
<add> ].concat(_HTML_DEFAULT_SCRIPTS_JS)
<ide> },
<ide> dart: {
<ide> '**': _HTML_DEFAULT_SCRIPTS_DART, |
|
Java | apache-2.0 | 1f54b96acef2a5e22a708e171ae79aad16f5a1c5 | 0 | jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics | /*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* 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.
*
* Author:
* Franz Wilhelmstötter ([email protected])
*/
package io.jenetics;
import static java.lang.Math.min;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import io.jenetics.util.ISeq;
import io.jenetics.util.MSeq;
import io.jenetics.util.Seq;
/**
* In truncation selection individuals are sorted according to their fitness.
* Only the n best individuals are selected. The truncation selection is a very
* basic selection algorithm. It has it's strength in fast selecting individuals
* in large populations, but is not very often used in practice.
*
* @see <a href="http://en.wikipedia.org/wiki/Truncation_selection">
* Wikipedia: Truncation selection
* </a>
*
* @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
* @since 1.0
* @version !__version__!
*/
public final class TruncationSelector<
G extends Gene<?, G>,
C extends Comparable<? super C>
>
implements Selector<G, C>
{
private final int _n;
/**
* Create a new {@code TruncationSelector} object, where the worst selected
* individual has rank {@code n}. This means, if you want to select
* {@code count} individuals, the worst selected individual has rank
* {@code n}. If {@code count > n}, the selected population will contain
* <em>duplicate</em> individuals.
*
* @since 3.8
*
* @param n the worst rank of the selected individuals
* @throws IllegalArgumentException if {@code n < 1}
*/
public TruncationSelector(final int n) {
if (n < 1) {
throw new IllegalArgumentException(format(
"n must be greater or equal 1, but was %d.", n
));
}
_n = n;
}
/**
* Create a new TruncationSelector object.
*/
public TruncationSelector() {
this(Integer.MAX_VALUE);
}
/**
* This method sorts the population in descending order while calculating
* the selection probabilities. If the selection size is greater the the
* population size, the whole population is duplicated until the desired
* sample size is reached.
*
* @throws NullPointerException if the {@code population} or {@code opt} is
* {@code null}.
*/
@Override
public ISeq<Phenotype<G, C>> select(
final Seq<Phenotype<G, C>> population,
final int count,
final Optimize opt
) {
requireNonNull(population, "Population");
requireNonNull(opt, "Optimization");
if (count < 0) {
throw new IllegalArgumentException(format(
"Selection count must be greater or equal then zero, but was %s",
count
));
}
final MSeq<Phenotype<G, C>> selection = MSeq
.ofLength(population.isEmpty() ? 0 : count);
if (count > 0 && !population.isEmpty()) {
final MSeq<Phenotype<G, C>> copy = population.asISeq().copy();
copy.sort((a, b) ->
opt.<C>descending().compare(a.getFitness(), b.getFitness()));
int size = count;
do {
final int length = min(min(copy.size(), size), _n);
for (int i = 0; i < length; ++i) {
selection.set((count - size) + i, copy.get(i));
}
size -= length;
} while (size > 0);
}
return selection.toISeq();
}
@Override
public String toString() {
return getClass().getName();
}
}
| jenetics/src/main/java/io/jenetics/TruncationSelector.java | /*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* 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.
*
* Author:
* Franz Wilhelmstötter ([email protected])
*/
package io.jenetics;
import static java.lang.Math.min;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static io.jenetics.internal.util.Hashes.hash;
import io.jenetics.util.ISeq;
import io.jenetics.util.MSeq;
import io.jenetics.util.Seq;
/**
* In truncation selection individuals are sorted according to their fitness.
* Only the n best individuals are selected. The truncation selection is a very
* basic selection algorithm. It has it's strength in fast selecting individuals
* in large populations, but is not very often used in practice.
*
* @see <a href="http://en.wikipedia.org/wiki/Truncation_selection">
* Wikipedia: Truncation selection
* </a>
*
* @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
* @since 1.0
* @version 4.0
*/
public final class TruncationSelector<
G extends Gene<?, G>,
C extends Comparable<? super C>
>
implements Selector<G, C>
{
private final int _n;
/**
* Create a new {@code TruncationSelector} object, where the worst selected
* individual has rank {@code n}. This means, if you want to select
* {@code count} individuals, the worst selected individual has rank
* {@code n}. If {@code count > n}, the selected population will contain
* <em>duplicate</em> individuals.
*
* @since 3.8
*
* @param n the worst rank of the selected individuals
* @throws IllegalArgumentException if {@code n < 1}
*/
public TruncationSelector(final int n) {
if (n < 1) {
throw new IllegalArgumentException(format(
"n must be greater or equal 1, but was %d.", n
));
}
_n = n;
}
/**
* Create a new TruncationSelector object.
*/
public TruncationSelector() {
this(Integer.MAX_VALUE);
}
/**
* This method sorts the population in descending order while calculating
* the selection probabilities. If the selection size is greater the the
* population size, the whole population is duplicated until the desired
* sample size is reached.
*
* @throws NullPointerException if the {@code population} or {@code opt} is
* {@code null}.
*/
@Override
public ISeq<Phenotype<G, C>> select(
final Seq<Phenotype<G, C>> population,
final int count,
final Optimize opt
) {
requireNonNull(population, "Population");
requireNonNull(opt, "Optimization");
if (count < 0) {
throw new IllegalArgumentException(format(
"Selection count must be greater or equal then zero, but was %s",
count
));
}
final MSeq<Phenotype<G, C>> selection = MSeq
.ofLength(population.isEmpty() ? 0 : count);
if (count > 0 && !population.isEmpty()) {
final MSeq<Phenotype<G, C>> copy = population.asISeq().copy();
copy.sort((a, b) ->
opt.<C>descending().compare(a.getFitness(), b.getFitness()));
int size = count;
do {
final int length = min(min(copy.size(), size), _n);
for (int i = 0; i < length; ++i) {
selection.set((count - size) + i, copy.get(i));
}
size -= length;
} while (size > 0);
}
return selection.toISeq();
}
@Override
public int hashCode() {
return hash(getClass());
}
@Override
public boolean equals(final Object obj) {
return obj == this || obj != null && getClass() == obj.getClass();
}
@Override
public String toString() {
return getClass().getName();
}
}
| #331: Remove 'equals' and 'hashCode' from 'TruncationSelector'.
| jenetics/src/main/java/io/jenetics/TruncationSelector.java | #331: Remove 'equals' and 'hashCode' from 'TruncationSelector'. | <ide><path>enetics/src/main/java/io/jenetics/TruncationSelector.java
<ide> import static java.lang.Math.min;
<ide> import static java.lang.String.format;
<ide> import static java.util.Objects.requireNonNull;
<del>import static io.jenetics.internal.util.Hashes.hash;
<ide>
<ide> import io.jenetics.util.ISeq;
<ide> import io.jenetics.util.MSeq;
<ide> *
<ide> * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
<ide> * @since 1.0
<del> * @version 4.0
<add> * @version !__version__!
<ide> */
<ide> public final class TruncationSelector<
<ide> G extends Gene<?, G>,
<ide> }
<ide>
<ide> @Override
<del> public int hashCode() {
<del> return hash(getClass());
<del> }
<del>
<del> @Override
<del> public boolean equals(final Object obj) {
<del> return obj == this || obj != null && getClass() == obj.getClass();
<del> }
<del>
<del> @Override
<ide> public String toString() {
<ide> return getClass().getName();
<ide> } |
|
Java | apache-2.0 | 5f8988a3a0af98b89d44185cfe77f3c8099afaf1 | 0 | spradnyesh/encog-java-core,krzysztof-magosa/encog-java-core,krzysztof-magosa/encog-java-core,SpenceSouth/encog-java-core,Crespo911/encog-java-core,ThiagoGarciaAlves/encog-java-core,danilodesousacubas/encog-java-core,Crespo911/encog-java-core,spradnyesh/encog-java-core,ThiagoGarciaAlves/encog-java-core,SpenceSouth/encog-java-core,danilodesousacubas/encog-java-core | /*
* Encog(tm) Core v3.2 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2013 Heaton Research, 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.engine.network.activation;
import org.encog.mathutil.BoundMath;
import org.encog.ml.factory.MLActivationFactory;
import org.encog.util.obj.ActivationUtil;
/**
* The sigmoid activation function takes on a sigmoidal shape. Only positive
* numbers are generated. Do not use this activation function if negative number
* output is desired.
*/
public class ActivationSigmoid implements ActivationFunction {
/**
* Serial id for this class.
*/
private static final long serialVersionUID = 5622349801036468572L;
/**
* The parameters.
*/
private final double[] params;
/**
* Construct a basic sigmoid function, with a slope of 1.
*/
public ActivationSigmoid() {
this.params = new double[0];
}
/**
* {@inheritDoc}
*/
@Override
public final void activationFunction(final double[] x, final int start,
final int size) {
for (int i = start; i < start + size; i++) {
x[i] = 1.0 / (1.0 + BoundMath.exp(-1 * x[i]));
}
}
/**
* @return The object cloned;
*/
@Override
public final ActivationFunction clone() {
return new ActivationSigmoid();
}
/**
* {@inheritDoc}
*/
@Override
public final double derivativeFunction(final double b, final double a) {
return a * (1.0 - a);
}
/**
* {@inheritDoc}
*/
@Override
public final String[] getParamNames() {
final String[] results = {};
return results;
}
/**
* {@inheritDoc}
*/
@Override
public final double[] getParams() {
return this.params;
}
/**
* @return True, sigmoid has a derivative.
*/
@Override
public final boolean hasDerivative() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public final void setParam(final int index, final double value) {
this.params[index] = value;
}
/**
* {@inheritDoc}
*/
@Override
public String getFactoryCode() {
return ActivationUtil.generateActivationFactory(MLActivationFactory.AF_SIGMOID, this);
}
}
| src/main/java/org/encog/engine/network/activation/ActivationSigmoid.java | /*
* Encog(tm) Core v3.2 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2013 Heaton Research, 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.engine.network.activation;
import org.encog.mathutil.BoundMath;
import org.encog.ml.factory.MLActivationFactory;
import org.encog.util.obj.ActivationUtil;
/**
* The sigmoid activation function takes on a sigmoidal shape. Only positive
* numbers are generated. Do not use this activation function if negative number
* output is desired.
*/
public class ActivationSigmoid implements ActivationFunction {
/**
* Serial id for this class.
*/
private static final long serialVersionUID = 5622349801036468572L;
/**
* The parameters.
*/
private final double[] params;
/**
* Construct a basic sigmoid function, with a slope of 1.
*/
public ActivationSigmoid() {
this.params = new double[0];
}
/**
* {@inheritDoc}
*/
@Override
public final void activationFunction(final double[] x, final int start,
final int size) {
for (int i = start; i < start + size; i++) {
x[i] = 1.0 / (1.0 + BoundMath.exp(-1 * x[i]));
}
}
/**
* @return The object cloned;
*/
@Override
public final ActivationFunction clone() {
return new ActivationSigmoid();
}
/**
* {@inheritDoc}
*/
@Override
public final double derivativeFunction(final double b, final double a) {
return a * (1.0 - a);
}
/**
* {@inheritDoc}
*/
@Override
public final String[] getParamNames() {
final String[] results = {};
return results;
}
/**
* {@inheritDoc}
*/
@Override
public final double[] getParams() {
return this.params;
}
/**
* @return True, sigmoid has a derivative.
*/
@Override
public final boolean hasDerivative() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public final void setParam(final int index, final double value) {
this.params[index] = value;
}
/**
* {@inheritDoc}
*/
@Override
public String getFactoryCode() {
return ActivationUtil.generateActivationFactory(MLActivationFactory.AF_SIGMOID, this);
}
}
| Revert "test"
This reverts commit 1949ee7ff7d77f096c638b67853f712575a4c66a.
| src/main/java/org/encog/engine/network/activation/ActivationSigmoid.java | Revert "test" | ||
Java | apache-2.0 | 9d9d771a7556e5ce713e611ff6ed8fdcc4c85b6a | 0 | IMAGINARY/FormulaMorph | package com.moeyinc.formulamorph;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.vecmath.*;
import javax.imageio.ImageIO;
import java.io.*;
import java.net.*;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Properties;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.EnumSet;
import java.text.DecimalFormat;
//import com.moeyinc.formulamorph.Parameters.ActiveParameterListener;
import de.mfo.jsurfer.algebra.*;
import de.mfo.jsurfer.rendering.*;
import de.mfo.jsurfer.util.BasicIO;
public class GUI extends JFrame implements Parameter.ValueChangeListener
{
class SurfaceGUIElements
{
final public JSurferRenderPanel panel;
final public LaTeXLabel title;
final public LaTeXLabel equation;
final public JPanel levelIcon;
final public LaTeXLabel levelLabel;
final private Surface surface;
private List< Gallery.GalleryItem > gallery_items;
private List< Gallery.GalleryItem > gallery_items_unmodifyable;
private int id_in_gallery;
private ArrayList< JPanel > gallery_panels;
private List< JPanel > gallery_panels_unmodifiable;
private Map< Gallery.Level, ImageScaler > levelIcons;
public SurfaceGUIElements( Surface s )
{
levelIcons = new EnumMap< Gallery.Level, ImageScaler >( Gallery.Level.class );
levelIcons.put( Gallery.Level.BASIC, new ImageScaler( sierpinskiBASIC ) );
levelIcons.put( Gallery.Level.INTERMEDIATE, new ImageScaler( sierpinskiINTERMEDIATE ) );
levelIcons.put( Gallery.Level.ADVANCED, new ImageScaler( sierpinskiADVANCED ) );
surface = s;
id_in_gallery = 0;
LaTeXCommands.getDynamicLaTeXMap().put( "FMImage" + s.name(), "\\includejavaimage[interpolation=bicubic]{FMImage" + s.name() + "}" );
this.panel = new JSurferRenderPanel();
this.title = new LaTeXLabel( "\\sf\\bf\\LARGE\\fgcolor{white}{\\jlmDynamic{FMTitle" + s.name() + "}}" );
this.title.setHAlignment( LaTeXLabel.HAlignment.CENTER );
this.title.setVAlignment( LaTeXLabel.VAlignment.CENTER_BASELINE );
//this.title.setBackground( Color.GRAY ); this.title.setOpaque( true );
this.equation = new LaTeXLabel( staticLaTeXSrc( s ) );
//this.equation.setBackground( Color.GRAY ); this.equation.setOpaque( true );
this.levelIcon = new JPanel( new BorderLayout() );
this.levelLabel = new LaTeXLabel( "\\tiny\\fgcolor{white}{\\jlmDynamic{FMLevel" + s.name() + "}}" );
gallery_panels = new ArrayList< JPanel >();
for( int i = 0; i < 7; ++i )
{
JPanel p = new JPanel( new BorderLayout() );
p.setBackground( new Color( 0.1f, 0.1f, 0.1f ) );
p.setOpaque( true );
gallery_panels.add( i, p );
}
gallery_panels.get( gallery_panels.size() / 2 ).setBorder( BorderFactory.createLineBorder( Color.WHITE, 3 ) );
gallery_panels_unmodifiable = Collections.unmodifiableList( gallery_panels );
// load galleries
gallery_items = new ArrayList< Gallery.GalleryItem >();
gallery_items_unmodifyable = Collections.unmodifiableList( gallery_items );
try
{
switch( surface )
{
case F:
case G:
this.gallery_items.addAll( new Gallery( Gallery.Level.BASIC, new File( "gallery" + File.separator + "basic" ) ).getItems() );
this.gallery_items.addAll( new Gallery( Gallery.Level.INTERMEDIATE, new File( "gallery" + File.separator + "intermediate" ) ).getItems() );
this.gallery_items.addAll( new Gallery( Gallery.Level.ADVANCED, new File( "gallery" + File.separator + "advanced" ) ).getItems() );
break;
default:
break;
}
}
catch( Exception e )
{
System.err.println( "Unable to initialize galleries" );
e.printStackTrace( System.err );
System.exit( -1 );
}
}
public int id() { return id_in_gallery; }
public void setId( int id ) { id_in_gallery = id; }
public List< Gallery.GalleryItem > galleryItems() { return gallery_items_unmodifyable; }
public List< JPanel > galleryPanels() { return gallery_panels_unmodifiable; }
public int highlightedGalleryPanel() { return 3; }
public void setLevelIcon( Gallery.Level l )
{
LaTeXCommands.getDynamicLaTeXMap().put( "FMLevel" + surface.name(), l.name().substring(0,1).toUpperCase() + l.name().substring(1).toLowerCase() );
this.levelIcon.removeAll();
this.levelIcon.add( this.levelIcons.get( l ) );
}
}
JPanel content; // fixed 16:9 top container
static final double aspectRatio = 16.0 / 9.0;
static final DecimalFormat decimalFormatter = new DecimalFormat("#0.00");
EnumMap< Surface, SurfaceGUIElements > surface2guielems = new EnumMap< Surface, SurfaceGUIElements >( Surface.class );
static BufferedImage triangle;
static BufferedImage triangleFlipped;
static {
triangle = new BufferedImage( 100, 100, BufferedImage.TYPE_BYTE_GRAY );
Graphics2D g = (Graphics2D) triangle.getGraphics();
g.setColor( new Color( 0, 0, 0, 0 ) );
g.fillRect( 0, 0, triangle.getWidth(), triangle.getHeight() );
g.setColor( Color.LIGHT_GRAY );
Polygon p = new Polygon();
p.addPoint( -triangle.getWidth() / 2, 0 );
p.addPoint( triangle.getWidth() / 2, 0 );
p.addPoint( 0, (int) ( triangle.getWidth() * Math.sqrt( 3.0 ) / 2.0 ) );
AffineTransform tx = AffineTransform.getScaleInstance( 0.6, 0.6 );
tx.preConcatenate( AffineTransform.getTranslateInstance( triangle.getWidth() / 2, 0 ) );
g.setTransform( tx );
g.fillPolygon( p );
tx = AffineTransform.getScaleInstance(1, -1);
tx.translate(0, -triangle.getHeight(null));
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
triangleFlipped = op.filter( triangle, null);
}
ImageScaler triangleFTop = new ImageScaler( triangleFlipped );
ImageScaler triangleFBottom = new ImageScaler( triangle );
ImageScaler triangleGTop = new ImageScaler( triangleFlipped );
ImageScaler triangleGBottom = new ImageScaler( triangle );
static BufferedImage sierpinskiBASIC = loadIMGResource( "BASIC.png" );
static BufferedImage sierpinskiINTERMEDIATE = loadIMGResource( "INTERMEDIATE.png" );
static BufferedImage sierpinskiADVANCED = loadIMGResource( "ADVANCED.png" );
public static BufferedImage loadIMGResource( String path )
{
InputStream stream = GUI.class.getResourceAsStream( path );
try
{
return ImageIO.read( stream );
}
catch (IOException e)
{
System.err.println( "unable to load resource \"" + path + "\"" );
e.printStackTrace();
}
return new BufferedImage( 1,1, BufferedImage.TYPE_BYTE_GRAY );
}
//JPanel blackStrip;
RotationAnimation rotationAnimation;
final GUIController caGUI = new GUIController();
JFrame caGUIFrame = new JFrame();
JInternalFrame caGUIInternalFrame = new JInternalFrame();
public GUI()
throws Exception, IOException
{
super( "FormulaMorph Main Window" );
this.getLayeredPane().add( caGUIInternalFrame );
this.addMouseListener( new MouseAdapter() { public void mouseClicked( MouseEvent e ) { setupControllerGUI( true ); } } );
Parameter.M_t.setMin( 0.0 );
Parameter.M_t.setMax( 1.0 );
Parameter.M_t.setValue( 0.5 );
LaTeXCommands.getDynamicLaTeXMap().put( "OneMinusT", "0.00" );
for( Parameter p : Parameter.values() )
p.addValueChangeListener( this );
// setup the container which has fixed 16:9 aspect ratio
content = new JPanel();
content.setBackground(Color.BLACK);
content.setLayout( null );
// init components
surface2guielems.put( Surface.F, new SurfaceGUIElements( Surface.F ) );
surface2guielems.put( Surface.M, new SurfaceGUIElements( Surface.M ) );
surface2guielems.put( Surface.G, new SurfaceGUIElements( Surface.G ) );
//blackStrip = new JPanel(); blackStrip.setBackground( Color.black );
final LaTeXLabel eqF = s2g( Surface.F ).equation;
final LaTeXLabel eqM = s2g( Surface.M ).equation;
final LaTeXLabel eqG = s2g( Surface.G ).equation;
s2g( Surface.F ).panel.addImageUpdateListener( new JSurferRenderPanel.ImageUpdateListener() {
public void imageUpdated( Image img )
{
LaTeXCommands.getImageMap().put( "FMImageF", img );
eqF.repaint();
eqM.repaint();
}
});
s2g( Surface.G ).panel.addImageUpdateListener( new JSurferRenderPanel.ImageUpdateListener() {
public void imageUpdated( Image img )
{
LaTeXCommands.getImageMap().put( "FMImageG", img );
eqG.repaint();
eqM.repaint();
}
});
// add components
content.add( s2g( Surface.F ).title );
content.add( s2g( Surface.F ).panel );
content.add( s2g( Surface.F ).equation );
content.add( s2g( Surface.M ).panel );
content.add( s2g( Surface.M ).equation );
content.add( s2g( Surface.G ).title );
content.add( s2g( Surface.G ).panel );
content.add( s2g( Surface.G ).equation );
for( JComponent c : s2g( Surface.F ).galleryPanels() )
content.add( c );
for( JComponent c : s2g( Surface.G ).galleryPanels() )
content.add( c );
content.add( triangleFTop );
content.add( triangleFBottom );
content.add( triangleGTop );
content.add( triangleGBottom );
content.add( s2g( Surface.F ).levelLabel );
content.add( s2g( Surface.F ).levelIcon );
content.add( s2g( Surface.G ).levelLabel );
content.add( s2g( Surface.G ).levelIcon );
//content.add( blackStrip );
// layout components
refreshLayout();
getContentPane().addComponentListener( new ComponentListener() {
public void componentResized(ComponentEvent e) {
// keep aspect ratio
Rectangle b = e.getComponent().getBounds();
Dimension d;
if( b.width * 9 < b.height * 16 )
d = new Dimension( b.width, ( 9 * b.width ) / 16 );
else
d = new Dimension( ( 16 * b.height ) / 9, b.height );
content.setBounds( b.x, b.y + ( b.height - d.height ) / 2, d.width, d.height );
// setup the layout again
refreshLayout();
}
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentShown(ComponentEvent e) {}
} );
getContentPane().setLayout( null );
getContentPane().add( content );
getContentPane().setBackground( Color.DARK_GRAY );
try
{
Properties props = new Properties();
props.load( new File( "gallery/defaults.jsurf" ).toURI().toURL().openStream() );
for( Surface s : Surface.values() )
setDefaults( s, props );
}
catch( Exception e )
{
e.printStackTrace();
}
rotationAnimation = new RotationAnimation();
rotationAnimation.pause();
new Thread( rotationAnimation ).start();
idChanged( Surface.F );
idChanged( Surface.G );
new Thread( new Robot() ).start();
}
SurfaceGUIElements s2g( Surface s ) { return this.surface2guielems.get( s ); }
public void refreshLayout()
{
//blackStrip.setBounds( computeBoundsFullHD( content, 0, 84, 1920, 624 ) );
int yCenter = 380;
int surfXStart = 36 + 62 + 1;
int surfSize = ( 1920 - 2 * surfXStart ) / 3;
int surfYStart = yCenter - surfSize / 2;
s2g( Surface.F ).panel.setBounds( computeBoundsFullHD( content, surfXStart, surfYStart, surfSize, surfSize ) );
s2g( Surface.M ).panel.setBounds( computeBoundsFullHD( content, surfXStart + surfSize, surfYStart, surfSize, surfSize ) );
s2g( Surface.G ).panel.setBounds( computeBoundsFullHD( content, surfXStart + 2 * surfSize, surfYStart, surfSize, surfSize ) );
int titlePrefWidth = 700;
int titlePrefHeight = surfYStart;
s2g( Surface.F ).title.setPreferredSize( new Dimension( titlePrefWidth, titlePrefHeight ) );
s2g( Surface.F ).title.setBounds( computeBoundsFullHD( content, surfXStart + ( surfSize - titlePrefWidth ) / 2.0, 0, titlePrefWidth, titlePrefHeight ) );
s2g( Surface.G ).title.setPreferredSize( new Dimension( titlePrefWidth, titlePrefHeight ) );
s2g( Surface.G ).title.setBounds( computeBoundsFullHD( content, surfXStart + 2 * surfSize + ( surfSize - titlePrefWidth ) / 2.0, 0, titlePrefWidth, titlePrefHeight ) );
int elYStart = surfYStart + surfSize;
int elPrefHeight = 1080 - elYStart;
int elPrefWidth = 516;
double elXStart = surfXStart + ( surfSize - elPrefWidth ) / 2;
s2g( Surface.F ).equation.setPreferredSize( new Dimension( elPrefWidth, elPrefHeight ) );
s2g( Surface.F ).equation.setBounds( computeBoundsFullHD( content, elXStart, elYStart, elPrefWidth, elPrefHeight ) );
s2g( Surface.M ).equation.setPreferredSize( new Dimension( elPrefWidth, elPrefHeight ) );
s2g( Surface.M ).equation.setBounds( computeBoundsFullHD( content, 1920 / 2 - elPrefWidth / 2.0, elYStart, elPrefWidth, elPrefHeight ) );
s2g( Surface.G ).equation.setPreferredSize( new Dimension( elPrefWidth, elPrefHeight ) );
s2g( Surface.G ).equation.setBounds( computeBoundsFullHD( content, 1920 - elXStart - elPrefWidth, elYStart, elPrefWidth, elPrefHeight ) );
int gal_length = s2g( Surface.F ).galleryPanels().size();
int galSize = 62;
int spacing = 8;
int galXStart = 36;
int galYStart = yCenter - ( gal_length * galSize + ( gal_length - 1 ) * spacing ) / 2;
for( int i = 0; i < gal_length; ++i )
{
s2g( Surface.F ).galleryPanels().get( i ).setBounds( computeBoundsFullHD( content, galXStart, galYStart + i * ( galSize + spacing ), galSize, galSize ) );
s2g( Surface.F ).galleryPanels().get( i ).revalidate();
s2g( Surface.G ).galleryPanels().get( i ).setBounds( computeBoundsFullHD( content, 1920 - galXStart - galSize, galYStart + i * ( galSize + spacing ), galSize, galSize ) );
s2g( Surface.G ).galleryPanels().get( i ).revalidate();
}
triangleFTop.setBounds( computeBoundsFullHD( content, galXStart, galYStart + -1 * ( galSize + spacing ), galSize, galSize ) );
triangleFBottom.setBounds( computeBoundsFullHD( content, galXStart, galYStart + gal_length * ( galSize + spacing ), galSize, galSize ) );
triangleGTop.setBounds( computeBoundsFullHD( content, 1920 - galXStart - galSize, galYStart + -1 * ( galSize + spacing ), galSize, galSize ) );
triangleGBottom.setBounds( computeBoundsFullHD( content, 1920 - galXStart - galSize, galYStart + gal_length * ( galSize + spacing ), galSize, galSize ) );
int galYEnd = galYStart + gal_length * ( galSize + spacing ) + galSize;
s2g( Surface.F ).levelIcon.setBounds( computeBoundsFullHD( content, galXStart, galYEnd + ( 1080 - galYEnd - galSize ) / 2.0, galSize, galSize ) );
s2g( Surface.G ).levelIcon.setBounds( computeBoundsFullHD( content, 1920 - galXStart - galSize, galYEnd + ( 1080 - galYEnd - galSize ) / 2.0, galSize, galSize ) );
s2g( Surface.F ).levelLabel.setPreferredSize( new Dimension( 2 * galSize, galSize / 2 ) );
s2g( Surface.F ).levelLabel.setBounds( computeBoundsFullHD( content, galXStart - galSize / 2.0, galYEnd + ( 1080 - galYEnd ) / 2.0 - galSize, 2 * galSize, galSize / 2 ) );
s2g( Surface.G ).levelLabel.setPreferredSize( new Dimension( 2 * galSize, galSize / 2 ) );
s2g( Surface.G ).levelLabel.setBounds( computeBoundsFullHD( content, 1920 - galXStart - 3 * galSize / 2.0, galYEnd + ( 1080 - galYEnd ) / 2.0 - galSize, 2 * galSize, galSize / 2 ) );
repaint();
}
private static Rectangle computeBoundsFullHD( Component p, double x, double y, double w, double h )
{
if( p.getWidth() == 1920 && p.getHeight() == 1080 )
{
return new Rectangle( (int) x, (int) y, (int) w, (int) h );
}
else
{
x = x / 19.2; y = y / 10.8; w = w / 19.2; h = h / 10.8;
return computeBounds( p, x, y, w, h );
}
}
private static Rectangle computeBounds( Component p, double x, double y, double w, double h )
{
x = x / 100; y = y / 100; w = w / 100; h = h / 100;
return new Rectangle( (int) ( p.getWidth() * x ), (int) ( p.getHeight() * y ), (int) ( p.getWidth() * w ), (int) ( p.getHeight() * h ) );
}
protected void hideCursor()
{
// Transparent 16 x 16 pixel boolean fullscreen cursor image.
BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
// Create a new blank cursor.
Cursor blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(
cursorImg, new Point(0, 0), "blank cursor");
// Set the blank cursor to the JFrame.
getContentPane().setCursor(blankCursor);
}
public void tryFullScreen() {
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
boolean isFullScreen = device.isFullScreenSupported();
if (isFullScreen)
hideCursor();
else
System.err.println( "Fullscreen mode not supported on this plattform! We try it anyway ..." );
boolean visible = isVisible();
setVisible(false);
dispose();
setUndecorated(true);
setResizable(false);
validate();
device.setFullScreenWindow( this );
setVisible(visible);
setupControllerGUI( caGUIFrame.isVisible() || caGUIInternalFrame.isVisible() );
}
public void tryWindowed()
{
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
boolean visible = isVisible();
setVisible( false );
dispose();
setUndecorated(false);
setResizable(true);
validate();
if( device.getFullScreenWindow() == this )
device.setFullScreenWindow( null );
setVisible( visible );
setupControllerGUI( caGUIFrame.isVisible() || caGUIInternalFrame.isVisible() );
}
public void setupControllerGUI( boolean visible )
{
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
caGUIFrame.setVisible( false );
caGUIInternalFrame.setVisible( false );
caGUIFrame.dispose();
caGUIInternalFrame.dispose();
caGUIFrame.getContentPane().remove( caGUI );
caGUIInternalFrame.getContentPane().remove( caGUI );
if( device.getFullScreenWindow() == GUI.this )
{
caGUIInternalFrame = new JInternalFrame();
caGUIInternalFrame.setClosable( true );
caGUIInternalFrame.setDefaultCloseOperation( JInternalFrame.DISPOSE_ON_CLOSE );
caGUIInternalFrame.getContentPane().add( caGUI );
caGUIInternalFrame.pack();
GUI.this.getLayeredPane().add( caGUIInternalFrame );
caGUIInternalFrame.setLocation( ( this.getWidth() - caGUIInternalFrame.getWidth() ) / 2, ( this.getHeight() - caGUIInternalFrame.getHeight() ) / 2 );
caGUIInternalFrame.setVisible( visible );
}
else
{
caGUIFrame = new JFrame();
caGUIFrame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
caGUIFrame.getContentPane().add( caGUI );
caGUIFrame.pack();
if( caGUIFrame.isAlwaysOnTopSupported() )
caGUIFrame.setAlwaysOnTop( true );
caGUIFrame.setVisible( visible );
}
}
public void saveScreenShotLeft() { try { saveScreenShotToFile( new File( "left.png" ) ); } catch ( IOException ioe ) { ioe.printStackTrace(); } }
public void saveScreenShotRight() { try { saveScreenShotToFile( new File( "right.png" ) ); } catch ( IOException ioe ) { ioe.printStackTrace(); } }
public void saveScreenShotToFile( File f )
throws IOException
{
FileOutputStream fos = new FileOutputStream( f );
saveScreenShot( fos );
fos.close();
}
public void saveScreenShotToURL( URL url )
throws IOException
{
URLConnection urlCon = url.openConnection();
urlCon.setDoOutput( true );
urlCon.connect();
OutputStream out = urlCon.getOutputStream();
saveScreenShot( out );
out.close();
}
public void saveScreenShot( OutputStream out )
throws IOException
{
BufferedImage image = new BufferedImage( content.getWidth(), content.getHeight(), BufferedImage.TYPE_INT_RGB );
Graphics2D graphics2D = image.createGraphics();
content.paint( graphics2D );
javax.imageio.ImageIO.write( image, "png", out );
}
private static final String staticLaTeXSrc( Surface s )
{
LaTeXCommands.getImageMap().put( "FMPImage" + s.name(), null ); // at least put it in the map although it is still null
StringBuilder sb = new StringBuilder();
sb.append( "\\newcommand{\\fixheight}{\\vphantom{Tpgqy}}" );
// parameters
for( Parameter p : s.getParameters() )
{
sb.append( p.getLaTeXColorDefinition() );
sb.append( "\\newcommand{\\FMC");
sb.append( p.getSurface().name() );
sb.append( p.getName() );
sb.append( "}[1]{\\fgcolor{");
sb.append( p.getLaTeXColorName() );
sb.append( "}{#1}}\n" );
sb.append( "\\newcommand{\\FMB");
sb.append( p.getSurface().name() );
sb.append( p.getName() );
sb.append( "}[1]{\\FMC" );
sb.append( p.getSurface().name() );
sb.append( p.getName() );
sb.append( "{\\FMOvalbox[0.4em]{\\fgcolor{white}{#1}}}}\n" );
sb.append( "\\newcommand{\\FMP" );
sb.append( p.getSurface().name() );
sb.append( p.getName() );
sb.append( "}{\\FMB" );
sb.append( p.getSurface().name() );
sb.append( p.getName() );
sb.append( "{\\jlmDynamic{FMParam" );
sb.append( p.getSurface().name() );
sb.append( p.getName() );
sb.append( "}\\vphantom{-}}}\n" );
}
String rem;
switch( s )
{
case M:
rem = "" +
"\\newcommand{\\nl}{\\\\}\n" +
"\\sf\\fgcolor{white}{\\begin{array}{c}\n" +
"\\bf\\Large\\text{Formula Morph}\\\\\\\\\n" +
"\\sf\\FMBMt{\\jlmDynamic{OneMinusT}}\\:\\cdot\\raisebox{4.1275ex}{\\scalebox{1}[-1]{\\resizebox{7ex}{!}{\\jlmDynamic{FMImageF}}}}\\qquad{\\bf +}\\qquad\\:\\FMPMt\\:\\cdot\\raisebox{4.1275ex}{\\scalebox{1}[-1]{\\resizebox{7ex}{!}{\\jlmDynamic{FMImageG}}}}\n" +
"\\end{array}}";
break;
case F:
case G:
rem = "" +
"\\newcommand{\\nl}{\\\\}\n" +
"\\sf\\begin{array}{c}\n" +
"\\raisebox{-2.5em}{\\bf\\Large\\fgcolor{white}\\FMDynamic[i]{FMTitleFormula" + s.name() + "}}\\\\\n" +
"\\fgcolor{white}{\n" +
"\\left[\n" +
// "\\fgcolor{white}{\n" +
"\\begin{array}{c}\n" +
"\\ \\vspace{1em} \\\\\n" +
"{\\Large\\FMDynamic[i]{FMTitleWImage" + s.name() + "}=}{\\small\\raisebox{3.4ex}{\\scalebox{1}[-1]{\\resizebox{5ex}{!}{\\jlmDynamic{FMImage" + s.name() + "}}}}}\\\\\\\\\n" +
"\\FMDynamic[i]{FMEquation" + s.name() + "}\\\\\n" +
"\\hphantom{MMMMMMMMMMMMMMMMMMMaj\\,}\n" +
"\\end{array}\n" +
// "}\n" +
"\\right]\n" +
"}\\\\\n" +
"\\vspace{1em}\n" +
"\\end{array}";
break;
default:
rem = "unknown surface: " + s;
}
sb.append( rem );
return sb.toString();
}
public void setDefaults( Surface surf, Properties props )
{
AlgebraicSurfaceRenderer asr = s2g( surf ).panel.getAlgebraicSurfaceRenderer();
asr.getCamera().loadProperties( props, "camera_", "" );
Util.setOptimalCameraDistance( asr.getCamera() );
for( int i = 0; i < AlgebraicSurfaceRenderer.MAX_LIGHTS; i++ )
{
asr.getLightSource( i ).setStatus(LightSource.Status.OFF);
asr.getLightSource( i ).loadProperties( props, "light_", "_" + i );
}
asr.setBackgroundColor( BasicIO.fromColor3fString( props.getProperty( "background_color" ) ) );
Matrix4d identity = new Matrix4d();
identity.setIdentity();
asr.setTransform( BasicIO.fromMatrix4dString( props.getProperty( "rotation_matrix" ) ) );
Matrix4d scaleMatrix = new Matrix4d();
scaleMatrix.setIdentity();
scaleMatrix.setScale( 1.0 / Double.parseDouble( props.getProperty( "scale_factor" ) ) );
asr.setSurfaceTransform( scaleMatrix );
}
public void valueChanged( Parameter p )
{
LaTeXCommands.getDynamicLaTeXMap().put( "FMParam" + p.getSurface().name() + p.getName(), decimalFormatter.format( p.getValue()) );
JSurferRenderPanel jsp = s2g( p.getSurface() ).panel;
jsp.getAlgebraicSurfaceRenderer().setParameterValue( Character.toString( p.getName() ), p.getValue() );
jsp.scheduleSurfaceRepaint();
AlgebraicSurfaceRenderer asr_M = s2g( Surface.M ).panel.getAlgebraicSurfaceRenderer();
if( p.getSurface() == Surface.M )
{
// interpolate colors of the morph
float t = (float) Parameter.M_t.getValue();
asr_M.setParameterValue( Character.toString( p.getName() ), p.getValue() );
AlgebraicSurfaceRenderer asr_F = s2g( Surface.F ).panel.getAlgebraicSurfaceRenderer();
AlgebraicSurfaceRenderer asr_G = s2g( Surface.G ).panel.getAlgebraicSurfaceRenderer();
asr_M.setFrontMaterial( Material.lerp( asr_F.getFrontMaterial(), asr_G.getFrontMaterial(), t ) );
asr_M.setBackMaterial( Material.lerp( asr_F.getBackMaterial(), asr_G.getBackMaterial(), t ) );
// update OneMinusT global LaTeX variable
LaTeXCommands.getDynamicLaTeXMap().put( "OneMinusT", decimalFormatter.format( Math.max( 0.0, 1.0 - p.getValue() ) ) );
}
else
{
// the parameter at morph, too
asr_M.setParameterValue( p.name(), p.getValue() );
}
s2g( p.getSurface() ).equation.repaint();
s2g( Surface.M ).panel.scheduleSurfaceRepaint();
// System.out.println(LaTeXCommands.getDynamicLaTeXMap().toString() );
}
public void nextSurface( Surface s )
{
nextSurface( s, 1 );
}
public void previousSurface( Surface s )
{
previousSurface( s, 1 );
}
public void nextSurface( Surface s, int offset )
{
s2g( s ).setId( s2g( s ).id() + offset );
idChanged( s );
}
public void previousSurface( Surface s, int offset )
{
nextSurface( s, -offset );
}
public void setLevel( Surface s, Gallery.Level level ) // jump to the middle item in the gallery that has the requested level
{
if( s2g( s ).galleryItems().get( s2g( s ).id() ).level() != level )
{
int id;
List< Gallery.GalleryItem > galleryItems = s2g( s ).galleryItems();
for( id = 0; id < galleryItems.size() && galleryItems.get( id ).level() != level; ++id )
; // find first item with requested level
/*
int count:
for( count = 0; count + id < galleryItems.size() && galleryItems.get( id + count ).level() == level; ++count )
; // count items which have that level starting from the first one
s2g( s ).setId( id + count / 2 );
*/
s2g( s ).setId( id );
idChanged( s );
}
}
private Gallery easterEggGallery = new Gallery( Gallery.Level.BASIC, new File( "gallery" + File.separator + "easter" ) );
private java.util.Random easterEggSelector = new java.util.Random();
public void selectEasterEggSurface( Surface s )
{
List< Gallery.GalleryItem > items = easterEggGallery.getItems();
setSurface(s, items.get( easterEggSelector.nextInt( items.size() ) ) );
}
public void selectRandomSurface( Surface s ) { selectRandomSurface( s, new java.util.Random() ); }
public void selectRandomSurface( Surface s, java.util.Random r )
{
s2g( s ).setId( r.nextInt( s2g( s ).galleryItems().size() ) );
idChanged( s );
}
public void idChanged( Surface s )
{
if( s == Surface.M )
return;
List< Gallery.GalleryItem > galleryItems = s2g( s ).galleryItems();
if( s2g( s ).id() < 0 )
{
s2g( s ).setId( 0 );
return;
}
if( s2g( s ).id() >= galleryItems.size() )
{
s2g( s ).setId( galleryItems.size() - 1 );
return;
}
Gallery.GalleryItem galleryItem = galleryItems.get( s2g( s ).id() );
s2g( s ).setLevelIcon( galleryItem.level() );
{ // set content of gallery panels
List< JPanel > galleryPanels = s2g( s ).galleryPanels();
for( JPanel p : galleryPanels )
{
p.removeAll();
p.revalidate();
}
for( int panel_id = 0; panel_id < galleryPanels.size(); ++panel_id )
{
JPanel p = galleryPanels.get( panel_id );
int galItemId = s2g( s ).id() - s2g( s ).highlightedGalleryPanel() + panel_id;
if( galItemId >= 0 && galItemId < galleryItems.size() )
{
Gallery.GalleryItem item = galleryItems.get( galItemId );
item.setGrayScale( panel_id != s2g( s ).highlightedGalleryPanel() );
p.add( item );
p.revalidate();
p.repaint();
}
}
}
setSurface( s, galleryItem );
}
public void setSurface( Surface s, Gallery.GalleryItem galleryItem )
{
s2g( s ).panel.setScheduleSurfaceRepaintEnabled( false );
s2g( Surface.M ).panel.setScheduleSurfaceRepaintEnabled( false );
try
{
loadFromProperties( s, galleryItem.jsurfProperties() );
}
catch( Exception e )
{
System.err.println( "Could not load item " + s2g( s ).id() + " of " + galleryItem.level().name() + " gallery of " + s.name() );
e.printStackTrace();
return;
}
// set the morphed surface
AlgebraicSurfaceRenderer asr_F = s2g( Surface.F ).panel.getAlgebraicSurfaceRenderer();
AlgebraicSurfaceRenderer asr_M = s2g( Surface.M ).panel.getAlgebraicSurfaceRenderer();
AlgebraicSurfaceRenderer asr_G = s2g( Surface.G ).panel.getAlgebraicSurfaceRenderer();
CloneVisitor cv = new CloneVisitor();
// retrieve syntax tree for F and rename parameters (a->F_a,...)
PolynomialOperation po_F = asr_F.getSurfaceFamily().accept( cv, ( Void ) null );
Map< String, String > m_F = new HashMap< String, String >();
for( Parameter p : Surface.F.getParameters() )
m_F.put( Character.toString( p.getName() ), p.name() );
po_F = po_F.accept( new DoubleVariableRenameVisitor( m_F ), ( Void ) null );
// retrieve syntax tree for G and rename parameters (a->G_a,...)
PolynomialOperation po_G = asr_G.getSurfaceFamily().accept( cv, ( Void ) null );
Map< String, String > m_G = new HashMap< String, String >();
for( Parameter p : Surface.G.getParameters() )
m_G.put( Character.toString( p.getName() ), p.name() );
po_G = po_G.accept( new DoubleVariableRenameVisitor( m_G ), ( Void ) null );
// connect both syntax trees using po_F*(1-t)+t+po_G
PolynomialOperation po_M = new PolynomialAddition(
new PolynomialMultiplication(
new DoubleBinaryOperation(
DoubleBinaryOperation.Op.sub,
new DoubleValue( 1.0 ),
new DoubleVariable( "t" )
),
po_F
),
new PolynomialMultiplication(
new DoubleVariable( "t" ),
po_G
)
);
asr_M.setSurfaceFamily( po_M );
Parameter.M_t.setActive( true );
Parameter.M_t.setMin( 0.0 );
Parameter.M_t.setMax( 1.0 );
for( Parameter p : Surface.F.getParameters() )
{
p.notifyActivationStateListeners();
p.notifyValueChangeListeners();
}
for( Parameter p : Surface.M.getParameters() )
{
p.notifyActivationStateListeners();
p.notifyValueChangeListeners();
}
for( Parameter p : Surface.G.getParameters() )
{
p.notifyActivationStateListeners();
p.notifyValueChangeListeners();
}
s2g( s ).title.reparseOnRepaint();
s2g( s ).equation.reparseOnRepaint();
s2g( s ).panel.setScheduleSurfaceRepaintEnabled( true );
s2g( Surface.M ).panel.setScheduleSurfaceRepaintEnabled( true );
s2g( s ).panel.scheduleSurfaceRepaint();
s2g( Surface.M ).panel.scheduleSurfaceRepaint();
repaint();
}
public void reload( Surface s )
throws IOException, Exception
{
s2g( s ).galleryItems().get( s2g( s ).id() ).reload();
idChanged( s );
}
public void loadFromString( Surface surf, String s )
throws Exception
{
Properties props = new Properties();
props.load( new ByteArrayInputStream( s.getBytes() ) );
loadFromProperties( surf, props );
}
public void loadFromFile( Surface s, URL url )
throws IOException, Exception
{
Properties props = new Properties();
props.load( url.openStream() );
loadFromProperties( s, props );
}
public void loadFromProperties( Surface surf, Properties props ) // load only attributes that are not handled in setDefaults(...)
throws Exception
{
AlgebraicSurfaceRenderer asr = s2g( surf ).panel.getAlgebraicSurfaceRenderer();
asr.setSurfaceFamily( props.getProperty( "surface_equation" ) );
Set< String > param_names = asr.getAllParameterNames();
EnumSet< Parameter > unsetFormulaMorphParams = surf.getParameters();
for( String name : param_names )
{
double value, min, max, speed;
try { value = Double.parseDouble( props.getProperty( "surface_parameter_" + name ) ); } catch( NumberFormatException nfe ) { value = Double.NaN; }
try { min = Double.parseDouble( props.getProperty( "surface_parametermin_" + name ) ); } catch( NumberFormatException nfe ) { min = Double.NaN; }
try { max = Double.parseDouble( props.getProperty( "surface_parametermax_" + name ) ); } catch( NumberFormatException nfe ) { max = Double.NaN; }
try { speed = Double.parseDouble( props.getProperty( "surface_parameterspeed_" + name ) ); }
catch( NumberFormatException nfe ) { speed = Double.NaN; }
catch( NullPointerException npe ) { speed = 1.0; }
min = Double.isNaN( min ) ? value : min;
max = Double.isNaN( max ) ? value : max;
value = value < min ? min : ( value > max ? max : value );
Parameter fmp = ( name.length() == 1 ) ? surf.getParameter( name.charAt(0) ) : null;
if( fmp != null )
{
// set value/min/max of FormulaMorph parameter and activate
fmp.setMin( min );
fmp.setMax( max );
fmp.setValue( value );
fmp.setActive( true );
fmp.notifyActivationStateListeners();
fmp.notifyValueChangeListeners();
unsetFormulaMorphParams.remove( fmp );
}
}
// disable FormulaMorphParameters that are not set
for( Parameter p : unsetFormulaMorphParams )
p.setActive( false );
asr.getFrontMaterial().loadProperties(props, "front_material_", "");
asr.getBackMaterial().loadProperties(props, "back_material_", "");
LaTeXCommands.getDynamicLaTeXMap().put( "FMTitle" + surf.name(), "\\begin{array}{c}\n\\vphantom{T}\\\\\n\\text{\\fixheight{}" + props.getProperty( "surface_title_latex" ).replaceAll( "\\\\\\\\", "\\ " ) + "}\\\\\n\\vphantom{.}\\end{array}" );
LaTeXCommands.getDynamicLaTeXMap().put( "FMTitleFormula" + surf.name(), "\\begin{array}{c}\n\\text{Formula for " + props.getProperty( "surface_title_latex" ).replaceAll( "\\\\\\\\", "}\\\\\\\\\\\\text{" ) + "\\fixheight}\\end{array}" );
LaTeXCommands.getDynamicLaTeXMap().put( "FMTitleWImage" + surf.name(), "\\begin{array}{c}\n\\text{" + props.getProperty( "surface_title_latex" ).replaceAll( "\\\\\\\\", "}\\\\\\\\\\\\text{" ) + "\\fixheight}\\end{array}" );
LaTeXCommands.getDynamicLaTeXMap().put( "FMEquation" + surf.name(), "{" + props.getProperty( "surface_equation_latex_size", "" ) + "\\begin{array}{c}\n" + props.getProperty( "surface_equation_latex" ).replaceAll( "\\\\FMB", "\\\\FMB" + surf.name() ).replaceAll( "\\\\FMC", "\\\\FMC" + surf.name() ).replaceAll( "\\\\FMP", "\\\\FMP" + surf.name() ).replaceAll( "\\\\\\\\", "\\\\nl" ) + "\n\\end{array}}\n" );
}
public void stepPath( int steps ) { this.rotationAnimation.stepPath( steps ); }
public void pauseAnimation() { this.rotationAnimation.pause(); }
public void resumeAnimation() { this.rotationAnimation.resume(); }
class RotationAnimation implements Runnable
{
boolean stop;
boolean pause;
Object lock;
Quat4d current;
Quat4d step;
public RotationAnimation()
{
stop = false;
pause = true;
lock = new Object();
current = new Quat4d();
current.set( new AxisAngle4d() );
step = new Quat4d();
step.set( new AxisAngle4d() );
double angleStep = 6 * Math.PI / 1000;
Quat4d rotX = new Quat4d(); rotX.set( new AxisAngle4d( 1, 0, 0, angleStep ) ); step.mul( rotX );
Quat4d rotY = new Quat4d(); rotY.set( new AxisAngle4d( 0, 1, 0, angleStep ) ); step.mul( rotY );
Quat4d rotZ = new Quat4d(); rotZ.set( new AxisAngle4d( 0, 0, 1, angleStep ) ); step.mul( rotZ );
}
public void setPathPosition()
{
Matrix4d newRotation = new Matrix4d();
newRotation.setIdentity();
newRotation.setRotation( current );
for( Surface s : Surface.values() )
{
GUI.this.s2g(s).panel.getAlgebraicSurfaceRenderer().setTransform( newRotation );
GUI.this.s2g(s).panel.scheduleSurfaceRepaint();
}
}
public void stepPath( int steps )
{
for( int i = 0; i < steps; ++i )
current.mul( step );
for( int i = 0; i < -steps; ++i )
current.mulInverse( step );
setPathPosition();
}
public void pause() { this.pause = true; }
public void resume() { if( pause ) { synchronized( lock ) { lock.notify(); } } this.pause = false; }
public void stop() { this.stop = true; }
public void run()
{
synchronized( lock )
{
try{ Thread.sleep( 500 ); } catch( Exception e ) {}
while( !stop )
{
try
{
Thread.sleep( 20 );
if( pause )
lock.wait();
} catch( Exception e ) {}
stepPath( 1 );
setPathPosition();
}
}
}
}
}
| src/com/moeyinc/formulamorph/GUI.java | package com.moeyinc.formulamorph;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.vecmath.*;
import javax.imageio.ImageIO;
import java.io.*;
import java.net.*;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Properties;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.EnumSet;
import java.text.DecimalFormat;
//import com.moeyinc.formulamorph.Parameters.ActiveParameterListener;
import de.mfo.jsurfer.algebra.*;
import de.mfo.jsurfer.rendering.*;
import de.mfo.jsurfer.util.BasicIO;
public class GUI extends JFrame implements Parameter.ValueChangeListener
{
class SurfaceGUIElements
{
final public JSurferRenderPanel panel;
final public LaTeXLabel title;
final public LaTeXLabel equation;
final public JPanel levelIcon;
final public LaTeXLabel levelLabel;
final private Surface surface;
private List< Gallery.GalleryItem > gallery_items;
private List< Gallery.GalleryItem > gallery_items_unmodifyable;
private int id_in_gallery;
private ArrayList< JPanel > gallery_panels;
private List< JPanel > gallery_panels_unmodifiable;
private Map< Gallery.Level, ImageScaler > levelIcons;
public SurfaceGUIElements( Surface s )
{
levelIcons = new EnumMap< Gallery.Level, ImageScaler >( Gallery.Level.class );
levelIcons.put( Gallery.Level.BASIC, new ImageScaler( sierpinskiBASIC ) );
levelIcons.put( Gallery.Level.INTERMEDIATE, new ImageScaler( sierpinskiINTERMEDIATE ) );
levelIcons.put( Gallery.Level.ADVANCED, new ImageScaler( sierpinskiADVANCED ) );
surface = s;
id_in_gallery = 0;
LaTeXCommands.getDynamicLaTeXMap().put( "FMImage" + s.name(), "\\includejavaimage[interpolation=bicubic]{FMImage" + s.name() + "}" );
this.panel = new JSurferRenderPanel();
this.title = new LaTeXLabel( "\\sf\\bf\\LARGE\\fgcolor{white}{\\jlmDynamic{FMTitle" + s.name() + "}}" );
this.title.setHAlignment( LaTeXLabel.HAlignment.CENTER );
this.title.setVAlignment( LaTeXLabel.VAlignment.CENTER_BASELINE );
//this.title.setBackground( Color.GRAY ); this.title.setOpaque( true );
this.equation = new LaTeXLabel( staticLaTeXSrc( s ) );
//this.equation.setBackground( Color.GRAY ); this.equation.setOpaque( true );
this.levelIcon = new JPanel( new BorderLayout() );
this.levelLabel = new LaTeXLabel( "\\tiny\\fgcolor{white}{\\jlmDynamic{FMLevel" + s.name() + "}}" );
gallery_panels = new ArrayList< JPanel >();
for( int i = 0; i < 7; ++i )
{
JPanel p = new JPanel( new BorderLayout() );
p.setBackground( new Color( 0.1f, 0.1f, 0.1f ) );
p.setOpaque( true );
gallery_panels.add( i, p );
}
gallery_panels.get( gallery_panels.size() / 2 ).setBorder( BorderFactory.createLineBorder( Color.WHITE, 3 ) );
gallery_panels_unmodifiable = Collections.unmodifiableList( gallery_panels );
// load galleries
gallery_items = new ArrayList< Gallery.GalleryItem >();
gallery_items_unmodifyable = Collections.unmodifiableList( gallery_items );
try
{
switch( surface )
{
case F:
case G:
this.gallery_items.addAll( new Gallery( Gallery.Level.BASIC, new File( "gallery" + File.separator + "basic" ) ).getItems() );
this.gallery_items.addAll( new Gallery( Gallery.Level.INTERMEDIATE, new File( "gallery" + File.separator + "intermediate" ) ).getItems() );
this.gallery_items.addAll( new Gallery( Gallery.Level.ADVANCED, new File( "gallery" + File.separator + "advanced" ) ).getItems() );
break;
default:
break;
}
}
catch( Exception e )
{
System.err.println( "Unable to initialize galleries" );
e.printStackTrace( System.err );
System.exit( -1 );
}
}
public int id() { return id_in_gallery; }
public void setId( int id ) { id_in_gallery = id; }
public List< Gallery.GalleryItem > galleryItems() { return gallery_items_unmodifyable; }
public List< JPanel > galleryPanels() { return gallery_panels_unmodifiable; }
public int highlightedGalleryPanel() { return 3; }
public void setLevelIcon( Gallery.Level l )
{
LaTeXCommands.getDynamicLaTeXMap().put( "FMLevel" + surface.name(), l.name().substring(0,1).toUpperCase() + l.name().substring(1).toLowerCase() );
this.levelIcon.removeAll();
this.levelIcon.add( this.levelIcons.get( l ) );
}
}
JPanel content; // fixed 16:9 top container
static final double aspectRatio = 16.0 / 9.0;
static final DecimalFormat decimalFormatter = new DecimalFormat("#0.00");
EnumMap< Surface, SurfaceGUIElements > surface2guielems = new EnumMap< Surface, SurfaceGUIElements >( Surface.class );
static BufferedImage triangle;
static BufferedImage triangleFlipped;
static {
triangle = new BufferedImage( 100, 100, BufferedImage.TYPE_BYTE_GRAY );
Graphics2D g = (Graphics2D) triangle.getGraphics();
g.setColor( new Color( 0, 0, 0, 0 ) );
g.fillRect( 0, 0, triangle.getWidth(), triangle.getHeight() );
g.setColor( Color.LIGHT_GRAY );
Polygon p = new Polygon();
p.addPoint( -triangle.getWidth() / 2, 0 );
p.addPoint( triangle.getWidth() / 2, 0 );
p.addPoint( 0, (int) ( triangle.getWidth() * Math.sqrt( 3.0 ) / 2.0 ) );
AffineTransform tx = AffineTransform.getScaleInstance( 0.6, 0.6 );
tx.preConcatenate( AffineTransform.getTranslateInstance( triangle.getWidth() / 2, 0 ) );
g.setTransform( tx );
g.fillPolygon( p );
tx = AffineTransform.getScaleInstance(1, -1);
tx.translate(0, -triangle.getHeight(null));
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
triangleFlipped = op.filter( triangle, null);
}
ImageScaler triangleFTop = new ImageScaler( triangleFlipped );
ImageScaler triangleFBottom = new ImageScaler( triangle );
ImageScaler triangleGTop = new ImageScaler( triangleFlipped );
ImageScaler triangleGBottom = new ImageScaler( triangle );
static BufferedImage sierpinskiBASIC = loadIMGResource( "BASIC.png" );
static BufferedImage sierpinskiINTERMEDIATE = loadIMGResource( "INTERMEDIATE.png" );
static BufferedImage sierpinskiADVANCED = loadIMGResource( "ADVANCED.png" );
public static BufferedImage loadIMGResource( String path )
{
InputStream stream = GUI.class.getResourceAsStream( path );
try
{
return ImageIO.read( stream );
}
catch (IOException e)
{
System.err.println( "unable to load resource \"" + path + "\"" );
e.printStackTrace();
}
return new BufferedImage( 1,1, BufferedImage.TYPE_BYTE_GRAY );
}
//JPanel blackStrip;
RotationAnimation rotationAnimation;
final GUIController caGUI = new GUIController();
JFrame caGUIFrame = new JFrame();
JInternalFrame caGUIInternalFrame = new JInternalFrame();
public GUI()
throws Exception, IOException
{
super( "FormulaMorph Main Window" );
this.getLayeredPane().add( caGUIInternalFrame );
this.addMouseListener( new MouseAdapter() { public void mouseClicked( MouseEvent e ) { setupControllerGUI( true ); } } );
Parameter.M_t.setMin( 0.0 );
Parameter.M_t.setMax( 1.0 );
Parameter.M_t.setValue( 0.5 );
LaTeXCommands.getDynamicLaTeXMap().put( "OneMinusT", "0.00" );
for( Parameter p : Parameter.values() )
p.addValueChangeListener( this );
// setup the container which has fixed 16:9 aspect ratio
content = new JPanel();
content.setBackground(Color.BLACK);
content.setLayout( null );
// init components
surface2guielems.put( Surface.F, new SurfaceGUIElements( Surface.F ) );
surface2guielems.put( Surface.M, new SurfaceGUIElements( Surface.M ) );
surface2guielems.put( Surface.G, new SurfaceGUIElements( Surface.G ) );
//blackStrip = new JPanel(); blackStrip.setBackground( Color.black );
final LaTeXLabel eqF = s2g( Surface.F ).equation;
final LaTeXLabel eqM = s2g( Surface.M ).equation;
final LaTeXLabel eqG = s2g( Surface.G ).equation;
s2g( Surface.F ).panel.addImageUpdateListener( new JSurferRenderPanel.ImageUpdateListener() {
public void imageUpdated( Image img )
{
LaTeXCommands.getImageMap().put( "FMImageF", img );
eqF.repaint();
eqM.repaint();
}
});
s2g( Surface.G ).panel.addImageUpdateListener( new JSurferRenderPanel.ImageUpdateListener() {
public void imageUpdated( Image img )
{
LaTeXCommands.getImageMap().put( "FMImageG", img );
eqG.repaint();
eqM.repaint();
}
});
// add components
content.add( s2g( Surface.F ).title );
content.add( s2g( Surface.F ).panel );
content.add( s2g( Surface.F ).equation );
content.add( s2g( Surface.M ).panel );
content.add( s2g( Surface.M ).equation );
content.add( s2g( Surface.G ).title );
content.add( s2g( Surface.G ).panel );
content.add( s2g( Surface.G ).equation );
for( JComponent c : s2g( Surface.F ).galleryPanels() )
content.add( c );
for( JComponent c : s2g( Surface.G ).galleryPanels() )
content.add( c );
content.add( triangleFTop );
content.add( triangleFBottom );
content.add( triangleGTop );
content.add( triangleGBottom );
content.add( s2g( Surface.F ).levelLabel );
content.add( s2g( Surface.F ).levelIcon );
content.add( s2g( Surface.G ).levelLabel );
content.add( s2g( Surface.G ).levelIcon );
//content.add( blackStrip );
// layout components
refreshLayout();
getContentPane().addComponentListener( new ComponentListener() {
public void componentResized(ComponentEvent e) {
// keep aspect ratio
Rectangle b = e.getComponent().getBounds();
Dimension d;
if( b.width * 9 < b.height * 16 )
d = new Dimension( b.width, ( 9 * b.width ) / 16 );
else
d = new Dimension( ( 16 * b.height ) / 9, b.height );
content.setBounds( b.x, b.y + ( b.height - d.height ) / 2, d.width, d.height );
// setup the layout again
refreshLayout();
}
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentShown(ComponentEvent e) {}
} );
getContentPane().setLayout( null );
getContentPane().add( content );
getContentPane().setBackground( Color.DARK_GRAY );
try
{
Properties props = new Properties();
props.load( new File( "gallery/defaults.jsurf" ).toURI().toURL().openStream() );
for( Surface s : Surface.values() )
setDefaults( s, props );
}
catch( Exception e )
{
e.printStackTrace();
}
rotationAnimation = new RotationAnimation();
rotationAnimation.pause();
new Thread( rotationAnimation ).start();
idChanged( Surface.F );
idChanged( Surface.G );
new Thread( new Robot() ).start();
}
SurfaceGUIElements s2g( Surface s ) { return this.surface2guielems.get( s ); }
public void refreshLayout()
{
//blackStrip.setBounds( computeBoundsFullHD( content, 0, 84, 1920, 624 ) );
int yCenter = 380;
int surfXStart = 36 + 62 + 1;
int surfSize = ( 1920 - 2 * surfXStart ) / 3;
int surfYStart = yCenter - surfSize / 2;
s2g( Surface.F ).panel.setBounds( computeBoundsFullHD( content, surfXStart, surfYStart, surfSize, surfSize ) );
s2g( Surface.M ).panel.setBounds( computeBoundsFullHD( content, surfXStart + surfSize, surfYStart, surfSize, surfSize ) );
s2g( Surface.G ).panel.setBounds( computeBoundsFullHD( content, surfXStart + 2 * surfSize, surfYStart, surfSize, surfSize ) );
int titlePrefWidth = 700;
int titlePrefHeight = surfYStart;
s2g( Surface.F ).title.setPreferredSize( new Dimension( titlePrefWidth, titlePrefHeight ) );
s2g( Surface.F ).title.setBounds( computeBoundsFullHD( content, surfXStart + ( surfSize - titlePrefWidth ) / 2.0, 0, titlePrefWidth, titlePrefHeight ) );
s2g( Surface.G ).title.setPreferredSize( new Dimension( titlePrefWidth, titlePrefHeight ) );
s2g( Surface.G ).title.setBounds( computeBoundsFullHD( content, surfXStart + 2 * surfSize + ( surfSize - titlePrefWidth ) / 2.0, 0, titlePrefWidth, titlePrefHeight ) );
int elYStart = surfYStart + surfSize;
int elPrefHeight = 1080 - elYStart;
int elPrefWidth = 516;
double elXStart = surfXStart + ( surfSize - elPrefWidth ) / 2;
s2g( Surface.F ).equation.setPreferredSize( new Dimension( elPrefWidth, elPrefHeight ) );
s2g( Surface.F ).equation.setBounds( computeBoundsFullHD( content, elXStart, elYStart, elPrefWidth, elPrefHeight ) );
s2g( Surface.M ).equation.setPreferredSize( new Dimension( elPrefWidth, elPrefHeight ) );
s2g( Surface.M ).equation.setBounds( computeBoundsFullHD( content, 1920 / 2 - elPrefWidth / 2.0, elYStart, elPrefWidth, elPrefHeight ) );
s2g( Surface.G ).equation.setPreferredSize( new Dimension( elPrefWidth, elPrefHeight ) );
s2g( Surface.G ).equation.setBounds( computeBoundsFullHD( content, 1920 - elXStart - elPrefWidth, elYStart, elPrefWidth, elPrefHeight ) );
int gal_length = s2g( Surface.F ).galleryPanels().size();
int galSize = 62;
int spacing = 8;
int galXStart = 36;
int galYStart = yCenter - ( gal_length * galSize + ( gal_length - 1 ) * spacing ) / 2;
for( int i = 0; i < gal_length; ++i )
{
s2g( Surface.F ).galleryPanels().get( i ).setBounds( computeBoundsFullHD( content, galXStart, galYStart + i * ( galSize + spacing ), galSize, galSize ) );
s2g( Surface.F ).galleryPanels().get( i ).revalidate();
s2g( Surface.G ).galleryPanels().get( i ).setBounds( computeBoundsFullHD( content, 1920 - galXStart - galSize, galYStart + i * ( galSize + spacing ), galSize, galSize ) );
s2g( Surface.G ).galleryPanels().get( i ).revalidate();
}
triangleFTop.setBounds( computeBoundsFullHD( content, galXStart, galYStart + -1 * ( galSize + spacing ), galSize, galSize ) );
triangleFBottom.setBounds( computeBoundsFullHD( content, galXStart, galYStart + gal_length * ( galSize + spacing ), galSize, galSize ) );
triangleGTop.setBounds( computeBoundsFullHD( content, 1920 - galXStart - galSize, galYStart + -1 * ( galSize + spacing ), galSize, galSize ) );
triangleGBottom.setBounds( computeBoundsFullHD( content, 1920 - galXStart - galSize, galYStart + gal_length * ( galSize + spacing ), galSize, galSize ) );
int galYEnd = galYStart + gal_length * ( galSize + spacing ) + galSize;
s2g( Surface.F ).levelIcon.setBounds( computeBoundsFullHD( content, galXStart, galYEnd + ( 1080 - galYEnd - galSize ) / 2.0, galSize, galSize ) );
s2g( Surface.G ).levelIcon.setBounds( computeBoundsFullHD( content, 1920 - galXStart - galSize, galYEnd + ( 1080 - galYEnd - galSize ) / 2.0, galSize, galSize ) );
s2g( Surface.F ).levelLabel.setPreferredSize( new Dimension( 2 * galSize, galSize / 2 ) );
s2g( Surface.F ).levelLabel.setBounds( computeBoundsFullHD( content, galXStart - galSize / 2.0, galYEnd + ( 1080 - galYEnd ) / 2.0 - galSize, 2 * galSize, galSize / 2 ) );
s2g( Surface.G ).levelLabel.setPreferredSize( new Dimension( 2 * galSize, galSize / 2 ) );
s2g( Surface.G ).levelLabel.setBounds( computeBoundsFullHD( content, 1920 - galXStart - 3 * galSize / 2.0, galYEnd + ( 1080 - galYEnd ) / 2.0 - galSize, 2 * galSize, galSize / 2 ) );
repaint();
}
private static Rectangle computeBoundsFullHD( Component p, double x, double y, double w, double h )
{
if( p.getWidth() == 1920 && p.getHeight() == 1080 )
{
return new Rectangle( (int) x, (int) y, (int) w, (int) h );
}
else
{
x = x / 19.2; y = y / 10.8; w = w / 19.2; h = h / 10.8;
return computeBounds( p, x, y, w, h );
}
}
private static Rectangle computeBounds( Component p, double x, double y, double w, double h )
{
x = x / 100; y = y / 100; w = w / 100; h = h / 100;
return new Rectangle( (int) ( p.getWidth() * x ), (int) ( p.getHeight() * y ), (int) ( p.getWidth() * w ), (int) ( p.getHeight() * h ) );
}
protected void hideCursor()
{
// Transparent 16 x 16 pixel boolean fullscreen cursor image.
BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
// Create a new blank cursor.
Cursor blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(
cursorImg, new Point(0, 0), "blank cursor");
// Set the blank cursor to the JFrame.
getContentPane().setCursor(blankCursor);
}
public void tryFullScreen() {
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
boolean isFullScreen = device.isFullScreenSupported();
if (isFullScreen)
hideCursor();
else
System.err.println( "Fullscreen mode not supported on this plattform! We try it anyway ..." );
boolean visible = isVisible();
setVisible(false);
dispose();
setUndecorated(true);
setResizable(false);
validate();
device.setFullScreenWindow( this );
setVisible(visible);
setupControllerGUI( caGUIFrame.isVisible() || caGUIInternalFrame.isVisible() );
}
public void tryWindowed()
{
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
boolean visible = isVisible();
setVisible( false );
dispose();
setUndecorated(false);
setResizable(true);
validate();
if( device.getFullScreenWindow() == this )
device.setFullScreenWindow( null );
setVisible( visible );
setupControllerGUI( caGUIFrame.isVisible() || caGUIInternalFrame.isVisible() );
}
public void setupControllerGUI( boolean visible )
{
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
caGUIFrame.setVisible( false );
caGUIInternalFrame.setVisible( false );
caGUIFrame.dispose();
caGUIInternalFrame.dispose();
caGUIFrame.getContentPane().remove( caGUI );
caGUIInternalFrame.getContentPane().remove( caGUI );
if( device.getFullScreenWindow() == GUI.this )
{
caGUIInternalFrame = new JInternalFrame();
caGUIInternalFrame.setClosable( true );
caGUIInternalFrame.setDefaultCloseOperation( JInternalFrame.DISPOSE_ON_CLOSE );
caGUIInternalFrame.getContentPane().add( caGUI );
caGUIInternalFrame.pack();
GUI.this.getLayeredPane().add( caGUIInternalFrame );
caGUIInternalFrame.setLocation( ( this.getWidth() - caGUIInternalFrame.getWidth() ) / 2, ( this.getHeight() - caGUIInternalFrame.getHeight() ) / 2 );
caGUIInternalFrame.setVisible( visible );
}
else
{
caGUIFrame = new JFrame();
caGUIFrame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
caGUIFrame.getContentPane().add( caGUI );
caGUIFrame.pack();
if( caGUIFrame.isAlwaysOnTopSupported() )
caGUIFrame.setAlwaysOnTop( true );
caGUIFrame.setVisible( visible );
}
}
public void saveScreenShotLeft() { try { saveScreenShotToFile( new File( "left.png" ) ); } catch ( IOException ioe ) { ioe.printStackTrace(); } }
public void saveScreenShotRight() { try { saveScreenShotToFile( new File( "right.png" ) ); } catch ( IOException ioe ) { ioe.printStackTrace(); } }
public void saveScreenShotToFile( File f )
throws IOException
{
FileOutputStream fos = new FileOutputStream( f );
saveScreenShot( fos );
fos.close();
}
public void saveScreenShotToURL( URL url )
throws IOException
{
URLConnection urlCon = url.openConnection();
urlCon.setDoOutput( true );
urlCon.connect();
OutputStream out = urlCon.getOutputStream();
saveScreenShot( out );
out.close();
}
public void saveScreenShot( OutputStream out )
throws IOException
{
BufferedImage image = new BufferedImage( content.getWidth(), content.getHeight(), BufferedImage.TYPE_INT_RGB );
Graphics2D graphics2D = image.createGraphics();
content.paint( graphics2D );
javax.imageio.ImageIO.write( image, "png", out );
}
private static final String staticLaTeXSrc( Surface s )
{
LaTeXCommands.getImageMap().put( "FMPImage" + s.name(), null ); // at least put it in the map although it is still null
StringBuilder sb = new StringBuilder();
sb.append( "\\newcommand{\\fixheight}{\\vphantom{Tpgqy}}" );
// parameters
for( Parameter p : s.getParameters() )
{
sb.append( p.getLaTeXColorDefinition() );
sb.append( "\\newcommand{\\FMC");
sb.append( p.getSurface().name() );
sb.append( p.getName() );
sb.append( "}[1]{\\fgcolor{");
sb.append( p.getLaTeXColorName() );
sb.append( "}{#1}}\n" );
sb.append( "\\newcommand{\\FMB");
sb.append( p.getSurface().name() );
sb.append( p.getName() );
sb.append( "}[1]{\\FMC" );
sb.append( p.getSurface().name() );
sb.append( p.getName() );
sb.append( "{\\FMOvalbox[0.4em]{\\fgcolor{white}{#1}}}}\n" );
sb.append( "\\newcommand{\\FMP" );
sb.append( p.getSurface().name() );
sb.append( p.getName() );
sb.append( "}{\\FMB" );
sb.append( p.getSurface().name() );
sb.append( p.getName() );
sb.append( "{\\jlmDynamic{FMParam" );
sb.append( p.getSurface().name() );
sb.append( p.getName() );
sb.append( "}\\vphantom{-}}}\n" );
}
String rem;
switch( s )
{
case M:
rem = "" +
"\\newcommand{\\nl}{\\\\}\n" +
"\\sf\\fgcolor{white}{\\begin{array}{c}\n" +
"\\bf\\Large\\text{Formula Morph}\\\\\\\\\n" +
"\\sf\\FMBMt{\\jlmDynamic{OneMinusT}}\\:\\cdot\\raisebox{4.1275ex}{\\scalebox{1}[-1]{\\resizebox{7ex}{!}{\\jlmDynamic{FMImageF}}}}\\qquad{\\bf +}\\qquad\\:\\FMPMt\\:\\cdot\\raisebox{4.1275ex}{\\scalebox{1}[-1]{\\resizebox{7ex}{!}{\\jlmDynamic{FMImageG}}}}\n" +
"\\end{array}}";
break;
case F:
case G:
rem = "" +
"\\newcommand{\\nl}{\\\\}\n" +
"\\sf\\begin{array}{c}\n" +
"\\raisebox{-2.5em}{\\bf\\Large\\fgcolor{white}\\FMDynamic[i]{FMTitleFormula" + s.name() + "}}\\\\\n" +
"\\fgcolor{white}{\n" +
"\\left[\n" +
// "\\fgcolor{white}{\n" +
"\\begin{array}{c}\n" +
"\\ \\vspace{1em} \\\\\n" +
"{\\Large\\FMDynamic[i]{FMTitleWImage" + s.name() + "}=}{\\small\\raisebox{3.4ex}{\\scalebox{1}[-1]{\\resizebox{5ex}{!}{\\jlmDynamic{FMImage" + s.name() + "}}}}}\\\\\\\\\n" +
"\\FMDynamic[i]{FMEquation" + s.name() + "}\\\\\n" +
"\\hphantom{MMMMMMMMMMMMMMMMMMMaj\\,}\n" +
"\\end{array}\n" +
// "}\n" +
"\\right]\n" +
"}\\\\\n" +
"\\vspace{1em}\n" +
"\\end{array}";
break;
default:
rem = "unknown surface: " + s;
}
sb.append( rem );
return sb.toString();
}
public void setDefaults( Surface surf, Properties props )
{
AlgebraicSurfaceRenderer asr = s2g( surf ).panel.getAlgebraicSurfaceRenderer();
asr.getCamera().loadProperties( props, "camera_", "" );
Util.setOptimalCameraDistance( asr.getCamera() );
for( int i = 0; i < AlgebraicSurfaceRenderer.MAX_LIGHTS; i++ )
{
asr.getLightSource( i ).setStatus(LightSource.Status.OFF);
asr.getLightSource( i ).loadProperties( props, "light_", "_" + i );
}
asr.setBackgroundColor( BasicIO.fromColor3fString( props.getProperty( "background_color" ) ) );
Matrix4d identity = new Matrix4d();
identity.setIdentity();
asr.setTransform( BasicIO.fromMatrix4dString( props.getProperty( "rotation_matrix" ) ) );
Matrix4d scaleMatrix = new Matrix4d();
scaleMatrix.setIdentity();
scaleMatrix.setScale( 1.0 / Double.parseDouble( props.getProperty( "scale_factor" ) ) );
asr.setSurfaceTransform( scaleMatrix );
}
public void valueChanged( Parameter p )
{
LaTeXCommands.getDynamicLaTeXMap().put( "FMParam" + p.getSurface().name() + p.getName(), decimalFormatter.format( p.getValue()) );
JSurferRenderPanel jsp = s2g( p.getSurface() ).panel;
jsp.getAlgebraicSurfaceRenderer().setParameterValue( Character.toString( p.getName() ), p.getValue() );
jsp.scheduleSurfaceRepaint();
AlgebraicSurfaceRenderer asr_M = s2g( Surface.M ).panel.getAlgebraicSurfaceRenderer();
if( p.getSurface() == Surface.M )
{
// interpolate colors of the morph
float t = (float) Parameter.M_t.getValue();
asr_M.setParameterValue( Character.toString( p.getName() ), p.getValue() );
AlgebraicSurfaceRenderer asr_F = s2g( Surface.F ).panel.getAlgebraicSurfaceRenderer();
AlgebraicSurfaceRenderer asr_G = s2g( Surface.G ).panel.getAlgebraicSurfaceRenderer();
asr_M.setFrontMaterial( Material.lerp( asr_F.getFrontMaterial(), asr_G.getFrontMaterial(), t ) );
asr_M.setBackMaterial( Material.lerp( asr_F.getBackMaterial(), asr_G.getBackMaterial(), t ) );
// update OneMinusT global LaTeX variable
LaTeXCommands.getDynamicLaTeXMap().put( "OneMinusT", decimalFormatter.format( Math.max( 0.0, 1.0 - p.getValue() ) ) );
}
else
{
// the parameter at morph, too
asr_M.setParameterValue( p.name(), p.getValue() );
}
s2g( p.getSurface() ).equation.repaint();
s2g( Surface.M ).panel.scheduleSurfaceRepaint();
// System.out.println(LaTeXCommands.getDynamicLaTeXMap().toString() );
}
public void nextSurface( Surface s )
{
nextSurface( s, 1 );
}
public void previousSurface( Surface s )
{
previousSurface( s, 1 );
}
public void nextSurface( Surface s, int offset )
{
s2g( s ).setId( s2g( s ).id() + offset );
idChanged( s );
}
public void previousSurface( Surface s, int offset )
{
nextSurface( s, -offset );
}
public void setLevel( Surface s, Gallery.Level level ) // jump to the middle item in the gallery that has the requested level
{
if( s2g( s ).galleryItems().get( s2g( s ).id() ).level() != level )
{
int id, count;
List< Gallery.GalleryItem > galleryItems = s2g( s ).galleryItems();
for( id = 0; id < galleryItems.size() && galleryItems.get( id ).level() != level; ++id )
; // find first item with requested level
for( count = 0; count + id < galleryItems.size() && galleryItems.get( id + count ).level() == level; ++count )
; // count items which have that level starting from the first one
s2g( s ).setId( id + count / 2 );
idChanged( s );
}
}
private Gallery easterEggGallery = new Gallery( Gallery.Level.BASIC, new File( "gallery" + File.separator + "easter" ) );
private java.util.Random easterEggSelector = new java.util.Random();
public void selectEasterEggSurface( Surface s )
{
List< Gallery.GalleryItem > items = easterEggGallery.getItems();
setSurface(s, items.get( easterEggSelector.nextInt( items.size() ) ) );
}
public void selectRandomSurface( Surface s ) { selectRandomSurface( s, new java.util.Random() ); }
public void selectRandomSurface( Surface s, java.util.Random r )
{
s2g( s ).setId( r.nextInt( s2g( s ).galleryItems().size() ) );
idChanged( s );
}
public void idChanged( Surface s )
{
if( s == Surface.M )
return;
List< Gallery.GalleryItem > galleryItems = s2g( s ).galleryItems();
if( s2g( s ).id() < 0 )
{
s2g( s ).setId( 0 );
return;
}
if( s2g( s ).id() >= galleryItems.size() )
{
s2g( s ).setId( galleryItems.size() - 1 );
return;
}
Gallery.GalleryItem galleryItem = galleryItems.get( s2g( s ).id() );
s2g( s ).setLevelIcon( galleryItem.level() );
{ // set content of gallery panels
List< JPanel > galleryPanels = s2g( s ).galleryPanels();
for( JPanel p : galleryPanels )
{
p.removeAll();
p.revalidate();
}
for( int panel_id = 0; panel_id < galleryPanels.size(); ++panel_id )
{
JPanel p = galleryPanels.get( panel_id );
int galItemId = s2g( s ).id() - s2g( s ).highlightedGalleryPanel() + panel_id;
if( galItemId >= 0 && galItemId < galleryItems.size() )
{
Gallery.GalleryItem item = galleryItems.get( galItemId );
item.setGrayScale( panel_id != s2g( s ).highlightedGalleryPanel() );
p.add( item );
p.revalidate();
p.repaint();
}
}
}
setSurface( s, galleryItem );
}
public void setSurface( Surface s, Gallery.GalleryItem galleryItem )
{
s2g( s ).panel.setScheduleSurfaceRepaintEnabled( false );
s2g( Surface.M ).panel.setScheduleSurfaceRepaintEnabled( false );
try
{
loadFromProperties( s, galleryItem.jsurfProperties() );
}
catch( Exception e )
{
System.err.println( "Could not load item " + s2g( s ).id() + " of " + galleryItem.level().name() + " gallery of " + s.name() );
e.printStackTrace();
return;
}
// set the morphed surface
AlgebraicSurfaceRenderer asr_F = s2g( Surface.F ).panel.getAlgebraicSurfaceRenderer();
AlgebraicSurfaceRenderer asr_M = s2g( Surface.M ).panel.getAlgebraicSurfaceRenderer();
AlgebraicSurfaceRenderer asr_G = s2g( Surface.G ).panel.getAlgebraicSurfaceRenderer();
CloneVisitor cv = new CloneVisitor();
// retrieve syntax tree for F and rename parameters (a->F_a,...)
PolynomialOperation po_F = asr_F.getSurfaceFamily().accept( cv, ( Void ) null );
Map< String, String > m_F = new HashMap< String, String >();
for( Parameter p : Surface.F.getParameters() )
m_F.put( Character.toString( p.getName() ), p.name() );
po_F = po_F.accept( new DoubleVariableRenameVisitor( m_F ), ( Void ) null );
// retrieve syntax tree for G and rename parameters (a->G_a,...)
PolynomialOperation po_G = asr_G.getSurfaceFamily().accept( cv, ( Void ) null );
Map< String, String > m_G = new HashMap< String, String >();
for( Parameter p : Surface.G.getParameters() )
m_G.put( Character.toString( p.getName() ), p.name() );
po_G = po_G.accept( new DoubleVariableRenameVisitor( m_G ), ( Void ) null );
// connect both syntax trees using po_F*(1-t)+t+po_G
PolynomialOperation po_M = new PolynomialAddition(
new PolynomialMultiplication(
new DoubleBinaryOperation(
DoubleBinaryOperation.Op.sub,
new DoubleValue( 1.0 ),
new DoubleVariable( "t" )
),
po_F
),
new PolynomialMultiplication(
new DoubleVariable( "t" ),
po_G
)
);
asr_M.setSurfaceFamily( po_M );
Parameter.M_t.setActive( true );
Parameter.M_t.setMin( 0.0 );
Parameter.M_t.setMax( 1.0 );
for( Parameter p : Surface.F.getParameters() )
{
p.notifyActivationStateListeners();
p.notifyValueChangeListeners();
}
for( Parameter p : Surface.M.getParameters() )
{
p.notifyActivationStateListeners();
p.notifyValueChangeListeners();
}
for( Parameter p : Surface.G.getParameters() )
{
p.notifyActivationStateListeners();
p.notifyValueChangeListeners();
}
s2g( s ).title.reparseOnRepaint();
s2g( s ).equation.reparseOnRepaint();
s2g( s ).panel.setScheduleSurfaceRepaintEnabled( true );
s2g( Surface.M ).panel.setScheduleSurfaceRepaintEnabled( true );
s2g( s ).panel.scheduleSurfaceRepaint();
s2g( Surface.M ).panel.scheduleSurfaceRepaint();
repaint();
}
public void reload( Surface s )
throws IOException, Exception
{
s2g( s ).galleryItems().get( s2g( s ).id() ).reload();
idChanged( s );
}
public void loadFromString( Surface surf, String s )
throws Exception
{
Properties props = new Properties();
props.load( new ByteArrayInputStream( s.getBytes() ) );
loadFromProperties( surf, props );
}
public void loadFromFile( Surface s, URL url )
throws IOException, Exception
{
Properties props = new Properties();
props.load( url.openStream() );
loadFromProperties( s, props );
}
public void loadFromProperties( Surface surf, Properties props ) // load only attributes that are not handled in setDefaults(...)
throws Exception
{
AlgebraicSurfaceRenderer asr = s2g( surf ).panel.getAlgebraicSurfaceRenderer();
asr.setSurfaceFamily( props.getProperty( "surface_equation" ) );
Set< String > param_names = asr.getAllParameterNames();
EnumSet< Parameter > unsetFormulaMorphParams = surf.getParameters();
for( String name : param_names )
{
double value, min, max, speed;
try { value = Double.parseDouble( props.getProperty( "surface_parameter_" + name ) ); } catch( NumberFormatException nfe ) { value = Double.NaN; }
try { min = Double.parseDouble( props.getProperty( "surface_parametermin_" + name ) ); } catch( NumberFormatException nfe ) { min = Double.NaN; }
try { max = Double.parseDouble( props.getProperty( "surface_parametermax_" + name ) ); } catch( NumberFormatException nfe ) { max = Double.NaN; }
try { speed = Double.parseDouble( props.getProperty( "surface_parameterspeed_" + name ) ); }
catch( NumberFormatException nfe ) { speed = Double.NaN; }
catch( NullPointerException npe ) { speed = 1.0; }
min = Double.isNaN( min ) ? value : min;
max = Double.isNaN( max ) ? value : max;
value = value < min ? min : ( value > max ? max : value );
Parameter fmp = ( name.length() == 1 ) ? surf.getParameter( name.charAt(0) ) : null;
if( fmp != null )
{
// set value/min/max of FormulaMorph parameter and activate
fmp.setMin( min );
fmp.setMax( max );
fmp.setValue( value );
fmp.setActive( true );
fmp.notifyActivationStateListeners();
fmp.notifyValueChangeListeners();
unsetFormulaMorphParams.remove( fmp );
}
}
// disable FormulaMorphParameters that are not set
for( Parameter p : unsetFormulaMorphParams )
p.setActive( false );
asr.getFrontMaterial().loadProperties(props, "front_material_", "");
asr.getBackMaterial().loadProperties(props, "back_material_", "");
LaTeXCommands.getDynamicLaTeXMap().put( "FMTitle" + surf.name(), "\\begin{array}{c}\n\\vphantom{T}\\\\\n\\text{\\fixheight{}" + props.getProperty( "surface_title_latex" ).replaceAll( "\\\\\\\\", "\\ " ) + "}\\\\\n\\vphantom{.}\\end{array}" );
LaTeXCommands.getDynamicLaTeXMap().put( "FMTitleFormula" + surf.name(), "\\begin{array}{c}\n\\text{Formula for " + props.getProperty( "surface_title_latex" ).replaceAll( "\\\\\\\\", "}\\\\\\\\\\\\text{" ) + "\\fixheight}\\end{array}" );
LaTeXCommands.getDynamicLaTeXMap().put( "FMTitleWImage" + surf.name(), "\\begin{array}{c}\n\\text{" + props.getProperty( "surface_title_latex" ).replaceAll( "\\\\\\\\", "}\\\\\\\\\\\\text{" ) + "\\fixheight}\\end{array}" );
LaTeXCommands.getDynamicLaTeXMap().put( "FMEquation" + surf.name(), "{" + props.getProperty( "surface_equation_latex_size", "" ) + "\\begin{array}{c}\n" + props.getProperty( "surface_equation_latex" ).replaceAll( "\\\\FMB", "\\\\FMB" + surf.name() ).replaceAll( "\\\\FMC", "\\\\FMC" + surf.name() ).replaceAll( "\\\\FMP", "\\\\FMP" + surf.name() ).replaceAll( "\\\\\\\\", "\\\\nl" ) + "\n\\end{array}}\n" );
}
public void stepPath( int steps ) { this.rotationAnimation.stepPath( steps ); }
public void pauseAnimation() { this.rotationAnimation.pause(); }
public void resumeAnimation() { this.rotationAnimation.resume(); }
class RotationAnimation implements Runnable
{
boolean stop;
boolean pause;
Object lock;
Quat4d current;
Quat4d step;
public RotationAnimation()
{
stop = false;
pause = true;
lock = new Object();
current = new Quat4d();
current.set( new AxisAngle4d() );
step = new Quat4d();
step.set( new AxisAngle4d() );
double angleStep = 6 * Math.PI / 1000;
Quat4d rotX = new Quat4d(); rotX.set( new AxisAngle4d( 1, 0, 0, angleStep ) ); step.mul( rotX );
Quat4d rotY = new Quat4d(); rotY.set( new AxisAngle4d( 0, 1, 0, angleStep ) ); step.mul( rotY );
Quat4d rotZ = new Quat4d(); rotZ.set( new AxisAngle4d( 0, 0, 1, angleStep ) ); step.mul( rotZ );
}
public void setPathPosition()
{
Matrix4d newRotation = new Matrix4d();
newRotation.setIdentity();
newRotation.setRotation( current );
for( Surface s : Surface.values() )
{
GUI.this.s2g(s).panel.getAlgebraicSurfaceRenderer().setTransform( newRotation );
GUI.this.s2g(s).panel.scheduleSurfaceRepaint();
}
}
public void stepPath( int steps )
{
for( int i = 0; i < steps; ++i )
current.mul( step );
for( int i = 0; i < -steps; ++i )
current.mulInverse( step );
setPathPosition();
}
public void pause() { this.pause = true; }
public void resume() { if( pause ) { synchronized( lock ) { lock.notify(); } } this.pause = false; }
public void stop() { this.stop = true; }
public void run()
{
synchronized( lock )
{
try{ Thread.sleep( 500 ); } catch( Exception e ) {}
while( !stop )
{
try
{
Thread.sleep( 20 );
if( pause )
lock.wait();
} catch( Exception e ) {}
stepPath( 1 );
setPathPosition();
}
}
}
}
}
| jump to beginning of gallery when changing the level
| src/com/moeyinc/formulamorph/GUI.java | jump to beginning of gallery when changing the level | <ide><path>rc/com/moeyinc/formulamorph/GUI.java
<ide> {
<ide> if( s2g( s ).galleryItems().get( s2g( s ).id() ).level() != level )
<ide> {
<del> int id, count;
<add> int id;
<ide> List< Gallery.GalleryItem > galleryItems = s2g( s ).galleryItems();
<ide> for( id = 0; id < galleryItems.size() && galleryItems.get( id ).level() != level; ++id )
<ide> ; // find first item with requested level
<add> /*
<add> int count:
<ide> for( count = 0; count + id < galleryItems.size() && galleryItems.get( id + count ).level() == level; ++count )
<ide> ; // count items which have that level starting from the first one
<ide> s2g( s ).setId( id + count / 2 );
<add> */
<add> s2g( s ).setId( id );
<ide> idChanged( s );
<ide> }
<ide> } |
|
Java | apache-2.0 | c2c420f15179f732542a1eb9f166302ded671601 | 0 | hortonworks/streamline,hortonworks/streamline,hortonworks/streamline,hortonworks/streamline,hortonworks/streamline | /**
* Copyright 2017 Hortonworks.
*
* 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.hortonworks.streamline.streams.actions.storm.topology;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.hortonworks.streamline.common.Config;
import com.hortonworks.streamline.common.exception.service.exception.request.TopologyAlreadyExistsOnCluster;
import com.hortonworks.streamline.streams.actions.StatusImpl;
import com.hortonworks.streamline.streams.actions.TopologyActionContext;
import com.hortonworks.streamline.streams.actions.TopologyActions;
import com.hortonworks.streamline.streams.catalog.TopologyTestRunHistory;
import com.hortonworks.streamline.streams.cluster.Constants;
import com.hortonworks.streamline.streams.cluster.service.EnvironmentService;
import com.hortonworks.streamline.streams.exception.TopologyNotAliveException;
import com.hortonworks.streamline.streams.layout.TopologyLayoutConstants;
import com.hortonworks.streamline.streams.layout.component.InputComponent;
import com.hortonworks.streamline.streams.layout.component.OutputComponent;
import com.hortonworks.streamline.streams.layout.component.TopologyDag;
import com.hortonworks.streamline.streams.layout.component.TopologyLayout;
import com.hortonworks.streamline.streams.layout.component.impl.HBaseSink;
import com.hortonworks.streamline.streams.layout.component.impl.HdfsSink;
import com.hortonworks.streamline.streams.layout.component.impl.HdfsSource;
import com.hortonworks.streamline.streams.layout.component.impl.HiveSink;
import com.hortonworks.streamline.streams.layout.component.impl.testing.TestRunProcessor;
import com.hortonworks.streamline.streams.layout.component.impl.testing.TestRunRulesProcessor;
import com.hortonworks.streamline.streams.layout.component.impl.testing.TestRunSink;
import com.hortonworks.streamline.streams.layout.component.impl.testing.TestRunSource;
import com.hortonworks.streamline.streams.layout.storm.StormTopologyFluxGenerator;
import com.hortonworks.streamline.streams.layout.storm.StormTopologyLayoutConstants;
import com.hortonworks.streamline.streams.layout.storm.StormTopologyValidator;
import com.hortonworks.streamline.streams.storm.common.StormJaasCreator;
import com.hortonworks.streamline.streams.storm.common.StormRestAPIClient;
import com.hortonworks.streamline.streams.storm.common.StormTopologyUtil;
import com.hortonworks.streamline.streams.storm.common.logger.LogLevelLoggerResponse;
import com.hortonworks.streamline.streams.storm.common.logger.LogLevelResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.client.ClientConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import javax.security.auth.Subject;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
/**
* Storm implementation of the TopologyActions interface
*/
public class StormTopologyActionsImpl implements TopologyActions {
private static final Logger LOG = LoggerFactory.getLogger(StormTopologyActionsImpl.class);
public static final int DEFAULT_WAIT_TIME_SEC = 30;
public static final int TEST_RUN_TOPOLOGY_DEFAULT_WAIT_MILLIS_FOR_SHUTDOWN = 30_000;
public static final String ROOT_LOGGER_NAME = "ROOT";
private static final String DEFAULT_THRIFT_TRANSPORT_PLUGIN = "org.apache.storm.security.auth.SimpleTransportPlugin";
private static final String DEFAULT_PRINCIPAL_TO_LOCAL = "org.apache.storm.security.auth.DefaultPrincipalToLocal";
private static final String NIMBUS_SEEDS = "nimbus.seeds";
private static final String NIMBUS_PORT = "nimbus.port";
public static final String STREAMLINE_TOPOLOGY_CONFIG_CLUSTER_SECURITY_CONFIG = "clustersSecurityConfig";
public static final String STREAMLINE_TOPOLOGY_CONFIG_CLUSTER_ID = "clusterId";
public static final String STREAMLINE_TOPOLOGY_CONFIG_PRINCIPAL = "principal";
public static final String STREAMLINE_TOPOLOGY_CONFIG_KEYTAB_PATH = "keytabPath";
public static final String STORM_TOPOLOGY_CONFIG_AUTO_CREDENTIALS = "topology.auto-credentials";
public static final String TOPOLOGY_CONFIG_KEY_CLUSTER_KEY_PREFIX_HDFS = "hdfs_";
public static final String TOPOLOGY_CONFIG_KEY_CLUSTER_KEY_PREFIX_HBASE = "hbase_";
public static final String TOPOLOGY_CONFIG_KEY_CLUSTER_KEY_PREFIX_HIVE = "hive_";
public static final String TOPOLOGY_CONFIG_KEY_HDFS_KEYTAB_FILE = "hdfs.keytab.file";
public static final String TOPOLOGY_CONFIG_KEY_HBASE_KEYTAB_FILE = "hbase.keytab.file";
public static final String TOPOLOGY_CONFIG_KEY_HIVE_KEYTAB_FILE = "hive.keytab.file";
public static final String TOPOLOGY_CONFIG_KEY_HDFS_KERBEROS_PRINCIPAL = "hdfs.kerberos.principal";
public static final String TOPOLOGY_CONFIG_KEY_HBASE_KERBEROS_PRINCIPAL = "hbase.kerberos.principal";
public static final String TOPOLOGY_CONFIG_KEY_HIVE_KERBEROS_PRINCIPAL = "hive.kerberos.principal";
public static final String TOPOLOGY_CONFIG_KEY_HDFS_CREDENTIALS_CONFIG_KEYS = "hdfsCredentialsConfigKeys";
public static final String TOPOLOGY_CONFIG_KEY_HBASE_CREDENTIALS_CONFIG_KEYS = "hbaseCredentialsConfigKeys";
public static final String TOPOLOGY_CONFIG_KEY_HIVE_CREDENTIALS_CONFIG_KEYS = "hiveCredentialsConfigKeys";
public static final String TOPOLOGY_AUTO_CREDENTIAL_CLASSNAME_HDFS = "org.apache.storm.hdfs.security.AutoHDFS";
public static final String TOPOLOGY_AUTO_CREDENTIAL_CLASSNAME_HBASE = "org.apache.storm.hbase.security.AutoHBase";
public static final String TOPOLOGY_AUTO_CREDENTIAL_CLASSNAME_HIVE = "org.apache.storm.hive.security.AutoHive";
private static final Long DEFAULT_NIMBUS_THRIFT_MAX_BUFFER_SIZE = 1048576L;
public static final String TOPOLOGY_EVENTLOGGER_REGISTER = "topology.event.logger.register";
public static final String TOPOLOGY_EVENTLOGGER_CLASSNAME_STREAMLINE = "com.hortonworks.streamline.streams.runtime.storm.event.sample.StreamlineEventLogger";
private String stormArtifactsLocation = "/tmp/storm-artifacts/";
private String stormCliPath = "storm";
private String stormJarLocation;
private String catalogRootUrl;
private String javaJarCommand;
private StormRestAPIClient client;
private String nimbusSeeds;
private Integer nimbusPort;
private Map<String, Object> conf;
private String thriftTransport;
private Optional<String> jaasFilePath;
private String principalToLocal;
private long nimbusThriftMaxBufferSize;
private AutoCredsServiceConfigurationReader serviceConfigurationReader;
private final ConcurrentHashMap<Long, Boolean> forceKillRequests = new ConcurrentHashMap<>();
public StormTopologyActionsImpl() {
}
@Override
public void init (Map<String, Object> conf) {
this.conf = conf;
if (conf != null) {
if (conf.containsKey(StormTopologyLayoutConstants.STORM_ARTIFACTS_LOCATION_KEY)) {
stormArtifactsLocation = (String) conf.get(StormTopologyLayoutConstants.STORM_ARTIFACTS_LOCATION_KEY);
}
if (conf.containsKey(StormTopologyLayoutConstants.STORM_HOME_DIR)) {
String stormHomeDir = (String) conf.get(StormTopologyLayoutConstants.STORM_HOME_DIR);
if (!stormHomeDir.endsWith(File.separator)) {
stormHomeDir += File.separator;
}
stormCliPath = stormHomeDir + "bin" + File.separator + "storm";
}
this.stormJarLocation = (String) conf.get(StormTopologyLayoutConstants.STORM_JAR_LOCATION_KEY);
catalogRootUrl = (String) conf.get(StormTopologyLayoutConstants.YAML_KEY_CATALOG_ROOT_URL);
Map<String, String> env = System.getenv();
String javaHomeStr = env.get("JAVA_HOME");
if (StringUtils.isNotEmpty(javaHomeStr)) {
if (!javaHomeStr.endsWith(File.separator)) {
javaHomeStr += File.separator;
}
javaJarCommand = javaHomeStr + "bin" + File.separator + "jar";
} else {
javaJarCommand = "jar";
}
String stormApiRootUrl = (String) conf.get(TopologyLayoutConstants.STORM_API_ROOT_URL_KEY);
Subject subject = (Subject) conf.get(TopologyLayoutConstants.SUBJECT_OBJECT);
Client restClient = ClientBuilder.newClient(new ClientConfig());
this.client = new StormRestAPIClient(restClient, stormApiRootUrl, subject);
nimbusSeeds = (String) conf.get(NIMBUS_SEEDS);
nimbusPort = Integer.valueOf((String) conf.get(NIMBUS_PORT));
if (conf.containsKey(TopologyLayoutConstants.NIMBUS_THRIFT_MAX_BUFFER_SIZE)) {
nimbusThriftMaxBufferSize = (Long) conf.get(TopologyLayoutConstants.NIMBUS_THRIFT_MAX_BUFFER_SIZE);
} else {
nimbusThriftMaxBufferSize = DEFAULT_NIMBUS_THRIFT_MAX_BUFFER_SIZE;
}
setupSecuredStormCluster(conf);
EnvironmentService environmentService = (EnvironmentService) conf.get(TopologyLayoutConstants.ENVIRONMENT_SERVICE_OBJECT);
Number namespaceId = (Number) conf.get(TopologyLayoutConstants.NAMESPACE_ID);
this.serviceConfigurationReader = new AutoCredsServiceConfigurationReader(environmentService,
namespaceId.longValue());
}
File f = new File (stormArtifactsLocation);
if (!f.exists() && !f.mkdirs()) {
throw new RuntimeException("Could not create directory " + f.getAbsolutePath());
}
}
private void setupSecuredStormCluster(Map<String, Object> conf) {
thriftTransport = (String) conf.get(TopologyLayoutConstants.STORM_THRIFT_TRANSPORT);
if (conf.containsKey(TopologyLayoutConstants.STORM_NIMBUS_PRINCIPAL_NAME)) {
String nimbusPrincipal = (String) conf.get(TopologyLayoutConstants.STORM_NIMBUS_PRINCIPAL_NAME);
String kerberizedNimbusServiceName = nimbusPrincipal.split("/")[0];
jaasFilePath = Optional.of(createJaasFile(kerberizedNimbusServiceName));
} else {
jaasFilePath = Optional.empty();
}
principalToLocal = (String) conf.getOrDefault(TopologyLayoutConstants.STORM_PRINCIPAL_TO_LOCAL, DEFAULT_PRINCIPAL_TO_LOCAL);
if (thriftTransport == null) {
if (jaasFilePath.isPresent()) {
thriftTransport = (String) conf.get(TopologyLayoutConstants.STORM_SECURED_THRIFT_TRANSPORT);
} else {
thriftTransport = (String) conf.get(TopologyLayoutConstants.STORM_NONSECURED_THRIFT_TRANSPORT);
}
}
// if it's still null, set to default
if (thriftTransport == null) {
thriftTransport = DEFAULT_THRIFT_TRANSPORT_PLUGIN;
}
}
@Override
public void deploy(TopologyLayout topology, String mavenArtifacts, TopologyActionContext ctx, String asUser) throws Exception {
ctx.setCurrentAction("Adding artifacts to jar");
Path jarToDeploy = addArtifactsToJar(getArtifactsLocation(topology));
ctx.setCurrentAction("Creating Storm topology YAML file");
String fileName = createYamlFileForDeploy(topology);
ctx.setCurrentAction("Deploying topology via 'storm jar' command");
List<String> commands = new ArrayList<String>();
commands.add(stormCliPath);
commands.add("jar");
commands.add(jarToDeploy.toString());
commands.addAll(getExtraJarsArg(topology));
commands.addAll(getMavenArtifactsRelatedArgs(mavenArtifacts));
commands.addAll(getNimbusConf());
commands.addAll(getSecuredClusterConf(asUser));
commands.add("org.apache.storm.flux.Flux");
commands.add("--remote");
commands.add(fileName);
LOG.info("Deploying Application {}", topology.getName());
LOG.info(String.join(" ", commands));
Process process = executeShellProcess(commands);
ShellProcessResult shellProcessResult = waitProcessFor(process);
int exitValue = shellProcessResult.exitValue;
if (exitValue != 0) {
LOG.error("Topology deploy command failed - exit code: {} / output: {}", exitValue, shellProcessResult.stdout);
String[] lines = shellProcessResult.stdout.split("\\n");
String errors = Arrays.stream(lines)
.filter(line -> line.startsWith("Exception"))
.collect(Collectors.joining(", "));
Pattern pattern = Pattern.compile("Topology with name `(.*)` already exists on cluster");
Matcher matcher = pattern.matcher(errors);
if (matcher.find()) {
throw new TopologyAlreadyExistsOnCluster(matcher.group(1));
} else {
throw new Exception("Topology could not be deployed successfully: storm deploy command failed with " + errors);
}
}
}
@Override
public void runTest(TopologyLayout topology, TopologyTestRunHistory testRunHistory, String mavenArtifacts,
Map<String, TestRunSource> testRunSourcesForEachSource,
Map<String, TestRunProcessor> testRunProcessorsForEachProcessor,
Map<String, TestRunRulesProcessor> testRunRulesProcessorsForEachProcessor,
Map<String, TestRunSink> testRunSinksForEachSink, Optional<Long> durationSecs) throws Exception {
TopologyDag originalTopologyDag = topology.getTopologyDag();
TestTopologyDagCreatingVisitor visitor = new TestTopologyDagCreatingVisitor(originalTopologyDag,
testRunSourcesForEachSource, testRunProcessorsForEachProcessor, testRunRulesProcessorsForEachProcessor,
testRunSinksForEachSink);
originalTopologyDag.traverse(visitor);
TopologyDag testTopologyDag = visitor.getTestTopologyDag();
TopologyLayout testTopology = copyTopologyLayout(topology, testTopologyDag);
Path jarToDeploy = addArtifactsToJar(getArtifactsLocation(testTopology));
String fileName = createYamlFileForTest(testTopology);
List<String> commands = new ArrayList<String>();
commands.add(stormCliPath);
commands.add("jar");
commands.add(jarToDeploy.toString());
commands.addAll(getExtraJarsArg(testTopology));
commands.addAll(getMavenArtifactsRelatedArgs(mavenArtifacts));
commands.addAll(getNimbusConf());
commands.addAll(getTempWorkerArtifactArgs());
commands.add("org.apache.storm.flux.Flux");
commands.add("--local");
commands.add("-s");
if (durationSecs.isPresent()) {
commands.add(String.valueOf(durationSecs.get() * 1000));
} else {
commands.add(String.valueOf(TEST_RUN_TOPOLOGY_DEFAULT_WAIT_MILLIS_FOR_SHUTDOWN));
}
commands.add(fileName);
Process process = executeShellProcess(commands);
ShellProcessResult shellProcessResult = waitTestRunProcess(process, testRunHistory.getId());
int exitValue = shellProcessResult.exitValue;
if (exitValue != 0) {
LOG.error("Topology deploy command as test mode failed - exit code: {} / output: {}", exitValue, shellProcessResult.stdout);
throw new Exception("Topology could not be run " +
"successfully as test mode: storm deploy command failed");
}
}
@Override
public boolean killTest(TopologyTestRunHistory testRunHistory) {
// just turn on the flag only if it exists
LOG.info("Turning on force kill flag on test run history {}", testRunHistory.getId());
Boolean newValue = forceKillRequests.computeIfPresent(testRunHistory.getId(), (id, flag) -> true);
return newValue != null;
}
@Override
public void kill (TopologyLayout topology, String asUser) throws Exception {
String stormTopologyId = getRuntimeTopologyId(topology, asUser);
boolean killed = client.killTopology(stormTopologyId, asUser, DEFAULT_WAIT_TIME_SEC);
if (!killed) {
throw new Exception("Topology could not be killed " +
"successfully.");
}
File artifactsDir = getArtifactsLocation(topology).toFile();
if (artifactsDir.exists() && artifactsDir.isDirectory()) {
LOG.debug("Cleaning up {}", artifactsDir);
FileUtils.cleanDirectory(artifactsDir);
}
}
@Override
public void validate (TopologyLayout topology) throws Exception {
Map<String, Object> topologyConfig = topology.getConfig().getProperties();
if (!topologyConfig.isEmpty()) {
StormTopologyValidator validator = new StormTopologyValidator(topologyConfig, this.catalogRootUrl);
validator.validate();
}
}
@Override
public void suspend (TopologyLayout topology, String asUser) throws Exception {
String stormTopologyId = getRuntimeTopologyId(topology, asUser);
boolean suspended = client.deactivateTopology(stormTopologyId, asUser);
if (!suspended) {
throw new Exception("Topology could not be suspended " +
"successfully.");
}
}
@Override
public void resume (TopologyLayout topology, String asUser) throws Exception {
String stormTopologyId = getRuntimeTopologyId(topology, asUser);
if (stormTopologyId == null || stormTopologyId.isEmpty()) {
throw new TopologyNotAliveException("Topology not found in Storm Cluster - topology id: " + topology.getId());
}
boolean resumed = client.activateTopology(stormTopologyId, asUser);
if (!resumed) {
throw new Exception("Topology could not be resumed " +
"successfully.");
}
}
@Override
public Status status(TopologyLayout topology, String asUser) throws Exception {
String stormTopologyId = getRuntimeTopologyId(topology, asUser);
Map topologyStatus = client.getTopology(stormTopologyId, asUser);
StatusImpl status = new StatusImpl();
status.setStatus((String) topologyStatus.get("status"));
status.putExtra("Num_tasks", String.valueOf(topologyStatus.get("workersTotal")));
status.putExtra("Num_workers", String.valueOf(topologyStatus.get("tasksTotal")));
status.putExtra("Uptime_secs", String.valueOf(topologyStatus.get("uptimeSeconds")));
return status;
}
@Override
public LogLevelInformation configureLogLevel(TopologyLayout topology, LogLevel targetLogLevel, int durationSecs, String asUser) throws Exception {
String stormTopologyId = StormTopologyUtil.findStormTopologyId(client, topology.getId(), asUser);
if (StringUtils.isEmpty(stormTopologyId)) {
return null;
}
LogLevelResponse response = client.configureLog(stormTopologyId, ROOT_LOGGER_NAME, targetLogLevel.name(),
durationSecs, asUser);
return convertLogLevelResponseToLogLevelInformation(response);
}
@Override
public LogLevelInformation getLogLevel(TopologyLayout topology, String asUser) throws Exception {
String stormTopologyId = StormTopologyUtil.findStormTopologyId(client, topology.getId(), asUser);
if (StringUtils.isEmpty(stormTopologyId)) {
return null;
}
LogLevelResponse response = client.getLogLevel(stormTopologyId, asUser);
return convertLogLevelResponseToLogLevelInformation(response);
}
/**
* the Path where any topology specific artifacts are kept
*/
@Override
public Path getArtifactsLocation(TopologyLayout topology) {
return Paths.get(stormArtifactsLocation, generateStormTopologyName(topology), "artifacts");
}
@Override
public Path getExtraJarsLocation(TopologyLayout topology) {
return Paths.get(stormArtifactsLocation, generateStormTopologyName(topology), "jars");
}
@Override
public String getRuntimeTopologyId(TopologyLayout topology, String asUser) {
String stormTopologyId = StormTopologyUtil.findStormTopologyId(client, topology.getId(), asUser);
if (StringUtils.isEmpty(stormTopologyId)) {
throw new TopologyNotAliveException("Topology not found in Storm Cluster - topology id: " + topology.getId());
}
return stormTopologyId;
}
private TopologyLayout copyTopologyLayout(TopologyLayout topology, TopologyDag replacedTopologyDag) {
return new TopologyLayout(topology.getId(), topology.getName(), topology.getConfig(), replacedTopologyDag);
}
private List<String> getMavenArtifactsRelatedArgs (String mavenArtifacts) {
List<String> args = new ArrayList<>();
if (mavenArtifacts != null && !mavenArtifacts.isEmpty()) {
args.add("--artifacts");
args.add(mavenArtifacts);
args.add("--artifactRepositories");
args.add((String) conf.get("mavenRepoUrl"));
String proxyUrl = (String) conf.get("proxyUrl");
if (StringUtils.isNotEmpty(proxyUrl)) {
args.add("--proxyUrl");
args.add(proxyUrl);
String proxyUsername = (String) conf.get("proxyUsername");
String proxyPassword = (String) conf.get("proxyPassword");
if (proxyUsername != null && proxyPassword != null) {
// allow empty string but not null
args.add("--proxyUsername");
args.add(proxyUsername);
args.add("--proxyPassword");
args.add(proxyPassword);
}
}
}
return args;
}
private List<String> getExtraJarsArg(TopologyLayout topology) {
List<String> args = new ArrayList<>();
List<String> jars = new ArrayList<>();
Path extraJarsPath = getExtraJarsLocation(topology);
if (extraJarsPath.toFile().isDirectory()) {
File[] jarFiles = extraJarsPath.toFile().listFiles();
if (jarFiles != null && jarFiles.length > 0) {
for (File jarFile : jarFiles) {
jars.add(jarFile.getAbsolutePath());
}
}
} else {
LOG.debug("Extra jars directory {} does not exist, not adding any extra jars", extraJarsPath);
}
if (!jars.isEmpty()) {
args.add("--jars");
args.add(Joiner.on(",").join(jars));
}
return args;
}
private List<String> getNimbusConf() {
List<String> args = new ArrayList<>();
// FIXME: Can't find how to pass list to nimbus.seeds for Storm CLI
// Maybe we need to fix Storm to parse string when expected parameter type is list
args.add("-c");
args.add("nimbus.host=" + nimbusSeeds.split(",")[0]);
args.add("-c");
args.add("nimbus.port=" + String.valueOf(nimbusPort));
args.add("-c");
args.add("nimbus.thrift.max_buffer_size=" + String.valueOf(nimbusThriftMaxBufferSize));
return args;
}
private List<String> getSecuredClusterConf(String asUser) {
List<String> args = new ArrayList<>();
args.add("-c");
args.add("storm.thrift.transport=" + thriftTransport);
if (jaasFilePath.isPresent()) {
args.add("-c");
args.add("java.security.auth.login.config=" + jaasFilePath.get());
}
args.add("-c");
args.add("storm.principal.tolocal=" + principalToLocal);
if (StringUtils.isNotEmpty(asUser)) {
args.add("-c");
args.add("storm.doAsUser=" + asUser);
}
return args;
}
private List<String> getTempWorkerArtifactArgs() throws IOException {
List<String> args = new ArrayList<>();
Path tempArtifacts = Files.createTempDirectory("worker-artifacts-");
args.add("-c");
args.add("storm.workers.artifacts.dir=" + tempArtifacts.toFile().getAbsolutePath());
return args;
}
private String createJaasFile(String kerberizedNimbusServiceName) {
try {
Path jaasFilePath = Files.createTempFile("jaas-", UUID.randomUUID().toString());
String filePath = jaasFilePath.toAbsolutePath().toString();
File jaasFile = new StormJaasCreator().create(filePath, kerberizedNimbusServiceName);
return jaasFile.getAbsolutePath();
} catch (IOException e) {
throw new RuntimeException("Can't create JAAS file to connect to secure nimbus", e);
}
}
private Path addArtifactsToJar(Path artifactsLocation) throws Exception {
Path jarFile = Paths.get(stormJarLocation);
if (artifactsLocation.toFile().isDirectory()) {
File[] artifacts = artifactsLocation.toFile().listFiles();
if (artifacts != null && artifacts.length > 0) {
Path newJar = Files.copy(jarFile, artifactsLocation.resolve(jarFile.getFileName()));
List<String> artifactFileNames = Arrays.stream(artifacts).filter(File::isFile)
.map(File::getName).collect(toList());
List<String> commands = new ArrayList<>();
commands.add(javaJarCommand);
commands.add("uf");
commands.add(newJar.toString());
artifactFileNames.stream().forEachOrdered(name -> {
commands.add("-C");
commands.add(artifactsLocation.toString());
commands.add(name);
});
Process process = executeShellProcess(commands);
ShellProcessResult shellProcessResult = waitProcessFor(process);
if (shellProcessResult.exitValue != 0) {
LOG.error("Adding artifacts to jar command failed - exit code: {} / output: {}",
shellProcessResult.exitValue, shellProcessResult.stdout);
throw new RuntimeException("Topology could not be deployed " +
"successfully: fail to add artifacts to jar");
}
LOG.debug("Added files {} to jar {}", artifactFileNames, jarFile);
return newJar;
}
} else {
LOG.debug("Artifacts directory {} does not exist, not adding any artifacts to jar", artifactsLocation);
}
return jarFile;
}
private String createYamlFileForDeploy(TopologyLayout topology) throws Exception {
return createYamlFile(topology, true);
}
private String createYamlFileForTest(TopologyLayout topology) throws Exception {
return createYamlFile(topology, false);
}
private String createYamlFile (TopologyLayout topology, boolean deploy) throws Exception {
Map<String, Object> yamlMap;
File f;
OutputStreamWriter fileWriter = null;
try {
f = new File(this.getFilePath(topology));
if (f.exists()) {
if (!f.delete()) {
throw new Exception("Unable to delete old storm " +
"artifact for topology id " + topology.getId());
}
}
yamlMap = new LinkedHashMap<>();
yamlMap.put(StormTopologyLayoutConstants.YAML_KEY_NAME, generateStormTopologyName(topology));
TopologyDag topologyDag = topology.getTopologyDag();
LOG.debug("Initial Topology config {}", topology.getConfig());
StormTopologyFluxGenerator fluxGenerator = new StormTopologyFluxGenerator(topology, conf,
getExtraJarsLocation(topology));
topologyDag.traverse(fluxGenerator);
for (Map.Entry<String, Map<String, Object>> entry: fluxGenerator.getYamlKeysAndComponents()) {
addComponentToCollection(yamlMap, entry.getValue(), entry.getKey());
}
Config topologyConfig = fluxGenerator.getTopologyConfig();
putAutoTokenDelegationConfig(topologyConfig, topologyDag);
registerEventLogger(topologyConfig);
Map<String, Object> properties = topologyConfig.getProperties();
if (!deploy) {
LOG.debug("Disabling topology event logger for test mode...");
properties.put("topology.eventlogger.executors", 0);
}
LOG.debug("Final Topology properties {}", properties);
addTopologyConfig(yamlMap, properties);
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setSplitLines(false);
//options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
Yaml yaml = new Yaml (options);
fileWriter = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
yaml.dump(yamlMap, fileWriter);
return f.getAbsolutePath();
} finally {
if (fileWriter != null) {
fileWriter.close();
}
}
}
private void registerEventLogger(Config topologyConfig) {
topologyConfig.put(TOPOLOGY_EVENTLOGGER_REGISTER,
Collections.singletonList(
Collections.singletonMap("class", TOPOLOGY_EVENTLOGGER_CLASSNAME_STREAMLINE))
);
}
private void putAutoTokenDelegationConfig(Config topologyConfig, TopologyDag topologyDag) {
Optional<?> securityConfigsOptional = topologyConfig.getAnyOptional(STREAMLINE_TOPOLOGY_CONFIG_CLUSTER_SECURITY_CONFIG);
Map<Long, Map<String, String>> clusterToConfiguration = new HashMap<>();
if (securityConfigsOptional.isPresent()) {
List<?> securityConfigurations = (List<?>) securityConfigsOptional.get();
securityConfigurations.forEach(securityConfig -> {
Map<String, Object> sc = (Map<String, Object>) securityConfig;
if ((sc != null) && !sc.isEmpty()) {
Long clusterId = ((Number) sc.get(STREAMLINE_TOPOLOGY_CONFIG_CLUSTER_ID)).longValue();
Map<String, String> configurationForCluster = new HashMap<>();
configurationForCluster.put(STREAMLINE_TOPOLOGY_CONFIG_PRINCIPAL, (String) sc.get(STREAMLINE_TOPOLOGY_CONFIG_PRINCIPAL));
configurationForCluster.put(STREAMLINE_TOPOLOGY_CONFIG_KEYTAB_PATH, (String) sc.get(STREAMLINE_TOPOLOGY_CONFIG_KEYTAB_PATH));
clusterToConfiguration.put(clusterId, configurationForCluster);
}
});
}
if (clusterToConfiguration.isEmpty()) {
// it will function only when user input keytab path and principal
return;
}
// Hive also needs HDFS auto token delegation, so HiveSink is added to the checklist
boolean hdfsCredentialNecessary = checkTopologyContainingServiceRelatedComponent(topologyDag,
Collections.singletonList(HdfsSource.class),
Lists.newArrayList(HdfsSink.class, HiveSink.class));
boolean hbaseCredentialNecessary = checkTopologyContainingServiceRelatedComponent(topologyDag,
Collections.emptyList(),
Collections.singletonList(HBaseSink.class));
boolean hiveCredentialNecessary = checkTopologyContainingServiceRelatedComponent(topologyDag,
Collections.emptyList(),
Collections.singletonList(HiveSink.class));
if (hdfsCredentialNecessary) {
putServiceSpecificCredentialConfig(topologyConfig, clusterToConfiguration,
Constants.HDFS.SERVICE_NAME,
Collections.emptyList(),
TOPOLOGY_CONFIG_KEY_CLUSTER_KEY_PREFIX_HDFS, TOPOLOGY_CONFIG_KEY_HDFS_KEYTAB_FILE,
TOPOLOGY_CONFIG_KEY_HDFS_KERBEROS_PRINCIPAL,
TOPOLOGY_CONFIG_KEY_HDFS_CREDENTIALS_CONFIG_KEYS, TOPOLOGY_AUTO_CREDENTIAL_CLASSNAME_HDFS);
}
if (hbaseCredentialNecessary) {
putServiceSpecificCredentialConfig(topologyConfig, clusterToConfiguration,
Constants.HBase.SERVICE_NAME,
Collections.singletonList(Constants.HDFS.SERVICE_NAME),
TOPOLOGY_CONFIG_KEY_CLUSTER_KEY_PREFIX_HBASE, TOPOLOGY_CONFIG_KEY_HBASE_KEYTAB_FILE,
TOPOLOGY_CONFIG_KEY_HBASE_KERBEROS_PRINCIPAL,
TOPOLOGY_CONFIG_KEY_HBASE_CREDENTIALS_CONFIG_KEYS, TOPOLOGY_AUTO_CREDENTIAL_CLASSNAME_HBASE);
}
if (hiveCredentialNecessary) {
putServiceSpecificCredentialConfig(topologyConfig, clusterToConfiguration,
Constants.Hive.SERVICE_NAME,
Collections.singletonList(Constants.HDFS.SERVICE_NAME),
TOPOLOGY_CONFIG_KEY_CLUSTER_KEY_PREFIX_HIVE, TOPOLOGY_CONFIG_KEY_HIVE_KEYTAB_FILE,
TOPOLOGY_CONFIG_KEY_HIVE_KERBEROS_PRINCIPAL,
TOPOLOGY_CONFIG_KEY_HIVE_CREDENTIALS_CONFIG_KEYS, TOPOLOGY_AUTO_CREDENTIAL_CLASSNAME_HIVE);
}
}
public boolean checkTopologyContainingServiceRelatedComponent(TopologyDag topologyDag,
List<Class<?>> outputComponentClasses,
List<Class<?>> inputComponentClasses) {
boolean componentExists = false;
for (OutputComponent outputComponent : topologyDag.getOutputComponents()) {
for (Class<?> clazz : outputComponentClasses) {
if (outputComponent.getClass().isAssignableFrom(clazz)) {
componentExists = true;
break;
}
}
}
if (!componentExists) {
for (InputComponent inputComponent : topologyDag.getInputComponents()) {
for (Class<?> clazz : inputComponentClasses) {
if (inputComponent.getClass().isAssignableFrom(clazz)) {
componentExists = true;
break;
}
}
}
}
return componentExists;
}
private void putServiceSpecificCredentialConfig(Config topologyConfig,
Map<Long, Map<String, String>> clusterToConfiguration,
String serviceName,
List<String> dependentServiceNames,
String clusterKeyPrefix,
String keytabPathKeyName, String principalKeyName,
String credentialConfigKeyName,
String topologyAutoCredentialClassName) {
List<String> clusterKeys = new ArrayList<>();
clusterToConfiguration.keySet()
.forEach(clusterId -> {
Map<String, String> conf = serviceConfigurationReader.read(clusterId, serviceName);
// add only when such (cluster, service) pair is available for the namespace
if (!conf.isEmpty()) {
Map<String, String> confForToken = clusterToConfiguration.get(clusterId);
conf.put(principalKeyName, confForToken.get(STREAMLINE_TOPOLOGY_CONFIG_PRINCIPAL));
conf.put(keytabPathKeyName, confForToken.get(STREAMLINE_TOPOLOGY_CONFIG_KEYTAB_PATH));
// also includes all configs for dependent services
// note that such services in cluster should also be associated to the namespace
Map<String, String> clusterConf = new HashMap<>();
dependentServiceNames.forEach(depSvcName -> {
Map<String, String> depConf = serviceConfigurationReader.read(clusterId, depSvcName);
clusterConf.putAll(depConf);
});
clusterConf.putAll(conf);
String clusterKey = clusterKeyPrefix + clusterId;
topologyConfig.put(clusterKey, clusterConf);
clusterKeys.add(clusterKey);
}
});
topologyConfig.put(credentialConfigKeyName, clusterKeys);
Optional<List<String>> autoCredentialsOptional = topologyConfig.getAnyOptional(STORM_TOPOLOGY_CONFIG_AUTO_CREDENTIALS);
if (autoCredentialsOptional.isPresent()) {
List<String> autoCredentials = autoCredentialsOptional.get();
autoCredentials.add(topologyAutoCredentialClassName);
} else {
topologyConfig.put(STORM_TOPOLOGY_CONFIG_AUTO_CREDENTIALS, Lists.newArrayList(topologyAutoCredentialClassName));
}
}
private String generateStormTopologyName(TopologyLayout topology) {
return StormTopologyUtil.generateStormTopologyName(topology.getId(), topology.getName());
}
private String getFilePath (TopologyLayout topology) {
return this.stormArtifactsLocation + generateStormTopologyName(topology) + ".yaml";
}
// Add topology level configs. catalogRootUrl, hbaseConf, hdfsConf,
// numWorkers, etc.
private void addTopologyConfig (Map<String, Object> yamlMap, Map<String, Object> topologyConfig) {
Map<String, Object> config = new LinkedHashMap<>();
config.put(StormTopologyLayoutConstants.YAML_KEY_CATALOG_ROOT_URL, catalogRootUrl);
//Hack to work around HBaseBolt expecting this map in prepare method. Fix HBaseBolt and get rid of this. We use hbase-site.xml conf from ambari
config.put(StormTopologyLayoutConstants.YAML_KEY_HBASE_CONF, new HashMap<>());
if (topologyConfig != null) {
config.putAll(topologyConfig);
}
yamlMap.put(StormTopologyLayoutConstants.YAML_KEY_CONFIG, config);
}
private void addComponentToCollection (Map<String, Object> yamlMap, Map<String, Object> yamlComponent, String collectionKey) {
if (yamlComponent == null ) {
return;
}
List<Map<String, Object>> components = (List<Map<String, Object>>) yamlMap.get(collectionKey);
if (components == null) {
components = new ArrayList<>();
yamlMap.put(collectionKey, components);
}
components.add(yamlComponent);
}
private Process executeShellProcess (List<String> commands) throws Exception {
LOG.debug("Executing command: {}", Joiner.on(" ").join(commands));
ProcessBuilder processBuilder = new ProcessBuilder(commands);
processBuilder.redirectErrorStream(true);
return processBuilder.start();
}
private ShellProcessResult waitProcessFor(Process process) throws IOException, InterruptedException {
StringWriter sw = new StringWriter();
IOUtils.copy(process.getInputStream(), sw, Charset.defaultCharset());
String stdout = sw.toString();
process.waitFor();
int exitValue = process.exitValue();
LOG.debug("Command output: {}", stdout);
LOG.debug("Command exit status: {}", exitValue);
return new ShellProcessResult(exitValue, stdout);
}
private ShellProcessResult waitTestRunProcess(Process process, long topologyRunHistoryId) throws IOException {
forceKillRequests.put(topologyRunHistoryId, false);
LOG.info("Waiting for test run for history {} to be finished...", topologyRunHistoryId);
StringBuilder sb = new StringBuilder();
for (int idx = 0 ; ; idx++) {
if (!process.isAlive()) {
break;
}
// read stdout if available
sb.append(readProcessStream(process.getInputStream()));
if (forceKillRequests.getOrDefault(topologyRunHistoryId, false)) {
LOG.info("Received force kill for test run {} - destroying process...", topologyRunHistoryId);
process.destroyForcibly();
}
// leave a log for each 10 secs...
if ((idx + 1) % 100 == 0) {
LOG.info("Still waiting for test run for history {} to be finished...", topologyRunHistoryId);
}
try {
process.waitFor(100, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// ignored
}
}
LOG.info("Test run for history {} is finished", topologyRunHistoryId);
String stdout = sb.toString();
forceKillRequests.remove(topologyRunHistoryId);
int exitValue = process.exitValue();
LOG.debug("Command output: {}", stdout);
LOG.debug("Command exit status: {}", exitValue);
return new ShellProcessResult(exitValue, stdout);
}
private String readProcessStream(InputStream processInputStream) {
try {
StringBuilder sb = new StringBuilder();
while (processInputStream.available() > 0) {
int bufferSize = processInputStream.available();
byte[] errorReadingBuffer = new byte[bufferSize];
int readSize = processInputStream.read(errorReadingBuffer, 0, bufferSize);
errorReadingBuffer = Arrays.copyOfRange(errorReadingBuffer, 0, readSize);
sb.append(new String(errorReadingBuffer, Charset.forName("UTF-8")));
}
return sb.toString();
} catch (IOException e) {
return "(cannot capture process stream)";
}
}
private static class ShellProcessResult {
private final int exitValue;
private final String stdout;
ShellProcessResult(int exitValue, String stdout) {
this.exitValue = exitValue;
this.stdout = stdout;
}
}
private LogLevelInformation convertLogLevelResponseToLogLevelInformation(LogLevelResponse response) {
Map<String, LogLevelLoggerResponse> namedLoggerLevels = response.getNamedLoggerLevels();
LogLevelLoggerResponse resp = namedLoggerLevels.get(ROOT_LOGGER_NAME);
if (resp == null) {
return LogLevelInformation.disabled();
}
return LogLevelInformation.enabled(LogLevel.valueOf(resp.getTargetLevel()), resp.getTimeoutEpoch());
}
}
| streams/runners/storm/actions/src/main/java/com/hortonworks/streamline/streams/actions/storm/topology/StormTopologyActionsImpl.java | /**
* Copyright 2017 Hortonworks.
*
* 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.hortonworks.streamline.streams.actions.storm.topology;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.hortonworks.streamline.common.Config;
import com.hortonworks.streamline.common.exception.service.exception.request.TopologyAlreadyExistsOnCluster;
import com.hortonworks.streamline.streams.actions.StatusImpl;
import com.hortonworks.streamline.streams.actions.TopologyActionContext;
import com.hortonworks.streamline.streams.actions.TopologyActions;
import com.hortonworks.streamline.streams.catalog.TopologyTestRunHistory;
import com.hortonworks.streamline.streams.cluster.Constants;
import com.hortonworks.streamline.streams.cluster.service.EnvironmentService;
import com.hortonworks.streamline.streams.exception.TopologyNotAliveException;
import com.hortonworks.streamline.streams.layout.TopologyLayoutConstants;
import com.hortonworks.streamline.streams.layout.component.InputComponent;
import com.hortonworks.streamline.streams.layout.component.OutputComponent;
import com.hortonworks.streamline.streams.layout.component.TopologyDag;
import com.hortonworks.streamline.streams.layout.component.TopologyLayout;
import com.hortonworks.streamline.streams.layout.component.impl.HBaseSink;
import com.hortonworks.streamline.streams.layout.component.impl.HdfsSink;
import com.hortonworks.streamline.streams.layout.component.impl.HdfsSource;
import com.hortonworks.streamline.streams.layout.component.impl.HiveSink;
import com.hortonworks.streamline.streams.layout.component.impl.testing.TestRunProcessor;
import com.hortonworks.streamline.streams.layout.component.impl.testing.TestRunRulesProcessor;
import com.hortonworks.streamline.streams.layout.component.impl.testing.TestRunSink;
import com.hortonworks.streamline.streams.layout.component.impl.testing.TestRunSource;
import com.hortonworks.streamline.streams.layout.storm.StormTopologyFluxGenerator;
import com.hortonworks.streamline.streams.layout.storm.StormTopologyLayoutConstants;
import com.hortonworks.streamline.streams.layout.storm.StormTopologyValidator;
import com.hortonworks.streamline.streams.storm.common.StormJaasCreator;
import com.hortonworks.streamline.streams.storm.common.StormRestAPIClient;
import com.hortonworks.streamline.streams.storm.common.StormTopologyUtil;
import com.hortonworks.streamline.streams.storm.common.logger.LogLevelLoggerResponse;
import com.hortonworks.streamline.streams.storm.common.logger.LogLevelResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.client.ClientConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import javax.security.auth.Subject;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
/**
* Storm implementation of the TopologyActions interface
*/
public class StormTopologyActionsImpl implements TopologyActions {
private static final Logger LOG = LoggerFactory.getLogger(StormTopologyActionsImpl.class);
public static final int DEFAULT_WAIT_TIME_SEC = 30;
public static final int TEST_RUN_TOPOLOGY_DEFAULT_WAIT_MILLIS_FOR_SHUTDOWN = 30_000;
public static final String ROOT_LOGGER_NAME = "ROOT";
private static final String DEFAULT_THRIFT_TRANSPORT_PLUGIN = "org.apache.storm.security.auth.SimpleTransportPlugin";
private static final String DEFAULT_PRINCIPAL_TO_LOCAL = "org.apache.storm.security.auth.DefaultPrincipalToLocal";
private static final String NIMBUS_SEEDS = "nimbus.seeds";
private static final String NIMBUS_PORT = "nimbus.port";
public static final String STREAMLINE_TOPOLOGY_CONFIG_CLUSTER_SECURITY_CONFIG = "clustersSecurityConfig";
public static final String STREAMLINE_TOPOLOGY_CONFIG_CLUSTER_ID = "clusterId";
public static final String STREAMLINE_TOPOLOGY_CONFIG_PRINCIPAL = "principal";
public static final String STREAMLINE_TOPOLOGY_CONFIG_KEYTAB_PATH = "keytabPath";
public static final String STORM_TOPOLOGY_CONFIG_AUTO_CREDENTIALS = "topology.auto-credentials";
public static final String TOPOLOGY_CONFIG_KEY_CLUSTER_KEY_PREFIX_HDFS = "hdfs_";
public static final String TOPOLOGY_CONFIG_KEY_CLUSTER_KEY_PREFIX_HBASE = "hbase_";
public static final String TOPOLOGY_CONFIG_KEY_CLUSTER_KEY_PREFIX_HIVE = "hive_";
public static final String TOPOLOGY_CONFIG_KEY_HDFS_KEYTAB_FILE = "hdfs.keytab.file";
public static final String TOPOLOGY_CONFIG_KEY_HBASE_KEYTAB_FILE = "hbase.keytab.file";
public static final String TOPOLOGY_CONFIG_KEY_HIVE_KEYTAB_FILE = "hive.keytab.file";
public static final String TOPOLOGY_CONFIG_KEY_HDFS_KERBEROS_PRINCIPAL = "hdfs.kerberos.principal";
public static final String TOPOLOGY_CONFIG_KEY_HBASE_KERBEROS_PRINCIPAL = "hbase.kerberos.principal";
public static final String TOPOLOGY_CONFIG_KEY_HIVE_KERBEROS_PRINCIPAL = "hive.kerberos.principal";
public static final String TOPOLOGY_CONFIG_KEY_HDFS_CREDENTIALS_CONFIG_KEYS = "hdfsCredentialsConfigKeys";
public static final String TOPOLOGY_CONFIG_KEY_HBASE_CREDENTIALS_CONFIG_KEYS = "hbaseCredentialsConfigKeys";
public static final String TOPOLOGY_CONFIG_KEY_HIVE_CREDENTIALS_CONFIG_KEYS = "hiveCredentialsConfigKeys";
public static final String TOPOLOGY_AUTO_CREDENTIAL_CLASSNAME_HDFS = "org.apache.storm.hdfs.security.AutoHDFS";
public static final String TOPOLOGY_AUTO_CREDENTIAL_CLASSNAME_HBASE = "org.apache.storm.hbase.security.AutoHBase";
public static final String TOPOLOGY_AUTO_CREDENTIAL_CLASSNAME_HIVE = "org.apache.storm.hive.security.AutoHive";
private static final Long DEFAULT_NIMBUS_THRIFT_MAX_BUFFER_SIZE = 1048576L;
public static final String TOPOLOGY_EVENTLOGGER_REGISTER = "topology.event.logger.register";
public static final String TOPOLOGY_EVENTLOGGER_CLASSNAME_STREAMLINE = "com.hortonworks.streamline.streams.runtime.storm.event.sample.StreamlineEventLogger";
private String stormArtifactsLocation = "/tmp/storm-artifacts/";
private String stormCliPath = "storm";
private String stormJarLocation;
private String catalogRootUrl;
private String javaJarCommand;
private StormRestAPIClient client;
private String nimbusSeeds;
private Integer nimbusPort;
private Map<String, Object> conf;
private String thriftTransport;
private Optional<String> jaasFilePath;
private String principalToLocal;
private long nimbusThriftMaxBufferSize;
private AutoCredsServiceConfigurationReader serviceConfigurationReader;
private final ConcurrentHashMap<Long, Boolean> forceKillRequests = new ConcurrentHashMap<>();
public StormTopologyActionsImpl() {
}
@Override
public void init (Map<String, Object> conf) {
this.conf = conf;
if (conf != null) {
if (conf.containsKey(StormTopologyLayoutConstants.STORM_ARTIFACTS_LOCATION_KEY)) {
stormArtifactsLocation = (String) conf.get(StormTopologyLayoutConstants.STORM_ARTIFACTS_LOCATION_KEY);
}
if (conf.containsKey(StormTopologyLayoutConstants.STORM_HOME_DIR)) {
String stormHomeDir = (String) conf.get(StormTopologyLayoutConstants.STORM_HOME_DIR);
if (!stormHomeDir.endsWith(File.separator)) {
stormHomeDir += File.separator;
}
stormCliPath = stormHomeDir + "bin" + File.separator + "storm";
}
this.stormJarLocation = (String) conf.get(StormTopologyLayoutConstants.STORM_JAR_LOCATION_KEY);
catalogRootUrl = (String) conf.get(StormTopologyLayoutConstants.YAML_KEY_CATALOG_ROOT_URL);
Map<String, String> env = System.getenv();
String javaHomeStr = env.get("JAVA_HOME");
if (StringUtils.isNotEmpty(javaHomeStr)) {
if (!javaHomeStr.endsWith(File.separator)) {
javaHomeStr += File.separator;
}
javaJarCommand = javaHomeStr + "bin" + File.separator + "jar";
} else {
javaJarCommand = "jar";
}
String stormApiRootUrl = (String) conf.get(TopologyLayoutConstants.STORM_API_ROOT_URL_KEY);
Subject subject = (Subject) conf.get(TopologyLayoutConstants.SUBJECT_OBJECT);
Client restClient = ClientBuilder.newClient(new ClientConfig());
this.client = new StormRestAPIClient(restClient, stormApiRootUrl, subject);
nimbusSeeds = (String) conf.get(NIMBUS_SEEDS);
nimbusPort = Integer.valueOf((String) conf.get(NIMBUS_PORT));
if (conf.containsKey(TopologyLayoutConstants.NIMBUS_THRIFT_MAX_BUFFER_SIZE)) {
nimbusThriftMaxBufferSize = (Long) conf.get(TopologyLayoutConstants.NIMBUS_THRIFT_MAX_BUFFER_SIZE);
} else {
nimbusThriftMaxBufferSize = DEFAULT_NIMBUS_THRIFT_MAX_BUFFER_SIZE;
}
setupSecuredStormCluster(conf);
EnvironmentService environmentService = (EnvironmentService) conf.get(TopologyLayoutConstants.ENVIRONMENT_SERVICE_OBJECT);
Number namespaceId = (Number) conf.get(TopologyLayoutConstants.NAMESPACE_ID);
this.serviceConfigurationReader = new AutoCredsServiceConfigurationReader(environmentService,
namespaceId.longValue());
}
File f = new File (stormArtifactsLocation);
if (!f.exists() && !f.mkdirs()) {
throw new RuntimeException("Could not create directory " + f.getAbsolutePath());
}
}
private void setupSecuredStormCluster(Map<String, Object> conf) {
thriftTransport = (String) conf.get(TopologyLayoutConstants.STORM_THRIFT_TRANSPORT);
if (conf.containsKey(TopologyLayoutConstants.STORM_NIMBUS_PRINCIPAL_NAME)) {
String nimbusPrincipal = (String) conf.get(TopologyLayoutConstants.STORM_NIMBUS_PRINCIPAL_NAME);
String kerberizedNimbusServiceName = nimbusPrincipal.split("/")[0];
jaasFilePath = Optional.of(createJaasFile(kerberizedNimbusServiceName));
} else {
jaasFilePath = Optional.empty();
}
principalToLocal = (String) conf.getOrDefault(TopologyLayoutConstants.STORM_PRINCIPAL_TO_LOCAL, DEFAULT_PRINCIPAL_TO_LOCAL);
if (thriftTransport == null) {
if (jaasFilePath.isPresent()) {
thriftTransport = (String) conf.get(TopologyLayoutConstants.STORM_SECURED_THRIFT_TRANSPORT);
} else {
thriftTransport = (String) conf.get(TopologyLayoutConstants.STORM_NONSECURED_THRIFT_TRANSPORT);
}
}
// if it's still null, set to default
if (thriftTransport == null) {
thriftTransport = DEFAULT_THRIFT_TRANSPORT_PLUGIN;
}
}
@Override
public void deploy(TopologyLayout topology, String mavenArtifacts, TopologyActionContext ctx, String asUser) throws Exception {
ctx.setCurrentAction("Adding artifacts to jar");
Path jarToDeploy = addArtifactsToJar(getArtifactsLocation(topology));
ctx.setCurrentAction("Creating Storm topology YAML file");
String fileName = createYamlFile(topology);
ctx.setCurrentAction("Deploying topology via 'storm jar' command");
List<String> commands = new ArrayList<String>();
commands.add(stormCliPath);
commands.add("jar");
commands.add(jarToDeploy.toString());
commands.addAll(getExtraJarsArg(topology));
commands.addAll(getMavenArtifactsRelatedArgs(mavenArtifacts));
commands.addAll(getNimbusConf());
commands.addAll(getSecuredClusterConf(asUser));
commands.add("org.apache.storm.flux.Flux");
commands.add("--remote");
commands.add(fileName);
LOG.info("Deploying Application {}", topology.getName());
LOG.info(String.join(" ", commands));
Process process = executeShellProcess(commands);
ShellProcessResult shellProcessResult = waitProcessFor(process);
int exitValue = shellProcessResult.exitValue;
if (exitValue != 0) {
LOG.error("Topology deploy command failed - exit code: {} / output: {}", exitValue, shellProcessResult.stdout);
String[] lines = shellProcessResult.stdout.split("\\n");
String errors = Arrays.stream(lines)
.filter(line -> line.startsWith("Exception"))
.collect(Collectors.joining(", "));
Pattern pattern = Pattern.compile("Topology with name `(.*)` already exists on cluster");
Matcher matcher = pattern.matcher(errors);
if (matcher.find()) {
throw new TopologyAlreadyExistsOnCluster(matcher.group(1));
} else {
throw new Exception("Topology could not be deployed successfully: storm deploy command failed with " + errors);
}
}
}
@Override
public void runTest(TopologyLayout topology, TopologyTestRunHistory testRunHistory, String mavenArtifacts,
Map<String, TestRunSource> testRunSourcesForEachSource,
Map<String, TestRunProcessor> testRunProcessorsForEachProcessor,
Map<String, TestRunRulesProcessor> testRunRulesProcessorsForEachProcessor,
Map<String, TestRunSink> testRunSinksForEachSink, Optional<Long> durationSecs) throws Exception {
TopologyDag originalTopologyDag = topology.getTopologyDag();
TestTopologyDagCreatingVisitor visitor = new TestTopologyDagCreatingVisitor(originalTopologyDag,
testRunSourcesForEachSource, testRunProcessorsForEachProcessor, testRunRulesProcessorsForEachProcessor,
testRunSinksForEachSink);
originalTopologyDag.traverse(visitor);
TopologyDag testTopologyDag = visitor.getTestTopologyDag();
TopologyLayout testTopology = copyTopologyLayout(topology, testTopologyDag);
Path jarToDeploy = addArtifactsToJar(getArtifactsLocation(testTopology));
String fileName = createYamlFile(testTopology);
List<String> commands = new ArrayList<String>();
commands.add(stormCliPath);
commands.add("jar");
commands.add(jarToDeploy.toString());
commands.addAll(getExtraJarsArg(testTopology));
commands.addAll(getMavenArtifactsRelatedArgs(mavenArtifacts));
commands.addAll(getNimbusConf());
commands.addAll(getTempWorkerArtifactArgs());
commands.add("org.apache.storm.flux.Flux");
commands.add("--local");
commands.add("-s");
if (durationSecs.isPresent()) {
commands.add(String.valueOf(durationSecs.get() * 1000));
} else {
commands.add(String.valueOf(TEST_RUN_TOPOLOGY_DEFAULT_WAIT_MILLIS_FOR_SHUTDOWN));
}
commands.add(fileName);
Process process = executeShellProcess(commands);
ShellProcessResult shellProcessResult = waitTestRunProcess(process, testRunHistory.getId());
int exitValue = shellProcessResult.exitValue;
if (exitValue != 0) {
LOG.error("Topology deploy command as test mode failed - exit code: {} / output: {}", exitValue, shellProcessResult.stdout);
throw new Exception("Topology could not be run " +
"successfully as test mode: storm deploy command failed");
}
}
@Override
public boolean killTest(TopologyTestRunHistory testRunHistory) {
// just turn on the flag only if it exists
LOG.info("Turning on force kill flag on test run history {}", testRunHistory.getId());
Boolean newValue = forceKillRequests.computeIfPresent(testRunHistory.getId(), (id, flag) -> true);
return newValue != null;
}
@Override
public void kill (TopologyLayout topology, String asUser) throws Exception {
String stormTopologyId = getRuntimeTopologyId(topology, asUser);
boolean killed = client.killTopology(stormTopologyId, asUser, DEFAULT_WAIT_TIME_SEC);
if (!killed) {
throw new Exception("Topology could not be killed " +
"successfully.");
}
File artifactsDir = getArtifactsLocation(topology).toFile();
if (artifactsDir.exists() && artifactsDir.isDirectory()) {
LOG.debug("Cleaning up {}", artifactsDir);
FileUtils.cleanDirectory(artifactsDir);
}
}
@Override
public void validate (TopologyLayout topology) throws Exception {
Map<String, Object> topologyConfig = topology.getConfig().getProperties();
if (!topologyConfig.isEmpty()) {
StormTopologyValidator validator = new StormTopologyValidator(topologyConfig, this.catalogRootUrl);
validator.validate();
}
}
@Override
public void suspend (TopologyLayout topology, String asUser) throws Exception {
String stormTopologyId = getRuntimeTopologyId(topology, asUser);
boolean suspended = client.deactivateTopology(stormTopologyId, asUser);
if (!suspended) {
throw new Exception("Topology could not be suspended " +
"successfully.");
}
}
@Override
public void resume (TopologyLayout topology, String asUser) throws Exception {
String stormTopologyId = getRuntimeTopologyId(topology, asUser);
if (stormTopologyId == null || stormTopologyId.isEmpty()) {
throw new TopologyNotAliveException("Topology not found in Storm Cluster - topology id: " + topology.getId());
}
boolean resumed = client.activateTopology(stormTopologyId, asUser);
if (!resumed) {
throw new Exception("Topology could not be resumed " +
"successfully.");
}
}
@Override
public Status status(TopologyLayout topology, String asUser) throws Exception {
String stormTopologyId = getRuntimeTopologyId(topology, asUser);
Map topologyStatus = client.getTopology(stormTopologyId, asUser);
StatusImpl status = new StatusImpl();
status.setStatus((String) topologyStatus.get("status"));
status.putExtra("Num_tasks", String.valueOf(topologyStatus.get("workersTotal")));
status.putExtra("Num_workers", String.valueOf(topologyStatus.get("tasksTotal")));
status.putExtra("Uptime_secs", String.valueOf(topologyStatus.get("uptimeSeconds")));
return status;
}
@Override
public LogLevelInformation configureLogLevel(TopologyLayout topology, LogLevel targetLogLevel, int durationSecs, String asUser) throws Exception {
String stormTopologyId = StormTopologyUtil.findStormTopologyId(client, topology.getId(), asUser);
if (StringUtils.isEmpty(stormTopologyId)) {
return null;
}
LogLevelResponse response = client.configureLog(stormTopologyId, ROOT_LOGGER_NAME, targetLogLevel.name(),
durationSecs, asUser);
return convertLogLevelResponseToLogLevelInformation(response);
}
@Override
public LogLevelInformation getLogLevel(TopologyLayout topology, String asUser) throws Exception {
String stormTopologyId = StormTopologyUtil.findStormTopologyId(client, topology.getId(), asUser);
if (StringUtils.isEmpty(stormTopologyId)) {
return null;
}
LogLevelResponse response = client.getLogLevel(stormTopologyId, asUser);
return convertLogLevelResponseToLogLevelInformation(response);
}
/**
* the Path where any topology specific artifacts are kept
*/
@Override
public Path getArtifactsLocation(TopologyLayout topology) {
return Paths.get(stormArtifactsLocation, generateStormTopologyName(topology), "artifacts");
}
@Override
public Path getExtraJarsLocation(TopologyLayout topology) {
return Paths.get(stormArtifactsLocation, generateStormTopologyName(topology), "jars");
}
@Override
public String getRuntimeTopologyId(TopologyLayout topology, String asUser) {
String stormTopologyId = StormTopologyUtil.findStormTopologyId(client, topology.getId(), asUser);
if (StringUtils.isEmpty(stormTopologyId)) {
throw new TopologyNotAliveException("Topology not found in Storm Cluster - topology id: " + topology.getId());
}
return stormTopologyId;
}
private TopologyLayout copyTopologyLayout(TopologyLayout topology, TopologyDag replacedTopologyDag) {
return new TopologyLayout(topology.getId(), topology.getName(), topology.getConfig(), replacedTopologyDag);
}
private List<String> getMavenArtifactsRelatedArgs (String mavenArtifacts) {
List<String> args = new ArrayList<>();
if (mavenArtifacts != null && !mavenArtifacts.isEmpty()) {
args.add("--artifacts");
args.add(mavenArtifacts);
args.add("--artifactRepositories");
args.add((String) conf.get("mavenRepoUrl"));
String proxyUrl = (String) conf.get("proxyUrl");
if (StringUtils.isNotEmpty(proxyUrl)) {
args.add("--proxyUrl");
args.add(proxyUrl);
String proxyUsername = (String) conf.get("proxyUsername");
String proxyPassword = (String) conf.get("proxyPassword");
if (proxyUsername != null && proxyPassword != null) {
// allow empty string but not null
args.add("--proxyUsername");
args.add(proxyUsername);
args.add("--proxyPassword");
args.add(proxyPassword);
}
}
}
return args;
}
private List<String> getExtraJarsArg(TopologyLayout topology) {
List<String> args = new ArrayList<>();
List<String> jars = new ArrayList<>();
Path extraJarsPath = getExtraJarsLocation(topology);
if (extraJarsPath.toFile().isDirectory()) {
File[] jarFiles = extraJarsPath.toFile().listFiles();
if (jarFiles != null && jarFiles.length > 0) {
for (File jarFile : jarFiles) {
jars.add(jarFile.getAbsolutePath());
}
}
} else {
LOG.debug("Extra jars directory {} does not exist, not adding any extra jars", extraJarsPath);
}
if (!jars.isEmpty()) {
args.add("--jars");
args.add(Joiner.on(",").join(jars));
}
return args;
}
private List<String> getNimbusConf() {
List<String> args = new ArrayList<>();
// FIXME: Can't find how to pass list to nimbus.seeds for Storm CLI
// Maybe we need to fix Storm to parse string when expected parameter type is list
args.add("-c");
args.add("nimbus.host=" + nimbusSeeds.split(",")[0]);
args.add("-c");
args.add("nimbus.port=" + String.valueOf(nimbusPort));
args.add("-c");
args.add("nimbus.thrift.max_buffer_size=" + String.valueOf(nimbusThriftMaxBufferSize));
return args;
}
private List<String> getSecuredClusterConf(String asUser) {
List<String> args = new ArrayList<>();
args.add("-c");
args.add("storm.thrift.transport=" + thriftTransport);
if (jaasFilePath.isPresent()) {
args.add("-c");
args.add("java.security.auth.login.config=" + jaasFilePath.get());
}
args.add("-c");
args.add("storm.principal.tolocal=" + principalToLocal);
if (StringUtils.isNotEmpty(asUser)) {
args.add("-c");
args.add("storm.doAsUser=" + asUser);
}
return args;
}
private List<String> getTempWorkerArtifactArgs() throws IOException {
List<String> args = new ArrayList<>();
Path tempArtifacts = Files.createTempDirectory("worker-artifacts-");
args.add("-c");
args.add("storm.workers.artifacts.dir=" + tempArtifacts.toFile().getAbsolutePath());
return args;
}
private String createJaasFile(String kerberizedNimbusServiceName) {
try {
Path jaasFilePath = Files.createTempFile("jaas-", UUID.randomUUID().toString());
String filePath = jaasFilePath.toAbsolutePath().toString();
File jaasFile = new StormJaasCreator().create(filePath, kerberizedNimbusServiceName);
return jaasFile.getAbsolutePath();
} catch (IOException e) {
throw new RuntimeException("Can't create JAAS file to connect to secure nimbus", e);
}
}
private Path addArtifactsToJar(Path artifactsLocation) throws Exception {
Path jarFile = Paths.get(stormJarLocation);
if (artifactsLocation.toFile().isDirectory()) {
File[] artifacts = artifactsLocation.toFile().listFiles();
if (artifacts != null && artifacts.length > 0) {
Path newJar = Files.copy(jarFile, artifactsLocation.resolve(jarFile.getFileName()));
List<String> artifactFileNames = Arrays.stream(artifacts).filter(File::isFile)
.map(File::getName).collect(toList());
List<String> commands = new ArrayList<>();
commands.add(javaJarCommand);
commands.add("uf");
commands.add(newJar.toString());
artifactFileNames.stream().forEachOrdered(name -> {
commands.add("-C");
commands.add(artifactsLocation.toString());
commands.add(name);
});
Process process = executeShellProcess(commands);
ShellProcessResult shellProcessResult = waitProcessFor(process);
if (shellProcessResult.exitValue != 0) {
LOG.error("Adding artifacts to jar command failed - exit code: {} / output: {}",
shellProcessResult.exitValue, shellProcessResult.stdout);
throw new RuntimeException("Topology could not be deployed " +
"successfully: fail to add artifacts to jar");
}
LOG.debug("Added files {} to jar {}", artifactFileNames, jarFile);
return newJar;
}
} else {
LOG.debug("Artifacts directory {} does not exist, not adding any artifacts to jar", artifactsLocation);
}
return jarFile;
}
private String createYamlFile (TopologyLayout topology) throws Exception {
Map<String, Object> yamlMap;
File f;
OutputStreamWriter fileWriter = null;
try {
f = new File(this.getFilePath(topology));
if (f.exists()) {
if (!f.delete()) {
throw new Exception("Unable to delete old storm " +
"artifact for topology id " + topology.getId());
}
}
yamlMap = new LinkedHashMap<>();
yamlMap.put(StormTopologyLayoutConstants.YAML_KEY_NAME, generateStormTopologyName(topology));
TopologyDag topologyDag = topology.getTopologyDag();
LOG.debug("Initial Topology config {}", topology.getConfig());
StormTopologyFluxGenerator fluxGenerator = new StormTopologyFluxGenerator(topology, conf,
getExtraJarsLocation(topology));
topologyDag.traverse(fluxGenerator);
for (Map.Entry<String, Map<String, Object>> entry: fluxGenerator.getYamlKeysAndComponents()) {
addComponentToCollection(yamlMap, entry.getValue(), entry.getKey());
}
Config topologyConfig = fluxGenerator.getTopologyConfig();
putAutoTokenDelegationConfig(topologyConfig, topologyDag);
registerEventLogger(topologyConfig);
LOG.debug("Final Topology config {}", topologyConfig);
addTopologyConfig(yamlMap, topologyConfig.getProperties());
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setSplitLines(false);
//options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
Yaml yaml = new Yaml (options);
fileWriter = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
yaml.dump(yamlMap, fileWriter);
return f.getAbsolutePath();
} finally {
if (fileWriter != null) {
fileWriter.close();
}
}
}
private void registerEventLogger(Config topologyConfig) {
topologyConfig.put(TOPOLOGY_EVENTLOGGER_REGISTER,
Collections.singletonList(
Collections.singletonMap("class", TOPOLOGY_EVENTLOGGER_CLASSNAME_STREAMLINE))
);
}
private void putAutoTokenDelegationConfig(Config topologyConfig, TopologyDag topologyDag) {
Optional<?> securityConfigsOptional = topologyConfig.getAnyOptional(STREAMLINE_TOPOLOGY_CONFIG_CLUSTER_SECURITY_CONFIG);
Map<Long, Map<String, String>> clusterToConfiguration = new HashMap<>();
if (securityConfigsOptional.isPresent()) {
List<?> securityConfigurations = (List<?>) securityConfigsOptional.get();
securityConfigurations.forEach(securityConfig -> {
Map<String, Object> sc = (Map<String, Object>) securityConfig;
if ((sc != null) && !sc.isEmpty()) {
Long clusterId = ((Number) sc.get(STREAMLINE_TOPOLOGY_CONFIG_CLUSTER_ID)).longValue();
Map<String, String> configurationForCluster = new HashMap<>();
configurationForCluster.put(STREAMLINE_TOPOLOGY_CONFIG_PRINCIPAL, (String) sc.get(STREAMLINE_TOPOLOGY_CONFIG_PRINCIPAL));
configurationForCluster.put(STREAMLINE_TOPOLOGY_CONFIG_KEYTAB_PATH, (String) sc.get(STREAMLINE_TOPOLOGY_CONFIG_KEYTAB_PATH));
clusterToConfiguration.put(clusterId, configurationForCluster);
}
});
}
if (clusterToConfiguration.isEmpty()) {
// it will function only when user input keytab path and principal
return;
}
// Hive also needs HDFS auto token delegation, so HiveSink is added to the checklist
boolean hdfsCredentialNecessary = checkTopologyContainingServiceRelatedComponent(topologyDag,
Collections.singletonList(HdfsSource.class),
Lists.newArrayList(HdfsSink.class, HiveSink.class));
boolean hbaseCredentialNecessary = checkTopologyContainingServiceRelatedComponent(topologyDag,
Collections.emptyList(),
Collections.singletonList(HBaseSink.class));
boolean hiveCredentialNecessary = checkTopologyContainingServiceRelatedComponent(topologyDag,
Collections.emptyList(),
Collections.singletonList(HiveSink.class));
if (hdfsCredentialNecessary) {
putServiceSpecificCredentialConfig(topologyConfig, clusterToConfiguration,
Constants.HDFS.SERVICE_NAME,
Collections.emptyList(),
TOPOLOGY_CONFIG_KEY_CLUSTER_KEY_PREFIX_HDFS, TOPOLOGY_CONFIG_KEY_HDFS_KEYTAB_FILE,
TOPOLOGY_CONFIG_KEY_HDFS_KERBEROS_PRINCIPAL,
TOPOLOGY_CONFIG_KEY_HDFS_CREDENTIALS_CONFIG_KEYS, TOPOLOGY_AUTO_CREDENTIAL_CLASSNAME_HDFS);
}
if (hbaseCredentialNecessary) {
putServiceSpecificCredentialConfig(topologyConfig, clusterToConfiguration,
Constants.HBase.SERVICE_NAME,
Collections.singletonList(Constants.HDFS.SERVICE_NAME),
TOPOLOGY_CONFIG_KEY_CLUSTER_KEY_PREFIX_HBASE, TOPOLOGY_CONFIG_KEY_HBASE_KEYTAB_FILE,
TOPOLOGY_CONFIG_KEY_HBASE_KERBEROS_PRINCIPAL,
TOPOLOGY_CONFIG_KEY_HBASE_CREDENTIALS_CONFIG_KEYS, TOPOLOGY_AUTO_CREDENTIAL_CLASSNAME_HBASE);
}
if (hiveCredentialNecessary) {
putServiceSpecificCredentialConfig(topologyConfig, clusterToConfiguration,
Constants.Hive.SERVICE_NAME,
Collections.singletonList(Constants.HDFS.SERVICE_NAME),
TOPOLOGY_CONFIG_KEY_CLUSTER_KEY_PREFIX_HIVE, TOPOLOGY_CONFIG_KEY_HIVE_KEYTAB_FILE,
TOPOLOGY_CONFIG_KEY_HIVE_KERBEROS_PRINCIPAL,
TOPOLOGY_CONFIG_KEY_HIVE_CREDENTIALS_CONFIG_KEYS, TOPOLOGY_AUTO_CREDENTIAL_CLASSNAME_HIVE);
}
}
public boolean checkTopologyContainingServiceRelatedComponent(TopologyDag topologyDag,
List<Class<?>> outputComponentClasses,
List<Class<?>> inputComponentClasses) {
boolean componentExists = false;
for (OutputComponent outputComponent : topologyDag.getOutputComponents()) {
for (Class<?> clazz : outputComponentClasses) {
if (outputComponent.getClass().isAssignableFrom(clazz)) {
componentExists = true;
break;
}
}
}
if (!componentExists) {
for (InputComponent inputComponent : topologyDag.getInputComponents()) {
for (Class<?> clazz : inputComponentClasses) {
if (inputComponent.getClass().isAssignableFrom(clazz)) {
componentExists = true;
break;
}
}
}
}
return componentExists;
}
private void putServiceSpecificCredentialConfig(Config topologyConfig,
Map<Long, Map<String, String>> clusterToConfiguration,
String serviceName,
List<String> dependentServiceNames,
String clusterKeyPrefix,
String keytabPathKeyName, String principalKeyName,
String credentialConfigKeyName,
String topologyAutoCredentialClassName) {
List<String> clusterKeys = new ArrayList<>();
clusterToConfiguration.keySet()
.forEach(clusterId -> {
Map<String, String> conf = serviceConfigurationReader.read(clusterId, serviceName);
// add only when such (cluster, service) pair is available for the namespace
if (!conf.isEmpty()) {
Map<String, String> confForToken = clusterToConfiguration.get(clusterId);
conf.put(principalKeyName, confForToken.get(STREAMLINE_TOPOLOGY_CONFIG_PRINCIPAL));
conf.put(keytabPathKeyName, confForToken.get(STREAMLINE_TOPOLOGY_CONFIG_KEYTAB_PATH));
// also includes all configs for dependent services
// note that such services in cluster should also be associated to the namespace
Map<String, String> clusterConf = new HashMap<>();
dependentServiceNames.forEach(depSvcName -> {
Map<String, String> depConf = serviceConfigurationReader.read(clusterId, depSvcName);
clusterConf.putAll(depConf);
});
clusterConf.putAll(conf);
String clusterKey = clusterKeyPrefix + clusterId;
topologyConfig.put(clusterKey, clusterConf);
clusterKeys.add(clusterKey);
}
});
topologyConfig.put(credentialConfigKeyName, clusterKeys);
Optional<List<String>> autoCredentialsOptional = topologyConfig.getAnyOptional(STORM_TOPOLOGY_CONFIG_AUTO_CREDENTIALS);
if (autoCredentialsOptional.isPresent()) {
List<String> autoCredentials = autoCredentialsOptional.get();
autoCredentials.add(topologyAutoCredentialClassName);
} else {
topologyConfig.put(STORM_TOPOLOGY_CONFIG_AUTO_CREDENTIALS, Lists.newArrayList(topologyAutoCredentialClassName));
}
}
private String generateStormTopologyName(TopologyLayout topology) {
return StormTopologyUtil.generateStormTopologyName(topology.getId(), topology.getName());
}
private String getFilePath (TopologyLayout topology) {
return this.stormArtifactsLocation + generateStormTopologyName(topology) + ".yaml";
}
// Add topology level configs. catalogRootUrl, hbaseConf, hdfsConf,
// numWorkers, etc.
private void addTopologyConfig (Map<String, Object> yamlMap, Map<String, Object> topologyConfig) {
Map<String, Object> config = new LinkedHashMap<>();
config.put(StormTopologyLayoutConstants.YAML_KEY_CATALOG_ROOT_URL, catalogRootUrl);
//Hack to work around HBaseBolt expecting this map in prepare method. Fix HBaseBolt and get rid of this. We use hbase-site.xml conf from ambari
config.put(StormTopologyLayoutConstants.YAML_KEY_HBASE_CONF, new HashMap<>());
if (topologyConfig != null) {
config.putAll(topologyConfig);
}
yamlMap.put(StormTopologyLayoutConstants.YAML_KEY_CONFIG, config);
}
private void addComponentToCollection (Map<String, Object> yamlMap, Map<String, Object> yamlComponent, String collectionKey) {
if (yamlComponent == null ) {
return;
}
List<Map<String, Object>> components = (List<Map<String, Object>>) yamlMap.get(collectionKey);
if (components == null) {
components = new ArrayList<>();
yamlMap.put(collectionKey, components);
}
components.add(yamlComponent);
}
private Process executeShellProcess (List<String> commands) throws Exception {
LOG.debug("Executing command: {}", Joiner.on(" ").join(commands));
ProcessBuilder processBuilder = new ProcessBuilder(commands);
processBuilder.redirectErrorStream(true);
return processBuilder.start();
}
private ShellProcessResult waitProcessFor(Process process) throws IOException, InterruptedException {
StringWriter sw = new StringWriter();
IOUtils.copy(process.getInputStream(), sw, Charset.defaultCharset());
String stdout = sw.toString();
process.waitFor();
int exitValue = process.exitValue();
LOG.debug("Command output: {}", stdout);
LOG.debug("Command exit status: {}", exitValue);
return new ShellProcessResult(exitValue, stdout);
}
private ShellProcessResult waitTestRunProcess(Process process, long topologyRunHistoryId) throws IOException {
forceKillRequests.put(topologyRunHistoryId, false);
LOG.info("Waiting for test run for history {} to be finished...", topologyRunHistoryId);
StringBuilder sb = new StringBuilder();
for (int idx = 0 ; ; idx++) {
if (!process.isAlive()) {
break;
}
// read stdout if available
sb.append(readProcessStream(process.getInputStream()));
if (forceKillRequests.getOrDefault(topologyRunHistoryId, false)) {
LOG.info("Received force kill for test run {} - destroying process...", topologyRunHistoryId);
process.destroyForcibly();
}
// leave a log for each 10 secs...
if ((idx + 1) % 100 == 0) {
LOG.info("Still waiting for test run for history {} to be finished...", topologyRunHistoryId);
}
try {
process.waitFor(100, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// ignored
}
}
LOG.info("Test run for history {} is finished", topologyRunHistoryId);
String stdout = sb.toString();
forceKillRequests.remove(topologyRunHistoryId);
int exitValue = process.exitValue();
LOG.debug("Command output: {}", stdout);
LOG.debug("Command exit status: {}", exitValue);
return new ShellProcessResult(exitValue, stdout);
}
private String readProcessStream(InputStream processInputStream) {
try {
StringBuilder sb = new StringBuilder();
while (processInputStream.available() > 0) {
int bufferSize = processInputStream.available();
byte[] errorReadingBuffer = new byte[bufferSize];
int readSize = processInputStream.read(errorReadingBuffer, 0, bufferSize);
errorReadingBuffer = Arrays.copyOfRange(errorReadingBuffer, 0, readSize);
sb.append(new String(errorReadingBuffer, Charset.forName("UTF-8")));
}
return sb.toString();
} catch (IOException e) {
return "(cannot capture process stream)";
}
}
private static class ShellProcessResult {
private final int exitValue;
private final String stdout;
ShellProcessResult(int exitValue, String stdout) {
this.exitValue = exitValue;
this.stdout = stdout;
}
}
private LogLevelInformation convertLogLevelResponseToLogLevelInformation(LogLevelResponse response) {
Map<String, LogLevelLoggerResponse> namedLoggerLevels = response.getNamedLoggerLevels();
LogLevelLoggerResponse resp = namedLoggerLevels.get(ROOT_LOGGER_NAME);
if (resp == null) {
return LogLevelInformation.disabled();
}
return LogLevelInformation.enabled(LogLevel.valueOf(resp.getTargetLevel()), resp.getTimeoutEpoch());
}
}
| ISSUE-1115 Disable topology event logger in test mode
This closes #1115
Author: Jungtaek Lim <[email protected]>
Closes #1116 from HeartSaVioR/ISSUE-1115
| streams/runners/storm/actions/src/main/java/com/hortonworks/streamline/streams/actions/storm/topology/StormTopologyActionsImpl.java | ISSUE-1115 Disable topology event logger in test mode | <ide><path>treams/runners/storm/actions/src/main/java/com/hortonworks/streamline/streams/actions/storm/topology/StormTopologyActionsImpl.java
<ide> ctx.setCurrentAction("Adding artifacts to jar");
<ide> Path jarToDeploy = addArtifactsToJar(getArtifactsLocation(topology));
<ide> ctx.setCurrentAction("Creating Storm topology YAML file");
<del> String fileName = createYamlFile(topology);
<add> String fileName = createYamlFileForDeploy(topology);
<ide> ctx.setCurrentAction("Deploying topology via 'storm jar' command");
<ide> List<String> commands = new ArrayList<String>();
<ide> commands.add(stormCliPath);
<ide> TopologyLayout testTopology = copyTopologyLayout(topology, testTopologyDag);
<ide>
<ide> Path jarToDeploy = addArtifactsToJar(getArtifactsLocation(testTopology));
<del> String fileName = createYamlFile(testTopology);
<add> String fileName = createYamlFileForTest(testTopology);
<ide> List<String> commands = new ArrayList<String>();
<ide> commands.add(stormCliPath);
<ide> commands.add("jar");
<ide> return jarFile;
<ide> }
<ide>
<del> private String createYamlFile (TopologyLayout topology) throws Exception {
<add> private String createYamlFileForDeploy(TopologyLayout topology) throws Exception {
<add> return createYamlFile(topology, true);
<add> }
<add>
<add> private String createYamlFileForTest(TopologyLayout topology) throws Exception {
<add> return createYamlFile(topology, false);
<add> }
<add>
<add> private String createYamlFile (TopologyLayout topology, boolean deploy) throws Exception {
<ide> Map<String, Object> yamlMap;
<ide> File f;
<ide> OutputStreamWriter fileWriter = null;
<ide> putAutoTokenDelegationConfig(topologyConfig, topologyDag);
<ide> registerEventLogger(topologyConfig);
<ide>
<del> LOG.debug("Final Topology config {}", topologyConfig);
<del> addTopologyConfig(yamlMap, topologyConfig.getProperties());
<add> Map<String, Object> properties = topologyConfig.getProperties();
<add> if (!deploy) {
<add> LOG.debug("Disabling topology event logger for test mode...");
<add> properties.put("topology.eventlogger.executors", 0);
<add> }
<add>
<add> LOG.debug("Final Topology properties {}", properties);
<add>
<add> addTopologyConfig(yamlMap, properties);
<ide> DumperOptions options = new DumperOptions();
<ide> options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
<ide> options.setSplitLines(false); |
|
Java | apache-2.0 | a85638093b6d034e1c640a0eea6b5dd4e1b1be5d | 0 | trajano/jaxws-maven-plugin | /*
* Copyright 2006 Guillaume Nodet.
*
* 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.codehaus.mojo.jaxws;
import com.sun.tools.ws.WsGen;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.artifact.Artifact;
import java.io.File;
import java.util.ArrayList;
import java.util.Set;
import java.util.List;
/**
*
*
* @author gnodet <[email protected]>
* @author dantran <[email protected]>
* @version $Id: WsGenMojo.java 3169 2007-01-22 02:51:29Z dantran $
*/
abstract class AbstractWsGenMojo extends AbstractJaxwsMojo {
/**
* Specify that a WSDL file should be generated in ${resourceDestDir}
*
* @parameter default-value="false"
*/
private boolean genWsdl;
/**
* Directory containing the generated wsdl files.
*
* @parameter default-value="${project.build.directory}/jaxws/wsgen/wsdl"
*/
private File resourceDestDir;
/**
* service endpoint implementation class name.
*
* @parameter
* @required
*/
private String sei;
/**
* Used in conjunction with genWsdl to specify the protocol to use in the
* wsdl:binding. Value values are "soap1.1" or "Xsoap1.2", default is "soap1.1".
* "Xsoap1.2" is not standard and can only be used in conjunction with the
* -extensions option
*
* @parameter
*/
private String protocol;
/**
* @parameter expression="${plugin.artifacts}"
* @required
*/
private List<Artifact> pluginArtifacts;
/**
* Specify where to place generated source files, keep is turned on with this option.
*
* @parameter
*/
private File sourceDestDir;
//default-value="${project.build.directory}/jaxws/java"
public void execute()
throws MojoExecutionException, MojoFailureException {
init();
// Need to build a URLClassloader since Maven removed it form the chain
ClassLoader parent = this.getClass().getClassLoader();
String orginalSystemClasspath = this.initClassLoader(parent);
try {
ArrayList<String> args = getWsGenArgs();
if (WsGen.doMain(args.toArray(new String[args.size()])) != 0)
throw new MojoExecutionException("Error executing: wsgen " + args);
} catch (MojoExecutionException e) {
throw e;
} catch (Throwable e) {
throw new MojoExecutionException("Failed to execute wsgen",e);
} finally {
// Set back the old classloader
Thread.currentThread().setContextClassLoader(parent);
System.setProperty("java.class.path", orginalSystemClasspath);
}
}
private void init() throws MojoExecutionException, MojoFailureException {
if (!getDestDir().exists())
getDestDir().mkdirs();
}
/**
* Construct wsgen arguments
* @return a list of arguments
* @throws MojoExecutionException
*/
private ArrayList<String> getWsGenArgs()
throws MojoExecutionException {
ArrayList<String> args = new ArrayList<String>();
if (verbose) {
args.add("-verbose");
}
if (keep || this.sourceDestDir!=null) {
args.add("-keep");
}
if (this.sourceDestDir != null) {
args.add("-s");
args.add(this.sourceDestDir.getAbsolutePath());
this.sourceDestDir.mkdirs();
}
args.add("-d");
args.add(getDestDir().getAbsolutePath());
args.add("-cp");
StringBuilder buf = new StringBuilder();
buf.append(getDestDir().getAbsolutePath());
for (Artifact a : (Set<Artifact>)project.getArtifacts()) {
buf.append(File.pathSeparatorChar);
buf.append(a.getFile().getAbsolutePath());
}
for (Artifact a : pluginArtifacts) {
buf.append(File.pathSeparatorChar);
buf.append(a.getFile().getAbsolutePath());
}
args.add(buf.toString());
if (this.genWsdl) {
if (this.protocol != null) {
args.add("-wsdl:" + this.protocol);
} else {
args.add("-wsdl");
}
args.add("-r");
args.add(this.resourceDestDir.getAbsolutePath());
this.resourceDestDir.mkdirs();
}
if ( this.extension ) {
args.add( "-extension" );
}
args.add(sei);
getLog().debug("jaxws:wsgen args: " + args);
return args;
}
}
| src/main/java/org/codehaus/mojo/jaxws/AbstractWsGenMojo.java | /*
* Copyright 2006 Guillaume Nodet.
*
* 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.codehaus.mojo.jaxws;
import com.sun.tools.ws.WsGen;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.artifact.Artifact;
import java.io.File;
import java.util.ArrayList;
import java.util.Set;
import java.util.List;
/**
*
*
* @author gnodet <[email protected]>
* @author dantran <[email protected]>
* @version $Id: WsGenMojo.java 3169 2007-01-22 02:51:29Z dantran $
*/
abstract class AbstractWsGenMojo extends AbstractJaxwsMojo {
/**
* Specify that a WSDL file should be generated in ${resourceDestDir}
*
* @parameter default-value="false"
*/
private boolean genWsdl;
/**
* Directory containing the generated wsdl files.
*
* @parameter default-value="${project.build.directory}/jaxws/wsgen/wsdl"
*/
private File resourceDestDir;
/**
* service endpoint implementation class name.
*
* @parameter
* @required
*/
private String sei;
/**
* Used in conjunction with genWsdl to specify the protocol to use in the
* wsdl:binding. Value values are "soap1.1" or "Xsoap1.2", default is "soap1.1".
* "Xsoap1.2" is not standard and can only be used in conjunction with the
* -extensions option
*
* @parameter
*/
private String protocol;
/**
* @parameter expression="${plugin.artifacts}"
* @required
*/
private List<Artifact> pluginArtifacts;
/**
* Specify where to place generated source files, keep is turned on with this option.
*
* @parameter
*/
private File sourceDestDir;
//default-value="${project.build.directory}/jaxws/java"
public void execute()
throws MojoExecutionException, MojoFailureException {
init();
// Need to build a URLClassloader since Maven removed it form the chain
ClassLoader parent = this.getClass().getClassLoader();
String orginalSystemClasspath = this.initClassLoader(parent);
try {
ArrayList<String> args = getWsGenArgs();
if (WsGen.doMain(args.toArray(new String[args.size()])) != 0)
throw new MojoExecutionException("Error executing: wsgen " + args);
} catch (MojoExecutionException e) {
throw e;
} catch (Throwable e) {
throw new MojoExecutionException("Failed to execute wsgen",e);
} finally {
// Set back the old classloader
Thread.currentThread().setContextClassLoader(parent);
System.setProperty("java.class.path", orginalSystemClasspath);
}
}
private void init() throws MojoExecutionException, MojoFailureException {
if (!getDestDir().exists())
getDestDir().mkdirs();
}
/**
* Construct wsgen arguments
* @return a list of arguments
* @throws MojoExecutionException
*/
private ArrayList<String> getWsGenArgs()
throws MojoExecutionException {
ArrayList<String> args = new ArrayList<String>();
if (verbose) {
args.add("-verbose");
}
if (keep || this.sourceDestDir!=null) {
args.add("-keep");
}
if (this.sourceDestDir != null) {
args.add("-s");
args.add(this.sourceDestDir.getAbsolutePath());
this.sourceDestDir.mkdirs();
}
args.add("-d");
args.add(getDestDir().getAbsolutePath());
args.add("-cp");
StringBuilder buf = new StringBuilder();
buf.append(getDestDir().getAbsolutePath());
for (Artifact a : (Set<Artifact>)project.getArtifacts()) {
buf.append(File.pathSeparatorChar);
buf.append(a.getFile().getAbsolutePath());
}
for (Artifact a : pluginArtifacts) {
buf.append(File.pathSeparatorChar);
buf.append(a.getFile().getAbsolutePath());
}
args.add(buf.toString());
if (this.genWsdl) {
if (this.protocol != null) {
args.add("-wsdl:" + this.protocol);
} else {
args.add("-wsdl");
}
args.add("-r");
args.add(this.resourceDestDir.getAbsolutePath());
this.resourceDestDir.mkdirs();
}
args.add(sei);
getLog().debug("jaxws:wsgen args: " + args);
return args;
}
}
| JAX-WS-COMMONS-36: Pass -extension option to wsgen, when extension parameter is passed.
git-svn-id: 14f40df4fbe57db75b406caa6ec541de922253f0@807 3b447fe2-3421-0410-a1d7-a2ef89021db4
| src/main/java/org/codehaus/mojo/jaxws/AbstractWsGenMojo.java | JAX-WS-COMMONS-36: Pass -extension option to wsgen, when extension parameter is passed. | <ide><path>rc/main/java/org/codehaus/mojo/jaxws/AbstractWsGenMojo.java
<ide>
<ide> }
<ide>
<add> if ( this.extension ) {
<add> args.add( "-extension" );
<add> }
<add>
<ide> args.add(sei);
<ide>
<ide> getLog().debug("jaxws:wsgen args: " + args); |
|
Java | mit | 3c76dca5e998df209f57c5eb2e014a748142dc50 | 0 | JohanBrunet/Polytheque | package polytheque.model.DAO;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.mysql.jdbc.Statement;
import polytheque.model.pojos.Adherent;
import polytheque.model.pojos.Reservation;
public class ReservationDAO extends DAO {
/**
* mthode permettant de crer une rservation dans la base de donnes
* @param reservation
* @param idAdherent
* @param idJeu
* @param idJextension
* @return
*/
public boolean create(Reservation reservation, int idAdherent, int idJeu, int idJextension) {
try {
super.connect();
PreparedStatement psInsert = connection.prepareStatement("INSERT INTO "
+ "RESERVATION(date_reservation, id_adherent, id_jeu, id_extension) "
+ "VALUES (?, ?, ?, ?)");
psInsert.setDate(1, reservation.getDate()); //A voir pcq return type"date"
psInsert.setInt(2, idAdherent);
psInsert.setInt(3, idJeu);
psInsert.setInt(4, idJextension);
psInsert.executeUpdate();
ResultSet idResult = psInsert.getGeneratedKeys();
if (idResult != null && idResult.next()) {
reservation.setIdReservation(idResult.getInt(1));;
} else {
throw new SQLException();
}
super.disconnect();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
/**
* Creation de reservation sans extention
* @param reservation
* @param idAdherent
* @param idJeu
* @return
*/
public boolean create2(Reservation reservation, int idAdherent, int idJeu) {
try {
super.connect();
PreparedStatement psInsert = connection.prepareStatement("INSERT INTO "
+ "RESERVATION(date_reservation, id_adherent, id_jeu ) "
+ "VALUES (?, ?, ? )",Statement.RETURN_GENERATED_KEYS);
psInsert.setDate(1, reservation.getDate()); //A voir pcq return type"date"
psInsert.setInt(2, idAdherent);
psInsert.setInt(3, idJeu);
psInsert.executeUpdate();
ResultSet idResult = psInsert.getGeneratedKeys();
;
if (idResult != null && idResult.next()) {
reservation.setIdReservation(idResult.getInt(1));;
} else {
throw new SQLException();
}
super.disconnect();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
/**
* Creation de reservation sans jeu
* @param reservation
* @param idAdherent
* @param idExtention
* @return
*/
public boolean create3(Reservation reservation, int idAdherent, int idExtention) {
try {
super.connect();
PreparedStatement psInsert = connection.prepareStatement("INSERT INTO "
+ "RESERVATION(date_reservation, id_adherent, id_extension) "
+ "VALUES (?, ?, ?)",Statement.RETURN_GENERATED_KEYS);
psInsert.setDate(1, reservation.getDate()); //A voir pcq return type"date"
psInsert.setInt(2, idAdherent);
psInsert.setInt(3, idExtention);
psInsert.executeUpdate();
ResultSet idResult = psInsert.getGeneratedKeys();
if (idResult != null && idResult.next()) {
reservation.setIdReservation(idResult.getInt(1));;
} else {
throw new SQLException();
}
super.disconnect();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
/**
* suppression d'une rservation dans la base de donnes par son id
* @param id
* @return
*/
public boolean delete(int id) {
try {
super.connect();
PreparedStatement psDelete = connection.prepareStatement("DELETE * FROM RESERVATION WHERE id_reservation = ?");
psDelete.setInt(1, id);
psDelete.execute();
psDelete.closeOnCompletion();
super.disconnect();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
/**
*
* @param reservation
* @param idAdherent
* @param idJeu
* @param idJextension
* @param idReservation
* @return
*/
public boolean update(Reservation reservation, int idAdherent, int idJeu, int idJextension, int idReservation) {
try {
super.connect();
PreparedStatement psUpdate = connection.prepareStatement("UPDATE RESERVATION "
+ "SET date_reservation = ?, id_adherent = ?, id_jeu = ?, id_extension = ? "
+ " WHERE id_reservation = ?");
psUpdate.setDate(1, reservation.getDate());
psUpdate.setInt(2, idAdherent);
psUpdate.setInt(3, idJeu);
psUpdate.setInt(4, idJextension);
psUpdate.setInt(5, idReservation);
psUpdate.executeUpdate();
psUpdate.closeOnCompletion();
super.disconnect();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
/**
* permet de rcuprer une reservation depuis la base de donnes partir d'un adherent et de la date
* @param adherent
* @param date
* @return
*/
public Reservation retreive(Adherent adherent, Date date) {
try {
super.connect();
PreparedStatement psSelect = connection.prepareStatement("SELECT * FROM RESERVATION "
+ "WHERE id_adherent = (SELECT id_adherent from adherent where pseudo = ? "
+ "AND date_reservation = ?");
psSelect.setString(1, adherent.getPseudo());
psSelect.setDate(2, date);
psSelect.execute();
psSelect.closeOnCompletion();
ResultSet resSet = psSelect.getResultSet();
Reservation reservation = null;
if (resSet.next()) { // On se place sur le 1er résultat
reservation = new Reservation(resSet.getInt("id_reservation"), resSet.getDate("date_reservation"), resSet.getInt("id_adherent"));
}
super.disconnect();
return reservation;
} catch(SQLException e) {
e.printStackTrace();
return null;
}
}
/**
* Methode de recuperation des reservations
* @return La liste de toutes les reservations
*/
public ArrayList<Reservation> getAll() {
ArrayList<Reservation> toutesLesReservations = new ArrayList<>();
try {
super.connect();
PreparedStatement psSelect = connection.prepareStatement("SELECT * FROM RESERVATION");
psSelect.execute();
psSelect.closeOnCompletion();
ResultSet resSet = psSelect.getResultSet();
if (resSet.next()) {
//while (resSet.next()) { // On se place sur le 1er résultat
toutesLesReservations.add(new Reservation(resSet.getInt("id_adherent"), resSet.getInt("id_jeu"), resSet.getInt("id_extension"), resSet.getDate("date_reservation")));
//}
}
super.disconnect();
} catch(SQLException e) {
e.printStackTrace();
}
return toutesLesReservations;
}
/**
* permet de rcuprer toutes les reservations d'un adherent en particulier
* @param pseudo
* @return
*/
public ArrayList<Reservation> searchByPseudo(String pseudo)
{
ArrayList<Reservation> reserv = new ArrayList<>();
try {
super.connect();
PreparedStatement psSelect = connection.prepareStatement("SELECT * FROM RESERVATION "
+ "WHERE id_adherent = (SELECT id_adherent FROM ADHERENT WHERE pseudo = ?)");
psSelect.setString(1, pseudo);
psSelect.execute();
psSelect.closeOnCompletion();
ResultSet resSet = psSelect.getResultSet();
if (resSet.next()) { // On se place sur le 1er résultat
while (resSet.next()) {
reserv.add(new Reservation(resSet.getInt("id_reservation"), resSet.getInt("id_adherent"), resSet.getInt("id_jeu"), resSet.getInt("id_extension"), resSet.getDate("date_reservation")));
}
}
super.disconnect();
} catch(SQLException e) {
e.printStackTrace();
}
return reserv;
}
public Reservation getById(int id) {
// TODO Auto-generated method stub
return null;
}
}
| Polytheque/src/polytheque/model/DAO/ReservationDAO.java | package polytheque.model.DAO;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.mysql.jdbc.Statement;
import polytheque.model.pojos.Adherent;
import polytheque.model.pojos.Reservation;
public class ReservationDAO extends DAO {
public boolean create(Reservation reservation, int idAdherent, int idJeu, int idJextension) {
try {
super.connect();
PreparedStatement psInsert = connection.prepareStatement("INSERT INTO "
+ "RESERVATION(date_reservation, id_adherent, id_jeu, id_extension) "
+ "VALUES (?, ?, ?, ?)");
psInsert.setDate(1, reservation.getDate()); //A voir pcq return type"date"
psInsert.setInt(2, idAdherent);
psInsert.setInt(3, idJeu);
psInsert.setInt(4, idJextension);
psInsert.executeUpdate();
ResultSet idResult = psInsert.getGeneratedKeys();
if (idResult != null && idResult.next()) {
reservation.setIdReservation(idResult.getInt(1));;
} else {
throw new SQLException();
}
super.disconnect();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
/**
* Creation de reservation sans extention
* @param reservation
* @param idAdherent
* @param idJeu
* @return
*/
public boolean create2(Reservation reservation, int idAdherent, int idJeu) {
try {
super.connect();
PreparedStatement psInsert = connection.prepareStatement("INSERT INTO "
+ "RESERVATION(date_reservation, id_adherent, id_jeu ) "
+ "VALUES (?, ?, ? )",Statement.RETURN_GENERATED_KEYS);
psInsert.setDate(1, reservation.getDate()); //A voir pcq return type"date"
psInsert.setInt(2, idAdherent);
psInsert.setInt(3, idJeu);
psInsert.executeUpdate();
ResultSet idResult = psInsert.getGeneratedKeys();
;
if (idResult != null && idResult.next()) {
reservation.setIdReservation(idResult.getInt(1));;
} else {
throw new SQLException();
}
super.disconnect();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean create3(Reservation reservation, int idAdherent, int idExtention) {
try {
super.connect();
PreparedStatement psInsert = connection.prepareStatement("INSERT INTO "
+ "RESERVATION(date_reservation, id_adherent, id_extension) "
+ "VALUES (?, ?, ?)",Statement.RETURN_GENERATED_KEYS);
psInsert.setDate(1, reservation.getDate()); //A voir pcq return type"date"
psInsert.setInt(2, idAdherent);
psInsert.setInt(3, idExtention);
psInsert.executeUpdate();
ResultSet idResult = psInsert.getGeneratedKeys();
if (idResult != null && idResult.next()) {
reservation.setIdReservation(idResult.getInt(1));;
} else {
throw new SQLException();
}
super.disconnect();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean delete(int id) {
try {
super.connect();
PreparedStatement psDelete = connection.prepareStatement("DELETE * FROM RESERVATION WHERE id_reservation = ?");
psDelete.setInt(1, id);
psDelete.execute();
psDelete.closeOnCompletion();
super.disconnect();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean update(Reservation reservation, int idAdherent, int idJeu, int idJextension, int idReservation) {
try {
super.connect();
PreparedStatement psUpdate = connection.prepareStatement("UPDATE RESERVATION "
+ "SET date_reservation = ?, id_adherent = ?, id_jeu = ?, id_extension = ? "
+ " WHERE id_reservation = ?");
psUpdate.setDate(1, reservation.getDate());
psUpdate.setInt(2, idAdherent);
psUpdate.setInt(3, idJeu);
psUpdate.setInt(4, idJextension);
psUpdate.setInt(5, idReservation);
psUpdate.executeUpdate();
psUpdate.closeOnCompletion();
super.disconnect();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public Reservation retreive(Adherent adherent, Date date) {
try {
super.connect();
PreparedStatement psSelect = connection.prepareStatement("SELECT * FROM RESERVATION "
+ "WHERE id_adherent = (SELECT id_adherent from adherent where pseudo = ? "
+ "AND date_reservation = ?");
psSelect.setString(1, adherent.getPseudo());
psSelect.setDate(2, date);
psSelect.execute();
psSelect.closeOnCompletion();
ResultSet resSet = psSelect.getResultSet();
Reservation reservation = null;
if (resSet.next()) { // On se place sur le 1er résultat
reservation = new Reservation(resSet.getInt("id_reservation"), resSet.getDate("date_reservation"), resSet.getInt("id_adherent"));
}
super.disconnect();
return reservation;
} catch(SQLException e) {
e.printStackTrace();
return null;
}
}
/**
* Methode de recuperation des reservations
* @return La liste de toutes les reservations
*/
public ArrayList<Reservation> getAll() {
ArrayList<Reservation> toutesLesReservations = new ArrayList<>();
try {
super.connect();
PreparedStatement psSelect = connection.prepareStatement("SELECT * FROM RESERVATION");
psSelect.execute();
psSelect.closeOnCompletion();
ResultSet resSet = psSelect.getResultSet();
if (resSet.next()) {
//while (resSet.next()) { // On se place sur le 1er résultat
toutesLesReservations.add(new Reservation(resSet.getInt("id_adherent"), resSet.getInt("id_jeu"), resSet.getInt("id_extension"), resSet.getDate("date_reservation")));
//}
}
super.disconnect();
} catch(SQLException e) {
e.printStackTrace();
}
return toutesLesReservations;
}
public ArrayList<Reservation> searchByPseudo(String pseudo)
{
ArrayList<Reservation> reserv = new ArrayList<>();
try {
super.connect();
PreparedStatement psSelect = connection.prepareStatement("SELECT * FROM RESERVATION "
+ "WHERE id_adherent = (SELECT id_adherent FROM ADHERENT WHERE pseudo = ?)");
psSelect.setString(1, pseudo);
psSelect.execute();
psSelect.closeOnCompletion();
ResultSet resSet = psSelect.getResultSet();
if (resSet.next()) { // On se place sur le 1er résultat
while (resSet.next()) {
reserv.add(new Reservation(resSet.getInt("id_reservation"), resSet.getInt("id_adherent"), resSet.getInt("id_jeu"), resSet.getInt("id_extension"), resSet.getDate("date_reservation")));
}
}
super.disconnect();
} catch(SQLException e) {
e.printStackTrace();
}
return reserv;
}
public Reservation getById(int id) {
// TODO Auto-generated method stub
return null;
}
}
| commentaires de reservationDAO | Polytheque/src/polytheque/model/DAO/ReservationDAO.java | commentaires de reservationDAO | <ide><path>olytheque/src/polytheque/model/DAO/ReservationDAO.java
<ide>
<ide> public class ReservationDAO extends DAO {
<ide>
<del>
<add> /**
<add> * mthode permettant de crer une rservation dans la base de donnes
<add> * @param reservation
<add> * @param idAdherent
<add> * @param idJeu
<add> * @param idJextension
<add> * @return
<add> */
<ide> public boolean create(Reservation reservation, int idAdherent, int idJeu, int idJextension) {
<ide> try {
<ide> super.connect();
<ide> return false;
<ide> }
<ide> }
<del>
<add> /**
<add> * Creation de reservation sans jeu
<add> * @param reservation
<add> * @param idAdherent
<add> * @param idExtention
<add> * @return
<add> */
<ide> public boolean create3(Reservation reservation, int idAdherent, int idExtention) {
<ide> try {
<ide> super.connect();
<ide> }
<ide> }
<ide>
<del>
<add> /**
<add> * suppression d'une rservation dans la base de donnes par son id
<add> * @param id
<add> * @return
<add> */
<ide> public boolean delete(int id) {
<ide> try {
<ide> super.connect();
<ide> }
<ide> }
<ide>
<del>
<add> /**
<add> *
<add> * @param reservation
<add> * @param idAdherent
<add> * @param idJeu
<add> * @param idJextension
<add> * @param idReservation
<add> * @return
<add> */
<ide> public boolean update(Reservation reservation, int idAdherent, int idJeu, int idJextension, int idReservation) {
<ide> try {
<ide>
<ide>
<ide> }
<ide>
<del>
<add> /**
<add> * permet de rcuprer une reservation depuis la base de donnes partir d'un adherent et de la date
<add> * @param adherent
<add> * @param date
<add> * @return
<add> */
<ide> public Reservation retreive(Adherent adherent, Date date) {
<ide> try {
<ide> super.connect();
<ide> return toutesLesReservations;
<ide> }
<ide>
<add> /**
<add> * permet de rcuprer toutes les reservations d'un adherent en particulier
<add> * @param pseudo
<add> * @return
<add> */
<ide> public ArrayList<Reservation> searchByPseudo(String pseudo)
<ide> {
<ide> ArrayList<Reservation> reserv = new ArrayList<>(); |
|
Java | mit | 674d0efa575f3850123a9e449166919a11b81324 | 0 | ONSdigital/tredegar,ONSdigital/babbage,ONSdigital/tredegar,ONSdigital/babbage,ONSdigital/tredegar,ONSdigital/babbage,ONSdigital/babbage,ONSdigital/tredegar | package com.github.onsdigital.api.data;
import com.github.davidcarboni.ResourceUtils;
import com.github.davidcarboni.restolino.framework.Endpoint;
import com.github.onsdigital.configuration.Configuration;
import com.github.onsdigital.data.DataService;
import com.github.onsdigital.util.HostHelper;
import com.github.onsdigital.util.Validator;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.http.HttpStatus;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.core.Context;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import static com.mashape.unirest.http.Unirest.get;
@Endpoint
public class Data {
static boolean validated;
@GET
public Map<String, String> getData(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
// Ensures ResourceUtils gets the right classloader when running
// reloadable in development:
ResourceUtils.classLoaderClass = Data.class;
// Validate all Json so that we get a warning if
// there's an issue with a file that's been edited.
if (!validated) {
Validator.validate();
validated = true;
}
// Add a five-minute cache time to static files to reduce round-trips to
// the server and increase performance whilst still allowing the system
// to be updated quite promptly if necessary:
if (!HostHelper.isLocalhost(request)) {
response.addHeader("cache-control", "public, max-age=300");
}
String collection = "";
String authenticationToken = "";
final String authenticationHeader = "X-Florence-Token";
if (request.getCookies() != null) {
for (Cookie cookie : request.getCookies()) {
if (cookie.getName().equals("collection"))
collection = cookie.getValue();
if (cookie.getName().equals("access_token"))
authenticationToken = cookie.getValue();
}
}
InputStream data;
if (StringUtils.isEmpty(collection))
{
data = DataService.getDataStream(request.getRequestURI());
}
else {
URI uri = URI.create(request.getRequestURI());
String uriPath = DataService.cleanPath(uri);
if (uriPath.length() > 0)
{
uriPath += "/";
}
uriPath += "data.json";
try {
String url = Configuration.getZebedeeUrl() + "/content/" + collection;
System.out.println("Calling zebedee: " + url + "for path " + uriPath + " with token: " + authenticationToken);
String dataString = get(Configuration.getZebedeeUrl() + "/content/" + collection)
.header(authenticationHeader, authenticationToken)
.queryString("uri", uriPath).asString().getBody();
data = IOUtils.toInputStream(dataString);
} catch (UnirestException e) {
// Look for a data file:
data = DataService.getDataStream(request.getRequestURI());
}
}
// Output directly to the response
// (rather than deserialise and re-serialise)
response.setCharacterEncoding("UTF8");
response.setContentType("application/json");
if (data != null) {
try (InputStream input = data) {
IOUtils.copy(input, response.getOutputStream());
}
return null;
} else {
response.setStatus(HttpStatus.NOT_FOUND_404);
Map<String, String> error404 = new HashMap<>();
error404.put("message", "These are not the data you are looking for.");
error404.put("status", String.valueOf(HttpStatus.NOT_FOUND_404));
return error404;
}
}
}
| src/main/java/com/github/onsdigital/api/data/Data.java | package com.github.onsdigital.api.data;
import com.github.davidcarboni.ResourceUtils;
import com.github.davidcarboni.restolino.framework.Endpoint;
import com.github.onsdigital.configuration.Configuration;
import com.github.onsdigital.data.DataService;
import com.github.onsdigital.util.HostHelper;
import com.github.onsdigital.util.Validator;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.http.HttpStatus;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.core.Context;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import static com.mashape.unirest.http.Unirest.get;
@Endpoint
public class Data {
static boolean validated;
@GET
public Map<String, String> getData(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
// Ensures ResourceUtils gets the right classloader when running
// reloadable in development:
ResourceUtils.classLoaderClass = Data.class;
// Validate all Json so that we get a warning if
// there's an issue with a file that's been edited.
if (!validated) {
Validator.validate();
validated = true;
}
// Add a five-minute cache time to static files to reduce round-trips to
// the server and increase performance whilst still allowing the system
// to be updated quite promptly if necessary:
if (!HostHelper.isLocalhost(request)) {
response.addHeader("cache-control", "public, max-age=300");
}
String collection = "";
String authenticationToken = "";
final String authenticationHeader = "X-Florence-Token";
if (request.getCookies() != null) {
for (Cookie cookie : request.getCookies()) {
if (cookie.getName().equals("collection"))
collection = cookie.getValue();
if (cookie.getName().equals("access_token"))
authenticationToken = cookie.getValue();
}
}
InputStream data;
if (StringUtils.isEmpty(collection))
{
data = DataService.getDataStream(request.getRequestURI());
}
else {
URI uri = URI.create(request.getRequestURI());
String uriPath = DataService.cleanPath(uri);
if (uriPath.length() > 0)
{
uriPath += "/";
}
uriPath += "data.json";
try {
System.out.println("Calling zebedee: ");
String dataString = get(Configuration.getZebedeeUrl() + "/content/" + collection)
.header(authenticationHeader, authenticationToken)
.queryString("uri", uriPath).asString().getBody();
data = IOUtils.toInputStream(dataString);
} catch (UnirestException e) {
// Look for a data file:
data = DataService.getDataStream(request.getRequestURI());
}
}
// Output directly to the response
// (rather than deserialise and re-serialise)
response.setCharacterEncoding("UTF8");
response.setContentType("application/json");
if (data != null) {
try (InputStream input = data) {
IOUtils.copy(input, response.getOutputStream());
}
return null;
} else {
response.setStatus(HttpStatus.NOT_FOUND_404);
Map<String, String> error404 = new HashMap<>();
error404.put("message", "These are not the data you are looking for.");
error404.put("status", String.valueOf(HttpStatus.NOT_FOUND_404));
return error404;
}
}
}
| Added debug output.
| src/main/java/com/github/onsdigital/api/data/Data.java | Added debug output. | <ide><path>rc/main/java/com/github/onsdigital/api/data/Data.java
<ide> uriPath += "data.json";
<ide>
<ide> try {
<add> String url = Configuration.getZebedeeUrl() + "/content/" + collection;
<ide>
<del> System.out.println("Calling zebedee: ");
<add> System.out.println("Calling zebedee: " + url + "for path " + uriPath + " with token: " + authenticationToken);
<ide> String dataString = get(Configuration.getZebedeeUrl() + "/content/" + collection)
<ide> .header(authenticationHeader, authenticationToken)
<ide> .queryString("uri", uriPath).asString().getBody(); |
|
Java | apache-2.0 | 2502abf67db9078996b1059828259f68780fd521 | 0 | subutai-io/Subutai,subutai-io/base,subutai-io/base,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai,subutai-io/Subutai,subutai-io/Subutai,subutai-io/base | package org.safehaus.subutai.core.env.impl.tasks;
import java.util.concurrent.Semaphore;
import org.safehaus.subutai.common.environment.EnvironmentModificationException;
import org.safehaus.subutai.common.environment.EnvironmentNotFoundException;
import org.safehaus.subutai.common.environment.EnvironmentStatus;
import org.safehaus.subutai.common.peer.ContainerHost;
import org.safehaus.subutai.common.peer.PeerException;
import org.safehaus.subutai.core.env.impl.EnvironmentManagerImpl;
import org.safehaus.subutai.core.env.impl.entity.EnvironmentContainerImpl;
import org.safehaus.subutai.core.env.impl.entity.EnvironmentImpl;
import org.safehaus.subutai.core.env.impl.exception.ResultHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Environment Container host destroy task. This destroys, removes {@link org.safehaus.subutai.core.env.impl.entity
* .EnvironmentContainerImpl} from {@link org.safehaus.subutai.core.env.impl.entity.EnvironmentImpl} metadata. And
* consequently destroys container host on existing Peer#ResourceHost
*
* @see org.safehaus.subutai.core.env.impl.EnvironmentManagerImpl
* @see org.safehaus.subutai.core.env.impl.entity.EnvironmentImpl
* @see org.safehaus.subutai.common.peer.ContainerHost
* @see org.safehaus.subutai.core.env.impl.exception.ResultHolder
* @see java.lang.Runnable
*/
public class DestroyContainerTask implements Runnable
{
private static final Logger LOG = LoggerFactory.getLogger( DestroyContainerTask.class.getName() );
private final EnvironmentManagerImpl environmentManager;
private final EnvironmentImpl environment;
private final ContainerHost containerHost;
private final boolean forceMetadataRemoval;
private final ResultHolder<EnvironmentModificationException> resultHolder;
private final Semaphore semaphore;
public DestroyContainerTask( final EnvironmentManagerImpl environmentManager, final EnvironmentImpl environment,
final ContainerHost containerHost, final boolean forceMetadataRemoval,
final ResultHolder<EnvironmentModificationException> resultHolder )
{
this.environmentManager = environmentManager;
this.environment = environment;
this.containerHost = containerHost;
this.forceMetadataRemoval = forceMetadataRemoval;
this.resultHolder = resultHolder;
this.semaphore = new Semaphore( 0 );
}
@Override
public void run()
{
try
{
environment.setStatus( EnvironmentStatus.UNDER_MODIFICATION );
try
{
try
{
( ( EnvironmentContainerImpl ) containerHost ).destroy();
}
catch ( PeerException e )
{
boolean skipError = false;
if ( e.getCause() != null && e.getCause().getMessage().contains(
"org.safehaus.subutai.core.peer.api.HostNotFoundException" ) )
{
//skip error since host is not found
skipError = true;
}
if ( !skipError )
{
if ( forceMetadataRemoval )
{
resultHolder.setResult( new EnvironmentModificationException( e ) );
}
else
{
throw e;
}
}
}
environment.removeContainer( containerHost.getId() );
environmentManager.notifyOnContainerDestroyed( environment, containerHost.getId() );
}
catch ( PeerException e )
{
environment.setStatus( EnvironmentStatus.UNHEALTHY );
throw new EnvironmentModificationException( e );
}
if ( environment.getContainerHosts().isEmpty() )
{
try
{
environmentManager.removeEnvironment( environment.getId() );
}
catch ( EnvironmentNotFoundException e )
{
LOG.error( "Error removing environment", e );
}
}
else
{
environment.setStatus( EnvironmentStatus.HEALTHY );
}
}
catch ( EnvironmentModificationException e )
{
LOG.error( String.format( "Error destroying container %s", containerHost.getHostname() ), e );
resultHolder.setResult( e );
}
finally
{
semaphore.release();
}
}
public void waitCompletion() throws InterruptedException
{
semaphore.acquire();
}
}
| management/server/core/env-manager/env-manager-impl/src/main/java/org/safehaus/subutai/core/env/impl/tasks/DestroyContainerTask.java | package org.safehaus.subutai.core.env.impl.tasks;
import java.util.concurrent.Semaphore;
import org.safehaus.subutai.common.environment.EnvironmentModificationException;
import org.safehaus.subutai.common.environment.EnvironmentNotFoundException;
import org.safehaus.subutai.common.environment.EnvironmentStatus;
import org.safehaus.subutai.common.peer.ContainerHost;
import org.safehaus.subutai.common.peer.PeerException;
import org.safehaus.subutai.core.env.impl.EnvironmentManagerImpl;
import org.safehaus.subutai.core.env.impl.entity.EnvironmentContainerImpl;
import org.safehaus.subutai.core.env.impl.entity.EnvironmentImpl;
import org.safehaus.subutai.core.env.impl.exception.ResultHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Environment Container host destroy task. This destroys, removes {@link org.safehaus.subutai.core.env.impl.entity
* .EnvironmentContainerImpl} from {@link org.safehaus.subutai.core.env.impl.entity.EnvironmentImpl} metadata. And
* consequently destroys container host on existing Peer#ResourceHost
*
* @see org.safehaus.subutai.core.env.impl.EnvironmentManagerImpl
* @see org.safehaus.subutai.core.env.impl.entity.EnvironmentImpl
* @see org.safehaus.subutai.common.peer.ContainerHost
* @see org.safehaus.subutai.core.env.impl.exception.ResultHolder
* @see java.lang.Runnable
*/
public class DestroyContainerTask implements Runnable
{
private static final Logger LOG = LoggerFactory.getLogger( DestroyContainerTask.class.getName() );
private final EnvironmentManagerImpl environmentManager;
private final EnvironmentImpl environment;
private final ContainerHost containerHost;
private final boolean forceMetadataRemoval;
private final ResultHolder<EnvironmentModificationException> resultHolder;
private final Semaphore semaphore;
public DestroyContainerTask( final EnvironmentManagerImpl environmentManager, final EnvironmentImpl environment,
final ContainerHost containerHost, final boolean forceMetadataRemoval,
final ResultHolder<EnvironmentModificationException> resultHolder )
{
this.environmentManager = environmentManager;
this.environment = environment;
this.containerHost = containerHost;
this.forceMetadataRemoval = forceMetadataRemoval;
this.resultHolder = resultHolder;
this.semaphore = new Semaphore( 0 );
}
@Override
public void run()
{
try
{
environment.setStatus( EnvironmentStatus.UNDER_MODIFICATION );
try
{
try
{
( ( EnvironmentContainerImpl ) containerHost ).destroy();
}
catch ( PeerException e )
{
boolean skipError = false;
if ( e.getCause() != null && e.getCause().getMessage().contains(
"HTTPException: org.safehaus.subutai.core.peer.api.HostNotFoundException" ) )
{
//skip error since host is not found
skipError = true;
}
if ( !skipError )
{
if ( forceMetadataRemoval )
{
resultHolder.setResult( new EnvironmentModificationException( e ) );
}
else
{
throw e;
}
}
}
environment.removeContainer( containerHost.getId() );
environmentManager.notifyOnContainerDestroyed( environment, containerHost.getId() );
}
catch ( PeerException e )
{
environment.setStatus( EnvironmentStatus.UNHEALTHY );
throw new EnvironmentModificationException( e );
}
if ( environment.getContainerHosts().isEmpty() )
{
try
{
environmentManager.removeEnvironment( environment.getId() );
}
catch ( EnvironmentNotFoundException e )
{
LOG.error( "Error removing environment", e );
}
}
else
{
environment.setStatus( EnvironmentStatus.HEALTHY );
}
}
catch ( EnvironmentModificationException e )
{
LOG.error( String.format( "Error destroying container %s", containerHost.getHostname() ), e );
resultHolder.setResult( e );
}
finally
{
semaphore.release();
}
}
public void waitCompletion() throws InterruptedException
{
semaphore.acquire();
}
}
| Fix Environment Manager bugs
| management/server/core/env-manager/env-manager-impl/src/main/java/org/safehaus/subutai/core/env/impl/tasks/DestroyContainerTask.java | Fix Environment Manager bugs | <ide><path>anagement/server/core/env-manager/env-manager-impl/src/main/java/org/safehaus/subutai/core/env/impl/tasks/DestroyContainerTask.java
<ide> {
<ide> boolean skipError = false;
<ide> if ( e.getCause() != null && e.getCause().getMessage().contains(
<del> "HTTPException: org.safehaus.subutai.core.peer.api.HostNotFoundException" ) )
<add> "org.safehaus.subutai.core.peer.api.HostNotFoundException" ) )
<ide> {
<ide> //skip error since host is not found
<ide> skipError = true; |
|
Java | apache-2.0 | 27232b0c0ed17817d387acf2204083e09a604aca | 0 | orcas-elite/Microservice-Fault-Injection,jgrunert/Microservice-Fault-Injection,jgrunert/Microservice-Fault-Injection,jgrunert/Microservice-Fault-Injection,orcas-elite/Microservice-Fault-Injection,jgrunert/Microservice-Fault-Injection,jgrunert/Microservice-Fault-Injection,orcas-elite/Microservice-Fault-Injection,jgrunert/Microservice-Fault-Injection |
import java.io.IOException;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.continuation.Continuation;
import org.eclipse.jetty.continuation.ContinuationListener;
import org.eclipse.jetty.continuation.ContinuationSupport;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
public class TestServerMain extends AbstractHandler {
private static int ResponseDelay = 0;
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
if (ResponseDelay > 0) {
Continuation continuation = ContinuationSupport.getContinuation(request);
if (continuation.isInitial()) {
continuation.setTimeout(ResponseDelay);
continuation.suspend();
} else {
sendResponse(baseRequest, request, response);
}
continuation.addContinuationListener(new ContinuationListener() {
public void onTimeout(Continuation continuation) {
continuation.resume();
}
public void onComplete(Continuation continuation) {
}
});
} else {
System.out.println("x " + request);
sendResponse(baseRequest, request, response);
}
}
private void sendResponse(Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("<h1>Hello Test" + request.getRequestURI() + "</h1>");
}
public static void main(String[] args) {
if (args.length < 1) {
showHelp();
return;
}
if(args.length >= 2) {
ResponseDelay = Integer.parseInt(args[1]);
}
System.out.println("Starting server. Delay: " + ResponseDelay);
Server server = new Server(Integer.parseInt(args[0]));
server.setHandler(new TestServerMain());
try {
server.start();
System.out.println("Started TestServer");
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void showHelp() {
System.out.println("Usage: [server-port]");
}
} | JInjectProxy/test-server/src/main/java/TestServerMain.java |
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
public class TestServerMain extends AbstractHandler {
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("<h1>Hello Test" + request.getRequestURI() + "</h1>");
}
public static void main(String[] args) {
if (args.length < 1) {
showHelp();
return;
}
System.out.println("Starting server");
Server server = new Server(Integer.parseInt(args[0]));
server.setHandler(new TestServerMain());
try {
server.start();
System.out.println("Started TestServer");
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void showHelp() {
System.out.println("Usage: [server-port]");
}
} | Test server with async response delay - for testing n-lane bridge | JInjectProxy/test-server/src/main/java/TestServerMain.java | Test server with async response delay - for testing n-lane bridge | <ide><path>InjectProxy/test-server/src/main/java/TestServerMain.java
<ide>
<ide> import java.io.IOException;
<ide>
<add>import javax.servlet.AsyncContext;
<ide> import javax.servlet.ServletException;
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import javax.servlet.http.HttpServletResponse;
<ide>
<add>import org.eclipse.jetty.continuation.Continuation;
<add>import org.eclipse.jetty.continuation.ContinuationListener;
<add>import org.eclipse.jetty.continuation.ContinuationSupport;
<ide> import org.eclipse.jetty.server.Request;
<ide> import org.eclipse.jetty.server.Server;
<ide> import org.eclipse.jetty.server.handler.AbstractHandler;
<ide>
<ide>
<ide> public class TestServerMain extends AbstractHandler {
<add>
<add> private static int ResponseDelay = 0;
<add>
<add>
<ide> public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
<del> throws IOException, ServletException {
<add> throws IOException, ServletException {
<add> if (ResponseDelay > 0) {
<add> Continuation continuation = ContinuationSupport.getContinuation(request);
<add>
<add> if (continuation.isInitial()) {
<add> continuation.setTimeout(ResponseDelay);
<add> continuation.suspend();
<add> } else {
<add> sendResponse(baseRequest, request, response);
<add> }
<add>
<add> continuation.addContinuationListener(new ContinuationListener() {
<add> public void onTimeout(Continuation continuation) {
<add> continuation.resume();
<add> }
<add>
<add> public void onComplete(Continuation continuation) {
<add> }
<add> });
<add> } else {
<add> System.out.println("x " + request);
<add> sendResponse(baseRequest, request, response);
<add> }
<add> }
<add>
<add> private void sendResponse(Request baseRequest, HttpServletRequest request, HttpServletResponse response)
<add> throws IOException {
<ide> response.setContentType("text/html;charset=utf-8");
<ide> response.setStatus(HttpServletResponse.SC_OK);
<ide> baseRequest.setHandled(true);
<ide> showHelp();
<ide> return;
<ide> }
<add> if(args.length >= 2) {
<add> ResponseDelay = Integer.parseInt(args[1]);
<add> }
<ide>
<del> System.out.println("Starting server");
<add> System.out.println("Starting server. Delay: " + ResponseDelay);
<ide>
<ide> Server server = new Server(Integer.parseInt(args[0]));
<ide> server.setHandler(new TestServerMain()); |
|
JavaScript | bsd-2-clause | 759944e7fd93fe630bfc2cd89fd574dc16470eb8 | 0 | Kronos-Integration/kronos-step | /* jslint node: true, esnext: true */
"use strict";
const endpoint = require('kronos-endpoint'),
llm = require('loglevel-mixin'),
stm = require('statetransition-mixin'),
merge = require('merge-deep');
const actions = stm.prepareActions({
start: {
stopped: {
target: "running",
during: "starting",
timeout: 5000
}
},
stop: {
running: {
target: "stopped",
during: "stopping",
timeout: 5000
},
starting: {
target: "stopped",
during: "stopping",
timeout: 5000
}
},
remove: {
stopped: {
target: "removed"
}
}
});
// Steps plain attributes without special handling
// may be extended by some properties like writable,...
const ATTRIBUTES = ['description'];
const BaseStep = {
"name": "kronos-step",
"description": "This step is the base class for step implementations",
/**
* Creates the properties for a given object
* @param {Object} manager The kronos service manager
* @param {String} (mandatory) name The Name of the step
* @param {Object} (optional) stepDefinition The step definition
*
*/
prepareProperties(manager, name, stepConfiguration) {
let endpoints = {};
// TODO ther is no better way ?
const type = stepConfiguration.type ? stepConfiguration.type : this.name;
const props = {
name: {
value: name
},
type: {
value: type
},
endpoints: {
value: endpoints
},
manager: {
value: manager
},
/**
* @return {Boolean} if step is in a running state
*/
isRunning: {
get: function () {
return this.state === 'running' || this.state === 'starting';
}
}
};
ATTRIBUTES.forEach(a => {
if (stepConfiguration[a] !== undefined) {
props[a] = {
value: stepConfiguration[a]
};
}
});
return props;
},
/**
* Called to initialize step
* Please note 'this' is not jet present
*/
initialize(manager, name, stepConfiguration, props) {},
/**
* Called when step instance properties are present.
*
*/
finalize(manager, stepConfiguration) {},
/**
* This method could be overwritten by a derived object to setup default endpoints.
* This method may be overwritten by derived classes.
* This will be called by the initialize method
* @param {Object} stepConfiguration The default step configuration
* @api protected
*/
createPredefinedEndpoints(stepConfiguration) {
if (this.endpoints.log) return;
const logEndpoint = new endpoint.SendEndpointDefault("log", this);
if (this.manager.services && this.manager.services.logger) {
logEndpoint.connected = this.manager.services.logger.endpoints.log;
}
this.addEndpoint(logEndpoint);
},
/**
* This function mixes the endpoint definitions of a step.
* So that extensions comming from the flow will be mixed into
* the definition from the step (The definition from the prototype).
* Only the 'endpoints' part will be extended
*
* @param def The step definition from the flow or step itslef.
* @return definition The new extended step definition
*/
inheritEndpoints(def) {
const prototype = Object.getPrototypeOf(this);
if (prototype && prototype.endpoints) {
if (def && def.endpoints) {
// before we can merge endpoints of type string needs to be converted
for (const endpointName in def.endpoints) {
const endpointDefinition = def.endpoints[endpointName];
if (typeof endpointDefinition === 'string') {
def.endpoints[endpointName] = {
"target": endpointDefinition
};
}
}
// need to mix the definition
def.endpoints = merge({}, prototype.endpoints, def.endpoints);
} else {
if (!def) {
def = {};
}
// just take the prototype definition
def.endpoints = prototype.endpoints;
}
}
return def;
},
/**
* Creates the endpoint objects defined as a combination from
* implementation and definition
* @param {Object} def The step configuration
* @api protected
*/
createEndpoints(def) {
if (def && def.endpoints) {
Object.keys(def.endpoints).forEach(name =>
this.createEndpoint(name, def.endpoints[name]));
}
},
createEndpoint(name, def) {
let ep;
if (def.in) ep = new endpoint.ReceiveEndpoint(name, this);
if (def.out) ep = new endpoint.SendEndpoint(name, this);
this.addEndpoint(ep);
if (def.interceptors) {
ep.interceptors = def.interceptors.map(icDef => this.manager.createInterceptorInstanceFromConfig(icDef, ep));
}
},
/**
* @param {Endpoint} ep
*/
addEndpoint(ep) {
this.endpoints[ep.name] = ep;
},
/**
* removes a endpoint
* @param {string} name
*/
removeEndpoint(name) {
delete this.endpoints[name];
},
/**
* Sends a 'stepStateChanged' event to the manager.
* arguments are:
* step,oldState,newState
* @param {String} oldState
* @param {String} newState
*/
stateChanged(oldState, newState) {
this.trace(level => ({
"message": "state changed",
"old": oldState,
"new": newState
}));
this.manager.emit('stepStateChanged', this, oldState, newState);
},
/**
* Returns the string representation of this step
* @return {String} human readable name
*/
toString() {
return this.name;
},
/**
* Deliver json representation
* @param {Objects} options
* with the following flags:
* includeRuntimeInfo - include runtime informtion like state
* includeName - name of the step
* includeDefaults - include all properties also the inherited and not overwittern ones
* @return json representation
*/
toJSONWithOptions(options) {
const json = {
type: this.type,
endpoints: {}
};
if (options.includeName) {
json.name = this.name;
}
if (options.includeRuntimeInfo) {
json.state = this.state;
}
for (const endpointName in this.endpoints) {
const ep = this.endpoints[endpointName];
if (ep.isDefault) {
if (options.includeDefaults) {
json.endpoints[endpointName] = ep.toJSON();
}
} else {
json.endpoints[endpointName] = ep.toJSON();
}
}
ATTRIBUTES.forEach(a => {
json[a] = this[a];
});
return json;
},
toJSON() {
return this.toJSONWithOptions({
includeRuntimeInfo: false,
includeDefaults: false,
includeName: false
});
},
/**
* @return {Step} newly created step
*/
createInstance(stepDefinition, manager) {
if (!manager) {
throw new Error(`No Manager given in 'createInstance' for step '${stepDefinition.name}'`);
}
const props = this.prepareProperties(manager, stepDefinition.name, stepDefinition);
this.initialize(manager, stepDefinition.name, stepDefinition, props);
const newInstance = Object.create(this, props);
stm.defineStateTransitionProperties(newInstance, actions, "stopped");
// get the default loglevel for this step
let logLevel = llm.defaultLogLevels[stepDefinition.logLevel] || llm.defaultLogLevels.info;
// create the properties to store the loglevel
llm.defineLogLevelProperties(newInstance, llm.defaultLogLevels, logLevel);
// mix the endpoints from the prototype with the new definition
stepDefinition = newInstance.inheritEndpoints(stepDefinition);
newInstance.createEndpoints(stepDefinition);
newInstance.createPredefinedEndpoints(stepDefinition);
newInstance.finalize(stepDefinition);
return newInstance;
},
log(level, arg) {
const logevent = llm.makeLogEvent(level, arg, {
"step-type": this.type,
"step-name": this.name
});
if (typeof arg === 'object') {
if (arg instanceof Error) {
// The 'arg' is an Error Object
const stack = arg.stack;
if (stack.getLineNumber) {
logevent.line = stack.getLineNumber();
}
if (stack.getFileName) {
logevent._file_name = stack.getFileName();
}
logevent._error_name = arg.name;
logevent.short_message = arg.message;
} else {
// The 'arg' is a normal object. Copy all the properties
if (arg.short_message !== undefined) {
logevent.short_message = arg.short_message;
delete(arg.short_message);
}
if (arg.full_message !== undefined) {
logevent.full_message = arg.full_message;
delete(arg.full_message);
}
}
}
if (this.endpoints.log && this.endpoints.log.isConnected) {
this.endpoints.log.receive(logevent);
} else {
console.log(logevent);
}
}
};
// define the logger methods
llm.defineLoggerMethods(BaseStep, llm.defaultLogLevels);
stm.defineActionMethods(BaseStep, actions, true);
module.exports.BaseStep = BaseStep;
| lib/step.js | /* jslint node: true, esnext: true */
"use strict";
const endpoint = require('kronos-endpoint'),
llm = require('loglevel-mixin'),
stm = require('statetransition-mixin'),
merge = require('merge-deep');
const actions = stm.prepareActions({
start: {
stopped: {
target: "running",
during: "starting",
timeout: 5000
}
},
stop: {
running: {
target: "stopped",
during: "stopping",
timeout: 5000
},
starting: {
target: "stopped",
during: "stopping",
timeout: 5000
}
},
remove: {
stopped: {
target: "removed"
}
}
});
// Steps plain attributes without special handling
// may be extended by some properties like writable,...
const ATTRIBUTES = ['description'];
const BaseStep = {
"name": "kronos-step",
"description": "This step is the base class for step implementations",
/**
* Creates the properties for a given object
* @param {Object} manager The kronos service manager
* @param {String} (mandatory) name The Name of the step
* @param {Object} (optional) stepDefinition The step definition
*
*/
prepareProperties(manager, name, stepConfiguration) {
let endpoints = {};
// TODO ther is no better way ?
const type = stepConfiguration.type ? stepConfiguration.type : this.name;
const props = {
name: {
value: name
},
type: {
value: type
},
endpoints: {
value: endpoints
},
manager: {
value: manager
},
/**
* @return {Boolean} if step is in a running state
*/
isRunning: {
get: function () {
return this.state === 'running' || this.state === 'starting';
}
}
};
ATTRIBUTES.forEach(a => {
if (stepConfiguration[a] !== undefined) {
props[a] = {
value: stepConfiguration[a]
};
}
});
return props;
},
/**
* Called to initialize step
* Please note 'this' is not jet present
*/
initialize(manager, name, stepConfiguration, props) {},
/**
* Called when step instance properties are present.
*
*/
finalize(manager, stepConfiguration) {},
/**
* This method could be overwritten by a derived object to setup default endpoints.
* This method may be overwritten by derived classes.
* This will be called by the initialize method
* @param {Object} stepConfiguration The default step configuration
* @api protected
*/
createPredefinedEndpoints(stepConfiguration) {
if (this.endpoints.log) return;
const logEndpoint = new endpoint.SendEndpointDefault("log", this);
if (this.manager.services && this.manager.services.logger) {
logEndpoint.connected = this.manager.services.logger.endpoints.log;
}
this.addEndpoint(logEndpoint);
},
/**
* This function mixes the endpoint definitions of a step.
* So that extensions comming from the flow will be mixed into
* the definition from the step (The definition from the prototype).
* Only the 'endpoints' part will be extended
*
* @param def The step definition from the flow or step itslef.
* @return definition The new extended step definition
*/
inheritEndpoints(def) {
const prototype = Object.getPrototypeOf(this);
if (prototype && prototype.endpoints) {
if (def && def.endpoints) {
// before we can merge endpoints of type string needs to be converted
for (const endpointName in def.endpoints) {
const endpointDefinition = def.endpoints[endpointName];
if (typeof endpointDefinition === 'string') {
def.endpoints[endpointName] = {
"target": endpointDefinition
};
}
}
// need to mix the definition
def.endpoints = merge({}, prototype.endpoints, def.endpoints);
} else {
if (!def) {
def = {};
}
// just take the prototype definition
def.endpoints = prototype.endpoints;
}
}
return def;
},
/**
* Creates the endpoint objects defined as a combination from
* implementation and definition
* @param {Object} def The step configuration
* @api protected
*/
createEndpoints(def) {
if (def && def.endpoints) {
Object.keys(def.endpoints).forEach(name =>
this.createEndpoint(name, def.endpoints[name]));
}
},
createEndpoint(name, def) {
let ep;
if (def.in) ep = new endpoint.ReceiveEndpoint(name, this);
if (def.out) ep = new endpoint.SendEndpoint(name, this);
this.addEndpoint(ep);
if (def.interceptors) {
ep.interceptors = def.interceptors.map(icDef => this.manager.createInterceptorInstanceFromConfig(icDef, ep));
}
},
/**
* @param {Endpoint} ep
*/
addEndpoint(ep) {
this.endpoints[ep.name] = ep;
},
/**
* removes a endpoint
* @param {string} name
*/
removeEndpoint(name) {
delete this.endpoints[name];
},
/**
* Sends a 'stepStateChanged' event to the manager.
* arguments are:
* step,oldState,newState
* @param {String} oldState
* @param {String} newState
*/
stateChanged(oldState, newState) {
this.trace(level => ({
"message": "state changed",
"oldState": oldState,
"newState": newState
}));
this.manager.emit('stepStateChanged', this, oldState, newState);
},
/**
* Returns the string representation of this step
* @return {String} human readable name
*/
toString() {
return this.name;
},
/**
* Deliver json representation
* @param {Objects} options
* with the following flags:
* includeRuntimeInfo - include runtime informtion like state
* includeName - name of the step
* includeDefaults - include all properties also the inherited and not overwittern ones
* @return json representation
*/
toJSONWithOptions(options) {
const json = {
type: this.type,
endpoints: {}
};
if (options.includeName) {
json.name = this.name;
}
if (options.includeRuntimeInfo) {
json.state = this.state;
}
for (const endpointName in this.endpoints) {
const ep = this.endpoints[endpointName];
if (ep.isDefault) {
if (options.includeDefaults) {
json.endpoints[endpointName] = ep.toJSON();
}
} else {
json.endpoints[endpointName] = ep.toJSON();
}
}
ATTRIBUTES.forEach(a => {
json[a] = this[a];
});
return json;
},
toJSON() {
return this.toJSONWithOptions({
includeRuntimeInfo: false,
includeDefaults: false,
includeName: false
});
},
/**
* @return {Step} newly created step
*/
createInstance(stepDefinition, manager) {
if (!manager) {
throw new Error(`No Manager given in 'createInstance' for step '${stepDefinition.name}'`);
}
const props = this.prepareProperties(manager, stepDefinition.name, stepDefinition);
this.initialize(manager, stepDefinition.name, stepDefinition, props);
const newInstance = Object.create(this, props);
stm.defineStateTransitionProperties(newInstance, actions, "stopped");
// get the default loglevel for this step
let logLevel = llm.defaultLogLevels[stepDefinition.logLevel] || llm.defaultLogLevels.info;
// create the properties to store the loglevel
llm.defineLogLevelProperties(newInstance, llm.defaultLogLevels, logLevel);
// mix the endpoints from the prototype with the new definition
stepDefinition = newInstance.inheritEndpoints(stepDefinition);
newInstance.createEndpoints(stepDefinition);
newInstance.createPredefinedEndpoints(stepDefinition);
newInstance.finalize(stepDefinition);
return newInstance;
},
log(level, arg) {
const logevent = llm.makeLogEvent(level, arg, {
"step-type": this.type,
"step-name": this.name
});
if (typeof arg === 'object') {
if (arg instanceof Error) {
// The 'arg' is an Error Object
const stack = arg.stack;
if (stack.getLineNumber) {
logevent.line = stack.getLineNumber();
}
if (stack.getFileName) {
logevent._file_name = stack.getFileName();
}
logevent._error_name = arg.name;
logevent.short_message = arg.message;
} else {
// The 'arg' is a normal object. Copy all the properties
if (arg.short_message !== undefined) {
logevent.short_message = arg.short_message;
delete(arg.short_message);
}
if (arg.full_message !== undefined) {
logevent.full_message = arg.full_message;
delete(arg.full_message);
}
}
}
if (this.endpoints.log && this.endpoints.log.isConnected) {
this.endpoints.log.receive(logevent);
} else {
console.log(logevent);
}
}
};
// define the logger methods
llm.defineLoggerMethods(BaseStep, llm.defaultLogLevels);
stm.defineActionMethods(BaseStep, actions, true);
module.exports.BaseStep = BaseStep;
| refactor(log): rename trace attribute oldState/newState into old/new
| lib/step.js | refactor(log): rename trace attribute oldState/newState into old/new | <ide><path>ib/step.js
<ide> stateChanged(oldState, newState) {
<ide> this.trace(level => ({
<ide> "message": "state changed",
<del> "oldState": oldState,
<del> "newState": newState
<add> "old": oldState,
<add> "new": newState
<ide> }));
<ide> this.manager.emit('stepStateChanged', this, oldState, newState);
<ide> }, |
|
Java | mit | 090240fc51e2100f8b8f8e029bdc8f30aa9eada9 | 0 | Nunnery/MythicDrops | package net.nunnerycode.bukkit.mythicdrops.hooks;
import com.gmail.nossr50.events.skills.repair.McMMOPlayerRepairCheckEvent;
import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops;
import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier;
import net.nunnerycode.bukkit.mythicdrops.utils.TierUtil;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
public final class McMMOWrapper implements Listener {
private MythicDrops mythicDrops;
public McMMOWrapper(MythicDrops mythicDrops) {
this.mythicDrops = mythicDrops;
}
@EventHandler
public void onRepairItemCheckEvent(McMMOPlayerRepairCheckEvent event) {
Tier t = TierUtil.getTierFromItemStack(event.getRepairedObject());
if (t != null && mythicDrops.getRepairingSettings().isCancelMcMMORepair()) {
event.setCancelled(true);
}
}
}
| src/main/java/net/nunnerycode/bukkit/mythicdrops/hooks/McMMOWrapper.java | package net.nunnerycode.bukkit.mythicdrops.hooks;
import com.gmail.nossr50.events.skills.repair.McMMOPlayerRepairCheckEvent;
import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops;
import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier;
import net.nunnerycode.bukkit.mythicdrops.utils.TierUtil;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
public final class mcMMOWrapper implements Listener {
private MythicDrops mythicDrops;
public mcMMOWrapper(MythicDrops mythicDrops) {
this.mythicDrops = mythicDrops;
}
@EventHandler
public void onRepairItemCheckEvent(McMMOPlayerRepairCheckEvent event) {
Tier t = TierUtil.getTierFromItemStack(event.getRepairedObject());
if (t != null && mythicDrops.getRepairingSettings().isCancelMcMMORepair()) {
event.setCancelled(true);
}
}
}
| Update McMMOWrapper.java | src/main/java/net/nunnerycode/bukkit/mythicdrops/hooks/McMMOWrapper.java | Update McMMOWrapper.java | <ide><path>rc/main/java/net/nunnerycode/bukkit/mythicdrops/hooks/McMMOWrapper.java
<ide> import org.bukkit.event.EventHandler;
<ide> import org.bukkit.event.Listener;
<ide>
<del>public final class mcMMOWrapper implements Listener {
<add>public final class McMMOWrapper implements Listener {
<ide>
<ide> private MythicDrops mythicDrops;
<ide>
<del> public mcMMOWrapper(MythicDrops mythicDrops) {
<add> public McMMOWrapper(MythicDrops mythicDrops) {
<ide> this.mythicDrops = mythicDrops;
<ide> }
<ide> |
|
JavaScript | mit | ca8e7c19d6ab302c27df56f8f755ac22d741aa53 | 0 | cheton/cnc.js,cheton/piduino-grbl,cheton/cnc,cheton/cnc.js,cncjs/cncjs,cheton/piduino-grbl,cheton/piduino-grbl,cheton/cnc.js,cheton/cnc,cheton/cnc,cncjs/cncjs,cncjs/cncjs | /* eslint no-unused-vars: 0 */
import dns from 'dns';
import fs from 'fs';
import os from 'os';
import path from 'path';
import _ from 'lodash';
import bcrypt from 'bcrypt-nodejs';
import chalk from 'chalk';
import webappengine from 'webappengine';
import app from './app';
import cncengine from './services/cncengine';
import monitor from './services/monitor';
import log from './lib/log';
import { readConfigFileSync, writeConfigFileSync } from './lib/config-file';
import settings from './config/settings';
const createServer = (options, callback) => {
const {
port = 0,
host,
backlog,
configFile,
verbosity,
mount,
watchDirectory,
allowRemoteAccess = false
} = { ...options };
const routes = [];
const cncrc = path.resolve(configFile || settings.cncrc);
const config = readConfigFileSync(cncrc);
// cncrc
settings.cncrc = cncrc;
{ // secret
if (!config.secret) {
// generate a secret key
config.secret = bcrypt.genSaltSync(); // TODO
// update changes
writeConfigFileSync(cncrc, config);
}
settings.secret = config.secret || settings.secret;
}
{ // routes
if (mount) {
routes.push({
type: 'static',
route: mount.url,
directory: mount.path
});
}
routes.push({
type: 'server',
route: '/',
server: () => app()
});
}
{ // verbosity
// https://github.com/winstonjs/winston#logging-levels
if (verbosity === 1) {
_.set(settings, 'verbosity', verbosity);
log.logger.level = 'verbose';
}
if (verbosity === 2) {
_.set(settings, 'verbosity', verbosity);
log.logger.level = 'debug';
}
if (verbosity === 3) {
_.set(settings, 'verbosity', verbosity);
log.logger.level = 'silly';
}
}
{ // watchDirectory
config.watchDirectory = _.get(config, 'watchDirectory', watchDirectory);
if (config.watchDirectory) {
if (fs.existsSync(config.watchDirectory)) {
log.info(`Start watching ${chalk.yellow(JSON.stringify(config.watchDirectory))} for file changes.`);
// Start monitor service
monitor.start({ watchDirectory: config.watchDirectory });
} else {
log.error(`The directory ${chalk.yellow(JSON.stringify(config.watchDirectory))} does not exist.`);
}
}
}
{ // allowRemoteAccess
config.allowRemoteAccess = _.get(config, 'allowRemoteAccess', allowRemoteAccess);
if (config.allowRemoteAccess) {
if (_.size(config.users) === 0) {
log.warning('You\'ve enabled remote access to the server. It\'s recommended to create an user account to protect against malicious attacks.');
}
_.set(settings, 'allowRemoteAccess', config.allowRemoteAccess);
}
}
webappengine({ port, host, backlog, routes })
.on('ready', (server) => {
// Start cncengine service
cncengine.start({ server: server });
const address = server.address().address;
const port = server.address().port;
if (address !== '0.0.0.0') {
log.info('Started the server at ' + chalk.cyan(`http://${address}:${port}`));
return;
}
dns.lookup(os.hostname(), { family: 4, all: true }, (err, addresses) => {
if (err) {
log.error('Can\'t resolve host name:', err);
return;
}
addresses.forEach(({ address, family }) => {
log.info('Started the server at ' + chalk.cyan(`http://${address}:${port}`));
});
});
})
.on('error', (err) => {
log.error(err);
});
};
export {
createServer
};
| src/app/index.js | /* eslint no-unused-vars: 0 */
import dns from 'dns';
import fs from 'fs';
import os from 'os';
import path from 'path';
import _ from 'lodash';
import bcrypt from 'bcrypt-nodejs';
import chalk from 'chalk';
import webappengine from 'webappengine';
import app from './app';
import cncengine from './services/cncengine';
import monitor from './services/monitor';
import log from './lib/log';
import { readConfigFileSync, writeConfigFileSync } from './lib/config-file';
import settings from './config/settings';
const createServer = (options, callback) => {
const {
port = 0,
host,
backlog,
configFile,
verbosity,
mount,
watchDirectory,
allowRemoteAccess = false
} = { ...options };
const routes = [];
const cncrc = path.resolve(configFile || settings.cncrc);
const config = readConfigFileSync(cncrc);
// Secret
if (!config.secret) {
// generate a secret key
config.secret = bcrypt.genSaltSync(); // TODO
// update changes
writeConfigFileSync(cncrc, config);
}
config.watchDirectory = _.get(config, 'watchDirectory', watchDirectory);
config.allowRemoteAccess = _.get(config, 'allowRemoteAccess', allowRemoteAccess);
{ // routes
if (mount) {
routes.push({
type: 'static',
route: mount.url,
directory: mount.path
});
}
routes.push({
type: 'server',
route: '/',
server: () => app()
});
}
{ // Settings
settings.cncrc = cncrc;
settings.secret = config.secret || settings.secret;
// https://github.com/winstonjs/winston#logging-levels
if (verbosity === 1) {
_.set(settings, 'verbosity', verbosity);
log.logger.level = 'verbose';
}
if (verbosity === 2) {
_.set(settings, 'verbosity', verbosity);
log.logger.level = 'debug';
}
if (verbosity === 3) {
_.set(settings, 'verbosity', verbosity);
log.logger.level = 'silly';
}
_.set(settings, 'allowRemoteAccess', config.allowRemoteAccess);
}
// Watch Directory
if (config.watchDirectory) {
if (fs.existsSync(config.watchDirectory)) {
log.info(`Start watching ${chalk.yellow(JSON.stringify(config.watchDirectory))} for file changes.`);
// Start monitor service
monitor.start({ watchDirectory: config.watchDirectory });
} else {
log.error(`The directory ${chalk.yellow(JSON.stringify(config.watchDirectory))} does not exist.`);
}
}
webappengine({ port, host, backlog, routes })
.on('ready', (server) => {
// Start cncengine service
cncengine.start({ server: server });
const address = server.address().address;
const port = server.address().port;
if (address !== '0.0.0.0') {
log.info('Started the server at ' + chalk.cyan(`http://${address}:${port}`));
return;
}
dns.lookup(os.hostname(), { family: 4, all: true }, (err, addresses) => {
if (err) {
log.error('Can\'t resolve host name:', err);
return;
}
addresses.forEach(({ address, family }) => {
log.info('Started the server at ' + chalk.cyan(`http://${address}:${port}`));
});
});
})
.on('error', (err) => {
log.error(err);
});
};
export {
createServer
};
| Code refinement
| src/app/index.js | Code refinement | <ide><path>rc/app/index.js
<ide> const cncrc = path.resolve(configFile || settings.cncrc);
<ide> const config = readConfigFileSync(cncrc);
<ide>
<del> // Secret
<del> if (!config.secret) {
<del> // generate a secret key
<del> config.secret = bcrypt.genSaltSync(); // TODO
<add> // cncrc
<add> settings.cncrc = cncrc;
<ide>
<del> // update changes
<del> writeConfigFileSync(cncrc, config);
<add> { // secret
<add> if (!config.secret) {
<add> // generate a secret key
<add> config.secret = bcrypt.genSaltSync(); // TODO
<add>
<add> // update changes
<add> writeConfigFileSync(cncrc, config);
<add> }
<add>
<add> settings.secret = config.secret || settings.secret;
<ide> }
<del>
<del> config.watchDirectory = _.get(config, 'watchDirectory', watchDirectory);
<del> config.allowRemoteAccess = _.get(config, 'allowRemoteAccess', allowRemoteAccess);
<ide>
<ide> { // routes
<ide> if (mount) {
<ide> });
<ide> }
<ide>
<del> { // Settings
<del> settings.cncrc = cncrc;
<del> settings.secret = config.secret || settings.secret;
<del>
<add> { // verbosity
<ide> // https://github.com/winstonjs/winston#logging-levels
<ide> if (verbosity === 1) {
<ide> _.set(settings, 'verbosity', verbosity);
<ide> _.set(settings, 'verbosity', verbosity);
<ide> log.logger.level = 'silly';
<ide> }
<del>
<del> _.set(settings, 'allowRemoteAccess', config.allowRemoteAccess);
<ide> }
<ide>
<del> // Watch Directory
<del> if (config.watchDirectory) {
<del> if (fs.existsSync(config.watchDirectory)) {
<del> log.info(`Start watching ${chalk.yellow(JSON.stringify(config.watchDirectory))} for file changes.`);
<add> { // watchDirectory
<add> config.watchDirectory = _.get(config, 'watchDirectory', watchDirectory);
<ide>
<del> // Start monitor service
<del> monitor.start({ watchDirectory: config.watchDirectory });
<del> } else {
<del> log.error(`The directory ${chalk.yellow(JSON.stringify(config.watchDirectory))} does not exist.`);
<add> if (config.watchDirectory) {
<add> if (fs.existsSync(config.watchDirectory)) {
<add> log.info(`Start watching ${chalk.yellow(JSON.stringify(config.watchDirectory))} for file changes.`);
<add>
<add> // Start monitor service
<add> monitor.start({ watchDirectory: config.watchDirectory });
<add> } else {
<add> log.error(`The directory ${chalk.yellow(JSON.stringify(config.watchDirectory))} does not exist.`);
<add> }
<add> }
<add> }
<add>
<add> { // allowRemoteAccess
<add> config.allowRemoteAccess = _.get(config, 'allowRemoteAccess', allowRemoteAccess);
<add>
<add> if (config.allowRemoteAccess) {
<add> if (_.size(config.users) === 0) {
<add> log.warning('You\'ve enabled remote access to the server. It\'s recommended to create an user account to protect against malicious attacks.');
<add> }
<add>
<add> _.set(settings, 'allowRemoteAccess', config.allowRemoteAccess);
<ide> }
<ide> }
<ide> |
|
Java | mit | 322d7215bee562f4884f852ccadc254a23dbeff1 | 0 | diachron/quality | /**
*
*/
package eu.diachron.qualitymetrics.intrinsic.consistency;
import java.util.List;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.sparql.core.Quad;
import de.unibonn.iai.eis.luzzu.properties.EnvironmentProperties;
import eu.diachron.qualitymetrics.utilities.TestLoader;
/**
* @author Jeremy Debattista
*
*/
public class ValidIFPUsageTest extends Assert {
protected TestLoader loader = new TestLoader();
protected ValidIFPUsage metric = new ValidIFPUsage();
@Before
public void setUp() throws Exception {
EnvironmentProperties.getInstance().setDatasetURI("http://www.example.org");
loader.loadDataSet("testdumps/SampleInput_ValidIFPUsage_Minimal.ttl");
}
@After
public void tearDown() throws Exception {
}
@Test
public void testValidIFPUsageMinimalExample() {
List<Quad> streamingQuads = loader.getStreamingQuads();
for(Quad quad : streamingQuads){
// here we start streaming triples to the quality metric
metric.compute(quad);
}
// Total # IFP Statements : 4; # Violated Predicate-Object Statements : 1
// In our minimal example only the predicate object pair foaf:jabberID "I_AM_NOT_A_VALID_IFP"
// was violated with :bob and :alice resources having the same jabberID
// 1 - (1 / 4)
assertEquals(0.75,metric.metricValue(), 0.0001);
Model m = ((Model)metric.getQualityProblems().getProblemList().get(0));
m.write(System.out, "TURTLE");
}
}
| lod-qualitymetrics/lod-qualitymetrics-intrinsic/src/test/java/eu/diachron/qualitymetrics/intrinsic/consistency/ValidIFPUsageTest.java | /**
*
*/
package eu.diachron.qualitymetrics.intrinsic.consistency;
import java.util.List;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.hp.hpl.jena.sparql.core.Quad;
import de.unibonn.iai.eis.luzzu.properties.EnvironmentProperties;
import eu.diachron.qualitymetrics.utilities.TestLoader;
/**
* @author Jeremy Debattista
*
*/
public class ValidIFPUsageTest extends Assert {
protected TestLoader loader = new TestLoader();
protected ValidIFPUsage metric = new ValidIFPUsage();
@Before
public void setUp() throws Exception {
EnvironmentProperties.getInstance().setDatasetURI("http://www.example.org");
loader.loadDataSet("testdumps/SampleInput_ValidIFPUsage_Minimal.ttl");
}
@After
public void tearDown() throws Exception {
}
@Test
public void testValidIFPUsageMinimalExample() {
List<Quad> streamingQuads = loader.getStreamingQuads();
for(Quad quad : streamingQuads){
// here we start streaming triples to the quality metric
metric.compute(quad);
}
// Total # IFP Statements : 4; # Violated Predicate-Object Statements : 1
// In our minimal example only the predicate object pair foaf:jabberID "I_AM_NOT_A_VALID_IFP"
// was violated with :bob and :alice resources having the same jabberID
// 1 - (2 / 4)
assertEquals(0.5,metric.metricValue(), 0.0001);
}
}
| fixed assertsEqual result
| lod-qualitymetrics/lod-qualitymetrics-intrinsic/src/test/java/eu/diachron/qualitymetrics/intrinsic/consistency/ValidIFPUsageTest.java | fixed assertsEqual result | <ide><path>od-qualitymetrics/lod-qualitymetrics-intrinsic/src/test/java/eu/diachron/qualitymetrics/intrinsic/consistency/ValidIFPUsageTest.java
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide>
<add>import com.hp.hpl.jena.rdf.model.Model;
<ide> import com.hp.hpl.jena.sparql.core.Quad;
<ide>
<ide> import de.unibonn.iai.eis.luzzu.properties.EnvironmentProperties;
<ide> // In our minimal example only the predicate object pair foaf:jabberID "I_AM_NOT_A_VALID_IFP"
<ide> // was violated with :bob and :alice resources having the same jabberID
<ide>
<del> // 1 - (2 / 4)
<del> assertEquals(0.5,metric.metricValue(), 0.0001);
<add> // 1 - (1 / 4)
<add> assertEquals(0.75,metric.metricValue(), 0.0001);
<add>
<add> Model m = ((Model)metric.getQualityProblems().getProblemList().get(0));
<add> m.write(System.out, "TURTLE");
<add>
<ide> }
<ide>
<ide> |
|
JavaScript | mit | 0675cadb53df6b4a5cd8f48b11594387dda287fb | 0 | ofalvai/raspi-weather,ofalvai/raspi-weather,ofalvai/raspi-weather | var config = {
/**
* Frequency of measurement in minutes
* Note: it's only needed for the graph intervals, doesn't set the logging interval.
* You have to edit your crontab for that.
*/
measurementInterval: 30,
/**
* Coordinates for getting outside weather data from forecast.io
* By default, location is determined by HTML5 geolocation,
* but as a fallback it relies on manual coordinates.
*
* You can disable geolocation and provide coordinates if you want.
*/
useGeoLocation: true,
latitude: 47.51,
longitude: 19.09,
/**
* Forecast.io API key.
* Please don't abuse this. Be a good guy and request your own at http://developer.forecast.io
*/
APIKey: '262d0436a1b2d47e7593f0bb41491b64',
// Limits of the night plotband (the gray area on the graphs)
nightStart: 0,
nightEnd: 7,
// Used in chartComplete() to delay loading current sensor data
numOfCharts: 2,
loadedCharts: [ ]
}
var globalHighchartsOptions = {
chart: {
type: 'spline',
zoomType: 'x',
// spacingLeft: 5,
// spacingRight: 5,
marginLeft: 50,
marginRight: 50,
events: {
load: chartComplete
}
},
xAxis: {
type: 'datetime',
plotBands: [ ]
},
yAxis: [{
title: {
text: 'Temperature (°C)',
margin: 5,
style: {
fontWeight: 'bold'
}
},
opposite: true
},
{
title: {
text: 'Humidity (%)',
margin: 5,
style: {
fontWeight: 'bold'
}
},
min: 0,
max: 100
}],
series: [{
name: 'Temperature',
yAxis: 0,
data: [ ],
lineWidth: 4,
marker: {
enabled: false
},
tooltip: {
valueSuffix: '°C'
},
color: '#F18324',
zones: [{
// 0-22: yellow
value: 22,
color: '#F1AE24'
},
{
// 22-30: orange
value: 30,
color: '#F18324'
},
{
// 30+: red
value: 80,
color: '#F7605C'
}]
},
{
name: 'Humidity',
yAxis: 1,
data: [],
marker: {
enabled: false
},
tooltip: {
valueSuffix: '%'
},
color: '#7C8FBF',
dashStyle: 'shortdot'
}
],
legend: {
align: 'left',
verticalAlign: 'bottom',
y: 22
},
tooltip: {
shared: true,
crosshairs: true
},
title: {
text: ''
},
};
var stats = {
today: {
temperature: {
avg: 0
},
humidity: {
avg: 0
}
},
interval: {
temperature: {
avg: 0
},
humidity: {
avg: 0
}
},
logged_days: 0
}
function loadChart(APICall, DOMtarget, moreOptions) {
$.getJSON(APICall, function(json) {
if(!json.success) {
displayError(json.error, DOMtarget);
return;
}
if(json.data.length == 0) {
displayError('No data to display.', DOMtarget);
return;
}
var options = $.extend(true, {}, globalHighchartsOptions, moreOptions);
$.each(json.data, function(index, el) {
// Populating the series
options.series[0].data.push(el.temperature);
options.series[1].data.push(el.humidity);
// Computing plot bands for the night interval(s)
// Firefox needs T between date and time
// el.timestamp = el.timestamp.replace(' ', 'T');
var timeEpoch = parseDateTime(el.timestamp + 'Z');
// The above creates a timezone-correct UNIX epoch representation
// of the timestamp, and we need a regular datetime object
// to get hours and minutes.
var time = new Date(el.timestamp);
// Night start
if(time.getHours() == config.nightStart && time.getMinutes() == 0) {
options.xAxis.plotBands.push({
from: timeEpoch,
to: null, // will be stored later
color: '#f2f2f2'
});
}
// Night end
if(time.getHours() == config.nightEnd && time.getMinutes() == 0) {
options.xAxis.plotBands[options.xAxis.plotBands.length-1].to = timeEpoch;
}
});
// End the plotband if currently it's night
var last = options.xAxis.plotBands.length - 1;
if(options.xAxis.plotBands[last].to == null) {
options.xAxis.plotBands[last].to = Date.parse(
json.data[json.data.length-1].timestamp + 'Z'
);
}
options.series[0].pointStart = Date.parse(json.data[0].timestamp + 'Z');
// Ugly timezone hacking, because Date.parse() assumes UTC,
// and the timestamp is in local timezone
options.series[1].pointStart = Date.parse(json.data[0].timestamp + 'Z');
options.series[0].pointInterval = config.measurementInterval * 1000 * 60;
options.series[1].pointInterval = config.measurementInterval * 1000 * 60;
// Custom property to compute stats from this data set
options.doStats = true;
config.loadedCharts.push(APICall);
$(DOMtarget).highcharts(options);
});
}
function loadDoubleChart(APICall, DOMtarget, moreOptions) {
$.getJSON(APICall, function(json) {
if(!json.success) {
displayError(json.error, DOMtarget);
return;
}
if(json.first.data.length == 0 || json.second.data.length == 0) {
displayError('No data to display.', DOMtarget);
return;
}
// Make sure yesterday's data starts at 00:00
var startTime = parseDateTime(json.second.data[0].timestamp);
if(startTime.getHours() !== 0) {
displayError('Not enough data for yesterday. A full day\'s data is required for comparison.', DOMtarget);
$(document).trigger('chartComplete');
return;
}
var options = $.extend(true, {}, globalHighchartsOptions, moreOptions);
// Add more series
options.series.push({
name: 'Temperature yesterday',
yAxis: 0,
data: [],
lineWidth: 2,
marker: {
enabled: false
},
tooltip: {
valueSuffix: '°C'
},
color: '#F18324',
zones: [{
// 0-22: yellow
value: 22,
color: '#F1AE24'
},
{
// 22-30: orange
value: 30,
color: '#F18324'
},
{
// 30+: red
value: 80,
color: '#F7605C'
}],
dashStyle: 'shortdash'
});
options.series.push({
name: 'Humidity yesterday',
yAxis: 1,
data: [],
marker: {
enabled: false
},
tooltip: {
valueSuffix: '%'
},
color: '#7C8FBF',
dashStyle: 'shortdash'
});
$.each(json.first.data, function(index, el) {
options.series[0].data.push(el.temperature);
options.series[1].data.push(el.humidity);
});
$.each(json.second.data, function(index, el) {
options.series[2].data.push(el.temperature);
options.series[3].data.push(el.humidity);
});
options.series[1].dashStyle = 'solid';
options.tooltip.xDateFormat = '%H:%M';
options.xAxis.labels = {
format: '{value: %H:%M}'
};
// options.series[1].visible = false;
options.series[3].visible = false;
for(var i = 0; i < options.series.length; i++) {
// Just a dummy date object set to the beginning of a dummy day
// Only the hours and minutes will be displayed
options.series[i].pointStart = Date.parse('2015-01-01T00:00Z');
options.series[i].pointInterval = config.measurementInterval * 1000 * 60;
}
// Converting the actual last timestamp to our dummy datetime object
var lastTimestamp = parseDateTime(json.first.data[json.first.data.length-1].timestamp);
var h = lastTimestamp.getHours();
var m = lastTimestamp.getMinutes();
// Trailing zeros
h = (h < 10) ? '0' + h : h;
m = (m < 10) ? '0' + m : m;
var adjustedTimestamp = parseDateTime(
'2015-01-01 '
+ h + ':'
+ m + ':00Z'
);
// Adding a red vertical marker at the last measurement
options.xAxis.plotLines = [{
value: adjustedTimestamp,
color: 'red',
width: 1
}];
config.loadedCharts.push(APICall);
$(DOMtarget).highcharts(options);
});
}
function loadCurrentData() {
$.getJSON('/api/current', function(json) {
if(!json.success) {
displayError(json.error, '#error-container');
return;
}
$('#curr-temp-inside').text(json.temperature + '°');
$('#curr-hum-inside').text(json.humidity + '%');
});
}
function parseDateTime(dateTimeString) {
// Firefox can't parse datetime strings like YYYY-MM-DD HH:MM:SS, just YYYY-MM-DDTHH:MM:SS
// BUT Chrome parses the 'T-format' as UTC time (the space-format is parsed as local time), and applies timezone differences,
// which is the exact thing we don't need.
// I can't believe I have to deal with this shit.
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
if(isFirefox) {
dateTimeString = dateTimeString.replace(' ', 'T');
}
return new Date(dateTimeString);
}
function chartComplete() {
// Fired at Highchars' load event
// 'this' points to the Highcharts object
if(config.loadedCharts.length == config.numOfCharts) {
// Delay the current weather request until the others (charts) have completed,
// because it takes a long time and slows down poor little Pi :(
loadCurrentData();
}
if(this.options.doStats) {
// Ironically, at the time of the load event, the chart's data is not yet available....
window.setTimeout(computeStats, 100);
}
}
function displayError(error, target, level) {
// Values: success (green), info (blue), warning (yellow), danger (red)
level = level || 'danger';
$(target).append('<div class="alert alert-' + level + '">' + error + '</div>');
}
function getLocation() {
if(config.useGeoLocation) {
if("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function(position) {
config.latitude = position.coords.latitude;
config.longitude = position.coords.longitude;
$(document).trigger('geolocation');
}, function() {
if(config.useGeoLocation) {
// Only display if it's configured to use geolocation,
// not manual coordinates.
displayError('Failed to get location. Using predefined coordinates instead.', '#error-container', 'warning');
}
$(document).trigger('geolocation');
});
} else {
displayError('No GeoLocation support :( Using predefined coordinates instead.', '#error-container', 'warning');
$(document).trigger('geolocation');
}
}
}
function loadOutsideWeather() {
if(!config.APIKey) {
displayError('No Forecast.io API key, unable to get outside weather data.', '#error-container');
return;
}
$.getJSON('https://api.forecast.io/forecast/'
+ config.APIKey + '/'
+ config.latitude + ','
+ config.longitude
+ '/?units=si&exclude=minutely,daily,alerts,flags&callback=?',
function(json) {
$('#curr-temp-outside').text(json.currently.temperature.toFixed(1) + '°');
$('#curr-hum-outside').text((json.currently.humidity*100).toFixed() + '%');
$('#forecast-summary').text(json.hourly.summary);
$('#forecast-link').attr('href', 'http://forecast.io/#/f/'
+ config.latitude + ',' + config.longitude);
});
}
function computeStats() {
$('#stats').empty();
var day = $('#chart-today-vs').highcharts().series;
var interval = $('#chart-past').highcharts().series;
var intervalType = $('#dropdown-label-past').data('intervalType');
// Today:
stats.today.temperature.min = day[0].dataMin;
stats.today.temperature.max = day[0].dataMax;
stats.today.humidity.min = day[1].dataMin;
stats.today.humidity.max = day[1].dataMax;
stats.today.temperature.avg = 0;
stats.today.humidity.avg = 0;
for(i = 0; i < day[0].data.length; i++) {
stats.today.temperature.avg += parseInt(day[0].data[i].y);
stats.today.humidity.avg += parseInt(day[1].data[i].y);
}
stats.today.temperature.avg = (stats.today.temperature.avg / day[0].data.length).toFixed(1);
stats.today.humidity.avg = (stats.today.humidity.avg / day[1].data.length).toFixed(1);
// Last [selected] interval:
stats.interval.temperature.min = interval[0].dataMin;
stats.interval.temperature.max = interval[0].dataMax;
stats.interval.humidity.min = interval[1].dataMin;
stats.interval.humidity.max = interval[1].dataMax;
stats.interval.temperature.avg = 0;
stats.interval.humidity.avg = 0;
for(i = 0; i < interval[0].data.length; i++) {
stats.interval.temperature.avg += parseInt(interval[0].data[i].y);
stats.interval.humidity.avg += parseInt(interval[1].data[i].y);
}
stats.interval.temperature.avg = (stats.interval.temperature.avg / interval[0].data.length).toFixed(1);
stats.interval.humidity.avg = (stats.interval.humidity.avg / interval[1].data.length).toFixed(1);
var up = '<span class="up-arrow" title="Compared to the selected interval\'s average">▲</span>';
var down = '<span class="down-arrow" title="Compared to the selected interval\'s average">▼</span>';
var todayTempArrow = (stats.today.temperature.avg > stats.interval.temperature.avg) ? up : down;
var todayHumArrow = (stats.today.humidity.avg > stats.interval.humidity.avg) ? up : down;
$('#stats').append('<tr><th>Temperature</th><th>today</th><th>' + intervalType + '</th></tr>');
$('#stats').append('<tr><th class="sub">avg</th><td>' + todayTempArrow + stats.today.temperature.avg + '°</td><td>' + stats.interval.temperature.avg + '°</td></tr>');
$('#stats').append('<tr><th class="sub">min</th><td>' + stats.today.temperature.min + '°</td><td>' + stats.interval.temperature.min + '°</td></tr>');
$('#stats').append('<tr><th class="sub">max</th><td>' + stats.today.temperature.max + '°</td><td>' + stats.interval.temperature.max + '°</td></tr>');
$('#stats').append('<tr><th>Humidity</th><th>today</th><th>' + intervalType + '</th></tr>');
$('#stats').append('<tr><th class="sub">avg</th><td>' + todayHumArrow + stats.today.humidity.avg + '%</td><td>' + stats.interval.humidity.avg + '%</td></tr>');
$('#stats').append('<tr><th class="sub">min</th><td>' + stats.today.humidity.min + '%</td><td>' + stats.interval.humidity.min + '%</td></tr>');
$('#stats').append('<tr><th class="sub">max</th><td>' + stats.today.humidity.max + '%</td><td>' + stats.interval.humidity.max + '%</td></tr>');
}
$(document).ready(function() {
$(document).on('geolocation', loadOutsideWeather);
getLocation();
loadDoubleChart('/api/compare/today/yesterday', '#chart-today-vs');
loadChart('/api/past/week', '#chart-past');
$('[data-toggle="tooltip"]').tooltip();
$('#dropdown-label-past').data('intervalType', 'week');
// Past chart: dropdown change interval
$('#chart-interval-past').on('click', function(e) {
e.preventDefault();
var interval = $(e.target).parent().attr('data-interval');
$('#dropdown-label-past').text(interval).data('intervalType', interval); // Data used in computeStats()
loadChart('/api/past/' + interval, '#chart-past');
});
$('#btn-reload-inside').on('click', function() {
$('#curr-temp-inside, #curr-hum-inside').text('...');
loadCurrentData();
});
$('#btn-reload-outside').on('click', function() {
$('#curr-temp-outside, #curr-hum-outside').text('...');
loadOutsideWeather();
});
$('#btn-reload-all').on('click', function() {
$('#error-container').empty();
$('#curr-temp-outside, #curr-hum-outside, #curr-temp-inside, #curr-hum-inside, #forecast-summary').text('...');
$('#chart-today-vs, #chart-past').each(function(i, el) {
$(el).highcharts().destroy();
});
config.loadedCharts = [ ];
loadOutsideWeather();
loadDoubleChart('/api/compare/today/yesterday', '#chart-today-vs');
loadChart('/api/past/week', '#chart-past');
});
});
| public/javascripts/app.js | var config = {
/**
* Frequency of measurement in minutes
* Note: it's only needed for the graph intervals, doesn't set the logging interval.
* You have to edit your crontab for that.
*/
measurementInterval: 30,
/**
* Coordinates for getting outside weather data from forecast.io
* By default, location is determined by HTML5 geolocation,
* but as a fallback it relies on manual coordinates.
*
* You can disable geolocation and provide coordinates if you want.
*/
useGeoLocation: true,
latitude: 47.51,
longitude: 19.09,
/**
* Forecast.io API key.
* Please don't abuse this. Be a good guy and request your own at http://developer.forecast.io
*/
APIKey: '262d0436a1b2d47e7593f0bb41491b64',
// Limits of the night plotband (the gray area on the graphs)
nightStart: 0,
nightEnd: 7
}
var globalHighchartsOptions = {
chart: {
type: 'spline',
zoomType: 'x',
// spacingLeft: 5,
// spacingRight: 5,
marginLeft: 50,
marginRight: 50,
events: {
load: chartComplete
}
},
xAxis: {
type: 'datetime',
plotBands: [ ]
},
yAxis: [{
title: {
text: 'Temperature (°C)',
margin: 5,
style: {
fontWeight: 'bold'
}
},
opposite: true
},
{
title: {
text: 'Humidity (%)',
margin: 5,
style: {
fontWeight: 'bold'
}
},
min: 0,
max: 100
}],
series: [{
name: 'Temperature',
yAxis: 0,
data: [ ],
lineWidth: 4,
marker: {
enabled: false
},
tooltip: {
valueSuffix: '°C'
},
color: '#F18324',
zones: [{
// 0-22: yellow
value: 22,
color: '#F1AE24'
},
{
// 22-30: orange
value: 30,
color: '#F18324'
},
{
// 30+: red
value: 80,
color: '#F7605C'
}]
},
{
name: 'Humidity',
yAxis: 1,
data: [],
marker: {
enabled: false
},
tooltip: {
valueSuffix: '%'
},
color: '#7C8FBF',
dashStyle: 'shortdot'
}
],
legend: {
align: 'left',
verticalAlign: 'bottom',
y: 22
},
tooltip: {
shared: true,
crosshairs: true
},
title: {
text: ''
},
};
var stats = {
today: {
temperature: {
avg: 0
},
humidity: {
avg: 0
}
},
interval: {
temperature: {
avg: 0
},
humidity: {
avg: 0
}
},
logged_days: 0
}
function loadChart(APICall, DOMtarget, moreOptions) {
$.getJSON(APICall, function(json) {
if(!json.success) {
displayError(json.error, DOMtarget);
return;
}
if(json.data.length == 0) {
displayError('No data to display.', DOMtarget);
return;
}
var options = $.extend(true, {}, globalHighchartsOptions, moreOptions);
$.each(json.data, function(index, el) {
// Populating the series
options.series[0].data.push(el.temperature);
options.series[1].data.push(el.humidity);
// Computing plot bands for the night interval(s)
// Firefox needs T between date and time
// el.timestamp = el.timestamp.replace(' ', 'T');
var timeEpoch = parseDateTime(el.timestamp + 'Z');
// The above creates a timezone-correct UNIX epoch representation
// of the timestamp, and we need a regular datetime object
// to get hours and minutes.
var time = new Date(el.timestamp);
// Night start
if(time.getHours() == config.nightStart && time.getMinutes() == 0) {
options.xAxis.plotBands.push({
from: timeEpoch,
to: null, // will be stored later
color: '#f2f2f2'
});
}
// Night end
if(time.getHours() == config.nightEnd && time.getMinutes() == 0) {
options.xAxis.plotBands[options.xAxis.plotBands.length-1].to = timeEpoch;
}
});
// End the plotband if currently it's night
var last = options.xAxis.plotBands.length - 1;
if(options.xAxis.plotBands[last].to == null) {
options.xAxis.plotBands[last].to = Date.parse(
json.data[json.data.length-1].timestamp + 'Z'
);
}
options.series[0].pointStart = Date.parse(json.data[0].timestamp + 'Z');
// Ugly timezone hacking, because Date.parse() assumes UTC,
// and the timestamp is in local timezone
options.series[1].pointStart = Date.parse(json.data[0].timestamp + 'Z');
options.series[0].pointInterval = config.measurementInterval * 1000 * 60;
options.series[1].pointInterval = config.measurementInterval * 1000 * 60;
// Custom property to compute stats from this data set
options.doStats = true;
$(DOMtarget).highcharts(options);
$(document).trigger('chartComplete');
});
}
function loadDoubleChart(APICall, DOMtarget, moreOptions) {
$.getJSON(APICall, function(json) {
if(!json.success) {
displayError(json.error, DOMtarget);
return;
}
if(json.first.data.length == 0 || json.second.data.length == 0) {
displayError('No data to display.', DOMtarget);
return;
}
// Make sure yesterday's data starts at 00:00
var startTime = parseDateTime(json.second.data[0].timestamp);
if(startTime.getHours() !== 0) {
displayError('Not enough data for yesterday. A full day\'s data is required for comparison.', DOMtarget);
$(document).trigger('chartComplete');
return;
}
var options = $.extend(true, {}, globalHighchartsOptions, moreOptions);
// Add more series
options.series.push({
name: 'Temperature yesterday',
yAxis: 0,
data: [],
lineWidth: 2,
marker: {
enabled: false
},
tooltip: {
valueSuffix: '°C'
},
color: '#F18324',
zones: [{
// 0-22: yellow
value: 22,
color: '#F1AE24'
},
{
// 22-30: orange
value: 30,
color: '#F18324'
},
{
// 30+: red
value: 80,
color: '#F7605C'
}],
dashStyle: 'shortdash'
});
options.series.push({
name: 'Humidity yesterday',
yAxis: 1,
data: [],
marker: {
enabled: false
},
tooltip: {
valueSuffix: '%'
},
color: '#7C8FBF',
dashStyle: 'shortdash'
});
$.each(json.first.data, function(index, el) {
options.series[0].data.push(el.temperature);
options.series[1].data.push(el.humidity);
});
$.each(json.second.data, function(index, el) {
options.series[2].data.push(el.temperature);
options.series[3].data.push(el.humidity);
});
options.series[1].dashStyle = 'solid';
options.tooltip.xDateFormat = '%H:%M';
options.xAxis.labels = {
format: '{value: %H:%M}'
};
// options.series[1].visible = false;
options.series[3].visible = false;
for(var i = 0; i < options.series.length; i++) {
// Just a dummy date object set to the beginning of a dummy day
// Only the hours and minutes will be displayed
options.series[i].pointStart = Date.parse('2015-01-01T00:00Z');
options.series[i].pointInterval = config.measurementInterval * 1000 * 60;
}
// Converting the actual last timestamp to our dummy datetime object
var lastTimestamp = parseDateTime(json.first.data[json.first.data.length-1].timestamp);
var h = lastTimestamp.getHours();
var m = lastTimestamp.getMinutes();
// Trailing zeros
h = (h < 10) ? '0' + h : h;
m = (m < 10) ? '0' + m : m;
var adjustedTimestamp = parseDateTime(
'2015-01-01 '
+ h + ':'
+ m + ':00Z'
);
// Adding a red vertical marker at the last measurement
options.xAxis.plotLines = [{
value: adjustedTimestamp,
color: 'red',
width: 1
}];
$(DOMtarget).highcharts(options);
$(document).trigger('chartComplete', true);
});
}
function loadCurrentData() {
$.getJSON('/api/current', function(json) {
if(!json.success) {
displayError(json.error, '#error-container');
return;
}
$('#curr-temp-inside').text(json.temperature + '°');
$('#curr-hum-inside').text(json.humidity + '%');
});
}
function parseDateTime(dateTimeString) {
// Firefox can't parse datetime strings like YYYY-MM-DD HH:MM:SS, just YYYY-MM-DDTHH:MM:SS
// BUT Chrome parses the 'T-format' as UTC time (the space-format is parsed as local time), and applies timezone differences,
// which is the exact thing we don't need.
// I can't believe I have to deal with this shit.
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
if(isFirefox) {
dateTimeString = dateTimeString.replace(' ', 'T');
}
return new Date(dateTimeString);
}
function chartComplete() {
// Fired at Highchars' load event
// 'this' points to Highcharts object
if(this.options.doStats) {
// Ironically, at the time of the load event, the chart's data is not yet available....
window.setTimeout(computeStats, 100);
}
}
function displayError(error, target, level) {
// Values: success (green), info (blue), warning (yellow), danger (red)
level = level || 'danger';
$(target).append('<div class="alert alert-' + level + '">' + error + '</div>');
}
function getLocation() {
if(config.useGeoLocation) {
if("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function(position) {
config.latitude = position.coords.latitude;
config.longitude = position.coords.longitude;
$(document).trigger('geolocation');
}, function() {
if(config.useGeoLocation) {
// Only display if it's configured to use geolocation,
// not manual coordinates.
displayError('Failed to get location. Using predefined coordinates instead.', '#error-container', 'warning');
}
$(document).trigger('geolocation');
});
} else {
displayError('No GeoLocation support :( Using predefined coordinates instead.', '#error-container', 'warning');
$(document).trigger('geolocation');
}
}
}
function loadOutsideWeather() {
if(!config.APIKey) {
displayError('No Forecast.io API key, unable to get outside weather data.', '#error-container');
return;
}
$.getJSON('https://api.forecast.io/forecast/'
+ config.APIKey + '/'
+ config.latitude + ','
+ config.longitude
+ '/?units=si&exclude=minutely,daily,alerts,flags&callback=?',
function(json) {
$('#curr-temp-outside').text(json.currently.temperature.toFixed(1) + '°');
$('#curr-hum-outside').text((json.currently.humidity*100).toFixed() + '%');
$('#forecast-summary').text(json.hourly.summary);
$('#forecast-link').attr('href', 'http://forecast.io/#/f/'
+ config.latitude + ',' + config.longitude);
});
}
function computeStats() {
$('#stats').empty();
var day = $('#chart-today-vs').highcharts().series;
var interval = $('#chart-past').highcharts().series;
var intervalType = $('#dropdown-label-past').data('intervalType');
// Today:
stats.today.temperature.min = day[0].dataMin;
stats.today.temperature.max = day[0].dataMax;
stats.today.humidity.min = day[1].dataMin;
stats.today.humidity.max = day[1].dataMax;
stats.today.temperature.avg = 0;
stats.today.humidity.avg = 0;
for(i = 0; i < day[0].data.length; i++) {
stats.today.temperature.avg += parseInt(day[0].data[i].y);
stats.today.humidity.avg += parseInt(day[1].data[i].y);
}
stats.today.temperature.avg = (stats.today.temperature.avg / day[0].data.length).toFixed(1);
stats.today.humidity.avg = (stats.today.humidity.avg / day[1].data.length).toFixed(1);
// Last [selected] interval:
stats.interval.temperature.min = interval[0].dataMin;
stats.interval.temperature.max = interval[0].dataMax;
stats.interval.humidity.min = interval[1].dataMin;
stats.interval.humidity.max = interval[1].dataMax;
stats.interval.temperature.avg = 0;
stats.interval.humidity.avg = 0;
for(i = 0; i < interval[0].data.length; i++) {
stats.interval.temperature.avg += parseInt(interval[0].data[i].y);
stats.interval.humidity.avg += parseInt(interval[1].data[i].y);
}
stats.interval.temperature.avg = (stats.interval.temperature.avg / interval[0].data.length).toFixed(1);
stats.interval.humidity.avg = (stats.interval.humidity.avg / interval[1].data.length).toFixed(1);
var up = '<span class="up-arrow" title="Compared to the selected interval\'s average">▲</span>';
var down = '<span class="down-arrow" title="Compared to the selected interval\'s average">▼</span>';
var todayTempArrow = (stats.today.temperature.avg > stats.interval.temperature.avg) ? up : down;
var todayHumArrow = (stats.today.humidity.avg > stats.interval.humidity.avg) ? up : down;
$('#stats').append('<tr><th>Temperature</th><th>today</th><th>' + intervalType + '</th></tr>');
$('#stats').append('<tr><th class="sub">avg</th><td>' + todayTempArrow + stats.today.temperature.avg + '°</td><td>' + stats.interval.temperature.avg + '°</td></tr>');
$('#stats').append('<tr><th class="sub">min</th><td>' + stats.today.temperature.min + '°</td><td>' + stats.interval.temperature.min + '°</td></tr>');
$('#stats').append('<tr><th class="sub">max</th><td>' + stats.today.temperature.max + '°</td><td>' + stats.interval.temperature.max + '°</td></tr>');
$('#stats').append('<tr><th>Humidity</th><th>today</th><th>' + intervalType + '</th></tr>');
$('#stats').append('<tr><th class="sub">avg</th><td>' + todayHumArrow + stats.today.humidity.avg + '%</td><td>' + stats.interval.humidity.avg + '%</td></tr>');
$('#stats').append('<tr><th class="sub">min</th><td>' + stats.today.humidity.min + '%</td><td>' + stats.interval.humidity.min + '%</td></tr>');
$('#stats').append('<tr><th class="sub">max</th><td>' + stats.today.humidity.max + '%</td><td>' + stats.interval.humidity.max + '%</td></tr>');
}
$(document).ready(function() {
$(document).on('geolocation', loadOutsideWeather);
getLocation();
loadDoubleChart('/api/compare/today/yesterday', '#chart-today-vs');
loadChart('/api/past/week', '#chart-past');
// Delay the current weather request until the others have completed,
// because it takes a long time and slows down poor little Pi :(
var charts_loaded = 0;
$(document).on('chartComplete', function(e, refreshStats) {
// TODO: erre még kitalálni valamit
charts_loaded++;
// WARNING: magic number
if(charts_loaded >= 2) {
loadCurrentData();
// Reshresh all button needs this thing again
charts_loaded = 0;
}
});
$('[data-toggle="tooltip"]').tooltip();
$('#dropdown-label-past').data('intervalType', 'week');
// Past chart: dropdown change interval
$('#chart-interval-past').on('click', function(e) {
e.preventDefault();
var interval = $(e.target).parent().attr('data-interval');
$('#dropdown-label-past').text(interval).data('intervalType', interval); // Data used in computeStats()
loadChart('/api/past/' + interval, '#chart-past');
});
$('#btn-reload-inside').on('click', function() {
$('#curr-temp-inside, #curr-hum-inside').text('...');
loadCurrentData();
});
$('#btn-reload-outside').on('click', function() {
$('#curr-temp-outside, #curr-hum-outside').text('...');
loadOutsideWeather();
});
$('#btn-reload-all').on('click', function() {
$('#error-container').empty();
$('#curr-temp-outside, #curr-hum-outside, #curr-temp-inside, #curr-hum-inside, #forecast-summary').text('...');
$('#chart-today-vs, #chart-past').each(function(i, el) {
$(el).highcharts().destroy();
});
loadOutsideWeather();
loadDoubleChart('/api/compare/today/yesterday', '#chart-today-vs');
loadChart('/api/past/week', '#chart-past');
// These will be handled by the chartComplete event logic:
// loadCurrentData();
// TODO
});
});
| Rewrote chartComplete event handling
| public/javascripts/app.js | Rewrote chartComplete event handling | <ide><path>ublic/javascripts/app.js
<ide>
<ide> // Limits of the night plotband (the gray area on the graphs)
<ide> nightStart: 0,
<del> nightEnd: 7
<add> nightEnd: 7,
<add>
<add> // Used in chartComplete() to delay loading current sensor data
<add> numOfCharts: 2,
<add> loadedCharts: [ ]
<ide> }
<ide>
<ide> var globalHighchartsOptions = {
<ide> // Custom property to compute stats from this data set
<ide> options.doStats = true;
<ide>
<add> config.loadedCharts.push(APICall);
<ide> $(DOMtarget).highcharts(options);
<del> $(document).trigger('chartComplete');
<ide> });
<ide> }
<ide>
<ide> width: 1
<ide> }];
<ide>
<add> config.loadedCharts.push(APICall);
<ide> $(DOMtarget).highcharts(options);
<del> $(document).trigger('chartComplete', true);
<ide> });
<ide> }
<ide>
<ide>
<ide> function chartComplete() {
<ide> // Fired at Highchars' load event
<del> // 'this' points to Highcharts object
<add> // 'this' points to the Highcharts object
<add>
<add> if(config.loadedCharts.length == config.numOfCharts) {
<add> // Delay the current weather request until the others (charts) have completed,
<add> // because it takes a long time and slows down poor little Pi :(
<add> loadCurrentData();
<add> }
<add>
<ide> if(this.options.doStats) {
<ide> // Ironically, at the time of the load event, the chart's data is not yet available....
<ide> window.setTimeout(computeStats, 100);
<ide>
<ide> loadChart('/api/past/week', '#chart-past');
<ide>
<del>
<del>
<del> // Delay the current weather request until the others have completed,
<del> // because it takes a long time and slows down poor little Pi :(
<del> var charts_loaded = 0;
<del> $(document).on('chartComplete', function(e, refreshStats) {
<del> // TODO: erre még kitalálni valamit
<del> charts_loaded++;
<del> // WARNING: magic number
<del> if(charts_loaded >= 2) {
<del> loadCurrentData();
<del> // Reshresh all button needs this thing again
<del> charts_loaded = 0;
<del> }
<del> });
<del>
<ide> $('[data-toggle="tooltip"]').tooltip();
<ide>
<ide> $('#dropdown-label-past').data('intervalType', 'week');
<ide> $('#chart-today-vs, #chart-past').each(function(i, el) {
<ide> $(el).highcharts().destroy();
<ide> });
<add> config.loadedCharts = [ ];
<ide>
<ide> loadOutsideWeather();
<ide> loadDoubleChart('/api/compare/today/yesterday', '#chart-today-vs');
<ide> loadChart('/api/past/week', '#chart-past');
<del>
<del> // These will be handled by the chartComplete event logic:
<del> // loadCurrentData();
<del> // TODO
<ide> });
<ide> }); |
|
JavaScript | bsd-3-clause | 5887b224cfe5df4142c723daf44fbbd390d71a52 | 0 | GPII/windows,GPII/windows | /*
* Tests for the windows login user listener.
*
* Copyright 2017 Raising the Floor - International
*
* Licensed under the New BSD license. You may not use this file except in
* compliance with this License.
*
* The R&D leading to these results received funding from the
* Department of Education - Grant H421A150005 (GPII-APCP). However,
* these results do not necessarily represent the policy of the
* Department of Education, and you should not assume endorsement by the
* Federal Government.
*
* You may obtain a copy of the License at
* https://github.com/GPII/universal/blob/master/LICENSE.txt
*/
"use strict";
var fluid = require("gpii-universal"),
os = require("os"),
path = require("path"),
fs = require("fs"),
child_process = require("child_process");
var jqUnit = fluid.require("node-jqunit");
var gpii = fluid.registerNamespace("gpii");
fluid.registerNamespace("gpii.tests.userListener");
require("../index.js");
var teardowns = [];
jqUnit.module("gpii.tests.userListener.windowsLogin", {
teardown: function () {
while (teardowns.length) {
teardowns.pop()();
}
}
});
fluid.defaults("gpii.tests.userListener.windowsLogin", {
gradeNames: ["fluid.component", "gpii.windows.userListeners.windowsLogin"],
listeners: {
"onTokenArrive.callFlowManager": "fluid.identity",
"onTokenRemove.callFlowManager": "fluid.identity"
},
distributeOptions: {
service: {
record: "gpii.test.userListeners.windowsLoginService",
target: "{/ gpii.userListeners.windows}.options.gradeNames"
}
}
});
// Give the user listeners an "onServiceReady" event.
fluid.defaults("gpii.test.userListeners.windowsLoginService", {
gradeNames: ["fluid.component"],
components: {
service: {
type: "fluid.component",
options: {
events: {
"onServiceReady": null
}
}
}
}
});
jqUnit.asyncTest("testing getting the user's SID", function () {
jqUnit.expect(5);
// User SIDs begin with this.
var sidPrefix = "S-1-5-21-";
var sid = gpii.windows.getUserSid();
jqUnit.assertEquals("getUserSid should return a string", "string", typeof(sid));
jqUnit.assertTrue("return from getUserSid should look like an SID", sid.startsWith(sidPrefix));
var sid2 = gpii.windows.getUserSid();
var sid3 = gpii.windows.getUserSid();
jqUnit.assertEquals("getUserSid should always return the same value", sid, sid2);
jqUnit.assertEquals("getUserSid should always return the same value (again)", sid, sid3);
// Compare it to the value from the "whoami" command.
child_process.exec("%SystemRoot%\\System32\\whoami.exe /user", function (err, stdout, stderr) {
if (err) {
jqUnit.fail(err);
}
fluid.log("whoami:", stdout, stderr);
jqUnit.assertTrue("SID should match the whoami command output", stdout.trim().endsWith(sid));
jqUnit.start();
});
});
jqUnit.test("testing hexToGuid", function () {
jqUnit.expect(2);
var expect = "01234567-89ab-cdef-0123-456789abcdef";
var guid1 = gpii.windows.userListeners.hexToGuid("0123456789abcdef0123456789abcdef");
jqUnit.assertEquals("hex string should produce the expected GUID (32 chars)", expect, guid1);
var guid2 =
gpii.windows.userListeners.hexToGuid("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef");
jqUnit.assertEquals("hex string should produce the expected GUID (over 32 chars)", expect, guid2);
jqUnit.expectFrameworkDiagnostic("hexToGuid should fails with a short string (16 chars)", function () {
gpii.windows.userListeners.hexToGuid("0123456789abcdef");
}, "hexToGuid wants a longer string");
});
jqUnit.test("Testing getUserId", function () {
// Windows Account SID
var userIdResult = gpii.windows.userListeners.getUserId("userid");
jqUnit.assertEquals("getUserId(userid) should return the user's SID", gpii.windows.getUserSid(), userIdResult);
// Windows username
var usernameResult = gpii.windows.userListeners.getUserId("username");
jqUnit.assertEquals("getUserId(username) should return the user's username", os.userInfo().username, usernameResult);
// File content
var testFile = path.join(os.tmpdir(), "gpii-username-test" + Math.random());
teardowns.push(function () {
fs.unlinkSync(testFile);
});
var expectFileResult = "test-userid" + Math.random();
fs.writeFileSync(testFile, expectFileResult);
var fileResult = gpii.windows.userListeners.getUserId("file:" + testFile);
jqUnit.assertEquals("getUserId(file) should return the correct value", expectFileResult, fileResult);
var testEnvFile = path.join("%TEMP%", path.basename(testFile));
var fileEnvResult = gpii.windows.userListeners.getUserId("file:" + testEnvFile);
jqUnit.assertEquals("getUserId(file) should return the correct value", expectFileResult, fileEnvResult);
// File content (no file)
var noFileResult = gpii.windows.userListeners.getUserId("file:c:\\not\\exists");
jqUnit.assertEquals("getUserId(no file) should return the correct value", null, noFileResult);
// Registry value
var baseKey = "HKEY_CURRENT_USER";
var subKey = "Software\\gpii-temp";
var valueName = "username-test";
var userValue = "test-userid" + Math.random();
gpii.windows.writeRegistryKey(baseKey, subKey, valueName, userValue, "REG_SZ");
teardowns.push(function () {
if (subKey.endsWith("gpii-temp")) {
gpii.windows.deleteRegistryKey(baseKey, subKey);
}
});
fluid.each(["reg:", "regkey:"], function (prefix) {
var expectedValue = prefix === "reg:"
? userValue
: ("gpiikey:" + userValue);
var regResult = gpii.windows.userListeners.getUserId(prefix + baseKey + "\\" + subKey + "\\" + valueName);
jqUnit.assertEquals("getUserId(file) should return the correct value", expectedValue, regResult);
// Abbreviated base key
var regResult2 = gpii.windows.userListeners.getUserId(prefix + "HKCU\\" + subKey + "\\" + valueName);
jqUnit.assertEquals("getUserId(file) should return the correct value", expectedValue, regResult2);
// Non existing registry key
var regResult3 = gpii.windows.userListeners.getUserId(prefix + "HKCU\\gpii\\does\\not\\exist");
jqUnit.assertEquals("getUserId(file) should return the correct value", null, regResult3);
});
});
jqUnit.test("testing blocked user name matching", function () {
var tests = [
{
blockedUsers: [],
usernames: {
"empty1": false,
"empty2": false
}
},
{
blockedUsers: [ "one", "*two", "three*", "*four*" ],
usernames: {
"one": true,
"two": true,
"three": true,
"four": true,
"a_one": false,
"a_two": true,
"a_three": false,
"a_four": true,
"one_b": false,
"two_b": false,
"three_b": true,
"four_b": true,
"a_one_b": false,
"a_two_b": false,
"a_three_b": false,
"a_four_b": true,
"xyz": false
}
},
{
blockedUsers: [ "one*two", "*three*four", "five*six*", "*seven*eight*" ],
usernames: {
"one_x_two": true,
"three_x_four": true,
"five_x_six": true,
"seven_x_eight": true,
"a_one_x_two": false,
"a_three_x_four": true,
"a_five_x_six": false,
"a_seven_x_eight": true,
"one_x_two_b": false,
"three_x_four_b": false,
"five_x_six_b": true,
"seven_x_eight_b": true,
"a_one_x_two_b": false,
"a_three_x_four_b": false,
"a_five_x_six_b": false,
"a_seven_x_eight_b": true
}
},
{
blockedUsers: [ "on?", "t?o", "?hree", "f?ur", "?iv?", "si?*", "s?v*" ],
usernames: {
"one": true,
"two": true,
"three": true,
"four": true,
"five": true,
"six": true,
"seven": true,
"eight": false
}
}
];
fluid.each(tests, function (test) {
fluid.each(test.usernames, function (expected, username) {
var result = gpii.windows.userListeners.checkBlockedUser(test.blockedUsers, username);
jqUnit.assertEquals("blockedUser " + username, expected, result);
});
});
});
jqUnit.asyncTest("testing blocked local accounts", function () {
// Create an instance with the current user being a blocked user
var windowsLogin = gpii.tests.userListener.windowsLogin({
config: {
blockedUsers: [os.userInfo().username]
}
});
jqUnit.expect(2);
windowsLogin.getGpiiKey = function () {
return fluid.promise().resolve("getGpiiKey");
};
var blockedPromise = gpii.windows.userListeners.startWindowsLogin(windowsLogin);
jqUnit.assertTrue("startWindowsLogin should return a promise", fluid.isPromise(blockedPromise));
blockedPromise.then(function () {
jqUnit.fail("startWindowsLogin should not resolve");
}, function (reason) {
jqUnit.assertEquals("startWindowsLogin should reject with 'blocked'", "blocked", reason);
jqUnit.start();
});
});
jqUnit.asyncTest("testing getGpiiKey", function () {
var windowsLogin = gpii.tests.userListener.windowsLogin({
config: {
userIdSource: "userid"
}
});
jqUnit.expect(2);
var sid = gpii.windows.getUserSid();
var expectedKey = "01234567-89ab-cdef-0123-456789abcdef";
var sign = function (payload) {
jqUnit.assertEquals("signing function should be called with the current SID", sid, payload);
return fluid.toPromise("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef");
};
gpii.windows.userListeners.getGpiiKey(windowsLogin, sign).then(function (key) {
jqUnit.assertEquals("getGpiiKey should resolve with the expected key", expectedKey, key);
jqUnit.start();
});
});
jqUnit.asyncTest("testing getGpiiKey (got a gpiiKey)", function () {
var gpiiKey = "test-key" + Math.random();
var baseKey = "HKEY_CURRENT_USER";
var subKey = "Software\\gpii-temp";
var valueName = "username-test";
var userValue = gpiiKey;
gpii.windows.writeRegistryKey(baseKey, subKey, valueName, userValue, "REG_SZ");
teardowns.push(function () {
if (subKey.endsWith("gpii-temp")) {
gpii.windows.deleteRegistryKey(baseKey, subKey);
}
});
var windowsLogin = gpii.tests.userListener.windowsLogin({
config: {
userIdSource: path.join("regkey:" + baseKey, subKey, valueName)
}
});
var sign = function () {
jqUnit.fail("signing function should not be called for a gpiiKey");
return fluid.promise().reject();
};
gpii.windows.userListeners.getGpiiKey(windowsLogin, sign).then(function (key) {
jqUnit.assertEquals("getGpiiKey should resolve with the expected key", gpiiKey, key);
jqUnit.start();
}, fluid.fail);
});
jqUnit.asyncTest("testing getGpiiKey, with blocked user id", function () {
var testFile = path.join(os.tmpdir(), "gpii-username-test" + Math.random());
teardowns.push(function () {
fs.unlinkSync(testFile);
});
fs.writeFileSync(testFile, "blocked-user");
var windowsLogin = gpii.tests.userListener.windowsLogin({
config: {
userIdSource: "file:" + testFile,
blockedUsers: [ "blocked-*" ]
}
});
jqUnit.expect(0);
var sign = function () {
jqUnit.fail("sign function should not be called for a blocked user id");
};
gpii.windows.userListeners.getGpiiKey(windowsLogin, sign).then(function () {
jqUnit.fail("getGpiiKey should not resolve");
}, jqUnit.start());
});
| gpii/node_modules/userListeners/test/windowsLoginTests.js | /*
* Tests for the windows login user listener.
*
* Copyright 2017 Raising the Floor - International
*
* Licensed under the New BSD license. You may not use this file except in
* compliance with this License.
*
* The R&D leading to these results received funding from the
* Department of Education - Grant H421A150005 (GPII-APCP). However,
* these results do not necessarily represent the policy of the
* Department of Education, and you should not assume endorsement by the
* Federal Government.
*
* You may obtain a copy of the License at
* https://github.com/GPII/universal/blob/master/LICENSE.txt
*/
"use strict";
var fluid = require("gpii-universal"),
os = require("os"),
path = require("path"),
fs = require("fs"),
child_process = require("child_process");
var jqUnit = fluid.require("node-jqunit");
var gpii = fluid.registerNamespace("gpii");
fluid.registerNamespace("gpii.tests.userListener");
require("../index.js");
var teardowns = [];
jqUnit.module("gpii.tests.userListener.windowsLogin", {
teardown: function () {
while (teardowns.length) {
teardowns.pop()();
}
}
});
fluid.defaults("gpii.tests.userListener.windowsLogin", {
gradeNames: ["fluid.component", "gpii.windows.userListeners.windowsLogin"],
listeners: {
"onTokenArrive.callFlowManager": "fluid.identity",
"onTokenRemove.callFlowManager": "fluid.identity"
},
distributeOptions: {
service: {
record: "gpii.test.userListeners.windowsLoginService",
target: "{/ gpii.userListeners.windows}.options.gradeNames"
}
}
});
// Give the user listeners an "onServiceReady" event.
fluid.defaults("gpii.test.userListeners.windowsLoginService", {
gradeNames: ["fluid.component"],
components: {
service: {
type: "fluid.component",
options: {
events: {
"onServiceReady": null
}
}
}
}
});
jqUnit.asyncTest("testing getting the user's SID", function () {
jqUnit.expect(5);
// User SIDs begin with this.
var sidPrefix = "S-1-5-21-";
var sid = gpii.windows.getUserSid();
jqUnit.assertEquals("getUserSid should return a string", "string", typeof(sid));
jqUnit.assertTrue("return from getUserSid should look like an SID", sid.startsWith(sidPrefix));
var sid2 = gpii.windows.getUserSid();
var sid3 = gpii.windows.getUserSid();
jqUnit.assertEquals("getUserSid should always return the same value", sid, sid2);
jqUnit.assertEquals("getUserSid should always return the same value (again)", sid, sid3);
// Compare it to the value from the "whoami" command.
child_process.exec("%SystemRoot%\\System32\\whoami.exe /user", function (err, stdout, stderr) {
if (err) {
jqUnit.fail(err);
}
fluid.log("whoami:", stdout, stderr);
jqUnit.assertTrue("SID should match the whoami command output", stdout.trim().endsWith(sid));
jqUnit.start();
});
});
jqUnit.test("testing hexToGuid", function () {
jqUnit.expect(2);
var expect = "01234567-89ab-cdef-0123-456789abcdef";
var guid1 = gpii.windows.userListeners.hexToGuid("0123456789abcdef0123456789abcdef");
jqUnit.assertEquals("hex string should produce the expected GUID (32 chars)", expect, guid1);
var guid2 =
gpii.windows.userListeners.hexToGuid("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef");
jqUnit.assertEquals("hex string should produce the expected GUID (over 32 chars)", expect, guid2);
jqUnit.expectFrameworkDiagnostic("hexToGuid should fails with a short string (16 chars)", function () {
gpii.windows.userListeners.hexToGuid("0123456789abcdef");
}, "hexToGuid wants a longer string");
});
jqUnit.test("Testing getUserId", function () {
// Windows Account SID
var userIdResult = gpii.windows.userListeners.getUserId("userid");
jqUnit.assertEquals("getUserId(userid) should return the user's SID", gpii.windows.getUserSid(), userIdResult);
// Windows username
var usernameResult = gpii.windows.userListeners.getUserId("username");
jqUnit.assertEquals("getUserId(username) should return the user's username", os.userInfo().username, usernameResult);
// File content
var testFile = path.join(os.tmpdir(), "gpii-username-test" + Math.random());
teardowns.push(function () {
fs.unlinkSync(testFile);
});
var expectFileResult = "test-userid" + Math.random();
fs.writeFileSync(testFile, expectFileResult);
var fileResult = gpii.windows.userListeners.getUserId("file:" + testFile);
jqUnit.assertEquals("getUserId(file) should return the correct value", expectFileResult, fileResult);
var testEnvFile = path.join("%TEMP%", path.basename(testFile));
var fileEnvResult = gpii.windows.userListeners.getUserId("file:" + testEnvFile);
jqUnit.assertEquals("getUserId(file) should return the correct value", expectFileResult, fileEnvResult);
// File content (no file)
var noFileResult = gpii.windows.userListeners.getUserId("file:c:\\not\\exists");
jqUnit.assertEquals("getUserId(no file) should return the correct value", null, noFileResult);
// Registry value
var baseKey = "HKEY_CURRENT_USER";
var subKey = "Software\\gpii-temp";
var valueName = "username-test";
var userValue = "test-userid" + Math.random();
gpii.windows.writeRegistryKey(baseKey, subKey, valueName, userValue, "REG_SZ");
teardowns.push(function () {
if (subKey.endsWith("gpii-temp")) {
gpii.windows.deleteRegistryKey(baseKey, subKey);
}
});
fluid.each(["reg:", "regkey:"], function (prefix) {
var expectedValue = prefix === "reg:"
? userValue
: ("gpiiKey:" + userValue);
var regResult = gpii.windows.userListeners.getUserId(prefix + baseKey + "\\" + subKey + "\\" + valueName);
jqUnit.assertEquals("getUserId(file) should return the correct value", expectedValue, regResult);
// Abbreviated base key
var regResult2 = gpii.windows.userListeners.getUserId(prefix + "HKCU\\" + subKey + "\\" + valueName);
jqUnit.assertEquals("getUserId(file) should return the correct value", expectedValue, regResult2);
// Non existing registry key
var regResult3 = gpii.windows.userListeners.getUserId(prefix + "HKCU\\gpii\\does\\not\\exist");
jqUnit.assertEquals("getUserId(file) should return the correct value", null, regResult3);
});
});
jqUnit.test("testing blocked user name matching", function () {
var tests = [
{
blockedUsers: [],
usernames: {
"empty1": false,
"empty2": false
}
},
{
blockedUsers: [ "one", "*two", "three*", "*four*" ],
usernames: {
"one": true,
"two": true,
"three": true,
"four": true,
"a_one": false,
"a_two": true,
"a_three": false,
"a_four": true,
"one_b": false,
"two_b": false,
"three_b": true,
"four_b": true,
"a_one_b": false,
"a_two_b": false,
"a_three_b": false,
"a_four_b": true,
"xyz": false
}
},
{
blockedUsers: [ "one*two", "*three*four", "five*six*", "*seven*eight*" ],
usernames: {
"one_x_two": true,
"three_x_four": true,
"five_x_six": true,
"seven_x_eight": true,
"a_one_x_two": false,
"a_three_x_four": true,
"a_five_x_six": false,
"a_seven_x_eight": true,
"one_x_two_b": false,
"three_x_four_b": false,
"five_x_six_b": true,
"seven_x_eight_b": true,
"a_one_x_two_b": false,
"a_three_x_four_b": false,
"a_five_x_six_b": false,
"a_seven_x_eight_b": true
}
},
{
blockedUsers: [ "on?", "t?o", "?hree", "f?ur", "?iv?", "si?*", "s?v*" ],
usernames: {
"one": true,
"two": true,
"three": true,
"four": true,
"five": true,
"six": true,
"seven": true,
"eight": false
}
}
];
fluid.each(tests, function (test) {
fluid.each(test.usernames, function (expected, username) {
var result = gpii.windows.userListeners.checkBlockedUser(test.blockedUsers, username);
jqUnit.assertEquals("blockedUser " + username, expected, result);
});
});
});
jqUnit.asyncTest("testing blocked local accounts", function () {
// Create an instance with the current user being a blocked user
var windowsLogin = gpii.tests.userListener.windowsLogin({
config: {
blockedUsers: [os.userInfo().username]
}
});
jqUnit.expect(2);
windowsLogin.getGpiiKey = function () {
return fluid.promise().resolve("getGpiiKey");
};
var blockedPromise = gpii.windows.userListeners.startWindowsLogin(windowsLogin);
jqUnit.assertTrue("startWindowsLogin should return a promise", fluid.isPromise(blockedPromise));
blockedPromise.then(function () {
jqUnit.fail("startWindowsLogin should not resolve");
}, function (reason) {
jqUnit.assertEquals("startWindowsLogin should reject with 'blocked'", "blocked", reason);
jqUnit.start();
});
});
jqUnit.asyncTest("testing getGpiiKey", function () {
var windowsLogin = gpii.tests.userListener.windowsLogin({
config: {
userIdSource: "userid"
}
});
jqUnit.expect(2);
var sid = gpii.windows.getUserSid();
var expectedKey = "01234567-89ab-cdef-0123-456789abcdef";
var sign = function (payload) {
jqUnit.assertEquals("signing function should be called with the current SID", sid, payload);
return fluid.toPromise("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef");
};
gpii.windows.userListeners.getGpiiKey(windowsLogin, sign).then(function (key) {
jqUnit.assertEquals("getGpiiKey should resolve with the expected key", expectedKey, key);
jqUnit.start();
});
});
jqUnit.asyncTest("testing getGpiiKey (got a gpiiKey)", function () {
var gpiiKey = "test-key" + Math.random();
var baseKey = "HKEY_CURRENT_USER";
var subKey = "Software\\gpii-temp";
var valueName = "username-test";
var userValue = gpiiKey;
gpii.windows.writeRegistryKey(baseKey, subKey, valueName, userValue, "REG_SZ");
teardowns.push(function () {
if (subKey.endsWith("gpii-temp")) {
gpii.windows.deleteRegistryKey(baseKey, subKey);
}
});
var windowsLogin = gpii.tests.userListener.windowsLogin({
config: {
userIdSource: path.join("regkey:" + baseKey, subKey, valueName)
}
});
var sign = function () {
jqUnit.fail("signing function should not be called for a gpiiKey");
return fluid.promise().reject();
};
gpii.windows.userListeners.getGpiiKey(windowsLogin, sign).then(function (key) {
jqUnit.assertEquals("getGpiiKey should resolve with the expected key", gpiiKey, key);
jqUnit.start();
}, fluid.fail);
});
jqUnit.asyncTest("testing getGpiiKey, with blocked user id", function () {
var testFile = path.join(os.tmpdir(), "gpii-username-test" + Math.random());
teardowns.push(function () {
fs.unlinkSync(testFile);
});
fs.writeFileSync(testFile, "blocked-user");
var windowsLogin = gpii.tests.userListener.windowsLogin({
config: {
userIdSource: "file:" + testFile,
blockedUsers: [ "blocked-*" ]
}
});
jqUnit.expect(0);
var sign = function () {
jqUnit.fail("sign function should not be called for a blocked user id");
};
gpii.windows.userListeners.getGpiiKey(windowsLogin, sign).then(function () {
jqUnit.fail("getGpiiKey should not resolve");
}, jqUnit.start());
});
| GPII-4397: Fixed user login texts to recognised lower cased marker
| gpii/node_modules/userListeners/test/windowsLoginTests.js | GPII-4397: Fixed user login texts to recognised lower cased marker | <ide><path>pii/node_modules/userListeners/test/windowsLoginTests.js
<ide> fluid.each(["reg:", "regkey:"], function (prefix) {
<ide> var expectedValue = prefix === "reg:"
<ide> ? userValue
<del> : ("gpiiKey:" + userValue);
<add> : ("gpiikey:" + userValue);
<ide>
<ide> var regResult = gpii.windows.userListeners.getUserId(prefix + baseKey + "\\" + subKey + "\\" + valueName);
<ide> jqUnit.assertEquals("getUserId(file) should return the correct value", expectedValue, regResult); |
|
Java | apache-2.0 | 66e07b64d861965ef15840c3506085a39b207947 | 0 | dropwizard/metrics,dropwizard/metrics,dropwizard/metrics | package com.codahale.metrics.jetty9;
import com.codahale.metrics.MetricRegistry;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
public class InstrumentedHandlerTest {
private final HttpClient client = new HttpClient();
private final MetricRegistry registry = new MetricRegistry();
private final Server server = new Server();
private final ServerConnector connector = new ServerConnector(server);
private final InstrumentedHandler handler = new InstrumentedHandler(registry);
@Before
public void setUp() throws Exception {
handler.setName("handler");
handler.setHandler(new TestHandler());
server.addConnector(connector);
server.setHandler(handler);
server.start();
client.start();
}
@After
public void tearDown() throws Exception {
server.stop();
client.stop();
}
@Test
public void hasAName() throws Exception {
assertThat(handler.getName())
.isEqualTo("handler");
}
@Test
public void createsMetricsForTheHandler() throws Exception {
final ContentResponse response = client.GET(uri("/hello"));
assertThat(response.getStatus())
.isEqualTo(404);
assertThat(registry.getNames())
.containsOnly(
MetricRegistry.name(TestHandler.class, "handler.1xx-responses"),
MetricRegistry.name(TestHandler.class, "handler.2xx-responses"),
MetricRegistry.name(TestHandler.class, "handler.3xx-responses"),
MetricRegistry.name(TestHandler.class, "handler.4xx-responses"),
MetricRegistry.name(TestHandler.class, "handler.5xx-responses"),
MetricRegistry.name(TestHandler.class, "handler.percent-4xx-1m"),
MetricRegistry.name(TestHandler.class, "handler.percent-4xx-5m"),
MetricRegistry.name(TestHandler.class, "handler.percent-4xx-15m"),
MetricRegistry.name(TestHandler.class, "handler.percent-5xx-1m"),
MetricRegistry.name(TestHandler.class, "handler.percent-5xx-5m"),
MetricRegistry.name(TestHandler.class, "handler.percent-5xx-15m"),
MetricRegistry.name(TestHandler.class, "handler.requests"),
MetricRegistry.name(TestHandler.class, "handler.active-suspended"),
MetricRegistry.name(TestHandler.class, "handler.async-dispatches"),
MetricRegistry.name(TestHandler.class, "handler.async-timeouts"),
MetricRegistry.name(TestHandler.class, "handler.get-requests"),
MetricRegistry.name(TestHandler.class, "handler.put-requests"),
MetricRegistry.name(TestHandler.class, "handler.active-dispatches"),
MetricRegistry.name(TestHandler.class, "handler.trace-requests"),
MetricRegistry.name(TestHandler.class, "handler.other-requests"),
MetricRegistry.name(TestHandler.class, "handler.connect-requests"),
MetricRegistry.name(TestHandler.class, "handler.dispatches"),
MetricRegistry.name(TestHandler.class, "handler.head-requests"),
MetricRegistry.name(TestHandler.class, "handler.post-requests"),
MetricRegistry.name(TestHandler.class, "handler.options-requests"),
MetricRegistry.name(TestHandler.class, "handler.active-requests"),
MetricRegistry.name(TestHandler.class, "handler.delete-requests"),
MetricRegistry.name(TestHandler.class, "handler.move-requests")
);
}
@Test
public void responseTimesAreRecordedForBlockingResponses() throws Exception {
final ContentResponse response = client.GET(uri("/blocking"));
assertThat(response.getStatus())
.isEqualTo(200);
assertResponseTimesValid();
}
@Test
@Ignore("flaky on virtual machines")
public void responseTimesAreRecordedForAsyncResponses() throws Exception {
final ContentResponse response = client.GET(uri("/async"));
assertThat(response.getStatus())
.isEqualTo(200);
assertResponseTimesValid();
}
private void assertResponseTimesValid() {
assertThat(registry.getMeters().get(metricName() + ".2xx-responses")
.getCount()).isGreaterThan(0L);
assertThat(registry.getTimers().get(metricName() + ".get-requests")
.getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1));
assertThat(registry.getTimers().get(metricName() + ".requests")
.getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1));
}
private String uri(String path) {
return "http://localhost:" + connector.getLocalPort() + path;
}
private String metricName() {
return MetricRegistry.name(TestHandler.class.getName(), "handler");
}
/**
* test handler.
* <p>
* Supports
* <p>
* /blocking - uses the standard servlet api
* /async - uses the 3.1 async api to complete the request
* <p>
* all other requests will return 404
*/
private static class TestHandler extends AbstractHandler {
@Override
public void handle(
String path,
Request request,
final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse
) throws IOException, ServletException {
switch (path) {
case "/blocking":
request.setHandled(true);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
httpServletResponse.setStatus(200);
httpServletResponse.setContentType("text/plain");
httpServletResponse.getWriter().write("some content from the blocking request\n");
break;
case "/async":
request.setHandled(true);
final AsyncContext context = request.startAsync();
Thread t = new Thread(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
httpServletResponse.setStatus(200);
httpServletResponse.setContentType("text/plain");
final ServletOutputStream servletOutputStream;
try {
servletOutputStream = httpServletResponse.getOutputStream();
servletOutputStream.setWriteListener(
new WriteListener() {
@Override
public void onWritePossible() throws IOException {
servletOutputStream.write("some content from the async\n"
.getBytes(StandardCharsets.UTF_8));
context.complete();
}
@Override
public void onError(Throwable throwable) {
context.complete();
}
}
);
} catch (IOException e) {
context.complete();
}
});
t.start();
break;
default:
break;
}
}
}
}
| metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHandlerTest.java | package com.codahale.metrics.jetty9;
import com.codahale.metrics.MetricRegistry;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
public class InstrumentedHandlerTest {
private final HttpClient client = new HttpClient();
private final MetricRegistry registry = new MetricRegistry();
private final Server server = new Server();
private final ServerConnector connector = new ServerConnector(server);
private final InstrumentedHandler handler = new InstrumentedHandler(registry);
@Before
public void setUp() throws Exception {
handler.setName("handler");
handler.setHandler(new TestHandler());
server.addConnector(connector);
server.setHandler(handler);
server.start();
client.start();
}
@After
public void tearDown() throws Exception {
server.stop();
client.stop();
}
@Test
public void hasAName() throws Exception {
assertThat(handler.getName())
.isEqualTo("handler");
}
@Test
public void createsMetricsForTheHandler() throws Exception {
final ContentResponse response = client.GET(uri("/hello"));
assertThat(response.getStatus())
.isEqualTo(404);
assertThat(registry.getNames())
.containsOnly(
MetricRegistry.name(TestHandler.class, "handler.1xx-responses"),
MetricRegistry.name(TestHandler.class, "handler.2xx-responses"),
MetricRegistry.name(TestHandler.class, "handler.3xx-responses"),
MetricRegistry.name(TestHandler.class, "handler.4xx-responses"),
MetricRegistry.name(TestHandler.class, "handler.5xx-responses"),
MetricRegistry.name(TestHandler.class, "handler.percent-4xx-1m"),
MetricRegistry.name(TestHandler.class, "handler.percent-4xx-5m"),
MetricRegistry.name(TestHandler.class, "handler.percent-4xx-15m"),
MetricRegistry.name(TestHandler.class, "handler.percent-5xx-1m"),
MetricRegistry.name(TestHandler.class, "handler.percent-5xx-5m"),
MetricRegistry.name(TestHandler.class, "handler.percent-5xx-15m"),
MetricRegistry.name(TestHandler.class, "handler.requests"),
MetricRegistry.name(TestHandler.class, "handler.active-suspended"),
MetricRegistry.name(TestHandler.class, "handler.async-dispatches"),
MetricRegistry.name(TestHandler.class, "handler.async-timeouts"),
MetricRegistry.name(TestHandler.class, "handler.get-requests"),
MetricRegistry.name(TestHandler.class, "handler.put-requests"),
MetricRegistry.name(TestHandler.class, "handler.active-dispatches"),
MetricRegistry.name(TestHandler.class, "handler.trace-requests"),
MetricRegistry.name(TestHandler.class, "handler.other-requests"),
MetricRegistry.name(TestHandler.class, "handler.connect-requests"),
MetricRegistry.name(TestHandler.class, "handler.dispatches"),
MetricRegistry.name(TestHandler.class, "handler.head-requests"),
MetricRegistry.name(TestHandler.class, "handler.post-requests"),
MetricRegistry.name(TestHandler.class, "handler.options-requests"),
MetricRegistry.name(TestHandler.class, "handler.active-requests"),
MetricRegistry.name(TestHandler.class, "handler.delete-requests"),
MetricRegistry.name(TestHandler.class, "handler.move-requests")
);
}
@Test
public void responseTimesAreRecordedForBlockingResponses() throws Exception {
final ContentResponse response = client.GET(uri("/blocking"));
assertThat(response.getStatus())
.isEqualTo(200);
assertResponseTimesValid();
}
@Test
public void responseTimesAreRecordedForAsyncResponses() throws Exception {
final ContentResponse response = client.GET(uri("/async"));
assertThat(response.getStatus())
.isEqualTo(200);
assertResponseTimesValid();
}
private void assertResponseTimesValid() {
assertThat(registry.getMeters().get(metricName() + ".2xx-responses")
.getCount()).isGreaterThan(0L);
assertThat(registry.getTimers().get(metricName() + ".get-requests")
.getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1));
assertThat(registry.getTimers().get(metricName() + ".requests")
.getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1));
}
private String uri(String path) {
return "http://localhost:" + connector.getLocalPort() + path;
}
private String metricName() {
return MetricRegistry.name(TestHandler.class.getName(), "handler");
}
/**
* test handler.
* <p>
* Supports
* <p>
* /blocking - uses the standard servlet api
* /async - uses the 3.1 async api to complete the request
* <p>
* all other requests will return 404
*/
private static class TestHandler extends AbstractHandler {
@Override
public void handle(
String path,
Request request,
final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse
) throws IOException, ServletException {
switch (path) {
case "/blocking":
request.setHandled(true);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
httpServletResponse.setStatus(200);
httpServletResponse.setContentType("text/plain");
httpServletResponse.getWriter().write("some content from the blocking request\n");
break;
case "/async":
request.setHandled(true);
final AsyncContext context = request.startAsync();
Thread t = new Thread(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
httpServletResponse.setStatus(200);
httpServletResponse.setContentType("text/plain");
final ServletOutputStream servletOutputStream;
try {
servletOutputStream = httpServletResponse.getOutputStream();
servletOutputStream.setWriteListener(
new WriteListener() {
@Override
public void onWritePossible() throws IOException {
servletOutputStream.write("some content from the async\n"
.getBytes(StandardCharsets.UTF_8));
context.complete();
}
@Override
public void onError(Throwable throwable) {
context.complete();
}
}
);
} catch (IOException e) {
context.complete();
}
});
t.start();
break;
default:
break;
}
}
}
}
| chore: Ignore flaky tests for Jetty's InstrumentedHandler
| metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHandlerTest.java | chore: Ignore flaky tests for Jetty's InstrumentedHandler | <ide><path>etrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHandlerTest.java
<ide> import org.eclipse.jetty.server.handler.AbstractHandler;
<ide> import org.junit.After;
<ide> import org.junit.Before;
<add>import org.junit.Ignore;
<ide> import org.junit.Test;
<ide>
<ide> import javax.servlet.AsyncContext;
<ide> }
<ide>
<ide> @Test
<add> @Ignore("flaky on virtual machines")
<ide> public void responseTimesAreRecordedForAsyncResponses() throws Exception {
<ide>
<ide> final ContentResponse response = client.GET(uri("/async")); |
|
Java | mit | d837fceaeb381fe5b89c3a89a9efb10438eb6c01 | 0 | jenkinsci/starteam-plugin,ahunigel/starteam-plugin,jenkinsci/starteam-plugin,ahunigel/starteam-plugin | package hudson.plugins.starteam;
import hudson.Util;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
* Builds <tt>changelog.xml</tt> for {@link StarTeamSCM}.
*
* Remove use of deprecated classes.
*
* @author Eric D. Broyles
* @author Steve Favez <[email protected]>
*/
public final class StarTeamChangeLogBuilder {
/**
* Stores the history objects to the output stream as xml.
* <p>
* Current version supports a format like the following:
*
* <pre>
* <?xml version='1.0' encoding='UTF-8'?>
* <changelog>
* <entry>
* <revisionNumber>73</revisionNumber>
* <date>2008-06-23 09:46:27</date>
* <message>Checkin message</message>
* <user>Author Name</user>
* </entry>
* </changelog>
*
* </pre>
*
* </p>
*
* @param outputStream
* the stream to write to
* @param changeSet
* the history objects to store
* @throws IOException
*
*/
public static boolean writeChangeLog(OutputStream outputStream,
StarTeamChangeSet changeSet)
throws IOException {
GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss");
dateFormat.setCalendar(cal);
dateFormat.setLenient(false);
OutputStreamWriter writer = new OutputStreamWriter(outputStream,
Charset.forName("UTF-8"));
PrintWriter printwriter = new PrintWriter( writer ) ;
printwriter.println("<?xml version='1.0' encoding='UTF-8'?>");
printwriter.println("<changelog>");
for (StarTeamChangeLogEntry change : changeSet.getChanges()) {
writeEntry(dateFormat, printwriter, change);
}
printwriter.println("</changelog>");
printwriter.close();
return true;
}
/**
* @param dateFormat
* @param printwriter
* @param change
*/
private static void writeEntry(SimpleDateFormat dateFormat,
PrintWriter printwriter, StarTeamChangeLogEntry change) {
printwriter.println("\t<entry>");
printwriter.println("\t\t<fileName>" + change.getFileName() + "</fileName>");
printwriter.println("\t\t<revisionNumber>" + change.getRevisionNumber()
+ "</revisionNumber>");
java.util.Date aDate = change.getDate();
printwriter.println("\t\t<date>"
+ Util.xmlEscape(dateFormat.format(aDate)) + "</date>");
printwriter.println("\t\t<message>"
+ Util.xmlEscape(change.getMsg()) + "</message>");
printwriter.println("\t\t<user>"
+ Util.xmlEscape(change.getUsername())
+ "</user>");
printwriter.println("\t\t<changeType>"
+ Util.xmlEscape(change.getChangeType())
+ "</changeType>");
printwriter.println("\t</entry>");
}
}
| src/main/java/hudson/plugins/starteam/StarTeamChangeLogBuilder.java | package hudson.plugins.starteam;
import hudson.Util;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
* Builds <tt>changelog.xml</tt> for {@link StarTeamSCM}.
*
* Remove use of deprecated classes.
*
* @author Eric D. Broyles
* @author Steve Favez <[email protected]>
*/
public final class StarTeamChangeLogBuilder {
/**
* Stores the history objects to the output stream as xml.
* <p>
* Current version supports a format like the following:
*
* <pre>
* <?xml version='1.0' encoding='UTF-8'?>
* <changelog>
* <entry>
* <revisionNumber>73</revisionNumber>
* <date>2008-06-23 09:46:27</date>
* <message>Checkin message</message>
* <user>Author Name</user>
* </entry>
* </changelog>
*
* </pre>
*
* </p>
*
* @param aOutputStream
* the stream to write to
* @param aChanges
* the history objects to store
* @throws IOException
*
*/
public static boolean writeChangeLog(OutputStream outputStream,
StarTeamChangeSet changeSet)
throws IOException {
GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss");
dateFormat.setCalendar(cal);
dateFormat.setLenient(false);
OutputStreamWriter writer = new OutputStreamWriter(outputStream,
Charset.forName("UTF-8"));
PrintWriter printwriter = new PrintWriter( writer ) ;
printwriter.println("<?xml version='1.0' encoding='UTF-8'?>");
printwriter.println("<changelog>");
for (StarTeamChangeLogEntry change : changeSet.getChanges()) {
writeEntry(dateFormat, printwriter, change);
}
printwriter.println("</changelog>");
printwriter.close();
return true;
}
/**
* @param dateFormat
* @param printwriter
* @param change
*/
private static void writeEntry(SimpleDateFormat dateFormat,
PrintWriter printwriter, StarTeamChangeLogEntry change) {
printwriter.println("\t<entry>");
printwriter.println("\t\t<fileName>" + change.getFileName() + "</fileName>");
printwriter.println("\t\t<revisionNumber>" + change.getRevisionNumber()
+ "</revisionNumber>");
java.util.Date aDate = change.getDate();
printwriter.println("\t\t<date>"
+ Util.xmlEscape(dateFormat.format(aDate)) + "</date>");
printwriter.println("\t\t<message>"
+ Util.xmlEscape(change.getMsg()) + "</message>");
printwriter.println("\t\t<user>"
+ change.getUsername()
+ "</user>");
printwriter.println("\t\t<changeType>"
+ change.getChangeType()
+ "</changeType>");
printwriter.println("\t</entry>");
}
}
| cleanup | src/main/java/hudson/plugins/starteam/StarTeamChangeLogBuilder.java | cleanup | <ide><path>rc/main/java/hudson/plugins/starteam/StarTeamChangeLogBuilder.java
<ide> *
<ide> * </p>
<ide> *
<del> * @param aOutputStream
<add> * @param outputStream
<ide> * the stream to write to
<del> * @param aChanges
<add> * @param changeSet
<ide> * the history objects to store
<ide> * @throws IOException
<ide> *
<ide> printwriter.println("\t\t<message>"
<ide> + Util.xmlEscape(change.getMsg()) + "</message>");
<ide> printwriter.println("\t\t<user>"
<del> + change.getUsername()
<add> + Util.xmlEscape(change.getUsername())
<ide> + "</user>");
<ide> printwriter.println("\t\t<changeType>"
<del> + change.getChangeType()
<add> + Util.xmlEscape(change.getChangeType())
<ide> + "</changeType>");
<ide> printwriter.println("\t</entry>");
<ide> } |
|
Java | apache-2.0 | ead213ad654662e916730e53c7935c852ce4c458 | 0 | speedment/speedment,speedment/speedment | runtime-parent/runtime-core/src/main/java/com/speedment/runtime/core/abstracts/AbstractDbmsOperationHandler.java | /*
*
* Copyright (c) 2006-2019, Speedment, 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.
*/
package com.speedment.runtime.core.abstracts;
import com.speedment.common.injector.State;
import com.speedment.common.injector.annotation.ExecuteBefore;
import com.speedment.common.logger.Logger;
import com.speedment.common.logger.LoggerManager;
import com.speedment.runtime.config.Dbms;
import com.speedment.runtime.core.ApplicationBuilder.LogType;
import com.speedment.runtime.core.component.DbmsHandlerComponent;
import com.speedment.runtime.core.component.connectionpool.ConnectionPoolComponent;
import com.speedment.runtime.core.component.transaction.TransactionComponent;
import com.speedment.runtime.core.db.AsynchronousQueryResult;
import com.speedment.runtime.core.db.DbmsOperationHandler;
import com.speedment.runtime.core.db.SqlFunction;
import com.speedment.runtime.core.exception.SpeedmentException;
import com.speedment.runtime.core.internal.db.AsynchronousQueryResultImpl;
import com.speedment.runtime.core.internal.db.ConnectionInfo;
import com.speedment.runtime.core.internal.manager.sql.SqlDeleteStatement;
import com.speedment.runtime.core.internal.manager.sql.SqlInsertStatement;
import com.speedment.runtime.core.internal.manager.sql.SqlUpdateStatement;
import com.speedment.runtime.core.manager.sql.SqlStatement;
import com.speedment.runtime.core.stream.parallel.ParallelStrategy;
import com.speedment.runtime.field.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.LongConsumer;
import java.util.stream.Stream;
import static com.speedment.common.invariant.NullUtil.requireNonNulls;
import static com.speedment.runtime.core.util.DatabaseUtil.dbmsTypeOf;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
/**
* Abstract base class for {@link DbmsOperationHandler}-implementations.
*
* @author Per Minborg
* @author Emil Forslund
*
* @deprecated Use the StandardDbmsOperationHandler instead
*/
@Deprecated
public abstract class AbstractDbmsOperationHandler implements DbmsOperationHandler {
private static final int INITIAL_RETRY_COUNT = 5;
private static final Logger LOGGER = LoggerManager.getLogger(AbstractDbmsOperationHandler.class);
private static final Logger LOGGER_PERSIST = LoggerManager.getLogger(LogType.PERSIST.getLoggerName());
private static final Logger LOGGER_UPDATE = LoggerManager.getLogger(LogType.UPDATE.getLoggerName());
private static final Logger LOGGER_REMOVE = LoggerManager.getLogger(LogType.REMOVE.getLoggerName());
private static final Logger LOGGER_SQL_RETRY = LoggerManager.getLogger(LogType.SQL_RETRY.getLoggerName());
private final ConnectionPoolComponent connectionPoolComponent;
private final DbmsHandlerComponent dbmsHandlerComponent;
private final TransactionComponent transactionComponent;
private final AtomicBoolean closed;
protected AbstractDbmsOperationHandler(
final ConnectionPoolComponent connectionPoolComponent,
final DbmsHandlerComponent dbmsHandlerComponent,
final TransactionComponent transactionComponent
) {
this.connectionPoolComponent = requireNonNull(connectionPoolComponent);
this.dbmsHandlerComponent = requireNonNull(dbmsHandlerComponent);
this.transactionComponent = requireNonNull(transactionComponent);
closed = new AtomicBoolean();
}
@Override
public <T> Stream<T> executeQuery(Dbms dbms, String sql, List<?> values, SqlFunction<ResultSet, T> rsMapper) {
requireNonNulls(sql, values, rsMapper);
assertNotClosed();
final ConnectionInfo connectionInfo = new ConnectionInfo(dbms, connectionPoolComponent, transactionComponent);
try (
final PreparedStatement ps = connectionInfo.connection().prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY)) {
configureSelect(ps);
connectionInfo.ifNotInTransaction(c -> c.setAutoCommit(false));
try {
int i = 1;
for (final Object o : values) {
ps.setObject(i++, o);
}
try (final ResultSet rs = ps.executeQuery()) {
configureSelect(rs);
// Todo: Make a transparent stream with closeHandler added.
final Stream.Builder<T> streamBuilder = Stream.builder();
while (rs.next()) {
streamBuilder.add(rsMapper.apply(rs));
}
return streamBuilder.build();
}
} finally {
connectionInfo.ifNotInTransaction(Connection::commit);
}
} catch (final SQLException sqle) {
LOGGER.error(sqle, "Error querying " + sql);
throw new SpeedmentException(sqle);
} finally {
closeQuietly(connectionInfo::close);
}
}
@Override
public <T> AsynchronousQueryResult<T> executeQueryAsync(
final Dbms dbms,
final String sql,
final List<?> values,
final SqlFunction<ResultSet, T> rsMapper,
final ParallelStrategy parallelStrategy
) {
assertNotClosed();
return new AsynchronousQueryResultImpl<>(
sql,
values,
rsMapper,
() -> new ConnectionInfo(dbms, connectionPoolComponent, transactionComponent),
parallelStrategy,
this::configureSelect,
this::configureSelect
);
}
@Override
public <ENTITY> void executeInsert(Dbms dbms, String sql, List<?> values, Collection<Field<ENTITY>> generatedKeyFields, Consumer<List<Long>> generatedKeyConsumer) throws SQLException {
logOperation(LOGGER_PERSIST, sql, values);
final SqlInsertStatement sqlUpdateStatement = new SqlInsertStatement(sql, values, new ArrayList<>(generatedKeyFields), generatedKeyConsumer);
execute(dbms, singletonList(sqlUpdateStatement));
}
@Override
public void executeUpdate(Dbms dbms, String sql, List<?> values) throws SQLException {
logOperation(LOGGER_UPDATE, sql, values);
final SqlUpdateStatement sqlUpdateStatement = new SqlUpdateStatement(sql, values);
execute(dbms, singletonList(sqlUpdateStatement));
}
@Override
public void executeDelete(Dbms dbms, String sql, List<?> values) throws SQLException {
logOperation(LOGGER_REMOVE, sql, values);
final SqlDeleteStatement sqlDeleteStatement = new SqlDeleteStatement(sql, values);
execute(dbms, singletonList(sqlDeleteStatement));
}
private void logOperation(Logger logger, final String sql, final List<?> values) {
logger.debug("%s, values:%s", sql, values);
}
private void execute(Dbms dbms, List<? extends SqlStatement> sqlStatementList) throws SQLException {
final ConnectionInfo connectionInfo = new ConnectionInfo(dbms, connectionPoolComponent, transactionComponent);
if (connectionInfo.isInTransaction()) {
executeInTransaction(dbms, connectionInfo.connection(), sqlStatementList);
} else {
executeNotInTransaction(dbms, connectionInfo.connection(), sqlStatementList);
}
}
// Todo: Rewrite the method below.
private void executeNotInTransaction(
final Dbms dbms,
final Connection conn,
final List<? extends SqlStatement> sqlStatementList
) throws SQLException {
requireNonNull(dbms);
requireNonNull(conn);
requireNonNull(sqlStatementList);
assertNotClosed();
int retryCount = INITIAL_RETRY_COUNT;
boolean transactionCompleted = false;
do {
final AtomicReference<SqlStatement> lastSqlStatement = new AtomicReference<>();
try {
conn.setAutoCommit(false);
executeSqlStatementList(sqlStatementList, lastSqlStatement, dbms, conn);
conn.commit();
conn.close();
transactionCompleted = true;
} catch (SQLException sqlEx) {
if (retryCount < INITIAL_RETRY_COUNT) {
LOGGER_SQL_RETRY.error("SqlStatementList: " + sqlStatementList);
LOGGER_SQL_RETRY.error("SQL: " + lastSqlStatement.get());
LOGGER_SQL_RETRY.error(sqlEx, sqlEx.getMessage());
}
final String sqlState = sqlEx.getSQLState();
if ("08S01".equals(sqlState) || "40001".equals(sqlState)) {
retryCount--;
} else {
throw sqlEx; // Finally will be executed...
}
} finally {
if (!transactionCompleted) {
try {
// If we got here the transaction should be rolled back, as not
// all work has been done
conn.rollback();
} catch (SQLException sqlEx) {
// If we got an exception here, something
// pretty serious is going on
LOGGER.error(sqlEx, "Rollback error! connection:" + sqlEx.getMessage());
retryCount = 0;
} finally {
conn.close();
}
}
}
} while (!transactionCompleted && (retryCount > 0));
if (transactionCompleted) {
postSuccessfulTransaction(sqlStatementList);
}
}
private void executeInTransaction(
final Dbms dbms,
final Connection conn,
final List<? extends SqlStatement> sqlStatementList
) throws SQLException {
requireNonNull(dbms);
requireNonNull(conn);
requireNonNull(sqlStatementList);
assertNotClosed();
final AtomicReference<SqlStatement> lastSqlStatement = new AtomicReference<>();
executeSqlStatementList(sqlStatementList, lastSqlStatement, dbms, conn);
postSuccessfulTransaction(sqlStatementList);
}
private void executeSqlStatementList(List<? extends SqlStatement> sqlStatementList, AtomicReference<SqlStatement> lastSqlStatement, Dbms dbms, Connection conn) throws SQLException {
assertNotClosed();
for (final SqlStatement sqlStatement : sqlStatementList) {
lastSqlStatement.set(sqlStatement);
switch (sqlStatement.getType()) {
case INSERT: {
final SqlInsertStatement s = (SqlInsertStatement) sqlStatement;
handleSqlStatement(dbms, conn, s);
break;
}
case UPDATE: {
final SqlUpdateStatement s = (SqlUpdateStatement) sqlStatement;
handleSqlStatement(dbms, conn, s);
break;
}
case DELETE: {
final SqlDeleteStatement s = (SqlDeleteStatement) sqlStatement;
handleSqlStatement(dbms, conn, s);
break;
}
}
}
}
private void handleSqlStatement(Dbms dbms, Connection conn, SqlInsertStatement sqlStatement) throws SQLException {
assertNotClosed();
try (final PreparedStatement ps = conn.prepareStatement(sqlStatement.getSql(), Statement.RETURN_GENERATED_KEYS)) {
int i = 1;
for (Object o : sqlStatement.getValues()) {
ps.setObject(i++, o);
}
ps.executeUpdate();
handleGeneratedKeys(ps, sqlStatement::addGeneratedKey);
}
}
private void handleGeneratedKeys(PreparedStatement ps, LongConsumer longConsumer) throws SQLException {
try (final ResultSet generatedKeys = ps.getGeneratedKeys()) {
while (generatedKeys.next()) {
longConsumer.accept(generatedKeys.getLong(1));
//sqlStatement.addGeneratedKey(generatedKeys.getLong(1));
}
}
}
private void handleSqlStatement(Dbms dbms, Connection conn, SqlUpdateStatement sqlStatement) throws SQLException {
handleSqlStatementHelper(conn, sqlStatement);
}
private void handleSqlStatement(Dbms dbms, Connection conn, SqlDeleteStatement sqlStatement) throws SQLException {
handleSqlStatementHelper(conn, sqlStatement);
}
private void handleSqlStatementHelper(Connection conn, SqlStatement sqlStatement) throws SQLException {
assertNotClosed();
try (final PreparedStatement ps = conn.prepareStatement(sqlStatement.getSql(), Statement.NO_GENERATED_KEYS)) {
int i = 1;
for (Object o : sqlStatement.getValues()) {
ps.setObject(i++, o);
}
ps.executeUpdate();
}
}
private void postSuccessfulTransaction(List<? extends SqlStatement> sqlStatementList) {
sqlStatementList.stream()
.filter(SqlInsertStatement.class::isInstance)
.map(SqlInsertStatement.class::cast)
.forEach(SqlInsertStatement::notifyGeneratedKeyListener);
}
protected String encloseField(Dbms dbms, String fieldName) {
return dbmsTypeOf(dbmsHandlerComponent, dbms).getDatabaseNamingConvention().encloseField(fieldName);
}
@Override
public Clob createClob(Dbms dbms) throws SQLException {
return applyOnConnection(dbms, Connection::createClob);
}
@Override
public Blob createBlob(Dbms dbms) throws SQLException {
return applyOnConnection(dbms, Connection::createBlob);
}
@Override
public NClob createNClob(Dbms dbms) throws SQLException {
return applyOnConnection(dbms, Connection::createNClob);
}
@Override
public SQLXML createSQLXML(Dbms dbms) throws SQLException {
return applyOnConnection(dbms, Connection::createSQLXML);
}
@Override
public Array createArray(Dbms dbms, String typeName, Object[] elements) throws SQLException {
assertNotClosed();
try (final Connection connection = connectionPoolComponent.getConnection(dbms)) {
return connection.createArrayOf(typeName, elements);
}
}
@Override
public Struct createStruct(Dbms dbms, String typeName, Object[] attributes) throws SQLException {
assertNotClosed();
try (final Connection connection = connectionPoolComponent.getConnection(dbms)) {
return connection.createStruct(typeName, attributes);
}
}
private <T> T applyOnConnection(Dbms dbms, SqlFunction<Connection, T> mapper) throws SQLException {
assertNotClosed();
try (final Connection c = connectionPoolComponent.getConnection(dbms)) {
return mapper.apply(c);
}
}
@ExecuteBefore(State.STOPPED)
public void close() {
closed.set(true);
}
private void assertNotClosed() {
if (closed.get()) {
throw new IllegalStateException(
"The " + DbmsOperationHandler.class.getSimpleName() + " " +
getClass().getSimpleName() + " has been closed."
);
}
}
private interface ThrowingClosable {
void close() throws Exception;
}
private void closeQuietly(ThrowingClosable closeable) {
try {
closeable.close();
} catch (Exception e) {
LOGGER.warn(e);
}
}
}
| runtime-core: Remove AbstractDbmsOperationHandler, Fix #787
| runtime-parent/runtime-core/src/main/java/com/speedment/runtime/core/abstracts/AbstractDbmsOperationHandler.java | runtime-core: Remove AbstractDbmsOperationHandler, Fix #787 | <ide><path>untime-parent/runtime-core/src/main/java/com/speedment/runtime/core/abstracts/AbstractDbmsOperationHandler.java
<del>/*
<del> *
<del> * Copyright (c) 2006-2019, Speedment, Inc. All Rights Reserved.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License"); You may not
<del> * use this file except in compliance with the License. You may obtain a copy of
<del> * the License at:
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<del> * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
<del> * License for the specific language governing permissions and limitations under
<del> * the License.
<del> */
<del>package com.speedment.runtime.core.abstracts;
<del>
<del>import com.speedment.common.injector.State;
<del>import com.speedment.common.injector.annotation.ExecuteBefore;
<del>import com.speedment.common.logger.Logger;
<del>import com.speedment.common.logger.LoggerManager;
<del>import com.speedment.runtime.config.Dbms;
<del>import com.speedment.runtime.core.ApplicationBuilder.LogType;
<del>import com.speedment.runtime.core.component.DbmsHandlerComponent;
<del>import com.speedment.runtime.core.component.connectionpool.ConnectionPoolComponent;
<del>import com.speedment.runtime.core.component.transaction.TransactionComponent;
<del>import com.speedment.runtime.core.db.AsynchronousQueryResult;
<del>import com.speedment.runtime.core.db.DbmsOperationHandler;
<del>import com.speedment.runtime.core.db.SqlFunction;
<del>import com.speedment.runtime.core.exception.SpeedmentException;
<del>import com.speedment.runtime.core.internal.db.AsynchronousQueryResultImpl;
<del>import com.speedment.runtime.core.internal.db.ConnectionInfo;
<del>import com.speedment.runtime.core.internal.manager.sql.SqlDeleteStatement;
<del>import com.speedment.runtime.core.internal.manager.sql.SqlInsertStatement;
<del>import com.speedment.runtime.core.internal.manager.sql.SqlUpdateStatement;
<del>import com.speedment.runtime.core.manager.sql.SqlStatement;
<del>import com.speedment.runtime.core.stream.parallel.ParallelStrategy;
<del>import com.speedment.runtime.field.Field;
<del>
<del>import java.sql.*;
<del>import java.util.ArrayList;
<del>import java.util.Collection;
<del>import java.util.List;
<del>import java.util.concurrent.atomic.AtomicBoolean;
<del>import java.util.concurrent.atomic.AtomicReference;
<del>import java.util.function.Consumer;
<del>import java.util.function.LongConsumer;
<del>import java.util.stream.Stream;
<del>
<del>import static com.speedment.common.invariant.NullUtil.requireNonNulls;
<del>import static com.speedment.runtime.core.util.DatabaseUtil.dbmsTypeOf;
<del>import static java.util.Collections.singletonList;
<del>import static java.util.Objects.requireNonNull;
<del>
<del>/**
<del> * Abstract base class for {@link DbmsOperationHandler}-implementations.
<del> *
<del> * @author Per Minborg
<del> * @author Emil Forslund
<del> *
<del> * @deprecated Use the StandardDbmsOperationHandler instead
<del> */
<del>@Deprecated
<del>public abstract class AbstractDbmsOperationHandler implements DbmsOperationHandler {
<del>
<del> private static final int INITIAL_RETRY_COUNT = 5;
<del> private static final Logger LOGGER = LoggerManager.getLogger(AbstractDbmsOperationHandler.class);
<del> private static final Logger LOGGER_PERSIST = LoggerManager.getLogger(LogType.PERSIST.getLoggerName());
<del> private static final Logger LOGGER_UPDATE = LoggerManager.getLogger(LogType.UPDATE.getLoggerName());
<del> private static final Logger LOGGER_REMOVE = LoggerManager.getLogger(LogType.REMOVE.getLoggerName());
<del> private static final Logger LOGGER_SQL_RETRY = LoggerManager.getLogger(LogType.SQL_RETRY.getLoggerName());
<del>
<del>
<del>
<del> private final ConnectionPoolComponent connectionPoolComponent;
<del> private final DbmsHandlerComponent dbmsHandlerComponent;
<del> private final TransactionComponent transactionComponent;
<del> private final AtomicBoolean closed;
<del>
<del> protected AbstractDbmsOperationHandler(
<del> final ConnectionPoolComponent connectionPoolComponent,
<del> final DbmsHandlerComponent dbmsHandlerComponent,
<del> final TransactionComponent transactionComponent
<del> ) {
<del> this.connectionPoolComponent = requireNonNull(connectionPoolComponent);
<del> this.dbmsHandlerComponent = requireNonNull(dbmsHandlerComponent);
<del> this.transactionComponent = requireNonNull(transactionComponent);
<del> closed = new AtomicBoolean();
<del> }
<del>
<del> @Override
<del> public <T> Stream<T> executeQuery(Dbms dbms, String sql, List<?> values, SqlFunction<ResultSet, T> rsMapper) {
<del> requireNonNulls(sql, values, rsMapper);
<del> assertNotClosed();
<del>
<del> final ConnectionInfo connectionInfo = new ConnectionInfo(dbms, connectionPoolComponent, transactionComponent);
<del> try (
<del> final PreparedStatement ps = connectionInfo.connection().prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY)) {
<del> configureSelect(ps);
<del> connectionInfo.ifNotInTransaction(c -> c.setAutoCommit(false));
<del> try {
<del> int i = 1;
<del> for (final Object o : values) {
<del> ps.setObject(i++, o);
<del> }
<del> try (final ResultSet rs = ps.executeQuery()) {
<del> configureSelect(rs);
<del>
<del> // Todo: Make a transparent stream with closeHandler added.
<del> final Stream.Builder<T> streamBuilder = Stream.builder();
<del> while (rs.next()) {
<del> streamBuilder.add(rsMapper.apply(rs));
<del> }
<del> return streamBuilder.build();
<del> }
<del> } finally {
<del> connectionInfo.ifNotInTransaction(Connection::commit);
<del> }
<del> } catch (final SQLException sqle) {
<del> LOGGER.error(sqle, "Error querying " + sql);
<del> throw new SpeedmentException(sqle);
<del> } finally {
<del> closeQuietly(connectionInfo::close);
<del> }
<del> }
<del>
<del> @Override
<del> public <T> AsynchronousQueryResult<T> executeQueryAsync(
<del> final Dbms dbms,
<del> final String sql,
<del> final List<?> values,
<del> final SqlFunction<ResultSet, T> rsMapper,
<del> final ParallelStrategy parallelStrategy
<del> ) {
<del> assertNotClosed();
<del> return new AsynchronousQueryResultImpl<>(
<del> sql,
<del> values,
<del> rsMapper,
<del> () -> new ConnectionInfo(dbms, connectionPoolComponent, transactionComponent),
<del> parallelStrategy,
<del> this::configureSelect,
<del> this::configureSelect
<del> );
<del> }
<del>
<del> @Override
<del> public <ENTITY> void executeInsert(Dbms dbms, String sql, List<?> values, Collection<Field<ENTITY>> generatedKeyFields, Consumer<List<Long>> generatedKeyConsumer) throws SQLException {
<del> logOperation(LOGGER_PERSIST, sql, values);
<del> final SqlInsertStatement sqlUpdateStatement = new SqlInsertStatement(sql, values, new ArrayList<>(generatedKeyFields), generatedKeyConsumer);
<del> execute(dbms, singletonList(sqlUpdateStatement));
<del> }
<del>
<del> @Override
<del> public void executeUpdate(Dbms dbms, String sql, List<?> values) throws SQLException {
<del> logOperation(LOGGER_UPDATE, sql, values);
<del> final SqlUpdateStatement sqlUpdateStatement = new SqlUpdateStatement(sql, values);
<del> execute(dbms, singletonList(sqlUpdateStatement));
<del> }
<del>
<del> @Override
<del> public void executeDelete(Dbms dbms, String sql, List<?> values) throws SQLException {
<del> logOperation(LOGGER_REMOVE, sql, values);
<del> final SqlDeleteStatement sqlDeleteStatement = new SqlDeleteStatement(sql, values);
<del> execute(dbms, singletonList(sqlDeleteStatement));
<del> }
<del>
<del> private void logOperation(Logger logger, final String sql, final List<?> values) {
<del> logger.debug("%s, values:%s", sql, values);
<del> }
<del>
<del> private void execute(Dbms dbms, List<? extends SqlStatement> sqlStatementList) throws SQLException {
<del> final ConnectionInfo connectionInfo = new ConnectionInfo(dbms, connectionPoolComponent, transactionComponent);
<del> if (connectionInfo.isInTransaction()) {
<del> executeInTransaction(dbms, connectionInfo.connection(), sqlStatementList);
<del> } else {
<del> executeNotInTransaction(dbms, connectionInfo.connection(), sqlStatementList);
<del> }
<del> }
<del>
<del> // Todo: Rewrite the method below.
<del>
<del> private void executeNotInTransaction(
<del> final Dbms dbms,
<del> final Connection conn,
<del> final List<? extends SqlStatement> sqlStatementList
<del> ) throws SQLException {
<del> requireNonNull(dbms);
<del> requireNonNull(conn);
<del> requireNonNull(sqlStatementList);
<del>
<del> assertNotClosed();
<del> int retryCount = INITIAL_RETRY_COUNT;
<del> boolean transactionCompleted = false;
<del> do {
<del> final AtomicReference<SqlStatement> lastSqlStatement = new AtomicReference<>();
<del> try {
<del> conn.setAutoCommit(false);
<del> executeSqlStatementList(sqlStatementList, lastSqlStatement, dbms, conn);
<del> conn.commit();
<del> conn.close();
<del> transactionCompleted = true;
<del> } catch (SQLException sqlEx) {
<del> if (retryCount < INITIAL_RETRY_COUNT) {
<del> LOGGER_SQL_RETRY.error("SqlStatementList: " + sqlStatementList);
<del> LOGGER_SQL_RETRY.error("SQL: " + lastSqlStatement.get());
<del> LOGGER_SQL_RETRY.error(sqlEx, sqlEx.getMessage());
<del> }
<del>
<del> final String sqlState = sqlEx.getSQLState();
<del>
<del> if ("08S01".equals(sqlState) || "40001".equals(sqlState)) {
<del> retryCount--;
<del> } else {
<del> throw sqlEx; // Finally will be executed...
<del> }
<del> } finally {
<del>
<del> if (!transactionCompleted) {
<del> try {
<del> // If we got here the transaction should be rolled back, as not
<del> // all work has been done
<del> conn.rollback();
<del> } catch (SQLException sqlEx) {
<del> // If we got an exception here, something
<del> // pretty serious is going on
<del> LOGGER.error(sqlEx, "Rollback error! connection:" + sqlEx.getMessage());
<del> retryCount = 0;
<del> } finally {
<del> conn.close();
<del> }
<del> }
<del> }
<del> } while (!transactionCompleted && (retryCount > 0));
<del>
<del> if (transactionCompleted) {
<del> postSuccessfulTransaction(sqlStatementList);
<del> }
<del> }
<del>
<del> private void executeInTransaction(
<del> final Dbms dbms,
<del> final Connection conn,
<del> final List<? extends SqlStatement> sqlStatementList
<del> ) throws SQLException {
<del> requireNonNull(dbms);
<del> requireNonNull(conn);
<del> requireNonNull(sqlStatementList);
<del>
<del> assertNotClosed();
<del> final AtomicReference<SqlStatement> lastSqlStatement = new AtomicReference<>();
<del> executeSqlStatementList(sqlStatementList, lastSqlStatement, dbms, conn);
<del> postSuccessfulTransaction(sqlStatementList);
<del> }
<del>
<del> private void executeSqlStatementList(List<? extends SqlStatement> sqlStatementList, AtomicReference<SqlStatement> lastSqlStatement, Dbms dbms, Connection conn) throws SQLException {
<del> assertNotClosed();
<del> for (final SqlStatement sqlStatement : sqlStatementList) {
<del> lastSqlStatement.set(sqlStatement);
<del> switch (sqlStatement.getType()) {
<del> case INSERT: {
<del> final SqlInsertStatement s = (SqlInsertStatement) sqlStatement;
<del> handleSqlStatement(dbms, conn, s);
<del> break;
<del> }
<del> case UPDATE: {
<del> final SqlUpdateStatement s = (SqlUpdateStatement) sqlStatement;
<del> handleSqlStatement(dbms, conn, s);
<del> break;
<del> }
<del> case DELETE: {
<del> final SqlDeleteStatement s = (SqlDeleteStatement) sqlStatement;
<del> handleSqlStatement(dbms, conn, s);
<del> break;
<del> }
<del> }
<del>
<del> }
<del> }
<del>
<del> private void handleSqlStatement(Dbms dbms, Connection conn, SqlInsertStatement sqlStatement) throws SQLException {
<del> assertNotClosed();
<del> try (final PreparedStatement ps = conn.prepareStatement(sqlStatement.getSql(), Statement.RETURN_GENERATED_KEYS)) {
<del> int i = 1;
<del> for (Object o : sqlStatement.getValues()) {
<del> ps.setObject(i++, o);
<del> }
<del> ps.executeUpdate();
<del>
<del> handleGeneratedKeys(ps, sqlStatement::addGeneratedKey);
<del> }
<del> }
<del>
<del> private void handleGeneratedKeys(PreparedStatement ps, LongConsumer longConsumer) throws SQLException {
<del> try (final ResultSet generatedKeys = ps.getGeneratedKeys()) {
<del> while (generatedKeys.next()) {
<del> longConsumer.accept(generatedKeys.getLong(1));
<del> //sqlStatement.addGeneratedKey(generatedKeys.getLong(1));
<del> }
<del> }
<del> }
<del>
<del> private void handleSqlStatement(Dbms dbms, Connection conn, SqlUpdateStatement sqlStatement) throws SQLException {
<del> handleSqlStatementHelper(conn, sqlStatement);
<del> }
<del>
<del> private void handleSqlStatement(Dbms dbms, Connection conn, SqlDeleteStatement sqlStatement) throws SQLException {
<del> handleSqlStatementHelper(conn, sqlStatement);
<del> }
<del>
<del> private void handleSqlStatementHelper(Connection conn, SqlStatement sqlStatement) throws SQLException {
<del> assertNotClosed();
<del> try (final PreparedStatement ps = conn.prepareStatement(sqlStatement.getSql(), Statement.NO_GENERATED_KEYS)) {
<del> int i = 1;
<del> for (Object o : sqlStatement.getValues()) {
<del> ps.setObject(i++, o);
<del> }
<del> ps.executeUpdate();
<del> }
<del> }
<del>
<del> private void postSuccessfulTransaction(List<? extends SqlStatement> sqlStatementList) {
<del> sqlStatementList.stream()
<del> .filter(SqlInsertStatement.class::isInstance)
<del> .map(SqlInsertStatement.class::cast)
<del> .forEach(SqlInsertStatement::notifyGeneratedKeyListener);
<del> }
<del>
<del> protected String encloseField(Dbms dbms, String fieldName) {
<del> return dbmsTypeOf(dbmsHandlerComponent, dbms).getDatabaseNamingConvention().encloseField(fieldName);
<del> }
<del>
<del> @Override
<del> public Clob createClob(Dbms dbms) throws SQLException {
<del> return applyOnConnection(dbms, Connection::createClob);
<del> }
<del>
<del> @Override
<del> public Blob createBlob(Dbms dbms) throws SQLException {
<del> return applyOnConnection(dbms, Connection::createBlob);
<del> }
<del>
<del> @Override
<del> public NClob createNClob(Dbms dbms) throws SQLException {
<del> return applyOnConnection(dbms, Connection::createNClob);
<del> }
<del>
<del> @Override
<del> public SQLXML createSQLXML(Dbms dbms) throws SQLException {
<del> return applyOnConnection(dbms, Connection::createSQLXML);
<del> }
<del>
<del> @Override
<del> public Array createArray(Dbms dbms, String typeName, Object[] elements) throws SQLException {
<del> assertNotClosed();
<del> try (final Connection connection = connectionPoolComponent.getConnection(dbms)) {
<del> return connection.createArrayOf(typeName, elements);
<del> }
<del> }
<del>
<del> @Override
<del> public Struct createStruct(Dbms dbms, String typeName, Object[] attributes) throws SQLException {
<del> assertNotClosed();
<del> try (final Connection connection = connectionPoolComponent.getConnection(dbms)) {
<del> return connection.createStruct(typeName, attributes);
<del> }
<del> }
<del>
<del> private <T> T applyOnConnection(Dbms dbms, SqlFunction<Connection, T> mapper) throws SQLException {
<del> assertNotClosed();
<del> try (final Connection c = connectionPoolComponent.getConnection(dbms)) {
<del> return mapper.apply(c);
<del> }
<del> }
<del>
<del> @ExecuteBefore(State.STOPPED)
<del> public void close() {
<del> closed.set(true);
<del> }
<del>
<del> private void assertNotClosed() {
<del> if (closed.get()) {
<del> throw new IllegalStateException(
<del> "The " + DbmsOperationHandler.class.getSimpleName() + " " +
<del> getClass().getSimpleName() + " has been closed."
<del> );
<del> }
<del> }
<del>
<del> private interface ThrowingClosable {
<del> void close() throws Exception;
<del> }
<del>
<del> private void closeQuietly(ThrowingClosable closeable) {
<del> try {
<del> closeable.close();
<del> } catch (Exception e) {
<del> LOGGER.warn(e);
<del> }
<del> }
<del>
<del>} |
||
JavaScript | mit | d518fab49a533cdd726ee7f9840015101be3e4cb | 0 | voyagr/voyagr,voyagr/voyagr | import * as firebase from 'firebase'
import config from '../firebaseConfig'
export const initialize = firebase.initializeApp(config)
export const database = firebase.database()
export const auth = firebase.auth()
export const ref = database.ref()
| db/firebase.js | import * as firebase from 'firebase'
import config from '../firebaseConfig'
// import { bindActionCreators } from 'redux'
export const initialize = firebase.initializeApp(config)
export const database = firebase.database()
export const auth = firebase.auth()
export const ref = database.ref()
| Update firebase.js | db/firebase.js | Update firebase.js | <ide><path>b/firebase.js
<ide> import * as firebase from 'firebase'
<ide> import config from '../firebaseConfig'
<del>// import { bindActionCreators } from 'redux'
<ide>
<ide> export const initialize = firebase.initializeApp(config)
<ide> |
|
JavaScript | mit | 399562daa73dcb094a3f65b3f724549b0c381e37 | 0 | opentok/accelerator-core-js,opentok/accelerator-core-js,adrice727/accelerator-core-js,adrice727/accelerator-core-js | /* global OT */
/**
* Dependencies
*/
const util = require('./util');
const State = require('./state').default;
const accPackEvents = require('./events');
const Communication = require('./communication').default;
const OpenTokSDK = require('./sdk-wrapper/sdkWrapper');
const { CoreError } = require('./errors');
const {
message,
Analytics,
logAction,
logVariation,
} = require('./logging');
/**
* Helper methods
*/
const { dom, path, pathOr, properCase } = util;
/**
* Ensure that we have the required credentials
* @param {Object} credentials
* @param {String} credentials.apiKey
* @param {String} credentials.sessionId
* @param {String} credentials.token
*/
const validateCredentials = (credentials = []) => {
const required = ['apiKey', 'sessionId', 'token'];
required.forEach((credential) => {
if (!credentials[credential]) {
throw new CoreError(`${credential} is a required credential`, 'invalidParameters');
}
});
};
class AccCore {
constructor(options) {
// Options/credentials validation
if (!options) {
throw new CoreError('Missing options required for initialization', 'invalidParameters');
}
const { credentials } = options;
validateCredentials(options.credentials);
this.name = options.name;
// Init analytics
this.analytics = new Analytics(window.location.origin, credentials.sessionId, null, credentials.apiKey);
this.analytics.log(logAction.init, logVariation.attempt);
// Create session, setup state
this.session = OT.initSession(credentials.apiKey, credentials.sessionId);
this.internalState = new State();
this.internalState.setSession(this.session);
this.internalState.setCredentials(credentials);
this.internalState.setOptions(options);
// Individual accelerator packs
this.communication = null;
this.textChat = null;
this.screenSharing = null;
this.annotation = null;
this.archiving = null;
// Create internal event listeners
this.createEventListeners(this.session, options);
this.analytics.log(logAction.init, logVariation.success);
}
// OpenTok SDK Wrapper
static OpenTokSDK = OpenTokSDK;
// Expose utility methods
static util = util
/**
* Get access to an accelerator pack
* @param {String} packageName - textChat, screenSharing, annotation, or archiving
* @returns {Object} The instance of the accelerator pack
*/
getAccPack = (packageName) => {
const { analytics, textChat, screenSharing, annotation, archiving } = this;
analytics.log(logAction.getAccPack, logVariation.attempt);
const packages = {
textChat,
screenSharing,
annotation,
archiving,
};
analytics.log(logAction.getAccPack, logVariation.success);
return packages[packageName];
}
/** Eventing */
/**
* Register events that can be listened to be other components/modules
* @param {array | string} events - A list of event names. A single event may
* also be passed as a string.
*/
registerEvents = (events) => {
const { eventListeners } = this;
const eventList = Array.isArray(events) ? events : [events];
eventList.forEach((event) => {
if (!eventListeners[event]) {
eventListeners[event] = new Set();
}
});
};
/**
* Register a callback for a specific event or pass an object with
* with event => callback key/value pairs to register listeners for
* multiple events.
* @param {String | Object} event - The name of the event
* @param {Function} callback
*/
on = (event, callback) => {
const { eventListeners, on } = this;
// analytics.log(logAction.on, logVariation.attempt);
if (typeof event === 'object') {
Object.keys(event).forEach((eventName) => {
on(eventName, event[eventName]);
});
return;
}
const eventCallbacks = eventListeners[event];
if (!eventCallbacks) {
message(`${event} is not a registered event.`);
// analytics.log(logAction.on, logVariation.fail);
} else {
eventCallbacks.add(callback);
// analytics.log(logAction.on, logVariation.success);
}
}
/**
* Remove a callback for a specific event. If no parameters are passed,
* all event listeners will be removed.
* @param {String} event - The name of the event
* @param {Function} callback
*/
off = (event, callback) => {
const { eventListeners } = this;
// analytics.log(logAction.off, logVariation.attempt);
if (!event && !callback) {
Object.keys(eventListeners).forEach((eventType) => {
eventListeners[eventType].clear();
});
} else {
const eventCallbacks = eventListeners[event];
if (!eventCallbacks) {
// analytics.log(logAction.off, logVariation.fail);
message(`${event} is not a registered event.`);
} else {
eventCallbacks.delete(callback);
// analytics.log(logAction.off, logVariation.success);
}
}
}
/**
* Trigger an event and fire all registered callbacks
* @param {String} event - The name of the event
* @param {*} data - Data to be passed to callback functions
*/
triggerEvent = (event, data) => {
const { eventListeners, registerEvents } = this;
const eventCallbacks = eventListeners[event];
if (!eventCallbacks) {
registerEvents(event);
message(`${event} has been registered as a new event.`);
} else {
eventCallbacks.forEach(callback => callback(data, event));
}
};
/**
* Get the current OpenTok session object
* @returns {Object}
*/
getSession = () => this.internalState.getSession()
/**
* Returns the current OpenTok session credentials
* @returns {Object}
*/
getCredentials = () => this.internalState.getCredentials()
/**
* Returns the options used for initialization
* @returns {Object}
*/
getOptions = () => this.internalState.getOptions()
createEventListeners = (session, options) => {
this.eventListeners = {};
const { registerEvents, internalState, triggerEvent, on, getSession } = this;
Object.keys(accPackEvents).forEach(type => registerEvents(accPackEvents[type]));
/**
* If using screen sharing + annotation in an external window, the screen sharing
* package will take care of calling annotation.start() and annotation.linkCanvas()
*/
const usingAnnotation = path('screenSharing.annotation', options);
const internalAnnotation = usingAnnotation && !path('screenSharing.externalWindow', options);
/**
* Wrap session events and update internalState when streams are created
* or destroyed
*/
accPackEvents.session.forEach((eventName) => {
session.on(eventName, (event) => {
if (eventName === 'streamCreated') { internalState.addStream(event.stream); }
if (eventName === 'streamDestroyed') { internalState.removeStream(event.stream); }
triggerEvent(eventName, event);
});
});
if (usingAnnotation) {
on('subscribeToScreen', ({ subscriber }) => {
this.annotation.start(getSession())
.then(() => {
const absoluteParent = dom.query(path('annotation.absoluteParent.subscriber', options));
const linkOptions = absoluteParent ? { absoluteParent } : null;
this.annotation.linkCanvas(subscriber, subscriber.element.parentElement, linkOptions);
});
});
on('unsubscribeFromScreen', () => {
this.annotation.end();
});
}
on('startScreenSharing', (publisher) => {
internalState.addPublisher('screen', publisher);
triggerEvent('startScreenShare', Object.assign({}, { publisher }, internalState.getPubSub()));
if (internalAnnotation) {
this.annotation.start(getSession())
.then(() => {
const absoluteParent = dom.query(path('annotation.absoluteParent.publisher', options));
const linkOptions = absoluteParent ? { absoluteParent } : null;
this.annotation.linkCanvas(publisher, publisher.element.parentElement, linkOptions);
});
}
});
on('endScreenSharing', (publisher) => {
// delete publishers.screen[publisher.id];
internalState.removePublisher('screen', publisher);
triggerEvent('endScreenShare', internalState.getPubSub());
if (usingAnnotation) {
this.annotation.end();
}
});
}
setupExternalAnnotation = () => this.annotation.start(this.getSession(), { screensharing: true })
linkAnnotation = (pubSub, annotationContainer, externalWindow) => {
const { annotation, internalState } = this;
annotation.linkCanvas(pubSub, annotationContainer, {
externalWindow,
});
if (externalWindow) {
// Add subscribers to the external window
const streams = internalState.getStreams();
const cameraStreams = Object.keys(streams).reduce((acc, streamId) => {
const stream = streams[streamId];
return stream.videoType === 'camera' || stream.videoType === 'sip' ? acc.concat(stream) : acc;
}, []);
cameraStreams.forEach(annotation.addSubscriberToExternalWindow);
}
}
initPackages = () => {
const { analytics, getSession, getOptions, internalState } = this;
const { on, registerEvents, setupExternalAnnotation, triggerEvent, linkAnnotation } = this;
analytics.log(logAction.initPackages, logVariation.attempt);
const session = getSession();
const options = getOptions();
/**
* Try to require a package. If 'require' is unavailable, look for
* the package in global scope. A switch ttatement is used because
* webpack and Browserify aren't able to resolve require statements
* that use variable names.
* @param {String} packageName - The name of the npm package
* @param {String} globalName - The name of the package if exposed on global/window
* @returns {Object}
*/
const optionalRequire = (packageName, globalName) => {
let result;
/* eslint-disable global-require, import/no-extraneous-dependencies, import/no-unresolved */
try {
switch (packageName) {
case 'opentok-text-chat':
result = require('opentok-text-chat');
break;
case 'opentok-screen-sharing':
result = require('opentok-screen-sharing');
break;
case 'opentok-annotation':
result = require('opentok-annotation');
break;
case 'opentok-archiving':
result = require('opentok-archiving');
break;
default:
break;
}
/* eslint-enable global-require */
} catch (error) {
result = window[globalName];
}
if (!result) {
analytics.log(logAction.initPackages, logVariation.fail);
throw new CoreError(`Could not load ${packageName}`, 'missingDependency');
}
return result;
};
const availablePackages = {
textChat() {
return optionalRequire('opentok-text-chat', 'TextChatAccPack');
},
screenSharing() {
return optionalRequire('opentok-screen-sharing', 'ScreenSharingAccPack');
},
annotation() {
return optionalRequire('opentok-annotation', 'AnnotationAccPack');
},
archiving() {
return optionalRequire('opentok-archiving', 'ArchivingAccPack');
},
};
const packages = {};
(path('packages', options) || []).forEach((acceleratorPack) => {
if (availablePackages[acceleratorPack]) { // eslint-disable-next-line no-param-reassign
packages[properCase(acceleratorPack)] = availablePackages[acceleratorPack]();
} else {
message(`${acceleratorPack} is not a valid accelerator pack`);
}
});
/**
* Get containers for streams, controls, and the chat widget
*/
const getDefaultContainer = pubSub => document.getElementById(`${pubSub}Container`);
const getContainerElements = () => {
// Need to use path to check for null values
const controls = pathOr('#videoControls', 'controlsContainer', options);
const chat = pathOr('#chat', 'textChat.container', options);
const stream = pathOr(getDefaultContainer, 'streamContainers', options);
return { stream, controls, chat };
};
/** *** *** *** *** */
/**
* Return options for the specified package
* @param {String} packageName
* @returns {Object}
*/
const packageOptions = (packageName) => {
/**
* Methods to expose to accelerator packs
*/
const accPack = {
registerEventListener: on, // Legacy option
on,
registerEvents,
triggerEvent,
setupExternalAnnotation,
linkAnnotation,
};
/**
* If options.controlsContainer/containers.controls is null,
* accelerator packs should not append their controls.
*/
const containers = getContainerElements();
const appendControl = !!containers.controls;
const controlsContainer = containers.controls; // Legacy option
const streamContainers = containers.stream;
const baseOptions = {
session,
core: accPack,
accPack,
controlsContainer,
appendControl,
streamContainers,
};
switch (packageName) {
/* beautify ignore:start */
case 'communication': {
return Object.assign({}, baseOptions, { state: internalState, analytics }, options.communication);
}
case 'textChat': {
const textChatOptions = {
textChatContainer: path('textChat.container', options),
waitingMessage: path('textChat.waitingMessage', options),
sender: { alias: path('textChat.name', options) },
alwaysOpen: path('textChat.alwaysOpen', options),
};
return Object.assign({}, baseOptions, textChatOptions);
}
case 'screenSharing': {
const screenSharingContainer = { screenSharingContainer: streamContainers };
return Object.assign({}, baseOptions, screenSharingContainer, options.screenSharing);
}
case 'annotation': {
return Object.assign({}, baseOptions, options.annotation);
}
case 'archiving': {
return Object.assign({}, baseOptions, options.archiving);
}
default:
return {};
/* beautify ignore:end */
}
};
/** Create instances of each package */
// eslint-disable-next-line global-require,import/no-extraneous-dependencies
this.communication = new Communication(packageOptions('communication'));
this.textChat = packages.TextChat ? new packages.TextChat(packageOptions('textChat')) : null;
this.screenSharing = packages.ScreenSharing ? new packages.ScreenSharing(packageOptions('screenSharing')) : null;
this.annotation = packages.Annotation ? new packages.Annotation(packageOptions('annotation')) : null;
this.archiving = packages.Archiving ? new packages.Archiving(packageOptions('archiving')) : null;
analytics.log(logAction.initPackages, logVariation.success);
}
/**
* Connect to the session
* @returns {Promise} <resolve: -, reject: Error>
*/
connect = () => {
const { analytics, getSession, initPackages, triggerEvent, getCredentials } = this;
return new Promise((resolve, reject) => {
analytics.log(logAction.connect, logVariation.attempt);
const session = getSession();
const { token } = getCredentials();
session.connect(token, (error) => {
if (error) {
message(error);
analytics.log(logAction.connect, logVariation.fail);
return reject(error);
}
const { sessionId, apiKey } = session;
analytics.update(sessionId, path('connection.connectionId', session), apiKey);
analytics.log(logAction.connect, logVariation.success);
initPackages();
triggerEvent('connected', session);
return resolve({ connections: session.connections.length() });
});
});
}
/**
* Disconnect from the session
* @returns {Promise} <resolve: -, reject: Error>
*/
disconnect = () => {
const { analytics, getSession, internalState } = this;
analytics.log(logAction.disconnect, logVariation.attempt);
getSession().disconnect();
internalState.reset();
analytics.log(logAction.disconnect, logVariation.success);
};
/**
* Force a remote connection to leave the session
* @param {Object} connection
* @returns {Promise} <resolve: empty, reject: Error>
*/
forceDisconnect = (connection) => {
const { analytics, getSession } = this;
return new Promise((resolve, reject) => {
analytics.log(logAction.forceDisconnect, logVariation.attempt);
getSession().forceDisconnect(connection, (error) => {
if (error) {
analytics.log(logAction.forceDisconnect, logVariation.fail);
reject(error);
} else {
analytics.log(logAction.forceDisconnect, logVariation.success);
resolve();
}
});
});
}
/**
* Start publishing video and subscribing to streams
* @param {Object} publisherProps - https://goo.gl/0mL0Eo
* @returns {Promise} <resolve: State + Publisher, reject: Error>
*/
startCall = publisherProps => this.communication.startCall(publisherProps)
/**
* Stop all publishing un unsubscribe from all streams
* @returns {void}
*/
endCall = () => this.communication.endCall()
/**
* Manually subscribe to a stream
* @param {Object} stream - An OpenTok stream
* @returns {Promise} <resolve: Subscriber, reject: Error>
*/
subscribe = stream => this.communication.subscribe(stream)
/**
* Manually unsubscribe from a stream
* @param {Object} subscriber - An OpenTok subscriber object
* @returns {Promise} <resolve: void, reject: Error>
*/
unsubscribe = subscriber => this.communication.unsubscribe(subscriber)
/**
* Force the publisher of a stream to stop publishing the stream
* @param {Object} stream
* @returns {Promise} <resolve: empty, reject: Error>
*/
forceUnpublish = (stream) => {
const { analytics, getSession } = this;
return new Promise((resolve, reject) => {
analytics.log(logAction.forceUnpublish, logVariation.attempt);
getSession().forceUnpublish(stream, (error) => {
if (error) {
analytics.log(logAction.forceUnpublish, logVariation.fail);
reject(error);
} else {
analytics.log(logAction.forceUnpublish, logVariation.success);
resolve();
}
});
});
}
/**
* Get the local publisher object for a stream
* @param {Object} stream - An OpenTok stream object
* @returns {Object} - The publisher object
*/
getPublisherForStream = stream => this.getSession().getPublisherForStream(stream);
/**
* Get the local subscriber objects for a stream
* @param {Object} stream - An OpenTok stream object
* @returns {Array} - An array of subscriber object
*/
getSubscribersForStream = stream => this.getSession().getSubscribersForStream(stream);
/**
* Send a signal using the OpenTok signaling apiKey
* @param {String} type
* @param {*} [data]
* @param {Object} [to] - An OpenTok connection object
* @returns {Promise} <resolve: empty, reject: Error>
*/
signal = (type, data, to) => {
const { analytics, getSession } = this;
return new Promise((resolve, reject) => {
analytics.log(logAction.signal, logVariation.attempt);
const session = getSession();
const signalObj = Object.assign({},
type ? { type } : null,
data ? { data: JSON.stringify(data) } : null,
to ? { to } : null // eslint-disable-line comma-dangle
);
session.signal(signalObj, (error) => {
if (error) {
analytics.log(logAction.signal, logVariation.fail);
reject(error);
} else {
analytics.log(logAction.signal, logVariation.success);
resolve();
}
});
});
}
/**
* Enable or disable local audio
* @param {Boolean} enable
*/
toggleLocalAudio = (enable) => {
const { analytics, internalState, communication } = this;
analytics.log(logAction.toggleLocalAudio, logVariation.attempt);
const { publishers } = internalState.getPubSub();
const toggleAudio = id => communication.enableLocalAV(id, 'audio', enable);
Object.keys(publishers.camera).forEach(toggleAudio);
analytics.log(logAction.toggleLocalAudio, logVariation.success);
};
/**
* Enable or disable local video
* @param {Boolean} enable
*/
toggleLocalVideo = (enable) => {
const { analytics, internalState, communication } = this;
analytics.log(logAction.toggleLocalVideo, logVariation.attempt);
const { publishers } = internalState.getPubSub();
const toggleVideo = id => communication.enableLocalAV(id, 'video', enable);
Object.keys(publishers.camera).forEach(toggleVideo);
analytics.log(logAction.toggleLocalVideo, logVariation.success);
};
/**
* Enable or disable remote audio
* @param {String} id - Subscriber id
* @param {Boolean} enable
*/
toggleRemoteAudio = (id, enable) => {
const { analytics, communication } = this;
analytics.log(logAction.toggleRemoteAudio, logVariation.attempt);
communication.enableRemoteAV(id, 'audio', enable);
analytics.log(logAction.toggleRemoteAudio, logVariation.success);
};
/**
* Enable or disable remote video
* @param {String} id - Subscriber id
* @param {Boolean} enable
*/
toggleRemoteVideo = (id, enable) => {
const { analytics, communication } = this;
analytics.log(logAction.toggleRemoteVideo, logVariation.attempt);
communication.enableRemoteAV(id, 'video', enable);
analytics.log(logAction.toggleRemoteVideo, logVariation.success);
}
}
if (global === window) {
window.AccCore = AccCore;
}
module.exports = AccCore;
| src/core.js | /* global OT */
/**
* Dependencies
*/
const util = require('./util');
const State = require('./state').default;
const accPackEvents = require('./events');
const Communication = require('./communication').default;
const OpenTokSDK = require('./sdk-wrapper/sdkWrapper');
const { CoreError } = require('./errors');
const {
message,
Analytics,
logAction,
logVariation,
} = require('./logging');
/**
* Helper methods
*/
const { dom, path, pathOr, properCase } = util;
/**
* Ensure that we have the required credentials
* @param {Object} credentials
* @param {String} credentials.apiKey
* @param {String} credentials.sessionId
* @param {String} credentials.token
*/
const validateCredentials = (credentials = []) => {
const required = ['apiKey', 'sessionId', 'token'];
required.forEach((credential) => {
if (!credentials[credential]) {
throw new CoreError(`${credential} is a required credential`, 'invalidParameters');
}
});
};
class AccCore {
constructor(options) {
// Options/credentials validation
if (!options) {
throw new CoreError('Missing options required for initialization', 'invalidParameters');
}
const { credentials } = options;
validateCredentials(options.credentials);
// Init analytics
this.analytics = new Analytics(window.location.origin, credentials.sessionId, null, credentials.apiKey);
this.analytics.log(logAction.init, logVariation.attempt);
// Create session, setup state
this.session = OT.initSession(credentials.apiKey, credentials.sessionId);
this.internalState = new State();
this.internalState.setSession(this.session);
this.internalState.setCredentials(credentials);
this.internalState.setOptions(options);
// Individual accelerator packs
this.communication = null;
this.textChat = null;
this.screenSharing = null;
this.annotation = null;
this.archiving = null;
// Create internal event listeners
this.createEventListeners(this.session, options);
this.analytics.log(logAction.init, logVariation.success);
}
// OpenTok SDK Wrapper
static OpenTokSDK = OpenTokSDK;
// Expose utility methods
static util = util
/**
* Get access to an accelerator pack
* @param {String} packageName - textChat, screenSharing, annotation, or archiving
* @returns {Object} The instance of the accelerator pack
*/
getAccPack = (packageName) => {
const { analytics, textChat, screenSharing, annotation, archiving } = this;
analytics.log(logAction.getAccPack, logVariation.attempt);
const packages = {
textChat,
screenSharing,
annotation,
archiving,
};
analytics.log(logAction.getAccPack, logVariation.success);
return packages[packageName];
}
/** Eventing */
/**
* Register events that can be listened to be other components/modules
* @param {array | string} events - A list of event names. A single event may
* also be passed as a string.
*/
registerEvents = (events) => {
const { eventListeners } = this;
const eventList = Array.isArray(events) ? events : [events];
eventList.forEach((event) => {
if (!eventListeners[event]) {
eventListeners[event] = new Set();
}
});
};
/**
* Register a callback for a specific event or pass an object with
* with event => callback key/value pairs to register listeners for
* multiple events.
* @param {String | Object} event - The name of the event
* @param {Function} callback
*/
on = (event, callback) => {
const { eventListeners, on } = this;
// analytics.log(logAction.on, logVariation.attempt);
if (typeof event === 'object') {
Object.keys(event).forEach((eventName) => {
on(eventName, event[eventName]);
});
return;
}
const eventCallbacks = eventListeners[event];
if (!eventCallbacks) {
message(`${event} is not a registered event.`);
// analytics.log(logAction.on, logVariation.fail);
} else {
eventCallbacks.add(callback);
// analytics.log(logAction.on, logVariation.success);
}
}
/**
* Remove a callback for a specific event. If no parameters are passed,
* all event listeners will be removed.
* @param {String} event - The name of the event
* @param {Function} callback
*/
off = (event, callback) => {
const { eventListeners } = this;
// analytics.log(logAction.off, logVariation.attempt);
if (!event && !callback) {
Object.keys(eventListeners).forEach((eventType) => {
eventListeners[eventType].clear();
});
} else {
const eventCallbacks = eventListeners[event];
if (!eventCallbacks) {
// analytics.log(logAction.off, logVariation.fail);
message(`${event} is not a registered event.`);
} else {
eventCallbacks.delete(callback);
// analytics.log(logAction.off, logVariation.success);
}
}
}
/**
* Trigger an event and fire all registered callbacks
* @param {String} event - The name of the event
* @param {*} data - Data to be passed to callback functions
*/
triggerEvent = (event, data) => {
const { eventListeners, registerEvents } = this;
const eventCallbacks = eventListeners[event];
if (!eventCallbacks) {
registerEvents(event);
message(`${event} has been registered as a new event.`);
} else {
eventCallbacks.forEach(callback => callback(data, event));
}
};
/**
* Get the current OpenTok session object
* @returns {Object}
*/
getSession = () => this.internalState.getSession()
/**
* Returns the current OpenTok session credentials
* @returns {Object}
*/
getCredentials = () => this.internalState.getCredentials()
/**
* Returns the options used for initialization
* @returns {Object}
*/
getOptions = () => this.internalState.getOptions()
createEventListeners = (session, options) => {
this.eventListeners = {};
const { registerEvents, internalState, triggerEvent, on, getSession } = this;
Object.keys(accPackEvents).forEach(type => registerEvents(accPackEvents[type]));
/**
* If using screen sharing + annotation in an external window, the screen sharing
* package will take care of calling annotation.start() and annotation.linkCanvas()
*/
const usingAnnotation = path('screenSharing.annotation', options);
const internalAnnotation = usingAnnotation && !path('screenSharing.externalWindow', options);
/**
* Wrap session events and update internalState when streams are created
* or destroyed
*/
accPackEvents.session.forEach((eventName) => {
session.on(eventName, (event) => {
if (eventName === 'streamCreated') { internalState.addStream(event.stream); }
if (eventName === 'streamDestroyed') { internalState.removeStream(event.stream); }
triggerEvent(eventName, event);
});
});
if (usingAnnotation) {
on('subscribeToScreen', ({ subscriber }) => {
this.annotation.start(getSession())
.then(() => {
const absoluteParent = dom.query(path('annotation.absoluteParent.subscriber', options));
const linkOptions = absoluteParent ? { absoluteParent } : null;
this.annotation.linkCanvas(subscriber, subscriber.element.parentElement, linkOptions);
});
});
on('unsubscribeFromScreen', () => {
this.annotation.end();
});
}
on('startScreenSharing', (publisher) => {
internalState.addPublisher('screen', publisher);
triggerEvent('startScreenShare', Object.assign({}, { publisher }, internalState.getPubSub()));
if (internalAnnotation) {
this.annotation.start(getSession())
.then(() => {
const absoluteParent = dom.query(path('annotation.absoluteParent.publisher', options));
const linkOptions = absoluteParent ? { absoluteParent } : null;
this.annotation.linkCanvas(publisher, publisher.element.parentElement, linkOptions);
});
}
});
on('endScreenSharing', (publisher) => {
// delete publishers.screen[publisher.id];
internalState.removePublisher('screen', publisher);
triggerEvent('endScreenShare', internalState.getPubSub());
if (usingAnnotation) {
this.annotation.end();
}
});
}
setupExternalAnnotation = () => this.annotation.start(this.getSession(), { screensharing: true })
linkAnnotation = (pubSub, annotationContainer, externalWindow) => {
const { annotation, internalState } = this;
annotation.linkCanvas(pubSub, annotationContainer, {
externalWindow,
});
if (externalWindow) {
// Add subscribers to the external window
const streams = internalState.getStreams();
const cameraStreams = Object.keys(streams).reduce((acc, streamId) => {
const stream = streams[streamId];
return stream.videoType === 'camera' || stream.videoType === 'sip' ? acc.concat(stream) : acc;
}, []);
cameraStreams.forEach(annotation.addSubscriberToExternalWindow);
}
}
initPackages = () => {
const { analytics, getSession, getOptions, internalState } = this;
const { on, registerEvents, setupExternalAnnotation, triggerEvent, linkAnnotation } = this;
analytics.log(logAction.initPackages, logVariation.attempt);
const session = getSession();
const options = getOptions();
/**
* Try to require a package. If 'require' is unavailable, look for
* the package in global scope. A switch ttatement is used because
* webpack and Browserify aren't able to resolve require statements
* that use variable names.
* @param {String} packageName - The name of the npm package
* @param {String} globalName - The name of the package if exposed on global/window
* @returns {Object}
*/
const optionalRequire = (packageName, globalName) => {
let result;
/* eslint-disable global-require, import/no-extraneous-dependencies, import/no-unresolved */
try {
switch (packageName) {
case 'opentok-text-chat':
result = require('opentok-text-chat');
break;
case 'opentok-screen-sharing':
result = require('opentok-screen-sharing');
break;
case 'opentok-annotation':
result = require('opentok-annotation');
break;
case 'opentok-archiving':
result = require('opentok-archiving');
break;
default:
break;
}
/* eslint-enable global-require */
} catch (error) {
result = window[globalName];
}
if (!result) {
analytics.log(logAction.initPackages, logVariation.fail);
throw new CoreError(`Could not load ${packageName}`, 'missingDependency');
}
return result;
};
const availablePackages = {
textChat() {
return optionalRequire('opentok-text-chat', 'TextChatAccPack');
},
screenSharing() {
return optionalRequire('opentok-screen-sharing', 'ScreenSharingAccPack');
},
annotation() {
return optionalRequire('opentok-annotation', 'AnnotationAccPack');
},
archiving() {
return optionalRequire('opentok-archiving', 'ArchivingAccPack');
},
};
const packages = {};
(path('packages', options) || []).forEach((acceleratorPack) => {
if (availablePackages[acceleratorPack]) { // eslint-disable-next-line no-param-reassign
packages[properCase(acceleratorPack)] = availablePackages[acceleratorPack]();
} else {
message(`${acceleratorPack} is not a valid accelerator pack`);
}
});
/**
* Get containers for streams, controls, and the chat widget
*/
const getDefaultContainer = pubSub => document.getElementById(`${pubSub}Container`);
const getContainerElements = () => {
// Need to use path to check for null values
const controls = pathOr('#videoControls', 'controlsContainer', options);
const chat = pathOr('#chat', 'textChat.container', options);
const stream = pathOr(getDefaultContainer, 'streamContainers', options);
return { stream, controls, chat };
};
/** *** *** *** *** */
/**
* Return options for the specified package
* @param {String} packageName
* @returns {Object}
*/
const packageOptions = (packageName) => {
/**
* Methods to expose to accelerator packs
*/
const accPack = {
registerEventListener: on, // Legacy option
on,
registerEvents,
triggerEvent,
setupExternalAnnotation,
linkAnnotation,
};
/**
* If options.controlsContainer/containers.controls is null,
* accelerator packs should not append their controls.
*/
const containers = getContainerElements();
const appendControl = !!containers.controls;
const controlsContainer = containers.controls; // Legacy option
const streamContainers = containers.stream;
const baseOptions = {
session,
core: accPack,
accPack,
controlsContainer,
appendControl,
streamContainers,
};
switch (packageName) {
/* beautify ignore:start */
case 'communication': {
return Object.assign({}, baseOptions, { state: internalState, analytics }, options.communication);
}
case 'textChat': {
const textChatOptions = {
textChatContainer: path('textChat.container', options),
waitingMessage: path('textChat.waitingMessage', options),
sender: { alias: path('textChat.name', options) },
alwaysOpen: path('textChat.alwaysOpen', options),
};
return Object.assign({}, baseOptions, textChatOptions);
}
case 'screenSharing': {
const screenSharingContainer = { screenSharingContainer: streamContainers };
return Object.assign({}, baseOptions, screenSharingContainer, options.screenSharing);
}
case 'annotation': {
return Object.assign({}, baseOptions, options.annotation);
}
case 'archiving': {
return Object.assign({}, baseOptions, options.archiving);
}
default:
return {};
/* beautify ignore:end */
}
};
/** Create instances of each package */
// eslint-disable-next-line global-require,import/no-extraneous-dependencies
this.communication = new Communication(packageOptions('communication'));
this.textChat = packages.TextChat ? new packages.TextChat(packageOptions('textChat')) : null;
this.screenSharing = packages.ScreenSharing ? new packages.ScreenSharing(packageOptions('screenSharing')) : null;
this.annotation = packages.Annotation ? new packages.Annotation(packageOptions('annotation')) : null;
this.archiving = packages.Archiving ? new packages.Archiving(packageOptions('archiving')) : null;
analytics.log(logAction.initPackages, logVariation.success);
}
/**
* Connect to the session
* @returns {Promise} <resolve: -, reject: Error>
*/
connect = () => {
const { analytics, getSession, initPackages, triggerEvent, getCredentials } = this;
return new Promise((resolve, reject) => {
analytics.log(logAction.connect, logVariation.attempt);
const session = getSession();
const { token } = getCredentials();
session.connect(token, (error) => {
if (error) {
message(error);
analytics.log(logAction.connect, logVariation.fail);
return reject(error);
}
const { sessionId, apiKey } = session;
analytics.update(sessionId, path('connection.connectionId', session), apiKey);
analytics.log(logAction.connect, logVariation.success);
initPackages();
triggerEvent('connected', session);
return resolve({ connections: session.connections.length() });
});
});
}
/**
* Disconnect from the session
* @returns {Promise} <resolve: -, reject: Error>
*/
disconnect = () => {
const { analytics, getSession, internalState } = this;
analytics.log(logAction.disconnect, logVariation.attempt);
getSession().disconnect();
internalState.reset();
analytics.log(logAction.disconnect, logVariation.success);
};
/**
* Force a remote connection to leave the session
* @param {Object} connection
* @returns {Promise} <resolve: empty, reject: Error>
*/
forceDisconnect = (connection) => {
const { analytics, getSession } = this;
return new Promise((resolve, reject) => {
analytics.log(logAction.forceDisconnect, logVariation.attempt);
getSession().forceDisconnect(connection, (error) => {
if (error) {
analytics.log(logAction.forceDisconnect, logVariation.fail);
reject(error);
} else {
analytics.log(logAction.forceDisconnect, logVariation.success);
resolve();
}
});
});
}
/**
* Start publishing video and subscribing to streams
* @param {Object} publisherProps - https://goo.gl/0mL0Eo
* @returns {Promise} <resolve: State + Publisher, reject: Error>
*/
startCall = publisherProps => this.communication.startCall(publisherProps)
/**
* Stop all publishing un unsubscribe from all streams
* @returns {void}
*/
endCall = () => this.communication.endCall()
/**
* Manually subscribe to a stream
* @param {Object} stream - An OpenTok stream
* @returns {Promise} <resolve: Subscriber, reject: Error>
*/
subscribe = stream => this.communication.subscribe(stream)
/**
* Manually unsubscribe from a stream
* @param {Object} subscriber - An OpenTok subscriber object
* @returns {Promise} <resolve: void, reject: Error>
*/
unsubscribe = subscriber => this.communication.unsubscribe(subscriber)
/**
* Force the publisher of a stream to stop publishing the stream
* @param {Object} stream
* @returns {Promise} <resolve: empty, reject: Error>
*/
forceUnpublish = (stream) => {
const { analytics, getSession } = this;
return new Promise((resolve, reject) => {
analytics.log(logAction.forceUnpublish, logVariation.attempt);
getSession().forceUnpublish(stream, (error) => {
if (error) {
analytics.log(logAction.forceUnpublish, logVariation.fail);
reject(error);
} else {
analytics.log(logAction.forceUnpublish, logVariation.success);
resolve();
}
});
});
}
/**
* Get the local publisher object for a stream
* @param {Object} stream - An OpenTok stream object
* @returns {Object} - The publisher object
*/
getPublisherForStream = stream => this.getSession().getPublisherForStream(stream);
/**
* Get the local subscriber objects for a stream
* @param {Object} stream - An OpenTok stream object
* @returns {Array} - An array of subscriber object
*/
getSubscribersForStream = stream => this.getSession().getSubscribersForStream(stream);
/**
* Send a signal using the OpenTok signaling apiKey
* @param {String} type
* @param {*} [data]
* @param {Object} [to] - An OpenTok connection object
* @returns {Promise} <resolve: empty, reject: Error>
*/
signal = (type, data, to) => {
const { analytics, getSession } = this;
return new Promise((resolve, reject) => {
analytics.log(logAction.signal, logVariation.attempt);
const session = getSession();
const signalObj = Object.assign({},
type ? { type } : null,
data ? { data: JSON.stringify(data) } : null,
to ? { to } : null // eslint-disable-line comma-dangle
);
session.signal(signalObj, (error) => {
if (error) {
analytics.log(logAction.signal, logVariation.fail);
reject(error);
} else {
analytics.log(logAction.signal, logVariation.success);
resolve();
}
});
});
}
/**
* Enable or disable local audio
* @param {Boolean} enable
*/
toggleLocalAudio = (enable) => {
const { analytics, internalState, communication } = this;
analytics.log(logAction.toggleLocalAudio, logVariation.attempt);
const { publishers } = internalState.getPubSub();
const toggleAudio = id => communication.enableLocalAV(id, 'audio', enable);
Object.keys(publishers.camera).forEach(toggleAudio);
analytics.log(logAction.toggleLocalAudio, logVariation.success);
};
/**
* Enable or disable local video
* @param {Boolean} enable
*/
toggleLocalVideo = (enable) => {
const { analytics, internalState, communication } = this;
analytics.log(logAction.toggleLocalVideo, logVariation.attempt);
const { publishers } = internalState.getPubSub();
const toggleVideo = id => communication.enableLocalAV(id, 'video', enable);
Object.keys(publishers.camera).forEach(toggleVideo);
analytics.log(logAction.toggleLocalVideo, logVariation.success);
};
/**
* Enable or disable remote audio
* @param {String} id - Subscriber id
* @param {Boolean} enable
*/
toggleRemoteAudio = (id, enable) => {
const { analytics, communication } = this;
analytics.log(logAction.toggleRemoteAudio, logVariation.attempt);
communication.enableRemoteAV(id, 'audio', enable);
analytics.log(logAction.toggleRemoteAudio, logVariation.success);
};
/**
* Enable or disable remote video
* @param {String} id - Subscriber id
* @param {Boolean} enable
*/
toggleRemoteVideo = (id, enable) => {
const { analytics, communication } = this;
analytics.log(logAction.toggleRemoteVideo, logVariation.attempt);
communication.enableRemoteAV(id, 'video', enable);
analytics.log(logAction.toggleRemoteVideo, logVariation.success);
}
}
if (global === window) {
window.AccCore = AccCore;
}
module.exports = AccCore;
| Accept a name parameter when creating a new instance.
| src/core.js | Accept a name parameter when creating a new instance. | <ide><path>rc/core.js
<ide> }
<ide> const { credentials } = options;
<ide> validateCredentials(options.credentials);
<add> this.name = options.name;
<ide>
<ide> // Init analytics
<ide> this.analytics = new Analytics(window.location.origin, credentials.sessionId, null, credentials.apiKey); |
|
Java | apache-2.0 | 55f2f62ba3a833ad42002cb01a4275731ed9de53 | 0 | grassjedi/undertow,baranowb/undertow,wildfly-security-incubator/undertow,rogerchina/undertow,amannm/undertow,undertow-io/undertow,jasonchaffee/undertow,popstr/undertow,Karm/undertow,jstourac/undertow,soul2zimate/undertow,msfm/undertow,yonglehou/undertow,rhusar/undertow,jasonchaffee/undertow,golovnin/undertow,emag/codereading-undertow,rhatlapa/undertow,rhusar/undertow,wildfly-security-incubator/undertow,n1hility/undertow,golovnin/undertow,n1hility/undertow,pferraro/undertow,popstr/undertow,marschall/undertow,amannm/undertow,undertow-io/undertow,darranl/undertow,Karm/undertow,aradchykov/undertow,aldaris/undertow,emag/codereading-undertow,marschall/undertow,jamezp/undertow,stuartwdouglas/undertow,biddyweb/undertow,pferraro/undertow,darranl/undertow,pedroigor/undertow,aldaris/undertow,undertow-io/undertow,nkhuyu/undertow,marschall/undertow,Karm/undertow,msfm/undertow,rhatlapa/undertow,stuartwdouglas/undertow,msfm/undertow,pedroigor/undertow,pedroigor/undertow,baranowb/undertow,biddyweb/undertow,ctomc/undertow,grassjedi/undertow,golovnin/undertow,soul2zimate/undertow,jamezp/undertow,rogerchina/undertow,rhusar/undertow,yonglehou/undertow,darranl/undertow,grassjedi/undertow,soul2zimate/undertow,TomasHofman/undertow,amannm/undertow,rogerchina/undertow,pferraro/undertow,jstourac/undertow,ctomc/undertow,baranowb/undertow,rhatlapa/undertow,popstr/undertow,n1hility/undertow,jasonchaffee/undertow,jstourac/undertow,aradchykov/undertow,TomasHofman/undertow,wildfly-security-incubator/undertow,nkhuyu/undertow,nkhuyu/undertow,aldaris/undertow,stuartwdouglas/undertow,TomasHofman/undertow,ctomc/undertow,yonglehou/undertow,biddyweb/undertow,jamezp/undertow,aradchykov/undertow | package io.undertow.websockets.jsr;
import io.undertow.servlet.ServletExtension;
import io.undertow.servlet.Servlets;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.ThreadSetupAction;
import io.undertow.servlet.core.CompositeThreadSetupAction;
import io.undertow.servlet.core.ContextClassLoaderSetupAction;
import io.undertow.servlet.spec.ServletContextImpl;
import javax.servlet.DispatcherType;
import javax.websocket.DeploymentException;
import javax.websocket.server.ServerContainer;
import javax.websocket.server.ServerEndpointConfig;
import java.util.ArrayList;
import java.util.List;
/**
* @author Stuart Douglas
*/
public class Bootstrap implements ServletExtension {
public static final String FILTER_NAME = "Undertow Web Socket Filter";
@Override
public void handleDeployment(DeploymentInfo deploymentInfo, ServletContextImpl servletContext) {
WebSocketDeploymentInfo info = (WebSocketDeploymentInfo) deploymentInfo.getServletContextAttributes().get(WebSocketDeploymentInfo.ATTRIBUTE_NAME);
if (info == null) {
return;
}
final List<ThreadSetupAction> setup = new ArrayList<ThreadSetupAction>();
setup.add(new ContextClassLoaderSetupAction(deploymentInfo.getClassLoader()));
setup.addAll(deploymentInfo.getThreadSetupActions());
final CompositeThreadSetupAction threadSetupAction = new CompositeThreadSetupAction(setup);
ServerWebSocketContainer container = new ServerWebSocketContainer(deploymentInfo.getClassIntrospecter(), info.getWorker(), info.getBuffers(), threadSetupAction);
try {
for (Class<?> annotation : info.getAnnotatedEndpoints()) {
container.addEndpoint(annotation);
}
for(ServerEndpointConfig programatic : info.getProgramaticEndpoints()) {
container.addEndpoint(programatic);
}
} catch (DeploymentException e) {
throw new RuntimeException(e);
}
deploymentInfo.addFilter(Servlets.filter(FILTER_NAME, JsrWebSocketFilter.class).setAsyncSupported(true));
deploymentInfo.addFilterUrlMapping(FILTER_NAME, "/*", DispatcherType.REQUEST);
servletContext.setAttribute(ServerContainer.class.getName(), container);
info.containerReady(container);
}
}
| websockets-jsr/src/main/java/io/undertow/websockets/jsr/Bootstrap.java | package io.undertow.websockets.jsr;
import io.undertow.servlet.ServletExtension;
import io.undertow.servlet.Servlets;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.ThreadSetupAction;
import io.undertow.servlet.core.CompositeThreadSetupAction;
import io.undertow.servlet.core.ContextClassLoaderSetupAction;
import io.undertow.servlet.spec.ServletContextImpl;
import javax.servlet.DispatcherType;
import javax.websocket.DeploymentException;
import javax.websocket.server.ServerContainer;
import javax.websocket.server.ServerEndpointConfig;
import java.util.ArrayList;
import java.util.List;
/**
* @author Stuart Douglas
*/
public class Bootstrap implements ServletExtension {
public static final String FILTER_NAME = "Undertow Web Socket Filter";
@Override
public void handleDeployment(DeploymentInfo deploymentInfo, ServletContextImpl servletContext) {
WebSocketDeploymentInfo info = (WebSocketDeploymentInfo) deploymentInfo.getServletContextAttributes().get(WebSocketDeploymentInfo.ATTRIBUTE_NAME);
if (info == null) {
return;
}
final List<ThreadSetupAction> setup = new ArrayList<ThreadSetupAction>();
setup.add(new ContextClassLoaderSetupAction(deploymentInfo.getClassLoader()));
setup.addAll(deploymentInfo.getThreadSetupActions());
final CompositeThreadSetupAction threadSetupAction = new CompositeThreadSetupAction(setup);
ServerWebSocketContainer container = new ServerWebSocketContainer(deploymentInfo.getClassIntrospecter(), info.getWorker(), info.getBuffers(), threadSetupAction);
try {
for (Class<?> annotation : info.getAnnotatedEndpoints()) {
container.addEndpoint(annotation);
}
for(ServerEndpointConfig programatic : info.getProgramaticEndpoints()) {
container.addEndpoint(programatic);
}
} catch (DeploymentException e) {
throw new RuntimeException(e);
}
deploymentInfo.addFilter(Servlets.filter(FILTER_NAME, JsrWebSocketFilter.class));
deploymentInfo.addFilterUrlMapping(FILTER_NAME, "/*", DispatcherType.REQUEST);
servletContext.setAttribute(ServerContainer.class.getName(), container);
info.containerReady(container);
}
}
| Make the JSR web socket filter support async requests
| websockets-jsr/src/main/java/io/undertow/websockets/jsr/Bootstrap.java | Make the JSR web socket filter support async requests | <ide><path>ebsockets-jsr/src/main/java/io/undertow/websockets/jsr/Bootstrap.java
<ide> } catch (DeploymentException e) {
<ide> throw new RuntimeException(e);
<ide> }
<del> deploymentInfo.addFilter(Servlets.filter(FILTER_NAME, JsrWebSocketFilter.class));
<add> deploymentInfo.addFilter(Servlets.filter(FILTER_NAME, JsrWebSocketFilter.class).setAsyncSupported(true));
<ide> deploymentInfo.addFilterUrlMapping(FILTER_NAME, "/*", DispatcherType.REQUEST);
<ide> servletContext.setAttribute(ServerContainer.class.getName(), container);
<ide> info.containerReady(container); |
|
Java | mit | error: pathspec 'momo-manage/src/main/java/com/momohelp/calculate/service/ICost.java' did not match any file(s) known to git
| 1c64bcff17129806649ec31fa63fdfe0fad94228 | 1 | momo3210/gold,momo3210/gold,momo3210/gold | package com.momohelp.calculate.service;
import com.momohelp.model.User;
public interface ICost {
/**
*
* @param user
* 当前会员
* @return boolean true 表示计算成功 false 计算失败
*/
public abstract boolean premium(User user);
// 推荐奖计算
public abstract void recommend(User user);
// 管理奖计算
public abstract void manage(User user);
public abstract void burn(User user);
// 鸡饲料计算
public abstract void feed(User user);
// 下蛋利息计算
public abstract void egg();
// 鸡苗饲养利息计算
public abstract void keepe();
} | momo-manage/src/main/java/com/momohelp/calculate/service/ICost.java | 增加生产消费队列以及线程池 | momo-manage/src/main/java/com/momohelp/calculate/service/ICost.java | 增加生产消费队列以及线程池 | <ide><path>omo-manage/src/main/java/com/momohelp/calculate/service/ICost.java
<add>package com.momohelp.calculate.service;
<add>
<add>import com.momohelp.model.User;
<add>
<add>public interface ICost {
<add>
<add> /**
<add> *
<add> * @param user
<add> * 当前会员
<add> * @return boolean true 表示计算成功 false 计算失败
<add> */
<add> public abstract boolean premium(User user);
<add>
<add> // 推荐奖计算
<add> public abstract void recommend(User user);
<add>
<add> // 管理奖计算
<add> public abstract void manage(User user);
<add>
<add> public abstract void burn(User user);
<add>
<add> // 鸡饲料计算
<add> public abstract void feed(User user);
<add>
<add> // 下蛋利息计算
<add> public abstract void egg();
<add>
<add> // 鸡苗饲养利息计算
<add> public abstract void keepe();
<add>
<add>} |
|
Java | apache-2.0 | d9b10289c85bbe4c5abe10a60cde9148d6e391ed | 0 | openengsb/openengsb,openengsb/openengsb,openengsb/openengsb,tobster/openengsb,tobster/openengsb,openengsb/openengsb,openengsb/openengsb,tobster/openengsb,tobster/openengsb,openengsb/openengsb | /**
Copyright 2010 OpenEngSB Division, Vienna University of Technology
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.openengsb.drools.source;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Timer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.drools.RuleBase;
import org.drools.RuleBaseFactory;
import org.drools.compiler.DroolsParserException;
import org.drools.compiler.PackageBuilder;
import org.drools.rule.Package;
import org.openengsb.drools.RuleBaseException;
import org.openengsb.drools.message.RuleBaseElementId;
import org.openengsb.drools.message.RuleBaseElementType;
import org.openengsb.drools.source.dir.DirectoryFunctionHandler;
import org.openengsb.drools.source.dir.DirectoryGlobalHandler;
import org.openengsb.drools.source.dir.DirectoryImportHandler;
import org.openengsb.drools.source.dir.DirectoryRuleHandler;
import org.openengsb.drools.source.dir.ReloadChecker;
public class DirectoryRuleSource extends RuleBaseSource {
private static final Log log = LogFactory.getLog(DirectoryRuleSource.class);
public static final String IMPORTS_FILENAME = "imports";
public static final String GLOBALS_FILENAME = "globals";
public static final String FUNC_EXTENSION = "func";
public static final String RULE_EXTENSION = "rule";
public static final String FLOW_EXTENSION = "rf";
private String path;
private RuleBase ruleBase;
private String prelude;
public DirectoryRuleSource() {
}
public DirectoryRuleSource(String path) {
this.path = path;
}
public final String getPath() {
return this.path;
}
public final void setPath(String path) {
this.path = path;
}
@Override
public RuleBase getRulebase() throws RuleBaseException {
if (this.ruleBase == null) {
ruleBase = RuleBaseFactory.newRuleBase();
initReloadListener();
readRuleBase();
}
return this.ruleBase;
}
private void initReloadListener() {
Timer t = new Timer(true);
t.schedule(new ReloadChecker(new File(path, "reload"), this), 0, 5000);
}
@Override
protected ResourceHandler<?> getRessourceHandler(RuleBaseElementType e) {
switch (e) {
case Rule:
return new DirectoryRuleHandler(this);
case Import:
return new DirectoryImportHandler(this);
case Function:
return new DirectoryFunctionHandler(this);
case Global:
return new DirectoryGlobalHandler(this);
default:
throw new UnsupportedOperationException("operation not implemented for type " + e);
}
}
public void readRuleBase() throws RuleBaseException {
if (this.path == null) {
throw new IllegalStateException("path must be set");
}
File pathFile = new File(path);
Collection<Package> packages;
try {
if (!pathFile.exists()) {
initRuleBase();
}
String imports = readImportsFromRulebaseDirectory();
String globals = readGlobalsFromRulebaseDirectory();
prelude = imports + globals;
Collection<File> dirs = listAllSubDirs(new File(this.path));
packages = new LinkedList<Package>();
for (File dir : dirs) {
Package p = doReadPackage(dir);
packages.add(p);
}
} catch (IOException e) {
throw new RuleBaseException(e);
}
ruleBase.lock();
for (Package ep : ruleBase.getPackages()) {
ruleBase.removePackage(ep.getName());
}
ruleBase.addPackages(packages.toArray(new Package[packages.size()]));
ruleBase.unlock();
}
private void initRuleBase() throws IOException {
File pathFile = new File(path);
pathFile.mkdirs();
URL defaultImports = this.getClass().getClassLoader().getResource("rulebase/imports");
URL defaultglobals = this.getClass().getClassLoader().getResource("rulebase/globals");
URL helloWorldRule = this.getClass().getClassLoader().getResource("rulebase/org/openengsb/hello1.rule");
FileUtils.copyURLToFile(defaultImports, new File(path, IMPORTS_FILENAME));
FileUtils.copyURLToFile(defaultglobals, new File(path, GLOBALS_FILENAME));
File packagePath = new File(path, "org/openengsb/hello1.rule");
packagePath.getParentFile().mkdirs();
FileUtils.copyURLToFile(helloWorldRule, packagePath);
}
public void readPackage(String packageName) throws RuleBaseException {
File dir = new File(this.path, packageName.replace(".", File.separator));
Package p;
try {
p = doReadPackage(dir);
} catch (IOException e) {
throw new RuleBaseException(e);
}
ruleBase.lock();
if (ruleBase.getPackage(packageName) != null) {
ruleBase.removePackage(packageName);
}
ruleBase.addPackage(p);
ruleBase.unlock();
}
private Package doReadPackage(File path) throws IOException, RuleBaseException {
StringBuffer content = new StringBuffer();
content.append(String.format("package %s;\n", getPackageName(path)));
content.append(prelude);
Collection<File> functions = listFiles(path, FUNC_EXTENSION);
for (File f : functions) {
String func = IOUtils.toString(new FileReader(f));
content.append(func);
}
Collection<File> rules = listFiles(path, RULE_EXTENSION);
for (File f : rules) {
String ruleName = FilenameUtils.getBaseName(f.getName());
content.append(String.format("rule \"%s\"\n", ruleName));
content.append(IOUtils.toString(new FileReader(f)));
content.append("end\n");
}
final PackageBuilder builder = new PackageBuilder();
try {
builder.addPackageFromDrl(new StringReader(content.toString()));
Collection<File> flows = listFiles(path, FLOW_EXTENSION);
for (File f : flows) {
builder.addProcessFromXml(new FileReader(f));
}
} catch (DroolsParserException e) {
throw new RuleBaseException(e);
}
if (builder.hasErrors()) {
log.error(content.toString());
throw new RuleBaseException(builder.getErrors().toString());
}
return builder.getPackage();
}
@SuppressWarnings("unchecked")
private Collection<File> listFiles(File path, String extension) {
Collection<File> functions = FileUtils.listFiles(path, new String[] { extension }, false);
return functions;
}
private String getPackageName(File file) {
String filePath = file.getAbsolutePath();
File path = new File(this.path);
String name = filePath.substring(path.getAbsolutePath().length() + 1);
return name.replace(File.separator, ".");
}
private static Collection<File> listAllSubDirs(File file) {
Collection<File> result = new LinkedList<File>();
for (File f : file.listFiles()) {
if (f.isDirectory()) {
result.add(f);
result.addAll(listAllSubDirs(f));
}
}
return result;
}
private String readGlobalsFromRulebaseDirectory() throws IOException {
File globalsFile = new File(this.path + File.separator + GLOBALS_FILENAME);
StringBuffer result = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(globalsFile));
String line;
while ((line = reader.readLine()) != null) {
if (!line.trim().isEmpty()) {
result.append("global ");
result.append(line);
result.append("\n");
}
}
reader.close();
return result.toString();
}
private String readImportsFromRulebaseDirectory() throws IOException {
File importsfile = new File(this.path + File.separator + IMPORTS_FILENAME);
StringBuffer result = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(importsfile));
String line;
while ((line = reader.readLine()) != null) {
if (!line.trim().isEmpty()) {
result.append("import ");
result.append(line);
result.append("\n");
}
}
reader.close();
return result.toString();
}
public File getFilePath(RuleBaseElementId id) {
switch (id.getType()) {
case Import:
return new File(this.path, IMPORTS_FILENAME);
case Global:
return new File(this.path, GLOBALS_FILENAME);
case Function:
return new File(this.path, getPathName(id) + FUNC_EXTENSION);
case Rule:
return new File(this.path, getPathName(id) + RULE_EXTENSION);
}
return null;
}
private String getPathName(RuleBaseElementId id) {
StringBuffer result = new StringBuffer();
result.append(id.getPackageName().replace('.', File.separatorChar));
result.append(File.separator);
result.append(id.getName());
result.append(".");
return result.toString();
}
}
| core/workflow/service-engine/src/main/java/org/openengsb/drools/source/DirectoryRuleSource.java | /**
Copyright 2010 OpenEngSB Division, Vienna University of Technology
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.openengsb.drools.source;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Timer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.drools.RuleBase;
import org.drools.RuleBaseFactory;
import org.drools.compiler.DroolsParserException;
import org.drools.compiler.PackageBuilder;
import org.drools.rule.Package;
import org.openengsb.drools.RuleBaseException;
import org.openengsb.drools.message.RuleBaseElementId;
import org.openengsb.drools.message.RuleBaseElementType;
import org.openengsb.drools.source.dir.DirectoryFunctionHandler;
import org.openengsb.drools.source.dir.DirectoryGlobalHandler;
import org.openengsb.drools.source.dir.DirectoryImportHandler;
import org.openengsb.drools.source.dir.DirectoryRuleHandler;
import org.openengsb.drools.source.dir.ReloadChecker;
public class DirectoryRuleSource extends RuleBaseSource {
private static final Log log = LogFactory.getLog(DirectoryRuleSource.class);
public static final String IMPORTS_FILENAME = "imports";
public static final String GLOBALS_FILENAME = "globals";
public static final String FUNC_EXTENSION = "func";
public static final String RULE_EXTENSION = "rule";
public static final String FLOW_EXTENSION = "rf";
private String path;
private RuleBase ruleBase;
private String prelude;
public DirectoryRuleSource() {
}
public DirectoryRuleSource(String path) {
this.path = path;
}
public final String getPath() {
return this.path;
}
public final void setPath(String path) {
this.path = path;
}
@Override
public RuleBase getRulebase() throws RuleBaseException {
if (this.ruleBase == null) {
ruleBase = RuleBaseFactory.newRuleBase();
initReloadListener();
readRuleBase();
}
return this.ruleBase;
}
private void initReloadListener() {
Timer t = new Timer(true);
t.schedule(new ReloadChecker(new File(path, "reload"), this), 0, 5000);
}
@Override
protected ResourceHandler<?> getRessourceHandler(RuleBaseElementType e) {
switch (e) {
case Rule:
return new DirectoryRuleHandler(this);
case Import:
return new DirectoryImportHandler(this);
case Function:
return new DirectoryFunctionHandler(this);
case Global:
return new DirectoryGlobalHandler(this);
default:
throw new UnsupportedOperationException("operation not implemented for type " + e);
}
}
public void readRuleBase() throws RuleBaseException {
if (this.path == null) {
throw new IllegalStateException("path must be set");
}
File pathFile = new File(path);
Collection<Package> packages;
try {
if (!pathFile.exists()) {
initRuleBase();
}
String imports = readImportsFromRulebaseDirectory();
String globals = readGlobalsFromRulebaseDirectory();
prelude = imports + globals;
Collection<File> dirs = listAllSubDirs(new File(this.path));
packages = new LinkedList<Package>();
for (File dir : dirs) {
Package p = doReadPackage(dir);
packages.add(p);
}
} catch (IOException e) {
throw new RuleBaseException(e);
}
ruleBase.lock();
for (Package ep : ruleBase.getPackages()) {
ruleBase.removePackage(ep.getName());
}
ruleBase.addPackages(packages.toArray(new Package[packages.size()]));
ruleBase.unlock();
}
private void initRuleBase() throws IOException {
File pathFile = new File(path);
pathFile.mkdirs();
URL defaultImports = this.getClass().getClassLoader().getResource("rulebase/imports");
URL defaultglobals = this.getClass().getClassLoader().getResource("rulebase/globals");
URL helloWorldRule = this.getClass().getClassLoader().getResource("rulebase/org/openengsb/hello1.rule");
FileUtils.copyURLToFile(defaultImports, new File(path, IMPORTS_FILENAME));
FileUtils.copyURLToFile(defaultglobals, new File(path, GLOBALS_FILENAME));
File packagePath = new File(path, "org/openengsb/hello1.rule");
packagePath.getParentFile().mkdirs();
FileUtils.copyURLToFile(helloWorldRule, packagePath);
}
public void readPackage(String packageName) throws RuleBaseException {
File dir = new File(this.path, packageName.replace(".", File.separator));
Package p;
try {
p = doReadPackage(dir);
} catch (IOException e) {
throw new RuleBaseException(e);
}
ruleBase.lock();
if (ruleBase.getPackage(packageName) != null) {
ruleBase.removePackage(packageName);
}
ruleBase.addPackage(p);
ruleBase.unlock();
}
private Package doReadPackage(File path) throws IOException, RuleBaseException {
StringBuffer content = new StringBuffer();
content.append(String.format("package %s;\n", getPackageName(path)));
content.append(prelude);
Collection<File> functions = FileUtils.listFiles(path, new String[] { FUNC_EXTENSION }, false);
for (File f : functions) {
String func = IOUtils.toString(new FileReader(f));
content.append(func);
}
Collection<File> rules = FileUtils.listFiles(path, new String[] { RULE_EXTENSION }, false);
for (File f : rules) {
String ruleName = FilenameUtils.getBaseName(f.getName());
content.append(String.format("rule \"%s\"\n", ruleName));
content.append(IOUtils.toString(new FileReader(f)));
content.append("end\n");
}
final PackageBuilder builder = new PackageBuilder();
try {
builder.addPackageFromDrl(new StringReader(content.toString()));
Collection<File> flows = FileUtils.listFiles(path, new String[] { FLOW_EXTENSION }, false);
for (File f : flows) {
builder.addProcessFromXml(new FileReader(f));
}
} catch (DroolsParserException e) {
throw new RuleBaseException(e);
}
if (builder.hasErrors()) {
log.error(content.toString());
throw new RuleBaseException(builder.getErrors().toString());
}
return builder.getPackage();
}
private String getPackageName(File file) {
String filePath = file.getAbsolutePath();
File path = new File(this.path);
String name = filePath.substring(path.getAbsolutePath().length() + 1);
return name.replace(File.separator, ".");
}
private static Collection<File> listAllSubDirs(File file) {
Collection<File> result = new LinkedList<File>();
for (File f : file.listFiles()) {
if (f.isDirectory()) {
result.add(f);
result.addAll(listAllSubDirs(f));
}
}
return result;
}
private String readGlobalsFromRulebaseDirectory() throws IOException {
File globalsFile = new File(this.path + File.separator + GLOBALS_FILENAME);
StringBuffer result = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(globalsFile));
String line;
while ((line = reader.readLine()) != null) {
if (!line.trim().isEmpty()) {
result.append("global ");
result.append(line);
result.append("\n");
}
}
reader.close();
return result.toString();
}
private String readImportsFromRulebaseDirectory() throws IOException {
File importsfile = new File(this.path + File.separator + IMPORTS_FILENAME);
StringBuffer result = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(importsfile));
String line;
while ((line = reader.readLine()) != null) {
if (!line.trim().isEmpty()) {
result.append("import ");
result.append(line);
result.append("\n");
}
}
reader.close();
return result.toString();
}
public File getFilePath(RuleBaseElementId id) {
switch (id.getType()) {
case Import:
return new File(this.path, IMPORTS_FILENAME);
case Global:
return new File(this.path, GLOBALS_FILENAME);
case Function:
return new File(this.path, getPathName(id) + FUNC_EXTENSION);
case Rule:
return new File(this.path, getPathName(id) + RULE_EXTENSION);
}
return null;
}
private String getPathName(RuleBaseElementId id) {
StringBuffer result = new StringBuffer();
result.append(id.getPackageName().replace('.', File.separatorChar));
result.append(File.separator);
result.append(id.getName());
result.append(".");
return result.toString();
}
}
| move listFiles to seperate functions to get rid of the warnings
| core/workflow/service-engine/src/main/java/org/openengsb/drools/source/DirectoryRuleSource.java | move listFiles to seperate functions to get rid of the warnings | <ide><path>ore/workflow/service-engine/src/main/java/org/openengsb/drools/source/DirectoryRuleSource.java
<ide> StringBuffer content = new StringBuffer();
<ide> content.append(String.format("package %s;\n", getPackageName(path)));
<ide> content.append(prelude);
<del> Collection<File> functions = FileUtils.listFiles(path, new String[] { FUNC_EXTENSION }, false);
<add> Collection<File> functions = listFiles(path, FUNC_EXTENSION);
<ide> for (File f : functions) {
<ide> String func = IOUtils.toString(new FileReader(f));
<ide> content.append(func);
<ide> }
<del> Collection<File> rules = FileUtils.listFiles(path, new String[] { RULE_EXTENSION }, false);
<add> Collection<File> rules = listFiles(path, RULE_EXTENSION);
<ide> for (File f : rules) {
<ide> String ruleName = FilenameUtils.getBaseName(f.getName());
<ide> content.append(String.format("rule \"%s\"\n", ruleName));
<ide> final PackageBuilder builder = new PackageBuilder();
<ide> try {
<ide> builder.addPackageFromDrl(new StringReader(content.toString()));
<del> Collection<File> flows = FileUtils.listFiles(path, new String[] { FLOW_EXTENSION }, false);
<add> Collection<File> flows = listFiles(path, FLOW_EXTENSION);
<ide> for (File f : flows) {
<ide> builder.addProcessFromXml(new FileReader(f));
<ide> }
<ide>
<ide> return builder.getPackage();
<ide>
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> private Collection<File> listFiles(File path, String extension) {
<add> Collection<File> functions = FileUtils.listFiles(path, new String[] { extension }, false);
<add> return functions;
<ide> }
<ide>
<ide> private String getPackageName(File file) { |
|
JavaScript | mit | 42589aad90ac3fe7079dce503bc1450f0569ceb7 | 0 | ludumdare/ludumdare,local-minimum/ludumdare,zwrawr/ludumdare,povrazor/ludumdare,ludumdare/ludumdare,zwrawr/ludumdare,Noojuno/ludumdare,sgstair/ludumdare,ludumdare/ludumdare,zwrawr/ludumdare,local-minimum/ludumdare,zwrawr/ludumdare,Noojuno/ludumdare,povrazor/ludumdare,sgstair/ludumdare,sgstair/ludumdare,ludumdare/ludumdare,povrazor/ludumdare,Noojuno/ludumdare,local-minimum/ludumdare,Noojuno/ludumdare,povrazor/ludumdare,local-minimum/ludumdare,sgstair/ludumdare | import { h, Component } from 'preact/preact';
//import ShallowCompare from 'shallow-compare/index';
import NavSpinner from 'com/nav-spinner/spinner';
import NavLink from 'com/nav-link/link';
import SVGIcon from 'com/svg-icon/icon';
import IMG2 from 'com/img2/img2';
import ContentFooterButtonComments from 'com/content-footer/footer-button-comments';
import ContentCommentsMarkup from 'comments-markup';
import ContentCommentsComment from 'comments-comment';
import $Note from '../../shrub/js/note/note';
import $Node from '../../shrub/js/node/node';
export default class ContentComments extends Component {
constructor( props ) {
super(props);
this.state = {
'comments': null,
'tree': null,
'authors': null,
'newcomment': null,
};
this.onPublish = this.onPublish.bind(this);
}
componentWillMount() {
this.getComments(this.props.node);
}
genComment() {
return {
'parent': 0,
'node': this.props.node.id,
'author': this.props.user.id,
'body': '',
'love': 0,
};
}
getComments( node ) {
$Note.Get( node.id )
.then(r => {
// Has comments
if ( r.note && r.note.length ) {
this.setState({ 'comments': r.note, 'tree': null, 'authors': null });
}
// Does not have comments
else if ( r.note ) {
this.setState({ 'comments': [], 'tree': null, 'authors': null });
}
// Async first
this.getAuthors().then( rr => {
this.setState({'newcomment': this.genComment()});
});
// Sync last
this.setState({'tree': this.buildTree()});
})
.catch(err => {
this.setState({ 'error': err });
});
}
buildTree() {
var comments = this.state.comments;
// Only supports single level deep trees
var tree = {};
for ( var idx = 0; idx < comments.length; idx++ ) {
if ( comments[idx].parent === 0 ) {
tree[comments[idx].id] = {
'node': comments[idx],
};
}
else if ( comments[idx].parent && tree[comments[idx].parent] ) {
if (!tree[comments[idx].parent].child) {
tree[comments[idx].parent].child = {};
}
tree[comments[idx].parent].child[comments[idx].id] = {
'node': comments[idx],
};
}
else {
console.log('[Comments] Unable to find parent for '+comments[idx].id);
}
}
return tree;
}
getAuthors() {
var user = this.props.user;
var comments = this.state.comments;
if ( comments ) {
var Authors = [];
// Extract a list of all authors from comments
for ( var idx = 0; idx < comments.length; idx++ ) {
Authors.push(comments[idx].author);
}
// Add self (in case we start making comments
if ( user && user.id ) {
Authors.push(user.id);
}
// http://stackoverflow.com/a/23282067/5678759
// Remove Duplicates
Authors = Authors.filter(function(item, i, ar){ return ar.indexOf(item) === i; });
// Fetch authors
return $Node.GetKeyed( Authors )
.then(r => {
this.setState({ 'authors': r.node });
})
.catch(err => {
this.setState({ 'error': err });
});
}
}
renderComments( tree, indent = 0 ) {
var user = this.props.user;
var authors = this.state.authors;
var ret = [];
for ( var item in tree ) {
var comment = tree[item].node;
var author = authors[comment.author];
ret.push(<ContentCommentsComment user={user} comment={comment} author={author} indent={indent} />);
if ( tree[item].child ) {
ret.push(<div class="-indent">{this.renderComments(tree[item].child, indent+1)}</div>);
}
}
return ret;
}
renderPostNew() {
var user = this.props.user;
var authors = this.state.authors;
var comment = this.state.newcomment;
var author = authors[comment.author];
return <div class="-new-comment"><ContentCommentsComment user={user} comment={comment} author={author} indent={0} editing publish onpublish={this.onPublish}/></div>;
}
onPublish( e ) {
var node = this.props.node;
var newcomment = this.state.newcomment;
$Note.Add( newcomment.parent, newcomment.node, newcomment.body )
.then(r => {
if ( r.note ) {
var Now = new Date();
var comment = Object.assign({
'id': r.note,
'created': Now.toISOString(),
'modified': Now.toISOString()
}, newcomment);
// TODO: insert properly
this.state.comments.push(comment);
// Reset newcomment
newcomment.parent = 0;
newcomment.body = '';
this.setState({'tree': this.buildTree()});
}
else {
this.setState({ 'error': err });
}
})
.catch(err => {
this.setState({ 'error': err });
});
}
render( props, {comments, tree, authors, newcomment} ) {
var node = props.node;
var user = props.user;
var path = props.path;
var extra = props.extra;
// var FooterItems = [];
// if ( !props['no_comments'] )
// FooterItems.push(<ContentFooterButtonComments href={path} node={node} wedge_left_bottom />);
var ShowComments = <NavSpinner />;
if ( comments && tree && authors ) {
if ( comments.length )
ShowComments = this.renderComments(tree);
else
ShowComments = <div class={"-item -comment -indent-0"}><div class="-nothing">No Comments.</div></div>;
}
var ShowPostNew = null;
if ( user && user['id'] && newcomment ) {
ShowPostNew = this.renderPostNew();
}
else {
ShowPostNew = <div class="-new-comment" style="padding:0"><div class={"-item -comment -indent-0"}><div class="-nothing">Sign in to post a comment</div></div></div>;
}
return (
<div class={['content-base','content-common','content-comments',props['no_gap']?'-no-gap':'',props['no_header']?'-no-header':'']}>
<div class="-headline">COMMENTS</div>
{ShowComments}
{ShowPostNew}
<div class="content-footer content-footer-common -footer" style="height:0" />
</div>
);
}
// <div class="content-footer content-footer-common -footer">
// <div class="-left">
// </div>
// <div class="-right">
// {FooterItems}
// </div>
// </div>
}
| src/com/content-comments/comments.js | import { h, Component } from 'preact/preact';
//import ShallowCompare from 'shallow-compare/index';
import NavSpinner from 'com/nav-spinner/spinner';
import NavLink from 'com/nav-link/link';
import SVGIcon from 'com/svg-icon/icon';
import IMG2 from 'com/img2/img2';
import ContentFooterButtonComments from 'com/content-footer/footer-button-comments';
import ContentCommentsMarkup from 'comments-markup';
import ContentCommentsComment from 'comments-comment';
import $Note from '../../shrub/js/note/note';
import $Node from '../../shrub/js/node/node';
export default class ContentComments extends Component {
constructor( props ) {
super(props);
this.state = {
'comments': null,
'tree': null,
'authors': null,
'newcomment': null,
};
this.onPublish = this.onPublish.bind(this);
}
componentWillMount() {
this.getComments(this.props.node);
}
genComment() {
return {
'parent': 0,
'node': this.props.node.id,
'author': this.props.user.id,
'body': '',
'love': 0,
};
}
getComments( node ) {
$Note.Get( node.id )
.then(r => {
// Has comments
if ( r.note && r.note.length ) {
this.setState({ 'comments': r.note, 'tree': null, 'authors': null });
}
// Does not have comments
else if ( r.note ) {
this.setState({ 'comments': [], 'tree': null, 'authors': null });
}
// Async first
this.getAuthors().then( rr => {
this.setState({'newcomment': this.genComment()});
});
// Sync last
this.setState({'tree': this.buildTree()});
})
.catch(err => {
this.setState({ 'error': err });
});
}
buildTree() {
var comments = this.state.comments;
// Only supports single level deep trees
var tree = {};
for ( var idx = 0; idx < comments.length; idx++ ) {
if ( comments[idx].parent === 0 ) {
tree[comments[idx].id] = {
'node': comments[idx],
};
}
else if ( comments[idx].parent && tree[comments[idx].parent] ) {
if (!tree[comments[idx].parent].child) {
tree[comments[idx].parent].child = {};
}
tree[comments[idx].parent].child[comments[idx].id] = {
'node': comments[idx],
};
}
else {
console.log('[Comments] Unable to find parent for '+comments[idx].id);
}
}
return tree;
}
getAuthors() {
var user = this.props.user;
var comments = this.state.comments;
if ( comments ) {
var Authors = [];
// Extract a list of all authors from comments
for ( var idx = 0; idx < comments.length; idx++ ) {
Authors.push(comments[idx].author);
}
// Add self (in case we start making comments
if ( user && user.id ) {
Authors.push(user.id);
}
// http://stackoverflow.com/a/23282067/5678759
// Remove Duplicates
Authors = Authors.filter(function(item, i, ar){ return ar.indexOf(item) === i; });
// Fetch authors
return $Node.GetKeyed( Authors )
.then(r => {
this.setState({ 'authors': r.node });
})
.catch(err => {
this.setState({ 'error': err });
});
}
}
renderComments( tree, indent = 0 ) {
var user = this.props.user;
var authors = this.state.authors;
var ret = [];
for ( var item in tree ) {
var comment = tree[item].node;
var author = authors[comment.author];
ret.push(<ContentCommentsComment user={user} comment={comment} author={author} indent={indent} />);
if ( tree[item].child ) {
ret.push(<div class="-indent">{this.renderComments(tree[item].child, indent+1)}</div>);
}
}
return ret;
}
renderPostNew() {
var user = this.props.user;
var authors = this.state.authors;
var comment = this.state.newcomment;
var author = authors[comment.author];
return <div class="-new-comment"><ContentCommentsComment user={user} comment={comment} author={author} indent={0} editing publish onpublish={this.onPublish}/></div>;
}
onPublish( e ) {
var node = this.props.node;
var newcomment = this.state.newcomment;
$Note.Add( newcomment.parent, newcomment.node, newcomment.body )
.then(r => {
if ( r.note ) {
var comment = Object.assign({'id': r.note}, newcomment);
// TODO: insert properly
this.state.comments.push(comment);
// Reset newcomment
newcomment.parent = 0;
newcomment.body = '';
this.setState({'tree': this.buildTree()});
}
else {
this.setState({ 'error': err });
}
})
.catch(err => {
this.setState({ 'error': err });
});
}
render( props, {comments, tree, authors, newcomment} ) {
var node = props.node;
var user = props.user;
var path = props.path;
var extra = props.extra;
// var FooterItems = [];
// if ( !props['no_comments'] )
// FooterItems.push(<ContentFooterButtonComments href={path} node={node} wedge_left_bottom />);
var ShowComments = <NavSpinner />;
if ( comments && tree && authors ) {
if ( comments.length )
ShowComments = this.renderComments(tree);
else
ShowComments = <div class={"-item -comment -indent-0"}><div class="-nothing">No Comments.</div></div>;
}
var ShowPostNew = null;
if ( user && user['id'] && newcomment ) {
ShowPostNew = this.renderPostNew();
}
else {
ShowPostNew = <div class="-new-comment" style="padding:0"><div class={"-item -comment -indent-0"}><div class="-nothing">Sign in to post a comment</div></div></div>;
}
return (
<div class={['content-base','content-common','content-comments',props['no_gap']?'-no-gap':'',props['no_header']?'-no-header':'']}>
<div class="-headline">COMMENTS</div>
{ShowComments}
{ShowPostNew}
<div class="content-footer content-footer-common -footer" style="height:0" />
</div>
);
}
// <div class="content-footer content-footer-common -footer">
// <div class="-left">
// </div>
// <div class="-right">
// {FooterItems}
// </div>
// </div>
}
| added placeholder dates to newly injected comments
| src/com/content-comments/comments.js | added placeholder dates to newly injected comments | <ide><path>rc/com/content-comments/comments.js
<ide> $Note.Add( newcomment.parent, newcomment.node, newcomment.body )
<ide> .then(r => {
<ide> if ( r.note ) {
<del> var comment = Object.assign({'id': r.note}, newcomment);
<add> var Now = new Date();
<add> var comment = Object.assign({
<add> 'id': r.note,
<add> 'created': Now.toISOString(),
<add> 'modified': Now.toISOString()
<add> }, newcomment);
<ide>
<ide> // TODO: insert properly
<ide> this.state.comments.push(comment); |
|
Java | agpl-3.0 | 7498c3422b3737bc0061989f85411f9a9a7d22cc | 0 | thehyve/Open-Clinica-Data-Uploader,thehyve/Open-Clinica-Data-Uploader,thehyve/Open-Clinica-Data-Uploader | package nl.thehyve.ocdu;
import nl.thehyve.ocdu.models.OcDefinitions.*;
import nl.thehyve.ocdu.soap.ResponseHandlers.GetStudyMetadataResponseHandler;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.core.AllOf.allOf;
import static org.hamcrest.core.Every.everyItem;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* Created by piotrzakrzewski on 02/05/16.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = OcduApplication.class)
@WebAppConfiguration
public class GetMetadataTests {
private static final Logger log = LoggerFactory.getLogger(GetMetadataTests.class);
private SOAPMessage mockedResponseGetMetadata;
private File testFile;
@Before
public void setUp() {
try {
MessageFactory messageFactory = MessageFactory.newInstance();
this.testFile = new File("docs/responseExamples/getStudyMetadata.xml"); //TODO: Replace File with Path
FileInputStream in = new FileInputStream(testFile);
mockedResponseGetMetadata = messageFactory.createMessage(null, in);//soapMessage;
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Test
public void testFileExists() throws Exception {
assertEquals(true, testFile.exists());
}
@Test
public void xpathSelectorTest() throws Exception {
String selector = GetStudyMetadataResponseHandler.presentInEventSelector;
XPath xpath = XPathFactory.newInstance().newXPath();
Document odm = GetStudyMetadataResponseHandler.getOdm(mockedResponseGetMetadata);
NodeList crfNodes = (NodeList) xpath.evaluate(selector,
odm, XPathConstants.NODESET);
assertEquals(true, crfNodes.getLength() > 0);
}
@Test
public void xpathCRfVersion() throws Exception {
String selector = GetStudyMetadataResponseHandler.CRF_VERSION_SELECTOR;
XPath xpath = XPathFactory.newInstance().newXPath();
Document odm = GetStudyMetadataResponseHandler.getOdm(mockedResponseGetMetadata);
String versions= (String) xpath.evaluate(selector,
odm, XPathConstants.STRING);
assertThat(versions, is(notNullValue()));
}
@Test
public void responseHandlerSimpleCase() throws Exception {
MetaData metaData = GetStudyMetadataResponseHandler.parseGetStudyMetadataResponse(mockedResponseGetMetadata);
assertThat(metaData, is(notNullValue()));
List<EventDefinition> eventDefinitions = metaData.getEventDefinitions();
assertThat(eventDefinitions
,
everyItem(is(allOf(notNullValue(), instanceOf(EventDefinition.class)))));
assertEquals(2, eventDefinitions.size());
EventDefinition eventDefinition = eventDefinitions.get(1);
assertEquals("SE_NONREPEATINGEVENT", eventDefinition.getStudyEventOID());
assertEquals("Non-repeating event", eventDefinition.getName());
List<CRFDefinition> crfDefinitions = eventDefinition.getCrfDefinitions();
assertEquals(7, crfDefinitions.size());
crfDefinitions.forEach(crDef -> {
assertThat(crDef.getVersion(), is(notNullValue()));
}
);
List<ItemGroupDefinition> itemGroupDefinitions = metaData.getItemGroupDefinitions();
assertEquals(24, itemGroupDefinitions.size());
int totalExpectedItemDefs = 282;
int totalExpectedItemNames = 57; // only items that are assigned to an ItemGroup are counted
Set<String> allItemNames = new HashSet<>();
List<ItemDefinition> allItemdefs = new ArrayList<>();
itemGroupDefinitions.forEach(itemGroupDefinition -> {
assertThat(itemGroupDefinition.getOid(), is(notNullValue()) );
assertThat(itemGroupDefinition.getName(), is(notNullValue()) );
assertThat(itemGroupDefinition.getItems(), is(notNullValue()) );
List<ItemDefinition> items = itemGroupDefinition.getItems();
assertTrue(items.size() > 0);
allItemdefs.addAll(items);
items.stream().forEach(item -> {
allItemNames.add(item.getName());
assertTrue(isUnique(item, items));
});
});
assertEquals(totalExpectedItemDefs, allItemdefs.size());
assertEquals(totalExpectedItemNames, allItemNames.size());
}
private boolean isUnique(ItemDefinition item, List<ItemDefinition> collection ) {
long count = collection.stream().filter(itemDefinition -> itemDefinition.getOid().equals(item.getOid())).count();
return count == 1;
}
}
| src/test/java/nl/thehyve/ocdu/GetMetadataTests.java | package nl.thehyve.ocdu;
import nl.thehyve.ocdu.models.OcDefinitions.*;
import nl.thehyve.ocdu.soap.ResponseHandlers.GetStudyMetadataResponseHandler;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.core.AllOf.allOf;
import static org.hamcrest.core.Every.everyItem;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* Created by piotrzakrzewski on 02/05/16.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = OcduApplication.class)
@WebAppConfiguration
public class GetMetadataTests {
private static final Logger log = LoggerFactory.getLogger(GetMetadataTests.class);
private SOAPMessage mockedResponseGetMetadata;
private File testFile;
@Before
public void setUp() {
try {
MessageFactory messageFactory = MessageFactory.newInstance();
this.testFile = new File("docs/responseExamples/getStudyMetadata.xml"); //TODO: Replace File with Path
FileInputStream in = new FileInputStream(testFile);
mockedResponseGetMetadata = messageFactory.createMessage(null, in);//soapMessage;
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Test
public void testFileExists() throws Exception {
assertEquals(true, testFile.exists());
}
@Test
public void xpathSelectorTest() throws Exception {
String selector = GetStudyMetadataResponseHandler.presentInEventSelector;
XPath xpath = XPathFactory.newInstance().newXPath();
Document odm = GetStudyMetadataResponseHandler.getOdm(mockedResponseGetMetadata);
NodeList crfNodes = (NodeList) xpath.evaluate(selector,
odm, XPathConstants.NODESET);
assertEquals(true, crfNodes.getLength() > 0);
}
@Test
public void xpathCRfVersion() throws Exception {
String selector = GetStudyMetadataResponseHandler.CRF_VERSION_SELECTOR;
XPath xpath = XPathFactory.newInstance().newXPath();
Document odm = GetStudyMetadataResponseHandler.getOdm(mockedResponseGetMetadata);
String versions= (String) xpath.evaluate(selector,
odm, XPathConstants.STRING);
assertThat(versions, is(notNullValue()));
}
@Test
public void responseHandlerSimpleCase() throws Exception {
MetaData metaData = GetStudyMetadataResponseHandler.parseGetStudyMetadataResponse(mockedResponseGetMetadata);
assertThat(metaData, is(notNullValue()));
List<EventDefinition> eventDefinitions = metaData.getEventDefinitions();
assertThat(eventDefinitions
,
everyItem(is(allOf(notNullValue(), instanceOf(EventDefinition.class)))));
assertEquals(2, eventDefinitions.size());
EventDefinition eventDefinition = eventDefinitions.get(1);
assertEquals("SE_NONREPEATINGEVENT", eventDefinition.getStudyEventOID());
assertEquals("Non-repeating event", eventDefinition.getName());
List<CRFDefinition> crfDefinitions = eventDefinition.getCrfDefinitions();
assertEquals(7, crfDefinitions.size());
crfDefinitions.forEach(crDef -> {
assertThat(crDef.getVersion(), is(notNullValue()));
}
);
List<ItemGroupDefinition> itemGroupDefinitions = metaData.getItemGroupDefinitions();
assertEquals(24, itemGroupDefinitions.size());
int totalExpectedItemDefs = 166;
List<ItemDefinition> allItemdefs = new ArrayList<>();
itemGroupDefinitions.forEach(itemGroupDefinition -> {
assertThat(itemGroupDefinition.getOid(), is(notNullValue()) );
assertThat(itemGroupDefinition.getName(), is(notNullValue()) );
assertThat(itemGroupDefinition.getItems(), is(notNullValue()) );
List<ItemDefinition> items = itemGroupDefinition.getItems();
assertTrue(items.size() > 0);
allItemdefs.addAll(items);
items.stream().forEach(item -> assertTrue(isUnique(item, items)));
});
assertEquals(totalExpectedItemDefs, allItemdefs.size());
}
private boolean isUnique(ItemDefinition item, List<ItemDefinition> collection ) {
long count = collection.stream().filter(itemDefinition -> itemDefinition.getOid().equals(item.getOid())).count();
return count == 1;
}
}
| Fix tests.
| src/test/java/nl/thehyve/ocdu/GetMetadataTests.java | Fix tests. | <ide><path>rc/test/java/nl/thehyve/ocdu/GetMetadataTests.java
<ide> import javax.xml.xpath.XPathFactory;
<ide> import java.io.File;
<ide> import java.io.FileInputStream;
<del>import java.util.ArrayList;
<del>import java.util.List;
<add>import java.util.*;
<ide>
<ide> import static org.hamcrest.CoreMatchers.is;
<ide> import static org.hamcrest.core.AllOf.allOf;
<ide> List<ItemGroupDefinition> itemGroupDefinitions = metaData.getItemGroupDefinitions();
<ide> assertEquals(24, itemGroupDefinitions.size());
<ide>
<del> int totalExpectedItemDefs = 166;
<add> int totalExpectedItemDefs = 282;
<add> int totalExpectedItemNames = 57; // only items that are assigned to an ItemGroup are counted
<add> Set<String> allItemNames = new HashSet<>();
<ide> List<ItemDefinition> allItemdefs = new ArrayList<>();
<ide> itemGroupDefinitions.forEach(itemGroupDefinition -> {
<ide> assertThat(itemGroupDefinition.getOid(), is(notNullValue()) );
<ide> List<ItemDefinition> items = itemGroupDefinition.getItems();
<ide> assertTrue(items.size() > 0);
<ide> allItemdefs.addAll(items);
<del> items.stream().forEach(item -> assertTrue(isUnique(item, items)));
<add> items.stream().forEach(item -> {
<add> allItemNames.add(item.getName());
<add> assertTrue(isUnique(item, items));
<add> });
<ide> });
<ide> assertEquals(totalExpectedItemDefs, allItemdefs.size());
<add> assertEquals(totalExpectedItemNames, allItemNames.size());
<ide> }
<ide>
<ide> |
|
Java | apache-2.0 | 78c77bb8e36ac646d5862ff410f69407a1950e98 | 0 | apache/wicket,bitstorm/wicket,topicusonderwijs/wicket,mafulafunk/wicket,AlienQueen/wicket,klopfdreh/wicket,topicusonderwijs/wicket,zwsong/wicket,mosoft521/wicket,mosoft521/wicket,aldaris/wicket,apache/wicket,martin-g/wicket-osgi,aldaris/wicket,Servoy/wicket,AlienQueen/wicket,mafulafunk/wicket,aldaris/wicket,bitstorm/wicket,dashorst/wicket,selckin/wicket,dashorst/wicket,topicusonderwijs/wicket,klopfdreh/wicket,freiheit-com/wicket,apache/wicket,selckin/wicket,apache/wicket,zwsong/wicket,apache/wicket,Servoy/wicket,AlienQueen/wicket,topicusonderwijs/wicket,astrapi69/wicket,bitstorm/wicket,AlienQueen/wicket,zwsong/wicket,klopfdreh/wicket,klopfdreh/wicket,freiheit-com/wicket,mafulafunk/wicket,bitstorm/wicket,zwsong/wicket,bitstorm/wicket,AlienQueen/wicket,martin-g/wicket-osgi,selckin/wicket,martin-g/wicket-osgi,freiheit-com/wicket,selckin/wicket,freiheit-com/wicket,astrapi69/wicket,klopfdreh/wicket,Servoy/wicket,Servoy/wicket,astrapi69/wicket,selckin/wicket,aldaris/wicket,mosoft521/wicket,astrapi69/wicket,dashorst/wicket,aldaris/wicket,Servoy/wicket,topicusonderwijs/wicket,dashorst/wicket,freiheit-com/wicket,dashorst/wicket,mosoft521/wicket,mosoft521/wicket | /*
* $Id$
* $Revision$
* $Date$
*
* ====================================================================
* 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.extensions.markup.html.datepicker;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Locale;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import wicket.Application;
import wicket.ResourceReference;
import wicket.markup.html.PackageResourceReference;
/**
* The settings of the date picker component. Use this to customize the datepicker
* (e.g. the icon, locale, format, etc).
*
* @author Eelco Hillenius
*/
public class DatePickerSettings implements Serializable
{
private static final long serialVersionUID = 1L;
/** log. */
private static Log log = LogFactory.getLog(DatePickerSettings.class);
/** all date formats. */
private static Properties dateformats = new Properties();
static
{
InputStream resourceAsStream = null;
try
{
resourceAsStream = DatePickerSettings.class.getResourceAsStream("dateformats.properties");
dateformats.load(resourceAsStream);
}
catch (IOException e)
{
log.error(e.getMessage(), e);
throw new RuntimeException(e);
}
finally
{
try
{
if(resourceAsStream != null) resourceAsStream.close();
}
catch (IOException ex)
{
// ignore
}
}
}
/**
* The format string that will be used to enter the date in the input field. This
* format will be honored even if the input field is hidden.
*/
private String ifFormat = null;
/**
* Wether the calendar is in ``single-click mode'' or ``double-click mode''. If
* true (the default) the calendar will be created in single-click mode.
*/
private boolean mode = true;
/**
* Specifies which day is to be displayed as the first day of week. Possible
* values are 0 to 6; 0 means Sunday, 1 means Monday, ..., 6 means Saturday. The
* end user can easily change this too, by clicking on the day name in the
* calendar header.
*/
private int firstDay = 0;
/**
* If ``true'' then the calendar will display week numbers.
*/
private boolean weekNumbers = true;
/**
* Alignment of the calendar, relative to the reference element. The reference
* element is dynamically chosen like this: if a displayArea is specified then it
* will be the reference element. Otherwise, the input field is the reference
* element.
* <p>
* Align may contain one or two characters. The first character dictates the
* vertical alignment, relative to the element, and the second character dictates
* the horizontal alignment. If the second character is missing it will be assumed
* "l" (the left margin of the calendar will be at the same horizontal position as
* the left margin of the element). The characters given for the align parameters
* are case sensitive. This function only makes sense when the calendar is in
* popup mode. After computing the position it uses Calendar.showAt to display the
* calendar there.
* </p>
* <p>
* <strong>Vertical alignment</strong> The first character in ``align'' can take
* one of the following values:
* <ul>
* <li>T -- completely above the reference element (bottom margin of the calendar
* aligned to the top margin of the element). </li>
* <li>t -- above the element but may overlap it (bottom margin of the calendar
* aligned to the bottom margin of the element). </li>
* <li>c -- the calendar displays vertically centered to the reference element.
* It might overlap it (that depends on the horizontal alignment). </li>
* <li>b -- below the element but may overlap it (top margin of the calendar
* aligned to the top margin of the element). </li>
* <li>B -- completely below the element (top margin of the calendar aligned to
* the bottom margin of the element). </li>
* </ul>
* </p>
* <p>
* <strong>Horizontal alignment</strong> The second character in ``align'' can
* take one of the following values:
* <ul>
* <li>L -- completely to the left of the reference element (right margin of the
* calendar aligned to the left margin of the element). </li>
* <li>l -- to the left of the element but may overlap it (left margin of the
* calendar aligned to the left margin of the element). </li>
* <li>c -- horizontally centered to the element. Might overlap it, depending on
* the vertical alignment. </li>
* <li>r -- to the right of the element but may overlap it (right margin of the
* calendar aligned to the right margin of the element). </li>
* <li>R -- completely to the right of the element (left margin of the calendar
* aligned to the right margin of the element). </li>
* </ul>
* </p>
*/
private String align = null;
/**
* If this is set to true then the calendar will also allow time selection.
*/
private boolean showsTime = false;
/**
* Set this to ``12'' or ``24'' to configure the way that the calendar will
* display time.
*/
private String timeFormat = null;
/**
* Set this to ``false'' if you want the calendar to update the field only when
* closed (by default it updates the field at each date change, even if the
* calendar is not closed).
*/
private boolean electric = true;
/**
* If set to ``true'' then days belonging to months overlapping with the currently
* displayed month will also be displayed in the calendar (but in a ``faded-out''
* color).
*/
private boolean showOthers = false;
/** the style. */
private ResourceReference style = null;
/** the button icon. */
private ResourceReference icon = null;
/** the language. */
private ResourceReference language = null;
/**
* Construct.
*/
public DatePickerSettings()
{
}
/**
* Return the properties as a script.
* @param locale the current locale
* @return the properties as a script
*/
public String toScript(Locale locale)
{
StringBuffer b = new StringBuffer();
// create the script that represents these properties. Only create entries for
// values that are different from the default value (save a bit bandwith)
if (!isMode())
{
b.append("\n\tmode : false,");
}
if (getFirstDay() != 0)
{
b.append("\n\tfistDay : ").append(getFirstDay()).append(",");
}
if (!isWeekNumbers())
{
b.append("\n\tweekNumbers : false,");
}
if (getAlign() != null)
{
b.append("\n\talign : ").append(getAlign()).append(",");
}
if (isShowsTime())
{
b.append("\n\tshowsTime : true,");
}
if (getTimeFormat() != null)
{
b.append("\n\timeFormat : ").append(getTimeFormat()).append(",");
}
if (!isElectric())
{
b.append("\n\telectric : false,");
}
if (isShowOthers())
{
b.append("\n\tshowOthers : true,");
}
// append date format
String ifFormat = getIfFormat(locale);
if (ifFormat != null)
{
b.append("\n\t\tifFormat : \"").append(ifFormat).append("\"");
}
return b.toString();
}
/**
* create a button icon.
* @return a button icon.
*/
public final PackageResourceReference newButtonIconRed()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "calendar_icon_1.gif");
}
/**
* create a button icon.
* @return a button icon.
*/
public final PackageResourceReference newButtonIconPlain()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "calendar_icon_2.gif");
}
/**
* create a button icon.
* @return a button icon.
*/
public final PackageResourceReference newButtonIconBlue()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "calendar_icon_3.gif");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleAqua()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/aqua/theme.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleWinter()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-blue.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleBlue()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-blue2.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleSummer()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-brown.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleGreen()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-green.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleSystem()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-system.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleTas()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-tas.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleWin2k()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-win2k.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleWin2k1()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-win2k-1.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleWin2k2()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/aqua/theme.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleWin2kCold1()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-win2k-cold-1.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleWin2kCold2()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-win2k-cold-2.css");
}
/**
* Gets the align.
* @return align
*/
public String getAlign()
{
return align;
}
/**
* Sets the align.
* @param align align
*/
public void setAlign(String align)
{
this.align = align;
}
/**
* Gets the electric.
* @return electric
*/
public boolean isElectric()
{
return electric;
}
/**
* Sets the electric.
* @param electric electric
*/
public void setElectric(boolean electric)
{
this.electric = electric;
}
/**
* Gets the firstDay.
* @return firstDay
*/
public int getFirstDay()
{
return firstDay;
}
/**
* Sets the firstDay.
* @param firstDay firstDay
*/
public void setFirstDay(int firstDay)
{
this.firstDay = firstDay;
}
/**
* Gets the ifFormat.
* @param locale current locale
* @return ifFormat
*/
public String getIfFormat(Locale locale)
{
// when it was set explicitly, return that
if (ifFormat != null)
{
return ifFormat;
}
// else, get it from our map - might be null, but our calling
// function can handle that
return dateformats.getProperty(locale.toString());
}
/**
* Sets the ifFormat.
* @param ifFormat ifFormat
*/
public void setIfFormat(String ifFormat)
{
this.ifFormat = ifFormat;
}
/**
* Gets the mode.
* @return mode
*/
public boolean isMode()
{
return mode;
}
/**
* Sets the mode.
* @param mode mode
*/
public void setMode(boolean mode)
{
this.mode = mode;
}
/**
* Gets the showOthers.
* @return showOthers
*/
public boolean isShowOthers()
{
return showOthers;
}
/**
* Sets the showOthers.
* @param showOthers showOthers
*/
public void setShowOthers(boolean showOthers)
{
this.showOthers = showOthers;
}
/**
* Gets the showsTime.
* @return showsTime
*/
public boolean isShowsTime()
{
return showsTime;
}
/**
* Sets the showsTime.
* @param showsTime showsTime
*/
public void setShowsTime(boolean showsTime)
{
this.showsTime = showsTime;
}
/**
* Gets the timeFormat.
* @return timeFormat
*/
public String getTimeFormat()
{
return timeFormat;
}
/**
* Sets the timeFormat.
* @param timeFormat timeFormat
*/
public void setTimeFormat(String timeFormat)
{
this.timeFormat = timeFormat;
}
/**
* Gets the weekNumbers.
* @return weekNumbers
*/
public boolean isWeekNumbers()
{
return weekNumbers;
}
/**
* Sets the weekNumbers.
* @param weekNumbers weekNumbers
*/
public void setWeekNumbers(boolean weekNumbers)
{
this.weekNumbers = weekNumbers;
}
/**
* Gets the icon.
* @return icon
*/
public ResourceReference getIcon()
{
if (icon == null)
{
icon = newButtonIconRed();
}
return icon;
}
/**
* Sets the icon.
* @param icon icon
*/
public void setIcon(ResourceReference icon)
{
this.icon = icon;
}
/**
* Gets the language.
* @param currentLocale the current locale
* @return language
*/
public ResourceReference getLanguage(Locale currentLocale)
{
// if the language was set explicitly, return that
if (language != null)
{
return language;
}
return DatePickerComponentInitializer.getLanguage(currentLocale);
}
/**
* Sets the language.
* @param language language
*/
public void setLanguage(ResourceReference language)
{
this.language = language;
}
/**
* Gets the style.
* @return style
*/
public ResourceReference getStyle()
{
if (style == null)
{
style = newStyleAqua();
}
return style;
}
/**
* Sets the style.
* @param style style
*/
public void setStyle(ResourceReference style)
{
this.style = style;
}
} | wicket-extensions/src/java/wicket/extensions/markup/html/datepicker/DatePickerSettings.java | /*
* $Id$
* $Revision$
* $Date$
*
* ====================================================================
* 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.extensions.markup.html.datepicker;
import java.io.IOException;
import java.io.Serializable;
import java.util.Locale;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import wicket.Application;
import wicket.ResourceReference;
import wicket.markup.html.PackageResourceReference;
/**
* The settings of the date picker component. Use this to customize the datepicker
* (e.g. the icon, locale, format, etc).
*
* @author Eelco Hillenius
*/
public class DatePickerSettings implements Serializable
{
private static final long serialVersionUID = 1L;
/** log. */
private static Log log = LogFactory.getLog(DatePickerSettings.class);
/** all date formats. */
private static Properties dateformats = new Properties();
static
{
try
{
dateformats.load(DatePickerSettings.class.getResourceAsStream("dateformats.properties"));
}
catch (IOException e)
{
log.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
/**
* The format string that will be used to enter the date in the input field. This
* format will be honored even if the input field is hidden.
*/
private String ifFormat = null;
/**
* Wether the calendar is in ``single-click mode'' or ``double-click mode''. If
* true (the default) the calendar will be created in single-click mode.
*/
private boolean mode = true;
/**
* Specifies which day is to be displayed as the first day of week. Possible
* values are 0 to 6; 0 means Sunday, 1 means Monday, ..., 6 means Saturday. The
* end user can easily change this too, by clicking on the day name in the
* calendar header.
*/
private int firstDay = 0;
/**
* If ``true'' then the calendar will display week numbers.
*/
private boolean weekNumbers = true;
/**
* Alignment of the calendar, relative to the reference element. The reference
* element is dynamically chosen like this: if a displayArea is specified then it
* will be the reference element. Otherwise, the input field is the reference
* element.
* <p>
* Align may contain one or two characters. The first character dictates the
* vertical alignment, relative to the element, and the second character dictates
* the horizontal alignment. If the second character is missing it will be assumed
* "l" (the left margin of the calendar will be at the same horizontal position as
* the left margin of the element). The characters given for the align parameters
* are case sensitive. This function only makes sense when the calendar is in
* popup mode. After computing the position it uses Calendar.showAt to display the
* calendar there.
* </p>
* <p>
* <strong>Vertical alignment</strong> The first character in ``align'' can take
* one of the following values:
* <ul>
* <li>T -- completely above the reference element (bottom margin of the calendar
* aligned to the top margin of the element). </li>
* <li>t -- above the element but may overlap it (bottom margin of the calendar
* aligned to the bottom margin of the element). </li>
* <li>c -- the calendar displays vertically centered to the reference element.
* It might overlap it (that depends on the horizontal alignment). </li>
* <li>b -- below the element but may overlap it (top margin of the calendar
* aligned to the top margin of the element). </li>
* <li>B -- completely below the element (top margin of the calendar aligned to
* the bottom margin of the element). </li>
* </ul>
* </p>
* <p>
* <strong>Horizontal alignment</strong> The second character in ``align'' can
* take one of the following values:
* <ul>
* <li>L -- completely to the left of the reference element (right margin of the
* calendar aligned to the left margin of the element). </li>
* <li>l -- to the left of the element but may overlap it (left margin of the
* calendar aligned to the left margin of the element). </li>
* <li>c -- horizontally centered to the element. Might overlap it, depending on
* the vertical alignment. </li>
* <li>r -- to the right of the element but may overlap it (right margin of the
* calendar aligned to the right margin of the element). </li>
* <li>R -- completely to the right of the element (left margin of the calendar
* aligned to the right margin of the element). </li>
* </ul>
* </p>
*/
private String align = null;
/**
* If this is set to true then the calendar will also allow time selection.
*/
private boolean showsTime = false;
/**
* Set this to ``12'' or ``24'' to configure the way that the calendar will
* display time.
*/
private String timeFormat = null;
/**
* Set this to ``false'' if you want the calendar to update the field only when
* closed (by default it updates the field at each date change, even if the
* calendar is not closed).
*/
private boolean electric = true;
/**
* If set to ``true'' then days belonging to months overlapping with the currently
* displayed month will also be displayed in the calendar (but in a ``faded-out''
* color).
*/
private boolean showOthers = false;
/** the style. */
private ResourceReference style = null;
/** the button icon. */
private ResourceReference icon = null;
/** the language. */
private ResourceReference language = null;
/**
* Construct.
*/
public DatePickerSettings()
{
}
/**
* Return the properties as a script.
* @param locale the current locale
* @return the properties as a script
*/
public String toScript(Locale locale)
{
StringBuffer b = new StringBuffer();
// create the script that represents these properties. Only create entries for
// values that are different from the default value (save a bit bandwith)
if (!isMode())
{
b.append("\n\tmode : false,");
}
if (getFirstDay() != 0)
{
b.append("\n\tfistDay : ").append(getFirstDay()).append(",");
}
if (!isWeekNumbers())
{
b.append("\n\tweekNumbers : false,");
}
if (getAlign() != null)
{
b.append("\n\talign : ").append(getAlign()).append(",");
}
if (isShowsTime())
{
b.append("\n\tshowsTime : true,");
}
if (getTimeFormat() != null)
{
b.append("\n\timeFormat : ").append(getTimeFormat()).append(",");
}
if (!isElectric())
{
b.append("\n\telectric : false,");
}
if (isShowOthers())
{
b.append("\n\tshowOthers : true,");
}
// append date format
String ifFormat = getIfFormat(locale);
if (ifFormat != null)
{
b.append("\n\t\tifFormat : \"").append(ifFormat).append("\"");
}
return b.toString();
}
/**
* create a button icon.
* @return a button icon.
*/
public final PackageResourceReference newButtonIconRed()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "calendar_icon_1.gif");
}
/**
* create a button icon.
* @return a button icon.
*/
public final PackageResourceReference newButtonIconPlain()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "calendar_icon_2.gif");
}
/**
* create a button icon.
* @return a button icon.
*/
public final PackageResourceReference newButtonIconBlue()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "calendar_icon_3.gif");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleAqua()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/aqua/theme.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleWinter()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-blue.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleBlue()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-blue2.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleSummer()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-brown.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleGreen()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-green.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleSystem()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-system.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleTas()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-tas.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleWin2k()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-win2k.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleWin2k1()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-win2k-1.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleWin2k2()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/aqua/theme.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleWin2kCold1()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-win2k-cold-1.css");
}
/**
* Create a style
* @return a style
*/
public final PackageResourceReference newStyleWin2kCold2()
{
return new PackageResourceReference(Application.get(), DatePickerSettings.class, "style/calendar-win2k-cold-2.css");
}
/**
* Gets the align.
* @return align
*/
public String getAlign()
{
return align;
}
/**
* Sets the align.
* @param align align
*/
public void setAlign(String align)
{
this.align = align;
}
/**
* Gets the electric.
* @return electric
*/
public boolean isElectric()
{
return electric;
}
/**
* Sets the electric.
* @param electric electric
*/
public void setElectric(boolean electric)
{
this.electric = electric;
}
/**
* Gets the firstDay.
* @return firstDay
*/
public int getFirstDay()
{
return firstDay;
}
/**
* Sets the firstDay.
* @param firstDay firstDay
*/
public void setFirstDay(int firstDay)
{
this.firstDay = firstDay;
}
/**
* Gets the ifFormat.
* @param locale current locale
* @return ifFormat
*/
public String getIfFormat(Locale locale)
{
// when it was set explicitly, return that
if (ifFormat != null)
{
return ifFormat;
}
// else, get it from our map - might be null, but our calling
// function can handle that
return dateformats.getProperty(locale.toString());
}
/**
* Sets the ifFormat.
* @param ifFormat ifFormat
*/
public void setIfFormat(String ifFormat)
{
this.ifFormat = ifFormat;
}
/**
* Gets the mode.
* @return mode
*/
public boolean isMode()
{
return mode;
}
/**
* Sets the mode.
* @param mode mode
*/
public void setMode(boolean mode)
{
this.mode = mode;
}
/**
* Gets the showOthers.
* @return showOthers
*/
public boolean isShowOthers()
{
return showOthers;
}
/**
* Sets the showOthers.
* @param showOthers showOthers
*/
public void setShowOthers(boolean showOthers)
{
this.showOthers = showOthers;
}
/**
* Gets the showsTime.
* @return showsTime
*/
public boolean isShowsTime()
{
return showsTime;
}
/**
* Sets the showsTime.
* @param showsTime showsTime
*/
public void setShowsTime(boolean showsTime)
{
this.showsTime = showsTime;
}
/**
* Gets the timeFormat.
* @return timeFormat
*/
public String getTimeFormat()
{
return timeFormat;
}
/**
* Sets the timeFormat.
* @param timeFormat timeFormat
*/
public void setTimeFormat(String timeFormat)
{
this.timeFormat = timeFormat;
}
/**
* Gets the weekNumbers.
* @return weekNumbers
*/
public boolean isWeekNumbers()
{
return weekNumbers;
}
/**
* Sets the weekNumbers.
* @param weekNumbers weekNumbers
*/
public void setWeekNumbers(boolean weekNumbers)
{
this.weekNumbers = weekNumbers;
}
/**
* Gets the icon.
* @return icon
*/
public ResourceReference getIcon()
{
if (icon == null)
{
icon = newButtonIconRed();
}
return icon;
}
/**
* Sets the icon.
* @param icon icon
*/
public void setIcon(ResourceReference icon)
{
this.icon = icon;
}
/**
* Gets the language.
* @param currentLocale the current locale
* @return language
*/
public ResourceReference getLanguage(Locale currentLocale)
{
// if the language was set explicitly, return that
if (language != null)
{
return language;
}
return DatePickerComponentInitializer.getLanguage(currentLocale);
}
/**
* Sets the language.
* @param language language
*/
public void setLanguage(ResourceReference language)
{
this.language = language;
}
/**
* Gets the style.
* @return style
*/
public ResourceReference getStyle()
{
if (style == null)
{
style = newStyleAqua();
}
return style;
}
/**
* Sets the style.
* @param style style
*/
public void setStyle(ResourceReference style)
{
this.style = style;
}
} | close resource stream
git-svn-id: ac804e38dcddf5e42ac850d29d9218b7df6087b7@460227 13f79535-47bb-0310-9956-ffa450edef68
| wicket-extensions/src/java/wicket/extensions/markup/html/datepicker/DatePickerSettings.java | close resource stream | <ide><path>icket-extensions/src/java/wicket/extensions/markup/html/datepicker/DatePickerSettings.java
<ide> package wicket.extensions.markup.html.datepicker;
<ide>
<ide> import java.io.IOException;
<add>import java.io.InputStream;
<ide> import java.io.Serializable;
<ide> import java.util.Locale;
<ide> import java.util.Properties;
<ide> private static Properties dateformats = new Properties();
<ide> static
<ide> {
<add> InputStream resourceAsStream = null;
<ide> try
<ide> {
<del> dateformats.load(DatePickerSettings.class.getResourceAsStream("dateformats.properties"));
<add> resourceAsStream = DatePickerSettings.class.getResourceAsStream("dateformats.properties");
<add> dateformats.load(resourceAsStream);
<ide> }
<ide> catch (IOException e)
<ide> {
<ide> log.error(e.getMessage(), e);
<ide> throw new RuntimeException(e);
<add> }
<add> finally
<add> {
<add> try
<add> {
<add> if(resourceAsStream != null) resourceAsStream.close();
<add> }
<add> catch (IOException ex)
<add> {
<add> // ignore
<add> }
<ide> }
<ide> }
<ide> |
|
Java | mit | 954b380ad5ee37c2611040971ad5c70667944274 | 0 | ming-soft/MCMS,ming-soft/MCMS,ming-soft/MCMS,ming-soft/MCMS | /**
* The MIT License (MIT)
* Copyright (c) 2020 铭软科技(mingsoft.net)
* 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 net.mingsoft.cms.biz.impl;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import net.mingsoft.base.biz.impl.BaseBizImpl;
import net.mingsoft.base.dao.IBaseDao;
import net.mingsoft.basic.util.PinYinUtil;
import net.mingsoft.cms.biz.ICategoryBiz;
import net.mingsoft.cms.dao.ICategoryDao;
import net.mingsoft.cms.dao.IContentDao;
import net.mingsoft.cms.entity.CategoryEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
* 分类管理持久化层
* @author 铭飞开发团队
* 创建日期:2019-11-28 15:12:32<br/>
* 历史修订:<br/>
*/
@Service("cmscategoryBizImpl")
@Transactional(rollbackFor = RuntimeException.class)
public class CategoryBizImpl extends BaseBizImpl<ICategoryDao, CategoryEntity> implements ICategoryBiz {
@Autowired
private ICategoryDao categoryDao;
@Autowired
private IContentDao contentDao;
@Override
protected IBaseDao getDao() {
// TODO Auto-generated method stub
return categoryDao;
}
@Override
public List<CategoryEntity> queryChilds(CategoryEntity category) {
// TODO Auto-generated method stub
return categoryDao.queryChildren(category);
}
@Override
public void saveEntity(CategoryEntity categoryEntity) {
// TODO Auto-generated method stub
String pingYin = PinYinUtil.getPingYin(categoryEntity.getCategoryTitle());
//如果用户自己填入了拼音则使用用户的
if (StrUtil.isNotBlank(categoryEntity.getCategoryPinyin())) {
pingYin = categoryEntity.getCategoryPinyin();
}
CategoryEntity category=new CategoryEntity();
category.setCategoryPinyin(pingYin);
Object categoryBizEntity = getEntity(category);
setParentId(categoryEntity);
categoryEntity.setCategoryPinyin(pingYin);
//更新新的父级
if(StrUtil.isNotBlank(categoryEntity.getCategoryId())&&!"0".equals(categoryEntity.getCategoryId())){
CategoryEntity parent = getById(categoryEntity.getCategoryId());
//如果之前是叶子节点就更新
if(parent.getLeaf()){
parent.setLeaf(false);
updateById(parent);
}
}
categoryEntity.setLeaf(false);
//如果是新增栏目一定是叶子节点
if (StrUtil.isEmpty(categoryEntity.getId())) {
categoryEntity.setLeaf(true);
}
super.save(categoryEntity);
//拼音存在则拼接id
if(categoryBizEntity!=null){
categoryEntity.setCategoryPinyin(pingYin+categoryEntity.getId());
}
CategoryEntity parentCategory = null;
if (StringUtils.isNotBlank(categoryEntity.getCategoryId())) {
parentCategory = (CategoryEntity)getById(categoryEntity.getCategoryId());
}
//保存链接地址
String path=ObjectUtil.isNotNull(parentCategory)?parentCategory.getCategoryPath():"";
categoryEntity.setCategoryPath( path+"/" + categoryEntity.getCategoryPinyin());
setTopId(categoryEntity);
super.updateById(categoryEntity);
}
private void setParentId(CategoryEntity categoryEntity) {
String path = "";
if(StringUtils.isNotEmpty(categoryEntity.getCategoryId())&&Long.parseLong(categoryEntity.getCategoryId())>0) {
CategoryEntity category = (CategoryEntity)getById(categoryEntity.getCategoryId());
path = category.getCategoryPath();
if(StringUtils.isEmpty(category.getCategoryParentIds())) {
categoryEntity.setCategoryParentIds(category.getId());
} else {
categoryEntity.setCategoryParentIds(category.getCategoryParentIds()+","+category.getId());
}
}else {
categoryEntity.setCategoryParentIds(null);
}
//保存时先保存再修改链接地址,修改时直接修改
if(StringUtils.isNotBlank(categoryEntity.getId())) {
categoryEntity.setCategoryPath(path+ "/" + categoryEntity.getCategoryPinyin());
}
}
private void setChildParentId(CategoryEntity categoryEntity, String topId) {
CategoryEntity category=new CategoryEntity();
category.setCategoryId(categoryEntity.getId());
List<CategoryEntity> list = categoryDao.query(category);
list.forEach(x->{
if(StringUtils.isEmpty(categoryEntity.getCategoryParentIds())) {
x.setCategoryParentIds(categoryEntity.getId());
} else {
x.setCategoryParentIds(categoryEntity.getCategoryParentIds()+","+categoryEntity.getId());
}
//更新topid
x.setTopId(topId);
String path=categoryEntity.getCategoryPath();
//判断是否有parentIds
x.setCategoryPath(path+"/"+x.getCategoryPinyin());
//去除多余的/符号
super.updateEntity(x);
setChildParentId(x, topId);
});
}
@Override
public void updateEntity(CategoryEntity entity) {
setParentId(entity);
String pingYin =entity.getCategoryPinyin();
if(StrUtil.isNotBlank(pingYin)){
CategoryEntity category=new CategoryEntity();
category.setCategoryPinyin(pingYin);
CategoryEntity categoryBizEntity = (CategoryEntity)getEntity(category);
//拼音存在则拼接id
if(categoryBizEntity!=null&&!categoryBizEntity.getId().equals(entity.getId())){
entity.setCategoryPinyin(pingYin+entity.getId());
}
}
setParentLeaf(entity);
setTopId(entity);
//如果父级栏目和父级id为空字符串则转化成null
if (StringUtils.isEmpty(entity.getCategoryId())) {
entity.setCategoryId(null);
}
if (StringUtils.isEmpty(entity.getCategoryParentIds())) {
entity.setCategoryParentIds(null);
}
categoryDao.updateEntity(entity);
//更新子节点所有父节点id和topid
//如果本节点的topid为0(顶级栏目),则把自身的id作为子栏目的topid,非0所有的子栏目和本栏目使用同一个topid
String topId = entity.getTopId();
if (topId.equals("0")) {
topId = entity.getId();
}
setChildParentId(entity, topId);
}
@Override
public void update(CategoryEntity entity) {
super.updateEntity(entity);
}
@Override
public void delete(String categoryId) {
// TODO Auto-generated method stub
CategoryEntity category = (CategoryEntity) categoryDao.selectById(categoryId);
//删除父类
if(category != null){
category.setCategoryParentIds(null);
List<CategoryEntity> childrenList = categoryDao.queryChildren(category);
List<String> ids = new ArrayList<>();
for(int i = 0; i < childrenList.size(); i++){
//删除子类
ids.add(childrenList.get(i).getId());
}
categoryDao.deleteBatchIds(ids);
// 删除文章
contentDao.deleteEntityByCategoryIds(ids.toArray(new String[ids.size()]));
//获取被删节点的父节点
CategoryEntity parentNode = categoryDao.selectById(category.getCategoryId());
//获取被删节点的所属栏目的其他节点
List<CategoryEntity> childNode = categoryDao.queryChildren(parentNode);
//判断删除的是否为主节点
if (parentNode != null) {
UpdateWrapper<CategoryEntity> updateWrapper = new UpdateWrapper<>();
//是否还有子节点
if (childNode.size() > 1)
updateWrapper.eq("id", parentNode.getId()).set("leaf", 0);
else
updateWrapper.eq("id", parentNode.getId()).set("leaf", 1);
categoryDao.update(null, updateWrapper);
}
}
}
/**
* 设置父级叶子节点
* @param entity
*/
private void setParentLeaf(CategoryEntity entity){
CategoryEntity categoryEntity = getById(entity.getId());
//如果父级不为空并且修改了父级则需要更新父级
if(entity.getCategoryId() != null && !entity.getCategoryId().equals(categoryEntity.getCategoryId())){
//更新旧的父级
if(StrUtil.isNotBlank(categoryEntity.getCategoryId())&&!"0".equals(categoryEntity.getCategoryId())){
CategoryEntity parent = getById(categoryEntity.getCategoryId());
//如果修改了父级则需要判断父级是否还有子节点
boolean leaf = parent.getLeaf();
//查找不等于当前更新的分类子集,有则不是叶子节点
QueryWrapper<CategoryEntity> queryWrapper = new QueryWrapper<>();
parent.setLeaf(count(queryWrapper.eq("category_id",parent.getId()).ne("id",entity.getId()))==0);
if(leaf!=parent.getLeaf()){
updateById(parent);
}
}
//更新新的父级
if(StrUtil.isNotBlank(entity.getCategoryId())&&!"0".equals(entity.getCategoryId())){
CategoryEntity parent = getById(entity.getCategoryId());
//如果之前是叶子节点就更新
if(parent.getLeaf()){
parent.setLeaf(false);
updateById(parent);
}
}
}
}
/**
* 设置顶级id
* @param entity
*/
private void setTopId(CategoryEntity entity){
String categoryParentId = entity.getCategoryParentIds();
if(StrUtil.isNotBlank(categoryParentId)){
String[] ids = categoryParentId.split(",");
//如果有ParentId就取第一个
if(ids.length>0){
entity.setTopId(ids[0]);
return;
}
}
entity.setTopId("0");
}
@Override
public void copyCategory(CategoryEntity category) {
String oldId = category.getId();
//先保存被复制第一层栏目,因为第一层栏目不需要变更父级栏目
category = getById(oldId);
//id、拼音和路径按照原来的业务逻辑生成
category.setId(null);
category.setCategoryPinyin(null);
category.setCategoryPath(null);
saveEntity(category);
//传入简要被复制子栏目的id和复制后的生成的id,复制的子栏目全部使用
recursionCopyChilds(oldId, category.getId());
}
/*
* 递归复制子栏目
* @param oldParentId:被复制的父级栏目id(需要数据库原来存在该数据)
* @param newParentId:复制栏目后新父级的id(新插入数据的id)
* */
private void recursionCopyChilds(String oldParentId, String newParentId) {
CategoryEntity _category = new CategoryEntity();
_category.setCategoryId(oldParentId);
List<CategoryEntity> childs = query(_category);
for (CategoryEntity child : childs) {
String childId = child.getId();
//id、拼音和路径按照原来的业务逻辑生成
child.setId(null);
child.setCategoryPinyin(null);
child.setCategoryPath(null);
child.setCategoryId(newParentId);
saveEntity(child);
//如果该栏目下还有子栏目则继续复制该栏目里的子栏目
recursionCopyChilds(childId, child.getId());
}
}
}
| src/main/java/net/mingsoft/cms/biz/impl/CategoryBizImpl.java | /**
* The MIT License (MIT)
* Copyright (c) 2020 铭软科技(mingsoft.net)
* 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 net.mingsoft.cms.biz.impl;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.mingsoft.base.biz.impl.BaseBizImpl;
import net.mingsoft.base.dao.IBaseDao;
import net.mingsoft.basic.util.PinYinUtil;
import net.mingsoft.cms.biz.ICategoryBiz;
import net.mingsoft.cms.dao.ICategoryDao;
import net.mingsoft.cms.dao.IContentDao;
import net.mingsoft.cms.entity.CategoryEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
* 分类管理持久化层
* @author 铭飞开发团队
* 创建日期:2019-11-28 15:12:32<br/>
* 历史修订:<br/>
*/
@Service("cmscategoryBizImpl")
@Transactional(rollbackFor = RuntimeException.class)
public class CategoryBizImpl extends BaseBizImpl<ICategoryDao, CategoryEntity> implements ICategoryBiz {
@Autowired
private ICategoryDao categoryDao;
@Autowired
private IContentDao contentDao;
@Override
protected IBaseDao getDao() {
// TODO Auto-generated method stub
return categoryDao;
}
@Override
public List<CategoryEntity> queryChilds(CategoryEntity category) {
// TODO Auto-generated method stub
return categoryDao.queryChildren(category);
}
@Override
public void saveEntity(CategoryEntity categoryEntity) {
// TODO Auto-generated method stub
String pingYin = PinYinUtil.getPingYin(categoryEntity.getCategoryTitle());
//如果用户自己填入了拼音则使用用户的
if (StrUtil.isNotBlank(categoryEntity.getCategoryPinyin())) {
pingYin = categoryEntity.getCategoryPinyin();
}
CategoryEntity category=new CategoryEntity();
category.setCategoryPinyin(pingYin);
Object categoryBizEntity = getEntity(category);
setParentId(categoryEntity);
categoryEntity.setCategoryPinyin(pingYin);
//更新新的父级
if(StrUtil.isNotBlank(categoryEntity.getCategoryId())&&!"0".equals(categoryEntity.getCategoryId())){
CategoryEntity parent = getById(categoryEntity.getCategoryId());
//如果之前是叶子节点就更新
if(parent.getLeaf()){
parent.setLeaf(false);
updateById(parent);
}
}
categoryEntity.setLeaf(false);
//如果是新增栏目一定是叶子节点
if (StrUtil.isEmpty(categoryEntity.getId())) {
categoryEntity.setLeaf(true);
}
super.save(categoryEntity);
//拼音存在则拼接id
if(categoryBizEntity!=null){
categoryEntity.setCategoryPinyin(pingYin+categoryEntity.getId());
}
CategoryEntity parentCategory = null;
if (StringUtils.isNotBlank(categoryEntity.getCategoryId())) {
parentCategory = (CategoryEntity)getById(categoryEntity.getCategoryId());
}
//保存链接地址
String path=ObjectUtil.isNotNull(parentCategory)?parentCategory.getCategoryPath():"";
categoryEntity.setCategoryPath( path+"/" + categoryEntity.getCategoryPinyin());
setTopId(categoryEntity);
super.updateById(categoryEntity);
}
private void setParentId(CategoryEntity categoryEntity) {
String path = "";
if(StringUtils.isNotEmpty(categoryEntity.getCategoryId())&&Long.parseLong(categoryEntity.getCategoryId())>0) {
CategoryEntity category = (CategoryEntity)getById(categoryEntity.getCategoryId());
path = category.getCategoryPath();
if(StringUtils.isEmpty(category.getCategoryParentIds())) {
categoryEntity.setCategoryParentIds(category.getId());
} else {
categoryEntity.setCategoryParentIds(category.getCategoryParentIds()+","+category.getId());
}
}else {
categoryEntity.setCategoryParentIds(null);
}
//保存时先保存再修改链接地址,修改时直接修改
if(StringUtils.isNotBlank(categoryEntity.getId())) {
categoryEntity.setCategoryPath(path+ "/" + categoryEntity.getCategoryPinyin());
}
}
private void setChildParentId(CategoryEntity categoryEntity, String topId) {
CategoryEntity category=new CategoryEntity();
category.setCategoryId(categoryEntity.getId());
List<CategoryEntity> list = categoryDao.query(category);
list.forEach(x->{
if(StringUtils.isEmpty(categoryEntity.getCategoryParentIds())) {
x.setCategoryParentIds(categoryEntity.getId());
} else {
x.setCategoryParentIds(categoryEntity.getCategoryParentIds()+","+categoryEntity.getId());
}
//更新topid
x.setTopId(topId);
String path=categoryEntity.getCategoryPath();
//判断是否有parentIds
x.setCategoryPath(path+"/"+x.getCategoryPinyin());
//去除多余的/符号
super.updateEntity(x);
setChildParentId(x, topId);
});
}
@Override
public void updateEntity(CategoryEntity entity) {
setParentId(entity);
String pingYin =entity.getCategoryPinyin();
if(StrUtil.isNotBlank(pingYin)){
CategoryEntity category=new CategoryEntity();
category.setCategoryPinyin(pingYin);
CategoryEntity categoryBizEntity = (CategoryEntity)getEntity(category);
//拼音存在则拼接id
if(categoryBizEntity!=null&&!categoryBizEntity.getId().equals(entity.getId())){
entity.setCategoryPinyin(pingYin+entity.getId());
}
}
setParentLeaf(entity);
setTopId(entity);
//如果父级栏目和父级id为空字符串则转化成null
if (StringUtils.isEmpty(entity.getCategoryId())) {
entity.setCategoryId(null);
}
if (StringUtils.isEmpty(entity.getCategoryParentIds())) {
entity.setCategoryParentIds(null);
}
categoryDao.updateEntity(entity);
//更新子节点所有父节点id和topid
//如果本节点的topid为0(顶级栏目),则把自身的id作为子栏目的topid,非0所有的子栏目和本栏目使用同一个topid
String topId = entity.getTopId();
if (topId.equals("0")) {
topId = entity.getId();
}
setChildParentId(entity, topId);
}
@Override
public void update(CategoryEntity entity) {
super.updateEntity(entity);
}
@Override
public void delete(String categoryId) {
// TODO Auto-generated method stub
CategoryEntity category = (CategoryEntity) categoryDao.selectById(categoryId);
//删除父类
if(category != null){
category.setCategoryParentIds(null);
List<CategoryEntity> childrenList = categoryDao.queryChildren(category);
List<String> ids = new ArrayList<>();
for(int i = 0; i < childrenList.size(); i++){
//删除子类
ids.add(childrenList.get(i).getId());
}
categoryDao.deleteBatchIds(ids);
// 删除文章
contentDao.deleteEntityByCategoryIds(ids.toArray(new String[ids.size()]));
}
}
/**
* 设置父级叶子节点
* @param entity
*/
private void setParentLeaf(CategoryEntity entity){
CategoryEntity categoryEntity = getById(entity.getId());
//如果父级不为空并且修改了父级则需要更新父级
if(entity.getCategoryId() != null && !entity.getCategoryId().equals(categoryEntity.getCategoryId())){
//更新旧的父级
if(StrUtil.isNotBlank(categoryEntity.getCategoryId())&&!"0".equals(categoryEntity.getCategoryId())){
CategoryEntity parent = getById(categoryEntity.getCategoryId());
//如果修改了父级则需要判断父级是否还有子节点
boolean leaf = parent.getLeaf();
//查找不等于当前更新的分类子集,有则不是叶子节点
QueryWrapper<CategoryEntity> queryWrapper = new QueryWrapper<>();
parent.setLeaf(count(queryWrapper.eq("category_id",parent.getId()).ne("id",entity.getId()))==0);
if(leaf!=parent.getLeaf()){
updateById(parent);
}
}
//更新新的父级
if(StrUtil.isNotBlank(entity.getCategoryId())&&!"0".equals(entity.getCategoryId())){
CategoryEntity parent = getById(entity.getCategoryId());
//如果之前是叶子节点就更新
if(parent.getLeaf()){
parent.setLeaf(false);
updateById(parent);
}
}
}
}
/**
* 设置顶级id
* @param entity
*/
private void setTopId(CategoryEntity entity){
String categoryParentId = entity.getCategoryParentIds();
if(StrUtil.isNotBlank(categoryParentId)){
String[] ids = categoryParentId.split(",");
//如果有ParentId就取第一个
if(ids.length>0){
entity.setTopId(ids[0]);
return;
}
}
entity.setTopId("0");
}
@Override
public void copyCategory(CategoryEntity category) {
String oldId = category.getId();
//先保存被复制第一层栏目,因为第一层栏目不需要变更父级栏目
category = getById(oldId);
//id、拼音和路径按照原来的业务逻辑生成
category.setId(null);
category.setCategoryPinyin(null);
category.setCategoryPath(null);
saveEntity(category);
//传入简要被复制子栏目的id和复制后的生成的id,复制的子栏目全部使用
recursionCopyChilds(oldId, category.getId());
}
/*
* 递归复制子栏目
* @param oldParentId:被复制的父级栏目id(需要数据库原来存在该数据)
* @param newParentId:复制栏目后新父级的id(新插入数据的id)
* */
private void recursionCopyChilds(String oldParentId, String newParentId) {
CategoryEntity _category = new CategoryEntity();
_category.setCategoryId(oldParentId);
List<CategoryEntity> childs = query(_category);
for (CategoryEntity child : childs) {
String childId = child.getId();
//id、拼音和路径按照原来的业务逻辑生成
child.setId(null);
child.setCategoryPinyin(null);
child.setCategoryPath(null);
child.setCategoryId(newParentId);
saveEntity(child);
//如果该栏目下还有子栏目则继续复制该栏目里的子栏目
recursionCopyChilds(childId, child.getId());
}
}
}
| 修复叶子节点
| src/main/java/net/mingsoft/cms/biz/impl/CategoryBizImpl.java | 修复叶子节点 | <ide><path>rc/main/java/net/mingsoft/cms/biz/impl/CategoryBizImpl.java
<ide> import cn.hutool.core.util.ObjectUtil;
<ide> import cn.hutool.core.util.StrUtil;
<ide> import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
<add>import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
<ide> import net.mingsoft.base.biz.impl.BaseBizImpl;
<ide> import net.mingsoft.base.dao.IBaseDao;
<ide> import net.mingsoft.basic.util.PinYinUtil;
<ide> categoryDao.deleteBatchIds(ids);
<ide> // 删除文章
<ide> contentDao.deleteEntityByCategoryIds(ids.toArray(new String[ids.size()]));
<add>
<add> //获取被删节点的父节点
<add> CategoryEntity parentNode = categoryDao.selectById(category.getCategoryId());
<add> //获取被删节点的所属栏目的其他节点
<add> List<CategoryEntity> childNode = categoryDao.queryChildren(parentNode);
<add> //判断删除的是否为主节点
<add> if (parentNode != null) {
<add> UpdateWrapper<CategoryEntity> updateWrapper = new UpdateWrapper<>();
<add>
<add> //是否还有子节点
<add> if (childNode.size() > 1)
<add> updateWrapper.eq("id", parentNode.getId()).set("leaf", 0);
<add> else
<add> updateWrapper.eq("id", parentNode.getId()).set("leaf", 1);
<add>
<add> categoryDao.update(null, updateWrapper);
<add> }
<add>
<ide> }
<ide> }
<ide> |
|
Java | bsd-2-clause | 83660849cba6cc1bc5e120499a4a9c5ba0cce394 | 0 | runelite/runelite,l2-/runelite,l2-/runelite,Sethtroll/runelite,runelite/runelite,Sethtroll/runelite,runelite/runelite | /*
* Copyright (c) 2018, Lotto <https://github.com/devLotto>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.cluescrolls.clues;
import com.google.common.collect.ImmutableSet;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.Set;
import lombok.Getter;
import net.runelite.api.NPC;
import static net.runelite.api.NullObjectID.NULL_1293;
import net.runelite.api.ObjectComposition;
import static net.runelite.api.ObjectID.*;
import net.runelite.api.TileObject;
import net.runelite.api.coords.LocalPoint;
import net.runelite.api.coords.WorldPoint;
import static net.runelite.client.plugins.cluescrolls.ClueScrollOverlay.TITLED_CONTENT_COLOR;
import net.runelite.client.plugins.cluescrolls.ClueScrollPlugin;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_BORDER_COLOR;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_FILL_COLOR;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_HOVER_BORDER_COLOR;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.IMAGE_Z_OFFSET;
import net.runelite.client.ui.overlay.OverlayUtil;
import net.runelite.client.ui.overlay.components.LineComponent;
import net.runelite.client.ui.overlay.components.PanelComponent;
import net.runelite.client.ui.overlay.components.TitleComponent;
@Getter
public class CrypticClue extends ClueScroll implements TextClueScroll, NpcClueScroll, ObjectClueScroll
{
public static final Set<CrypticClue> CLUES = ImmutableSet.of(
new CrypticClue("Show this to Sherlock.", "Sherlock", new WorldPoint(2733, 3415, 0), "Sherlock is located to the east of the Sorcerer's tower in Seers' Village."),
new CrypticClue("Talk to the bartender of the Rusty Anchor in Port Sarim.", "Bartender", new WorldPoint(3045, 3256, 0), "The Rusty Anchor is located in the north of Port Sarim."),
new CrypticClue("The keeper of Melzars... Spare? Skeleton? Anar?", "Oziach", new WorldPoint(3068, 3516, 0), "Speak to Oziach in Edgeville"),
new CrypticClue("Speak to Ulizius.", "Ulizius", new WorldPoint(3444, 3461, 0), "Ulizius is the monk who guards the gate into Mort Myre Swamp. South of fairy ring CKS"),
new CrypticClue("Search for a crate in a building in Hemenster.", CRATE_357, new WorldPoint(2636, 3453, 0), "House north of the Fishing Contest quest area. West of Grandpa Jack."),
new CrypticClue("A reck you say; let's pray there aren't any ghosts.", "Father Aereck", new WorldPoint(3242, 3207, 0), "Speak to Father Aereck in Lumbridge."),
new CrypticClue("Search the bucket in the Port Sarim jail.", BUCKET_9568, new WorldPoint(3013, 3179, 0), "Talk to Shantay & identify yourself as an outlaw, refuse to pay the 5gp fine twice and you will be sent to the Port Sarim jail."),
new CrypticClue("Search the crates in a bank in Varrock.", CRATE_5107, new WorldPoint(3187, 9825, 0), "Search in the basement of the West Varrock bank."),
new CrypticClue("Falo the bard wants to see you.", "Falo the Bard", new WorldPoint(2689, 3550, 0), "Speak to Falo the Bard located between Seer's Village and Rellekka. Southwest of fairy ring CJR."),
new CrypticClue("Search a bookcase in the Wizards tower.", BOOKCASE_12539, new WorldPoint(3113, 3159, 0), "The bookcase located on the ground floor."),
new CrypticClue("Come have a cip with this great soot covered denizen.", "Miner Magnus", new WorldPoint(2527, 3891, 0), "Talk to Miner Magnus east of the fairy ring CIP. Answer: 8"),
new CrypticClue("Citric cellar.", "Heckel Funch", new WorldPoint(2490, 3488, 0), "Speak to Heckel Funch on the first floor in the Grand Tree."),
new CrypticClue("I burn between heroes and legends.", "Candle maker", new WorldPoint(2799, 3438, 0), "Speak to the Candle maker in Catherby."),
new CrypticClue("Speak to Sarah at Falador farm.", "Sarah", new WorldPoint(3038, 3292, 0), "Talk to Sarah at Falador farm, north of Port Sarim."),
new CrypticClue("Search for a crate on the ground floor of a house in Seers' Village.", CRATE_25775, new WorldPoint(2699, 3470, 0), "Search inside Phantuwti Fanstuwi Farsight's house, located south of the pub in Seers' Village."),
new CrypticClue("Snah? I feel all confused, like one of those cakes...", "Hans", new WorldPoint(3211, 3219, 0), "Talk to Hans roaming around Lumbridge Castle."),
new CrypticClue("Speak to Sir Kay in Camelot Castle.", "Sir Kay", new WorldPoint(2759, 3497, 0), "Sir Kay can be found in the courtyard at Camelot castle."),
new CrypticClue("Gold I see, yet gold I require. Give me 875 if death you desire.", "Saniboch", new WorldPoint(2745, 3151, 0), "Speak to Saniboch at the Brimhaven Dungeon entrance."),
new CrypticClue("Find a crate close to the monks that like to paaarty!", CRATE_354, new WorldPoint(2614, 3204, 0), "The crate is in the east side of the Kandarin monastery, near Brother Omad"),
new CrypticClue("Identify the back of this over-acting brother. (He's a long way from home.)", "Hamid", new WorldPoint(3376, 3284, 0), "Talk to Hamid, the monk at the altar in the Duel Arena"),
new CrypticClue("In a town where thieves steal from stalls, search for some drawers in the upstairs of a house near the bank.", "Guard", DRAWERS, new WorldPoint(2611, 3324, 1), "Kill any Guard located around East Ardougne for a medium key. Then search the drawers in the upstairs hallway of Jerico's house, which is the house with pigeon cages located south of the northern East Ardougne bank."),
new CrypticClue("His bark is worse than his bite.", "Barker", new WorldPoint(3499, 3503, 0), "Speak to the Barker at Canifis's Barkers' Haberdashery."),
new CrypticClue("The beasts to my east snap claws and tails, The rest to my west can slide and eat fish. The force to my north will jump and they'll wail, Come dig by my fire and make a wish.", new WorldPoint(2598, 3267, 0), "Dig by the torch in the Ardougne Zoo, between the penguins and the scorpions."),
new CrypticClue("A town with a different sort of night-life is your destination. Search for some crates in one of the houses.", CRATE_24344, new WorldPoint(3498, 3507, 0), "Search the crate inside of the clothes shop in Canifis."),
new CrypticClue("Stop crying! Talk to the head.", "Head mourner", new WorldPoint(2042, 4630, 0), "Talk to the Head mourner in the mourner headquarters in West Ardougne"),
new CrypticClue("Search the crate near a cart in Port Khazard.", CRATE_366, new WorldPoint(2660, 3149, 0), "Search by the southern Khazard General Store in Port Khazard."),
new CrypticClue("Speak to the bartender of the Blue Moon Inn in Varrock.", "Bartender", new WorldPoint(3226, 3399, 0), "Talk to the bartender in Blue Moon Inn in Varrock."),
new CrypticClue("This aviator is at the peak of his profession.", "Captain Bleemadge", new WorldPoint(2846, 1749, 0), "Captain Bleemadge, the gnome glider pilot, is found at the top of White Wolf Mountain."),
new CrypticClue("Search the crates in the shed just north of East Ardougne.", CRATE_355, new WorldPoint(2617, 3347, 0), "The crates in the shed north of the northern Ardougne bank."),
new CrypticClue("I wouldn't wear this jean on my legs.", "Father Jean", new WorldPoint(1734, 3576, 0), "Talk to father Jean in the Hosidius church"),
new CrypticClue("Search the crate in the Toad and Chicken pub.", CRATE_354, new WorldPoint(2913, 3536, 0), "The Toad and Chicken pub is located in Burthorpe."),
new CrypticClue("Search chests found in the upstairs of shops in Port Sarim.", CLOSED_CHEST_375, new WorldPoint(3016, 3205, 1), "Search the chest in the upstairs of Wydin's Food Store, on the east wall."),
new CrypticClue("Right on the blessed border, cursed by the evil ones. On the spot inaccessible by both; I will be waiting. The bugs' imminent possession holds the answer.", new WorldPoint(3410, 3324, 0), "B I P. Dig right under the fairy ring."),
new CrypticClue("The dead, red dragon watches over this chest. He must really dig the view.", "Barbarian", 375, new WorldPoint(3353, 3332, 0), "Search the chest underneath the Red Dragon's head in the Exam Centre. Kill a MALE Barbarian in Barbarian Village or Barbarian Outpost to receive the key."),
new CrypticClue("My home is grey, and made of stone; A castle with a search for a meal. Hidden in some drawers I am, across from a wooden wheel.", DRAWERS_5618, new WorldPoint(3213, 3216, 1), "Open the drawers inside the room with the spinning wheel on the first floor of Lumbridge Castle."),
new CrypticClue("Come to the evil ledge, Yew know yew want to. Try not to get stung.", new WorldPoint(3089, 3468, 0), "Dig in Edgeville, just east of the Southern Yew tree."),
new CrypticClue("Look in the ground floor crates of houses in Falador.", CRATES_24088, new WorldPoint(3029, 3355, 0), "The house east of the east bank."),
new CrypticClue("You were 3 and I was the 6th. Come speak to me.", "Vannaka", new WorldPoint(3146, 9913, 0), "Speak to Vannaka in Edgeville Dungeon."),
new CrypticClue("Search the crates in Draynor Manor.", CRATE_11485, new WorldPoint(3106, 3369, 2), "Top floor of the manor"),
new CrypticClue("Search the crates near a cart in Varrock.", CRATE_5107, new WorldPoint(3226, 3452, 0), "South east of Varrock Palace, south of the tree farming patch."),
new CrypticClue("A Guthixian ring lies between two peaks. Search the stones and you'll find what you seek.", STONES_26633, new WorldPoint(2922, 3484, 0), "Search the stones several steps west of the Guthixian stone circle in Taverley"),
new CrypticClue("Search the boxes in the house near the south entrance to Varrock.", BOXES_5111, new WorldPoint(3203, 3384, 0), "The first house on the left when entering the city from the southern entrance."),
new CrypticClue("His head might be hollow, but the crates nearby are filled with surprises.", CRATE_354, new WorldPoint(3478, 3091, 0), "Search the crates near the Clay golem in the ruins of Uzer."),
new CrypticClue("One of the sailors in Port Sarim is your next destination.", "Captain Tobias", new WorldPoint(3026, 3216, 0), "Speak to Captain Tobias on the docks of Port Sarim."),
new CrypticClue("THEY'RE EVERYWHERE!!!! But they were here first. Dig for treasure where the ground is rich with ore.", new WorldPoint(3081, 3421, 0), "Dig at Barbarian Village, next to the Stronghold of Security."),
new CrypticClue("Talk to the mother of a basement dwelling son.", "Doris", new WorldPoint(3079, 3493, 0), "Evil Dave's mother, Doris is located in the house west of Edgeville bank."),
new CrypticClue("Speak to Ned in Draynor Village.", "Ned", new WorldPoint(3098, 3258, 0), "Ned is found north of the Draynor bank."),
new CrypticClue("Speak to Hans to solve the clue.", "Hans", new WorldPoint(3211, 3219, 0), "Hans can be found at Lumbridge Castle."),
new CrypticClue("Search the crates in Canifis.", CRATE_24344, new WorldPoint(3509, 3497, 0), "Search inside the shop, Rufus' Meat Emporium."),
new CrypticClue("Search the crates in the Dwarven mine.", CRATE_357, new WorldPoint(3035, 9849, 0), "Search the crate in the room east of the Ice Mountain ladder entrance in the Drogo's Mining Emporium."),
new CrypticClue("A crate found in the tower of a church is your next location.", CRATE_357, new WorldPoint(2612, 3304, 1), "Climb the ladder and search the crates on the first floor in the Church in Ardougne"),
new CrypticClue("Covered in shadows, the centre of the circle is where you will find the answer.", new WorldPoint(3488, 3289, 0), "Dig in the centre of Mort'ton, where the roads intersect"),
new CrypticClue("I lie lonely and forgotten in mid wilderness, where the dead rise from their beds. Feel free to quarrel and wind me up, and dig while you shoot their heads.", new WorldPoint(3174, 3663, 0), "Directly under the crossbow respawn in the Graveyard of Shadows in level 18 Wilderness."),
new CrypticClue("In the city where merchants are said to have lived, talk to a man with a splendid cape, but a hat dropped by goblins.", "Head chef", new WorldPoint(3143, 3445, 0), "Talk to the Head chef in Cooks' Guild west of Varrock."),
new CrypticClue("The mother of the reptilian sacrifice.", "Zul-Cheray", new WorldPoint(2204, 3050, 0), "Talk to Zul-Cheray in a house near the sacrificial boat at Zul-Andra."),
new CrypticClue("I watch the sea. I watch you fish. I watch your tree.", "Ellena", new WorldPoint(2860, 3431, 0), "Speak to Ellena at Catherby fruit tree patch."),
new CrypticClue("Dig between some ominous stones in Falador.", new WorldPoint(3040, 3399, 0), "Three standing stones inside a walled area. East of the northern Falador gate."),
new CrypticClue("Speak to Rusty north of Falador.", "Rusty", new WorldPoint(2979, 3435, 0), "Rusty can be found northeast of Falador on the way to the Mind altar."),
new CrypticClue("Search a wardrobe in Draynor.", WARDROBE_5622, new WorldPoint(3087, 3261, 0), "Go to Aggie's house and search the wardrobe in northern wall."),
new CrypticClue("I have many arms but legs, I have just one. I have little family but my seed you can grow on, I am not dead, yet I am but a spirit, and my power, on your quests, you will earn the right to free it.", NULL_1293, new WorldPoint(2544, 3170, 0), "Spirit Tree in Tree Gnome Village. Answer: 13112221"),
new CrypticClue("I am the one who watches the giants. The giants in turn watch me. I watch with two while they watch with one. Come seek where I may be.", "Kamfreena", new WorldPoint(2845, 3539, 0), "Speak to Kamfreena on the top floor of the Warriors' Guild."),
new CrypticClue("In a town where wizards are known to gather, search upstairs in a large house to the north.", "Man", 375, new WorldPoint(2593, 3108, 1), "Search the chest upstairs in the house north of Yanille Wizard's Guild. Kill a man for the key."),
new CrypticClue("Probably filled with wizards socks.", "Wizard", DRAWERS_350, new WorldPoint(3116, 9562, 0), "Search the drawers in the basement of the Wizard's Tower south of Draynor Village. Kill one of the Wizards for the key. Fairy ring DIS"),
new CrypticClue("Even the seers say this clue goes right over their heads.", CRATE_14934, new WorldPoint(2707, 3488, 2), "Search the crate on the Seers Agility Course in Seers Village"),
new CrypticClue("Speak to a Wyse man.", "Wyson the gardener", new WorldPoint(3026, 3378, 0), "Talk to Wyson the gardener at Falador Park."),
new CrypticClue("You'll need to look for a town with a central fountain. Look for a locked chest in the town's chapel.", "Monk" , CLOSED_CHEST_5108, new WorldPoint(3256, 3487, 0), "Search the chest by the stairs in the Varrock church. Kill a Monk in Ardougne Monastery to obtain the key."),
new CrypticClue("Talk to Ambassador Spanfipple in the White Knights Castle.", "Ambassador Spanfipple", new WorldPoint(2979, 3340, 0), "Ambassador Spanfipple can be found roaming on the first floor of the White Knights Castle."),
new CrypticClue("Mine was the strangest birth under the sun. I left the crimson sack, yet life had not begun. Entered the world, and yet was seen by none.", new WorldPoint(2832, 9586, 0), "Inside Karamja Volcano, dig directly underneath the Red spiders' eggs respawn."),
new CrypticClue("Search for a crate in Varrock Castle.", CRATE_5113, new WorldPoint(3224, 3492, 0), "Search the crate in the corner of the kitchen in Varrock Castle."),
new CrypticClue("And so on, and so on, and so on. Walking from the land of many unimportant things leads to a choice of paths.", new WorldPoint(2591, 3879, 0), "Dig on Etceteria next to the Evergreen tree in front of the castle walls."),
new CrypticClue("Speak to Donovan, the Family Handyman.", "Donovan the Family Handyman", new WorldPoint(2743, 3578, 0), "Donovan the Family Handyman is found on the first floor of Sinclair Mansion."),
new CrypticClue("Search the crates in the Barbarian Village helmet shop.", CRATES_11600, new WorldPoint(3073, 3430, 0), "Peksa's Helmet Shop in Barbarian Village."),
new CrypticClue("Search the boxes of Falador's general store.", CRATES_24088, new WorldPoint(2955, 3390, 0), "Falador general store."),
new CrypticClue("In a village made of bamboo, look for some crates under one of the houses.", CRATE_356, new WorldPoint(2800, 3074, 0), "Search the crate by the house at the northern point of the broken jungle fence in Tai Bwo Wannai."),
new CrypticClue("This crate is mine, all mine, even if it is in the middle of the desert.", CRATE_18889, new WorldPoint(3289, 3022, 0), "Center of desert Mining Camp. Search the crates. Requires the metal key from Tourist Trap to enter."),
new CrypticClue("Dig where 4 siblings and I all live with our evil overlord.", new WorldPoint(3195, 3357, 0), "Dig in the chicken pen inside the Champions' Guild"),
new CrypticClue("In a town where the guards are armed with maces, search the upstairs rooms of the Public House.", "Guard dog", 348, new WorldPoint(2574, 3326, 1), "Search the drawers upstairs in the pub north of Ardougne Castle. Kill a Guard dog at Handelmort Mansion to obtain the key."),
new CrypticClue("Four blades I have, yet draw no blood; Still I turn my prey to powder. If you are brave, come search my roof; It is there my blades are louder.", CRATE_12963, new WorldPoint(3166, 3309, 2), "Lumbridge windmill, search the crates on the top floor."),
new CrypticClue("Search through some drawers in the upstairs of a house in Rimmington.", DRAWERS_352, new WorldPoint(2970, 3214, 1), "On the first floor of the house north of Hetty the Witch's house in Rimmington."),
new CrypticClue("Probably filled with books on magic.", BOOKCASE_380, new WorldPoint(3096, 9572, 0), "Search the bookcase in the basement of Wizard's Tower. Fairy ring DIS"),
new CrypticClue("If you look closely enough, it seems that the archers have lost more than their needles.", HAYSTACK, new WorldPoint(2672, 3416, 0), "Search the haystack by the south corner of the Rangers' Guild"),
new CrypticClue("Search the crate in the left-hand tower of Lumbridge Castle.", CRATE_357, new WorldPoint(3228, 3212, 1), "Located on the first floor of the southern tower at the Lumbridge Castle entrance."),
new CrypticClue("'Small shoe.' Often found with rod on mushroom.", "Gnome trainer", new WorldPoint(2476, 3428, 0), "Talk to any Gnome trainer in the agility area of the Tree Gnome Stronghold."),
new CrypticClue("I live in a deserted crack collecting soles.", "Genie", new WorldPoint(3371, 9320, 0), "Enter the crack west of Nardah Rug merchant, and talk to the Genie. You'll need a light source and a rope."),
new CrypticClue("46 is my number. My body is the colour of burnt orange and crawls among those with eight. Three mouths I have, yet I cannot eat. My blinking blue eye hides my grave.", new WorldPoint(3170, 3885, 0), "Sapphire respawn in the Spider's Nest, lvl 46 Wilderness. Dig under the sapphire spawn."),
new CrypticClue("Green is the colour of my death as the winter-guise, I swoop towards the ground.", new WorldPoint(2780, 3783, 0), "Players need to slide down to where Trollweiss grows on Trollweiss Mountain."),
new CrypticClue("Talk to a party-goer in Falador.", "Lucy", new WorldPoint(3046, 3382, 0), "Lucy is the bartender on the first floor of the party room."),
new CrypticClue("He knows just how easy it is to lose track of time.", "Brother Kojo", new WorldPoint(2570, 3250, 0), "Speak to Brother Kojo in the Clock Tower. Answer: 22"),
new CrypticClue("A great view - watch the rapidly drying hides get splashed. Check the box you are sitting on.", BOXES, new WorldPoint(2523, 3493, 1), "Almera's House north of Baxtorian Falls, search boxes on the first floor."),
new CrypticClue("Search the Coffin in Edgeville.", COFFIN, new WorldPoint(3091, 3477, 0), "Search the coffin located by the Wilderness teleport lever."),
new CrypticClue("When no weapons are at hand, then is the time to reflect. In Saradomin's name, redemption draws closer...", DRAWERS_350, new WorldPoint(2818, 3351, 0), "On Entrana, search the southern drawer in the house with the cooking range."),
new CrypticClue("Search the crates in a house in Yanille that has a piano.", CRATE_357, new WorldPoint(2598, 3105, 0), "The house is located northwest of the bank."),
new CrypticClue("Speak to the staff of Sinclair mansion.", "Louisa", new WorldPoint(2736, 3578, 0), "Speak to Louisa, on the ground floor, found at the Sinclair Mansion. Fairy ring CJR"),
new CrypticClue("I am a token of the greatest love. I have no beginning or end. My eye is red, I can fit like a glove. Go to the place where it's money they lend, And dig by the gate to be my friend.", new WorldPoint(3191, 9825, 0), "Dig by the gate in the basement of the West Varrock bank."),
new CrypticClue("Speak to Kangai Mau.", "Kangai Mau", new WorldPoint(2791, 3183, 0), "Kangai Mau is found in the Shrimp and Parrot in Brimhaven."),
new CrypticClue("Speak to Hajedy.", "Hajedy", new WorldPoint(2779, 3211, 0), "Hajedy is found by the cart, located just south of the Brimhaven docks."),
new CrypticClue("Must be full of railings.", BOXES_6176, new WorldPoint(2576, 3464, 0), "Search the boxes around the hut where the broken Dwarf Cannon is, close to the start of the Dwarf Cannon quest."),
new CrypticClue("I wonder how many bronze swords he has handed out.", "Vannaka", new WorldPoint(3164, 9913, 0), "Talk to Vannaka. He can be found in Edgeville Dungeon."),
new CrypticClue("Read 'How to breed scorpions.' By O.W.Thathurt.", BOOKCASE_380, new WorldPoint(2703, 3409, 1), "Search the northern bookcase on the first floor of the Sorcerer's Tower."),
new CrypticClue("Search the crates in the Port Sarim Fishing shop.", CRATE_9534, new WorldPoint(3012, 3222, 0), "Search the crates, by the door, in Gerrant's Fishy Business in Port Sarim."),
new CrypticClue("Speak to The Lady of the Lake.", "The Lady of the Lake", new WorldPoint(2924, 3405, 0), "Talk to The Lady of the Lake in Taverley."),
new CrypticClue("Rotting next to a ditch. Dig next to the fish.", new WorldPoint(3547, 3183, 0), "Dig next to a fishing spot on the south-east side of Burgh de Rott."),
new CrypticClue("The King's magic won't be wasted by me.", "Guardian Mummy", new WorldPoint(1934, 4427, 0), "Talk to the Guardian mummy inside the Pyramid Plunder minigame in Sophanem"),
new CrypticClue("Dig where the forces of Zamorak and Saradomin collide.", new WorldPoint(3049, 4839, 0), "Dig next to the law rift in the Abyss"),
new CrypticClue("Search the boxes in the goblin house near Lumbridge.", BOXES, new WorldPoint(3245, 3245, 0), "Goblin house on the eastern side of the river."),
new CrypticClue("W marks the spot.", new WorldPoint(2867, 3546, 0), "Dig in the middle of the Warriors' Guild entrance hall"),
new CrypticClue("There is no 'worthier' lord.", "Lord Iorwerth", new WorldPoint(2205, 3252, 0), "Speak to Lord Iorwerth in the elven camp near Prifddinas"),
new CrypticClue("Surviving.", "Sir Vyvin", new WorldPoint(2983, 3338, 0), "Talk to Sir Vyvin on the second floor of Falador castle."),
new CrypticClue("My name is like a tree, yet it is spelt with a 'g'. Come see the fur which is right near me.", "Wilough", new WorldPoint(3221, 3435, 0), "Speak to Wilough, next to the Fur Merchant in Varrock Square."),
new CrypticClue("Speak to Jatix in Taverley.", "Jatix", new WorldPoint(2898, 3428, 0), "Jatix is found in the middle of Taverley."),
new CrypticClue("Speak to Gaius in Taverley.", "Gaius", new WorldPoint(2884, 3450, 0), "Gaius is found at the northwest corner in Taverley."),
new CrypticClue("If a man carried my burden, he would break his back. I am not rich, but leave silver in my track. Speak to the keeper of my trail.", "Gerrant", new WorldPoint(3014, 3222, 0), "Speak to Gerrant in the fish shop in Port Sarim."),
new CrypticClue("Search the drawers in Falador's chain mail shop.", DRAWERS, new WorldPoint(2969, 3311, 0), "Wayne's Chains - Chainmail Specialist store at the southern Falador walls."),
new CrypticClue("Talk to the barber in the Falador barber shop.", "Hairdresser", new WorldPoint(2945, 3379, 0), "The Hairdresser can be found in the barber shop, north of the west Falador bank."),
new CrypticClue("Often sought out by scholars of histories past, find me where words of wisdom speak volumes.", "Examiner", new WorldPoint(3362, 3341, 0), "Speak to an examiner at the Exam Centre."),
new CrypticClue("Generally speaking, his nose was very bent.", "General Bentnoze", new WorldPoint(2957, 3511, 0), "Talk to General Bentnoze"),
new CrypticClue("Search the bush at the digsite centre.", BUSH_2357, new WorldPoint(3345, 3378, 0), "The bush is on the east side of the first pathway towards the digsite from the Exam Centre."),
new CrypticClue("Someone watching the fights in the Duel Arena is your next destination.", "Jeed", new WorldPoint(3360, 3242, 0), "Talk to Jeed, found on the upper floors, at the Duel Arena."),
new CrypticClue("It seems to have reached the end of the line, and it's still empty.", MINE_CART_6045, new WorldPoint(3041, 9820, 0), "Search the carts in the northern part of the Dwarven Mine."),
new CrypticClue("You'll have to plug your nose if you use this source of herbs.", null, "Kill an Aberrant spectre."),
new CrypticClue("When you get tired of fighting, go deep, deep down until you need an antidote.", CRATE_357, new WorldPoint(2576, 9583, 0), "Go to Yanille Agility dungeon and fall into the place with the poison spiders. Search the crate by the stairs leading up."),
new CrypticClue("Search the bookcase in the monastery.", BOOKCASE_380, new WorldPoint(3054, 3484, 0), "Search the southeastern bookcase at Edgeville Monastery."),
new CrypticClue("Surprising? I bet he is...", "Sir Prysin", new WorldPoint(3205, 3474, 0), "Talk to Sir Prysin in Varrock Palace."),
new CrypticClue("Search upstairs in the houses of Seers' Village for some drawers.", DRAWERS_25766, new WorldPoint(2716, 3471, 1), "Located in the house with the spinning wheel. South of the Seers' Village bank."),
new CrypticClue("Leader of the Yak City.", "Mawnis Burowgar", new WorldPoint(2336, 3799, 0), "Talk to Mawnis Burowgar in Neitiznot."),
new CrypticClue("Speak to Arhein in Catherby.", "Arhein", new WorldPoint(2803, 3430, 0), "Arhein is just south of the Catherby bank."),
new CrypticClue("Speak to Doric, who lives north of Falador.", "Doric", new WorldPoint(2951, 3451, 0), "Doric is found north of Falador and east of the Taverley gate."),
new CrypticClue("Between where the best are commemorated for a year, and a celebratory cup, not just for beer.", new WorldPoint(3388, 3152, 0), "Dig at the Clan Cup Trophy at Clan Wars."),
new CrypticClue("'See you in your dreams' said the vegetable man.", "Dominic Onion", new WorldPoint(2608, 3116, 0), "Speak to Dominic Onion at the Nightmare Zone teleport spot."),
new CrypticClue("Try not to step on any aquatic nasties while searching this crate.", CRATE_18204, new WorldPoint(2764, 3273, 0), "Search the crate in Bailey's house on the Fishing Platform."),
new CrypticClue("The cheapest water for miles around, but they react badly to religious icons.", CRATE_354, new WorldPoint(3178, 2987, 0), "Search the crates in the General Store tent in the Bandit Camp"),
new CrypticClue("This village has a problem with cartloads of the undead. Try checking the bookcase to find an answer.", BOOKCASE_394, new WorldPoint(2833, 2992, 0), "Search the bookcase by the doorway of the building just south east of the Shilo Village Gem Mine."),
new CrypticClue("Dobson is my last name, and with gardening I seek fame.", "Horacio", new WorldPoint(2635, 3310, 0), "Horacio, located in the garden of the Handelmort Mansion in East Ardougne."),
new CrypticClue("The magic of 4 colours, an early experience you could learn. The large beast caged up top, rages, as his demised kin's loot now returns.", "Wizard Mizgog", new WorldPoint(3103, 3163, 2), "Speak to Wizard Mizgog at the top of the Wizard's Tower south of Draynor."),
new CrypticClue("Aggie I see. Lonely and southern I feel. I am neither inside nor outside the house, yet no home would be complete without me. The treasure lies beneath me!", new WorldPoint(3085, 3255, 0), "Dig outside the window of Aggie's house in Draynor Village."),
new CrypticClue("Search the chest in Barbarian Village.", CLOSED_CHEST_375, new WorldPoint(3085, 3429, 0), "The chest located in the house with a spinning wheel."),
new CrypticClue("Search the crates in the outhouse of the long building in Taverley.", CRATE_357, new WorldPoint(2914, 3433, 0), "Located in the small building attached by a fence to the main building. Climb over the stile."),
new CrypticClue("Talk to Ermin.", "Ermin", new WorldPoint(2488, 3409, 1), "Ermin can be found on the first floor of the tree house south-east of the Gnome Agility Course."),
new CrypticClue("Ghostly bones.", null, "Kill an Ankou."),
new CrypticClue("Search through chests found in the upstairs of houses in eastern Falador.", CLOSED_CHEST_375, new WorldPoint(3041, 3364, 1), "The house is located southwest of the Falador Party Room. There are two chests in the room, search the northern chest."),
new CrypticClue("Let's hope you don't meet a watery death when you encounter this fiend.", null, "Kill a waterfiend."),
new CrypticClue("Reflection is the weakness for these eyes of evil.", null, "Kill a basilisk."),
new CrypticClue("Search a bookcase in Lumbridge swamp.", BOOKCASE_9523, new WorldPoint(3146, 3177, 0), "Located in Father Urhney's house."),
new CrypticClue("Surround my bones in fire, ontop the wooden pyre. Finally lay me to rest, before my one last test.", null, "Kill a confused/lost barbarian to receive mangled bones. Construct and burn a pyre ship. Kill the ferocious barbarian spirit that spawns to receive a clue casket."),
new CrypticClue("Fiendish cooks probably won't dig the dirty dishes.", new WorldPoint(3043, 4974, 1), "Dig by the fire in the Rogues' Den."),
new CrypticClue("My life was spared but these voices remain, now guarding these iron gates is my bane.", "Key Master", new WorldPoint(1310, 1251, 0), "Speak to the Key Master in Cerberus' Lair."),
new CrypticClue("Search the boxes in one of the tents in Al Kharid.", BOXES_361, new WorldPoint(3308, 3206, 0), "Search the boxes in the tent east of the Silk trader."),
new CrypticClue("One of several rhyming brothers, in business attire with an obsession for paper work.", "Piles", new WorldPoint(3186, 3936, 0), "Speak to Piles in the Wilderness Resource Area. An entry fee of 7,500 coins is required, or less if Wilderness Diaries have been completed."),
new CrypticClue("Search the drawers on the first floor of a building overlooking Ardougne's Market.", DRAWERS_352, new WorldPoint(2657, 3322, 1), "Climb the ladder in the house north of the market."),
new CrypticClue("'A bag belt only?', he asked his balding brothers.", "Abbot Langley", new WorldPoint(3058, 3487, 0), "Talk-to Abbot Langley in Monastery west of Edgeville"),
new CrypticClue("Search the drawers upstairs in Falador's shield shop.", DRAWERS, new WorldPoint(2971, 3386, 1), "Cassie's Shield Shop at the northern Falador entrance."),
new CrypticClue("Go to this building to be illuminated, and check the drawers while you are there.", "Market Guard", DRAWERS_350 , new WorldPoint(2512, 3641, 1), "Search the drawers in the first floor of the Lighthouse. Kill a Rellekka marketplace guard to obtain the key."),
new CrypticClue("Dig near some giant mushrooms, behind the Grand Tree.", new WorldPoint(2458, 3504, 0), "Dig near the red mushrooms northwest of the Grand Tree."),
new CrypticClue("Pentagrams and demons, burnt bones and remains, I wonder what the blood contains.", new WorldPoint(3297, 3890, 0), "Dig under the blood rune spawn next the the Demonic Ruins."),
new CrypticClue("Search the drawers above Varrock's shops.", DRAWERS_7194, new WorldPoint(3206, 3419, 1), "Located upstairs in Thessalia's Fine Clothes shop in Varrock."),
new CrypticClue("Search the drawers in one of Gertrude's bedrooms.", DRAWERS_7194, new WorldPoint(3156, 3406, 0), "Kanel's bedroom (southeastern room), outside of west Varrock."),
new CrypticClue("Under a giant robotic bird that cannot fly.", new WorldPoint(1756, 4940, 0), "Dig next to the terrorbird display in the south exhibit of Varrock Museum's basement."),
new CrypticClue("Great demons, dragons and spiders protect this blue rock, beneath which, you may find what you seek.", new WorldPoint(3045, 10265, 0), "Dig by the runite rock in the Lava Maze Dungeon"),
new CrypticClue("My giant guardians below the market streets would be fans of rock and roll, if only they could grab hold of it. Dig near my green bubbles!", new WorldPoint(3161, 9904, 0), "Dig near the cauldron by Moss Giants under Varrock Sewers"),
new CrypticClue("Varrock is where I reside, not the land of the dead, but I am so old, I should be there instead. Let's hope your reward is as good as it says, just 1 gold one and you can have it read.", "Gypsy Aris", new WorldPoint(3203, 3424, 0), "Talk to Gypsy Aris, West of varrock main square."),
new CrypticClue("Speak to a referee.", "Gnome ball referee", new WorldPoint(2386, 3487, 0), "Talk to a Gnome ball referee found on the Gnome ball field in the Gnome Stronghold. Answer: 5096"),
new CrypticClue("This crate holds a better reward than a broken arrow.", CRATE_356, new WorldPoint(2671, 3437, 0), "Inside the Ranging Guild. Search the crate behind the northern most building."),
new CrypticClue("Search the drawers in the house next to the Port Sarim mage shop.", DRAWERS, new WorldPoint(3024, 3259, 0), "House east of Betty's. Contains a cooking sink."),
new CrypticClue("With a name like that, you'd expect a little more than just a few scimitars.", "Daga", new WorldPoint(2759, 2775, 0), "Speak to Daga on Ape Atoll."),
new CrypticClue("Strength potions with red spiders' eggs? He is quite a herbalist.", "Apothecary", new WorldPoint(3194, 3403, 0), "Talk to Apothecary in the South-western Varrock. (the) apothecary is just north-west of the Varrock Swordshop."),
new CrypticClue("Robin wishes to see your finest ranged equipment.", "Robin", new WorldPoint(3673, 3492, 0), "Robin at the inn in Port Phasmatys. Speak to him with +182 in ranged attack bonus."),
new CrypticClue("You will need to under-cook to solve this one.", CRATE_357, new WorldPoint(3219, 9617, 0), "Search the crate in the Lumbridge basement."),
new CrypticClue("Search through some drawers found in Taverley's houses.", DRAWERS_350, new WorldPoint(2894, 3418, 0), "The south-eastern most house, south of Jatix's Herblore Shop."),
new CrypticClue("Anger Abbot Langley.", "Abbot Langley", new WorldPoint(3058, 3487, 0), "Speak to Abbot Langley in the Edgeville Monastery while you have a negative prayer bonus (currently only possible with an Ancient staff)."),
new CrypticClue("Dig where only the skilled, the wealthy, or the brave can choose not to visit again.", new WorldPoint(3221, 3219, 0), "Dig at Lumbridge spawn"),
new CrypticClue("Scattered coins and gems fill the floor. The chest you seek is in the north east.", "King Black Dragon", CLOSED_CHEST_375, new WorldPoint(2288, 4702, 0), "Kill the King Black Dragon for a key (elite), and then open the closed chest in the NE corner of the lair."),
new CrypticClue("A ring of water surrounds 4 powerful rings, dig above the ladder located there.", new WorldPoint(1910, 4367, 0), "Dig by the ladder leading to the Dagannoth Kings room in the Waterbirth Island Dungeon."),
new CrypticClue("This place sure is a mess.", "Ewesey", new WorldPoint(1646, 3631, 0), "Ewesey is located in the mess hall in Hosidius."),
new CrypticClue("Here, there are tears, but nobody is crying. Speak to the guardian and show off your alignment to balance.", "Juna", JUNA, new WorldPoint(3252, 9517, 2), "Talk to Juna while wearing three Guthix related items."),
new CrypticClue("You might have to turn over a few stones to progress.", null, "Kill a rock crab."),
new CrypticClue("Dig under Razorlor's toad batta.", new WorldPoint(3139, 4554, 0), "Dig on the toad batta spawn in Tarn's Lair."),
new CrypticClue("Talk to Cassie in Falador.", "Cassie", new WorldPoint(2975, 3383, 0), "Cassie is found just south-east of the northern Falador gate."),
new CrypticClue("Faint sounds of 'Arr', fire giants found deep, the eastern tip of a lake, are the rewards you could reap.", new WorldPoint(3055, 10338, 0), "Dig south of the pillar at the end of the Deep Wilderness Dungeon."),
new CrypticClue("If you're feeling brave, dig beneath the dragon's eye.", new WorldPoint(2410, 4714, 0), "Dig below the mossy rock under the Viyeldi caves (Legend's Quest). Items needed: Pickaxe, unpowered orb, lockpick, spade, and any charge orb spell."),
new CrypticClue("Search the tents in the Imperial Guard camp in Burthorpe for some boxes.", BOXES_3686, new WorldPoint(2885, 3540, 0), "Search in the tents in northwest corner of the camp."),
new CrypticClue("A dwarf, approaching death, but very much in the light.", "Thorgel", new WorldPoint(1863, 4639, 0), "Thorgel at the entrance to the Death altar"),
new CrypticClue("You must be 100 to play with me.", "Squire (Veteran)", new WorldPoint(2638, 2656, 0), "Speak to the Veteran boat squire at Pest Control"),
new CrypticClue("Three rule below and three sit at top. Come dig at my entrance.", new WorldPoint(2523, 3739, 0), "Dig in front of the entrance to the Waterbirth Island Dungeon."),
new CrypticClue("Search the drawers in the ground floor of a shop in Yanille.", DRAWERS_350, new WorldPoint(2570, 3085, 0), "Search the drawers in Yanille's hunting shop."),
new CrypticClue("Search the drawers of houses in Burthorpe.", DRAWERS, new WorldPoint(2929, 3570, 0), "Inside Hild's house in the northeast corner of Burthorpe."),
new CrypticClue("Where safe to speak, the man who offers the pouch of smallest size wishes to see your alignment.", "Mage of Zamorak", new WorldPoint(3260, 3385, 0), "Speak to the Mage of Zamorak south of the Rune Shop in Varrock while wearing three zamorakian items"),
new CrypticClue("Search the crates in the guard house of the northern gate of East Ardougne.", CRATE_356, new WorldPoint(2645, 3338, 0), "The guard house is northeast of the Handelmort Mansion."),
new CrypticClue("Go to the village being attacked by trolls, search the drawers in one of the houses.", "Penda", DRAWERS_350, new WorldPoint(2921, 3577, 0), "Go to Dunstan's house in the northeast corner of Burthorpe. Kill Penda in the Toad and Chicken to obtain the key."),
new CrypticClue("You'll get licked.", null, "Kill a Bloodveld."),
new CrypticClue("She's small but can build both literally and figuratively, as long as you have their favour.", "Lovada", new WorldPoint(1486, 3834, 0), "Speak to Lovada by the entrance to the blast mine in Lovakengj."),
new CrypticClue("Dig in front of the icy arena where 1 of 4 was fought.", new WorldPoint(2874, 3757, 0), "Where you fought Kamil from Desert Treasure."),
new CrypticClue("Speak to Roavar.", "Roavar", new WorldPoint(3494, 3474, 0), "Talk to Roavar in the Canifis tavern."),
new CrypticClue("Search the drawers upstairs of houses in the eastern part of Falador.", DRAWERS_350, new WorldPoint(3035, 3347, 1), "House is located east of the eastern Falador bank and south of the fountain. The house is indicated by the icon on the minimap."),
new CrypticClue("Search the drawers found upstairs in East Ardougne's houses.", DRAWERS, new WorldPoint(2574, 3326, 1), "Upstairs of the pub north of the Ardougne Castle."),
new CrypticClue("The far north eastern corner where 1 of 4 was defeated, the shadows still linger.", new WorldPoint(2744, 5116, 0), "Dig on the northeastern-most corner of the Shadow Dungeon. Bring a ring of visibility."),
new CrypticClue("Search the drawers in a house in Draynor Village.", DRAWERS_350, new WorldPoint(3097, 3277, 0), "The drawer is located in the northernmost house in Draynor Village."),
new CrypticClue("Search the boxes in a shop in Taverley.", BOXES_360, new WorldPoint(2886, 3449, 0), "The box inside Gaius' Two Handed Shop."),
new CrypticClue("I lie beneath the first descent to the holy encampment.", new WorldPoint(2914, 5300, 1), "Dig immediately after climbing down the first set of rocks towards Saradomin's encampment within the God Wars Dungeon."),
new CrypticClue("Search the upstairs drawers of a house in a village where pirates are known to have a good time.", "Pirate", 348, new WorldPoint(2809, 3165, 1), "The house in the southeast corner of Brimhaven, northeast of Davon's Amulet Store. Kill any Pirate located around Brimhaven to obtain the key."),
new CrypticClue("Search the chest in the Duke of Lumbridge's bedroom.", CLOSED_CHEST_375, new WorldPoint(3209, 3218, 1), "The Duke's room is on the first floor in Lumbridge Castle."),
new CrypticClue("Talk to the Doomsayer.", "Doomsayer", new WorldPoint(3232, 3228, 0), "Doomsayer can be found just north of Lumbridge Castle entrance."),
new CrypticClue("Search the chests upstairs in Al Kharid Palace.", CLOSED_CHEST_375, new WorldPoint(3301, 3169, 1), "The chest is located, in the northeast corner, on the first floor of the Al Kharid Palace"),
new CrypticClue("Search the boxes just outside the Armour shop in East Ardougne.", BOXES_361, new WorldPoint(2654, 3299, 0), "Outside Zenesha's Plate Mail Body Shop"),
new CrypticClue("Surrounded by white walls and gems.", "Herquin", new WorldPoint(2945, 3335, 0), "Talk to Herquin, the gem store owner in Falador."),
new CrypticClue("Monk's residence in the far west. See robe storage device.", DRAWERS_350, new WorldPoint(1742, 3490, 1), "Search the drawers upstairs in the chapel found on the southern coast of Hosidius, directly south of the player-owned house portal."),
new CrypticClue("Search the drawers in Catherby's Archery shop.", DRAWERS_350, new WorldPoint(2825, 3442, 0), "Hickton's Archery Emporium in Catherby."),
new CrypticClue("The hand ain't listening.", "The Face", new WorldPoint(3019, 3232, 0), "Talk to The Face located by the manhole just north of the Port Sarim fishing shop."),
new CrypticClue("Search the chest in the left-hand tower of Camelot Castle.", CLOSED_CHEST_25592, new WorldPoint(2748, 3495, 2), "Located on the second floor of the western tower of Camelot."),
new CrypticClue("Kill the spiritual, magic and godly whilst representing their own god.", null, "Kill a spiritual mage while wearing a corresponding god item."),
new CrypticClue("Anger those who adhere to Saradomin's edicts to prevent travel.", "Monk of Entrana", new WorldPoint(3042, 3236, 0), "Port Sarim Docks, try to charter a ship to Entrana with armour or weapons equipped."),
new CrypticClue("South of a river in a town surrounded by the undead, what lies beneath the furnace?", new WorldPoint(2857, 2966, 0), "Dig in front of the Shilo Village furnace."),
new CrypticClue("Talk to the Squire in the White Knights' castle in Falador.", "Squire", new WorldPoint(2977, 3343, 0), "The squire is located in the courtyard of the White Knights' Castle."),
new CrypticClue("Thanks, Grandma!", "Tynan", new WorldPoint(1836, 3786, 0), "Tynan can be found in the north-east corner of Port Piscarilius."),
new CrypticClue("In a town where everyone has perfect vision, seek some locked drawers in a house that sits opposite a workshop.", "Chicken", DRAWERS_25766, new WorldPoint(2709, 3478, 0), "The Seers' Village house south of the Elemental Workshop entrance. Kill any Chicken to obtain a key."),
new CrypticClue("The treasure is buried in a small building full of bones. Here is a hint: it's not near a graveyard.", new WorldPoint(3356, 3507, 0), "In the western building near the Limestone quarry east of Varrock. Dig south of the box of bones in the smaller building."),
new CrypticClue("Search the crates in East Ardougne's general store.", CRATE_357, new WorldPoint(2615, 3291, 0), "Located south of the Ardounge church."),
new CrypticClue("Come brave adventurer, your sense is on fire. If you talk to me, it's an old god you desire.", "Viggora", null, "Speak to Viggora"),
new CrypticClue("2 musical birds. Dig in front of the spinning light.", new WorldPoint(2671, 10396, 0), "Dig in front of the spinning light in Ping and Pong's room inside the Iceberg"),
new CrypticClue("Search the wheelbarrow in Rimmington mine.", WHEELBARROW_9625, new WorldPoint(2978, 3239, 0), "The Rimmington mining site is located north of Rimmington."),
new CrypticClue("Belladonna, my dear. If only I had gloves, then I could hold you at last.", "Tool Leprechaun", new WorldPoint(3088, 3357, 0), "Talk to Tool Leprechaun at Draynor Manor"),
new CrypticClue("Impossible to make angry", "Abbot Langley", new WorldPoint(3059, 3486, 0), "Speak to Abbot Langley at the Edgeville Monastery."),
new CrypticClue("Search the crates in Horvik's armoury.", CRATE_5106, new WorldPoint(3228, 3433, 0), "Horvik's in Varrock"),
new CrypticClue("Ghommal wishes to be impressed by how strong your equipment is.", "Ghommal", new WorldPoint(2878, 3546, 0), "Speak to Ghommal at the Warriors' Guild with a total Melee Strength bonus of over 100."),
new CrypticClue("Shhhh!", "Logosia", new WorldPoint(1633, 3808, 0), "Speak to Logosia in the Arceuus Library's ground floor."),
new CrypticClue("Salty peter.", "Konoo", new WorldPoint(1703, 3524, 0), "Talk to Konoo who is digging saltpetre in Hosidius, south of the bank."),
new CrypticClue("Talk to Zeke in Al Kharid.", "Zeke", new WorldPoint(3287, 3190, 0), "Zeke is the owner of the scimitar shop in Al Kharid."),
new CrypticClue("Guthix left his mark in a fiery lake, dig at the tip of it.", new WorldPoint(3069, 3935, 0), "Dig at the tip of the lava lake that is shaped like a Guthixian symbol, west of the Mage Arena."),
new CrypticClue("Search the drawers in the upstairs of a house in Catherby.", DRAWERS_350, new WorldPoint(2809, 3451, 1), "Perdu's house in Catherby."),
new CrypticClue("Search a crate in the Haymaker's arms.", CRATE_27532, new WorldPoint(1720, 3652, 1), "Search the crate in the north-east corner of The Haymaker's Arms tavern east of Kourend Castle."),
new CrypticClue("Desert insects is what I see. Taking care of them was my responsibility. Your solution is found by digging near me.", new WorldPoint(3307, 9505, 0), "Dig next to the Entomologist, Kalphite area, near Shantay Pass."),
new CrypticClue("Search the crates in the most north-western house in Al Kharid.", CRATE_358, new WorldPoint(3289, 3202, 0), "Search the crates in the house, marked with a icon, southeast of the gem stall."),
new CrypticClue("You will have to fly high where a sword cannot help you.", null, "Kill an Aviansie."),
new CrypticClue("A massive battle rages beneath so be careful when you dig by the large broken crossbow.", new WorldPoint(2927, 3761, 0), "NE of the God Wars Dungeon entrance, climb the rocky handholds & dig by large crossbow."),
new CrypticClue("Mix yellow with blue and add heat, make sure you bring protection.", null, "Kill a green dragon."),
new CrypticClue("Speak to Ellis in Al Kharid.", "Ellis", new WorldPoint(3276, 3191, 0), "Ellis is tanner just north of Al Kharid bank."),
new CrypticClue("Search the chests in the Dwarven Mine.", CLOSED_CHEST_375, new WorldPoint(3000, 9798, 0), "The chest is on the western wall, where Hura's Crossbow Shop is, in the Dwarven Mine."),
new CrypticClue("In a while...", null, "Kill a crocodile."),
new CrypticClue("A chisel and hammer reside in his home, strange for one of magic. Impress him with your magical equipment.", "Wizard Cromperty", new WorldPoint(2682, 3325, 0), "Wizard Cromperty, NE corner of East Ardougne. +100 magic attack bonus needed"),
new CrypticClue("You have all of the elements available to solve this clue. Fortunately you do not have to go as far as to stand in a draft.", CRATE_18506, new WorldPoint(2723, 9891, 0), "Search the crate, west of the Air Elementals, inside the Elemental Workshop."),
new CrypticClue("A demon's best friend holds the next step of this clue.", null, "Kill a hellhound."),
new CrypticClue("Dig in the centre of a great kingdom of 5 cities.", new WorldPoint(1639, 3673, 0), "Dig in front of the large statue in the centre of Great Kourend."),
new CrypticClue("Hopefully this set of armour will help you to keep surviving.", "Sir Vyvin", new WorldPoint(2982, 3336, 2), "Speak to Sir Vyvin while wearing a white platebody, and platelegs."),
new CrypticClue("The beasts retreat, for their Queen is gone; the song of this town still plays on. Dig near the birthplace of a blade, be careful not to melt your spade.", new WorldPoint(2342, 3677, 0), "Dig in front of the small furnace in the Piscatoris Fishing Colony."),
new CrypticClue("Darkness wanders around me, but fills my mind with knowledge.", "Biblia", new WorldPoint(1633, 3825, 2), "Speak to Biblia on the Arceuus Library's top floor."),
new CrypticClue("I would make a chemistry joke, but I'm afraid I wouldn't get a reaction.", "Chemist", new WorldPoint(2932, 3212, 0), "Talk to the Chemist in Rimmington"),
new CrypticClue("Show this to Hazelmere.", "Hazelmere", new WorldPoint(2677, 3088, 1), "Hazelmere is found upstairs on the island located just east of Yanille."),
new CrypticClue("Does one really need a fire to stay warm here?", new WorldPoint(3816, 3810, 0), "Dig next to the fire near the Volcanic Mine entrance."),
new CrypticClue("Search the open crate found in the Hosidius kitchens.", CRATE_27533, new WorldPoint(1683, 3616, 0), "The kitchens are north-west of the town in Hosidius."),
new CrypticClue("Dig under Ithoi's cabin.", new WorldPoint(2529, 2838, 0), "Dig under Ithoi's cabin in the Corsair Cove."),
new CrypticClue("Search the drawers, upstairs in the bank to the East of Varrock.", DRAWERS_7194, new WorldPoint(3250, 3420, 1), "Search the drawers upstairs in Varrock east bank."),
new CrypticClue("Speak to Hazelmere.", "Hazelmere", new WorldPoint(2677, 3088, 1), "Located upstairs in the house to the north of fairy ring CLS. Answer: 6859"),
new CrypticClue("The effects of this fire are magnified.", new WorldPoint(1179, 3626, 0), "Dig by the fire beside Ket'sal K'uk in the westernmost part of the Kebos Swamp. "),
new CrypticClue("Always walking around the castle grounds and somehow knows everyone's age.", "Hans", new WorldPoint(3221, 3218, 0), "Talk to Hans walking around Lumbridge Castle."),
new CrypticClue("In the place Duke Horacio calls home, talk to a man with a hat dropped by goblins.", "Cook", new WorldPoint(3208, 3213, 0), "Talk to the Cook in Lumbridge Castle."),
new CrypticClue("In a village of barbarians, I am the one who guards the village from up high.", "Hunding", new WorldPoint(3097, 3432, 2), "Talk to Hunding atop the tower on the east side of Barbarian Village."),
new CrypticClue("Talk to Charlie the Tramp in Varrock.", "Charlie the Tramp", new WorldPoint(3209, 3390, 0), "Talk to Charlie the Tramp by the southern entrance to Varrock. He will give you a task."),
new CrypticClue("Near the open desert I reside, to get past me you must abide. Go forward if you dare, for when you pass me, you'll be sweating by your hair.", "Shantay", new WorldPoint(3303, 3123, 0), "Talk to Shantay at the Shantay Pass south of Al Kharid."),
new CrypticClue("Search the chest in Fred the Farmer's bedroom.", CLOSED_CHEST_375, new WorldPoint(3185, 3274, 0), "Search the chest by Fred the Farmer's bed in his house north-west of Lumbridge."),
new CrypticClue("Search the eastern bookcase in Father Urhney's house.", BOOKCASE_9523, new WorldPoint(3149, 3177, 0), "Father Urhney's house is found in the western end of the Lumbridge Swamp."),
new CrypticClue("Talk to Morgan in his house at Draynor Village.", "Morgan", new WorldPoint(3098, 3268, 0), "Morgan can be found in the house with the quest start map icon."),
new CrypticClue("Talk to Charles at Port Piscarilius.", "Charles", new WorldPoint(1821, 3690, 0), "Charles is found by Veos' ship in Port Piscarilius."),
new CrypticClue("Search the crate in Rommiks crafting shop in Rimmington.", CRATE_9534, new WorldPoint(2947, 3206, 0), "The crates in Rommik's Crafty Supplies in Rimmington."),
new CrypticClue("Talk to Ali the Leaflet Dropper north of the Al Kharid mine.", "Ali the Leaflet Dropper", new WorldPoint(3283, 3329, 0), "Ali the Leaflet Dropper can be found roaming north of the Al Kharid mine."),
new CrypticClue("Talk to the cook in the Blue Moon Inn in Varrock.", "Cook", new WorldPoint(3230, 3401, 0), "The Blue Moon Inn can be found by the southern entrance to Varrock."),
new CrypticClue("Search the single crate in Horvik's smithy in Varrock.", CRATE_5106, new WorldPoint(3228, 3433, 0), "Horvik's Smithy is found north-east of of Varrock Square."),
new CrypticClue("Search the crates in Falador General store.", CRATES_24088, new WorldPoint(2955, 3390, 0), "The Falador General Store can be found by the northern entrance to the city."),
new CrypticClue("Talk to Wayne at Wayne's Chains in Falador.", "Wayne", new WorldPoint(2972, 3312, 0), "Wayne's shop is found directly south of the White Knights' Castle."),
new CrypticClue("Search the boxes next to a chest that needs a crystal key.", BOXES_360, new WorldPoint(2915, 3452, 0), "The Crystal chest can be found in the house directly south of the Witch's house in Taverley."),
new CrypticClue("Talk to Turael in Burthorpe.", "Turael", new WorldPoint(2930, 3536, 0), "Turael is located in the small house east of the Toad and Chicken inn."),
new CrypticClue("More resources than I can handle, but in a very dangerous area. Can't wait to strike gold!", new WorldPoint(3183, 3941, 0), "Dig between the three gold ores in the Wilderness Resource Area."),
new CrypticClue("Observing someone in a swamp, under the telescope lies treasure.", new WorldPoint(2221, 3091, 0), "Dig next to the telescope on Broken Handz's island in the poison wastes. (Accessible only through fairy ring DLR)")
);
private final String text;
private final String npc;
private final int objectId;
private final WorldPoint location;
private final String solution;
private CrypticClue(String text, WorldPoint location, String solution)
{
this(text, null, -1, location, solution);
}
private CrypticClue(String text, int objectId, WorldPoint location, String solution)
{
this(text, null, objectId, location, solution);
}
private CrypticClue(String text, String npc, WorldPoint location, String solution)
{
this(text, npc, -1, location, solution);
}
private CrypticClue(String text, String npc, int objectId, WorldPoint location, String solution)
{
this.text = text;
this.npc = npc;
this.objectId = objectId;
this.location = location;
this.solution = solution;
setRequiresSpade(getLocation() != null && getNpc() == null && objectId == -1);
}
@Override
public void makeOverlayHint(PanelComponent panelComponent, ClueScrollPlugin plugin)
{
panelComponent.getChildren().add(TitleComponent.builder().text("Cryptic Clue").build());
if (getNpc() != null)
{
panelComponent.getChildren().add(LineComponent.builder().left("NPC:").build());
panelComponent.getChildren().add(LineComponent.builder()
.left(getNpc())
.leftColor(TITLED_CONTENT_COLOR)
.build());
}
if (objectId != -1)
{
ObjectComposition object = plugin.getClient().getObjectDefinition(objectId);
if (object != null && object.getImpostorIds() != null)
{
object = object.getImpostor();
}
if (object != null)
{
panelComponent.getChildren().add(LineComponent.builder().left("Object:").build());
panelComponent.getChildren().add(LineComponent.builder()
.left(object.getName())
.leftColor(TITLED_CONTENT_COLOR)
.build());
}
}
panelComponent.getChildren().add(LineComponent.builder().left("Solution:").build());
panelComponent.getChildren().add(LineComponent.builder()
.left(getSolution())
.leftColor(TITLED_CONTENT_COLOR)
.build());
}
@Override
public void makeWorldOverlayHint(Graphics2D graphics, ClueScrollPlugin plugin)
{
// Mark dig location
if (getLocation() != null && getNpc() == null && objectId == -1)
{
LocalPoint localLocation = LocalPoint.fromWorld(plugin.getClient(), getLocation());
if (localLocation != null)
{
OverlayUtil.renderTileOverlay(plugin.getClient(), graphics, localLocation, plugin.getSpadeImage(), Color.ORANGE);
}
}
// Mark NPC
if (plugin.getNpcsToMark() != null)
{
for (NPC npc : plugin.getNpcsToMark())
{
OverlayUtil.renderActorOverlayImage(graphics, npc, plugin.getClueScrollImage(), Color.ORANGE, IMAGE_Z_OFFSET);
}
}
// Mark game object
if (objectId != -1)
{
net.runelite.api.Point mousePosition = plugin.getClient().getMouseCanvasPosition();
if (plugin.getObjectsToMark() != null)
{
for (TileObject gameObject : plugin.getObjectsToMark())
{
OverlayUtil.renderHoverableArea(graphics, gameObject.getClickbox(), mousePosition,
CLICKBOX_FILL_COLOR, CLICKBOX_BORDER_COLOR, CLICKBOX_HOVER_BORDER_COLOR);
OverlayUtil.renderImageLocation(plugin.getClient(), graphics, gameObject.getLocalLocation(), plugin.getClueScrollImage(), IMAGE_Z_OFFSET);
}
}
}
}
public static CrypticClue forText(String text)
{
for (CrypticClue clue : CLUES)
{
if (clue.text.equalsIgnoreCase(text))
{
return clue;
}
}
return null;
}
@Override
public int[] getObjectIds()
{
return new int[] {objectId};
}
@Override
public String[] getNpcs()
{
return new String[] {npc};
}
}
| runelite-client/src/main/java/net/runelite/client/plugins/cluescrolls/clues/CrypticClue.java | /*
* Copyright (c) 2018, Lotto <https://github.com/devLotto>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.cluescrolls.clues;
import com.google.common.collect.ImmutableSet;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.Set;
import lombok.Getter;
import net.runelite.api.NPC;
import static net.runelite.api.NullObjectID.NULL_1293;
import net.runelite.api.ObjectComposition;
import static net.runelite.api.ObjectID.*;
import net.runelite.api.TileObject;
import net.runelite.api.coords.LocalPoint;
import net.runelite.api.coords.WorldPoint;
import static net.runelite.client.plugins.cluescrolls.ClueScrollOverlay.TITLED_CONTENT_COLOR;
import net.runelite.client.plugins.cluescrolls.ClueScrollPlugin;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_BORDER_COLOR;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_FILL_COLOR;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_HOVER_BORDER_COLOR;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.IMAGE_Z_OFFSET;
import net.runelite.client.ui.overlay.OverlayUtil;
import net.runelite.client.ui.overlay.components.LineComponent;
import net.runelite.client.ui.overlay.components.PanelComponent;
import net.runelite.client.ui.overlay.components.TitleComponent;
@Getter
public class CrypticClue extends ClueScroll implements TextClueScroll, NpcClueScroll, ObjectClueScroll
{
public static final Set<CrypticClue> CLUES = ImmutableSet.of(
new CrypticClue("Show this to Sherlock.", "Sherlock", new WorldPoint(2733, 3415, 0), "Sherlock is located to the east of the Sorcerer's tower in Seers' Village."),
new CrypticClue("Talk to the bartender of the Rusty Anchor in Port Sarim.", "Bartender", new WorldPoint(3045, 3256, 0), "The Rusty Anchor is located in the north of Port Sarim."),
new CrypticClue("The keeper of Melzars... Spare? Skeleton? Anar?", "Oziach", new WorldPoint(3068, 3516, 0), "Speak to Oziach in Edgeville"),
new CrypticClue("Speak to Ulizius.", "Ulizius", new WorldPoint(3444, 3461, 0), "Ulizius is the monk who guards the gate into Mort Myre Swamp. South of fairy ring CKS"),
new CrypticClue("Search for a crate in a building in Hemenster.", CRATE_357, new WorldPoint(2636, 3453, 0), "House north of the Fishing Contest quest area. West of Grandpa Jack."),
new CrypticClue("A reck you say; let's pray there aren't any ghosts.", "Father Aereck", new WorldPoint(3242, 3207, 0), "Speak to Father Aereck in Lumbridge."),
new CrypticClue("Search the bucket in the Port Sarim jail.", BUCKET_9568, new WorldPoint(3013, 3179, 0), "Talk to Shantay & identify yourself as an outlaw, refuse to pay the 5gp fine twice and you will be sent to the Port Sarim jail."),
new CrypticClue("Search the crates in a bank in Varrock.", CRATE_5107, new WorldPoint(3187, 9825, 0), "Search in the basement of the West Varrock bank."),
new CrypticClue("Falo the bard wants to see you.", "Falo the Bard", new WorldPoint(2689, 3550, 0), "Speak to Falo the Bard located between Seer's Village and Rellekka. Southwest of fairy ring CJR."),
new CrypticClue("Search a bookcase in the Wizards tower.", BOOKCASE_12539, new WorldPoint(3113, 3159, 0), "The bookcase located on the ground floor."),
new CrypticClue("Come have a cip with this great soot covered denizen.", "Miner Magnus", new WorldPoint(2527, 3891, 0), "Talk to Miner Magnus east of the fairy ring CIP. Answer: 8"),
new CrypticClue("Citric cellar.", "Heckel Funch", new WorldPoint(2490, 3488, 0), "Speak to Heckel Funch on the first floor in the Grand Tree."),
new CrypticClue("I burn between heroes and legends.", "Candle maker", new WorldPoint(2799, 3438, 0), "Speak to the Candle maker in Catherby."),
new CrypticClue("Speak to Sarah at Falador farm.", "Sarah", new WorldPoint(3038, 3292, 0), "Talk to Sarah at Falador farm, north of Port Sarim."),
new CrypticClue("Search for a crate on the ground floor of a house in Seers' Village.", CRATE_25775, new WorldPoint(2699, 3470, 0), "Search inside Phantuwti Fanstuwi Farsight's house, located south of the pub in Seers' Village."),
new CrypticClue("Snah? I feel all confused, like one of those cakes...", "Hans", new WorldPoint(3211, 3219, 0), "Talk to Hans roaming around Lumbridge Castle."),
new CrypticClue("Speak to Sir Kay in Camelot Castle.", "Sir Kay", new WorldPoint(2759, 3497, 0), "Sir Kay can be found in the courtyard at Camelot castle."),
new CrypticClue("Gold I see, yet gold I require. Give me 875 if death you desire.", "Saniboch", new WorldPoint(2745, 3151, 0), "Speak to Saniboch at the Brimhaven Dungeon entrance."),
new CrypticClue("Find a crate close to the monks that like to paaarty!", CRATE_354, new WorldPoint(2614, 3204, 0), "The crate is in the east side of the Kandarin monastery, near Brother Omad"),
new CrypticClue("Identify the back of this over-acting brother. (He's a long way from home.)", "Hamid", new WorldPoint(3376, 3284, 0), "Talk to Hamid, the monk at the altar in the Duel Arena"),
new CrypticClue("In a town where thieves steal from stalls, search for some drawers in the upstairs of a house near the bank.", "Guard", DRAWERS, new WorldPoint(2611, 3324, 1), "Kill any Guard located around East Ardougne for a medium key. Then search the drawers in the upstairs hallway of Jerico's house, which is the house with pigeon cages located south of the northern East Ardougne bank."),
new CrypticClue("His bark is worse than his bite.", "Barker", new WorldPoint(3499, 3503, 0), "Speak to the Barker at Canifis's Barkers' Haberdashery."),
new CrypticClue("The beasts to my east snap claws and tails, The rest to my west can slide and eat fish. The force to my north will jump and they'll wail, Come dig by my fire and make a wish.", new WorldPoint(2598, 3267, 0), "Dig by the torch in the Ardougne Zoo, between the penguins and the scorpions."),
new CrypticClue("A town with a different sort of night-life is your destination. Search for some crates in one of the houses.", CRATE_24344, new WorldPoint(3498, 3507, 0), "Search the crate inside of the clothes shop in Canifis."),
new CrypticClue("Stop crying! Talk to the head.", "Head mourner", new WorldPoint(2042, 4630, 0), "Talk to the Head mourner in the mourner headquarters in West Ardougne"),
new CrypticClue("Search the crate near a cart in Port Khazard.", CRATE_366, new WorldPoint(2660, 3149, 0), "Search by the southern Khazard General Store in Port Khazard."),
new CrypticClue("Speak to the bartender of the Blue Moon Inn in Varrock.", "Bartender", new WorldPoint(3226, 3399, 0), "Talk to the bartender in Blue Moon Inn in Varrock."),
new CrypticClue("This aviator is at the peak of his profession.", "Captain Bleemadge", new WorldPoint(2846, 1749, 0), "Captain Bleemadge, the gnome glider pilot, is found at the top of White Wolf Mountain."),
new CrypticClue("Search the crates in the shed just north of East Ardougne.", CRATE_355, new WorldPoint(2617, 3347, 0), "The crates in the shed north of the northern Ardougne bank."),
new CrypticClue("I wouldn't wear this jean on my legs.", "Father Jean", new WorldPoint(1734, 3576, 0), "Talk to father Jean in the Hosidius church"),
new CrypticClue("Search the crate in the Toad and Chicken pub.", CRATE_354, new WorldPoint(2913, 3536, 0), "The Toad and Chicken pub is located in Burthorpe."),
new CrypticClue("Search chests found in the upstairs of shops in Port Sarim.", CLOSED_CHEST_375, new WorldPoint(3016, 3205, 1), "Search the chest in the upstairs of Wydin's Food Store, on the east wall."),
new CrypticClue("Right on the blessed border, cursed by the evil ones. On the spot inaccessible by both; I will be waiting. The bugs' imminent possession holds the answer.", new WorldPoint(3410, 3324, 0), "B I P. Dig right under the fairy ring."),
new CrypticClue("The dead, red dragon watches over this chest. He must really dig the view.", "Barbarian", 375, new WorldPoint(3353, 3332, 0), "Search the chest underneath the Red Dragon's head in the Exam Centre. Kill a MALE Barbarian in Barbarian Village or Barbarian Outpost to receive the key."),
new CrypticClue("My home is grey, and made of stone; A castle with a search for a meal. Hidden in some drawers I am, across from a wooden wheel.", DRAWERS_5618, new WorldPoint(3213, 3216, 1), "Open the drawers inside the room with the spinning wheel on the first floor of Lumbridge Castle."),
new CrypticClue("Come to the evil ledge, Yew know yew want to. Try not to get stung.", new WorldPoint(3089, 3468, 0), "Dig in Edgeville, just east of the Southern Yew tree."),
new CrypticClue("Look in the ground floor crates of houses in Falador.", CRATES_24088, new WorldPoint(3029, 3355, 0), "The house east of the east bank."),
new CrypticClue("You were 3 and I was the 6th. Come speak to me.", "Vannaka", new WorldPoint(3146, 9913, 0), "Speak to Vannaka in Edgeville Dungeon."),
new CrypticClue("Search the crates in Draynor Manor.", CRATE_11485, new WorldPoint(3106, 3369, 2), "Top floor of the manor"),
new CrypticClue("Search the crates near a cart in Varrock.", CRATE_5107, new WorldPoint(3226, 3452, 0), "South east of Varrock Palace, south of the tree farming patch."),
new CrypticClue("A Guthixian ring lies between two peaks. Search the stones and you'll find what you seek.", STONES_26633, new WorldPoint(2922, 3484, 0), "Search the stones several steps west of the Guthixian stone circle in Taverley"),
new CrypticClue("Search the boxes in the house near the south entrance to Varrock.", BOXES_5111, new WorldPoint(3203, 3384, 0), "The first house on the left when entering the city from the southern entrance."),
new CrypticClue("His head might be hollow, but the crates nearby are filled with surprises.", CRATE_354, new WorldPoint(3478, 3091, 0), "Search the crates near the Clay golem in the ruins of Uzer."),
new CrypticClue("One of the sailors in Port Sarim is your next destination.", "Captain Tobias", new WorldPoint(3026, 3216, 0), "Speak to Captain Tobias on the docks of Port Sarim."),
new CrypticClue("THEY'RE EVERYWHERE!!!! But they were here first. Dig for treasure where the ground is rich with ore.", new WorldPoint(3081, 3421, 0), "Dig at Barbarian Village, next to the Stronghold of Security."),
new CrypticClue("Talk to the mother of a basement dwelling son.", "Doris", new WorldPoint(3079, 3493, 0), "Evil Dave's mother, Doris is located in the house west of Edgeville bank."),
new CrypticClue("Speak to Ned in Draynor Village.", "Ned", new WorldPoint(3098, 3258, 0), "Ned is found north of the Draynor bank."),
new CrypticClue("Speak to Hans to solve the clue.", "Hans", new WorldPoint(3211, 3219, 0), "Hans can be found at Lumbridge Castle."),
new CrypticClue("Search the crates in Canifis.", CRATE_24344, new WorldPoint(3509, 3497, 0), "Search inside the shop, Rufus' Meat Emporium."),
new CrypticClue("Search the crates in the Dwarven mine.", CRATE_357, new WorldPoint(3035, 9849, 0), "Search the crate in the room east of the Ice Mountain ladder entrance in the Drogo's Mining Emporium."),
new CrypticClue("A crate found in the tower of a church is your next location.", CRATE_357, new WorldPoint(2612, 3304, 1), "Climb the ladder and search the crates on the first floor in the Church in Ardougne"),
new CrypticClue("Covered in shadows, the centre of the circle is where you will find the answer.", new WorldPoint(3488, 3289, 0), "Dig in the centre of Mort'ton, where the roads intersect"),
new CrypticClue("I lie lonely and forgotten in mid wilderness, where the dead rise from their beds. Feel free to quarrel and wind me up, and dig while you shoot their heads.", new WorldPoint(3174, 3663, 0), "Directly under the crossbow respawn in the Graveyard of Shadows in level 18 Wilderness."),
new CrypticClue("In the city where merchants are said to have lived, talk to a man with a splendid cape, but a hat dropped by goblins.", "Head chef", new WorldPoint(3143, 3445, 0), "Talk to the Head chef in Cooks' Guild west of Varrock."),
new CrypticClue("The mother of the reptilian sacrifice.", "Zul-Cheray", new WorldPoint(2204, 3050, 0), "Talk to Zul-Cheray in a house near the sacrificial boat at Zul-Andra."),
new CrypticClue("I watch the sea. I watch you fish. I watch your tree.", "Ellena", new WorldPoint(2860, 3431, 0), "Speak to Ellena at Catherby fruit tree patch."),
new CrypticClue("Dig between some ominous stones in Falador.", new WorldPoint(3040, 3399, 0), "Three standing stones inside a walled area. East of the northern Falador gate."),
new CrypticClue("Speak to Rusty north of Falador.", "Rusty", new WorldPoint(2979, 3435, 0), "Rusty can be found northeast of Falador on the way to the Mind altar."),
new CrypticClue("Search a wardrobe in Draynor.", WARDROBE_5622, new WorldPoint(3087, 3261, 0), "Go to Aggie's house and search the wardrobe in northern wall."),
new CrypticClue("I have many arms but legs, I have just one. I have little family but my seed you can grow on, I am not dead, yet I am but a spirit, and my power, on your quests, you will earn the right to free it.", NULL_1293, new WorldPoint(2544, 3170, 0), "Spirit Tree in Tree Gnome Village. Answer: 13112221"),
new CrypticClue("I am the one who watches the giants. The giants in turn watch me. I watch with two while they watch with one. Come seek where I may be.", "Kamfreena", new WorldPoint(2845, 3539, 0), "Speak to Kamfreena on the top floor of the Warriors' Guild."),
new CrypticClue("In a town where wizards are known to gather, search upstairs in a large house to the north.", "Man", 375, new WorldPoint(2593, 3108, 1), "Search the chest upstairs in the house north of Yanille Wizard's Guild. Kill a man for the key."),
new CrypticClue("Probably filled with wizards socks.", "Wizard", DRAWERS_350, new WorldPoint(3116, 9562, 0), "Search the drawers in the basement of the Wizard's Tower south of Draynor Village. Kill one of the Wizards for the key. Fairy ring DIS"),
new CrypticClue("Even the seers say this clue goes right over their heads.", CRATE_14934, new WorldPoint(2707, 3488, 2), "Search the crate on the Seers Agility Course in Seers Village"),
new CrypticClue("Speak to a Wyse man.", "Wyson the gardener", new WorldPoint(3026, 3378, 0), "Talk to Wyson the gardener at Falador Park."),
new CrypticClue("You'll need to look for a town with a central fountain. Look for a locked chest in the town's chapel.", "Monk" , CLOSED_CHEST_5108, new WorldPoint(3256, 3487, 0), "Search the chest by the stairs in the Varrock church. Kill a Monk in Ardougne Monastery to obtain the key."),
new CrypticClue("Talk to Ambassador Spanfipple in the White Knights Castle.", "Ambassador Spanfipple", new WorldPoint(2979, 3340, 0), "Ambassador Spanfipple can be found roaming on the first floor of the White Knights Castle."),
new CrypticClue("Mine was the strangest birth under the sun. I left the crimson sack, yet life had not begun. Entered the world, and yet was seen by none.", new WorldPoint(2832, 9586, 0), "Inside Karamja Volcano, dig directly underneath the Red spiders' eggs respawn."),
new CrypticClue("Search for a crate in Varrock Castle.", CRATE_5113, new WorldPoint(3224, 3492, 0), "Search the crate in the corner of the kitchen in Varrock Castle."),
new CrypticClue("And so on, and so on, and so on. Walking from the land of many unimportant things leads to a choice of paths.", new WorldPoint(2591, 3879, 0), "Dig on Etceteria next to the Evergreen tree in front of the castle walls."),
new CrypticClue("Speak to Donovan, the Family Handyman.", "Donovan the Family Handyman", new WorldPoint(2743, 3578, 0), "Donovan the Family Handyman is found on the first floor of Sinclair Mansion."),
new CrypticClue("Search the crates in the Barbarian Village helmet shop.", CRATES_11600, new WorldPoint(3073, 3430, 0), "Peksa's Helmet Shop in Barbarian Village."),
new CrypticClue("Search the boxes of Falador's general store.", CRATES_24088, new WorldPoint(2955, 3390, 0), "Falador general store."),
new CrypticClue("In a village made of bamboo, look for some crates under one of the houses.", CRATE_356, new WorldPoint(2800, 3074, 0), "Search the crate by the house at the northern point of the broken jungle fence in Tai Bwo Wannai."),
new CrypticClue("This crate is mine, all mine, even if it is in the middle of the desert.", CRATE_18889, new WorldPoint(3289, 3022, 0), "Center of desert Mining Camp. Search the crates. Requires the metal key from Tourist Trap to enter."),
new CrypticClue("Dig where 4 siblings and I all live with our evil overlord.", new WorldPoint(3195, 3357, 0), "Dig in the chicken pen inside the Champions' Guild"),
new CrypticClue("In a town where the guards are armed with maces, search the upstairs rooms of the Public House.", "Guard dog", 348, new WorldPoint(2574, 3326, 1), "Search the drawers upstairs in the pub north of Ardougne Castle. Kill a Guard dog at Handelmort Mansion to obtain the key."),
new CrypticClue("Four blades I have, yet draw no blood; Still I turn my prey to powder. If you are brave, come search my roof; It is there my blades are louder.", CRATE_12963, new WorldPoint(3166, 3309, 2), "Lumbridge windmill, search the crates on the top floor."),
new CrypticClue("Search through some drawers in the upstairs of a house in Rimmington.", DRAWERS_352, new WorldPoint(2970, 3214, 1), "On the first floor of the house north of Hetty the Witch's house in Rimmington."),
new CrypticClue("Probably filled with books on magic.", BOOKCASE_380, new WorldPoint(3096, 9572, 0), "Search the bookcase in the basement of Wizard's Tower. Fairy ring DIS"),
new CrypticClue("If you look closely enough, it seems that the archers have lost more than their needles.", HAYSTACK, new WorldPoint(2672, 3416, 0), "Search the haystack by the south corner of the Rangers' Guild"),
new CrypticClue("Search the crate in the left-hand tower of Lumbridge Castle.", CRATE_357, new WorldPoint(3228, 3212, 1), "Located on the first floor of the southern tower at the Lumbridge Castle entrance."),
new CrypticClue("'Small shoe.' Often found with rod on mushroom.", "Gnome trainer", new WorldPoint(2476, 3428, 0), "Talk to any Gnome trainer in the agility area of the Tree Gnome Stronghold."),
new CrypticClue("I live in a deserted crack collecting soles.", "Genie", new WorldPoint(3371, 9320, 0), "Enter the crack west of Nardah Rug merchant, and talk to the Genie. You'll need a light source and a rope."),
new CrypticClue("46 is my number. My body is the colour of burnt orange and crawls among those with eight. Three mouths I have, yet I cannot eat. My blinking blue eye hides my grave.", new WorldPoint(3170, 3885, 0), "Sapphire respawn in the Spider's Nest, lvl 46 Wilderness. Dig under the sapphire spawn."),
new CrypticClue("Green is the colour of my death as the winter-guise, I swoop towards the ground.", new WorldPoint(2780, 3783, 0), "Players need to slide down to where Trollweiss grows on Trollweiss Mountain."),
new CrypticClue("Talk to a party-goer in Falador.", "Lucy", new WorldPoint(3046, 3382, 0), "Lucy is the bartender on the first floor of the party room."),
new CrypticClue("He knows just how easy it is to lose track of time.", "Brother Kojo", new WorldPoint(2570, 3250, 0), "Speak to brother Kojo in the Clock Tower. Answer: 22"),
new CrypticClue("A great view - watch the rapidly drying hides get splashed. Check the box you are sitting on.", BOXES, new WorldPoint(2523, 3493, 1), "Almera's House north of Baxtorian Falls, search boxes on the first floor."),
new CrypticClue("Search the Coffin in Edgeville.", COFFIN, new WorldPoint(3091, 3477, 0), "Search the coffin located by the Wilderness teleport lever."),
new CrypticClue("When no weapons are at hand, then is the time to reflect. In Saradomin's name, redemption draws closer...", DRAWERS_350, new WorldPoint(2818, 3351, 0), "On Entrana, search the southern drawer in the house with the cooking range."),
new CrypticClue("Search the crates in a house in Yanille that has a piano.", CRATE_357, new WorldPoint(2598, 3105, 0), "The house is located northwest of the bank."),
new CrypticClue("Speak to the staff of Sinclair mansion.", "Louisa", new WorldPoint(2736, 3578, 0), "Speak to Louisa, on the ground floor, found at the Sinclair Mansion. Fairy ring CJR"),
new CrypticClue("I am a token of the greatest love. I have no beginning or end. My eye is red, I can fit like a glove. Go to the place where it's money they lend, And dig by the gate to be my friend.", new WorldPoint(3191, 9825, 0), "Dig by the gate in the basement of the West Varrock bank."),
new CrypticClue("Speak to Kangai Mau.", "Kangai Mau", new WorldPoint(2791, 3183, 0), "Kangai Mau is found in the Shrimp and Parrot in Brimhaven."),
new CrypticClue("Speak to Hajedy.", "Hajedy", new WorldPoint(2779, 3211, 0), "Hajedy is found by the cart, located just south of the Brimhaven docks."),
new CrypticClue("Must be full of railings.", BOXES_6176, new WorldPoint(2576, 3464, 0), "Search the boxes around the hut where the broken Dwarf Cannon is, close to the start of the Dwarf Cannon quest."),
new CrypticClue("I wonder how many bronze swords he has handed out.", "Vannaka", new WorldPoint(3164, 9913, 0), "Talk to Vannaka. He can be found in Edgeville Dungeon."),
new CrypticClue("Read 'How to breed scorpions.' By O.W.Thathurt.", BOOKCASE_380, new WorldPoint(2703, 3409, 1), "Search the northern bookcase on the first floor of the Sorcerer's Tower."),
new CrypticClue("Search the crates in the Port Sarim Fishing shop.", CRATE_9534, new WorldPoint(3012, 3222, 0), "Search the crates, by the door, in Gerrant's Fishy Business in Port Sarim."),
new CrypticClue("Speak to The Lady of the Lake.", "The Lady of the Lake", new WorldPoint(2924, 3405, 0), "Talk to The Lady of the Lake in Taverley."),
new CrypticClue("Rotting next to a ditch. Dig next to the fish.", new WorldPoint(3547, 3183, 0), "Dig next to a fishing spot on the south-east side of Burgh de Rott."),
new CrypticClue("The King's magic won't be wasted by me.", "Guardian Mummy", new WorldPoint(1934, 4427, 0), "Talk to the Guardian mummy inside the Pyramid Plunder minigame in Sophanem"),
new CrypticClue("Dig where the forces of Zamorak and Saradomin collide.", new WorldPoint(3049, 4839, 0), "Dig next to the law rift in the Abyss"),
new CrypticClue("Search the boxes in the goblin house near Lumbridge.", BOXES, new WorldPoint(3245, 3245, 0), "Goblin house on the eastern side of the river."),
new CrypticClue("W marks the spot.", new WorldPoint(2867, 3546, 0), "Dig in the middle of the Warriors' Guild entrance hall"),
new CrypticClue("There is no 'worthier' lord.", "Lord Iorwerth", new WorldPoint(2205, 3252, 0), "Speak to Lord Iorwerth in the elven camp near Prifddinas"),
new CrypticClue("Surviving.", "Sir Vyvin", new WorldPoint(2983, 3338, 0), "Talk to Sir Vyvin on the second floor of Falador castle."),
new CrypticClue("My name is like a tree, yet it is spelt with a 'g'. Come see the fur which is right near me.", "Wilough", new WorldPoint(3221, 3435, 0), "Speak to Wilough, next to the Fur Merchant in Varrock Square."),
new CrypticClue("Speak to Jatix in Taverley.", "Jatix", new WorldPoint(2898, 3428, 0), "Jatix is found in the middle of Taverley."),
new CrypticClue("Speak to Gaius in Taverley.", "Gaius", new WorldPoint(2884, 3450, 0), "Gaius is found at the northwest corner in Taverley."),
new CrypticClue("If a man carried my burden, he would break his back. I am not rich, but leave silver in my track. Speak to the keeper of my trail.", "Gerrant", new WorldPoint(3014, 3222, 0), "Speak to Gerrant in the fish shop in Port Sarim."),
new CrypticClue("Search the drawers in Falador's chain mail shop.", DRAWERS, new WorldPoint(2969, 3311, 0), "Wayne's Chains - Chainmail Specialist store at the southern Falador walls."),
new CrypticClue("Talk to the barber in the Falador barber shop.", "Hairdresser", new WorldPoint(2945, 3379, 0), "The Hairdresser can be found in the barber shop, north of the west Falador bank."),
new CrypticClue("Often sought out by scholars of histories past, find me where words of wisdom speak volumes.", "Examiner", new WorldPoint(3362, 3341, 0), "Speak to an examiner at the Exam Centre."),
new CrypticClue("Generally speaking, his nose was very bent.", "General Bentnoze", new WorldPoint(2957, 3511, 0), "Talk to General Bentnoze"),
new CrypticClue("Search the bush at the digsite centre.", BUSH_2357, new WorldPoint(3345, 3378, 0), "The bush is on the east side of the first pathway towards the digsite from the Exam Centre."),
new CrypticClue("Someone watching the fights in the Duel Arena is your next destination.", "Jeed", new WorldPoint(3360, 3242, 0), "Talk to Jeed, found on the upper floors, at the Duel Arena."),
new CrypticClue("It seems to have reached the end of the line, and it's still empty.", MINE_CART_6045, new WorldPoint(3041, 9820, 0), "Search the carts in the northern part of the Dwarven Mine."),
new CrypticClue("You'll have to plug your nose if you use this source of herbs.", null, "Kill an Aberrant spectre."),
new CrypticClue("When you get tired of fighting, go deep, deep down until you need an antidote.", CRATE_357, new WorldPoint(2576, 9583, 0), "Go to Yanille Agility dungeon and fall into the place with the poison spiders. Search the crate by the stairs leading up."),
new CrypticClue("Search the bookcase in the monastery.", BOOKCASE_380, new WorldPoint(3054, 3484, 0), "Search the southeastern bookcase at Edgeville Monastery."),
new CrypticClue("Surprising? I bet he is...", "Sir Prysin", new WorldPoint(3205, 3474, 0), "Talk to Sir Prysin in Varrock Palace."),
new CrypticClue("Search upstairs in the houses of Seers' Village for some drawers.", DRAWERS_25766, new WorldPoint(2716, 3471, 1), "Located in the house with the spinning wheel. South of the Seers' Village bank."),
new CrypticClue("Leader of the Yak City.", "Mawnis Burowgar", new WorldPoint(2336, 3799, 0), "Talk to Mawnis Burowgar in Neitiznot."),
new CrypticClue("Speak to Arhein in Catherby.", "Arhein", new WorldPoint(2803, 3430, 0), "Arhein is just south of the Catherby bank."),
new CrypticClue("Speak to Doric, who lives north of Falador.", "Doric", new WorldPoint(2951, 3451, 0), "Doric is found north of Falador and east of the Taverley gate."),
new CrypticClue("Between where the best are commemorated for a year, and a celebratory cup, not just for beer.", new WorldPoint(3388, 3152, 0), "Dig at the Clan Cup Trophy at Clan Wars."),
new CrypticClue("'See you in your dreams' said the vegetable man.", "Dominic Onion", new WorldPoint(2608, 3116, 0), "Speak to Dominic Onion at the Nightmare Zone teleport spot."),
new CrypticClue("Try not to step on any aquatic nasties while searching this crate.", CRATE_18204, new WorldPoint(2764, 3273, 0), "Search the crate in Bailey's house on the Fishing Platform."),
new CrypticClue("The cheapest water for miles around, but they react badly to religious icons.", CRATE_354, new WorldPoint(3178, 2987, 0), "Search the crates in the General Store tent in the Bandit Camp"),
new CrypticClue("This village has a problem with cartloads of the undead. Try checking the bookcase to find an answer.", BOOKCASE_394, new WorldPoint(2833, 2992, 0), "Search the bookcase by the doorway of the building just south east of the Shilo Village Gem Mine."),
new CrypticClue("Dobson is my last name, and with gardening I seek fame.", "Horacio", new WorldPoint(2635, 3310, 0), "Horacio, located in the garden of the Handelmort Mansion in East Ardougne."),
new CrypticClue("The magic of 4 colours, an early experience you could learn. The large beast caged up top, rages, as his demised kin's loot now returns.", "Wizard Mizgog", new WorldPoint(3103, 3163, 2), "Speak to Wizard Mizgog at the top of the Wizard's Tower south of Draynor."),
new CrypticClue("Aggie I see. Lonely and southern I feel. I am neither inside nor outside the house, yet no home would be complete without me. The treasure lies beneath me!", new WorldPoint(3085, 3255, 0), "Dig outside the window of Aggie's house in Draynor Village."),
new CrypticClue("Search the chest in Barbarian Village.", CLOSED_CHEST_375, new WorldPoint(3085, 3429, 0), "The chest located in the house with a spinning wheel."),
new CrypticClue("Search the crates in the outhouse of the long building in Taverley.", CRATE_357, new WorldPoint(2914, 3433, 0), "Located in the small building attached by a fence to the main building. Climb over the stile."),
new CrypticClue("Talk to Ermin.", "Ermin", new WorldPoint(2488, 3409, 1), "Ermin can be found on the first floor of the tree house south-east of the Gnome Agility Course."),
new CrypticClue("Ghostly bones.", null, "Kill an Ankou."),
new CrypticClue("Search through chests found in the upstairs of houses in eastern Falador.", CLOSED_CHEST_375, new WorldPoint(3041, 3364, 1), "The house is located southwest of the Falador Party Room. There are two chests in the room, search the northern chest."),
new CrypticClue("Let's hope you don't meet a watery death when you encounter this fiend.", null, "Kill a waterfiend."),
new CrypticClue("Reflection is the weakness for these eyes of evil.", null, "Kill a basilisk."),
new CrypticClue("Search a bookcase in Lumbridge swamp.", BOOKCASE_9523, new WorldPoint(3146, 3177, 0), "Located in Father Urhney's house."),
new CrypticClue("Surround my bones in fire, ontop the wooden pyre. Finally lay me to rest, before my one last test.", null, "Kill a confused/lost barbarian to receive mangled bones. Construct and burn a pyre ship. Kill the ferocious barbarian spirit that spawns to receive a clue casket."),
new CrypticClue("Fiendish cooks probably won't dig the dirty dishes.", new WorldPoint(3043, 4974, 1), "Dig by the fire in the Rogues' Den."),
new CrypticClue("My life was spared but these voices remain, now guarding these iron gates is my bane.", "Key Master", new WorldPoint(1310, 1251, 0), "Speak to the Key Master in Cerberus' Lair."),
new CrypticClue("Search the boxes in one of the tents in Al Kharid.", BOXES_361, new WorldPoint(3308, 3206, 0), "Search the boxes in the tent east of the Silk trader."),
new CrypticClue("One of several rhyming brothers, in business attire with an obsession for paper work.", "Piles", new WorldPoint(3186, 3936, 0), "Speak to Piles in the Wilderness Resource Area. An entry fee of 7,500 coins is required, or less if Wilderness Diaries have been completed."),
new CrypticClue("Search the drawers on the first floor of a building overlooking Ardougne's Market.", DRAWERS_352, new WorldPoint(2657, 3322, 1), "Climb the ladder in the house north of the market."),
new CrypticClue("'A bag belt only?', he asked his balding brothers.", "Abbot Langley", new WorldPoint(3058, 3487, 0), "Talk-to Abbot Langley in Monastery west of Edgeville"),
new CrypticClue("Search the drawers upstairs in Falador's shield shop.", DRAWERS, new WorldPoint(2971, 3386, 1), "Cassie's Shield Shop at the northern Falador entrance."),
new CrypticClue("Go to this building to be illuminated, and check the drawers while you are there.", "Market Guard", DRAWERS_350 , new WorldPoint(2512, 3641, 1), "Search the drawers in the first floor of the Lighthouse. Kill a Rellekka marketplace guard to obtain the key."),
new CrypticClue("Dig near some giant mushrooms, behind the Grand Tree.", new WorldPoint(2458, 3504, 0), "Dig near the red mushrooms northwest of the Grand Tree."),
new CrypticClue("Pentagrams and demons, burnt bones and remains, I wonder what the blood contains.", new WorldPoint(3297, 3890, 0), "Dig under the blood rune spawn next the the Demonic Ruins."),
new CrypticClue("Search the drawers above Varrock's shops.", DRAWERS_7194, new WorldPoint(3206, 3419, 1), "Located upstairs in Thessalia's Fine Clothes shop in Varrock."),
new CrypticClue("Search the drawers in one of Gertrude's bedrooms.", DRAWERS_7194, new WorldPoint(3156, 3406, 0), "Kanel's bedroom (southeastern room), outside of west Varrock."),
new CrypticClue("Under a giant robotic bird that cannot fly.", new WorldPoint(1756, 4940, 0), "Dig next to the terrorbird display in the south exhibit of Varrock Museum's basement."),
new CrypticClue("Great demons, dragons and spiders protect this blue rock, beneath which, you may find what you seek.", new WorldPoint(3045, 10265, 0), "Dig by the runite rock in the Lava Maze Dungeon"),
new CrypticClue("My giant guardians below the market streets would be fans of rock and roll, if only they could grab hold of it. Dig near my green bubbles!", new WorldPoint(3161, 9904, 0), "Dig near the cauldron by Moss Giants under Varrock Sewers"),
new CrypticClue("Varrock is where I reside, not the land of the dead, but I am so old, I should be there instead. Let's hope your reward is as good as it says, just 1 gold one and you can have it read.", "Gypsy Aris", new WorldPoint(3203, 3424, 0), "Talk to Gypsy Aris, West of varrock main square."),
new CrypticClue("Speak to a referee.", "Gnome ball referee", new WorldPoint(2386, 3487, 0), "Talk to a Gnome ball referee found on the Gnome ball field in the Gnome Stronghold. Answer: 5096"),
new CrypticClue("This crate holds a better reward than a broken arrow.", CRATE_356, new WorldPoint(2671, 3437, 0), "Inside the Ranging Guild. Search the crate behind the northern most building."),
new CrypticClue("Search the drawers in the house next to the Port Sarim mage shop.", DRAWERS, new WorldPoint(3024, 3259, 0), "House east of Betty's. Contains a cooking sink."),
new CrypticClue("With a name like that, you'd expect a little more than just a few scimitars.", "Daga", new WorldPoint(2759, 2775, 0), "Speak to Daga on Ape Atoll."),
new CrypticClue("Strength potions with red spiders' eggs? He is quite a herbalist.", "Apothecary", new WorldPoint(3194, 3403, 0), "Talk to Apothecary in the South-western Varrock. (the) apothecary is just north-west of the Varrock Swordshop."),
new CrypticClue("Robin wishes to see your finest ranged equipment.", "Robin", new WorldPoint(3673, 3492, 0), "Robin at the inn in Port Phasmatys. Speak to him with +182 in ranged attack bonus."),
new CrypticClue("You will need to under-cook to solve this one.", CRATE_357, new WorldPoint(3219, 9617, 0), "Search the crate in the Lumbridge basement."),
new CrypticClue("Search through some drawers found in Taverley's houses.", DRAWERS_350, new WorldPoint(2894, 3418, 0), "The south-eastern most house, south of Jatix's Herblore Shop."),
new CrypticClue("Anger Abbot Langley.", "Abbot Langley", new WorldPoint(3058, 3487, 0), "Speak to Abbot Langley in the Edgeville Monastery while you have a negative prayer bonus (currently only possible with an Ancient staff)."),
new CrypticClue("Dig where only the skilled, the wealthy, or the brave can choose not to visit again.", new WorldPoint(3221, 3219, 0), "Dig at Lumbridge spawn"),
new CrypticClue("Scattered coins and gems fill the floor. The chest you seek is in the north east.", "King Black Dragon", CLOSED_CHEST_375, new WorldPoint(2288, 4702, 0), "Kill the King Black Dragon for a key (elite), and then open the closed chest in the NE corner of the lair."),
new CrypticClue("A ring of water surrounds 4 powerful rings, dig above the ladder located there.", new WorldPoint(1910, 4367, 0), "Dig by the ladder leading to the Dagannoth Kings room in the Waterbirth Island Dungeon."),
new CrypticClue("This place sure is a mess.", "Ewesey", new WorldPoint(1646, 3631, 0), "Ewesey is located in the mess hall in Hosidius."),
new CrypticClue("Here, there are tears, but nobody is crying. Speak to the guardian and show off your alignment to balance.", "Juna", JUNA, new WorldPoint(3252, 9517, 2), "Talk to Juna while wearing three Guthix related items."),
new CrypticClue("You might have to turn over a few stones to progress.", null, "Kill a rock crab."),
new CrypticClue("Dig under Razorlor's toad batta.", new WorldPoint(3139, 4554, 0), "Dig on the toad batta spawn in Tarn's Lair."),
new CrypticClue("Talk to Cassie in Falador.", "Cassie", new WorldPoint(2975, 3383, 0), "Cassie is found just south-east of the northern Falador gate."),
new CrypticClue("Faint sounds of 'Arr', fire giants found deep, the eastern tip of a lake, are the rewards you could reap.", new WorldPoint(3055, 10338, 0), "Dig south of the pillar at the end of the Deep Wilderness Dungeon."),
new CrypticClue("If you're feeling brave, dig beneath the dragon's eye.", new WorldPoint(2410, 4714, 0), "Dig below the mossy rock under the Viyeldi caves (Legend's Quest). Items needed: Pickaxe, unpowered orb, lockpick, spade, and any charge orb spell."),
new CrypticClue("Search the tents in the Imperial Guard camp in Burthorpe for some boxes.", BOXES_3686, new WorldPoint(2885, 3540, 0), "Search in the tents in northwest corner of the camp."),
new CrypticClue("A dwarf, approaching death, but very much in the light.", "Thorgel", new WorldPoint(1863, 4639, 0), "Thorgel at the entrance to the Death altar"),
new CrypticClue("You must be 100 to play with me.", "Squire (Veteran)", new WorldPoint(2638, 2656, 0), "Speak to the Veteran boat squire at Pest Control"),
new CrypticClue("Three rule below and three sit at top. Come dig at my entrance.", new WorldPoint(2523, 3739, 0), "Dig in front of the entrance to the Waterbirth Island Dungeon."),
new CrypticClue("Search the drawers in the ground floor of a shop in Yanille.", DRAWERS_350, new WorldPoint(2570, 3085, 0), "Search the drawers in Yanille's hunting shop."),
new CrypticClue("Search the drawers of houses in Burthorpe.", DRAWERS, new WorldPoint(2929, 3570, 0), "Inside Hild's house in the northeast corner of Burthorpe."),
new CrypticClue("Where safe to speak, the man who offers the pouch of smallest size wishes to see your alignment.", "Mage of Zamorak", new WorldPoint(3260, 3385, 0), "Speak to the Mage of Zamorak south of the Rune Shop in Varrock while wearing three zamorakian items"),
new CrypticClue("Search the crates in the guard house of the northern gate of East Ardougne.", CRATE_356, new WorldPoint(2645, 3338, 0), "The guard house is northeast of the Handelmort Mansion."),
new CrypticClue("Go to the village being attacked by trolls, search the drawers in one of the houses.", "Penda", DRAWERS_350, new WorldPoint(2921, 3577, 0), "Go to Dunstan's house in the northeast corner of Burthorpe. Kill Penda in the Toad and Chicken to obtain the key."),
new CrypticClue("You'll get licked.", null, "Kill a Bloodveld."),
new CrypticClue("She's small but can build both literally and figuratively, as long as you have their favour.", "Lovada", new WorldPoint(1486, 3834, 0), "Speak to Lovada by the entrance to the blast mine in Lovakengj."),
new CrypticClue("Dig in front of the icy arena where 1 of 4 was fought.", new WorldPoint(2874, 3757, 0), "Where you fought Kamil from Desert Treasure."),
new CrypticClue("Speak to Roavar.", "Roavar", new WorldPoint(3494, 3474, 0), "Talk to Roavar in the Canifis tavern."),
new CrypticClue("Search the drawers upstairs of houses in the eastern part of Falador.", DRAWERS_350, new WorldPoint(3035, 3347, 1), "House is located east of the eastern Falador bank and south of the fountain. The house is indicated by the icon on the minimap."),
new CrypticClue("Search the drawers found upstairs in East Ardougne's houses.", DRAWERS, new WorldPoint(2574, 3326, 1), "Upstairs of the pub north of the Ardougne Castle."),
new CrypticClue("The far north eastern corner where 1 of 4 was defeated, the shadows still linger.", new WorldPoint(2744, 5116, 0), "Dig on the northeastern-most corner of the Shadow Dungeon. Bring a ring of visibility."),
new CrypticClue("Search the drawers in a house in Draynor Village.", DRAWERS_350, new WorldPoint(3097, 3277, 0), "The drawer is located in the northernmost house in Draynor Village."),
new CrypticClue("Search the boxes in a shop in Taverley.", BOXES_360, new WorldPoint(2886, 3449, 0), "The box inside Gaius' Two Handed Shop."),
new CrypticClue("I lie beneath the first descent to the holy encampment.", new WorldPoint(2914, 5300, 1), "Dig immediately after climbing down the first set of rocks towards Saradomin's encampment within the God Wars Dungeon."),
new CrypticClue("Search the upstairs drawers of a house in a village where pirates are known to have a good time.", "Pirate", 348, new WorldPoint(2809, 3165, 1), "The house in the southeast corner of Brimhaven, northeast of Davon's Amulet Store. Kill any Pirate located around Brimhaven to obtain the key."),
new CrypticClue("Search the chest in the Duke of Lumbridge's bedroom.", CLOSED_CHEST_375, new WorldPoint(3209, 3218, 1), "The Duke's room is on the first floor in Lumbridge Castle."),
new CrypticClue("Talk to the Doomsayer.", "Doomsayer", new WorldPoint(3232, 3228, 0), "Doomsayer can be found just north of Lumbridge Castle entrance."),
new CrypticClue("Search the chests upstairs in Al Kharid Palace.", CLOSED_CHEST_375, new WorldPoint(3301, 3169, 1), "The chest is located, in the northeast corner, on the first floor of the Al Kharid Palace"),
new CrypticClue("Search the boxes just outside the Armour shop in East Ardougne.", BOXES_361, new WorldPoint(2654, 3299, 0), "Outside Zenesha's Plate Mail Body Shop"),
new CrypticClue("Surrounded by white walls and gems.", "Herquin", new WorldPoint(2945, 3335, 0), "Talk to Herquin, the gem store owner in Falador."),
new CrypticClue("Monk's residence in the far west. See robe storage device.", DRAWERS_350, new WorldPoint(1742, 3490, 1), "Search the drawers upstairs in the chapel found on the southern coast of Hosidius, directly south of the player-owned house portal."),
new CrypticClue("Search the drawers in Catherby's Archery shop.", DRAWERS_350, new WorldPoint(2825, 3442, 0), "Hickton's Archery Emporium in Catherby."),
new CrypticClue("The hand ain't listening.", "The Face", new WorldPoint(3019, 3232, 0), "Talk to The Face located by the manhole just north of the Port Sarim fishing shop."),
new CrypticClue("Search the chest in the left-hand tower of Camelot Castle.", CLOSED_CHEST_25592, new WorldPoint(2748, 3495, 2), "Located on the second floor of the western tower of Camelot."),
new CrypticClue("Kill the spiritual, magic and godly whilst representing their own god.", null, "Kill a spiritual mage while wearing a corresponding god item."),
new CrypticClue("Anger those who adhere to Saradomin's edicts to prevent travel.", "Monk of Entrana", new WorldPoint(3042, 3236, 0), "Port Sarim Docks, try to charter a ship to Entrana with armour or weapons equipped."),
new CrypticClue("South of a river in a town surrounded by the undead, what lies beneath the furnace?", new WorldPoint(2857, 2966, 0), "Dig in front of the Shilo Village furnace."),
new CrypticClue("Talk to the Squire in the White Knights' castle in Falador.", "Squire", new WorldPoint(2977, 3343, 0), "The squire is located in the courtyard of the White Knights' Castle."),
new CrypticClue("Thanks, Grandma!", "Tynan", new WorldPoint(1836, 3786, 0), "Tynan can be found in the north-east corner of Port Piscarilius."),
new CrypticClue("In a town where everyone has perfect vision, seek some locked drawers in a house that sits opposite a workshop.", "Chicken", DRAWERS_25766, new WorldPoint(2709, 3478, 0), "The Seers' Village house south of the Elemental Workshop entrance. Kill any Chicken to obtain a key."),
new CrypticClue("The treasure is buried in a small building full of bones. Here is a hint: it's not near a graveyard.", new WorldPoint(3356, 3507, 0), "In the western building near the Limestone quarry east of Varrock. Dig south of the box of bones in the smaller building."),
new CrypticClue("Search the crates in East Ardougne's general store.", CRATE_357, new WorldPoint(2615, 3291, 0), "Located south of the Ardounge church."),
new CrypticClue("Come brave adventurer, your sense is on fire. If you talk to me, it's an old god you desire.", "Viggora", null, "Speak to Viggora"),
new CrypticClue("2 musical birds. Dig in front of the spinning light.", new WorldPoint(2671, 10396, 0), "Dig in front of the spinning light in Ping and Pong's room inside the Iceberg"),
new CrypticClue("Search the wheelbarrow in Rimmington mine.", WHEELBARROW_9625, new WorldPoint(2978, 3239, 0), "The Rimmington mining site is located north of Rimmington."),
new CrypticClue("Belladonna, my dear. If only I had gloves, then I could hold you at last.", "Tool Leprechaun", new WorldPoint(3088, 3357, 0), "Talk to Tool Leprechaun at Draynor Manor"),
new CrypticClue("Impossible to make angry", "Abbot Langley", new WorldPoint(3059, 3486, 0), "Speak to Abbot Langley at the Edgeville Monastery."),
new CrypticClue("Search the crates in Horvik's armoury.", CRATE_5106, new WorldPoint(3228, 3433, 0), "Horvik's in Varrock"),
new CrypticClue("Ghommal wishes to be impressed by how strong your equipment is.", "Ghommal", new WorldPoint(2878, 3546, 0), "Speak to Ghommal at the Warriors' Guild with a total Melee Strength bonus of over 100."),
new CrypticClue("Shhhh!", "Logosia", new WorldPoint(1633, 3808, 0), "Speak to Logosia in the Arceuus Library's ground floor."),
new CrypticClue("Salty peter.", "Konoo", new WorldPoint(1703, 3524, 0), "Talk to Konoo who is digging saltpetre in Hosidius, south of the bank."),
new CrypticClue("Talk to Zeke in Al Kharid.", "Zeke", new WorldPoint(3287, 3190, 0), "Zeke is the owner of the scimitar shop in Al Kharid."),
new CrypticClue("Guthix left his mark in a fiery lake, dig at the tip of it.", new WorldPoint(3069, 3935, 0), "Dig at the tip of the lava lake that is shaped like a Guthixian symbol, west of the Mage Arena."),
new CrypticClue("Search the drawers in the upstairs of a house in Catherby.", DRAWERS_350, new WorldPoint(2809, 3451, 1), "Perdu's house in Catherby."),
new CrypticClue("Search a crate in the Haymaker's arms.", CRATE_27532, new WorldPoint(1720, 3652, 1), "Search the crate in the north-east corner of The Haymaker's Arms tavern east of Kourend Castle."),
new CrypticClue("Desert insects is what I see. Taking care of them was my responsibility. Your solution is found by digging near me.", new WorldPoint(3307, 9505, 0), "Dig next to the Entomologist, Kalphite area, near Shantay Pass."),
new CrypticClue("Search the crates in the most north-western house in Al Kharid.", CRATE_358, new WorldPoint(3289, 3202, 0), "Search the crates in the house, marked with a icon, southeast of the gem stall."),
new CrypticClue("You will have to fly high where a sword cannot help you.", null, "Kill an Aviansie."),
new CrypticClue("A massive battle rages beneath so be careful when you dig by the large broken crossbow.", new WorldPoint(2927, 3761, 0), "NE of the God Wars Dungeon entrance, climb the rocky handholds & dig by large crossbow."),
new CrypticClue("Mix yellow with blue and add heat, make sure you bring protection.", null, "Kill a green dragon."),
new CrypticClue("Speak to Ellis in Al Kharid.", "Ellis", new WorldPoint(3276, 3191, 0), "Ellis is tanner just north of Al Kharid bank."),
new CrypticClue("Search the chests in the Dwarven Mine.", CLOSED_CHEST_375, new WorldPoint(3000, 9798, 0), "The chest is on the western wall, where Hura's Crossbow Shop is, in the Dwarven Mine."),
new CrypticClue("In a while...", null, "Kill a crocodile."),
new CrypticClue("A chisel and hammer reside in his home, strange for one of magic. Impress him with your magical equipment.", "Wizard Cromperty", new WorldPoint(2682, 3325, 0), "Wizard Cromperty, NE corner of East Ardougne. +100 magic attack bonus needed"),
new CrypticClue("You have all of the elements available to solve this clue. Fortunately you do not have to go as far as to stand in a draft.", CRATE_18506, new WorldPoint(2723, 9891, 0), "Search the crate, west of the Air Elementals, inside the Elemental Workshop."),
new CrypticClue("A demon's best friend holds the next step of this clue.", null, "Kill a hellhound."),
new CrypticClue("Dig in the centre of a great kingdom of 5 cities.", new WorldPoint(1639, 3673, 0), "Dig in front of the large statue in the centre of Great Kourend."),
new CrypticClue("Hopefully this set of armour will help you to keep surviving.", "Sir Vyvin", new WorldPoint(2982, 3336, 2), "Speak to Sir Vyvin while wearing a white platebody, and platelegs."),
new CrypticClue("The beasts retreat, for their Queen is gone; the song of this town still plays on. Dig near the birthplace of a blade, be careful not to melt your spade.", new WorldPoint(2342, 3677, 0), "Dig in front of the small furnace in the Piscatoris Fishing Colony."),
new CrypticClue("Darkness wanders around me, but fills my mind with knowledge.", "Biblia", new WorldPoint(1633, 3825, 2), "Speak to Biblia on the Arceuus Library's top floor."),
new CrypticClue("I would make a chemistry joke, but I'm afraid I wouldn't get a reaction.", "Chemist", new WorldPoint(2932, 3212, 0), "Talk to the Chemist in Rimmington"),
new CrypticClue("Show this to Hazelmere.", "Hazelmere", new WorldPoint(2677, 3088, 1), "Hazelmere is found upstairs on the island located just east of Yanille."),
new CrypticClue("Does one really need a fire to stay warm here?", new WorldPoint(3816, 3810, 0), "Dig next to the fire near the Volcanic Mine entrance."),
new CrypticClue("Search the open crate found in the Hosidius kitchens.", CRATE_27533, new WorldPoint(1683, 3616, 0), "The kitchens are north-west of the town in Hosidius."),
new CrypticClue("Dig under Ithoi's cabin.", new WorldPoint(2529, 2838, 0), "Dig under Ithoi's cabin in the Corsair Cove."),
new CrypticClue("Search the drawers, upstairs in the bank to the East of Varrock.", DRAWERS_7194, new WorldPoint(3250, 3420, 1), "Search the drawers upstairs in Varrock east bank."),
new CrypticClue("Speak to Hazelmere.", "Hazelmere", new WorldPoint(2677, 3088, 1), "Located upstairs in the house to the north of fairy ring CLS. Answer: 6859"),
new CrypticClue("The effects of this fire are magnified.", new WorldPoint(1179, 3626, 0), "Dig by the fire beside Ket'sal K'uk in the westernmost part of the Kebos Swamp. "),
new CrypticClue("Always walking around the castle grounds and somehow knows everyone's age.", "Hans", new WorldPoint(3221, 3218, 0), "Talk to Hans walking around Lumbridge Castle."),
new CrypticClue("In the place Duke Horacio calls home, talk to a man with a hat dropped by goblins.", "Cook", new WorldPoint(3208, 3213, 0), "Talk to the Cook in Lumbridge Castle."),
new CrypticClue("In a village of barbarians, I am the one who guards the village from up high.", "Hunding", new WorldPoint(3097, 3432, 2), "Talk to Hunding atop the tower on the east side of Barbarian Village."),
new CrypticClue("Talk to Charlie the Tramp in Varrock.", "Charlie the Tramp", new WorldPoint(3209, 3390, 0), "Talk to Charlie the Tramp by the southern entrance to Varrock. He will give you a task."),
new CrypticClue("Near the open desert I reside, to get past me you must abide. Go forward if you dare, for when you pass me, you'll be sweating by your hair.", "Shantay", new WorldPoint(3303, 3123, 0), "Talk to Shantay at the Shantay Pass south of Al Kharid."),
new CrypticClue("Search the chest in Fred the Farmer's bedroom.", CLOSED_CHEST_375, new WorldPoint(3185, 3274, 0), "Search the chest by Fred the Farmer's bed in his house north-west of Lumbridge."),
new CrypticClue("Search the eastern bookcase in Father Urhney's house.", BOOKCASE_9523, new WorldPoint(3149, 3177, 0), "Father Urhney's house is found in the western end of the Lumbridge Swamp."),
new CrypticClue("Talk to Morgan in his house at Draynor Village.", "Morgan", new WorldPoint(3098, 3268, 0), "Morgan can be found in the house with the quest start map icon."),
new CrypticClue("Talk to Charles at Port Piscarilius.", "Charles", new WorldPoint(1821, 3690, 0), "Charles is found by Veos' ship in Port Piscarilius."),
new CrypticClue("Search the crate in Rommiks crafting shop in Rimmington.", CRATE_9534, new WorldPoint(2947, 3206, 0), "The crates in Rommik's Crafty Supplies in Rimmington."),
new CrypticClue("Talk to Ali the Leaflet Dropper north of the Al Kharid mine.", "Ali the Leaflet Dropper", new WorldPoint(3283, 3329, 0), "Ali the Leaflet Dropper can be found roaming north of the Al Kharid mine."),
new CrypticClue("Talk to the cook in the Blue Moon Inn in Varrock.", "Cook", new WorldPoint(3230, 3401, 0), "The Blue Moon Inn can be found by the southern entrance to Varrock."),
new CrypticClue("Search the single crate in Horvik's smithy in Varrock.", CRATE_5106, new WorldPoint(3228, 3433, 0), "Horvik's Smithy is found north-east of of Varrock Square."),
new CrypticClue("Search the crates in Falador General store.", CRATES_24088, new WorldPoint(2955, 3390, 0), "The Falador General Store can be found by the northern entrance to the city."),
new CrypticClue("Talk to Wayne at Wayne's Chains in Falador.", "Wayne", new WorldPoint(2972, 3312, 0), "Wayne's shop is found directly south of the White Knights' Castle."),
new CrypticClue("Search the boxes next to a chest that needs a crystal key.", BOXES_360, new WorldPoint(2915, 3452, 0), "The Crystal chest can be found in the house directly south of the Witch's house in Taverley."),
new CrypticClue("Talk to Turael in Burthorpe.", "Turael", new WorldPoint(2930, 3536, 0), "Turael is located in the small house east of the Toad and Chicken inn."),
new CrypticClue("More resources than I can handle, but in a very dangerous area. Can't wait to strike gold!", new WorldPoint(3183, 3941, 0), "Dig between the three gold ores in the Wilderness Resource Area."),
new CrypticClue("Observing someone in a swamp, under the telescope lies treasure.", new WorldPoint(2221, 3091, 0), "Dig next to the telescope on Broken Handz's island in the poison wastes. (Accessible only through fairy ring DLR)")
);
private final String text;
private final String npc;
private final int objectId;
private final WorldPoint location;
private final String solution;
private CrypticClue(String text, WorldPoint location, String solution)
{
this(text, null, -1, location, solution);
}
private CrypticClue(String text, int objectId, WorldPoint location, String solution)
{
this(text, null, objectId, location, solution);
}
private CrypticClue(String text, String npc, WorldPoint location, String solution)
{
this(text, npc, -1, location, solution);
}
private CrypticClue(String text, String npc, int objectId, WorldPoint location, String solution)
{
this.text = text;
this.npc = npc;
this.objectId = objectId;
this.location = location;
this.solution = solution;
setRequiresSpade(getLocation() != null && getNpc() == null && objectId == -1);
}
@Override
public void makeOverlayHint(PanelComponent panelComponent, ClueScrollPlugin plugin)
{
panelComponent.getChildren().add(TitleComponent.builder().text("Cryptic Clue").build());
if (getNpc() != null)
{
panelComponent.getChildren().add(LineComponent.builder().left("NPC:").build());
panelComponent.getChildren().add(LineComponent.builder()
.left(getNpc())
.leftColor(TITLED_CONTENT_COLOR)
.build());
}
if (objectId != -1)
{
ObjectComposition object = plugin.getClient().getObjectDefinition(objectId);
if (object != null && object.getImpostorIds() != null)
{
object = object.getImpostor();
}
if (object != null)
{
panelComponent.getChildren().add(LineComponent.builder().left("Object:").build());
panelComponent.getChildren().add(LineComponent.builder()
.left(object.getName())
.leftColor(TITLED_CONTENT_COLOR)
.build());
}
}
panelComponent.getChildren().add(LineComponent.builder().left("Solution:").build());
panelComponent.getChildren().add(LineComponent.builder()
.left(getSolution())
.leftColor(TITLED_CONTENT_COLOR)
.build());
}
@Override
public void makeWorldOverlayHint(Graphics2D graphics, ClueScrollPlugin plugin)
{
// Mark dig location
if (getLocation() != null && getNpc() == null && objectId == -1)
{
LocalPoint localLocation = LocalPoint.fromWorld(plugin.getClient(), getLocation());
if (localLocation != null)
{
OverlayUtil.renderTileOverlay(plugin.getClient(), graphics, localLocation, plugin.getSpadeImage(), Color.ORANGE);
}
}
// Mark NPC
if (plugin.getNpcsToMark() != null)
{
for (NPC npc : plugin.getNpcsToMark())
{
OverlayUtil.renderActorOverlayImage(graphics, npc, plugin.getClueScrollImage(), Color.ORANGE, IMAGE_Z_OFFSET);
}
}
// Mark game object
if (objectId != -1)
{
net.runelite.api.Point mousePosition = plugin.getClient().getMouseCanvasPosition();
if (plugin.getObjectsToMark() != null)
{
for (TileObject gameObject : plugin.getObjectsToMark())
{
OverlayUtil.renderHoverableArea(graphics, gameObject.getClickbox(), mousePosition,
CLICKBOX_FILL_COLOR, CLICKBOX_BORDER_COLOR, CLICKBOX_HOVER_BORDER_COLOR);
OverlayUtil.renderImageLocation(plugin.getClient(), graphics, gameObject.getLocalLocation(), plugin.getClueScrollImage(), IMAGE_Z_OFFSET);
}
}
}
}
public static CrypticClue forText(String text)
{
for (CrypticClue clue : CLUES)
{
if (clue.text.equalsIgnoreCase(text))
{
return clue;
}
}
return null;
}
@Override
public int[] getObjectIds()
{
return new int[] {objectId};
}
@Override
public String[] getNpcs()
{
return new String[] {npc};
}
}
| Properly capitalize 'Brother Kojo' in Watchtower clue scroll (#9297)
| runelite-client/src/main/java/net/runelite/client/plugins/cluescrolls/clues/CrypticClue.java | Properly capitalize 'Brother Kojo' in Watchtower clue scroll (#9297) | <ide><path>unelite-client/src/main/java/net/runelite/client/plugins/cluescrolls/clues/CrypticClue.java
<ide> new CrypticClue("46 is my number. My body is the colour of burnt orange and crawls among those with eight. Three mouths I have, yet I cannot eat. My blinking blue eye hides my grave.", new WorldPoint(3170, 3885, 0), "Sapphire respawn in the Spider's Nest, lvl 46 Wilderness. Dig under the sapphire spawn."),
<ide> new CrypticClue("Green is the colour of my death as the winter-guise, I swoop towards the ground.", new WorldPoint(2780, 3783, 0), "Players need to slide down to where Trollweiss grows on Trollweiss Mountain."),
<ide> new CrypticClue("Talk to a party-goer in Falador.", "Lucy", new WorldPoint(3046, 3382, 0), "Lucy is the bartender on the first floor of the party room."),
<del> new CrypticClue("He knows just how easy it is to lose track of time.", "Brother Kojo", new WorldPoint(2570, 3250, 0), "Speak to brother Kojo in the Clock Tower. Answer: 22"),
<add> new CrypticClue("He knows just how easy it is to lose track of time.", "Brother Kojo", new WorldPoint(2570, 3250, 0), "Speak to Brother Kojo in the Clock Tower. Answer: 22"),
<ide> new CrypticClue("A great view - watch the rapidly drying hides get splashed. Check the box you are sitting on.", BOXES, new WorldPoint(2523, 3493, 1), "Almera's House north of Baxtorian Falls, search boxes on the first floor."),
<ide> new CrypticClue("Search the Coffin in Edgeville.", COFFIN, new WorldPoint(3091, 3477, 0), "Search the coffin located by the Wilderness teleport lever."),
<ide> new CrypticClue("When no weapons are at hand, then is the time to reflect. In Saradomin's name, redemption draws closer...", DRAWERS_350, new WorldPoint(2818, 3351, 0), "On Entrana, search the southern drawer in the house with the cooking range."), |
|
Java | apache-2.0 | ea2caac6cdc39906e504554899031f4697ae77a1 | 0 | MCUpdater/MCUpdater,MCUpdater/MCUpdater | package org.smbarbour.mcu.util;
// Credit for this class goes to Peter Koeleman, who graciously provided the initial code.
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTML.Tag;
import org.apache.commons.io.FileUtils;
public class ModDownload extends javax.swing.text.html.HTMLEditorKit.ParserCallback {
private boolean isAdfly = false, isMediafire = false, isOptifined = false, readingScript = false;
private String redirectURL = null;
private String remoteFilename;
private File destFile = null;
public final URL url;
public final String expectedMD5;
public boolean cacheHit = false;
public ModDownload(URL url, File destination, String MD5) throws Exception {
this(url, destination, null, MD5);
}
public ModDownload(URL url, File destination) throws Exception {
this(url, destination, null, null);
}
public ModDownload(URL url, File destination, ModDownload referer) throws Exception {
this(url, destination, referer, null);
}
public ModDownload(URL url, File destination, ModDownload referer, String MD5) throws Exception {
this.url = url;
this.expectedMD5 = MD5;
this.remoteFilename = url.getFile().substring(url.getFile().lastIndexOf('/')+1);
// TODO: check for md5 in download cache first
if( MD5 != null ) {
final File cacheFile = DownloadCache.getFile(MD5);
if( cacheFile.exists() ) {
cacheHit = true;
System.out.println("\n\nCache hit - "+MD5);
this.destFile = new File(destination, this.remoteFilename);
FileUtils.copyFile(cacheFile, this.destFile);
return;
} else {
System.out.println("\n\nCache miss - "+MD5);
}
}
if (url.getProtocol().equals("file")){
this.destFile = new File(destination, this.remoteFilename);
FileUtils.copyURLToFile(url, this.destFile);
return;
}
isOptifined = url.getHost().endsWith("optifined.net");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
if (referer != null)
connection.setRequestProperty("Referer", referer.url.toString());
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(false);
System.out.println("\n\nDownloading: "+url+"\n\n");printheaders(connection.getHeaderFields());
if (connection.getResponseCode() / 100 == 3) {
String newLocation = connection.getHeaderField("Location");
url = redirect(url, newLocation);
ModDownload redirect = new ModDownload(url, destination, this, MD5);
this.remoteFilename = redirect.getRemoteFilename();
this.destFile = redirect.getDestFile();
return;
}
String contentType = connection.getContentType();
System.out.println("Content type: "+contentType);
if (contentType.toLowerCase().startsWith("text/html")) {
InputStreamReader r = new InputStreamReader(connection.getInputStream());
javax.swing.text.html.HTMLEditorKit.Parser parser;
parser = new javax.swing.text.html.parser.ParserDelegator();
parser.parse(r, this, true);
r.close();
connection = null;
}
if (redirectURL != null) {
url = redirect(url, redirectURL);
ModDownload redirect = new ModDownload(url, destination, this, MD5);
this.remoteFilename = redirect.getRemoteFilename();
this.destFile = redirect.getDestFile();
return;
}
if (connection != null) {
this.destFile = new File(destination, this.remoteFilename);
InputStream is = connection.getInputStream();
//InputStreamReader isr = new InputStreamReader(connection.getInputStream());
FileOutputStream fos = new FileOutputStream(this.destFile);
byte[] inBuffer = new byte[4096];
int bytesRead;
while (((bytesRead = is.read(inBuffer)) != -1)) {
byte[] outBuffer = Arrays.copyOf(inBuffer, bytesRead);
fos.write(outBuffer);
}
is.close();
fos.close();
// verify md5 && cache the newly retrieved file
if( MD5 != null ) {
final boolean cached = DownloadCache.cacheFile(destFile, MD5);
if( cached ) {
System.out.println("\nSaved in cache");
}
}
}
}
public File getDestFile() {
return this.destFile;
}
public static void printheaders(Map<String, List<String>> headers) {
System.out.println("\nPrinting headers:\n=====================");
Iterator<String> it = headers.keySet().iterator();
while (it.hasNext()) {
String header = it.next();
System.out.println(header);
List<String> ls = headers.get(header);
for (String t : ls)
System.out.println("\t"+t);
}
System.out.println("=====================");
}
@Override
public void handleStartTag(Tag t, MutableAttributeSet attributes, int pos) {
if (t == Tag.HTML) {
Enumeration<?> e = attributes.getAttributeNames();
while (e.hasMoreElements()) {
Object name = e.nextElement();
String value = (String) attributes.getAttribute(name);
if (name == HTML.Attribute.ID && value.equalsIgnoreCase("adfly_html"))
isAdfly = true;
}
}
if (isOptifined && t == Tag.A) {
Enumeration<?> e = attributes.getAttributeNames();
while (e.hasMoreElements()) {
Object name = e.nextElement();
String value = (String) attributes.getAttribute(name);
if (name == HTML.Attribute.HREF && value.startsWith("downloadx.php"))
redirectURL = value;
}
}
readingScript = (t == Tag.SCRIPT);
}
@Override
public void handleSimpleTag(Tag t, MutableAttributeSet attributes, int pos) {
if (t == Tag.META) {
Enumeration<?> e = attributes.getAttributeNames();
boolean readsitename = false, contentmediafire = false;
boolean httprefresh = false;
String localRedirectURL = null;
while (e.hasMoreElements()) {
Object name = e.nextElement();
String value = (String) attributes.getAttribute(name);
//System.out.println("name: "+name.toString()+" value: "+value);
if (name.toString().equalsIgnoreCase("property") && value.equalsIgnoreCase("og:site_name"))
readsitename = true;
if (name.toString().equalsIgnoreCase("content") && value.equals("MediaFire"))
contentmediafire = true;
if (name == HTML.Attribute.HTTPEQUIV && value.equalsIgnoreCase("Refresh"))
httprefresh = true;
if (name == HTML.Attribute.CONTENT) {
String[] tokens = value.split(";");
for (String token : tokens) {
String[] parts = token.split("=");
if (parts.length == 2 && parts[0].trim().equalsIgnoreCase("url")) {
localRedirectURL = parts[1].trim();
}
}
}
}
if (httprefresh && localRedirectURL != null)
redirectURL = localRedirectURL;
if (readsitename && contentmediafire)
isMediafire = true;
}
}
@Override
public void handleComment(char[] data, int pos) {
if (readingScript) {
String code = new String(data);
if (isAdfly) {
String[] tokens = code.split("'");
for (int j = 0; j < tokens.length; j++) {
if (tokens[j].startsWith("/go/")) {
redirectURL = tokens[j];
break;
}
if (tokens[j].startsWith("https://adf.ly/go/")) {
redirectURL = tokens[j];
break;
}
}
}
if (isMediafire) {
String[] tokens = code.split("\"");
for (int j = 0; j < tokens.length; j++) {
if (tokens[j].endsWith("kNO = ")) {
redirectURL = tokens[j+1];
break;
}
}
}
}
}
private static URL redirect(URL url, String newLocation) throws MalformedURLException, URISyntaxException {
newLocation = unescape(newLocation);
if (newLocation.startsWith("http")) {
url = new URL(newLocation);
} else if (!newLocation.startsWith("/")) {
newLocation = url.getPath().substring(0, url.getPath().lastIndexOf('/')+1) + newLocation;
url = new URL(url.getProtocol()+"://"+url.getHost()+newLocation);
} else {
url = new URL(url.getProtocol()+"://"+url.getHost()+newLocation);
}
URI nu = new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), null);
return nu.toURL();
}
private static String unescape(String s) {
int index = -1;
do {
index = s.indexOf("%", index);
if (index == -1) break;
if (s.charAt(index + 1) == '%') continue;
String charcode;
char c;
try {
charcode = s.substring(index + 1, index + 3);
c = (char)Integer.parseInt(charcode, 16);
} catch (IndexOutOfBoundsException ioobe) {
break;
}
s = s.substring(0, index) + c + ((s.length() > index + 3) ? s.substring(index + 3) : "");
} while (index != -1);
return s;
}
public String getRemoteFilename() {
return unescape(remoteFilename);
}
/* Code for testing. Not needed for API usage.
public static void main(String[] args) {
try {
URL url;
url = new URL("http://adf.ly/3X3dW"); // NEI
url = new URL("http://goo.gl/x5mGr"); // REI's minimap
url = new URL("http://adf.ly/89H6K"); // backpacks
url = new URL("http://optifined.net/adload.php?f=OptiFine_1.2.5_HD_MT_C6.zip");
File tmp = new File("/tmp/testdownload");
System.out.println("File downloaded from "+url+": "+(new ModDownload(url, tmp)).remoteFilename+" into "+tmp);
//url = new URL("http://www.example.com");
//url = redirect(url, "/Files/goto.php?file=WR-CBE%20Core-Client");
//System.out.println(url);
} catch (Exception e) {
e.printStackTrace();
}
}
*/
}
| MCU-API/src/org/smbarbour/mcu/util/ModDownload.java | package org.smbarbour.mcu.util;
// Credit for this class goes to Peter Koeleman, who graciously provided the initial code.
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTML.Tag;
import org.apache.commons.io.FileUtils;
public class ModDownload extends javax.swing.text.html.HTMLEditorKit.ParserCallback {
private boolean isAdfly = false, isMediafire = false, isOptifined = false, readingScript = false;
private String redirectURL = null;
private String remoteFilename;
private File destFile = null;
public final URL url;
public final String expectedMD5;
public boolean cacheHit = false;
public ModDownload(URL url, File destination, String MD5) throws Exception {
this(url, destination, null, MD5);
}
public ModDownload(URL url, File destination) throws Exception {
this(url, destination, null, null);
}
public ModDownload(URL url, File destination, ModDownload referer) throws Exception {
this(url, destination, referer, null);
}
public ModDownload(URL url, File destination, ModDownload referer, String MD5) throws Exception {
this.url = url;
this.expectedMD5 = MD5;
this.remoteFilename = url.getFile().substring(url.getFile().lastIndexOf('/')+1);
// TODO: check for md5 in download cache first
if( MD5 != null ) {
final File cacheFile = DownloadCache.getFile(MD5);
if( cacheFile.exists() ) {
cacheHit = true;
System.out.println("\n\nCache hit - "+MD5);
this.destFile = new File(destination, this.remoteFilename);
FileUtils.copyFile(cacheFile, this.destFile);
return;
} else {
System.out.println("\n\nCache miss - "+MD5);
}
}
if (url.getProtocol().equals("file")){
this.destFile = new File(destination, this.remoteFilename);
FileUtils.copyURLToFile(url, this.destFile);
return;
}
isOptifined = url.getHost().endsWith("optifined.net");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
if (referer != null)
connection.setRequestProperty("Referer", referer.url.toString());
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(false);
System.out.println("\n\nDownloading: "+url+"\n\n");printheaders(connection.getHeaderFields());
if (connection.getResponseCode() / 100 == 3) {
String newLocation = connection.getHeaderField("Location");
url = redirect(url, newLocation);
ModDownload redirect = new ModDownload(url, destination, this, MD5);
this.remoteFilename = redirect.getRemoteFilename();
this.destFile = redirect.getDestFile();
return;
}
String contentType = connection.getContentType();
System.out.println("Content type: "+contentType);
if (contentType.toLowerCase().startsWith("text/html")) {
InputStreamReader r = new InputStreamReader(connection.getInputStream());
javax.swing.text.html.HTMLEditorKit.Parser parser;
parser = new javax.swing.text.html.parser.ParserDelegator();
parser.parse(r, this, true);
r.close();
connection = null;
}
if (redirectURL != null) {
url = redirect(url, redirectURL);
ModDownload redirect = new ModDownload(url, destination, this, MD5);
this.remoteFilename = redirect.getRemoteFilename();
this.destFile = redirect.getDestFile();
return;
}
if (connection != null) {
this.destFile = new File(destination, this.remoteFilename);
InputStream is = connection.getInputStream();
//InputStreamReader isr = new InputStreamReader(connection.getInputStream());
FileOutputStream fos = new FileOutputStream(this.destFile);
byte[] inBuffer = new byte[4096];
int bytesRead;
while (((bytesRead = is.read(inBuffer)) != -1)) {
byte[] outBuffer = Arrays.copyOf(inBuffer, bytesRead);
fos.write(outBuffer);
}
is.close();
fos.close();
// verify md5 && cache the newly retrieved file
if( MD5 != null ) {
final boolean cached = DownloadCache.cacheFile(destFile, MD5);
if( cached ) {
System.out.println("\nSaved in cache");
}
}
}
}
public File getDestFile() {
return this.destFile;
}
public static void printheaders(Map<String, List<String>> headers) {
System.out.println("\nPrinting headers:\n=====================");
Iterator<String> it = headers.keySet().iterator();
while (it.hasNext()) {
String header = it.next();
System.out.println(header);
List<String> ls = headers.get(header);
for (String t : ls)
System.out.println("\t"+t);
}
System.out.println("=====================");
}
@Override
public void handleStartTag(Tag t, MutableAttributeSet attributes, int pos) {
if (t == Tag.HTML) {
Enumeration<?> e = attributes.getAttributeNames();
while (e.hasMoreElements()) {
Object name = e.nextElement();
String value = (String) attributes.getAttribute(name);
if (name == HTML.Attribute.ID && value.equalsIgnoreCase("adfly_html"))
isAdfly = true;
}
}
if (isOptifined && t == Tag.A) {
Enumeration<?> e = attributes.getAttributeNames();
while (e.hasMoreElements()) {
Object name = e.nextElement();
String value = (String) attributes.getAttribute(name);
if (name == HTML.Attribute.HREF && value.startsWith("download.php"))
redirectURL = value;
}
}
readingScript = (t == Tag.SCRIPT);
}
@Override
public void handleSimpleTag(Tag t, MutableAttributeSet attributes, int pos) {
if (t == Tag.META) {
Enumeration<?> e = attributes.getAttributeNames();
boolean readsitename = false, contentmediafire = false;
boolean httprefresh = false;
String localRedirectURL = null;
while (e.hasMoreElements()) {
Object name = e.nextElement();
String value = (String) attributes.getAttribute(name);
//System.out.println("name: "+name.toString()+" value: "+value);
if (name.toString().equalsIgnoreCase("property") && value.equalsIgnoreCase("og:site_name"))
readsitename = true;
if (name.toString().equalsIgnoreCase("content") && value.equals("MediaFire"))
contentmediafire = true;
if (name == HTML.Attribute.HTTPEQUIV && value.equalsIgnoreCase("Refresh"))
httprefresh = true;
if (name == HTML.Attribute.CONTENT) {
String[] tokens = value.split(";");
for (String token : tokens) {
String[] parts = token.split("=");
if (parts.length == 2 && parts[0].trim().equalsIgnoreCase("url")) {
localRedirectURL = parts[1].trim();
}
}
}
}
if (httprefresh && localRedirectURL != null)
redirectURL = localRedirectURL;
if (readsitename && contentmediafire)
isMediafire = true;
}
}
@Override
public void handleComment(char[] data, int pos) {
if (readingScript) {
String code = new String(data);
if (isAdfly) {
String[] tokens = code.split("'");
for (int j = 0; j < tokens.length; j++) {
if (tokens[j].startsWith("/go/")) {
redirectURL = tokens[j];
break;
}
if (tokens[j].startsWith("https://adf.ly/go/")) {
redirectURL = tokens[j];
break;
}
}
}
if (isMediafire) {
String[] tokens = code.split("\"");
for (int j = 0; j < tokens.length; j++) {
if (tokens[j].endsWith("kNO = ")) {
redirectURL = tokens[j+1];
break;
}
}
}
}
}
private static URL redirect(URL url, String newLocation) throws MalformedURLException, URISyntaxException {
newLocation = unescape(newLocation);
if (newLocation.startsWith("http")) {
url = new URL(newLocation);
} else if (!newLocation.startsWith("/")) {
newLocation = url.getPath().substring(0, url.getPath().lastIndexOf('/')+1) + newLocation;
url = new URL(url.getProtocol()+"://"+url.getHost()+newLocation);
} else {
url = new URL(url.getProtocol()+"://"+url.getHost()+newLocation);
}
URI nu = new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), null);
return nu.toURL();
}
private static String unescape(String s) {
int index = -1;
do {
index = s.indexOf("%", index);
if (index == -1) break;
if (s.charAt(index + 1) == '%') continue;
String charcode;
char c;
try {
charcode = s.substring(index + 1, index + 3);
c = (char)Integer.parseInt(charcode, 16);
} catch (IndexOutOfBoundsException ioobe) {
break;
}
s = s.substring(0, index) + c + ((s.length() > index + 3) ? s.substring(index + 3) : "");
} while (index != -1);
return s;
}
public String getRemoteFilename() {
return unescape(remoteFilename);
}
/* Code for testing. Not needed for API usage.
public static void main(String[] args) {
try {
URL url;
url = new URL("http://adf.ly/3X3dW"); // NEI
url = new URL("http://goo.gl/x5mGr"); // REI's minimap
url = new URL("http://adf.ly/89H6K"); // backpacks
url = new URL("http://optifined.net/adload.php?f=OptiFine_1.2.5_HD_MT_C6.zip");
File tmp = new File("/tmp/testdownload");
System.out.println("File downloaded from "+url+": "+(new ModDownload(url, tmp)).remoteFilename+" into "+tmp);
//url = new URL("http://www.example.com");
//url = redirect(url, "/Files/goto.php?file=WR-CBE%20Core-Client");
//System.out.println(url);
} catch (Exception e) {
e.printStackTrace();
}
}
*/
}
| Attempt at making direct download of Optifine work | MCU-API/src/org/smbarbour/mcu/util/ModDownload.java | Attempt at making direct download of Optifine work | <ide><path>CU-API/src/org/smbarbour/mcu/util/ModDownload.java
<ide> while (e.hasMoreElements()) {
<ide> Object name = e.nextElement();
<ide> String value = (String) attributes.getAttribute(name);
<del> if (name == HTML.Attribute.HREF && value.startsWith("download.php"))
<add> if (name == HTML.Attribute.HREF && value.startsWith("downloadx.php"))
<ide> redirectURL = value;
<ide> }
<ide> } |
|
Java | apache-2.0 | bde61486d43c80ea23295c7995259e5b41bc78a4 | 0 | orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb | package com.orientechnologies.distribution.integration;
import com.orientechnologies.orient.core.collate.OCaseInsensitiveCollate;
import com.orientechnologies.orient.core.collate.ODefaultCollate;
import com.orientechnologies.orient.core.db.ODatabaseType;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
/**
* Created by santo-it on 03/22/2017.
*/
public class OGitHubIssuesIT extends OIntegrationTestTemplate {
@Override
@Before
public void setUp() throws Exception {
super.setUp();
String database = this.getClass().getName();
if (!orientDB.exists(database)) {
orientDB.create(database, ODatabaseType.PLOCAL);
}
db = orientDB.open(database, "admin", "admin");
}
@Test
public void Issue7264() throws Exception {
OClass oOtherClass = db.createVertexClass("OtherClass");
OProperty oPropertyOtherCI = oOtherClass.createProperty("OtherCI", OType.STRING);
oPropertyOtherCI.setCollate(OCaseInsensitiveCollate.NAME);
OProperty oPropertyOtherCS = oOtherClass.createProperty("OtherCS", OType.STRING);
oPropertyOtherCS.setCollate(ODefaultCollate.NAME);
oOtherClass.createIndex("other_ci_idx", OClass.INDEX_TYPE.NOTUNIQUE, "OtherCI");
oOtherClass.createIndex("other_cs_idx", OClass.INDEX_TYPE.NOTUNIQUE, "OtherCS");
db.command("INSERT INTO OtherClass SET OtherCS='abc', OtherCI='abc';");
db.command("INSERT INTO OtherClass SET OtherCS='ABC', OtherCI='ABC';");
db.command("INSERT INTO OtherClass SET OtherCS='Abc', OtherCI='Abc';");
db.command("INSERT INTO OtherClass SET OtherCS='aBc', OtherCI='aBc';");
db.command("INSERT INTO OtherClass SET OtherCS='abC', OtherCI='abC';");
db.command("INSERT INTO OtherClass SET OtherCS='ABc', OtherCI='ABc';");
db.command("INSERT INTO OtherClass SET OtherCS='aBC', OtherCI='aBC';");
db.command("INSERT INTO OtherClass SET OtherCS='AbC', OtherCI='AbC';");
OResultSet results = db.query("SELECT FROM OtherClass WHERE OtherCS='abc'");
assertThat(results).hasSize(1);
results = db.query("SELECT FROM OtherClass WHERE OtherCI='abc'");
assertThat(results).hasSize(8);
OClass oClassCS = db.createVertexClass("CaseSensitiveCollationIndex");
OProperty oPropertyGroupCS = oClassCS.createProperty("Group", OType.STRING);
oPropertyGroupCS.setCollate(ODefaultCollate.NAME);
OProperty oPropertyNameCS = oClassCS.createProperty("Name", OType.STRING);
oPropertyNameCS.setCollate(ODefaultCollate.NAME);
OProperty oPropertyVersionCS = oClassCS.createProperty("Version", OType.STRING);
oPropertyVersionCS.setCollate(ODefaultCollate.NAME);
oClassCS.createIndex("group_name_version_cs_idx", OClass.INDEX_TYPE.NOTUNIQUE, "Group", "Name", "Version");
db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='abc', Version='1';");
db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='ABC', Version='1';");
db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='Abc', Version='1';");
db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='aBc', Version='1';");
db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='abC', Version='1';");
db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='ABc', Version='1';");
db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='aBC', Version='1';");
db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='AbC', Version='1';");
results = db.query("SELECT FROM CaseSensitiveCollationIndex WHERE Version='1' AND `Group` = 1 AND Name='abc'");
assertThat(results).hasSize(1);
results = db.query("SELECT FROM CaseSensitiveCollationIndex WHERE Version='1' AND Name='abc' AND `Group` = 1");
assertThat(results).hasSize(1);
results = db.query("SELECT FROM CaseSensitiveCollationIndex WHERE `Group` = 1 AND Name='abc' AND Version='1'");
assertThat(results).hasSize(1);
results = db.query("SELECT FROM CaseSensitiveCollationIndex WHERE `Group` = 1 AND Version='1' AND Name='abc'");
assertThat(results).hasSize(1);
results = db.query("SELECT FROM CaseSensitiveCollationIndex WHERE Name='abc' AND Version='1' AND `Group` = 1");
assertThat(results).hasSize(1);
results = db.query("SELECT FROM CaseSensitiveCollationIndex WHERE Name='abc' AND `Group` = 1 AND Version='1'");
assertThat(results).hasSize(1);
OClass oClassCI = db.createVertexClass("CaseInsensitiveCollationIndex");
OProperty oPropertyGroupCI = oClassCI.createProperty("Group", OType.STRING);
oPropertyGroupCI.setCollate(OCaseInsensitiveCollate.NAME);
OProperty oPropertyNameCI = oClassCI.createProperty("Name", OType.STRING);
oPropertyNameCI.setCollate(OCaseInsensitiveCollate.NAME);
OProperty oPropertyVersionCI = oClassCI.createProperty("Version", OType.STRING);
oPropertyVersionCI.setCollate(OCaseInsensitiveCollate.NAME);
oClassCI.createIndex("group_name_version_ci_idx", OClass.INDEX_TYPE.NOTUNIQUE, "Group", "Name", "Version");
db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='abc', Version='1';");
db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='ABC', Version='1';");
db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='Abc', Version='1';");
db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='aBc', Version='1';");
db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='abC', Version='1';");
db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='ABc', Version='1';");
db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='aBC', Version='1';");
db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='AbC', Version='1';");
results = db.query("SELECT FROM CaseInsensitiveCollationIndex WHERE Version='1' AND `Group` = 1 AND Name='abc'");
assertThat(results).hasSize(8);
results = db.query("SELECT FROM CaseInsensitiveCollationIndex WHERE Version='1' AND Name='abc' AND `Group` = 1");
assertThat(results).hasSize(8);
results = db.query("SELECT FROM CaseInsensitiveCollationIndex WHERE `Group` = 1 AND Name='abc' AND Version='1'");
assertThat(results).hasSize(8);
results = db.query("SELECT FROM CaseInsensitiveCollationIndex WHERE `Group` = 1 AND Version='1' AND Name='abc'");
assertThat(results).hasSize(8);
results = db.query("SELECT FROM CaseInsensitiveCollationIndex WHERE Name='abc' AND Version='1' AND `Group` = 1");
assertThat(results).hasSize(8);
results = db.query("SELECT FROM CaseInsensitiveCollationIndex WHERE Name='abc' AND `Group` = 1 AND Version='1'");
assertThat(results).hasSize(8);
}
@Test
public void Issue7249() throws Exception {
db.command("CREATE CLASS t7249Profiles EXTENDS V;");
db.command("CREATE CLASS t7249HasFriend EXTENDS E;");
db.command("INSERT INTO t7249Profiles SET Name = 'Santo';");
db.command("INSERT INTO t7249Profiles SET Name = 'Luca';");
db.command("INSERT INTO t7249Profiles SET Name = 'Luigi';");
db.command("INSERT INTO t7249Profiles SET Name = 'Colin';");
db.command("INSERT INTO t7249Profiles SET Name = 'Enrico';");
db.command(
"CREATE EDGE t7249HasFriend FROM (SELECT FROM t7249Profiles WHERE Name='Santo') TO (SELECT FROM t7249Profiles WHERE Name='Luca');");
db.command(
"CREATE EDGE t7249HasFriend FROM (SELECT FROM t7249Profiles WHERE Name='Santo') TO (SELECT FROM t7249Profiles WHERE Name='Luigi');");
db.command(
"CREATE EDGE t7249HasFriend FROM (SELECT FROM t7249Profiles WHERE Name='Santo') TO (SELECT FROM t7249Profiles WHERE Name='Colin');");
db.command(
"CREATE EDGE t7249HasFriend FROM (SELECT FROM t7249Profiles WHERE Name='Enrico') TO (SELECT FROM t7249Profiles WHERE Name='Santo');");
List<OResult> results = db.query("SELECT in('t7249HasFriend').size() as InFriendsNumber FROM t7249Profiles WHERE Name='Santo'")
.stream().collect(Collectors.toList());
assertEquals(1, results.size());
assertEquals((Object) 1, results.get(0).getProperty("InFriendsNumber"));
results = db.query("SELECT out('t7249HasFriend').size() as OutFriendsNumber FROM t7249Profiles WHERE Name='Santo'").stream()
.collect(Collectors.toList());
assertEquals(1, results.size());
assertEquals((Object) 3, results.get(0).getProperty("OutFriendsNumber"));
results = db.query("SELECT both('t7249HasFriend').size() as TotalFriendsNumber FROM t7249Profiles WHERE Name='Santo'").stream()
.collect(Collectors.toList());
assertEquals(1, results.size());
assertEquals((Object) 4, results.get(0).getProperty("TotalFriendsNumber"));
}
@Test
public void Issue7256() throws Exception {
db.command("CREATE CLASS t7265Customers EXTENDS V;");
db.command("CREATE CLASS t7265Services EXTENDS V;");
db.command("CREATE CLASS t7265Hotels EXTENDS V, t7265Services;");
db.command("CREATE CLASS t7265Restaurants EXTENDS V, t7265Services;");
db.command("CREATE CLASS t7265Countries EXTENDS V;");
db.command("CREATE CLASS t7265IsFromCountry EXTENDS E;");
db.command("CREATE CLASS t7265HasUsedService EXTENDS E;");
db.command("CREATE CLASS t7265HasStayed EXTENDS E, t7265HasUsedService;");
db.command("CREATE CLASS t7265HasEaten EXTENDS E, t7265HasUsedService;");
db.command("INSERT INTO t7265Customers SET OrderedId = 1, Phone = '+1400844724';");
db.command("INSERT INTO t7265Hotels SET Id = 1, Name = 'Best Western Ascott', Type = 'hotel';");
db.command("INSERT INTO t7265Restaurants SET Id = 1, Name = 'La Brasserie de Milan', Type = 'restaurant';");
db.command("INSERT INTO t7265Countries SET Id = 1, Code = 'AD', Name = 'Andorra';");
db.command(
"CREATE EDGE t7265HasEaten FROM (SELECT FROM t7265Customers WHERE OrderedId=1) TO (SELECT FROM t7265Restaurants WHERE Id=1);");
db.command(
"CREATE EDGE t7265HasStayed FROM (SELECT FROM t7265Customers WHERE OrderedId=1) TO (SELECT FROM t7265Hotels WHERE Id=1);");
db.command(
"CREATE EDGE t7265IsFromCountry FROM (SELECT FROM t7265Customers WHERE OrderedId=1) TO (SELECT FROM t7265Countries WHERE Id=1);");
OResultSet results = db.query(
"MATCH {class: t7265Customers, as: customer, where: (OrderedId=1)}--{Class: t7265Services, as: service} RETURN service.Name");
assertThat(results).hasSize(2);
}
}
| distribution/src/test/java/com/orientechnologies/distribution/integration/OGitHubIssuesIT.java | package com.orientechnologies.distribution.integration;
import com.orientechnologies.orient.core.db.ODatabaseType;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
/**
* Created by santo-it on 03/22/2017.
*/
public class OGitHubIssuesIT extends OIntegrationTestTemplate {
@Override
@Before
public void setUp() throws Exception {
super.setUp();
String database = this.getClass().getName();
if (!orientDB.exists(database)) {
orientDB.create(database, ODatabaseType.PLOCAL);
}
db = orientDB.open(database, "admin", "admin");
}
@Test
public void Issue7249() throws Exception {
db.command("CREATE CLASS t7249Profiles EXTENDS V;");
db.command("CREATE CLASS t7249HasFriend EXTENDS E;");
db.command("INSERT INTO t7249Profiles SET Name = 'Santo';");
db.command("INSERT INTO t7249Profiles SET Name = 'Luca';");
db.command("INSERT INTO t7249Profiles SET Name = 'Luigi';");
db.command("INSERT INTO t7249Profiles SET Name = 'Colin';");
db.command("INSERT INTO t7249Profiles SET Name = 'Enrico';");
db.command(
"CREATE EDGE t7249HasFriend FROM (SELECT FROM t7249Profiles WHERE Name='Santo') TO (SELECT FROM t7249Profiles WHERE Name='Luca');");
db.command(
"CREATE EDGE t7249HasFriend FROM (SELECT FROM t7249Profiles WHERE Name='Santo') TO (SELECT FROM t7249Profiles WHERE Name='Luigi');");
db.command(
"CREATE EDGE t7249HasFriend FROM (SELECT FROM t7249Profiles WHERE Name='Santo') TO (SELECT FROM t7249Profiles WHERE Name='Colin');");
db.command(
"CREATE EDGE t7249HasFriend FROM (SELECT FROM t7249Profiles WHERE Name='Enrico') TO (SELECT FROM t7249Profiles WHERE Name='Santo');");
List<OResult> results = db.query("SELECT in('t7249HasFriend').size() as InFriendsNumber FROM t7249Profiles WHERE Name='Santo'")
.stream().collect(Collectors.toList());
assertEquals(1, results.size());
assertEquals((Object) 1, results.get(0).getProperty("InFriendsNumber"));
results = db.query("SELECT out('t7249HasFriend').size() as OutFriendsNumber FROM t7249Profiles WHERE Name='Santo'").stream()
.collect(Collectors.toList());
assertEquals(1, results.size());
assertEquals((Object) 3, results.get(0).getProperty("OutFriendsNumber"));
results = db.query("SELECT both('t7249HasFriend').size() as TotalFriendsNumber FROM t7249Profiles WHERE Name='Santo'").stream()
.collect(Collectors.toList());
assertEquals(1, results.size());
assertEquals((Object) 4, results.get(0).getProperty("TotalFriendsNumber"));
}
@Test
public void Issue7256() throws Exception {
db.command("CREATE CLASS t7265Customers EXTENDS V;");
db.command("CREATE CLASS t7265Services EXTENDS V;");
db.command("CREATE CLASS t7265Hotels EXTENDS V, t7265Services;");
db.command("CREATE CLASS t7265Restaurants EXTENDS V, t7265Services;");
db.command("CREATE CLASS t7265Countries EXTENDS V;");
db.command("CREATE CLASS t7265IsFromCountry EXTENDS E;");
db.command("CREATE CLASS t7265HasUsedService EXTENDS E;");
db.command("CREATE CLASS t7265HasStayed EXTENDS E, t7265HasUsedService;");
db.command("CREATE CLASS t7265HasEaten EXTENDS E, t7265HasUsedService;");
db.command("INSERT INTO t7265Customers SET OrderedId = 1, Phone = '+1400844724';");
db.command("INSERT INTO t7265Hotels SET Id = 1, Name = 'Best Western Ascott', Type = 'hotel';");
db.command("INSERT INTO t7265Restaurants SET Id = 1, Name = 'La Brasserie de Milan', Type = 'restaurant';");
db.command("INSERT INTO t7265Countries SET Id = 1, Code = 'AD', Name = 'Andorra';");
db.command(
"CREATE EDGE t7265HasEaten FROM (SELECT FROM t7265Customers WHERE OrderedId=1) TO (SELECT FROM t7265Restaurants WHERE Id=1);");
db.command(
"CREATE EDGE t7265HasStayed FROM (SELECT FROM t7265Customers WHERE OrderedId=1) TO (SELECT FROM t7265Hotels WHERE Id=1);");
db.command(
"CREATE EDGE t7265IsFromCountry FROM (SELECT FROM t7265Customers WHERE OrderedId=1) TO (SELECT FROM t7265Countries WHERE Id=1);");
OResultSet results = db.query(
"MATCH {class: t7265Customers, as: customer, where: (OrderedId=1)}--{Class: t7265Services, as: service} RETURN service.Name");
assertThat(results).hasSize(2);
}
}
| Test for Issue #7264
| distribution/src/test/java/com/orientechnologies/distribution/integration/OGitHubIssuesIT.java | Test for Issue #7264 | <ide><path>istribution/src/test/java/com/orientechnologies/distribution/integration/OGitHubIssuesIT.java
<ide> package com.orientechnologies.distribution.integration;
<ide>
<add>import com.orientechnologies.orient.core.collate.OCaseInsensitiveCollate;
<add>import com.orientechnologies.orient.core.collate.ODefaultCollate;
<ide> import com.orientechnologies.orient.core.db.ODatabaseType;
<add>import com.orientechnologies.orient.core.metadata.schema.OClass;
<add>import com.orientechnologies.orient.core.metadata.schema.OProperty;
<add>import com.orientechnologies.orient.core.metadata.schema.OType;
<ide> import com.orientechnologies.orient.core.sql.executor.OResult;
<ide> import com.orientechnologies.orient.core.sql.executor.OResultSet;
<ide> import org.junit.Before;
<ide> }
<ide>
<ide> db = orientDB.open(database, "admin", "admin");
<add> }
<add>
<add> @Test
<add> public void Issue7264() throws Exception {
<add>
<add> OClass oOtherClass = db.createVertexClass("OtherClass");
<add>
<add> OProperty oPropertyOtherCI = oOtherClass.createProperty("OtherCI", OType.STRING);
<add> oPropertyOtherCI.setCollate(OCaseInsensitiveCollate.NAME);
<add>
<add> OProperty oPropertyOtherCS = oOtherClass.createProperty("OtherCS", OType.STRING);
<add> oPropertyOtherCS.setCollate(ODefaultCollate.NAME);
<add>
<add> oOtherClass.createIndex("other_ci_idx", OClass.INDEX_TYPE.NOTUNIQUE, "OtherCI");
<add> oOtherClass.createIndex("other_cs_idx", OClass.INDEX_TYPE.NOTUNIQUE, "OtherCS");
<add>
<add> db.command("INSERT INTO OtherClass SET OtherCS='abc', OtherCI='abc';");
<add> db.command("INSERT INTO OtherClass SET OtherCS='ABC', OtherCI='ABC';");
<add> db.command("INSERT INTO OtherClass SET OtherCS='Abc', OtherCI='Abc';");
<add> db.command("INSERT INTO OtherClass SET OtherCS='aBc', OtherCI='aBc';");
<add> db.command("INSERT INTO OtherClass SET OtherCS='abC', OtherCI='abC';");
<add> db.command("INSERT INTO OtherClass SET OtherCS='ABc', OtherCI='ABc';");
<add> db.command("INSERT INTO OtherClass SET OtherCS='aBC', OtherCI='aBC';");
<add> db.command("INSERT INTO OtherClass SET OtherCS='AbC', OtherCI='AbC';");
<add>
<add> OResultSet results = db.query("SELECT FROM OtherClass WHERE OtherCS='abc'");
<add> assertThat(results).hasSize(1);
<add>
<add> results = db.query("SELECT FROM OtherClass WHERE OtherCI='abc'");
<add> assertThat(results).hasSize(8);
<add>
<add> OClass oClassCS = db.createVertexClass("CaseSensitiveCollationIndex");
<add>
<add> OProperty oPropertyGroupCS = oClassCS.createProperty("Group", OType.STRING);
<add> oPropertyGroupCS.setCollate(ODefaultCollate.NAME);
<add> OProperty oPropertyNameCS = oClassCS.createProperty("Name", OType.STRING);
<add> oPropertyNameCS.setCollate(ODefaultCollate.NAME);
<add> OProperty oPropertyVersionCS = oClassCS.createProperty("Version", OType.STRING);
<add> oPropertyVersionCS.setCollate(ODefaultCollate.NAME);
<add>
<add> oClassCS.createIndex("group_name_version_cs_idx", OClass.INDEX_TYPE.NOTUNIQUE, "Group", "Name", "Version");
<add>
<add> db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='abc', Version='1';");
<add> db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='ABC', Version='1';");
<add> db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='Abc', Version='1';");
<add> db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='aBc', Version='1';");
<add> db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='abC', Version='1';");
<add> db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='ABc', Version='1';");
<add> db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='aBC', Version='1';");
<add> db.command("INSERT INTO CaseSensitiveCollationIndex SET `Group`='1', Name='AbC', Version='1';");
<add>
<add> results = db.query("SELECT FROM CaseSensitiveCollationIndex WHERE Version='1' AND `Group` = 1 AND Name='abc'");
<add> assertThat(results).hasSize(1);
<add>
<add> results = db.query("SELECT FROM CaseSensitiveCollationIndex WHERE Version='1' AND Name='abc' AND `Group` = 1");
<add> assertThat(results).hasSize(1);
<add>
<add> results = db.query("SELECT FROM CaseSensitiveCollationIndex WHERE `Group` = 1 AND Name='abc' AND Version='1'");
<add> assertThat(results).hasSize(1);
<add>
<add> results = db.query("SELECT FROM CaseSensitiveCollationIndex WHERE `Group` = 1 AND Version='1' AND Name='abc'");
<add> assertThat(results).hasSize(1);
<add>
<add> results = db.query("SELECT FROM CaseSensitiveCollationIndex WHERE Name='abc' AND Version='1' AND `Group` = 1");
<add> assertThat(results).hasSize(1);
<add>
<add> results = db.query("SELECT FROM CaseSensitiveCollationIndex WHERE Name='abc' AND `Group` = 1 AND Version='1'");
<add> assertThat(results).hasSize(1);
<add>
<add> OClass oClassCI = db.createVertexClass("CaseInsensitiveCollationIndex");
<add>
<add> OProperty oPropertyGroupCI = oClassCI.createProperty("Group", OType.STRING);
<add> oPropertyGroupCI.setCollate(OCaseInsensitiveCollate.NAME);
<add> OProperty oPropertyNameCI = oClassCI.createProperty("Name", OType.STRING);
<add> oPropertyNameCI.setCollate(OCaseInsensitiveCollate.NAME);
<add> OProperty oPropertyVersionCI = oClassCI.createProperty("Version", OType.STRING);
<add> oPropertyVersionCI.setCollate(OCaseInsensitiveCollate.NAME);
<add>
<add> oClassCI.createIndex("group_name_version_ci_idx", OClass.INDEX_TYPE.NOTUNIQUE, "Group", "Name", "Version");
<add>
<add> db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='abc', Version='1';");
<add> db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='ABC', Version='1';");
<add> db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='Abc', Version='1';");
<add> db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='aBc', Version='1';");
<add> db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='abC', Version='1';");
<add> db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='ABc', Version='1';");
<add> db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='aBC', Version='1';");
<add> db.command("INSERT INTO CaseInsensitiveCollationIndex SET `Group`='1', Name='AbC', Version='1';");
<add>
<add> results = db.query("SELECT FROM CaseInsensitiveCollationIndex WHERE Version='1' AND `Group` = 1 AND Name='abc'");
<add> assertThat(results).hasSize(8);
<add>
<add> results = db.query("SELECT FROM CaseInsensitiveCollationIndex WHERE Version='1' AND Name='abc' AND `Group` = 1");
<add> assertThat(results).hasSize(8);
<add>
<add> results = db.query("SELECT FROM CaseInsensitiveCollationIndex WHERE `Group` = 1 AND Name='abc' AND Version='1'");
<add> assertThat(results).hasSize(8);
<add>
<add> results = db.query("SELECT FROM CaseInsensitiveCollationIndex WHERE `Group` = 1 AND Version='1' AND Name='abc'");
<add> assertThat(results).hasSize(8);
<add>
<add> results = db.query("SELECT FROM CaseInsensitiveCollationIndex WHERE Name='abc' AND Version='1' AND `Group` = 1");
<add> assertThat(results).hasSize(8);
<add>
<add> results = db.query("SELECT FROM CaseInsensitiveCollationIndex WHERE Name='abc' AND `Group` = 1 AND Version='1'");
<add> assertThat(results).hasSize(8);
<add>
<ide> }
<ide>
<ide> @Test |
|
Java | apache-2.0 | e05dc641e89d8419e72d0591c05361915f1b7b2e | 0 | skremp/pictura-io,skremp/pictura-io,skremp/pictura-io | /**
* Copyright 2015, 2016 Steffen Kremp
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.pictura.servlet;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This is the basic implementation of an request processor which will be
* executed for any {@link PicturaServlet} request.
*
* @see Runnable
*
* @author Steffen Kremp
*
* @since 1.0
*/
public abstract class RequestProcessor implements Runnable, Cacheable {
private static final Log LOG = Log.getLog(RequestProcessor.class);
// HTTP header field names
protected static final String HEADER_IFMODSINCE = "If-Modified-Since";
protected static final String HEADER_LASTMOD = "Last-Modified";
protected static final String HEADER_IFNONMATCH = "If-None-Match";
protected static final String HEADER_ETAG = "ETag";
protected static final String HEADER_DATE = "Date";
protected static final String HEADER_EXPIRES = "Expires";
protected static final String HEADER_PRAGMA = "Pragma";
protected static final String HEADER_CONNECTION = "Connection";
protected static final String HEADER_CACHECONTROL = "Cache-Control";
protected static final String HEADER_CONTACCEPT = "Content-Accept";
protected static final String HEADER_CONTENC = "Content-Encoding";
protected static final String HEADER_CONTLANG = "Content-Language";
protected static final String HEADER_CONTLOC = "Content-Location";
protected static final String HEADER_CONTTYPE = "Content-Type";
protected static final String HEADER_CONTLEN = "Content-Length";
protected static final String HEADER_LOCATION = "Location";
protected static final String HEADER_COOKIE = "Cookie";
protected static final String HEADER_VARY = "Vary";
protected static final String HEADER_ACCEPT = "Accept";
protected static final String HEADER_ACCEPTENC = "Accept-Encoding";
protected static final String HEADER_ALLOW = "Allow";
protected static final String HEADER_USERAGENT = "User-Agent";
// The associated servlet request and response object
private HttpServletRequest req;
private HttpServletResponse resp;
// Pre-process stuff
private Runnable preProcessor;
// State flags
private boolean committed;
private boolean completed;
private boolean interrupted;
// Context if the processor is running async
private AsyncContext asyncCtx;
private Pattern[] resPaths;
private ResourceLocator[] resLocators;
// A calculated "true" cache key for the response
private String trueCacheKey;
// Processor timestamps
private long duration;
private long runtime;
private final long timestamp;
// A unique request ID (for debugging purposes)
private UUID requestId;
/**
* Creates a new <code>RequestProcessor</code>.
*/
public RequestProcessor() {
this.duration = -1;
this.timestamp = System.currentTimeMillis();
}
/**
* Creates a new <code>RequestProcessor</code> based on the specified
* "origin" request processor.
*
* @param rp The base request processor.
*/
protected RequestProcessor(RequestProcessor rp) {
if (rp == null) {
throw new IllegalArgumentException("Origin request processor must be not null");
}
this.req = rp.getRequest();
this.resp = rp.getResponse();
// Optional
this.asyncCtx = rp.getAsyncContext();
this.resPaths = rp.getResourcePaths();
this.resLocators = rp.getResourceLocators();
this.preProcessor = rp.getPreProcessor();
this.duration = rp.duration;
this.timestamp = rp.timestamp;
this.committed = rp.committed;
this.completed = rp.completed;
this.interrupted = rp.interrupted;
this.requestId = rp.requestId;
}
Runnable getPreProcessor() {
return preProcessor;
}
void setPreProcessor(Runnable r) {
if (committed) {
throw new IllegalStateException("setPreProcessor() after comitted");
}
this.preProcessor = r;
}
HttpServletRequest getRequest() {
return req;
}
void setRequest(HttpServletRequest req) {
if (committed) {
throw new IllegalStateException("setPreProcessor() after comitted");
}
this.req = req;
}
HttpServletResponse getResponse() {
return resp;
}
void setResponse(HttpServletResponse resp) {
if (committed) {
throw new IllegalStateException("setPreProcessor() after comitted");
}
this.resp = resp;
}
AsyncContext getAsyncContext() {
return asyncCtx;
}
void setAsyncContext(AsyncContext asyncCtx) {
if (committed) {
throw new IllegalStateException("setPreProcessor() after comitted");
}
this.asyncCtx = asyncCtx;
setRequest((HttpServletRequest) asyncCtx.getRequest());
setResponse((HttpServletResponse) asyncCtx.getResponse());
}
Pattern[] getResourcePaths() {
return resPaths;
}
void setResourcePaths(Pattern[] resPaths) {
if (committed) {
throw new IllegalStateException("setPreProcessor() after comitted");
}
this.resPaths = resPaths;
}
long getDuration() {
return duration;
}
long getTimestamp() {
return timestamp;
}
/**
* Tests whether the general debug parameter was set to <code>true</code> or
* whether the optional debug query parameter (URL) is set to
* <code>true</code>.
*
* @return <code>true</code> if debugging for this request is enabled;
* otherwise <code>false</code>.
*/
public final boolean isDebugEnabled() {
return req != null && req.getParameter("debug") != null
|| (req.getAttribute("io.pictura.servlet.DEBUG") instanceof Boolean
&& (boolean) req.getAttribute("io.pictura.servlet.DEBUG"));
}
/**
* Checks if this request processor could execute in an asynchronous way.
*
* <p>
* Asynchronous operation is disabled for this processor if this request
* (servlet request) is within the scope of a filter or servlet that has not
* been annotated or flagged in the deployment descriptor as being able to
* support asynchronous handling.
*
* @return <code>true</code> if asynchronous operation is supported;
* otherwise <code>false</code>.
*/
public final boolean isAsyncSupported() {
return asyncCtx != null && req.isAsyncSupported();
}
/**
* Checks if this request processor is already committed.
*
* @return <code>true</code> if this request processor is already committed;
* otherwise <code>false</code>.
*
* @see #isCompleted()
* @see #isInterrupted()
*/
public final boolean isCommitted() {
return committed;
}
/**
* Checks if this request processor is already completed.
*
* @return <code>true</code> if this request processor is already completed;
* otherwise <code>false</code>.
*
* @see #isCommitted()
* @see #isInterrupted()
*/
public final boolean isCompleted() {
return completed;
}
/**
* Checks if this request processor was interrupted.
*
* <p>
* A request processor is interrupted (normally) after an error was send to
* the client.
*
* @return <code>true</code> if this request processor was interrupted;
* otherwise <code>false</code>.
*
* @see #isCommitted()
* @see #isCompleted()
*/
public final boolean isInterrupted() {
return interrupted;
}
/**
* Handles an interrupt on this request processor and sends an error
* response to the client using the <code>Internal Server Error</code>
* status code and clears the buffer (response).
*
* <p>
* If the related HTTP response has already been committed, this method
* throws an IllegalStateException.
*
* @throws IOException If an input or output exception occurs.
* @throws IllegalStateException If the response was committed before this
* method call.
*
* @see #doInterrupt(int)
* @see #doInterrupt(int, java.lang.String)
* @see #doInterrupt(int, java.lang.String, java.lang.Throwable)
*/
public final void doInterrupt() throws IOException, IllegalStateException {
this.doInterrupt(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null);
}
/**
* Handles an interrupt on this request processor and sends an error
* response to the client using the specified status code and clears the
* buffer (response).
*
* <p>
* If the related HTTP response has already been committed, this method
* throws an IllegalStateException.
*
* @param sc The error status code.
*
* @throws IOException If an input or output exception occurs.
* @throws IllegalStateException If the response was committed before this
* method call.
*
* @see #doInterrupt()
* @see #doInterrupt(int, java.lang.String)
* @see #doInterrupt(int, java.lang.String, java.lang.Throwable)
*/
public final void doInterrupt(int sc) throws IOException, IllegalStateException {
this.doInterrupt(sc, null);
}
/**
* Handles an interrupt on this request processor and sends an error
* response to the client using the specified status code and message and
* clears the buffer (response).
*
* <p>
* If the related HTTP response has already been committed, this method
* throws an IllegalStateException.
*
* @param sc The error status code.
* @param msg The error message.
*
* @throws IOException If an input or output exception occurs.
* @throws IllegalStateException If the response was committed before this
* method call.
*
* @see #doInterrupt()
* @see #doInterrupt(int)
* @see #doInterrupt(int, java.lang.String, java.lang.Throwable)
*/
public final void doInterrupt(int sc, String msg)
throws IOException, IllegalStateException {
this.doInterrupt(sc, msg, null);
}
/**
* Handles an interrupt on this request processor and sends an error
* response to the client using the specified status code and message and
* clears the buffer (response).
*
* <p>
* If the related HTTP response has already been committed, this method
* throws an IllegalStateException.
*
* <p>
* If the specified cause is an {@link IOException} this method will not
* send any data back to the client.
*
* @param sc The error status code.
* @param msg The error message.
* @param e The associated exception which is the cause of this interrupt
* method call.
*
* @throws IOException If an input or output exception occurs.
* @throws IllegalStateException If the response was committed before this
* method call.
*
* @see #doInterrupt()
* @see #doInterrupt(int)
* @see #doInterrupt(int, java.lang.String, java.lang.Throwable)
*/
public void doInterrupt(int sc, String msg, Throwable e)
throws IOException, IllegalStateException {
// Do nothing if the processor was already interrupted
if (interrupted) {
return;
}
interrupted = true;
// On an IO error it makes no sense to try to send a message to the
// client because it is not longer possible to send data to the client.
if (e instanceof IOException) {
return;
}
if (isCompleted()) {
throw new IllegalStateException("Request already completed.", e);
}
HttpServletResponse response = getResponse();
if (response == null || response.isCommitted()) {
throw new IllegalStateException("Response already committed.", e);
}
if (sc == HttpServletResponse.SC_NOT_MODIFIED) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.flushBuffer();
return;
}
response.reset();
if (msg != null) {
response.sendError(sc, msg);
} else {
response.sendError(sc);
}
}
/**
* Returns the full request URI from this request including optional query
* strings.
*
* @return The request URI.
*/
public final String getRequestURI() {
if (getRequest() != null) {
HttpServletRequest request = getRequest();
String ctxPath = request.getContextPath();
String uri = request.getRequestURI();
if (uri.startsWith("/" + ctxPath)) {
uri = uri.replaceFirst(ctxPath, "");
}
String reqUri = uri;
String reqQuery = request.getQueryString();
StringBuilder sb = new StringBuilder();
sb.append(reqUri);
if (reqQuery != null) {
sb.append("?").append(reqQuery);
}
return sb.toString();
}
return null;
}
/**
* Returns all resource locators which are associated with this request. The
* request processor will use this resource locators to handle all resource
* lookups in {@link #getResource(java.lang.String)}, too.
*
* @return The resource locators for this request.
*
* @see ResourceLocator
*/
public final ResourceLocator[] getResourceLocators() {
if (resLocators != null) {
return resLocators;
}
return null;
}
/**
* Sets the resource locators are used by this request processor to
* determine the URL of resources.
*
* @param resLocators The defined resource locators for this processor
* or <code>null</code> if there are no resource locators are set.
*
* @throws IllegalStateException if the method was called after the
* request processor was comitted.
*/
public final void setResourceLocators(ResourceLocator[] resLocators) {
if (committed) {
throw new IllegalStateException("setPreProcessor() after comitted");
}
this.resLocators = resLocators;
}
/**
* Tests whether the requested resource path is allowed to request. To test
* the method will use the defined resource path restrictions from the
* servlet init parameter.
*
* @param path The path to test.
* @return <code>true</code> if it is allowed to access the specified
* resource path; otherwise <code>false</code>.
*/
protected final boolean isAllowedResourcePath(String path) {
if (resPaths != null && resPaths.length > 0) {
Matcher m;
for (Pattern p : resPaths) {
m = p.matcher(path);
if (m.matches()) {
return true;
}
}
return false;
}
return true;
}
/**
* Returns an URL to the resource that is mapped to the given path.
* <p>
* This method returns <tt>null</tt> if no resource is mapped to the
* pathname or if it is not allowed to access the resource.
*
* @param path A <code>String</code> specifying the path to the resource.
* @return The resource located at the named path, or <tt>null</tt> if there
* is no resource at that path.
* @throws MalformedURLException if the pathname is not given in the correct
* form.
*
* @see URL
* @see #getResourceLocators()
*/
public URL getResource(String path) throws MalformedURLException {
if (!isAllowedResourcePath(path)) {
return null;
}
URL resource = null;
ResourceLocator[] locators = getResourceLocators();
if (locators != null) {
for (ResourceLocator rl : locators) {
resource = rl.getResource(path);
if (resource != null) {
break;
}
}
}
return resource;
}
/**
* Gets the first cookie with the specified name from this request if
* present.
*
* @param name The cookie name.
* @return The first cookie if present; otherwise <code>null</code>.
*
* @see Cookie
*/
public final Cookie getCookie(String name) {
if (req != null && name != null) {
Cookie[] cookies = req.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie c : cookies) {
if (c == null || !name.equals(c.getName())) {
continue;
}
return c;
}
}
}
return null;
}
/**
* Tests whether or not the request comes from a mobile device. To make the
* decision, this method reads the user agent string from the associated
* servlet request. If there is no user agent string is present, the method
* returns <code>false</code> as default.
*
* @return <code>true</code> if the request is from a mobile device.
*/
public boolean isMobileDeviceRequest() {
if (req != null) {
final String ua = req.getHeader(HEADER_USERAGENT);
return (ua != null && ua.contains("Mobi"));
}
return false;
}
/**
* Calculates a weight ETag based on the true cache key for this request.
*
* @return The ETag or <code>null</code> if the true cache key from this
* request is <code>null</code>, too.
*
* @see #getETag(byte[])
*/
public String getETag() {
String tck = getTrueCacheKey();
if (tck != null) {
return getETag(tck.getBytes());
}
return null;
}
/**
* Calculates a weight ETag based on the true cache key and the last
* modified timestamp of the given file object.
*
* @param f The file for which the ETag should calculate.
* @return The ETag or <code>null</code> if the true cache key or the given
* file is <code>null</code>.
*
* @see #getTrueCacheKey()
* @see #getETagByDate(long)
*/
public String getETagByFile(File f) {
if (f != null) {
return getETagByDate(f.lastModified());
}
return null;
}
/**
* Calculates a weight ETag based on the true cache key and the given date.
*
* @param date The date for which the ETag should calculate.
* @return The ETag or <code>null</code> if the true cache key is
* <code>null</code> or the given time less than 1.
*
* @see #getTrueCacheKey()
* @see #getETagByFile(java.io.File)
*/
public String getETagByDate(long date) {
if (date > 0) {
String tck = getTrueCacheKey();
if (tck != null && !tck.isEmpty()) {
StringBuilder s = new StringBuilder(tck);
s.append("#").append(date);
return getETag(s.toString().getBytes());
}
}
return null;
}
/**
* Calculates a weight ETag based on the specified data array.
*
* @param data The source data for which the ETag should be created.
*
* @return The ETag or <code>null</code> if it was not possible to calculate
* an ETag for the specified data array (e.g. if the data array was null).
*/
protected String getETag(byte[] data) {
if (data != null) {
try {
StringBuilder sb = new StringBuilder("W/\"");
byte[] md5 = getMD5(data);
for (int i = 0; i < md5.length; i++) {
sb.append(Integer.toString((md5[i] & 0xff) + 0x100, 16).substring(1));
}
sb.append("\"");
return sb.toString();
} catch (NoSuchAlgorithmException ex) {
// TODO: Is there an alternative required if MD5 is not available?
}
}
return null;
}
private byte[] getMD5(byte[] input) throws NoSuchAlgorithmException {
return MessageDigest.getInstance("MD5").digest(input);
}
/**
* Calculates a true cache key based on the requested resource (including
* all request parameters).
*
* @return The true cache key.
*
* @see HttpServletRequest
*/
public String getTrueCacheKey() {
if (trueCacheKey == null) {
trueCacheKey = getRequestURI();
}
return trueCacheKey;
}
/**
* Returns <code>true</code> if the response which is produced by this
* request processor is generally cacheable; otherwise <code>false</code>.
* <p>
* Generally means it is not a unique selling point and you have to obtain
* the cache-control headers, too.
*
* @return <code>true</code> if the produced response data is cacheable;
* otherwise <code>false</code>.
*/
@Override
public boolean isCacheable() {
return false;
}
/**
* Returns an unique request ID for this request. The UUID can be used in
* cases of troubleshooting if the UUID is logged with an associated
* exception. As default, if {@link #isDebugEnabled()} is <code>true</code>
* the request ID (UUID) will be automatically added to the response
* headers.
*
* @return A uniqe (anonymized) request ID for this request.
*/
public UUID getRequestId() {
if (requestId == null) {
if (req == null) {
throw new IllegalStateException("Request processor not yet initialized");
}
StringBuilder buf = new StringBuilder();
buf.append(timestamp);
try {
buf.append(req.getAttribute("io.pictura.servlet.SERVICE_NANO_TIMESTAMP") instanceof Long
? (long) req.getAttribute("io.pictura.servlet.SERVICE_NANO_TIMESTAMP") : "")
.append("Pictura/").append(Version.getVersionString())
.append(req.getServletContext().getServerInfo())
.append(req.getLocalAddr()).append(":").append(req.getLocalPort())
.append(req.getRemoteAddr()).append(":").append(req.getRemotePort())
.append(req.getRemoteUser() != null ? req.getRemoteUser() : "")
.append(req.getRequestURL()).append("?")
.append(req.getQueryString() != null ? req.getQueryString() : "");
} catch (RuntimeException ignore) {
}
requestId = UUID.nameUUIDFromBytes(buf.toString().getBytes());
}
return requestId;
}
/**
* Returns the value of the named attribute as an Object, or null if no
* attribute of the given name exists.
*
* @param name a String specifying the name of the attribute
* @return the named attribute as an Object, or null if no attribute of the
* given name exists.
*
* @throws IllegalStateException if the request processor was not yet
* initialized (there was no servlet request object set).
*
* @see #setAttribute(java.lang.String, java.lang.Object)
*/
public Object getAttribute(String name) {
if (req == null) {
throw new IllegalStateException("Request processor not yet initialized");
}
return req.getAttribute(name);
}
/**
* Stores an attribute in this request processor servelt request.
*
* @param name a String specifying the name of the attribute
* @param o the Object to be stored
*
* @throws IllegalStateException if the request processor was not yet
* initialized (there was no servlet request object set).
*
* @see #getAttribute(java.lang.String)
*/
public void setAttribute(String name, Object o) {
if (req == null) {
throw new IllegalStateException("Request processor not yet initialized");
}
req.setAttribute(name, o);
}
/**
* Called by the parent thread pool executor to handle (execute) this
* request processor in it's own background thread.
*/
@Override
public final void run() throws IllegalStateException {
if (committed) {
throw new IllegalStateException("Request processor already committed to process.");
}
committed = true;
long start = System.currentTimeMillis();
try {
HttpServletRequest request = getRequest();
if (request == null) {
throw new IllegalStateException("Servlet request is null.");
}
HttpServletResponse response = getResponse();
if (response == null) {
throw new IllegalStateException("Servlet response is null.");
}
req.setAttribute("io.pictura.servlet.REQUEST_ID", getRequestId().toString());
if (isDebugEnabled() || (boolean) req.getAttribute("io.pictura.servlet.HEADER_ADD_REQUEST_ID")) {
response.setHeader("X-Pictura-RequestId", getRequestId().toString());
}
try {
// Test if the user is allowed to send this request
if (req.getAttribute("io.pictura.servlet.IP_ADDRESS_MATCH") != null) {
final String[] ipAddrMatch = (String[]) req.getAttribute("io.pictura.servlet.IP_ADDRESS_MATCH");
boolean forbidden = true;
for (String ipAddrRange : ipAddrMatch) {
if (new IpAddressMatcher(ipAddrRange.trim()).matches(request.getRemoteAddr())) {
forbidden = false;
break;
}
}
if (forbidden) {
doInterrupt(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
if (!response.isCommitted()) {
// Append our true cache key if requested and possible
if (isCacheable() && (isDebugEnabled()
|| (Boolean) req.getAttribute("io.pictura.servlet.HEADER_ADD_TRUE_CACHE_KEY"))) {
response.setHeader("X-Pictura-TrueCacheKey", getTrueCacheKey());
}
if (getPreProcessor() != null) {
getPreProcessor().run();
}
doProcess(request, response);
}
} catch (Exception | Error e) {
request.setAttribute("io.pictura.servlet.REQUEST_PROCESSOR_THROWABLE", e);
if (!response.isCommitted()) {
try {
if (e instanceof IllegalArgumentException) {
doInterrupt(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
} else {
LOG.error("Internal server error. See nested exception for more details.", e);
doInterrupt(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"The request processor was not able to fullfill the request.", e);
throw new RuntimeException(e);
}
} catch (IOException e2) {
throw new RuntimeException(e2);
}
return;
}
LOG.error("Internal server error. See nested exception for more details.", e);
throw new RuntimeException(e);
}
} finally {
// Set status to complet
duration = System.currentTimeMillis() - start;
completed = true;
try {
if (req != null) {
req.setAttribute("io.pictura.servlet.PROC_DURATION", duration);
req.setAttribute("io.pictura.servlet.PROC_RUNTIME", runtime);
}
if (asyncCtx != null) {
asyncCtx.complete();
}
} catch (RuntimeException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Unknown runtime exception while finally request thread", e);
}
}
runFinalize();
}
}
/**
* Convenience method to clean-up resources after the response was sent.
*/
protected void runFinalize() {
}
/**
* Called by the {@link PicturaServlet} servlet (via the service method) to
* handle the request.
* <p>
* When implementing this method, read the request data, write the response
* headers, get the response's writer or output stream object, and finally,
* write the response data. It's best to include content type and encoding.
* When using a {@link PrintWriter} object to return the response, set the
* content type before accessing the {@link PrintWriter} object.
* <p>
* Where possible, set the <code>Content-Length</code> header (with the
* <code>ServletResponse.setContentLength(int)</code> method), to allow the
* servlet container to use a persistent connection to return its response
* to the client, improving performance. The content length is automatically
* set if the entire response fits inside the response buffer.
* <p>
* If the request is incorrectly formatted, <code>doProcess</code> should
* returns an HTTP "Bad Request" message.
*
* @param req An {@link HttpServletRequest} object that contains the request
* the client has made of the servlet.
* @param resp An {@link HttpServletResponse} object that contains the
* response the servlet sends to the client.
* @throws ServletException if an input or output error is detected when the
* servlet handles the GET request.
* @throws IOException if the request for the GET could not be handled.
*
* @see HttpServletRequest
* @see HttpServletResponse
*/
protected abstract void doProcess(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException;
/**
* Writes the given output data to the output stream which is defined by the
* given servlet response.
* <p>
* If the response is text based (not binary), e.g. the content type starts
* with <code>text/</code> and the data length is larger than 1k bytes and
* the client accepts <i>gzip</i> or <i>deflate</i>, the response content is
* automatically compressed and the content length header field will be
* correct.
*
* @param data The encoded image data.
* @param req The request object.
* @param resp The respnse object.
*
* @return Bytes sent or -1L if the process was already interrupted. Will
* return "0" in cases of "HEAD" requests.
*
* @throws ServletException if an input or output error is detected when the
* servlet handles the request.
* @throws IOException if the request for could not be handled.
*
* @see #doWrite(byte[], int, int, javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
protected long doWrite(final byte[] data, final HttpServletRequest req,
final HttpServletResponse resp) throws ServletException, IOException {
return doWrite(data, 0, data.length, req, resp);
}
/**
* Writes the specified range of the given output data to the output stream
* which is defined by the given servlet response.
* <p>
* If the response is text based (not binary), e.g. the content type starts
* with <code>text/</code> and the data length is larger than 1k bytes and
* the client accepts <i>gzip</i> or <i>deflate</i>, the response content is
* automatically compressed and the content length header field will be
* correct.
*
* @param data The encoded image data.
* @param off The start offset in the data.
* @param len The number of bytes to write.
* @param req The request object.
* @param resp The respnse object.
*
* @return Bytes sent or -1L if the process was already interrupted. Will
* return "0" in cases of "HEAD" requests.
*
* @throws ServletException if an input or output error is detected when the
* servlet handles the request.
* @throws IOException if the request for could not be handled.
*
* @since 1.1
*/
protected long doWrite(final byte[] data, final int off, final int len,
final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final int length = len - off;
if (!isInterrupted()) {
if (!isCacheable()) {
resp.setHeader(HEADER_CACHECONTROL, "no-cache");
resp.setHeader(HEADER_PRAGMA, "no-cache");
resp.setHeader(HEADER_EXPIRES, null);
}
if (isDebugEnabled()) {
if (getAttribute("io.pictura.servlet.BYTES_READ") instanceof Long) {
long clIn = (long) getAttribute("io.pictura.servlet.BYTES_READ");
resp.setHeader("X-Pictura-SavedData", String.valueOf(clIn - length));
}
}
// Do not compress resources <= 1kB
if (!"gzip".equalsIgnoreCase(resp.getHeader(HEADER_CONTENC))
&& !"deflate".equalsIgnoreCase(resp.getHeader(HEADER_CONTENC))
&& length > ((int) req.getAttribute("io.pictura.servlet.DEFLATER_COMPRESSION_MIN_SIZE"))
&& resp.getContentType() != null
&& isGZipAllowed(resp.getContentType())) {
String acceptEncoding = req.getHeader("Accept-Encoding");
FastByteArrayOutputStream bos = null;
DeflaterOutputStream dos = null;
if (acceptEncoding != null) {
if (acceptEncoding.contains("gzip")) {
dos = new GZIPOutputStream(bos = new FastByteArrayOutputStream()) {
{
def.setLevel((int) req.getAttribute("io.pictura.servlet.DEFLATER_COMPRESSION_LEVEL"));
}
};
resp.setHeader(HEADER_CONTENC, "gzip");
} else if (acceptEncoding.contains("deflate")) {
dos = new DeflaterOutputStream(bos = new FastByteArrayOutputStream()) {
{
def.setLevel((int) req.getAttribute("io.pictura.servlet.DEFLATER_COMPRESSION_LEVEL"));
}
};
resp.setHeader(HEADER_CONTENC, "deflate");
}
}
if (dos != null && bos != null) {
if ("HEAD".equalsIgnoreCase(req.getMethod())) {
return 0L;
}
dos.write(data, off, len);
dos.finish();
resp.setContentLength(bos.size());
bos.writeTo(resp.getOutputStream());
return bos.size();
}
}
resp.setContentLength(length);
if ("HEAD".equalsIgnoreCase(req.getMethod())) {
return 0L;
}
OutputStream os = new ContextOutputStream(req, resp.getOutputStream());
os.write(data, off, len);
return length;
}
return -1L;
}
// Allowed GZIP content types
private static final String[] GZIP_CONTENT_TYPES = new String[] {
"text/",
"application/json",
"application/javascript",
"application/x-javascript",
"application/xml",
"application/pdf",
"image/x-icon",
"image/svg+xml",
"image/vnd.microsoft.icon"
};
private boolean isGZipAllowed(String contentType) {
if (contentType == null || contentType.isEmpty()) {
return false;
}
for (String s : GZIP_CONTENT_TYPES) {
if (contentType.startsWith(s)) {
return true;
}
}
return false;
}
/**
* Matches a request based on IP Address or subnet mask matching against the
* remote address.
* <p>
* Both IPv6 and IPv4 addresses are supported, but a matcher which is
* configured with an IPv4 address will never match a request which returns
* an IPv6 address, and vice-versa.
* <p>
* <i>
* Derived from org.springframework.security/spring-security-web/
* 3.1.2.RELEASE/org/springframework/security/web/util/IpAddressMatcher.java.
* The origin source is licensed under the Apache License, Version 2.0
*/
private static final class IpAddressMatcher {
private final int nMaskBits;
private final InetAddress requiredAddress;
/**
* Takes a specific IP address or a range specified using the IP/Netmask
* (e.g. 192.168.1.0/24 or 202.24.0.0/14).
*
* @param ipAddress the address or range of addresses from which the
* request must come.
*/
IpAddressMatcher(String ipAddress) {
if (ipAddress.indexOf('/') > 0) {
String[] addressAndMask = ipAddress.split("/");
ipAddress = addressAndMask[0];
nMaskBits = Integer.parseInt(addressAndMask[1]);
} else {
nMaskBits = -1;
}
requiredAddress = parseAddress(ipAddress);
}
boolean matches(String address) {
InetAddress remoteAddress = parseAddress(address);
if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {
return false;
}
if (nMaskBits < 0) {
return remoteAddress.equals(requiredAddress);
}
byte[] remAddr = remoteAddress.getAddress();
byte[] reqAddr = requiredAddress.getAddress();
int oddBits = nMaskBits % 8;
int nMaskBytes = nMaskBits / 8 + (oddBits == 0 ? 0 : 1);
byte[] mask = new byte[nMaskBytes];
Arrays.fill(mask, 0, oddBits == 0 ? mask.length : mask.length - 1, (byte) 0xFF);
if (oddBits != 0) {
int finalByte = (1 << oddBits) - 1;
finalByte <<= 8 - oddBits;
mask[mask.length - 1] = (byte) finalByte;
}
for (int i = 0; i < mask.length; i++) {
if ((remAddr[i] & mask[i]) != (reqAddr[i] & mask[i])) {
return false;
}
}
return true;
}
private InetAddress parseAddress(String address) {
try {
return InetAddress.getByName(address);
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Failed to parse address" + address, e);
}
}
}
}
| servlet/src/main/java/io/pictura/servlet/RequestProcessor.java | /**
* Copyright 2015, 2016 Steffen Kremp
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.pictura.servlet;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This is the basic implementation of an request processor which will be
* executed for any {@link PicturaServlet} request.
*
* @see Runnable
*
* @author Steffen Kremp
*
* @since 1.0
*/
public abstract class RequestProcessor implements Runnable, Cacheable {
private static final Log LOG = Log.getLog(RequestProcessor.class);
// HTTP header field names
protected static final String HEADER_IFMODSINCE = "If-Modified-Since";
protected static final String HEADER_LASTMOD = "Last-Modified";
protected static final String HEADER_IFNONMATCH = "If-None-Match";
protected static final String HEADER_ETAG = "ETag";
protected static final String HEADER_DATE = "Date";
protected static final String HEADER_EXPIRES = "Expires";
protected static final String HEADER_PRAGMA = "Pragma";
protected static final String HEADER_CONNECTION = "Connection";
protected static final String HEADER_CACHECONTROL = "Cache-Control";
protected static final String HEADER_CONTACCEPT = "Content-Accept";
protected static final String HEADER_CONTENC = "Content-Encoding";
protected static final String HEADER_CONTLANG = "Content-Language";
protected static final String HEADER_CONTLOC = "Content-Location";
protected static final String HEADER_CONTTYPE = "Content-Type";
protected static final String HEADER_CONTLEN = "Content-Length";
protected static final String HEADER_LOCATION = "Location";
protected static final String HEADER_COOKIE = "Cookie";
protected static final String HEADER_VARY = "Vary";
protected static final String HEADER_ACCEPT = "Accept";
protected static final String HEADER_ACCEPTENC = "Accept-Encoding";
protected static final String HEADER_ALLOW = "Allow";
protected static final String HEADER_USERAGENT = "User-Agent";
// The associated servlet request and response object
private HttpServletRequest req;
private HttpServletResponse resp;
// Pre-process stuff
private Runnable preProcessor;
// State flags
private boolean committed;
private boolean completed;
private boolean interrupted;
// Context if the processor is running async
private AsyncContext asyncCtx;
private Pattern[] resPaths;
private ResourceLocator[] resLocators;
// A calculated "true" cache key for the response
private String trueCacheKey;
// Processor timestamps
private long duration;
private long runtime;
private final long timestamp;
// A unique request ID (for debugging purposes)
private UUID requestId;
/**
* Creates a new <code>RequestProcessor</code>.
*/
public RequestProcessor() {
this.duration = -1;
this.timestamp = System.currentTimeMillis();
}
/**
* Creates a new <code>RequestProcessor</code> based on the specified
* "origin" request processor.
*
* @param rp The base request processor.
*/
protected RequestProcessor(RequestProcessor rp) {
if (rp == null) {
throw new IllegalArgumentException("Origin request processor must be not null");
}
this.req = rp.getRequest();
this.resp = rp.getResponse();
// Optional
this.asyncCtx = rp.getAsyncContext();
this.resPaths = rp.getResourcePaths();
this.resLocators = rp.getResourceLocators();
this.preProcessor = rp.getPreProcessor();
this.duration = rp.duration;
this.timestamp = rp.timestamp;
this.committed = rp.committed;
this.completed = rp.completed;
this.interrupted = rp.interrupted;
this.requestId = rp.requestId;
}
Runnable getPreProcessor() {
return preProcessor;
}
void setPreProcessor(Runnable r) {
if (committed) {
throw new IllegalStateException("setPreProcessor() after comitted");
}
this.preProcessor = r;
}
HttpServletRequest getRequest() {
return req;
}
void setRequest(HttpServletRequest req) {
if (committed) {
throw new IllegalStateException("setPreProcessor() after comitted");
}
this.req = req;
}
HttpServletResponse getResponse() {
return resp;
}
void setResponse(HttpServletResponse resp) {
if (committed) {
throw new IllegalStateException("setPreProcessor() after comitted");
}
this.resp = resp;
}
AsyncContext getAsyncContext() {
return asyncCtx;
}
void setAsyncContext(AsyncContext asyncCtx) {
if (committed) {
throw new IllegalStateException("setPreProcessor() after comitted");
}
this.asyncCtx = asyncCtx;
setRequest((HttpServletRequest) asyncCtx.getRequest());
setResponse((HttpServletResponse) asyncCtx.getResponse());
}
Pattern[] getResourcePaths() {
return resPaths;
}
void setResourcePaths(Pattern[] resPaths) {
if (committed) {
throw new IllegalStateException("setPreProcessor() after comitted");
}
this.resPaths = resPaths;
}
long getDuration() {
return duration;
}
long getTimestamp() {
return timestamp;
}
/**
* Tests whether the general debug parameter was set to <code>true</code> or
* whether the optional debug query parameter (URL) is set to
* <code>true</code>.
*
* @return <code>true</code> if debugging is enabled; otherwise
* <code>false</code>.
*/
public final boolean isDebugEnabled() {
return req != null && req.getParameter("debug") != null
|| (req.getAttribute("io.pictura.servlet.DEBUG") instanceof Boolean
&& (boolean) req.getAttribute("io.pictura.servlet.DEBUG"));
}
/**
* Checks if this request processor could execute in an asynchronous way.
*
* <p>
* Asynchronous operation is disabled for this processor if this request
* (servlet request) is within the scope of a filter or servlet that has not
* been annotated or flagged in the deployment descriptor as being able to
* support asynchronous handling.
*
* @return <code>true</code> if asynchronous operation is supported;
* otherwise <code>false</code>.
*/
public final boolean isAsyncSupported() {
return asyncCtx != null && req.isAsyncSupported();
}
/**
* Checks if this request processor is already committed.
*
* @return <code>true</code> if this request processor is already committed;
* otherwise <code>false</code>.
*
* @see #isCompleted()
* @see #isInterrupted()
*/
public final boolean isCommitted() {
return committed;
}
/**
* Checks if this request processor is already completed.
*
* @return <code>true</code> if this request processor is already completed;
* otherwise <code>false</code>.
*
* @see #isCommitted()
* @see #isInterrupted()
*/
public final boolean isCompleted() {
return completed;
}
/**
* Checks if this request processor was interrupted.
*
* <p>
* A request processor is interrupted (normally) after an error was send to
* the client.
*
* @return <code>true</code> if this request processor was interrupted;
* otherwise <code>false</code>.
*
* @see #isCommitted()
* @see #isCompleted()
*/
public final boolean isInterrupted() {
return interrupted;
}
/**
* Handles an interrupt on this request processor and sends an error
* response to the client using the <code>Internal Server Error</code>
* status code and clears the buffer (response).
*
* <p>
* If the related HTTP response has already been committed, this method
* throws an IllegalStateException.
*
* @throws IOException If an input or output exception occurs.
* @throws IllegalStateException If the response was committed before this
* method call.
*
* @see #doInterrupt(int)
* @see #doInterrupt(int, java.lang.String)
* @see #doInterrupt(int, java.lang.String, java.lang.Throwable)
*/
public final void doInterrupt() throws IOException, IllegalStateException {
this.doInterrupt(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null);
}
/**
* Handles an interrupt on this request processor and sends an error
* response to the client using the specified status code and clears the
* buffer (response).
*
* <p>
* If the related HTTP response has already been committed, this method
* throws an IllegalStateException.
*
* @param sc The error status code.
*
* @throws IOException If an input or output exception occurs.
* @throws IllegalStateException If the response was committed before this
* method call.
*
* @see #doInterrupt()
* @see #doInterrupt(int, java.lang.String)
* @see #doInterrupt(int, java.lang.String, java.lang.Throwable)
*/
public final void doInterrupt(int sc) throws IOException, IllegalStateException {
this.doInterrupt(sc, null);
}
/**
* Handles an interrupt on this request processor and sends an error
* response to the client using the specified status code and message and
* clears the buffer (response).
*
* <p>
* If the related HTTP response has already been committed, this method
* throws an IllegalStateException.
*
* @param sc The error status code.
* @param msg The error message.
*
* @throws IOException If an input or output exception occurs.
* @throws IllegalStateException If the response was committed before this
* method call.
*
* @see #doInterrupt()
* @see #doInterrupt(int)
* @see #doInterrupt(int, java.lang.String, java.lang.Throwable)
*/
public final void doInterrupt(int sc, String msg)
throws IOException, IllegalStateException {
this.doInterrupt(sc, msg, null);
}
/**
* Handles an interrupt on this request processor and sends an error
* response to the client using the specified status code and message and
* clears the buffer (response).
*
* <p>
* If the related HTTP response has already been committed, this method
* throws an IllegalStateException.
*
* <p>
* If the specified cause is an {@link IOException} this method will not
* send any data back to the client.
*
* @param sc The error status code.
* @param msg The error message.
* @param e The associated exception which is the cause of this interrupt
* method call.
*
* @throws IOException If an input or output exception occurs.
* @throws IllegalStateException If the response was committed before this
* method call.
*
* @see #doInterrupt()
* @see #doInterrupt(int)
* @see #doInterrupt(int, java.lang.String, java.lang.Throwable)
*/
public void doInterrupt(int sc, String msg, Throwable e)
throws IOException, IllegalStateException {
// Do nothing if the processor was already interrupted
if (interrupted) {
return;
}
interrupted = true;
// On an IO error it makes no sense to try to send a message to the
// client because it is not longer possible to send data to the client.
if (e instanceof IOException) {
return;
}
if (isCompleted()) {
throw new IllegalStateException("Request already completed.", e);
}
HttpServletResponse response = getResponse();
if (response == null || response.isCommitted()) {
throw new IllegalStateException("Response already committed.", e);
}
if (sc == HttpServletResponse.SC_NOT_MODIFIED) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.flushBuffer();
return;
}
response.reset();
if (msg != null) {
response.sendError(sc, msg);
} else {
response.sendError(sc);
}
}
/**
* Returns the full request URI from this request including optional query
* strings.
*
* @return The request URI.
*/
public final String getRequestURI() {
if (getRequest() != null) {
HttpServletRequest request = getRequest();
String ctxPath = request.getContextPath();
String uri = request.getRequestURI();
if (uri.startsWith("/" + ctxPath)) {
uri = uri.replaceFirst(ctxPath, "");
}
String reqUri = uri;
String reqQuery = request.getQueryString();
StringBuilder sb = new StringBuilder();
sb.append(reqUri);
if (reqQuery != null) {
sb.append("?").append(reqQuery);
}
return sb.toString();
}
return null;
}
/**
* Returns all resource locators which are associated with this request. The
* request processor will use this resource locators to handle all resource
* lookups in {@link #getResource(java.lang.String)}, too.
*
* @return The resource locators for this request.
*
* @see ResourceLocator
*/
public final ResourceLocator[] getResourceLocators() {
if (resLocators != null) {
return resLocators;
}
return null;
}
/**
* Sets the resource locators are used by this request processor to
* determine the URL of resources.
*
* @param resLocators The defined resource locators for this processor
* or <code>null</code> if there are no resource locators are set.
*
* @throws IllegalStateException if the method was called after the
* request processor was comitted.
*/
public final void setResourceLocators(ResourceLocator[] resLocators) {
if (committed) {
throw new IllegalStateException("setPreProcessor() after comitted");
}
this.resLocators = resLocators;
}
/**
* Tests whether the requested resource path is allowed to request. To test
* the method will use the defined resource path restrictions from the
* servlet init parameter.
*
* @param path The path to test.
* @return <code>true</code> if it is allowed to access the specified
* resource path; otherwise <code>false</code>.
*/
protected final boolean isAllowedResourcePath(String path) {
if (resPaths != null && resPaths.length > 0) {
Matcher m;
for (Pattern p : resPaths) {
m = p.matcher(path);
if (m.matches()) {
return true;
}
}
return false;
}
return true;
}
/**
* Returns an URL to the resource that is mapped to the given path.
* <p>
* This method returns <tt>null</tt> if no resource is mapped to the
* pathname or if it is not allowed to access the resource.
*
* @param path A <code>String</code> specifying the path to the resource.
* @return The resource located at the named path, or <tt>null</tt> if there
* is no resource at that path.
* @throws MalformedURLException if the pathname is not given in the correct
* form.
*
* @see URL
* @see #getResourceLocators()
*/
public URL getResource(String path) throws MalformedURLException {
if (!isAllowedResourcePath(path)) {
return null;
}
URL resource = null;
ResourceLocator[] locators = getResourceLocators();
if (locators != null) {
for (ResourceLocator rl : locators) {
resource = rl.getResource(path);
if (resource != null) {
break;
}
}
}
return resource;
}
/**
* Gets the first cookie with the specified name from this request if
* present.
*
* @param name The cookie name.
* @return The first cookie if present; otherwise <code>null</code>.
*
* @see Cookie
*/
public final Cookie getCookie(String name) {
if (req != null && name != null) {
Cookie[] cookies = req.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie c : cookies) {
if (c == null || !name.equals(c.getName())) {
continue;
}
return c;
}
}
}
return null;
}
/**
* Tests whether or not the request comes from a mobile device. To make the
* decision, this method reads the user agent string from the associated
* servlet request. If there is no user agent string is present, the method
* returns <code>false</code> as default.
*
* @return <code>true</code> if the request is from a mobile device.
*/
public boolean isMobileDeviceRequest() {
if (req != null) {
final String ua = req.getHeader(HEADER_USERAGENT);
return (ua != null && ua.contains("Mobi"));
}
return false;
}
/**
* Calculates a weight ETag based on the true cache key for this request.
*
* @return The ETag or <code>null</code> if the true cache key from this
* request is <code>null</code>, too.
*
* @see #getETag(byte[])
*/
public String getETag() {
String tck = getTrueCacheKey();
if (tck != null) {
return getETag(tck.getBytes());
}
return null;
}
/**
* Calculates a weight ETag based on the true cache key and the last
* modified timestamp of the given file object.
*
* @param f The file for which the ETag should calculate.
* @return The ETag or <code>null</code> if the true cache key or the given
* file is <code>null</code>.
*
* @see #getTrueCacheKey()
* @see #getETagByDate(long)
*/
public String getETagByFile(File f) {
if (f != null) {
return getETagByDate(f.lastModified());
}
return null;
}
/**
* Calculates a weight ETag based on the true cache key and the given date.
*
* @param date The date for which the ETag should calculate.
* @return The ETag or <code>null</code> if the true cache key is
* <code>null</code> or the given time less than 1.
*
* @see #getTrueCacheKey()
* @see #getETagByFile(java.io.File)
*/
public String getETagByDate(long date) {
if (date > 0) {
String tck = getTrueCacheKey();
if (tck != null && !tck.isEmpty()) {
StringBuilder s = new StringBuilder(tck);
s.append("#").append(date);
return getETag(s.toString().getBytes());
}
}
return null;
}
/**
* Calculates a weight ETag based on the specified data array.
*
* @param data The source data for which the ETag should be created.
*
* @return The ETag or <code>null</code> if it was not possible to calculate
* an ETag for the specified data array (e.g. if the data array was null).
*/
protected String getETag(byte[] data) {
if (data != null) {
try {
StringBuilder sb = new StringBuilder("W/\"");
byte[] md5 = getMD5(data);
for (int i = 0; i < md5.length; i++) {
sb.append(Integer.toString((md5[i] & 0xff) + 0x100, 16).substring(1));
}
sb.append("\"");
return sb.toString();
} catch (NoSuchAlgorithmException ex) {
// TODO: Is there an alternative required if MD5 is not available?
}
}
return null;
}
private byte[] getMD5(byte[] input) throws NoSuchAlgorithmException {
return MessageDigest.getInstance("MD5").digest(input);
}
/**
* Calculates a true cache key based on the requested resource (including
* all request parameters).
*
* @return The true cache key.
*
* @see HttpServletRequest
*/
public String getTrueCacheKey() {
if (trueCacheKey == null) {
trueCacheKey = getRequestURI();
}
return trueCacheKey;
}
/**
* Returns <code>true</code> if the response which is produced by this
* request processor is generally cacheable; otherwise <code>false</code>.
* <p>
* Generally means it is not a unique selling point and you have to obtain
* the cache-control headers, too.
*
* @return <code>true</code> if the produced response data is cacheable;
* otherwise <code>false</code>.
*/
@Override
public boolean isCacheable() {
return false;
}
/**
* Returns an unique request ID for this request. The UUID can be used in
* cases of troubleshooting if the UUID is logged with an associated
* exception. As default, if {@link #isDebugEnabled()} is <code>true</code>
* the request ID (UUID) will be automatically added to the response
* headers.
*
* @return A uniqe (anonymized) request ID for this request.
*/
public UUID getRequestId() {
if (requestId == null) {
if (req == null) {
throw new IllegalStateException("Request processor not yet initialized");
}
StringBuilder buf = new StringBuilder();
buf.append(timestamp);
try {
buf.append(req.getAttribute("io.pictura.servlet.SERVICE_NANO_TIMESTAMP") instanceof Long
? (long) req.getAttribute("io.pictura.servlet.SERVICE_NANO_TIMESTAMP") : "")
.append("Pictura/").append(Version.getVersionString())
.append(req.getServletContext().getServerInfo())
.append(req.getLocalAddr()).append(":").append(req.getLocalPort())
.append(req.getRemoteAddr()).append(":").append(req.getRemotePort())
.append(req.getRemoteUser() != null ? req.getRemoteUser() : "")
.append(req.getRequestURL()).append("?")
.append(req.getQueryString() != null ? req.getQueryString() : "");
} catch (RuntimeException ignore) {
}
requestId = UUID.nameUUIDFromBytes(buf.toString().getBytes());
}
return requestId;
}
/**
* Returns the value of the named attribute as an Object, or null if no
* attribute of the given name exists.
*
* @param name a String specifying the name of the attribute
* @return the named attribute as an Object, or null if no attribute of the
* given name exists.
*
* @throws IllegalStateException if the request processor was not yet
* initialized (there was no servlet request object set).
*
* @see #setAttribute(java.lang.String, java.lang.Object)
*/
public Object getAttribute(String name) {
if (req == null) {
throw new IllegalStateException("Request processor not yet initialized");
}
return req.getAttribute(name);
}
/**
* Stores an attribute in this request processor servelt request.
*
* @param name a String specifying the name of the attribute
* @param o the Object to be stored
*
* @throws IllegalStateException if the request processor was not yet
* initialized (there was no servlet request object set).
*
* @see #getAttribute(java.lang.String)
*/
public void setAttribute(String name, Object o) {
if (req == null) {
throw new IllegalStateException("Request processor not yet initialized");
}
req.setAttribute(name, o);
}
/**
* Called by the parent thread pool executor to handle (execute) this
* request processor in it's own background thread.
*/
@Override
public final void run() throws IllegalStateException {
if (committed) {
throw new IllegalStateException("Request processor already committed to process.");
}
committed = true;
long start = System.currentTimeMillis();
try {
HttpServletRequest request = getRequest();
if (request == null) {
throw new IllegalStateException("Servlet request is null.");
}
HttpServletResponse response = getResponse();
if (response == null) {
throw new IllegalStateException("Servlet response is null.");
}
req.setAttribute("io.pictura.servlet.REQUEST_ID", getRequestId().toString());
if (isDebugEnabled() || (boolean) req.getAttribute("io.pictura.servlet.HEADER_ADD_REQUEST_ID")) {
response.setHeader("X-Pictura-RequestId", getRequestId().toString());
}
try {
// Test if the user is allowed to send this request
if (req.getAttribute("io.pictura.servlet.IP_ADDRESS_MATCH") != null) {
final String[] ipAddrMatch = (String[]) req.getAttribute("io.pictura.servlet.IP_ADDRESS_MATCH");
boolean forbidden = true;
for (String ipAddrRange : ipAddrMatch) {
if (new IpAddressMatcher(ipAddrRange.trim()).matches(request.getRemoteAddr())) {
forbidden = false;
break;
}
}
if (forbidden) {
doInterrupt(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
if (!response.isCommitted()) {
// Append our true cache key if requested and possible
if (isCacheable() && (isDebugEnabled()
|| (Boolean) req.getAttribute("io.pictura.servlet.HEADER_ADD_TRUE_CACHE_KEY"))) {
response.setHeader("X-Pictura-TrueCacheKey", getTrueCacheKey());
}
if (getPreProcessor() != null) {
getPreProcessor().run();
}
doProcess(request, response);
}
} catch (Exception | Error e) {
request.setAttribute("io.pictura.servlet.REQUEST_PROCESSOR_THROWABLE", e);
if (!response.isCommitted()) {
try {
if (e instanceof IllegalArgumentException) {
doInterrupt(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
} else {
LOG.error("Internal server error. See nested exception for more details.", e);
doInterrupt(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"The request processor was not able to fullfill the request.", e);
throw new RuntimeException(e);
}
} catch (IOException e2) {
throw new RuntimeException(e2);
}
return;
}
LOG.error("Internal server error. See nested exception for more details.", e);
throw new RuntimeException(e);
}
} finally {
// Set status to complet
duration = System.currentTimeMillis() - start;
completed = true;
try {
if (req != null) {
req.setAttribute("io.pictura.servlet.PROC_DURATION", duration);
req.setAttribute("io.pictura.servlet.PROC_RUNTIME", runtime);
}
if (asyncCtx != null) {
asyncCtx.complete();
}
} catch (RuntimeException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Unknown runtime exception while finally request thread", e);
}
}
runFinalize();
}
}
/**
* Convenience method to clean-up resources after the response was sent.
*/
protected void runFinalize() {
}
/**
* Called by the {@link PicturaServlet} servlet (via the service method) to
* handle the request.
* <p>
* When implementing this method, read the request data, write the response
* headers, get the response's writer or output stream object, and finally,
* write the response data. It's best to include content type and encoding.
* When using a {@link PrintWriter} object to return the response, set the
* content type before accessing the {@link PrintWriter} object.
* <p>
* Where possible, set the <code>Content-Length</code> header (with the
* <code>ServletResponse.setContentLength(int)</code> method), to allow the
* servlet container to use a persistent connection to return its response
* to the client, improving performance. The content length is automatically
* set if the entire response fits inside the response buffer.
* <p>
* If the request is incorrectly formatted, <code>doProcess</code> should
* returns an HTTP "Bad Request" message.
*
* @param req An {@link HttpServletRequest} object that contains the request
* the client has made of the servlet.
* @param resp An {@link HttpServletResponse} object that contains the
* response the servlet sends to the client.
* @throws ServletException if an input or output error is detected when the
* servlet handles the GET request.
* @throws IOException if the request for the GET could not be handled.
*
* @see HttpServletRequest
* @see HttpServletResponse
*/
protected abstract void doProcess(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException;
/**
* Writes the given output data to the output stream which is defined by the
* given servlet response.
* <p>
* If the response is text based (not binary), e.g. the content type starts
* with <code>text/</code> and the data length is larger than 1k bytes and
* the client accepts <i>gzip</i> or <i>deflate</i>, the response content is
* automatically compressed and the content length header field will be
* correct.
*
* @param data The encoded image data.
* @param req The request object.
* @param resp The respnse object.
*
* @return Bytes sent or -1L if the process was already interrupted. Will
* return "0" in cases of "HEAD" requests.
*
* @throws ServletException if an input or output error is detected when the
* servlet handles the request.
* @throws IOException if the request for could not be handled.
*
* @see #doWrite(byte[], int, int, javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
protected long doWrite(final byte[] data, final HttpServletRequest req,
final HttpServletResponse resp) throws ServletException, IOException {
return doWrite(data, 0, data.length, req, resp);
}
/**
* Writes the specified range of the given output data to the output stream
* which is defined by the given servlet response.
* <p>
* If the response is text based (not binary), e.g. the content type starts
* with <code>text/</code> and the data length is larger than 1k bytes and
* the client accepts <i>gzip</i> or <i>deflate</i>, the response content is
* automatically compressed and the content length header field will be
* correct.
*
* @param data The encoded image data.
* @param off The start offset in the data.
* @param len The number of bytes to write.
* @param req The request object.
* @param resp The respnse object.
*
* @return Bytes sent or -1L if the process was already interrupted. Will
* return "0" in cases of "HEAD" requests.
*
* @throws ServletException if an input or output error is detected when the
* servlet handles the request.
* @throws IOException if the request for could not be handled.
*
* @since 1.1
*/
protected long doWrite(final byte[] data, final int off, final int len,
final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final int length = len - off;
if (!isInterrupted()) {
if (!isCacheable()) {
resp.setHeader(HEADER_CACHECONTROL, "no-cache");
resp.setHeader(HEADER_PRAGMA, "no-cache");
resp.setHeader(HEADER_EXPIRES, null);
}
// Do not compress resources <= 1kB
if (!"gzip".equalsIgnoreCase(resp.getHeader(HEADER_CONTENC))
&& !"deflate".equalsIgnoreCase(resp.getHeader(HEADER_CONTENC))
&& length > ((int) req.getAttribute("io.pictura.servlet.DEFLATER_COMPRESSION_MIN_SIZE"))
&& resp.getContentType() != null
&& isGZipAllowed(resp.getContentType())) {
String acceptEncoding = req.getHeader("Accept-Encoding");
FastByteArrayOutputStream bos = null;
DeflaterOutputStream dos = null;
if (acceptEncoding != null) {
if (acceptEncoding.contains("gzip")) {
dos = new GZIPOutputStream(bos = new FastByteArrayOutputStream()) {
{
def.setLevel((int) req.getAttribute("io.pictura.servlet.DEFLATER_COMPRESSION_LEVEL"));
}
};
resp.setHeader(HEADER_CONTENC, "gzip");
} else if (acceptEncoding.contains("deflate")) {
dos = new DeflaterOutputStream(bos = new FastByteArrayOutputStream()) {
{
def.setLevel((int) req.getAttribute("io.pictura.servlet.DEFLATER_COMPRESSION_LEVEL"));
}
};
resp.setHeader(HEADER_CONTENC, "deflate");
}
}
if (dos != null && bos != null) {
if ("HEAD".equalsIgnoreCase(req.getMethod())) {
return 0L;
}
dos.write(data, off, len);
dos.finish();
resp.setContentLength(bos.size());
bos.writeTo(resp.getOutputStream());
return bos.size();
}
}
resp.setContentLength(length);
if ("HEAD".equalsIgnoreCase(req.getMethod())) {
return 0L;
}
OutputStream os = new ContextOutputStream(req, resp.getOutputStream());
os.write(data, off, len);
return length;
}
return -1L;
}
// Allowed GZIP content types
private static final String[] GZIP_CONTENT_TYPES = new String[] {
"text/",
"application/json",
"application/javascript",
"application/x-javascript",
"application/xml",
"application/pdf",
"image/x-icon",
"image/svg+xml",
"image/vnd.microsoft.icon"
};
private boolean isGZipAllowed(String contentType) {
if (contentType == null || contentType.isEmpty()) {
return false;
}
for (String s : GZIP_CONTENT_TYPES) {
if (contentType.startsWith(s)) {
return true;
}
}
return false;
}
/**
* Matches a request based on IP Address or subnet mask matching against the
* remote address.
* <p>
* Both IPv6 and IPv4 addresses are supported, but a matcher which is
* configured with an IPv4 address will never match a request which returns
* an IPv6 address, and vice-versa.
* <p>
* <i>
* Derived from org.springframework.security/spring-security-web/
* 3.1.2.RELEASE/org/springframework/security/web/util/IpAddressMatcher.java.
* The origin source is licensed under the Apache License, Version 2.0
*/
private static final class IpAddressMatcher {
private final int nMaskBits;
private final InetAddress requiredAddress;
/**
* Takes a specific IP address or a range specified using the IP/Netmask
* (e.g. 192.168.1.0/24 or 202.24.0.0/14).
*
* @param ipAddress the address or range of addresses from which the
* request must come.
*/
IpAddressMatcher(String ipAddress) {
if (ipAddress.indexOf('/') > 0) {
String[] addressAndMask = ipAddress.split("/");
ipAddress = addressAndMask[0];
nMaskBits = Integer.parseInt(addressAndMask[1]);
} else {
nMaskBits = -1;
}
requiredAddress = parseAddress(ipAddress);
}
boolean matches(String address) {
InetAddress remoteAddress = parseAddress(address);
if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {
return false;
}
if (nMaskBits < 0) {
return remoteAddress.equals(requiredAddress);
}
byte[] remAddr = remoteAddress.getAddress();
byte[] reqAddr = requiredAddress.getAddress();
int oddBits = nMaskBits % 8;
int nMaskBytes = nMaskBits / 8 + (oddBits == 0 ? 0 : 1);
byte[] mask = new byte[nMaskBytes];
Arrays.fill(mask, 0, oddBits == 0 ? mask.length : mask.length - 1, (byte) 0xFF);
if (oddBits != 0) {
int finalByte = (1 << oddBits) - 1;
finalByte <<= 8 - oddBits;
mask[mask.length - 1] = (byte) finalByte;
}
for (int i = 0; i < mask.length; i++) {
if ((remAddr[i] & mask[i]) != (reqAddr[i] & mask[i])) {
return false;
}
}
return true;
}
private InetAddress parseAddress(String address) {
try {
return InetAddress.getByName(address);
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Failed to parse address" + address, e);
}
}
}
}
| Added new debug response header X-Pictura-SavedData | servlet/src/main/java/io/pictura/servlet/RequestProcessor.java | Added new debug response header X-Pictura-SavedData | <ide><path>ervlet/src/main/java/io/pictura/servlet/RequestProcessor.java
<ide> * whether the optional debug query parameter (URL) is set to
<ide> * <code>true</code>.
<ide> *
<del> * @return <code>true</code> if debugging is enabled; otherwise
<del> * <code>false</code>.
<add> * @return <code>true</code> if debugging for this request is enabled;
<add> * otherwise <code>false</code>.
<ide> */
<ide> public final boolean isDebugEnabled() {
<ide> return req != null && req.getParameter("debug") != null
<ide> resp.setHeader(HEADER_PRAGMA, "no-cache");
<ide> resp.setHeader(HEADER_EXPIRES, null);
<ide> }
<add>
<add> if (isDebugEnabled()) {
<add> if (getAttribute("io.pictura.servlet.BYTES_READ") instanceof Long) {
<add> long clIn = (long) getAttribute("io.pictura.servlet.BYTES_READ");
<add> resp.setHeader("X-Pictura-SavedData", String.valueOf(clIn - length));
<add> }
<add> }
<ide>
<ide> // Do not compress resources <= 1kB
<ide> if (!"gzip".equalsIgnoreCase(resp.getHeader(HEADER_CONTENC)) |
|
JavaScript | mit | 9a839b676dbe2e228dd98e5f9fdd34558a86033c | 0 | alexn1/qforms,alexn1/qforms,alexn1/qforms | const months = [
'Январь', 'Февраль',
'Март', 'Апрель', 'Май',
'Июнь', 'Июль', 'Август',
'Сентябрь', 'Октябрь', 'Ноябрь',
'Декабрь'
];
class DatePicker {
constructor(el) {
console.log('DatePicker.constructor', el);
this.el = el;
this.year = null;
this.month = null;
this.selectedYear = null;
this.selectedMonth = null;
this.selectedDate = null;
this.onDateSelected = null;
this.el.addEventListener('click', this.onClick.bind(this));
this.el.addEventListener('mousedown', (e) => {
// console.log('mousedown', e);
e.preventDefault();
e.stopPropagation();
return false;
});
}
onClick(e) {
// console.log('DatePicker.onClick', e);
if (e.target === this.getNext()) {
return this.onNext();
} else if (e.target === this.getPrev()) {
return this.onPrev();
} else if (e.target.nodeName === 'TD' && e.target.classList.contains('selectable')) {
return this.onDateClick(e.target);
}
}
onDateClick(target) {
// console.log('DatePicker.onDateClick', target.dataset);
if (this.onDateSelected) {
this.selectedYear = parseInt(target.dataset.year);
this.selectedMonth = parseInt(target.dataset.month);
this.selectedDate = parseInt(target.dataset.date);
const date = new Date(this.selectedYear, this.selectedMonth, this.selectedDate);
// console.log('date:', date);
this.onDateSelected(date);
}
}
onNext() {
// console.log('DatePicker.onNext');
if (this.year === null) throw new Error('no current year');
if (this.month === null) throw new Error('no current month');
const next = new Date(this.year, this.month);
next.setMonth(next.getMonth() + 1);
this.setYearMonth(next.getFullYear(), next.getMonth());
}
onPrev() {
// console.log('DatePicker.onPrev');
if (this.year === null) throw new Error('no current year');
if (this.month === null) throw new Error('no current month');
const next = new Date(this.year, this.month);
next.setMonth(next.getMonth() - 1);
this.setYearMonth(next.getFullYear(), next.getMonth());
}
getCaption() {
return this.el.querySelector('caption > div > span');
}
getNext() {
return this.el.querySelector('caption > div > a.next');
}
getPrev() {
return this.el.querySelector('caption > div > a.prev');
}
static getDay(date) {
let day = date.getDay() - 1;
if (day === -1) day = 6;
return day;
}
isDateSelected() {
return this.selectedYear !== null && this.selectedMonth && this.selectedDate;
}
setSelectedDate(year, month, date) {
this.selectedYear = year;
this.selectedMonth = month;
this.selectedDate = date;
}
setYearMonth(year, month) {
console.log('DatePicker.setYearMonth', year, month);
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
if (year === undefined) year = today.getFullYear();
if (month === undefined) month = today.getMonth();
this.year = year;
this.month = month;
const date = new Date(year, month, 1); // first day of month
let day = DatePicker.getDay(date);
if (day === 0) {
date.setDate(date.getDate() - 7); // first day of table
} else {
date.setDate(date.getDate() - day); // first day of table
}
// caption
this.getCaption().innerText = `${months[month]}, ${year}`;
// days
const tds = this.el.querySelectorAll('td');
for (let i = 0; i < 42; i++) {
tds[i].innerText = date.getDate().toString();
tds[i].dataset.year = date.getFullYear();
tds[i].dataset.month = date.getMonth();
tds[i].dataset.date = date.getDate();
if (date.getMonth() !== month) {
tds[i].classList.add('out');
} else {
tds[i].classList.remove('out');
}
if (date >= today) {
tds[i].classList.add('selectable');
} else {
tds[i].classList.remove('selectable');
}
if (date.getTime() === today.getTime()) {
tds[i].classList.add('today');
} else {
tds[i].classList.remove('today');
}
if (date.getFullYear() === this.selectedYear && date.getMonth() === this.selectedMonth && date.getDate() === this.selectedDate) {
tds[i].classList.add('selected');
} else {
tds[i].classList.remove('selected');
}
date.setDate(date.getDate() + 1);
}
}
}
| gui/datepicker/DatePicker/DatePicker.js | const months = [
'Январь', 'Февраль',
'Март', 'Апрель', 'Май',
'Июнь', 'Июль', 'Август',
'Сентябрь', 'Октябрь', 'Ноябрь',
'Декабрь'
];
class DatePicker {
constructor(el) {
console.log('DatePicker.constructor', el);
this.el = el;
this.year = null;
this.month = null;
this.selectedYear = null;
this.selectedMonth = null;
this.selectedDate = null;
this.onDateSelected = null;
this.el.addEventListener('click', this.onClick.bind(this));
this.el.addEventListener('mousedown', (e) => {
// console.log('mousedown', e);
e.preventDefault();
e.stopPropagation();
return false;
});
}
onClick(e) {
// console.log('DatePicker.onClick', e);
if (e.target === this.getNext()) {
return this.onNext();
} else if (e.target === this.getPrev()) {
return this.onPrev();
} else if (e.target.nodeName === 'TD' && e.target.classList.contains('selectable')) {
return this.onDateClick(e.target);
}
}
onDateClick(target) {
// console.log('DatePicker.onDateClick', target.dataset);
if (this.onDateSelected) {
this.selectedYear = parseInt(target.dataset.year);
this.selectedMonth = parseInt(target.dataset.month);
this.selectedDate = parseInt(target.dataset.date);
const date = new Date(this.selectedYear, this.selectedMonth, this.selectedDate);
// console.log('date:', date);
this.onDateSelected(date);
}
}
onNext() {
// console.log('DatePicker.onNext');
if (this.year === null) throw new Error('no current year');
if (this.month === null) throw new Error('no current month');
const next = new Date(this.year, this.month);
next.setMonth(next.getMonth() + 1);
this.setYearMonth(next.getFullYear(), next.getMonth());
}
onPrev() {
// console.log('DatePicker.onPrev');
if (this.year === null) throw new Error('no current year');
if (this.month === null) throw new Error('no current month');
const next = new Date(this.year, this.month);
next.setMonth(next.getMonth() - 1);
this.setYearMonth(next.getFullYear(), next.getMonth());
}
getCaption() {
return this.el.querySelector('caption > div > span');
}
getNext() {
return this.el.querySelector('caption > div > a.next');
}
getPrev() {
return this.el.querySelector('caption > div > a.prev');
}
static getDay(date) {
let day = date.getDay() - 1;
if (day === -1) day = 6;
return day;
}
isDateSelected() {
return this.selectedYear !== null && this.selectedMonth && this.selectedDate;
}
setYearMonth(year, month) {
console.log('DatePicker.setYearMonth', year, month);
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
if (year === undefined) year = today.getFullYear();
if (month === undefined) month = today.getMonth();
this.year = year;
this.month = month;
const date = new Date(year, month, 1); // first day of month
let day = DatePicker.getDay(date);
if (day === 0) {
date.setDate(date.getDate() - 7); // first day of table
} else {
date.setDate(date.getDate() - day); // first day of table
}
// caption
this.getCaption().innerText = `${months[month]}, ${year}`;
// days
const tds = this.el.querySelectorAll('td');
for (let i = 0; i < 42; i++) {
tds[i].innerText = date.getDate().toString();
tds[i].dataset.year = date.getFullYear();
tds[i].dataset.month = date.getMonth();
tds[i].dataset.date = date.getDate();
if (date.getMonth() !== month) {
tds[i].classList.add('out');
} else {
tds[i].classList.remove('out');
}
if (date >= today) {
tds[i].classList.add('selectable');
} else {
tds[i].classList.remove('selectable');
}
if (date.getTime() === today.getTime()) {
tds[i].classList.add('today');
} else {
tds[i].classList.remove('today');
}
if (date.getFullYear() === this.selectedYear && date.getMonth() === this.selectedMonth && date.getDate() === this.selectedDate) {
tds[i].classList.add('selected');
} else {
tds[i].classList.remove('selected');
}
date.setDate(date.getDate() + 1);
}
}
}
| setSelectedDate
| gui/datepicker/DatePicker/DatePicker.js | setSelectedDate | <ide><path>ui/datepicker/DatePicker/DatePicker.js
<ide> return this.selectedYear !== null && this.selectedMonth && this.selectedDate;
<ide> }
<ide>
<add> setSelectedDate(year, month, date) {
<add> this.selectedYear = year;
<add> this.selectedMonth = month;
<add> this.selectedDate = date;
<add> }
<add>
<ide> setYearMonth(year, month) {
<ide> console.log('DatePicker.setYearMonth', year, month);
<ide> const now = new Date(); |
|
Java | apache-2.0 | error: pathspec 'flags/src/test/java/org/cloudname/flags/FlagsHelpTest.java' did not match any file(s) known to git
| 5ec45abfb8e4cb30f42bfb9ff830016c872c96f1 | 1 | stalehd/cloudname,stalehd/cloudname,stalehd/cloudname | package org.cloudname.flags;
public class FlagsHelpTest {
@Flag(name = "no.default.value.int")
public static int noDefaultValue;
@Flag(name = "no.default.value.string")
public static String noDefaultValue2;
}
| flags/src/test/java/org/cloudname/flags/FlagsHelpTest.java | Forgot a file.
| flags/src/test/java/org/cloudname/flags/FlagsHelpTest.java | Forgot a file. | <ide><path>lags/src/test/java/org/cloudname/flags/FlagsHelpTest.java
<add>package org.cloudname.flags;
<add>
<add>public class FlagsHelpTest {
<add>
<add> @Flag(name = "no.default.value.int")
<add> public static int noDefaultValue;
<add>
<add> @Flag(name = "no.default.value.string")
<add> public static String noDefaultValue2;
<add>} |
|
Java | apache-2.0 | 77720bd8c62a9230f1f3a37b6634e418e4f00b20 | 0 | rbrito/commons-graph | src/main/java/org/apache/commons/graph/algorithm/util/PathImpl.java | package org.apache.commons.graph.algorithm.util;
/*
* 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.
*/
import java.util.List;
import java.util.ArrayList;
import org.apache.commons.graph.*;
public class PathImpl
implements Path
{
protected List vertexList = new ArrayList();
protected List edgeList = new ArrayList();
public PathImpl( List vertexList,
List edgeList ) {
this.vertexList = vertexList;
this.edgeList = edgeList;
}
public PathImpl( Vertex start ) {
this.vertexList.add( start );
}
public PathImpl( Vertex start,
Vertex end,
Edge edge ) {
vertexList = new ArrayList();
vertexList.add( start );
vertexList.add( end );
edgeList = new ArrayList();
edgeList.add( edge );
}
public PathImpl append( PathImpl impl ) {
List newVertices = new ArrayList( vertexList );
newVertices.remove( newVertices.size() - 1 ); // Last should be duplicated
newVertices.addAll( impl.getVertices() );
List newEdges = new ArrayList( edgeList );
newEdges.addAll( impl.getEdges() );
return new PathImpl( newVertices, newEdges );
}
public PathImpl append( Vertex v, Edge e ) {
List newVertices = new ArrayList( vertexList );
newVertices.add( v );
List newEdges = new ArrayList( edgeList );
newEdges.add( e );
return new PathImpl( newVertices, newEdges );
}
public Vertex getSource() {
return (Vertex) vertexList.get( 0 );
}
public Vertex getTarget() {
return (Vertex) vertexList.get( vertexList.size() - 1 );
}
public List getVertices() {
return vertexList;
}
public List getEdges() {
return edgeList;
}
public int size() {
return vertexList.size();
}
public String toString() {
return vertexList.toString();
}
}
| removed unneeded Path impl, the new one is more verastile
git-svn-id: d10d6fea7dc5cdc41d063c212c6a6cfd08395fef@1135848 13f79535-47bb-0310-9956-ffa450edef68
| src/main/java/org/apache/commons/graph/algorithm/util/PathImpl.java | removed unneeded Path impl, the new one is more verastile | <ide><path>rc/main/java/org/apache/commons/graph/algorithm/util/PathImpl.java
<del>package org.apache.commons.graph.algorithm.util;
<del>
<del>/*
<del> * Licensed to the Apache Software Foundation (ASF) under one
<del> * or more contributor license agreements. See the NOTICE file
<del> * distributed with this work for additional information
<del> * regarding copyright ownership. The ASF licenses this file
<del> * to you under the Apache License, Version 2.0 (the
<del> * "License"); you may not use this file except in compliance
<del> * with the License. You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing,
<del> * software distributed under the License is distributed on an
<del> * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<del> * KIND, either express or implied. See the License for the
<del> * specific language governing permissions and limitations
<del> * under the License.
<del> */
<del>
<del>import java.util.List;
<del>import java.util.ArrayList;
<del>
<del>import org.apache.commons.graph.*;
<del>
<del>public class PathImpl
<del> implements Path
<del>{
<del> protected List vertexList = new ArrayList();
<del> protected List edgeList = new ArrayList();
<del>
<del> public PathImpl( List vertexList,
<del> List edgeList ) {
<del> this.vertexList = vertexList;
<del> this.edgeList = edgeList;
<del> }
<del>
<del> public PathImpl( Vertex start ) {
<del> this.vertexList.add( start );
<del> }
<del>
<del> public PathImpl( Vertex start,
<del> Vertex end,
<del> Edge edge ) {
<del> vertexList = new ArrayList();
<del> vertexList.add( start );
<del> vertexList.add( end );
<del>
<del> edgeList = new ArrayList();
<del> edgeList.add( edge );
<del> }
<del>
<del> public PathImpl append( PathImpl impl ) {
<del> List newVertices = new ArrayList( vertexList );
<del> newVertices.remove( newVertices.size() - 1 ); // Last should be duplicated
<del> newVertices.addAll( impl.getVertices() );
<del>
<del> List newEdges = new ArrayList( edgeList );
<del> newEdges.addAll( impl.getEdges() );
<del>
<del> return new PathImpl( newVertices, newEdges );
<del> }
<del>
<del> public PathImpl append( Vertex v, Edge e ) {
<del> List newVertices = new ArrayList( vertexList );
<del> newVertices.add( v );
<del>
<del> List newEdges = new ArrayList( edgeList );
<del> newEdges.add( e );
<del>
<del> return new PathImpl( newVertices, newEdges );
<del> }
<del>
<del> public Vertex getSource() {
<del> return (Vertex) vertexList.get( 0 );
<del> }
<del>
<del> public Vertex getTarget() {
<del> return (Vertex) vertexList.get( vertexList.size() - 1 );
<del> }
<del>
<del> public List getVertices() {
<del> return vertexList;
<del> }
<del>
<del> public List getEdges() {
<del> return edgeList;
<del> }
<del>
<del> public int size() {
<del> return vertexList.size();
<del> }
<del>
<del> public String toString() {
<del> return vertexList.toString();
<del> }
<del>}
<del>
<del> |
||
Java | mit | 27608663dfb8192d865ea9e7919ca0b31e9641c4 | 0 | jenkinsci/disk-usage-plugin | package hudson.plugins.disk_usage.integration;
import hudson.model.AbstractProject;
import org.jvnet.hudson.test.recipes.LocalData;
import hudson.plugins.disk_usage.*;
import hudson.model.TopLevelItem;
import hudson.model.Project;
import hudson.model.Build;
import hudson.model.TopLevelItemDescriptor;
import java.util.Map;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.io.File;
import java.io.IOException;
import hudson.model.ItemGroup;
import hudson.matrix.AxisList;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixConfiguration;
import hudson.matrix.MatrixProject;
import hudson.matrix.TextAxis;
import hudson.model.AbstractBuild;
import hudson.model.FreeStyleProject;
import hudson.model.listeners.ItemListener;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.junit.Rule;
import static org.junit.Assert.*;
/**
*
* @author Lucie Votypkova
*/
public class ProjectDiskUsageActionTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Test
public void testGetBuildsDiskUsage() throws Exception{
FreeStyleProject project = j.jenkins.createProject(FreeStyleProject.class, "project1");
MatrixProject matrixProject = j.jenkins.createProject(MatrixProject.class, "project2");
TextAxis axis1 = new TextAxis("axis", "axisA");
TextAxis axis2 = new TextAxis("axis2", "Aaxis");
AxisList list = new AxisList();
list.add(axis1);
list.add(axis2);
matrixProject.setAxes(list);
j.buildAndAssertSuccess(project);
AbstractBuild build = project.getLastBuild();
j.buildAndAssertSuccess(matrixProject);
MatrixBuild matrixBuild1 = matrixProject.getLastBuild();
j.buildAndAssertSuccess(matrixProject);
MatrixBuild matrixBuild2 = matrixProject.getLastBuild();
Long sizeofBuild = 7546l;
Long sizeOfMatrixBuild1 = 6800l;
Long sizeOfMatrixBuild2 = 14032l;
DiskUsageTestUtil.getBuildDiskUsageAction(build).setDiskUsage(sizeofBuild);
DiskUsageTestUtil.getBuildDiskUsageAction(matrixBuild1).setDiskUsage(sizeOfMatrixBuild1);
DiskUsageTestUtil.getBuildDiskUsageAction(matrixBuild2).setDiskUsage(sizeOfMatrixBuild2);
long size1 = 5390;
long size2 = 2390;
int count = 1;
Long matrixBuild1TotalSize = sizeOfMatrixBuild1;
Long matrixBuild2TotalSize = sizeOfMatrixBuild2;
for(MatrixConfiguration c: matrixProject.getItems()){
AbstractBuild configurationBuild = c.getBuildByNumber(1);
DiskUsageTestUtil.getBuildDiskUsageAction(configurationBuild).setDiskUsage(count*size1);
matrixBuild1TotalSize += count*size1;
AbstractBuild configurationBuild2 = c.getBuildByNumber(2);
DiskUsageTestUtil.getBuildDiskUsageAction(configurationBuild2).setDiskUsage(count*size2);
matrixBuild2TotalSize += count*size2;
count++;
}
ProjectDiskUsage usage = matrixProject.getAction(ProjectDiskUsageAction.class).getDiskUsage();
Long matrixProjectBuildsTotalSize = matrixBuild1TotalSize + matrixBuild2TotalSize;
assertEquals("BuildDiskUsageAction for build 1 of FreeStyleProject " + project.getDisplayName() + " returns wrong value for its size including sub-builds.", sizeofBuild, project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage().get("all"));
assertEquals("BuildDiskUsageAction for build 1 of MatrixProject " + matrixProject.getDisplayName() + " returns wrong value for its size including sub-builds.", matrixProjectBuildsTotalSize, matrixProject.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage().get("all"));
}
@Test
public void testGetBuildsDiskUsageNotDeletedConfigurations() throws Exception{
FreeStyleProject project = j.jenkins.createProject(FreeStyleProject.class, "project1");
MatrixProject matrixProject = j.jenkins.createProject(MatrixProject.class, "project2");
TextAxis axis1 = new TextAxis("axis", "axisA", "axisB", "axisC");
TextAxis axis2 = new TextAxis("axis2", "Aaxis", "Baxis", "Caxis");
AxisList list = new AxisList();
list.add(axis1);
list.add(axis2);
matrixProject.setAxes(list);
j.buildAndAssertSuccess(project);
AbstractBuild build = project.getLastBuild();
j.buildAndAssertSuccess(matrixProject);
MatrixBuild matrixBuild1 = matrixProject.getLastBuild();
j.buildAndAssertSuccess(matrixProject);
MatrixBuild matrixBuild2 = matrixProject.getLastBuild();
Long sizeofBuild = 7546l;
Long sizeOfMatrixBuild1 = 6800l;
Long sizeOfMatrixBuild2 = 14032l;
DiskUsageTestUtil.getBuildDiskUsageAction(build).setDiskUsage(sizeofBuild);
DiskUsageTestUtil.getBuildDiskUsageAction(matrixBuild1).setDiskUsage(sizeOfMatrixBuild1);
DiskUsageTestUtil.getBuildDiskUsageAction(matrixBuild2).setDiskUsage(sizeOfMatrixBuild2);
long size1 = 5390;
long size2 = 2390;
int count = 1;
Long matrixBuild1TotalSize = sizeOfMatrixBuild1;
Long matrixBuild2TotalSize = sizeOfMatrixBuild2;
Long matrixConfBuild2 = 0l;
for(MatrixConfiguration c: matrixProject.getItems()){
AbstractBuild configurationBuild = c.getBuildByNumber(1);
DiskUsageTestUtil.getBuildDiskUsageAction(configurationBuild).setDiskUsage(count*size1);
matrixBuild1TotalSize += count*size1;
AbstractBuild configurationBuild2 = c.getBuildByNumber(2);
DiskUsageTestUtil.getBuildDiskUsageAction(configurationBuild2).setDiskUsage(count*size2);
matrixBuild2TotalSize += count*size2;
matrixConfBuild2 += count*size2;
count++;
}
matrixBuild2.delete();
Long matrixProjectBuildsTotalSize = matrixBuild1TotalSize + matrixBuild2TotalSize - sizeOfMatrixBuild2 - matrixConfBuild2;
DiskUsageUtil.calculateDiskUsageNotLoadedJobs(matrixProject);
assertEquals("BuildDiskUsageAction for build 1 of FreeStyleProject " + project.getDisplayName() + " returns wrong value for its size including sub-builds.", sizeofBuild, project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage().get("all"));
assertEquals("BuildDiskUsageAction for build 1 of MatrixProject " + matrixProject.getDisplayName() + " returns wrong value for its size including sub-builds.", matrixProjectBuildsTotalSize, matrixProject.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage().get("all"));
}
@Test
public void getAllBuildDiskUsageFiltered() throws Exception{
ProjectTest project = new ProjectTest(j.jenkins, "project");
project.assignBuildNumber();
Calendar calendar1 = new GregorianCalendar();
Calendar calendar2 = new GregorianCalendar();
Calendar calendar3 = new GregorianCalendar();
calendar1.set(2013, 9, 9);
calendar2.set(2013, 8, 22);
calendar3.set(2013, 5, 9);
ProjectTestBuild build1 = (ProjectTestBuild) project.createExecutable(calendar1);
ProjectTestBuild build2 = (ProjectTestBuild) project.createExecutable(calendar2);
ProjectTestBuild build3 = (ProjectTestBuild) project.createExecutable(calendar3);
Calendar filterCalendar = new GregorianCalendar();
filterCalendar.set(2013, 8, 30);
Date youngerThan10days = filterCalendar.getTime();
filterCalendar.set(2013, 9, 2);
Date olderThan7days = filterCalendar.getTime();
filterCalendar.set(2013, 8, 19);
Date youngerThan3weeks = filterCalendar.getTime();
filterCalendar.set(2013, 4, 9);
Date olderThan5months = filterCalendar.getTime();
filterCalendar.set(2013, 8, 19);
Date olderThan3weeks = filterCalendar.getTime();
Long sizeofBuild1 = 7546l;
Long sizeofBuild2 = 9546l;
Long sizeofBuild3 = 15546l;
DiskUsageTestUtil.getBuildDiskUsageAction(build1).setDiskUsage(sizeofBuild1);
DiskUsageTestUtil.getBuildDiskUsageAction(build2).setDiskUsage(sizeofBuild2);
DiskUsageTestUtil.getBuildDiskUsageAction(build3).setDiskUsage(sizeofBuild3);
project.update();
Map<String,Long> size = project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage(null, youngerThan10days);
assertEquals("Disk usage of builds should count only build 1 (only build 1 is younger than 10 days ago).", sizeofBuild1, size.get("all"), 0);
size = project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage(olderThan7days, youngerThan10days);
assertEquals("Disk usage of builds should count only build 1 (only build 1 is younger than 10 days ago and older than 8 days ago).", 0, size.get("all"), 0);
size = project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage(olderThan7days, null);
assertEquals("Disk usage of builds should count all builds (all builds is older than 7 days ago).", sizeofBuild2 + sizeofBuild3, size.get("all"), 0);
size = project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage(olderThan7days, youngerThan3weeks);
assertEquals("Disk usage of builds should count build 1 and build 2 (build 1 and build 2 are older than 7 days but younger that 3 weeks).", sizeofBuild2, size.get("all"), 0);
size = project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage(olderThan5months, null);
assertEquals("No builds is older than 5 months ago", 0, size.get("all"), 0);
size = project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage(olderThan3weeks, null);
assertEquals("Disk usage of builds should count only build 3 (only build 3 is older tah 3 weeks).", sizeofBuild3, size.get("all"), 0);
}
@Test
@LocalData
public void testNotToBreakLazyLoading() throws IOException{
AbstractProject project = (AbstractProject) j.jenkins.getItem("project1");
project.isBuilding();
int loadedBuilds = project._getRuns().getLoadedBuilds().size();
assertTrue("This test does not have sense if there is loaded all builds", 8 > loadedBuilds);
project.getAction(ProjectDiskUsageAction.class).getGraph();
assertTrue("Creation of graph should not cause loading of builds.", project._getRuns().getLoadedBuilds().size() <= loadedBuilds );
}
public static class ProjectTest extends Project<ProjectTest,ProjectTestBuild> implements TopLevelItem{
ProjectTest(ItemGroup group, String name){
super(group, name);
onCreatedFromScratch();
ItemListener.fireOnCreated(this);
}
//@Override
@Override
public Class<ProjectTestBuild> getBuildClass(){
return ProjectTestBuild.class;
}
@Override
public ProjectTestBuild createExecutable() throws IOException{
ProjectTestBuild build = new ProjectTestBuild(this);
builds.put(getNextBuildNumber(), build);
return build;
}
public ProjectTestBuild createExecutable(Calendar calendar) throws IOException{
ProjectTestBuild build = super.createExecutable();
build.setTimestamp(calendar);
return build;
}
public TopLevelItemDescriptor getDescriptor() {
throw new UnsupportedOperationException("Not supported yet.");
}
public void update(){
this.updateTransientActions();;
}
@Override
public void save(){
//do not save fake project
getRootDir().mkdirs();
}
}
public static class ProjectTestBuild extends Build<ProjectTest,ProjectTestBuild>{
public ProjectTestBuild(ProjectTest project) throws IOException {
super(project);
}
public ProjectTestBuild(ProjectTest project, Calendar calendar) throws IOException {
super(project, calendar);
}
public ProjectTestBuild(ProjectTest project, File buildDir) throws IOException {
super(project, buildDir);
}
public void setTimestamp(Calendar c){
this.timestamp = c.getTimeInMillis();
}
}
}
| src/test/java/hudson/plugins/disk_usage/integration/ProjectDiskUsageActionTest.java | package hudson.plugins.disk_usage.integration;
import hudson.model.AbstractProject;
import org.jvnet.hudson.test.recipes.LocalData;
import hudson.plugins.disk_usage.*;
import hudson.model.TopLevelItem;
import hudson.model.Project;
import hudson.model.Build;
import hudson.model.TopLevelItemDescriptor;
import java.util.Map;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.io.File;
import java.io.IOException;
import hudson.model.ItemGroup;
import hudson.matrix.AxisList;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixConfiguration;
import hudson.matrix.MatrixProject;
import hudson.matrix.TextAxis;
import hudson.model.AbstractBuild;
import hudson.model.FreeStyleProject;
import hudson.model.listeners.ItemListener;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.junit.Rule;
import static org.junit.Assert.*;
/**
*
* @author Lucie Votypkova
*/
public class ProjectDiskUsageActionTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Test
public void testGetBuildsDiskUsage() throws Exception{
FreeStyleProject project = j.jenkins.createProject(FreeStyleProject.class, "project1");
MatrixProject matrixProject = j.jenkins.createProject(MatrixProject.class, "project2");
TextAxis axis1 = new TextAxis("axis", "axisA");
TextAxis axis2 = new TextAxis("axis2", "Aaxis");
AxisList list = new AxisList();
list.add(axis1);
list.add(axis2);
matrixProject.setAxes(list);
j.buildAndAssertSuccess(project);
AbstractBuild build = project.getLastBuild();
j.buildAndAssertSuccess(matrixProject);
MatrixBuild matrixBuild1 = matrixProject.getLastBuild();
j.buildAndAssertSuccess(matrixProject);
MatrixBuild matrixBuild2 = matrixProject.getLastBuild();
Long sizeofBuild = 7546l;
Long sizeOfMatrixBuild1 = 6800l;
Long sizeOfMatrixBuild2 = 14032l;
DiskUsageTestUtil.getBuildDiskUsageAction(build).setDiskUsage(sizeofBuild);
DiskUsageTestUtil.getBuildDiskUsageAction(matrixBuild1).setDiskUsage(sizeOfMatrixBuild1);
DiskUsageTestUtil.getBuildDiskUsageAction(matrixBuild2).setDiskUsage(sizeOfMatrixBuild2);
long size1 = 5390;
long size2 = 2390;
int count = 1;
Long matrixBuild1TotalSize = sizeOfMatrixBuild1;
Long matrixBuild2TotalSize = sizeOfMatrixBuild2;
for(MatrixConfiguration c: matrixProject.getItems()){
AbstractBuild configurationBuild = c.getBuildByNumber(1);
DiskUsageTestUtil.getBuildDiskUsageAction(configurationBuild).setDiskUsage(count*size1);
matrixBuild1TotalSize += count*size1;
AbstractBuild configurationBuild2 = c.getBuildByNumber(2);
DiskUsageTestUtil.getBuildDiskUsageAction(configurationBuild2).setDiskUsage(count*size2);
matrixBuild2TotalSize += count*size2;
count++;
}
ProjectDiskUsage usage = matrixProject.getAction(ProjectDiskUsageAction.class).getDiskUsage();
Long matrixProjectBuildsTotalSize = matrixBuild1TotalSize + matrixBuild2TotalSize;
assertEquals("BuildDiskUsageAction for build 1 of FreeStyleProject " + project.getDisplayName() + " returns wrong value for its size including sub-builds.", sizeofBuild, project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage().get("all"));
assertEquals("BuildDiskUsageAction for build 1 of MatrixProject " + matrixProject.getDisplayName() + " returns wrong value for its size including sub-builds.", matrixProjectBuildsTotalSize, matrixProject.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage().get("all"));
}
@Test
public void testGetBuildsDiskUsageNotDeletedConfigurations() throws Exception{
FreeStyleProject project = j.jenkins.createProject(FreeStyleProject.class, "project1");
MatrixProject matrixProject = j.jenkins.createProject(MatrixProject.class, "project2");
TextAxis axis1 = new TextAxis("axis", "axisA", "axisB", "axisC");
TextAxis axis2 = new TextAxis("axis2", "Aaxis", "Baxis", "Caxis");
AxisList list = new AxisList();
list.add(axis1);
list.add(axis2);
matrixProject.setAxes(list);
j.buildAndAssertSuccess(project);
AbstractBuild build = project.getLastBuild();
j.buildAndAssertSuccess(matrixProject);
MatrixBuild matrixBuild1 = matrixProject.getLastBuild();
j.buildAndAssertSuccess(matrixProject);
MatrixBuild matrixBuild2 = matrixProject.getLastBuild();
Long sizeofBuild = 7546l;
Long sizeOfMatrixBuild1 = 6800l;
Long sizeOfMatrixBuild2 = 14032l;
DiskUsageTestUtil.getBuildDiskUsageAction(build).setDiskUsage(sizeofBuild);
DiskUsageTestUtil.getBuildDiskUsageAction(matrixBuild1).setDiskUsage(sizeOfMatrixBuild1);
DiskUsageTestUtil.getBuildDiskUsageAction(matrixBuild2).setDiskUsage(sizeOfMatrixBuild2);
long size1 = 5390;
long size2 = 2390;
int count = 1;
Long matrixBuild1TotalSize = sizeOfMatrixBuild1;
Long matrixBuild2TotalSize = sizeOfMatrixBuild2;
Long matrixConfBuild2 = 0l;
for(MatrixConfiguration c: matrixProject.getItems()){
AbstractBuild configurationBuild = c.getBuildByNumber(1);
DiskUsageTestUtil.getBuildDiskUsageAction(configurationBuild).setDiskUsage(count*size1);
matrixBuild1TotalSize += count*size1;
AbstractBuild configurationBuild2 = c.getBuildByNumber(2);
DiskUsageTestUtil.getBuildDiskUsageAction(configurationBuild2).setDiskUsage(count*size2);
matrixBuild2TotalSize += count*size2;
matrixConfBuild2 += count*size2;
count++;
}
matrixBuild2.delete();
Long matrixProjectBuildsTotalSize = matrixBuild1TotalSize + matrixBuild2TotalSize - sizeOfMatrixBuild2 - matrixConfBuild2;
DiskUsageUtil.calculateDiskUsageNotLoadedJobs(matrixProject);
assertEquals("BuildDiskUsageAction for build 1 of FreeStyleProject " + project.getDisplayName() + " returns wrong value for its size including sub-builds.", sizeofBuild, project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage().get("all"));
assertEquals("BuildDiskUsageAction for build 1 of MatrixProject " + matrixProject.getDisplayName() + " returns wrong value for its size including sub-builds.", matrixProjectBuildsTotalSize, matrixProject.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage().get("all"));
}
@Test
public void getAllBuildDiskUsageFiltered() throws Exception{
ProjectTest project = new ProjectTest(j.jenkins, "project");
Calendar calendar1 = new GregorianCalendar();
Calendar calendar2 = new GregorianCalendar();
Calendar calendar3 = new GregorianCalendar();
calendar1.set(2013, 9, 9);
calendar2.set(2013, 8, 22);
calendar3.set(2013, 5, 9);
ProjectTestBuild build1 = (ProjectTestBuild) project.createExecutable(calendar1);
ProjectTestBuild build2 = (ProjectTestBuild) project.createExecutable(calendar2);
ProjectTestBuild build3 = (ProjectTestBuild) project.createExecutable(calendar3);
Calendar filterCalendar = new GregorianCalendar();
filterCalendar.set(2013, 8, 30);
Date youngerThan10days = filterCalendar.getTime();
filterCalendar.set(2013, 9, 2);
Date olderThan7days = filterCalendar.getTime();
filterCalendar.set(2013, 8, 19);
Date youngerThan3weeks = filterCalendar.getTime();
filterCalendar.set(2013, 4, 9);
Date olderThan5months = filterCalendar.getTime();
filterCalendar.set(2013, 8, 19);
Date olderThan3weeks = filterCalendar.getTime();
Long sizeofBuild1 = 7546l;
Long sizeofBuild2 = 9546l;
Long sizeofBuild3 = 15546l;
DiskUsageTestUtil.getBuildDiskUsageAction(build1).setDiskUsage(sizeofBuild1);
DiskUsageTestUtil.getBuildDiskUsageAction(build2).setDiskUsage(sizeofBuild2);
DiskUsageTestUtil.getBuildDiskUsageAction(build3).setDiskUsage(sizeofBuild3);
project.update();
Map<String,Long> size = project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage(null, youngerThan10days);
assertEquals("Disk usage of builds should count only build 1 (only build 1 is younger than 10 days ago).", sizeofBuild1, size.get("all"), 0);
size = project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage(olderThan7days, youngerThan10days);
assertEquals("Disk usage of builds should count only build 1 (only build 1 is younger than 10 days ago and older than 8 days ago).", 0, size.get("all"), 0);
size = project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage(olderThan7days, null);
assertEquals("Disk usage of builds should count all builds (all builds is older than 7 days ago).", sizeofBuild2 + sizeofBuild3, size.get("all"), 0);
size = project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage(olderThan7days, youngerThan3weeks);
assertEquals("Disk usage of builds should count build 1 and build 2 (build 1 and build 2 are older than 7 days but younger that 3 weeks).", sizeofBuild2, size.get("all"), 0);
size = project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage(olderThan5months, null);
assertEquals("No builds is older than 5 months ago", 0, size.get("all"), 0);
size = project.getAction(ProjectDiskUsageAction.class).getBuildsDiskUsage(olderThan3weeks, null);
assertEquals("Disk usage of builds should count only build 3 (only build 3 is older tah 3 weeks).", sizeofBuild3, size.get("all"), 0);
}
@Test
@LocalData
public void testNotToBreakLazyLoading() throws IOException{
AbstractProject project = (AbstractProject) j.jenkins.getItem("project1");
project.isBuilding();
int loadedBuilds = project._getRuns().getLoadedBuilds().size();
assertTrue("This test does not have sense if there is loaded all builds", 8 > loadedBuilds);
project.getAction(ProjectDiskUsageAction.class).getGraph();
assertTrue("Creation of graph should not cause loading of builds.", project._getRuns().getLoadedBuilds().size() <= loadedBuilds );
}
public class ProjectTest extends Project<ProjectTest,ProjectTestBuild> implements TopLevelItem{
ProjectTest(ItemGroup group, String name){
super(group, name);
onCreatedFromScratch();
ItemListener.fireOnCreated(this);
}
//@Override
@Override
public Class<ProjectTestBuild> getBuildClass(){
return ProjectTestBuild.class;
}
@Override
public ProjectTestBuild createExecutable() throws IOException{
ProjectTestBuild build = new ProjectTestBuild(this);
builds.put(getNextBuildNumber(), build);
return build;
}
public ProjectTestBuild createExecutable(Calendar calendar) throws IOException{
ProjectTestBuild build = new ProjectTestBuild(this, calendar);
builds.put(getNextBuildNumber(), build);
return build;
}
public TopLevelItemDescriptor getDescriptor() {
throw new UnsupportedOperationException("Not supported yet.");
}
public void update(){
this.updateTransientActions();;
}
@Override
public void save(){
//do not save fake project
getRootDir().mkdirs();
}
}
public class ProjectTestBuild extends Build<ProjectTest,ProjectTestBuild>{
public ProjectTestBuild(ProjectTest project) throws IOException {
super(project);
}
public ProjectTestBuild(ProjectTest project, Calendar calendar) throws IOException {
super(project, calendar);
}
public ProjectTestBuild(ProjectTest project, File buildDir) throws IOException {
super(project, buildDir);
}
}
}
| fix creation of executable in test.
| src/test/java/hudson/plugins/disk_usage/integration/ProjectDiskUsageActionTest.java | fix creation of executable in test. | <ide><path>rc/test/java/hudson/plugins/disk_usage/integration/ProjectDiskUsageActionTest.java
<ide> @Test
<ide> public void getAllBuildDiskUsageFiltered() throws Exception{
<ide> ProjectTest project = new ProjectTest(j.jenkins, "project");
<add> project.assignBuildNumber();
<ide> Calendar calendar1 = new GregorianCalendar();
<ide> Calendar calendar2 = new GregorianCalendar();
<ide> Calendar calendar3 = new GregorianCalendar();
<ide>
<ide> }
<ide>
<del> public class ProjectTest extends Project<ProjectTest,ProjectTestBuild> implements TopLevelItem{
<add> public static class ProjectTest extends Project<ProjectTest,ProjectTestBuild> implements TopLevelItem{
<ide>
<ide> ProjectTest(ItemGroup group, String name){
<ide> super(group, name);
<ide> }
<ide>
<ide> public ProjectTestBuild createExecutable(Calendar calendar) throws IOException{
<del> ProjectTestBuild build = new ProjectTestBuild(this, calendar);
<del> builds.put(getNextBuildNumber(), build);
<add> ProjectTestBuild build = super.createExecutable();
<add> build.setTimestamp(calendar);
<ide> return build;
<ide> }
<ide>
<ide> //do not save fake project
<ide> getRootDir().mkdirs();
<ide> }
<add>
<ide> }
<ide>
<del> public class ProjectTestBuild extends Build<ProjectTest,ProjectTestBuild>{
<add> public static class ProjectTestBuild extends Build<ProjectTest,ProjectTestBuild>{
<ide>
<ide>
<ide> public ProjectTestBuild(ProjectTest project) throws IOException {
<ide> super(project, buildDir);
<ide> }
<ide>
<add>
<add> public void setTimestamp(Calendar c){
<add> this.timestamp = c.getTimeInMillis();
<add> }
<add>
<add>
<add>
<ide> }
<ide>
<ide> } |
|
JavaScript | mit | 4ea8a7c18a8fb13e8604cd0a003cb044d0e133a1 | 0 | christoph26/foodgenerator-frontend,christoph26/foodgenerator-frontend | (function () {
angular.module('foodGenerator')
.service('recipeStorageService', recipeStorageService);
function recipeStorageService($window, recipeService) {
this.addMarkedRecipe = addMarkedRecipe;
this.removeMarkedRecipe = removeMarkedRecipe;
this.getMarkedRecipes = getMarkedRecipes;
this.clearMarkedRecipes = clearMarkedRecipes;
this.addRecentlyViewedRecipe = addRecentlyViewedRecipe;
this.getRecentlyViewedRecipes = getRecentlyViewedRecipes;
this.clearRecentlyViewedRecipes = clearRecentlyViewedRecipes;
this.addToShoppingList = addToShoppingList;
this.removeFromShoppingList = removeFromShoppingList;
this.getShoppingListRecipes = getShoppingListRecipes;
this.clearShoppingList = clearShoppingList;
////////////////
// Marked Recipes
function addMarkedRecipe(recipe) {
console.log("Adding recipe '" + recipe.title + "' to marked recipes.");
addRecipeToStorage(recipe, 'foodgenerator.recipes.marked');
}
function removeMarkedRecipe(recipe) {
if (removeRecipeFromStorage(recipe, 'foodgenerator.recipes.marked')) {
console.log("Removed recipe '" + recipe.title + "' from marked recipes.");
} else {
console.error("Could not remove recipe '" + recipe.title + "': not contained in marked recipe list.");
}
}
function getMarkedRecipes() {
return getRecipesFromIdList(getRecipeStorage('foodgenerator.recipes.marked'));
}
function clearMarkedRecipes() {
clearRecipeStorage('foodgenerator.recipes.marked');
}
// Recently Viewed Recipes
function addRecentlyViewedRecipe(recipe) {
console.log("Registering new view for recipe '" + recipe.title + "'.");
addRecipeToStorage(recipe, 'foodgenerator.recipes.recent');
}
function getRecentlyViewedRecipes() {
return getRecipesFromIdList(getRecipeStorage('foodgenerator.recipes.recent'));
}
function clearRecentlyViewedRecipes() {
clearRecipeStorage('foodgenerator.recipes.recent');
}
// Shopping List
function addToShoppingList(recipe) {
console.log("Adding recipe '" + recipe.title + "' to shopping list.");
addRecipeToStorage(recipe, 'foodgenerator.recipes.shopping');
}
function removeFromShoppingList(recipe) {
if (removeRecipeFromStorage(recipe, 'foodgenerator.recipes.shopping')) {
console.log("Removed recipe '" + recipe.title + "' from shopping list.");
} else {
console.error("Could not remove recipe '" + recipe.title + "': not contained in shopping list.");
}
}
function getShoppingListRecipes() {
return getRecipesFromIdList(getRecipeStorage('foodgenerator.recipes.shopping'));
}
function clearShoppingList() {
clearRecipeStorage('foodgenerator.recipes.shopping');
}
// Generic Functions
function addRecipeToStorage(recipe, storageName) {
// in case it is contained, remove element from current position
removeRecipeFromStorage(recipe, storageName);
// create a new list with the new recipe as only item
var reorderedStorage = [recipe._id];
// append other recipes if defined
var recipeStorage = getRecipeStorage(storageName);
if (recipeStorage) {
reorderedStorage.push.apply(reorderedStorage, recipeStorage);
}
// save back to local storage
setRecipeStorage(storageName, reorderedStorage);
}
function removeRecipeFromStorage(recipe, storageName) {
var recipeStorage = getRecipeStorage(storageName);
if (recipeStorage && recipeStorage.length) {
var recipeIndex = recipeStorage.indexOf(recipe._id);
if (recipeIndex > -1 && recipeStorage.length == 1) {
// clear if it is the only element
clearRecipeStorage(storageName);
return true;
} else if (recipeIndex > -1) {
// remove if list not empty and not a single element
recipeStorage.splice(recipeIndex, 1);
setRecipeStorage(storageName, recipeStorage);
return true;
}
}
return false;
}
function getRecipeStorage(storageName) {
var recipeStorage = $window.localStorage[storageName];
if (recipeStorage == undefined) {
return [];
}
console.log("Returning recipe storage '" + storageName + "': " + recipeStorage);
return recipeStorage.split(",");
}
function setRecipeStorage(storageName, recipeStorage) {
var storageString = "";
for (var index in recipeStorage) {
//noinspection JSUnfilteredForInLoop
storageString += recipeStorage[index] + ",";
}
storageString = storageString.slice(0, -1);
$window.localStorage[storageName] = storageString;
}
function clearRecipeStorage(storageName) {
$window.localStorage.removeItem(storageName);
}
function getRecipesFromIdList(recipeIds) {
var recipes = [];
for (var index in recipeIds) {
//noinspection JSUnfilteredForInLoop
recipeService.get(recipeIds[index]).then(function (response) {
recipes.push(response.data);
})
}
return recipes;
}
}
})();
| app/ng/components/recipe/recipe-storage-service.js | (function () {
angular.module('foodGenerator')
.service('recipeStorageService', recipeStorageService);
function recipeStorageService($window, recipeService) {
this.addMarkedRecipe = addMarkedRecipe;
this.removeMarkedRecipe = removeMarkedRecipe;
this.getMarkedRecipes = getMarkedRecipes;
this.clearMarkedRecipes = clearMarkedRecipes;
this.addRecentlyViewedRecipe = addRecentlyViewedRecipe;
this.getRecentlyViewedRecipes = getRecentlyViewedRecipes;
this.clearRecentlyViewedRecipes = clearRecentlyViewedRecipes;
this.addToShoppingList = addToShoppingList;
this.removeFromShoppingList = removeFromShoppingList;
this.getShoppingListRecipes = getShoppingListRecipes;
this.clearShoppingList = clearShoppingList;
////////////////
// Marked Recipes
function addMarkedRecipe(recipe) {
console.log("Adding recipe '" + recipe.title + "' to marked recipes.");
addRecipeToStorage(recipe, 'foodgenerator.recipes.marked');
}
function removeMarkedRecipe(recipe) {
if (removeRecipeFromStorage(recipe, 'foodgenerator.recipes.marked')) {
console.log("Removed recipe '" + recipe.title + "' from marked recipes.");
} else {
console.error("Could not remove recipe '" + recipe.title + "': not contained in marked recipe list.");
}
}
function getMarkedRecipes() {
return getRecipesFromIdList(getRecipeStorage('foodgenerator.recipes.marked'));
}
function clearMarkedRecipes() {
clearRecipeStorage('foodgenerator.recipes.marked');
}
// Recently Viewed Recipes
function addRecentlyViewedRecipe(recipe) {
console.log("Registering new view for recipe '" + recipe.title + "'.");
addRecipeToStorage(recipe, 'foodgenerator.recipes.recent');
}
function getRecentlyViewedRecipes() {
return getRecipesFromIdList(getRecipeStorage('foodgenerator.recipes.recent'));
}
function clearRecentlyViewedRecipes() {
clearRecipeStorage('foodgenerator.recipes.marked');
}
// Shopping List
function addToShoppingList(recipe) {
console.log("Adding recipe '" + recipe.title + "' to shopping list.");
addRecipeToStorage(recipe, 'foodgenerator.recipes.shopping');
}
function removeFromShoppingList(recipe) {
if (removeRecipeFromStorage(recipe, 'foodgenerator.recipes.shopping')) {
console.log("Removed recipe '" + recipe.title + "' from shopping list.");
} else {
console.error("Could not remove recipe '" + recipe.title + "': not contained in shopping list.");
}
}
function getShoppingListRecipes() {
return getRecipesFromIdList(getRecipeStorage('foodgenerator.recipes.shopping'));
}
function clearShoppingList() {
clearRecipeStorage('foodgenerator.recipes.shopping');
}
// Generic Functions
function addRecipeToStorage(recipe, storageName) {
// in case it is contained, remove element from current position
removeRecipeFromStorage(recipe, storageName);
// create a new list with the new recipe as only item
var reorderedStorage = [recipe._id];
// append other recipes if defined
var recipeStorage = getRecipeStorage(storageName);
if (recipeStorage) {
reorderedStorage.push.apply(reorderedStorage, recipeStorage);
}
// save back to local storage
setRecipeStorage(storageName, reorderedStorage);
}
function removeRecipeFromStorage(recipe, storageName) {
var recipeStorage = getRecipeStorage(storageName);
if (recipeStorage && recipeStorage.length) {
var recipeIndex = recipeStorage.indexOf(recipe._id);
if (recipeIndex > 0) {
// remove if list not empty and not a single element
recipeStorage.splice(recipeIndex, 1);
setRecipeStorage(storageName, recipeStorage);
return true;
} else if (recipeIndex == 0) {
// clear if it the only element
clearRecipeStorage(storageName);
}
}
return false;
}
function getRecipeStorage(storageName) {
var recipeStorage = $window.localStorage[storageName];
if (recipeStorage == undefined) {
return [];
}
console.log("Returning recipe storage '" + storageName + "': " + recipeStorage);
return recipeStorage.split(",");
}
function setRecipeStorage(storageName, recipeStorage) {
var storageString = "";
for (var index in recipeStorage) {
//noinspection JSUnfilteredForInLoop
storageString += recipeStorage[index] + ",";
}
storageString = storageString.slice(0, -1);
$window.localStorage[storageName] = storageString;
}
function clearRecipeStorage(storageName) {
$window.localStorage.removeItem(storageName);
}
function getRecipesFromIdList(recipeIds) {
var recipes = [];
for (var index in recipeIds) {
//noinspection JSUnfilteredForInLoop
recipeService.get(recipeIds[index]).then(function (response) {
recipes.push(response.data);
})
}
return recipes;
}
}
})();
| fixed index bug when removing recipes from storage
| app/ng/components/recipe/recipe-storage-service.js | fixed index bug when removing recipes from storage | <ide><path>pp/ng/components/recipe/recipe-storage-service.js
<ide> }
<ide>
<ide> function clearRecentlyViewedRecipes() {
<del> clearRecipeStorage('foodgenerator.recipes.marked');
<add> clearRecipeStorage('foodgenerator.recipes.recent');
<ide> }
<ide>
<ide> // Shopping List
<ide> if (recipeStorage && recipeStorage.length) {
<ide> var recipeIndex = recipeStorage.indexOf(recipe._id);
<ide>
<del> if (recipeIndex > 0) {
<add> if (recipeIndex > -1 && recipeStorage.length == 1) {
<add> // clear if it is the only element
<add> clearRecipeStorage(storageName);
<add> return true;
<add> } else if (recipeIndex > -1) {
<ide> // remove if list not empty and not a single element
<ide> recipeStorage.splice(recipeIndex, 1);
<ide> setRecipeStorage(storageName, recipeStorage);
<ide> return true;
<del> } else if (recipeIndex == 0) {
<del> // clear if it the only element
<del> clearRecipeStorage(storageName);
<ide> }
<ide> }
<ide> return false; |
|
Java | lgpl-2.1 | 38492a8e26066cc06b00a4ab35f30f3ab2a04aee | 0 | KengoTODA/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,sewe/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,sewe/spotbugs,sewe/spotbugs | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2005, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.ba;
import edu.umd.cs.findbugs.annotations.CheckForNull;
/**
* @author pugh
*/
public class NullnessAnnotationDatabase extends AnnotationDatabase<NullnessAnnotation> {
public NullnessAnnotationDatabase() {
addDefaultAnnotation(AnnotationDatabase.METHOD, "java.lang.String", NullnessAnnotation.NONNULL);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.package-info", NullnessAnnotation.NONNULL);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.CopyOnWriteArrayList", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.CopyOnWriteArraySet", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ConcurrentLinkedQueue$Node", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.Exchanger", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.FutureTask", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.LinkedBlockingQueue$Node", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.SynchronousQueue$WaitQueue", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ThreadPoolExecutor$Worker", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.AbstractExecutorService", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ConcurrentSkipListMap$ConcurrentSkipListSubMap", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ConcurrentSkipListMap$HeadIndex", NullnessAnnotation.UNKNOWN_NULLNESS)
;
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ConcurrentSkipListMap$Index", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ConcurrentSkipListMap$Node", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ConcurrentSkipListMap$SubMap", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ConcurrentSkipListSet$ConcurrentSkipListSubSet", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.LinkedBlockingDeque$Node", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.SynchronousQueue$TransferQueue", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.SynchronousQueue$TransferQueue$QNode", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.SynchronousQueue$TransferStack", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.SynchronousQueue$Transferer", NullnessAnnotation.UNKNOWN_NULLNESS);
addMethodParameterAnnotation("java.util.concurrent.ConcurrentHashMap$Segment", "remove", "(Ljava/lang/Object;ILjava/lang/Object;)Ljava/lang/Object;", false, 2, NullnessAnnotation.CHECK_FOR_NULL);
addMethodParameterAnnotation("java.util.concurrent.CyclicBarrier", "<init>", "(ILjava/lang/Runnable;)V", false, 1, NullnessAnnotation.CHECK_FOR_NULL);
addMethodParameterAnnotation("java.util.concurrent.Executors$RunnableAdapter", "<init>", "(Ljava/lang/Runnable;Ljava/lang/Object;)V", false, 1, NullnessAnnotation.CHECK_FOR_NULL);
addMethodParameterAnnotation("java.util.concurrent.ConcurrentSkipListMap", "doRemove", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", false, 1, NullnessAnnotation.CHECK_FOR_NULL);
addMethodAnnotation("java.util.concurrent.ConcurrentHashMap", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", false, NullnessAnnotation.CHECK_FOR_NULL);
addMethodAnnotation("java.util.concurrent.ConcurrentHashMap", "remove", "(Ljava/lang/Object;)Ljava/lang/Object;", false, NullnessAnnotation.CHECK_FOR_NULL);
addMethodAnnotation("java.util.concurrent.ConcurrentHashMap", "putIfAbsent", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", false, NullnessAnnotation.CHECK_FOR_NULL);
addMethodAnnotation("java.util.concurrent.locks.ReadWriteLock", "readLock", "()Ljava/util/concurrent/locks/Lock;", false, NullnessAnnotation.NONNULL);
addMethodAnnotation("java.util.concurrent.locks.ReadWriteLock", "writeLock", "()Ljava/util/concurrent/locks/Lock;", false, NullnessAnnotation.NONNULL);
addMethodAnnotation("java.util.concurrent.locks.ReentrantReadWriteLock", "readLock", "()Ljava/util/concurrent/locks/Lock;", false, NullnessAnnotation.NONNULL);
addMethodAnnotation("java.util.concurrent.locks.ReentrantReadWriteLock", "writeLock", "()Ljava/util/concurrent/locks/Lock;", false, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.concurrent.ThreadPoolExecutor", "addIfUnderCorePoolSize", "(Ljava/lang/Runnable;)Z", false, 0, NullnessAnnotation.CHECK_FOR_NULL);
addMethodParameterAnnotation("java.util.concurrent.ThreadPoolExecutor", "addThread", "(Ljava/lang/Runnable;)Ljava/lang/Thread;", false, 0, NullnessAnnotation.CHECK_FOR_NULL);
addMethodParameterAnnotation("java.util.concurrent.ThreadPoolExecutor", "afterExecute", "(Ljava/lang/Runnable;Ljava/lang/Throwable;)V", false, 1, NullnessAnnotation.CHECK_FOR_NULL);
addMethodParameterAnnotation("java.util.EnumMap", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.EnumMap", "containsKey", "(Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.EnumMap", "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.EnumMap", "remove", "(Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.SortedMap", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.SortedMap", "containsKey", "(Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.SortedMap", "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.SortedMap", "remove", "(Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.SortedSet", "add", "(Ljava/lang/Object;)Z", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.SortedSet", "remove", "(Ljava/lang/Object;)Z", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.SortedSet", "cotains", "(Ljava/lang/Object;)Z", false, 0, NullnessAnnotation.NONNULL);
// addMethodAnnotation("java.util.Queue", "poll", "()Ljava/lang/Object;", false, NullnessAnnotation.CHECK_FOR_NULL);
addMethodAnnotation("java.io.BufferedReader", "readLine", "()Ljava/lang/String;", false, NullnessAnnotation.CHECK_FOR_NULL);
}
public boolean parameterMustBeNonNull(XMethod m, int param) {
if (!anyAnnotations(NullnessAnnotation.NONNULL)) return false;
XMethodParameter xmp = new XMethodParameter(m,param);
NullnessAnnotation resolvedAnnotation = getResolvedAnnotation(xmp, true);
// System.out.println("QQQ parameter " + param + " of " + m + " is " + resolvedAnnotation);
return resolvedAnnotation == NullnessAnnotation.NONNULL;
}
@CheckForNull @Override
public NullnessAnnotation getResolvedAnnotation(final Object o, boolean getMinimal) {
if (o instanceof XMethodParameter) {
XMethodParameter mp = (XMethodParameter) o;
XMethod m = mp.getMethod();
if (m.getName().startsWith("access$")) return null;
if (mp.getParameterNumber() == 0 && m.getName().equals("equals")
&& m.getSignature().equals("(Ljava/lang/Object;)Z") && !m.isStatic())
return NullnessAnnotation.CHECK_FOR_NULL;
else if (mp.getParameterNumber() == 0 && m.getName().equals("compareTo")
&& m.getSignature().endsWith(";)Z") && !m.isStatic())
return NullnessAnnotation.NONNULL;
}
else if (o instanceof XMethod) {
XMethod m = (XMethod) o;
if (m.getName().startsWith("access$")) return null;
}
return super.getResolvedAnnotation(o, getMinimal);
}
}
| findbugs/src/java/edu/umd/cs/findbugs/ba/NullnessAnnotationDatabase.java | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2005, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.ba;
import edu.umd.cs.findbugs.annotations.CheckForNull;
/**
* @author pugh
*/
public class NullnessAnnotationDatabase extends AnnotationDatabase<NullnessAnnotation> {
public NullnessAnnotationDatabase() {
addDefaultAnnotation(AnnotationDatabase.METHOD, "java.lang.String", NullnessAnnotation.NONNULL);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.package-info", NullnessAnnotation.NONNULL);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.CopyOnWriteArrayList", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.CopyOnWriteArraySet", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ConcurrentLinkedQueue$Node", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.Exchanger", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.FutureTask", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.LinkedBlockingQueue$Node", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.SynchronousQueue$WaitQueue", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ThreadPoolExecutor$Worker", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.AbstractExecutorService", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ConcurrentSkipListMap$ConcurrentSkipListSubMap", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ConcurrentSkipListMap$HeadIndex", NullnessAnnotation.UNKNOWN_NULLNESS)
;
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ConcurrentSkipListMap$Index", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ConcurrentSkipListMap$Node", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ConcurrentSkipListMap$SubMap", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.ConcurrentSkipListSet$ConcurrentSkipListSubSet", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.LinkedBlockingDeque$Node", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.SynchronousQueue$TransferQueue", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.SynchronousQueue$TransferQueue$QNode", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.SynchronousQueue$TransferStack", NullnessAnnotation.UNKNOWN_NULLNESS);
addDefaultAnnotation(AnnotationDatabase.PARAMETER, "java.util.concurrent.SynchronousQueue$Transferer", NullnessAnnotation.UNKNOWN_NULLNESS);
addMethodParameterAnnotation("java.util.concurrent.ConcurrentHashMap$Segment", "remove", "(Ljava/lang/Object;ILjava/lang/Object;)Ljava/lang/Object;", false, 2, NullnessAnnotation.CHECK_FOR_NULL);
addMethodParameterAnnotation("java.util.concurrent.CyclicBarrier", "<init>", "(ILjava/lang/Runnable;)V", false, 1, NullnessAnnotation.CHECK_FOR_NULL);
addMethodParameterAnnotation("java.util.concurrent.Executors$RunnableAdapter", "<init>", "(Ljava/lang/Runnable;Ljava/lang/Object;)V", false, 1, NullnessAnnotation.CHECK_FOR_NULL);
addMethodParameterAnnotation("java.util.concurrent.ConcurrentSkipListMap", "doRemove", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", false, 1, NullnessAnnotation.CHECK_FOR_NULL);
addMethodAnnotation("java.util.concurrent.ConcurrentHashMap", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", false, NullnessAnnotation.CHECK_FOR_NULL);
addMethodAnnotation("java.util.concurrent.ConcurrentHashMap", "remove", "(Ljava/lang/Object;)Ljava/lang/Object;", false, NullnessAnnotation.CHECK_FOR_NULL);
addMethodAnnotation("java.util.concurrent.ConcurrentHashMap", "putIfAbsent", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", false, NullnessAnnotation.CHECK_FOR_NULL);
addMethodParameterAnnotation("java.util.concurrent.ThreadPoolExecutor", "addIfUnderCorePoolSize", "(Ljava/lang/Runnable;)Z", false, 0, NullnessAnnotation.CHECK_FOR_NULL);
addMethodParameterAnnotation("java.util.concurrent.ThreadPoolExecutor", "addThread", "(Ljava/lang/Runnable;)Ljava/lang/Thread;", false, 0, NullnessAnnotation.CHECK_FOR_NULL);
addMethodParameterAnnotation("java.util.concurrent.ThreadPoolExecutor", "afterExecute", "(Ljava/lang/Runnable;Ljava/lang/Throwable;)V", false, 1, NullnessAnnotation.CHECK_FOR_NULL);
addMethodParameterAnnotation("java.util.EnumMap", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.EnumMap", "containsKey", "(Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.EnumMap", "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.EnumMap", "remove", "(Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.SortedMap", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.SortedMap", "containsKey", "(Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.SortedMap", "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.SortedMap", "remove", "(Ljava/lang/Object;)Ljava/lang/Object;", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.SortedSet", "add", "(Ljava/lang/Object;)Z", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.SortedSet", "remove", "(Ljava/lang/Object;)Z", false, 0, NullnessAnnotation.NONNULL);
addMethodParameterAnnotation("java.util.SortedSet", "cotains", "(Ljava/lang/Object;)Z", false, 0, NullnessAnnotation.NONNULL);
// addMethodAnnotation("java.util.Queue", "poll", "()Ljava/lang/Object;", false, NullnessAnnotation.CHECK_FOR_NULL);
addMethodAnnotation("java.io.BufferedReader", "readLine", "()Ljava/lang/String;", false, NullnessAnnotation.CHECK_FOR_NULL);
}
public boolean parameterMustBeNonNull(XMethod m, int param) {
if (!anyAnnotations(NullnessAnnotation.NONNULL)) return false;
XMethodParameter xmp = new XMethodParameter(m,param);
NullnessAnnotation resolvedAnnotation = getResolvedAnnotation(xmp, true);
// System.out.println("QQQ parameter " + param + " of " + m + " is " + resolvedAnnotation);
return resolvedAnnotation == NullnessAnnotation.NONNULL;
}
@CheckForNull @Override
public NullnessAnnotation getResolvedAnnotation(final Object o, boolean getMinimal) {
if (o instanceof XMethodParameter) {
XMethodParameter mp = (XMethodParameter) o;
XMethod m = mp.getMethod();
if (m.getName().startsWith("access$")) return null;
if (mp.getParameterNumber() == 0 && m.getName().equals("equals")
&& m.getSignature().equals("(Ljava/lang/Object;)Z") && !m.isStatic())
return NullnessAnnotation.CHECK_FOR_NULL;
else if (mp.getParameterNumber() == 0 && m.getName().equals("compareTo")
&& m.getSignature().endsWith(";)Z") && !m.isStatic())
return NullnessAnnotation.NONNULL;
}
else if (o instanceof XMethod) {
XMethod m = (XMethod) o;
if (m.getName().startsWith("access$")) return null;
}
return super.getResolvedAnnotation(o, getMinimal);
}
}
| Tell system that readLock and writeLock always return nonnull values
git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@5935 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
| findbugs/src/java/edu/umd/cs/findbugs/ba/NullnessAnnotationDatabase.java | Tell system that readLock and writeLock always return nonnull values | <ide><path>indbugs/src/java/edu/umd/cs/findbugs/ba/NullnessAnnotationDatabase.java
<ide> addMethodAnnotation("java.util.concurrent.ConcurrentHashMap", "putIfAbsent", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", false, NullnessAnnotation.CHECK_FOR_NULL);
<ide>
<ide>
<add> addMethodAnnotation("java.util.concurrent.locks.ReadWriteLock", "readLock", "()Ljava/util/concurrent/locks/Lock;", false, NullnessAnnotation.NONNULL);
<add> addMethodAnnotation("java.util.concurrent.locks.ReadWriteLock", "writeLock", "()Ljava/util/concurrent/locks/Lock;", false, NullnessAnnotation.NONNULL);
<add> addMethodAnnotation("java.util.concurrent.locks.ReentrantReadWriteLock", "readLock", "()Ljava/util/concurrent/locks/Lock;", false, NullnessAnnotation.NONNULL);
<add> addMethodAnnotation("java.util.concurrent.locks.ReentrantReadWriteLock", "writeLock", "()Ljava/util/concurrent/locks/Lock;", false, NullnessAnnotation.NONNULL);
<add>
<add>
<ide> addMethodParameterAnnotation("java.util.concurrent.ThreadPoolExecutor", "addIfUnderCorePoolSize", "(Ljava/lang/Runnable;)Z", false, 0, NullnessAnnotation.CHECK_FOR_NULL);
<ide> addMethodParameterAnnotation("java.util.concurrent.ThreadPoolExecutor", "addThread", "(Ljava/lang/Runnable;)Ljava/lang/Thread;", false, 0, NullnessAnnotation.CHECK_FOR_NULL);
<ide> addMethodParameterAnnotation("java.util.concurrent.ThreadPoolExecutor", "afterExecute", "(Ljava/lang/Runnable;Ljava/lang/Throwable;)V", false, 1, NullnessAnnotation.CHECK_FOR_NULL); |
|
Java | apache-2.0 | 6456ebb55f83346630a9c04cb6e0eeaed9107fae | 0 | MadcowD/libgdx,xranby/libgdx,gf11speed/libgdx,PedroRomanoBarbosa/libgdx,mumer92/libgdx,NathanSweet/libgdx,realitix/libgdx,josephknight/libgdx,kagehak/libgdx,realitix/libgdx,titovmaxim/libgdx,MetSystem/libgdx,sinistersnare/libgdx,Thotep/libgdx,js78/libgdx,MovingBlocks/libgdx,flaiker/libgdx,ya7lelkom/libgdx,nelsonsilva/libgdx,Heart2009/libgdx,JFixby/libgdx,NathanSweet/libgdx,luischavez/libgdx,saqsun/libgdx,Senth/libgdx,antag99/libgdx,GreenLightning/libgdx,ninoalma/libgdx,revo09/libgdx,tell10glu/libgdx,jsjolund/libgdx,UnluckyNinja/libgdx,ninoalma/libgdx,FyiurAmron/libgdx,alex-dorokhov/libgdx,SidneyXu/libgdx,nelsonsilva/libgdx,JFixby/libgdx,zhimaijoy/libgdx,anserran/libgdx,Heart2009/libgdx,lordjone/libgdx,kagehak/libgdx,djom20/libgdx,nudelchef/libgdx,josephknight/libgdx,Xhanim/libgdx,FredGithub/libgdx,haedri/libgdx-1,noelsison2/libgdx,titovmaxim/libgdx,alireza-hosseini/libgdx,haedri/libgdx-1,nrallakis/libgdx,js78/libgdx,katiepino/libgdx,mumer92/libgdx,saqsun/libgdx,nrallakis/libgdx,gouessej/libgdx,alex-dorokhov/libgdx,azakhary/libgdx,junkdog/libgdx,snovak/libgdx,Deftwun/libgdx,jberberick/libgdx,stinsonga/libgdx,srwonka/libGdx,FyiurAmron/libgdx,ryoenji/libgdx,EsikAntony/libgdx,mumer92/libgdx,Dzamir/libgdx,toa5/libgdx,MikkelTAndersen/libgdx,noelsison2/libgdx,hyvas/libgdx,sjosegarcia/libgdx,MikkelTAndersen/libgdx,toloudis/libgdx,ninoalma/libgdx,hyvas/libgdx,nave966/libgdx,copystudy/libgdx,saqsun/libgdx,FredGithub/libgdx,alireza-hosseini/libgdx,gf11speed/libgdx,Zonglin-Li6565/libgdx,JFixby/libgdx,jberberick/libgdx,Badazdz/libgdx,azakhary/libgdx,ztv/libgdx,xranby/libgdx,GreenLightning/libgdx,tommycli/libgdx,azakhary/libgdx,1yvT0s/libgdx,SidneyXu/libgdx,czyzby/libgdx,tommycli/libgdx,1yvT0s/libgdx,ninoalma/libgdx,lordjone/libgdx,nrallakis/libgdx,xpenatan/libgdx-LWJGL3,ttencate/libgdx,Badazdz/libgdx,sarkanyi/libgdx,gf11speed/libgdx,srwonka/libGdx,katiepino/libgdx,nave966/libgdx,Badazdz/libgdx,stickyd/libgdx,andyvand/libgdx,Dzamir/libgdx,firefly2442/libgdx,stickyd/libgdx,del-sol/libgdx,nudelchef/libgdx,MathieuDuponchelle/gdx,thepullman/libgdx,zhimaijoy/libgdx,MathieuDuponchelle/gdx,davebaol/libgdx,Gliby/libgdx,libgdx/libgdx,toa5/libgdx,ricardorigodon/libgdx,ThiagoGarciaAlves/libgdx,sarkanyi/libgdx,codepoke/libgdx,andyvand/libgdx,bsmr-java/libgdx,del-sol/libgdx,KrisLee/libgdx,del-sol/libgdx,nrallakis/libgdx,junkdog/libgdx,bgroenks96/libgdx,ttencate/libgdx,xpenatan/libgdx-LWJGL3,sarkanyi/libgdx,flaiker/libgdx,xoppa/libgdx,luischavez/libgdx,yangweigbh/libgdx,ricardorigodon/libgdx,toloudis/libgdx,FredGithub/libgdx,ninoalma/libgdx,SidneyXu/libgdx,luischavez/libgdx,sjosegarcia/libgdx,youprofit/libgdx,jasonwee/libgdx,BlueRiverInteractive/libgdx,PedroRomanoBarbosa/libgdx,ttencate/libgdx,UnluckyNinja/libgdx,czyzby/libgdx,hyvas/libgdx,tell10glu/libgdx,bgroenks96/libgdx,davebaol/libgdx,srwonka/libGdx,thepullman/libgdx,MathieuDuponchelle/gdx,del-sol/libgdx,GreenLightning/libgdx,tommyettinger/libgdx,gdos/libgdx,xranby/libgdx,Deftwun/libgdx,GreenLightning/libgdx,kzganesan/libgdx,ya7lelkom/libgdx,Badazdz/libgdx,tell10glu/libgdx,ztv/libgdx,nudelchef/libgdx,fwolff/libgdx,realitix/libgdx,Dzamir/libgdx,TheAks999/libgdx,copystudy/libgdx,yangweigbh/libgdx,gouessej/libgdx,fwolff/libgdx,collinsmith/libgdx,stickyd/libgdx,UnluckyNinja/libgdx,Badazdz/libgdx,gdos/libgdx,MetSystem/libgdx,Wisienkas/libgdx,revo09/libgdx,jasonwee/libgdx,sjosegarcia/libgdx,jsjolund/libgdx,jsjolund/libgdx,zhimaijoy/libgdx,JFixby/libgdx,UnluckyNinja/libgdx,xoppa/libgdx,Gliby/libgdx,xoppa/libgdx,Gliby/libgdx,nudelchef/libgdx,yangweigbh/libgdx,youprofit/libgdx,ryoenji/libgdx,stinsonga/libgdx,js78/libgdx,alireza-hosseini/libgdx,JDReutt/libgdx,saltares/libgdx,fwolff/libgdx,JDReutt/libgdx,nrallakis/libgdx,jberberick/libgdx,Wisienkas/libgdx,anserran/libgdx,flaiker/libgdx,1yvT0s/libgdx,petugez/libgdx,designcrumble/libgdx,PedroRomanoBarbosa/libgdx,curtiszimmerman/libgdx,saltares/libgdx,tommycli/libgdx,jsjolund/libgdx,toa5/libgdx,bgroenks96/libgdx,zommuter/libgdx,petugez/libgdx,BlueRiverInteractive/libgdx,alex-dorokhov/libgdx,PedroRomanoBarbosa/libgdx,curtiszimmerman/libgdx,noelsison2/libgdx,snovak/libgdx,PedroRomanoBarbosa/libgdx,ninoalma/libgdx,katiepino/libgdx,zhimaijoy/libgdx,309746069/libgdx,EsikAntony/libgdx,Zonglin-Li6565/libgdx,kagehak/libgdx,samskivert/libgdx,stickyd/libgdx,gf11speed/libgdx,basherone/libgdxcn,revo09/libgdx,sinistersnare/libgdx,MadcowD/libgdx,Wisienkas/libgdx,saqsun/libgdx,ThiagoGarciaAlves/libgdx,hyvas/libgdx,gdos/libgdx,SidneyXu/libgdx,toloudis/libgdx,gdos/libgdx,shiweihappy/libgdx,ryoenji/libgdx,ya7lelkom/libgdx,anserran/libgdx,MovingBlocks/libgdx,saltares/libgdx,MadcowD/libgdx,titovmaxim/libgdx,JDReutt/libgdx,toloudis/libgdx,haedri/libgdx-1,andyvand/libgdx,curtiszimmerman/libgdx,sjosegarcia/libgdx,Deftwun/libgdx,jberberick/libgdx,Thotep/libgdx,luischavez/libgdx,MikkelTAndersen/libgdx,antag99/libgdx,JFixby/libgdx,saltares/libgdx,andyvand/libgdx,xranby/libgdx,toloudis/libgdx,kotcrab/libgdx,FyiurAmron/libgdx,fiesensee/libgdx,toloudis/libgdx,stickyd/libgdx,ryoenji/libgdx,xoppa/libgdx,MadcowD/libgdx,youprofit/libgdx,noelsison2/libgdx,1yvT0s/libgdx,djom20/libgdx,nooone/libgdx,bsmr-java/libgdx,tommyettinger/libgdx,shiweihappy/libgdx,ya7lelkom/libgdx,designcrumble/libgdx,bladecoder/libgdx,Arcnor/libgdx,gouessej/libgdx,ztv/libgdx,revo09/libgdx,MetSystem/libgdx,UnluckyNinja/libgdx,SidneyXu/libgdx,bladecoder/libgdx,billgame/libgdx,youprofit/libgdx,del-sol/libgdx,bladecoder/libgdx,xpenatan/libgdx-LWJGL3,PedroRomanoBarbosa/libgdx,FredGithub/libgdx,collinsmith/libgdx,Xhanim/libgdx,del-sol/libgdx,kzganesan/libgdx,MikkelTAndersen/libgdx,thepullman/libgdx,codepoke/libgdx,TheAks999/libgdx,MadcowD/libgdx,lordjone/libgdx,haedri/libgdx-1,jasonwee/libgdx,djom20/libgdx,junkdog/libgdx,gouessej/libgdx,Arcnor/libgdx,sjosegarcia/libgdx,basherone/libgdxcn,Zomby2D/libgdx,realitix/libgdx,MetSystem/libgdx,bladecoder/libgdx,gf11speed/libgdx,luischavez/libgdx,ricardorigodon/libgdx,MadcowD/libgdx,fwolff/libgdx,czyzby/libgdx,FredGithub/libgdx,1yvT0s/libgdx,andyvand/libgdx,samskivert/libgdx,fwolff/libgdx,nave966/libgdx,KrisLee/libgdx,lordjone/libgdx,libgdx/libgdx,copystudy/libgdx,Gliby/libgdx,antag99/libgdx,FredGithub/libgdx,mumer92/libgdx,tommycli/libgdx,cypherdare/libgdx,ttencate/libgdx,309746069/libgdx,nudelchef/libgdx,bsmr-java/libgdx,alex-dorokhov/libgdx,kotcrab/libgdx,Deftwun/libgdx,xranby/libgdx,nrallakis/libgdx,kzganesan/libgdx,copystudy/libgdx,Badazdz/libgdx,Wisienkas/libgdx,bgroenks96/libgdx,Thotep/libgdx,FyiurAmron/libgdx,nave966/libgdx,junkdog/libgdx,ThiagoGarciaAlves/libgdx,billgame/libgdx,srwonka/libGdx,zommuter/libgdx,yangweigbh/libgdx,katiepino/libgdx,tommyettinger/libgdx,djom20/libgdx,bgroenks96/libgdx,copystudy/libgdx,nelsonsilva/libgdx,ThiagoGarciaAlves/libgdx,1yvT0s/libgdx,Thotep/libgdx,bgroenks96/libgdx,azakhary/libgdx,anserran/libgdx,luischavez/libgdx,ryoenji/libgdx,josephknight/libgdx,Thotep/libgdx,antag99/libgdx,MathieuDuponchelle/gdx,ThiagoGarciaAlves/libgdx,saqsun/libgdx,hyvas/libgdx,gdos/libgdx,Heart2009/libgdx,309746069/libgdx,Dzamir/libgdx,xoppa/libgdx,TheAks999/libgdx,UnluckyNinja/libgdx,SidneyXu/libgdx,noelsison2/libgdx,jsjolund/libgdx,alireza-hosseini/libgdx,designcrumble/libgdx,nave966/libgdx,billgame/libgdx,revo09/libgdx,nrallakis/libgdx,Xhanim/libgdx,JFixby/libgdx,youprofit/libgdx,shiweihappy/libgdx,GreenLightning/libgdx,gf11speed/libgdx,libgdx/libgdx,fwolff/libgdx,lordjone/libgdx,bsmr-java/libgdx,sarkanyi/libgdx,jsjolund/libgdx,billgame/libgdx,djom20/libgdx,thepullman/libgdx,Heart2009/libgdx,js78/libgdx,gouessej/libgdx,curtiszimmerman/libgdx,Thotep/libgdx,flaiker/libgdx,ricardorigodon/libgdx,billgame/libgdx,gf11speed/libgdx,davebaol/libgdx,alireza-hosseini/libgdx,fiesensee/libgdx,firefly2442/libgdx,sarkanyi/libgdx,revo09/libgdx,ztv/libgdx,FyiurAmron/libgdx,snovak/libgdx,gdos/libgdx,josephknight/libgdx,josephknight/libgdx,stickyd/libgdx,gouessej/libgdx,realitix/libgdx,ricardorigodon/libgdx,nudelchef/libgdx,firefly2442/libgdx,ryoenji/libgdx,UnluckyNinja/libgdx,SidneyXu/libgdx,zommuter/libgdx,ztv/libgdx,Senth/libgdx,snovak/libgdx,gdos/libgdx,FyiurAmron/libgdx,js78/libgdx,djom20/libgdx,lordjone/libgdx,samskivert/libgdx,Zomby2D/libgdx,Xhanim/libgdx,309746069/libgdx,codepoke/libgdx,Wisienkas/libgdx,katiepino/libgdx,Xhanim/libgdx,MovingBlocks/libgdx,Senth/libgdx,noelsison2/libgdx,Arcnor/libgdx,hyvas/libgdx,stickyd/libgdx,TheAks999/libgdx,MikkelTAndersen/libgdx,tell10glu/libgdx,ztv/libgdx,yangweigbh/libgdx,xranby/libgdx,billgame/libgdx,BlueRiverInteractive/libgdx,MikkelTAndersen/libgdx,BlueRiverInteractive/libgdx,Zomby2D/libgdx,saltares/libgdx,collinsmith/libgdx,TheAks999/libgdx,KrisLee/libgdx,ricardorigodon/libgdx,czyzby/libgdx,jasonwee/libgdx,realitix/libgdx,yangweigbh/libgdx,nave966/libgdx,toa5/libgdx,EsikAntony/libgdx,saqsun/libgdx,MathieuDuponchelle/gdx,andyvand/libgdx,shiweihappy/libgdx,firefly2442/libgdx,xoppa/libgdx,sinistersnare/libgdx,thepullman/libgdx,MetSystem/libgdx,lordjone/libgdx,anserran/libgdx,copystudy/libgdx,thepullman/libgdx,sinistersnare/libgdx,fwolff/libgdx,Deftwun/libgdx,thepullman/libgdx,gdos/libgdx,katiepino/libgdx,davebaol/libgdx,GreenLightning/libgdx,fiesensee/libgdx,ztv/libgdx,curtiszimmerman/libgdx,MathieuDuponchelle/gdx,jasonwee/libgdx,saqsun/libgdx,zhimaijoy/libgdx,JDReutt/libgdx,tommyettinger/libgdx,saltares/libgdx,Heart2009/libgdx,MovingBlocks/libgdx,sinistersnare/libgdx,MathieuDuponchelle/gdx,Dzamir/libgdx,bladecoder/libgdx,MovingBlocks/libgdx,sjosegarcia/libgdx,nrallakis/libgdx,thepullman/libgdx,titovmaxim/libgdx,nave966/libgdx,xpenatan/libgdx-LWJGL3,tommycli/libgdx,cypherdare/libgdx,js78/libgdx,collinsmith/libgdx,BlueRiverInteractive/libgdx,gf11speed/libgdx,realitix/libgdx,stickyd/libgdx,sarkanyi/libgdx,codepoke/libgdx,Zonglin-Li6565/libgdx,MikkelTAndersen/libgdx,toa5/libgdx,kzganesan/libgdx,fiesensee/libgdx,Gliby/libgdx,mumer92/libgdx,309746069/libgdx,firefly2442/libgdx,Dzamir/libgdx,nooone/libgdx,hyvas/libgdx,Badazdz/libgdx,Wisienkas/libgdx,firefly2442/libgdx,titovmaxim/libgdx,tell10glu/libgdx,ricardorigodon/libgdx,hyvas/libgdx,toa5/libgdx,jsjolund/libgdx,shiweihappy/libgdx,NathanSweet/libgdx,kagehak/libgdx,sarkanyi/libgdx,ThiagoGarciaAlves/libgdx,antag99/libgdx,andyvand/libgdx,curtiszimmerman/libgdx,ya7lelkom/libgdx,flaiker/libgdx,KrisLee/libgdx,fiesensee/libgdx,Gliby/libgdx,alex-dorokhov/libgdx,srwonka/libGdx,nelsonsilva/libgdx,zhimaijoy/libgdx,Thotep/libgdx,revo09/libgdx,ninoalma/libgdx,xpenatan/libgdx-LWJGL3,alex-dorokhov/libgdx,anserran/libgdx,czyzby/libgdx,antag99/libgdx,djom20/libgdx,toloudis/libgdx,jsjolund/libgdx,ThiagoGarciaAlves/libgdx,zommuter/libgdx,FyiurAmron/libgdx,KrisLee/libgdx,Zonglin-Li6565/libgdx,JDReutt/libgdx,NathanSweet/libgdx,Senth/libgdx,libgdx/libgdx,Senth/libgdx,kzganesan/libgdx,stinsonga/libgdx,fiesensee/libgdx,ninoalma/libgdx,xranby/libgdx,MetSystem/libgdx,JDReutt/libgdx,JDReutt/libgdx,codepoke/libgdx,sjosegarcia/libgdx,mumer92/libgdx,alireza-hosseini/libgdx,nooone/libgdx,nooone/libgdx,ttencate/libgdx,haedri/libgdx-1,designcrumble/libgdx,samskivert/libgdx,MathieuDuponchelle/gdx,fwolff/libgdx,tommycli/libgdx,ttencate/libgdx,Badazdz/libgdx,junkdog/libgdx,MathieuDuponchelle/gdx,MadcowD/libgdx,haedri/libgdx-1,bsmr-java/libgdx,MikkelTAndersen/libgdx,1yvT0s/libgdx,JDReutt/libgdx,saltares/libgdx,Senth/libgdx,zommuter/libgdx,andyvand/libgdx,nelsonsilva/libgdx,katiepino/libgdx,KrisLee/libgdx,MovingBlocks/libgdx,KrisLee/libgdx,djom20/libgdx,codepoke/libgdx,ya7lelkom/libgdx,bgroenks96/libgdx,js78/libgdx,Xhanim/libgdx,snovak/libgdx,Thotep/libgdx,srwonka/libGdx,NathanSweet/libgdx,anserran/libgdx,srwonka/libGdx,BlueRiverInteractive/libgdx,flaiker/libgdx,snovak/libgdx,xoppa/libgdx,js78/libgdx,youprofit/libgdx,bsmr-java/libgdx,EsikAntony/libgdx,czyzby/libgdx,snovak/libgdx,zommuter/libgdx,kagehak/libgdx,czyzby/libgdx,309746069/libgdx,copystudy/libgdx,samskivert/libgdx,copystudy/libgdx,basherone/libgdxcn,bsmr-java/libgdx,xpenatan/libgdx-LWJGL3,Deftwun/libgdx,saqsun/libgdx,curtiszimmerman/libgdx,Xhanim/libgdx,jasonwee/libgdx,firefly2442/libgdx,davebaol/libgdx,snovak/libgdx,flaiker/libgdx,FredGithub/libgdx,zhimaijoy/libgdx,samskivert/libgdx,antag99/libgdx,davebaol/libgdx,toa5/libgdx,BlueRiverInteractive/libgdx,junkdog/libgdx,toa5/libgdx,kagehak/libgdx,Wisienkas/libgdx,jberberick/libgdx,noelsison2/libgdx,revo09/libgdx,fiesensee/libgdx,billgame/libgdx,tell10glu/libgdx,jberberick/libgdx,kotcrab/libgdx,BlueRiverInteractive/libgdx,SidneyXu/libgdx,zommuter/libgdx,xranby/libgdx,Dzamir/libgdx,collinsmith/libgdx,collinsmith/libgdx,Deftwun/libgdx,kotcrab/libgdx,MetSystem/libgdx,jberberick/libgdx,shiweihappy/libgdx,yangweigbh/libgdx,bsmr-java/libgdx,xpenatan/libgdx-LWJGL3,PedroRomanoBarbosa/libgdx,TheAks999/libgdx,Gliby/libgdx,PedroRomanoBarbosa/libgdx,KrisLee/libgdx,kagehak/libgdx,czyzby/libgdx,josephknight/libgdx,ttencate/libgdx,ricardorigodon/libgdx,libgdx/libgdx,EsikAntony/libgdx,JFixby/libgdx,nudelchef/libgdx,jasonwee/libgdx,nave966/libgdx,basherone/libgdxcn,stinsonga/libgdx,bgroenks96/libgdx,antag99/libgdx,srwonka/libGdx,Xhanim/libgdx,gouessej/libgdx,kzganesan/libgdx,kzganesan/libgdx,JFixby/libgdx,Zomby2D/libgdx,codepoke/libgdx,Deftwun/libgdx,titovmaxim/libgdx,petugez/libgdx,josephknight/libgdx,nooone/libgdx,ThiagoGarciaAlves/libgdx,GreenLightning/libgdx,Heart2009/libgdx,ryoenji/libgdx,Senth/libgdx,Gliby/libgdx,ya7lelkom/libgdx,fiesensee/libgdx,Dzamir/libgdx,xoppa/libgdx,mumer92/libgdx,noelsison2/libgdx,youprofit/libgdx,gouessej/libgdx,tell10glu/libgdx,309746069/libgdx,lordjone/libgdx,haedri/libgdx-1,TheAks999/libgdx,designcrumble/libgdx,titovmaxim/libgdx,billgame/libgdx,kagehak/libgdx,EsikAntony/libgdx,josephknight/libgdx,flaiker/libgdx,kotcrab/libgdx,youprofit/libgdx,stinsonga/libgdx,EsikAntony/libgdx,Zonglin-Li6565/libgdx,toloudis/libgdx,junkdog/libgdx,sarkanyi/libgdx,Zonglin-Li6565/libgdx,TheAks999/libgdx,Senth/libgdx,junkdog/libgdx,MovingBlocks/libgdx,alex-dorokhov/libgdx,katiepino/libgdx,1yvT0s/libgdx,collinsmith/libgdx,Heart2009/libgdx,Zonglin-Li6565/libgdx,designcrumble/libgdx,collinsmith/libgdx,realitix/libgdx,sinistersnare/libgdx,del-sol/libgdx,ztv/libgdx,Zonglin-Li6565/libgdx,samskivert/libgdx,luischavez/libgdx,tommycli/libgdx,tommycli/libgdx,nelsonsilva/libgdx,zommuter/libgdx,titovmaxim/libgdx,Wisienkas/libgdx,codepoke/libgdx,petugez/libgdx,ya7lelkom/libgdx,kotcrab/libgdx,del-sol/libgdx,jberberick/libgdx,cypherdare/libgdx,Heart2009/libgdx,MetSystem/libgdx,kotcrab/libgdx,zhimaijoy/libgdx,ttencate/libgdx,luischavez/libgdx,alireza-hosseini/libgdx,curtiszimmerman/libgdx,kotcrab/libgdx,cypherdare/libgdx,azakhary/libgdx,yangweigbh/libgdx,cypherdare/libgdx,azakhary/libgdx,UnluckyNinja/libgdx,xpenatan/libgdx-LWJGL3,basherone/libgdxcn,shiweihappy/libgdx,tell10glu/libgdx,FyiurAmron/libgdx,basherone/libgdxcn,Arcnor/libgdx,mumer92/libgdx,petugez/libgdx,haedri/libgdx-1,Arcnor/libgdx,designcrumble/libgdx,petugez/libgdx,nooone/libgdx,shiweihappy/libgdx,jasonwee/libgdx,saltares/libgdx,nudelchef/libgdx,GreenLightning/libgdx,samskivert/libgdx,Arcnor/libgdx,Zomby2D/libgdx,anserran/libgdx,petugez/libgdx,firefly2442/libgdx,EsikAntony/libgdx,designcrumble/libgdx,MovingBlocks/libgdx,sjosegarcia/libgdx,MadcowD/libgdx,alireza-hosseini/libgdx,FredGithub/libgdx,petugez/libgdx,tommyettinger/libgdx,alex-dorokhov/libgdx,309746069/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.scenes.scene2d;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.InputEvent.Type;
import com.badlogic.gdx.scenes.scene2d.utils.FocusListener.FocusEvent;
import com.badlogic.gdx.scenes.scene2d.utils.ScissorStack;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.Pool.Poolable;
import com.badlogic.gdx.utils.Pools;
import com.badlogic.gdx.utils.SnapshotArray;
/** A 2D scenegraph containing hierarchies of {@link Actor actors}. Stage handles the viewport and distributing input events.
* <p>
* A stage fills the whole screen. {@link #setViewport} controls the coordinates used within the stage and sets up the camera used
* to convert between stage coordinates and screen coordinates. *
* <p>
* A stage must receive input events so it can distribute them to actors. This is typically done by passing the stage to
* {@link Input#setInputProcessor(com.badlogic.gdx.InputProcessor) Gdx.input.setInputProcessor}. An {@link InputMultiplexer} may be
* used to handle input events before or after the stage does. If an actor handles an event by returning true from the input
* method, then the stage's input method will also return true, causing subsequent InputProcessors to not receive the event.
* @author mzechner
* @author Nathan Sweet */
public class Stage extends InputAdapter implements Disposable {
private float width, height;
private float gutterWidth, gutterHeight;
private float centerX, centerY;
private Camera camera;
private final SpriteBatch batch;
private final boolean ownsBatch;
private Group root;
private final Vector2 stageCoords = new Vector2();
private Actor[] pointerOverActors = new Actor[20];
private boolean[] pointerTouched = new boolean[20];
private int[] pointerScreenX = new int[20];
private int[] pointerScreenY = new int[20];
private int mouseScreenX, mouseScreenY;
private Actor mouseOverActor;
private Actor keyboardFocus, scrollFocus;
private SnapshotArray<TouchFocus> touchFocuses = new SnapshotArray(true, 4, TouchFocus.class);
/** Creates a stage with a {@link #setViewport(float, float, boolean) viewport} equal to the device screen resolution. The stage
* will use its own {@link SpriteBatch}. */
public Stage () {
this(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
}
/** Creates a stage with the specified {@link #setViewport(float, float, boolean) viewport}. The stage will use its own
* {@link SpriteBatch}, which will be disposed when the stage is disposed. */
public Stage (float width, float height, boolean stretch) {
batch = new SpriteBatch();
ownsBatch = true;
initialize(width, height, stretch);
}
/** Creates a stage with the specified {@link #setViewport(float, float, boolean) viewport} and {@link SpriteBatch}. This can be
* used to avoid creating a new SpriteBatch (which can be somewhat slow) if multiple stages are used during an applications
* life time.
* @param batch Will not be disposed if {@link #dispose()} is called. Handle disposal yourself. */
public Stage (float width, float height, boolean stretch, SpriteBatch batch) {
this.batch = batch;
ownsBatch = false;
initialize(width, height, stretch);
}
private void initialize (float width, float height, boolean stretch) {
this.width = width;
this.height = height;
root = new Group();
root.setStage(this);
camera = new OrthographicCamera();
setViewport(width, height, stretch);
}
/** Sets the dimensions of the stage's viewport. The viewport covers the entire screen. If keepAspectRatio is false, the
* viewport is simply stretched to the screen resolution, which may distort the aspect ratio. If keepAspectRatio is true, the
* viewport is first scaled to fit then the shorter dimension is lengthened to fill the screen, which keeps the aspect ratio
* from changing. The {@link #getGutterWidth()} and {@link #getGutterHeight()} provide access to the amount that was
* lengthened. */
public void setViewport (float width, float height, boolean keepAspectRatio) {
if (keepAspectRatio) {
float screenWidth = Gdx.graphics.getWidth();
float screenHeight = Gdx.graphics.getHeight();
if (screenHeight / screenWidth < height / width) {
float toScreenSpace = screenHeight / height;
float toViewportSpace = height / screenHeight;
float deviceWidth = width * toScreenSpace;
float lengthen = (screenWidth - deviceWidth) * toViewportSpace;
this.width = width + lengthen;
this.height = height;
gutterWidth = lengthen / 2;
gutterHeight = 0;
} else {
float toScreenSpace = screenWidth / width;
float toViewportSpace = width / screenWidth;
float deviceHeight = height * toScreenSpace;
float lengthen = (screenHeight - deviceHeight) * toViewportSpace;
this.height = height + lengthen;
this.width = width;
gutterWidth = 0;
gutterHeight = lengthen / 2;
}
} else {
this.width = width;
this.height = height;
gutterWidth = 0;
gutterHeight = 0;
}
centerX = this.width / 2;
centerY = this.height / 2;
camera.position.set(centerX, centerY, 0);
camera.viewportWidth = this.width;
camera.viewportHeight = this.height;
}
public void draw () {
camera.update();
if (!root.isVisible()) return;
batch.setProjectionMatrix(camera.combined);
batch.begin();
root.draw(batch, 1);
batch.end();
}
/** Calls {@link #act(float)} with {@link Graphics#getDeltaTime()}. */
public void act () {
act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
}
/** Calls the {@link Actor#act(float)} method on each actor in the stage. Typically called each frame. This method also fires
* enter and exit events.
* @param delta Time in seconds since the last frame. */
public void act (float delta) {
// Update over actors. Done in act() because actors may change position, which can fire enter/exit without an input event.
for (int pointer = 0, n = pointerOverActors.length; pointer < n; pointer++) {
Actor overLast = pointerOverActors[pointer];
// Check if pointer is gone.
if (!pointerTouched[pointer]) {
if (overLast != null) {
pointerOverActors[pointer] = null;
screenToStageCoordinates(stageCoords.set(pointerScreenX[pointer], pointerScreenY[pointer]));
// Exit over last.
InputEvent event = Pools.obtain(InputEvent.class);
event.setType(InputEvent.Type.exit);
event.setStage(this);
event.setStageX(stageCoords.x);
event.setStageY(stageCoords.y);
event.setRelatedActor(overLast);
event.setPointer(pointer);
overLast.fire(event);
Pools.free(event);
}
continue;
}
// Update over actor for the pointer.
pointerOverActors[pointer] = fireEnterAndExit(overLast, pointerScreenX[pointer], pointerScreenY[pointer], pointer);
}
// Update over actor for the mouse on the desktop.
if (Gdx.app.getType() == ApplicationType.Desktop)
mouseOverActor = fireEnterAndExit(mouseOverActor, mouseScreenX, mouseScreenY, -1);
root.act(delta);
}
private Actor fireEnterAndExit (Actor overLast, int screenX, int screenY, int pointer) {
// Find the actor under the point.
screenToStageCoordinates(stageCoords.set(screenX, screenY));
Actor over = hit(stageCoords.x, stageCoords.y, true);
if (over == overLast) return overLast;
InputEvent event = Pools.obtain(InputEvent.class);
event.setStage(this);
event.setStageX(stageCoords.x);
event.setStageY(stageCoords.y);
event.setPointer(pointer);
// Exit overLast.
if (overLast != null) {
event.setType(InputEvent.Type.exit);
event.setRelatedActor(over);
overLast.fire(event);
}
// Enter over.
if (over != null) {
event.setType(InputEvent.Type.enter);
event.setRelatedActor(overLast);
over.fire(event);
}
Pools.free(event);
return over;
}
/** Applies a touch down event to the stage and returns true if an actor in the scene {@link Event#handle() handled} the event. */
public boolean touchDown (int screenX, int screenY, int pointer, int button) {
pointerTouched[pointer] = true;
pointerScreenX[pointer] = screenX;
pointerScreenY[pointer] = screenY;
screenToStageCoordinates(stageCoords.set(screenX, screenY));
InputEvent event = Pools.obtain(InputEvent.class);
event.setType(Type.touchDown);
event.setStage(this);
event.setStageX(stageCoords.x);
event.setStageY(stageCoords.y);
event.setPointer(pointer);
event.setButton(button);
Actor target = hit(stageCoords.x, stageCoords.y, true);
if (target == null) target = root;
target.fire(event);
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Applies a touch moved event to the stage and returns true if an actor in the scene {@link Event#handle() handled} the event.
* Only {@link InputListener listeners} that returned true for touchDown will receive this event. */
public boolean touchDragged (int screenX, int screenY, int pointer) {
pointerScreenX[pointer] = screenX;
pointerScreenY[pointer] = screenY;
if (touchFocuses.size == 0) return false;
screenToStageCoordinates(stageCoords.set(screenX, screenY));
InputEvent event = Pools.obtain(InputEvent.class);
event.setType(Type.touchDragged);
event.setStage(this);
event.setStageX(stageCoords.x);
event.setStageY(stageCoords.y);
event.setPointer(pointer);
SnapshotArray<TouchFocus> touchFocuses = this.touchFocuses;
TouchFocus[] focuses = touchFocuses.begin();
for (int i = 0, n = touchFocuses.size; i < n; i++) {
TouchFocus focus = focuses[i];
if (focus.pointer != pointer) continue;
event.setTarget(focus.target);
event.setListenerActor(focus.listenerActor);
if (focus.listener.handle(event)) event.handle();
}
touchFocuses.end();
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Applies a touch up event to the stage and returns true if an actor in the scene {@link Event#handle() handled} the event.
* Only {@link InputListener listeners} that returned true for touchDown will receive this event. */
public boolean touchUp (int screenX, int screenY, int pointer, int button) {
pointerTouched[pointer] = false;
pointerScreenX[pointer] = screenX;
pointerScreenY[pointer] = screenY;
if (touchFocuses.size == 0) return false;
screenToStageCoordinates(stageCoords.set(screenX, screenY));
InputEvent event = Pools.obtain(InputEvent.class);
event.setType(Type.touchUp);
event.setStage(this);
event.setStageX(stageCoords.x);
event.setStageY(stageCoords.y);
event.setPointer(pointer);
event.setButton(button);
SnapshotArray<TouchFocus> touchFocuses = this.touchFocuses;
TouchFocus[] focuses = touchFocuses.begin();
for (int i = 0, n = touchFocuses.size; i < n; i++) {
TouchFocus focus = focuses[i];
if (focus.pointer != pointer || focus.button != button) continue;
event.setTarget(focus.target);
event.setListenerActor(focus.listenerActor);
if (focus.listener.handle(event)) event.handle();
}
touchFocuses.end();
for (int i = touchFocuses.size - 1; i >= 0; i--) {
TouchFocus focus = touchFocuses.get(i);
if (focus.pointer != pointer || focus.button != button) continue;
touchFocuses.removeIndex(i);
Pools.free(focus);
}
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Applies a mouse moved event to the stage and returns true if an actor in the scene {@link Event#handle() handled} the event.
* This event only occurs on the desktop. */
public boolean mouseMoved (int screenX, int screenY) {
mouseScreenX = screenX;
mouseScreenY = screenY;
screenToStageCoordinates(stageCoords.set(screenX, screenY));
InputEvent event = Pools.obtain(InputEvent.class);
event.setStage(this);
event.setType(Type.mouseMoved);
event.setStageX(stageCoords.x);
event.setStageY(stageCoords.y);
Actor target = hit(stageCoords.x, stageCoords.y, true);
if (target == null) target = root;
target.fire(event);
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Applies a mouse scroll event to the stage and returns true if an actor in the scene {@link Event#handle() handled} the
* event. This event only occurs on the desktop. */
public boolean scrolled (int amount) {
if (scrollFocus == null) return false;
InputEvent event = Pools.obtain(InputEvent.class);
event.setStage(this);
event.setType(InputEvent.Type.scrolled);
event.setScrollAmount(amount);
scrollFocus.fire(event);
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Applies a key down event to the actor that has {@link Stage#setKeyboardFocus(Actor) keyboard focus}, if any, and returns
* true if the event was {@link Event#handle() handled}. */
public boolean keyDown (int keyCode) {
if (keyboardFocus == null) return false;
InputEvent event = Pools.obtain(InputEvent.class);
event.setStage(this);
event.setType(InputEvent.Type.keyDown);
event.setKeyCode(keyCode);
keyboardFocus.fire(event);
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Applies a key up event to the actor that has {@link Stage#setKeyboardFocus(Actor) keyboard focus}, if any, and returns true
* if the event was {@link Event#handle() handled}. */
public boolean keyUp (int keyCode) {
if (keyboardFocus == null) return false;
InputEvent event = Pools.obtain(InputEvent.class);
event.setStage(this);
event.setType(InputEvent.Type.keyUp);
event.setKeyCode(keyCode);
keyboardFocus.fire(event);
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Applies a key typed event to the actor that has {@link Stage#setKeyboardFocus(Actor) keyboard focus}, if any, and returns
* true if the event was {@link Event#handle() handled}. */
public boolean keyTyped (char character) {
if (keyboardFocus == null) return false;
InputEvent event = Pools.obtain(InputEvent.class);
event.setStage(this);
event.setType(InputEvent.Type.keyTyped);
event.setCharacter(character);
keyboardFocus.fire(event);
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Adds the listener to be notified for all touchDragged and touchUp events for the specified pointer and button. The actor
* will be used as the {@link Event#getListenerActor() listener actor} and {@link Event#getTarget() target}. */
public void addTouchFocus (EventListener listener, Actor listenerActor, Actor target, int pointer, int button) {
TouchFocus focus = Pools.obtain(TouchFocus.class);
focus.listenerActor = listenerActor;
focus.target = target;
focus.listener = listener;
focus.pointer = pointer;
focus.button = button;
touchFocuses.add(focus);
}
/** Removes the listener from being notified for all touchDragged and touchUp events for the specified pointer and button. Note
* the listener may never receive a touchUp event if this method is used. */
public void removeTouchFocus (EventListener listener, Actor listenerActor, Actor target, int pointer, int button) {
SnapshotArray<TouchFocus> touchFocuses = this.touchFocuses;
for (int i = touchFocuses.size - 1; i >= 0; i--) {
TouchFocus focus = touchFocuses.get(i);
if (focus.listener == listener && focus.listenerActor == listenerActor && focus.target == target
&& focus.pointer == pointer && focus.button == button) {
touchFocuses.removeIndex(i);
Pools.free(focus);
}
}
}
/** Sends a touchUp event to all listeners that are registered to receive touchDragged and touchUp events and removes their
* touch focus. The location of the touchUp is {@link Integer#MIN_VALUE}. This method removes all touch focus listeners, but
* sends a touchUp event so that the state of the listeners remains consistent (listeners typically expect to receive touchUp
* eventually). */
public void cancelTouchFocus () {
cancelTouchFocus(null, null);
}
/** Cancels touch focus for all listeners except the specified listener.
* @see #cancelTouchFocus() */
public void cancelTouchFocus (EventListener listener, Actor actor) {
InputEvent event = Pools.obtain(InputEvent.class);
event.setStage(this);
event.setType(InputEvent.Type.touchUp);
event.setStageX(Integer.MIN_VALUE);
event.setStageY(Integer.MIN_VALUE);
SnapshotArray<TouchFocus> touchFocuses = this.touchFocuses;
for (int i = touchFocuses.size - 1; i >= 0; i--) {
TouchFocus focus = touchFocuses.get(i);
if (focus.listener == listener && focus.listenerActor == actor) continue;
event.setTarget(focus.target);
event.setListenerActor(focus.listenerActor);
event.setPointer(focus.pointer);
event.setButton(focus.button);
touchFocuses.removeIndex(i);
focus.listener.handle(event);
// Cannot return TouchFocus to the pool, as it may still be in use (eg if cancelTouchFocus is called from touchDragged).
}
Pools.free(event);
}
/** Adds an actor to the root of the stage.
* @see Group#addActor(Actor) */
public void addActor (Actor actor) {
root.addActor(actor);
}
/** Returns the root's child actors.
* @see Group#getChildren() */
public Array<Actor> getActors () {
return root.getChildren();
}
/** Adds a listener to the root.
* @see Actor#addListener(EventListener) */
public boolean addListener (EventListener listener) {
return root.addListener(listener);
}
/** Removes a listener from the root.
* @see Actor#removeListener(EventListener) */
public boolean removeListener (EventListener listener) {
return root.removeListener(listener);
}
/** Adds a capture listener to the root.
* @see Actor#addCaptureListener(EventListener) */
public boolean addCaptureListener (EventListener listener) {
return root.addCaptureListener(listener);
}
/** Removes a listener from the root.
* @see Actor#removeCaptureListener(EventListener) */
public boolean removeCaptureListener (EventListener listener) {
return root.removeCaptureListener(listener);
}
/** Clears the stage, removing all actors. */
public void clear () {
unfocusAll();
root.clear();
}
/** Removes the touch, keyboard, and scroll focused actors. */
public void unfocusAll () {
scrollFocus = null;
keyboardFocus = null;
cancelTouchFocus();
}
/** Removes the touch, keyboard, and scroll focus for the specified actor. */
public void unfocus (Actor actor) {
if (scrollFocus == actor) scrollFocus = null;
if (keyboardFocus == actor) keyboardFocus = null;
}
/** Sets the actor that will receive key events.
* @param actor May be null. */
public void setKeyboardFocus (Actor actor) {
if (keyboardFocus == actor) return;
FocusEvent event = Pools.obtain(FocusEvent.class);
event.setStage(this);
event.setType(FocusEvent.Type.keyboard);
if (keyboardFocus != null) {
event.setFocused(false);
keyboardFocus.fire(event);
}
keyboardFocus = actor;
if (keyboardFocus != null) {
event.setFocused(true);
keyboardFocus.fire(event);
}
Pools.free(event);
}
/** Gets the actor that will receive key events.
* @return May be null. */
public Actor getKeyboardFocus () {
return keyboardFocus;
}
/** Sets the actor that will receive scroll events.
* @param actor May be null. */
public void setScrollFocus (Actor actor) {
if (scrollFocus == actor) return;
FocusEvent event = Pools.obtain(FocusEvent.class);
event.setStage(this);
event.setType(FocusEvent.Type.scroll);
if (scrollFocus != null) {
event.setFocused(false);
scrollFocus.fire(event);
}
scrollFocus = actor;
if (scrollFocus != null) {
event.setFocused(true);
scrollFocus.fire(event);
}
Pools.free(event);
}
/** Gets the actor that will receive scroll events.
* @return May be null. */
public Actor getScrollFocus () {
return scrollFocus;
}
/** The width of the stage's viewport.
* @see #setViewport(float, float, boolean) */
public float getWidth () {
return width;
}
/** The height of the stage's viewport.
* @see #setViewport(float, float, boolean) */
public float getHeight () {
return height;
}
/** Half the amount in the x direction that the stage's viewport was lengthened to fill the screen.
* @see #setViewport(float, float, boolean) */
public float getGutterWidth () {
return gutterWidth;
}
/** Half the amount in the y direction that the stage's viewport was lengthened to fill the screen.
* @see #setViewport(float, float, boolean) */
public float getGutterHeight () {
return gutterHeight;
}
public SpriteBatch getSpriteBatch () {
return batch;
}
public Camera getCamera () {
return camera;
}
/** Sets the stage's camera. The camera must be configured properly or {@link #setViewport(float, float, boolean)} can be called
* after the camera is set. {@link Stage#draw()} will call {@link Camera#update()} and use the {@link Camera#combined} matrix
* for the SpriteBatch {@link SpriteBatch#setProjectionMatrix(com.badlogic.gdx.math.Matrix4) projection matrix}. */
public void setCamera (Camera camera) {
this.camera = camera;
}
/** Returns the root group which holds all actors in the stage. */
public Group getRoot () {
return root;
}
/** Returns the {@link Actor} at the specified location in stage coordinates. Hit testing is performed in the order the actors
* were inserted into the stage, last inserted actors being tested first. To get stage coordinates from screen coordinates, use
* {@link #screenToStageCoordinates(Vector2)}.
* @param touchable If true, the hit detection will respect the {@link Actor#setTouchable(Touchable) touchability}.
* @return May be null if no actor was hit. */
public Actor hit (float stageX, float stageY, boolean touchable) {
Vector2 actorCoords = Vector2.tmp;
root.parentToLocalCoordinates(actorCoords.set(stageX, stageY));
return root.hit(actorCoords.x, actorCoords.y, touchable);
}
/** Transforms the screen coordinates to stage coordinates.
* @param screenCoords Stores the result. */
public Vector2 screenToStageCoordinates (Vector2 screenCoords) {
camera.unproject(Vector3.tmp.set(screenCoords.x, screenCoords.y, 0));
screenCoords.x = Vector3.tmp.x;
screenCoords.y = Vector3.tmp.y;
return screenCoords;
}
/** Transforms the stage coordinates to screen coordinates. */
public Vector2 stageToScreenCoordinates (Vector2 stageCoords) {
Vector3.tmp.set(stageCoords.x, stageCoords.y, 0);
camera.project(Vector3.tmp);
stageCoords.x = Vector3.tmp.x;
stageCoords.y = Vector3.tmp.y;
return stageCoords;
}
/** Transforms the coordinates to screen coordinates. The coordinates can be anywhere in the stage since the transform matrix
* describes how to convert them. The transform matrix is typically obtained from {@link SpriteBatch#getTransformMatrix()}. */
public Vector2 toScreenCoordinates (Vector2 coords, Matrix4 transformMatrix) {
ScissorStack.toWindowCoordinates(camera, transformMatrix, coords);
return coords;
}
public void dispose () {
if (ownsBatch) batch.dispose();
}
/** Internal class for managing touch focus. Public only for GWT.
* @author Nathan Sweet */
public static final class TouchFocus implements Poolable {
EventListener listener;
Actor listenerActor, target;
int pointer, button;
public void reset () {
listenerActor = null;
listener = null;
}
}
}
| gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.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.scenes.scene2d;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.InputEvent.Type;
import com.badlogic.gdx.scenes.scene2d.utils.FocusListener.FocusEvent;
import com.badlogic.gdx.scenes.scene2d.utils.ScissorStack;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.Pool.Poolable;
import com.badlogic.gdx.utils.Pools;
import com.badlogic.gdx.utils.SnapshotArray;
/** A 2D scenegraph containing hierarchies of {@link Actor actors}. Stage handles the viewport and distributing input events.
* <p>
* A stage fills the whole screen. {@link #setViewport} controls the coordinates used within the stage and sets up the camera used
* to convert between stage coordinates and screen coordinates. *
* <p>
* A stage must receive input events so it can distribute them to actors. This is typically done by passing the stage to
* {@link Input#setInputProcessor(com.badlogic.gdx.InputProcessor) Gdx.input.setInputProcessor}. An {@link InputMultiplexer} may be
* used to handle input events before or after the stage does. If an actor handles an event by returning true from the input
* method, then the stage's input method will also return true, causing subsequent InputProcessors to not receive the event.
* @author mzechner
* @author Nathan Sweet */
public class Stage extends InputAdapter implements Disposable {
private float width, height;
private float gutterWidth, gutterHeight;
private float centerX, centerY;
private Camera camera;
private final SpriteBatch batch;
private final boolean ownsBatch;
private Group root;
private final Vector2 stageCoords = new Vector2();
private Actor[] pointerOverActors = new Actor[20];
private boolean[] pointerTouched = new boolean[20];
private int[] pointerScreenX = new int[20];
private int[] pointerScreenY = new int[20];
private int mouseScreenX, mouseScreenY;
private Actor mouseOverActor;
private Actor keyboardFocus, scrollFocus;
private SnapshotArray<TouchFocus> touchFocuses = new SnapshotArray(true, 4, TouchFocus.class);
/** Creates a stage with a {@link #setViewport(float, float, boolean) viewport} equal to the device screen resolution. The stage
* will use its own {@link SpriteBatch}. */
public Stage () {
this(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
}
/** Creates a stage with the specified {@link #setViewport(float, float, boolean) viewport}. The stage will use its own
* {@link SpriteBatch}, which will be disposed when the stage is disposed. */
public Stage (float width, float height, boolean stretch) {
batch = new SpriteBatch();
ownsBatch = true;
initialize(width, height, stretch);
}
/** Creates a stage with the specified {@link #setViewport(float, float, boolean) viewport} and {@link SpriteBatch}. This can be
* used to avoid creating a new SpriteBatch (which can be somewhat slow) if multiple stages are used during an applications
* life time.
* @param batch Will not be disposed if {@link #dispose()} is called. Handle disposal yourself. */
public Stage (float width, float height, boolean stretch, SpriteBatch batch) {
this.batch = batch;
ownsBatch = false;
initialize(width, height, stretch);
}
private void initialize (float width, float height, boolean stretch) {
this.width = width;
this.height = height;
root = new Group();
root.setStage(this);
camera = new OrthographicCamera();
setViewport(width, height, stretch);
}
/** Sets the dimensions of the stage's viewport. The viewport covers the entire screen. If keepAspectRatio is false, the
* viewport is simply stretched to the screen resolution, which may distort the aspect ratio. If keepAspectRatio is true, the
* viewport is first scaled to fit then the shorter dimension is lengthened to fill the screen, which keeps the aspect ratio
* from changing. The {@link #getGutterWidth()} and {@link #getGutterHeight()} provide access to the amount that was
* lengthened. */
public void setViewport (float width, float height, boolean keepAspectRatio) {
if (keepAspectRatio) {
float screenWidth = Gdx.graphics.getWidth();
float screenHeight = Gdx.graphics.getHeight();
if (screenHeight / screenWidth < height / width) {
float toScreenSpace = screenHeight / height;
float toViewportSpace = height / screenHeight;
float deviceWidth = width * toScreenSpace;
float lengthen = (screenWidth - deviceWidth) * toViewportSpace;
this.width = width + lengthen;
this.height = height;
gutterWidth = lengthen / 2;
gutterHeight = 0;
} else {
float toScreenSpace = screenWidth / width;
float toViewportSpace = width / screenWidth;
float deviceHeight = height * toScreenSpace;
float lengthen = (screenHeight - deviceHeight) * toViewportSpace;
this.height = height + lengthen;
this.width = width;
gutterWidth = 0;
gutterHeight = lengthen / 2;
}
} else {
this.width = width;
this.height = height;
gutterWidth = 0;
gutterHeight = 0;
}
centerX = this.width / 2;
centerY = this.height / 2;
camera.position.set(centerX, centerY, 0);
camera.viewportWidth = this.width;
camera.viewportHeight = this.height;
}
public void draw () {
camera.update();
if (!root.isVisible()) return;
batch.setProjectionMatrix(camera.combined);
batch.begin();
root.draw(batch, 1);
batch.end();
}
/** Calls {@link #act(float)} with {@link Graphics#getDeltaTime()}. */
public void act () {
act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
}
/** Calls the {@link Actor#act(float)} method on each actor in the stage. Typically called each frame. This method also fires
* enter and exit events.
* @param delta Time in seconds since the last frame. */
public void act (float delta) {
// Update over actors. Done in act() because actors may change position, which can fire enter/exit without an input event.
for (int pointer = 0, n = pointerOverActors.length; pointer < n; pointer++) {
Actor overLast = pointerOverActors[pointer];
// Check if pointer is gone.
if (!pointerTouched[pointer]) {
if (overLast != null) {
pointerOverActors[pointer] = null;
screenToStageCoordinates(stageCoords.set(pointerScreenX[pointer], pointerScreenY[pointer]));
// Exit over last.
InputEvent event = Pools.obtain(InputEvent.class);
event.setType(InputEvent.Type.exit);
event.setStage(this);
event.setStageX(stageCoords.x);
event.setStageY(stageCoords.y);
event.setRelatedActor(overLast);
event.setPointer(pointer);
overLast.fire(event);
Pools.free(event);
}
continue;
}
// Update over actor for the pointer.
pointerOverActors[pointer] = fireEnterAndExit(overLast, pointerScreenX[pointer], pointerScreenY[pointer], pointer);
}
// Update over actor for the mouse on the desktop.
if (Gdx.app.getType() == ApplicationType.Desktop)
mouseOverActor = fireEnterAndExit(mouseOverActor, mouseScreenX, mouseScreenY, -1);
root.act(delta);
}
private Actor fireEnterAndExit (Actor overLast, int screenX, int screenY, int pointer) {
// Find the actor under the point.
screenToStageCoordinates(stageCoords.set(screenX, screenY));
Actor over = hit(stageCoords.x, stageCoords.y, false);
if (over == overLast) return overLast;
InputEvent event = Pools.obtain(InputEvent.class);
event.setStage(this);
event.setStageX(stageCoords.x);
event.setStageY(stageCoords.y);
event.setPointer(pointer);
// Exit overLast.
if (overLast != null) {
event.setType(InputEvent.Type.exit);
event.setRelatedActor(over);
overLast.fire(event);
}
// Enter over.
if (over != null) {
event.setType(InputEvent.Type.enter);
event.setRelatedActor(overLast);
over.fire(event);
}
Pools.free(event);
return over;
}
/** Applies a touch down event to the stage and returns true if an actor in the scene {@link Event#handle() handled} the event. */
public boolean touchDown (int screenX, int screenY, int pointer, int button) {
pointerTouched[pointer] = true;
pointerScreenX[pointer] = screenX;
pointerScreenY[pointer] = screenY;
screenToStageCoordinates(stageCoords.set(screenX, screenY));
InputEvent event = Pools.obtain(InputEvent.class);
event.setType(Type.touchDown);
event.setStage(this);
event.setStageX(stageCoords.x);
event.setStageY(stageCoords.y);
event.setPointer(pointer);
event.setButton(button);
Actor target = hit(stageCoords.x, stageCoords.y, true);
if (target == null) target = root;
target.fire(event);
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Applies a touch moved event to the stage and returns true if an actor in the scene {@link Event#handle() handled} the event.
* Only {@link InputListener listeners} that returned true for touchDown will receive this event. */
public boolean touchDragged (int screenX, int screenY, int pointer) {
pointerScreenX[pointer] = screenX;
pointerScreenY[pointer] = screenY;
if (touchFocuses.size == 0) return false;
screenToStageCoordinates(stageCoords.set(screenX, screenY));
InputEvent event = Pools.obtain(InputEvent.class);
event.setType(Type.touchDragged);
event.setStage(this);
event.setStageX(stageCoords.x);
event.setStageY(stageCoords.y);
event.setPointer(pointer);
SnapshotArray<TouchFocus> touchFocuses = this.touchFocuses;
TouchFocus[] focuses = touchFocuses.begin();
for (int i = 0, n = touchFocuses.size; i < n; i++) {
TouchFocus focus = focuses[i];
if (focus.pointer != pointer) continue;
event.setTarget(focus.target);
event.setListenerActor(focus.listenerActor);
if (focus.listener.handle(event)) event.handle();
}
touchFocuses.end();
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Applies a touch up event to the stage and returns true if an actor in the scene {@link Event#handle() handled} the event.
* Only {@link InputListener listeners} that returned true for touchDown will receive this event. */
public boolean touchUp (int screenX, int screenY, int pointer, int button) {
pointerTouched[pointer] = false;
pointerScreenX[pointer] = screenX;
pointerScreenY[pointer] = screenY;
if (touchFocuses.size == 0) return false;
screenToStageCoordinates(stageCoords.set(screenX, screenY));
InputEvent event = Pools.obtain(InputEvent.class);
event.setType(Type.touchUp);
event.setStage(this);
event.setStageX(stageCoords.x);
event.setStageY(stageCoords.y);
event.setPointer(pointer);
event.setButton(button);
SnapshotArray<TouchFocus> touchFocuses = this.touchFocuses;
TouchFocus[] focuses = touchFocuses.begin();
for (int i = 0, n = touchFocuses.size; i < n; i++) {
TouchFocus focus = focuses[i];
if (focus.pointer != pointer || focus.button != button) continue;
event.setTarget(focus.target);
event.setListenerActor(focus.listenerActor);
if (focus.listener.handle(event)) event.handle();
}
touchFocuses.end();
for (int i = touchFocuses.size - 1; i >= 0; i--) {
TouchFocus focus = touchFocuses.get(i);
if (focus.pointer != pointer || focus.button != button) continue;
touchFocuses.removeIndex(i);
Pools.free(focus);
}
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Applies a mouse moved event to the stage and returns true if an actor in the scene {@link Event#handle() handled} the event.
* This event only occurs on the desktop. */
public boolean mouseMoved (int screenX, int screenY) {
mouseScreenX = screenX;
mouseScreenY = screenY;
screenToStageCoordinates(stageCoords.set(screenX, screenY));
InputEvent event = Pools.obtain(InputEvent.class);
event.setStage(this);
event.setType(Type.mouseMoved);
event.setStageX(stageCoords.x);
event.setStageY(stageCoords.y);
Actor target = hit(stageCoords.x, stageCoords.y, true);
if (target == null) target = root;
target.fire(event);
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Applies a mouse scroll event to the stage and returns true if an actor in the scene {@link Event#handle() handled} the
* event. This event only occurs on the desktop. */
public boolean scrolled (int amount) {
if (scrollFocus == null) return false;
InputEvent event = Pools.obtain(InputEvent.class);
event.setStage(this);
event.setType(InputEvent.Type.scrolled);
event.setScrollAmount(amount);
scrollFocus.fire(event);
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Applies a key down event to the actor that has {@link Stage#setKeyboardFocus(Actor) keyboard focus}, if any, and returns
* true if the event was {@link Event#handle() handled}. */
public boolean keyDown (int keyCode) {
if (keyboardFocus == null) return false;
InputEvent event = Pools.obtain(InputEvent.class);
event.setStage(this);
event.setType(InputEvent.Type.keyDown);
event.setKeyCode(keyCode);
keyboardFocus.fire(event);
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Applies a key up event to the actor that has {@link Stage#setKeyboardFocus(Actor) keyboard focus}, if any, and returns true
* if the event was {@link Event#handle() handled}. */
public boolean keyUp (int keyCode) {
if (keyboardFocus == null) return false;
InputEvent event = Pools.obtain(InputEvent.class);
event.setStage(this);
event.setType(InputEvent.Type.keyUp);
event.setKeyCode(keyCode);
keyboardFocus.fire(event);
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Applies a key typed event to the actor that has {@link Stage#setKeyboardFocus(Actor) keyboard focus}, if any, and returns
* true if the event was {@link Event#handle() handled}. */
public boolean keyTyped (char character) {
if (keyboardFocus == null) return false;
InputEvent event = Pools.obtain(InputEvent.class);
event.setStage(this);
event.setType(InputEvent.Type.keyTyped);
event.setCharacter(character);
keyboardFocus.fire(event);
boolean handled = event.isHandled();
Pools.free(event);
return handled;
}
/** Adds the listener to be notified for all touchDragged and touchUp events for the specified pointer and button. The actor
* will be used as the {@link Event#getListenerActor() listener actor} and {@link Event#getTarget() target}. */
public void addTouchFocus (EventListener listener, Actor listenerActor, Actor target, int pointer, int button) {
TouchFocus focus = Pools.obtain(TouchFocus.class);
focus.listenerActor = listenerActor;
focus.target = target;
focus.listener = listener;
focus.pointer = pointer;
focus.button = button;
touchFocuses.add(focus);
}
/** Removes the listener from being notified for all touchDragged and touchUp events for the specified pointer and button. Note
* the listener may never receive a touchUp event if this method is used. */
public void removeTouchFocus (EventListener listener, Actor listenerActor, Actor target, int pointer, int button) {
SnapshotArray<TouchFocus> touchFocuses = this.touchFocuses;
for (int i = touchFocuses.size - 1; i >= 0; i--) {
TouchFocus focus = touchFocuses.get(i);
if (focus.listener == listener && focus.listenerActor == listenerActor && focus.target == target
&& focus.pointer == pointer && focus.button == button) {
touchFocuses.removeIndex(i);
Pools.free(focus);
}
}
}
/** Sends a touchUp event to all listeners that are registered to receive touchDragged and touchUp events and removes their
* touch focus. The location of the touchUp is {@link Integer#MIN_VALUE}. This method removes all touch focus listeners, but
* sends a touchUp event so that the state of the listeners remains consistent (listeners typically expect to receive touchUp
* eventually). */
public void cancelTouchFocus () {
cancelTouchFocus(null, null);
}
/** Cancels touch focus for all listeners except the specified listener.
* @see #cancelTouchFocus() */
public void cancelTouchFocus (EventListener listener, Actor actor) {
InputEvent event = Pools.obtain(InputEvent.class);
event.setStage(this);
event.setType(InputEvent.Type.touchUp);
event.setStageX(Integer.MIN_VALUE);
event.setStageY(Integer.MIN_VALUE);
SnapshotArray<TouchFocus> touchFocuses = this.touchFocuses;
for (int i = touchFocuses.size - 1; i >= 0; i--) {
TouchFocus focus = touchFocuses.get(i);
if (focus.listener == listener && focus.listenerActor == actor) continue;
event.setTarget(focus.target);
event.setListenerActor(focus.listenerActor);
event.setPointer(focus.pointer);
event.setButton(focus.button);
touchFocuses.removeIndex(i);
focus.listener.handle(event);
// Cannot return TouchFocus to the pool, as it may still be in use (eg if cancelTouchFocus is called from touchDragged).
}
Pools.free(event);
}
/** Adds an actor to the root of the stage.
* @see Group#addActor(Actor) */
public void addActor (Actor actor) {
root.addActor(actor);
}
/** Returns the root's child actors.
* @see Group#getChildren() */
public Array<Actor> getActors () {
return root.getChildren();
}
/** Adds a listener to the root.
* @see Actor#addListener(EventListener) */
public boolean addListener (EventListener listener) {
return root.addListener(listener);
}
/** Removes a listener from the root.
* @see Actor#removeListener(EventListener) */
public boolean removeListener (EventListener listener) {
return root.removeListener(listener);
}
/** Adds a capture listener to the root.
* @see Actor#addCaptureListener(EventListener) */
public boolean addCaptureListener (EventListener listener) {
return root.addCaptureListener(listener);
}
/** Removes a listener from the root.
* @see Actor#removeCaptureListener(EventListener) */
public boolean removeCaptureListener (EventListener listener) {
return root.removeCaptureListener(listener);
}
/** Clears the stage, removing all actors. */
public void clear () {
unfocusAll();
root.clear();
}
/** Removes the touch, keyboard, and scroll focused actors. */
public void unfocusAll () {
scrollFocus = null;
keyboardFocus = null;
cancelTouchFocus();
}
/** Removes the touch, keyboard, and scroll focus for the specified actor. */
public void unfocus (Actor actor) {
if (scrollFocus == actor) scrollFocus = null;
if (keyboardFocus == actor) keyboardFocus = null;
}
/** Sets the actor that will receive key events.
* @param actor May be null. */
public void setKeyboardFocus (Actor actor) {
if (keyboardFocus == actor) return;
FocusEvent event = Pools.obtain(FocusEvent.class);
event.setStage(this);
event.setType(FocusEvent.Type.keyboard);
if (keyboardFocus != null) {
event.setFocused(false);
keyboardFocus.fire(event);
}
keyboardFocus = actor;
if (keyboardFocus != null) {
event.setFocused(true);
keyboardFocus.fire(event);
}
Pools.free(event);
}
/** Gets the actor that will receive key events.
* @return May be null. */
public Actor getKeyboardFocus () {
return keyboardFocus;
}
/** Sets the actor that will receive scroll events.
* @param actor May be null. */
public void setScrollFocus (Actor actor) {
if (scrollFocus == actor) return;
FocusEvent event = Pools.obtain(FocusEvent.class);
event.setStage(this);
event.setType(FocusEvent.Type.scroll);
if (scrollFocus != null) {
event.setFocused(false);
scrollFocus.fire(event);
}
scrollFocus = actor;
if (scrollFocus != null) {
event.setFocused(true);
scrollFocus.fire(event);
}
Pools.free(event);
}
/** Gets the actor that will receive scroll events.
* @return May be null. */
public Actor getScrollFocus () {
return scrollFocus;
}
/** The width of the stage's viewport.
* @see #setViewport(float, float, boolean) */
public float getWidth () {
return width;
}
/** The height of the stage's viewport.
* @see #setViewport(float, float, boolean) */
public float getHeight () {
return height;
}
/** Half the amount in the x direction that the stage's viewport was lengthened to fill the screen.
* @see #setViewport(float, float, boolean) */
public float getGutterWidth () {
return gutterWidth;
}
/** Half the amount in the y direction that the stage's viewport was lengthened to fill the screen.
* @see #setViewport(float, float, boolean) */
public float getGutterHeight () {
return gutterHeight;
}
public SpriteBatch getSpriteBatch () {
return batch;
}
public Camera getCamera () {
return camera;
}
/** Sets the stage's camera. The camera must be configured properly or {@link #setViewport(float, float, boolean)} can be called
* after the camera is set. {@link Stage#draw()} will call {@link Camera#update()} and use the {@link Camera#combined} matrix
* for the SpriteBatch {@link SpriteBatch#setProjectionMatrix(com.badlogic.gdx.math.Matrix4) projection matrix}. */
public void setCamera (Camera camera) {
this.camera = camera;
}
/** Returns the root group which holds all actors in the stage. */
public Group getRoot () {
return root;
}
/** Returns the {@link Actor} at the specified location in stage coordinates. Hit testing is performed in the order the actors
* were inserted into the stage, last inserted actors being tested first. To get stage coordinates from screen coordinates, use
* {@link #screenToStageCoordinates(Vector2)}.
* @param touchable If true, the hit detection will respect the {@link Actor#setTouchable(Touchable) touchability}.
* @return May be null if no actor was hit. */
public Actor hit (float stageX, float stageY, boolean touchable) {
Vector2 actorCoords = Vector2.tmp;
root.parentToLocalCoordinates(actorCoords.set(stageX, stageY));
return root.hit(actorCoords.x, actorCoords.y, touchable);
}
/** Transforms the screen coordinates to stage coordinates.
* @param screenCoords Stores the result. */
public Vector2 screenToStageCoordinates (Vector2 screenCoords) {
camera.unproject(Vector3.tmp.set(screenCoords.x, screenCoords.y, 0));
screenCoords.x = Vector3.tmp.x;
screenCoords.y = Vector3.tmp.y;
return screenCoords;
}
/** Transforms the stage coordinates to screen coordinates. */
public Vector2 stageToScreenCoordinates (Vector2 stageCoords) {
Vector3.tmp.set(stageCoords.x, stageCoords.y, 0);
camera.project(Vector3.tmp);
stageCoords.x = Vector3.tmp.x;
stageCoords.y = Vector3.tmp.y;
return stageCoords;
}
/** Transforms the coordinates to screen coordinates. The coordinates can be anywhere in the stage since the transform matrix
* describes how to convert them. The transform matrix is typically obtained from {@link SpriteBatch#getTransformMatrix()}. */
public Vector2 toScreenCoordinates (Vector2 coords, Matrix4 transformMatrix) {
ScissorStack.toWindowCoordinates(camera, transformMatrix, coords);
return coords;
}
public void dispose () {
if (ownsBatch) batch.dispose();
}
/** Internal class for managing touch focus. Public only for GWT.
* @author Nathan Sweet */
public static final class TouchFocus implements Poolable {
EventListener listener;
Actor listenerActor, target;
int pointer, button;
public void reset () {
listenerActor = null;
listener = null;
}
}
}
| Stage, enter/exit were ignoring touchability.
| gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java | Stage, enter/exit were ignoring touchability. | <ide><path>dx/src/com/badlogic/gdx/scenes/scene2d/Stage.java
<ide> private Actor fireEnterAndExit (Actor overLast, int screenX, int screenY, int pointer) {
<ide> // Find the actor under the point.
<ide> screenToStageCoordinates(stageCoords.set(screenX, screenY));
<del> Actor over = hit(stageCoords.x, stageCoords.y, false);
<add> Actor over = hit(stageCoords.x, stageCoords.y, true);
<ide> if (over == overLast) return overLast;
<ide>
<ide> InputEvent event = Pools.obtain(InputEvent.class); |
|
Java | apache-2.0 | 8c9d4de88bb6a455f8c77e83492ac7263259fc28 | 0 | vase4kin/TeamCityApp,vase4kin/TeamCityApp,vase4kin/TeamCityApp | /*
* Copyright 2016 Andrey Tolpeev
*
* 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.vase4kin.teamcityapp.buildlog.presenter;
import com.github.vase4kin.teamcityapp.buildlog.data.BuildLogInteractor;
import com.github.vase4kin.teamcityapp.buildlog.router.BuildLogRouter;
import com.github.vase4kin.teamcityapp.buildlog.urlprovider.BuildLogUrlProvider;
import com.github.vase4kin.teamcityapp.buildlog.view.BuildLogView;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class BuildLogPresenterImplTest {
@Mock
private BuildLogView mView;
@Mock
private BuildLogUrlProvider mBuildLogUrlProvider;
@Mock
private BuildLogInteractor mInteractor;
@Mock
private BuildLogRouter router;
private BuildLogPresenterImpl mPresenter;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(mBuildLogUrlProvider.provideUrl()).thenReturn("http://fake-teamcity-url");
mPresenter = new BuildLogPresenterImpl(mView, mBuildLogUrlProvider, mInteractor, router);
}
@After
public void tearDown() throws Exception {
verifyNoMoreInteractions(mView, mBuildLogUrlProvider, mInteractor, router);
}
@Test
public void testHandleOnCreateViewIfDialogIsNotShown() throws Exception {
when(mInteractor.isSslDisabled()).thenReturn(false);
when(mInteractor.isAuthDialogShown()).thenReturn(true);
mPresenter.onCreateViews();
verify(mView).initViews(eq(mPresenter));
verify(mInteractor).isSslDisabled();
verify(mInteractor).isAuthDialogShown();
verify(mBuildLogUrlProvider).provideUrl();
verify(mView).loadBuildLog(eq("http://fake-teamcity-url"));
}
@Test
public void testHandleOnCreateViewIfSslIsDisabled() throws Exception {
when(mInteractor.isSslDisabled()).thenReturn(true);
mPresenter.onCreateViews();
verify(mView).initViews(eq(mPresenter));
verify(mInteractor).isSslDisabled();
verify(mView).showSslWarningView();
}
@Test
public void testHandleOnCreateViewIfGuestUser() throws Exception {
when(mInteractor.isAuthDialogShown()).thenReturn(false);
when(mInteractor.isSslDisabled()).thenReturn(false);
when(mInteractor.isGuestUser()).thenReturn(true);
mPresenter.onCreateViews();
verify(mView).initViews(eq(mPresenter));
verify(mInteractor).isSslDisabled();
verify(mInteractor).isAuthDialogShown();
verify(mInteractor).isGuestUser();
verify(mBuildLogUrlProvider).provideUrl();
verify(mView).loadBuildLog(eq("http://fake-teamcity-url"));
}
@Test
public void testHandleOnCreateViewIfNotGuest() throws Exception {
when(mInteractor.isGuestUser()).thenReturn(false);
when(mInteractor.isSslDisabled()).thenReturn(false);
when(mInteractor.isAuthDialogShown()).thenReturn(false);
mPresenter.onCreateViews();
verify(mView).initViews(eq(mPresenter));
verify(mInteractor).isSslDisabled();
verify(mInteractor).isGuestUser();
verify(mInteractor).isAuthDialogShown();
verify(mView).showAuthView();
}
@Test
public void testHandleOnDestroyView() throws Exception {
mPresenter.onDestroyViews();
verify(mView).unBindViews();
verify(router).unbindCustomsTabs();
}
@Test
public void testLoadBuildLog() throws Exception {
mPresenter.loadBuildLog();
verify(mBuildLogUrlProvider).provideUrl();
verify(mView).loadBuildLog(eq("http://fake-teamcity-url"));
}
@Test
public void testOpenBuildLog() throws Exception {
mPresenter.onOpenBuildLogInBrowser();
verify(mBuildLogUrlProvider).provideUrl();
verify(router).openUrl(eq("http://fake-teamcity-url"));
}
@Test
public void testOnAuthButtonClick() throws Exception {
mPresenter.onAuthButtonClick();
verify(mView).hideAuthView();
verify(mInteractor).setAuthDialogStatus(eq(true));
verify(mBuildLogUrlProvider).provideUrl();
verify(mView).loadBuildLog(eq("http://fake-teamcity-url"));
}
} | app/src/test/java/com/github/vase4kin/teamcityapp/buildlog/presenter/BuildLogPresenterImplTest.java | /*
* Copyright 2016 Andrey Tolpeev
*
* 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.vase4kin.teamcityapp.buildlog.presenter;
import com.github.vase4kin.teamcityapp.buildlog.data.BuildLogInteractor;
import com.github.vase4kin.teamcityapp.buildlog.urlprovider.BuildLogUrlProvider;
import com.github.vase4kin.teamcityapp.buildlog.view.BuildLogView;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class BuildLogPresenterImplTest {
@Mock
private BuildLogView mView;
@Mock
private BuildLogUrlProvider mBuildLogUrlProvider;
@Mock
private BuildLogInteractor mInteractor;
private BuildLogPresenterImpl mPresenter;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(mBuildLogUrlProvider.provideUrl()).thenReturn("http://fake-teamcity-url");
mPresenter = new BuildLogPresenterImpl(mView, mBuildLogUrlProvider, mInteractor);
}
@After
public void tearDown() throws Exception {
verifyNoMoreInteractions(mView, mBuildLogUrlProvider, mInteractor);
}
@Test
public void testHandleOnCreateViewIfDialogIsNotShown() throws Exception {
when(mInteractor.isAuthDialogShown()).thenReturn(true);
mPresenter.onCreateViews();
verify(mView).initViews(eq(mPresenter));
verify(mInteractor).isAuthDialogShown();
verify(mBuildLogUrlProvider).provideUrl();
verify(mView).loadBuildLog(eq("http://fake-teamcity-url"));
}
@Test
public void testHandleOnCreateViewIfGuestUser() throws Exception {
when(mInteractor.isAuthDialogShown()).thenReturn(false);
when(mInteractor.isGuestUser()).thenReturn(true);
mPresenter.onCreateViews();
verify(mView).initViews(eq(mPresenter));
verify(mInteractor).isAuthDialogShown();
verify(mInteractor).isGuestUser();
verify(mBuildLogUrlProvider).provideUrl();
verify(mView).loadBuildLog(eq("http://fake-teamcity-url"));
}
@Test
public void testHandleOnCreateViewIfNotGuest() throws Exception {
when(mInteractor.isGuestUser()).thenReturn(false);
when(mInteractor.isAuthDialogShown()).thenReturn(false);
mPresenter.onCreateViews();
verify(mView).initViews(eq(mPresenter));
verify(mInteractor).isGuestUser();
verify(mInteractor).isAuthDialogShown();
verify(mView).showAuthView();
}
@Test
public void testHandleOnDestroyView() throws Exception {
mPresenter.onDestroyViews();
verify(mView).unBindViews();
}
@Test
public void testLoadBuildLog() throws Exception {
mPresenter.loadBuildLog();
verify(mBuildLogUrlProvider).provideUrl();
verify(mView).loadBuildLog(eq("http://fake-teamcity-url"));
}
@Test
public void testOnAuthButtonClick() throws Exception {
mPresenter.onAuthButtonClick();
verify(mView).hideAuthView();
verify(mInteractor).setAuthDialogStatus(eq(true));
verify(mBuildLogUrlProvider).provideUrl();
verify(mView).loadBuildLog(eq("http://fake-teamcity-url"));
}
} | Fix build log presenter tests
| app/src/test/java/com/github/vase4kin/teamcityapp/buildlog/presenter/BuildLogPresenterImplTest.java | Fix build log presenter tests | <ide><path>pp/src/test/java/com/github/vase4kin/teamcityapp/buildlog/presenter/BuildLogPresenterImplTest.java
<ide> package com.github.vase4kin.teamcityapp.buildlog.presenter;
<ide>
<ide> import com.github.vase4kin.teamcityapp.buildlog.data.BuildLogInteractor;
<add>import com.github.vase4kin.teamcityapp.buildlog.router.BuildLogRouter;
<ide> import com.github.vase4kin.teamcityapp.buildlog.urlprovider.BuildLogUrlProvider;
<ide> import com.github.vase4kin.teamcityapp.buildlog.view.BuildLogView;
<ide>
<ide> @Mock
<ide> private BuildLogInteractor mInteractor;
<ide>
<add> @Mock
<add> private BuildLogRouter router;
<add>
<ide> private BuildLogPresenterImpl mPresenter;
<ide>
<ide> @Before
<ide> public void setUp() {
<ide> MockitoAnnotations.initMocks(this);
<ide> when(mBuildLogUrlProvider.provideUrl()).thenReturn("http://fake-teamcity-url");
<del> mPresenter = new BuildLogPresenterImpl(mView, mBuildLogUrlProvider, mInteractor);
<add> mPresenter = new BuildLogPresenterImpl(mView, mBuildLogUrlProvider, mInteractor, router);
<ide> }
<ide>
<ide> @After
<ide> public void tearDown() throws Exception {
<del> verifyNoMoreInteractions(mView, mBuildLogUrlProvider, mInteractor);
<add> verifyNoMoreInteractions(mView, mBuildLogUrlProvider, mInteractor, router);
<ide> }
<ide>
<ide> @Test
<ide> public void testHandleOnCreateViewIfDialogIsNotShown() throws Exception {
<add> when(mInteractor.isSslDisabled()).thenReturn(false);
<ide> when(mInteractor.isAuthDialogShown()).thenReturn(true);
<ide> mPresenter.onCreateViews();
<ide> verify(mView).initViews(eq(mPresenter));
<add> verify(mInteractor).isSslDisabled();
<ide> verify(mInteractor).isAuthDialogShown();
<ide> verify(mBuildLogUrlProvider).provideUrl();
<ide> verify(mView).loadBuildLog(eq("http://fake-teamcity-url"));
<ide> }
<ide>
<ide> @Test
<add> public void testHandleOnCreateViewIfSslIsDisabled() throws Exception {
<add> when(mInteractor.isSslDisabled()).thenReturn(true);
<add> mPresenter.onCreateViews();
<add> verify(mView).initViews(eq(mPresenter));
<add> verify(mInteractor).isSslDisabled();
<add> verify(mView).showSslWarningView();
<add> }
<add>
<add> @Test
<ide> public void testHandleOnCreateViewIfGuestUser() throws Exception {
<ide> when(mInteractor.isAuthDialogShown()).thenReturn(false);
<add> when(mInteractor.isSslDisabled()).thenReturn(false);
<ide> when(mInteractor.isGuestUser()).thenReturn(true);
<ide> mPresenter.onCreateViews();
<ide> verify(mView).initViews(eq(mPresenter));
<add> verify(mInteractor).isSslDisabled();
<ide> verify(mInteractor).isAuthDialogShown();
<ide> verify(mInteractor).isGuestUser();
<ide> verify(mBuildLogUrlProvider).provideUrl();
<ide> @Test
<ide> public void testHandleOnCreateViewIfNotGuest() throws Exception {
<ide> when(mInteractor.isGuestUser()).thenReturn(false);
<add> when(mInteractor.isSslDisabled()).thenReturn(false);
<ide> when(mInteractor.isAuthDialogShown()).thenReturn(false);
<ide> mPresenter.onCreateViews();
<ide> verify(mView).initViews(eq(mPresenter));
<add> verify(mInteractor).isSslDisabled();
<ide> verify(mInteractor).isGuestUser();
<ide> verify(mInteractor).isAuthDialogShown();
<ide> verify(mView).showAuthView();
<ide> public void testHandleOnDestroyView() throws Exception {
<ide> mPresenter.onDestroyViews();
<ide> verify(mView).unBindViews();
<add> verify(router).unbindCustomsTabs();
<ide> }
<ide>
<ide> @Test
<ide> mPresenter.loadBuildLog();
<ide> verify(mBuildLogUrlProvider).provideUrl();
<ide> verify(mView).loadBuildLog(eq("http://fake-teamcity-url"));
<add> }
<add>
<add> @Test
<add> public void testOpenBuildLog() throws Exception {
<add> mPresenter.onOpenBuildLogInBrowser();
<add> verify(mBuildLogUrlProvider).provideUrl();
<add> verify(router).openUrl(eq("http://fake-teamcity-url"));
<ide> }
<ide>
<ide> @Test |
|
JavaScript | apache-2.0 | 3bb75d3ad43f5da7f39fabe99f6c2498e6badcbf | 0 | wallw-bits/cesium,wallw-bits/cesium,ggetz/cesium,NaderCHASER/cesium,CesiumGS/cesium,ggetz/cesium,CesiumGS/cesium,progsung/cesium,oterral/cesium,YonatanKra/cesium,geoscan/cesium,wallw-bits/cesium,hodbauer/cesium,ggetz/cesium,josh-bernstein/cesium,jasonbeverage/cesium,oterral/cesium,CesiumGS/cesium,hodbauer/cesium,soceur/cesium,jasonbeverage/cesium,likangning93/cesium,soceur/cesium,kaktus40/cesium,YonatanKra/cesium,emackey/cesium,AnalyticalGraphicsInc/cesium,ggetz/cesium,likangning93/cesium,CesiumGS/cesium,emackey/cesium,CesiumGS/cesium,AnalyticalGraphicsInc/cesium,emackey/cesium,NaderCHASER/cesium,josh-bernstein/cesium,hodbauer/cesium,likangning93/cesium,likangning93/cesium,likangning93/cesium,progsung/cesium,YonatanKra/cesium,soceur/cesium,NaderCHASER/cesium,geoscan/cesium,wallw-bits/cesium,emackey/cesium,oterral/cesium,kaktus40/cesium,YonatanKra/cesium | /*jslint node: true, latedef: nofunc*/
/*eslint-env node*/
'use strict';
var fs = require('fs');
var path = require('path');
var os = require('os');
var child_process = require('child_process');
var crypto = require('crypto');
var zlib = require('zlib');
var readline = require('readline');
var request = require('request');
var globby = require('globby');
var gulpTap = require('gulp-tap');
var rimraf = require('rimraf');
var glslStripComments = require('glsl-strip-comments');
var mkdirp = require('mkdirp');
var eventStream = require('event-stream');
var gulp = require('gulp');
var gulpInsert = require('gulp-insert');
var gulpZip = require('gulp-zip');
var gulpRename = require('gulp-rename');
var gulpReplace = require('gulp-replace');
var Promise = require('bluebird');
var requirejs = require('requirejs');
var karma = require('karma').Server;
var yargs = require('yargs');
var aws = require('aws-sdk');
var mime = require('mime');
var compressible = require('compressible');
var packageJson = require('./package.json');
var version = packageJson.version;
if (/\.0$/.test(version)) {
version = version.substring(0, version.length - 2);
}
var karmaConfigFile = path.join(__dirname, 'Specs/karma.conf.js');
var travisDeployUrl = 'http://cesium-dev.s3-website-us-east-1.amazonaws.com/cesium/';
//Gulp doesn't seem to have a way to get the currently running tasks for setting
//per-task variables. We use the command line argument here to detect which task is being run.
var taskName = process.argv[2];
var noDevelopmentGallery = taskName === 'release' || taskName === 'makeZipFile';
var buildingRelease = noDevelopmentGallery;
var minifyShaders = taskName === 'minify' || taskName === 'minifyRelease' || taskName === 'release' || taskName === 'makeZipFile' || taskName === 'buildApps';
var concurrency = yargs.argv.concurrency;
if (!concurrency) {
concurrency = os.cpus().length;
}
//Since combine and minify run in parallel already, split concurrency in half when building both.
//This can go away when gulp 4 comes out because it allows for synchronous tasks.
if (buildingRelease) {
concurrency = concurrency / 2;
}
var sourceFiles = ['Source/**/*.js',
'!Source/*.js',
'!Source/Workers/**',
'!Source/ThirdParty/Workers/**',
'Source/Workers/createTaskProcessorWorker.js'];
var buildFiles = ['Specs/**/*.js',
'!Specs/SpecList.js',
'Source/Shaders/**/*.glsl'];
var filesToClean = ['Source/Cesium.js',
'Build',
'Instrumented',
'Source/Shaders/**/*.js',
'Source/ThirdParty/Shaders/*.js',
'Specs/SpecList.js',
'Apps/Sandcastle/jsHintOptions.js',
'Apps/Sandcastle/gallery/gallery-index.js',
'Cesium-*.zip'];
var filesToSortRequires = ['Source/**/*.js',
'!Source/Shaders/**',
'!Source/ThirdParty/**',
'!Source/Workers/cesiumWorkerBootstrapper.js',
'!Source/copyrightHeader.js',
'!Source/Workers/transferTypedArrayTest.js',
'Apps/**/*.js',
'!Apps/Sandcastle/ThirdParty/**',
'!Apps/Sandcastle/jsHintOptions.js',
'Specs/**/*.js',
'!Specs/spec-main.js',
'!Specs/SpecRunner.js',
'!Specs/SpecList.js',
'!Specs/karma.conf.js',
'!Apps/Sandcastle/Sandcastle-client.js',
'!Apps/Sandcastle/Sandcastle-header.js',
'!Apps/Sandcastle/Sandcastle-warn.js',
'!Apps/Sandcastle/gallery/gallery-index.js'];
gulp.task('default', ['combine']);
gulp.task('build', function(done) {
mkdirp.sync('Build');
glslToJavaScript(minifyShaders, 'Build/minifyShaders.state');
createCesiumJs();
createSpecList();
createGalleryList();
createJsHintOptions();
done();
});
gulp.task('build-watch', function() {
gulp.watch(buildFiles, ['build']);
});
gulp.task('buildApps', function() {
return Promise.join(
buildCesiumViewer(),
buildSandcastle()
);
});
gulp.task('clean', function(done) {
filesToClean.forEach(function(file) {
rimraf.sync(file);
});
done();
});
gulp.task('requirejs', function(done) {
var config = JSON.parse(new Buffer(process.argv[3].substring(2), 'base64').toString('utf8'));
// Disable module load timeout
config.waitSeconds = 0;
requirejs.optimize(config, function() {
done();
}, done);
});
gulp.task('cloc', ['build'], function() {
var cmdLine;
var clocPath = path.join('Tools', 'cloc-1.60', 'cloc-1.60.pl');
var cloc_definitions = path.join('Tools', 'cloc-1.60', 'cloc_definitions');
//Run cloc on primary Source files only
var source = new Promise(function(resolve, reject) {
var glsl = globby.sync(['Source/Shaders/*.glsl', 'Source/Shaders/**/*.glsl']).join(' ');
cmdLine = 'perl ' + clocPath + ' --quiet --progress-rate=0 --read-lang-def=' + cloc_definitions +
' Source/main.js Source/Core/ Source/DataSources/ Source/Renderer/ Source/Scene/ Source/Widgets/ Source/Workers/ ' + glsl;
child_process.exec(cmdLine, function(error, stdout, stderr) {
if (error) {
console.log(stderr);
return reject(error);
}
console.log('Source:');
console.log(stdout);
resolve();
});
});
//If running cloc on source succeeded, also run it on the tests.
return source.then(function() {
return new Promise(function(resolve, reject) {
cmdLine = 'perl ' + clocPath + ' --quiet --progress-rate=0 --read-lang-def=' + cloc_definitions + ' Specs/';
child_process.exec(cmdLine, function(error, stdout, stderr) {
if (error) {
console.log(stderr);
return reject(error);
}
console.log('Specs:');
console.log(stdout);
resolve();
});
});
});
});
gulp.task('combine', ['generateStubs'], function() {
var outputDirectory = path.join('Build', 'CesiumUnminified');
return combineJavaScript({
removePragmas : false,
optimizer : 'none',
outputDirectory : outputDirectory
});
});
gulp.task('combineRelease', ['generateStubs'], function() {
var outputDirectory = path.join('Build', 'CesiumUnminified');
return combineJavaScript({
removePragmas : true,
optimizer : 'none',
outputDirectory : outputDirectory
});
});
//Builds the documentation
gulp.task('generateDocumentation', function() {
var envPathSeperator = os.platform() === 'win32' ? ';' : ':';
return new Promise(function(resolve, reject) {
child_process.exec('jsdoc --configure Tools/jsdoc/conf.json', {
env : {
PATH : process.env.PATH + envPathSeperator + 'node_modules/.bin',
CESIUM_VERSION : version
}
}, function(error, stdout, stderr) {
if (error) {
console.log(stderr);
return reject(error);
}
console.log(stdout);
var stream = gulp.src('Documentation/Images/**').pipe(gulp.dest('Build/Documentation/Images'));
return streamToPromise(stream).then(resolve);
});
});
});
gulp.task('instrumentForCoverage', ['build'], function(done) {
var jscoveragePath = path.join('Tools', 'jscoverage-0.5.1', 'jscoverage.exe');
var cmdLine = jscoveragePath + ' Source Instrumented --no-instrument=./ThirdParty';
child_process.exec(cmdLine, function(error, stdout, stderr) {
if (error) {
console.log(stderr);
return done(error);
}
console.log(stdout);
done();
});
});
gulp.task('makeZipFile', ['release'], function() {
//For now we regenerate the JS glsl to force it to be unminified in the release zip
//See https://github.com/AnalyticalGraphicsInc/cesium/pull/3106#discussion_r42793558 for discussion.
glslToJavaScript(false, 'Build/minifyShaders.state');
var builtSrc = gulp.src([
'Build/Apps/**',
'Build/Cesium/**',
'Build/CesiumUnminified/**',
'Build/Documentation/**'
], {
base : '.'
});
var staticSrc = gulp.src([
'Apps/**',
'!Apps/Sandcastle/gallery/development/**',
'Source/**',
'Specs/**',
'ThirdParty/**',
'favicon.ico',
'gulpfile.js',
'server.js',
'package.json',
'LICENSE.md',
'CHANGES.md',
'README.md',
'web.config'
], {
base : '.',
nodir : true
});
var indexSrc = gulp.src('index.release.html').pipe(gulpRename('index.html'));
return eventStream.merge(builtSrc, staticSrc, indexSrc)
.pipe(gulpTap(function(file) {
// Work around an issue with gulp-zip where archives generated on Windows do
// not properly have their directory executable mode set.
// see https://github.com/sindresorhus/gulp-zip/issues/64#issuecomment-205324031
if (file.isDirectory()) {
file.stat.mode = parseInt('40777', 8);
}
}))
.pipe(gulpZip('Cesium-' + version + '.zip'))
.pipe(gulp.dest('.'));
});
gulp.task('minify', ['generateStubs'], function() {
return combineJavaScript({
removePragmas : false,
optimizer : 'uglify2',
outputDirectory : path.join('Build', 'Cesium')
});
});
gulp.task('minifyRelease', ['generateStubs'], function() {
return combineJavaScript({
removePragmas : true,
optimizer : 'uglify2',
outputDirectory : path.join('Build', 'Cesium')
});
});
function isTravisPullRequest() {
return process.env.TRAVIS_PULL_REQUEST !== undefined && process.env.TRAVIS_PULL_REQUEST !== 'false';
}
gulp.task('deploy-s3', function(done) {
if (isTravisPullRequest()) {
console.log('Skipping deployment for non-pull request.');
return;
}
var argv = yargs.usage('Usage: deploy-s3 -b [Bucket Name] -d [Upload Directory]')
.demand(['b', 'd']).argv;
var uploadDirectory = argv.d;
var bucketName = argv.b;
var cacheControl = argv.c ? argv.c : 'max-age=3600';
if (argv.confirm) {
// skip prompt for travis
deployCesium(bucketName, uploadDirectory, cacheControl, done);
return;
}
var iface = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// prompt for confirmation
iface.question('Files from your computer will be published to the ' + bucketName + ' bucket. Continue? [y/n] ', function(answer) {
iface.close();
if (answer === 'y') {
deployCesium(bucketName, uploadDirectory, cacheControl, done);
} else {
console.log('Deploy aborted by user.');
done();
}
});
});
// Deploy cesium to s3
function deployCesium(bucketName, uploadDirectory, cacheControl, done) {
var readFile = Promise.promisify(fs.readFile);
var gzip = Promise.promisify(zlib.gzip);
var getCredentials = Promise.promisify(aws.config.getCredentials, {context: aws.config});
var concurrencyLimit = 2000;
var s3 = new Promise.promisifyAll(new aws.S3({
maxRetries : 10,
retryDelayOptions : {
base : 500
}
}));
var existingBlobs = [];
var totalFiles = 0;
var uploaded = 0;
var skipped = 0;
var errors = [];
return getCredentials()
.then(function() {
var prefix = uploadDirectory + '/';
return listAll(s3, bucketName, prefix, existingBlobs)
.then(function() {
return globby([
'Apps/**',
'Build/**',
'Source/**',
'Specs/**',
'ThirdParty/**',
'*.md',
'favicon.ico',
'gulpfile.js',
'index.html',
'package.json',
'server.js',
'web.config',
'*.zip',
'*.tgz'
], {
dot : true, // include hidden files
nodir : true // only directory files
});
})
.then(function(files) {
return Promise.map(files, function(file) {
var blobName = uploadDirectory + '/' + file;
var mimeLookup = getMimeType(blobName);
var contentType = mimeLookup.type;
var compress = mimeLookup.compress;
var contentEncoding = compress || mimeLookup.isCompressed ? 'gzip' : undefined;
var etag;
totalFiles++;
return readFile(file)
.then(function(content) {
return compress ? gzip(content) : content;
})
.then(function(content) {
// compute hash and etag
var hash = crypto.createHash('md5').update(content).digest('hex');
etag = crypto.createHash('md5').update(content).digest('base64');
var index = existingBlobs.indexOf(blobName);
if (index <= -1) {
return content;
}
// remove files as we find them on disk
existingBlobs.splice(index, 1);
// get file info
return s3.headObjectAsync({
Bucket : bucketName,
Key : blobName
})
.then(function(data) {
if (data.ETag !== ('"' + hash + '"') ||
data.CacheControl !== cacheControl ||
data.ContentType !== contentType ||
data.ContentEncoding !== contentEncoding) {
return content;
}
// We don't need to upload this file again
skipped++;
return undefined;
})
.catch(function(error) {
errors.push(error);
});
})
.then(function(content) {
if (!content) {
return;
}
console.log('Uploading ' + blobName + '...');
var params = {
Bucket : bucketName,
Key : blobName,
Body : content,
ContentMD5 : etag,
ContentType : contentType,
ContentEncoding : contentEncoding,
CacheControl : cacheControl
};
return s3.putObjectAsync(params).then(function() {
uploaded++;
})
.catch(function(error) {
errors.push(error);
});
});
}, {concurrency : concurrencyLimit});
})
.then(function() {
console.log('Skipped ' + skipped + ' files and successfully uploaded ' + uploaded + ' files of ' + (totalFiles - skipped) + ' files.');
if (existingBlobs.length === 0) {
return;
}
var objectToDelete = [];
existingBlobs.forEach(function(file) {
//Don't delete generate zip files.
if (!/\.(zip|tgz)$/.test(file)) {
objectToDelete.push({Key : file});
}
});
if (objectToDelete.length > 0) {
console.log('Cleaning up old files...');
return s3.deleteObjectsAsync({
Bucket : bucketName,
Delete : {
Objects : objectToDelete
}
})
.then(function() {
console.log('Cleaned ' + existingBlobs.length + ' files.');
});
}
})
.catch(function(error) {
errors.push(error);
})
.then(function() {
if (errors.length === 0) {
done();
return;
}
console.log('Errors: ');
errors.map(function(e) {
console.log(e);
});
done(1);
});
})
.catch(function(error) {
console.log('Error: Could not load S3 credentials.');
done();
});
}
function getMimeType(filename) {
var ext = path.extname(filename);
if (ext === '.bin' || ext === '.terrain') {
return {type : 'application/octet-stream', compress : true, isCompressed : false};
} else if (ext === '.md' || ext === '.glsl') {
return {type : 'text/plain', compress : true, isCompressed : false};
} else if (ext === '.czml' || ext === '.geojson' || ext === '.json') {
return {type : 'application/json', compress : true, isCompressed : false};
} else if (ext === '.js') {
return {type : 'application/javascript', compress : true, isCompressed : false};
} else if (ext === '.svg') {
return {type : 'image/svg+xml', compress : true, isCompressed : false};
} else if (ext === '.woff') {
return {type : 'application/font-woff', compress : false, isCompressed : false};
}
var mimeType = mime.lookup(filename);
var compress = compressible(mimeType);
return {type : mimeType, compress : compress, isCompressed : false};
}
// get all files currently in bucket asynchronously
function listAll(s3, bucketName, prefix, files, marker) {
return s3.listObjectsAsync({
Bucket : bucketName,
MaxKeys : 1000,
Prefix : prefix,
Marker : marker
})
.then(function(data) {
var items = data.Contents;
for (var i = 0; i < items.length; i++) {
files.push(items[i].Key);
}
if (data.IsTruncated) {
// get next page of results
return listAll(s3, bucketName, prefix, files, files[files.length - 1]);
}
});
}
gulp.task('deploy-set-version', function() {
var version = yargs.argv.version;
if (version) {
// NPM versions can only contain alphanumeric and hyphen characters
packageJson.version += '-' + version.replace(/[^[0-9A-Za-z-]/g, '');
fs.writeFileSync('package.json', JSON.stringify(packageJson, undefined, 2));
}
});
gulp.task('deploy-status', function() {
if (isTravisPullRequest()) {
console.log('Skipping deployment status for non-pull request.');
return;
}
var status = yargs.argv.status;
var message = yargs.argv.message;
var deployUrl = travisDeployUrl + process.env.TRAVIS_BRANCH + '/';
var zipUrl = deployUrl + 'Cesium-' + packageJson.version + '.zip';
var npmUrl = deployUrl + 'cesium-' + packageJson.version + '.tgz';
return Promise.join(
setStatus(status, deployUrl, message, 'deployment'),
setStatus(status, zipUrl, message, 'zip file'),
setStatus(status, npmUrl, message, 'npm package')
);
});
function setStatus(state, targetUrl, description, context) {
// skip if the environment does not have the token
if (!process.env.TOKEN) {
return;
}
var requestPost = Promise.promisify(request.post);
return requestPost({
url: 'https://api.github.com/repos/' + process.env.TRAVIS_REPO_SLUG + '/statuses/' + process.env.TRAVIS_COMMIT,
json: true,
headers: {
'Authorization': 'token ' + process.env.TOKEN,
'User-Agent': 'Cesium'
},
body: {
state: state,
target_url: targetUrl,
description: description,
context: context
}
});
}
gulp.task('release', ['combine', 'minifyRelease', 'generateDocumentation']);
gulp.task('test', function(done) {
var argv = yargs.argv;
var enableAllBrowsers = argv.all ? true : false;
var includeCategory = argv.include ? argv.include : '';
var excludeCategory = argv.exclude ? argv.exclude : '';
var webglValidation = argv.webglValidation ? argv.webglValidation : false;
var webglStub = argv.webglStub ? argv.webglStub : false;
var release = argv.release ? argv.release : false;
var failTaskOnError = argv.failTaskOnError ? argv.failTaskOnError : false;
var suppressPassed = argv.suppressPassed ? argv.suppressPassed : false;
var browsers = ['Chrome'];
if (argv.browsers) {
browsers = argv.browsers.split(',');
}
var files = [
'Specs/karma-main.js',
{pattern : 'Source/**', included : false},
{pattern : 'Specs/**', included : false}
];
if (release) {
files.push({pattern : 'Build/**', included : false});
}
karma.start({
configFile: karmaConfigFile,
browsers : browsers,
specReporter: {
suppressErrorSummary: false,
suppressFailed: false,
suppressPassed: suppressPassed,
suppressSkipped: true
},
detectBrowsers : {
enabled: enableAllBrowsers
},
files: files,
client: {
args: [includeCategory, excludeCategory, webglValidation, webglStub, release]
}
}, function(e) {
return done(failTaskOnError ? e : undefined);
});
});
gulp.task('generateStubs', ['build'], function(done) {
mkdirp.sync(path.join('Build', 'Stubs'));
var contents = '\
/*global define,Cesium*/\n\
(function() {\n\
\'use strict\';\n';
var modulePathMappings = [];
globby.sync(sourceFiles).forEach(function(file) {
file = path.relative('Source', file);
var moduleId = filePathToModuleId(file);
contents += '\
define(\'' + moduleId + '\', function() {\n\
return Cesium[\'' + path.basename(file, path.extname(file)) + '\'];\n\
});\n\n';
modulePathMappings.push(' \'' + moduleId + '\' : \'../Stubs/Cesium\'');
});
contents += '})();';
var paths = '\
define(function() {\n\
\'use strict\';\n\
return {\n' + modulePathMappings.join(',\n') + '\n\
};\n\
});';
fs.writeFileSync(path.join('Build', 'Stubs', 'Cesium.js'), contents);
fs.writeFileSync(path.join('Build', 'Stubs', 'paths.js'), paths);
done();
});
gulp.task('sortRequires', function() {
var noModulesRegex = /[\s\S]*?define\(function\(\)/;
var requiresRegex = /([\s\S]*?(define|defineSuite|require)\((?:{[\s\S]*}, )?\[)([\S\s]*?)]([\s\S]*?function\s*)\(([\S\s]*?)\) {([\s\S]*)/;
var splitRegex = /,\s*/;
var fsReadFile = Promise.promisify(fs.readFile);
var fsWriteFile = Promise.promisify(fs.writeFile);
var files = globby.sync(filesToSortRequires);
return Promise.map(files, function(file) {
return fsReadFile(file).then(function(contents) {
var result = requiresRegex.exec(contents);
if (result === null) {
if (!noModulesRegex.test(contents)) {
console.log(file + ' does not have the expected syntax.');
}
return;
}
// In specs, the first require is significant,
// unless the spec is given an explicit name.
var preserveFirst = false;
if (result[2] === 'defineSuite' && result[4] === ', function') {
preserveFirst = true;
}
var names = result[3].split(splitRegex);
if (names.length === 1 && names[0].trim() === '') {
names.length = 0;
}
var i;
for (i = 0; i < names.length; ++i) {
if (names[i].indexOf('//') >= 0 || names[i].indexOf('/*') >= 0) {
console.log(file + ' contains comments in the require list. Skipping so nothing gets broken.');
return;
}
}
var identifiers = result[5].split(splitRegex);
if (identifiers.length === 1 && identifiers[0].trim() === '') {
identifiers.length = 0;
}
for (i = 0; i < identifiers.length; ++i) {
if (identifiers[i].indexOf('//') >= 0 || identifiers[i].indexOf('/*') >= 0) {
console.log(file + ' contains comments in the require list. Skipping so nothing gets broken.');
return;
}
}
var requires = [];
for (i = preserveFirst ? 1 : 0; i < names.length && i < identifiers.length; ++i) {
requires.push({
name : names[i].trim(),
identifier : identifiers[i].trim()
});
}
requires.sort(function(a, b) {
var aName = a.name.toLowerCase();
var bName = b.name.toLowerCase();
if (aName < bName) {
return -1;
} else if (aName > bName) {
return 1;
}
return 0;
});
if (preserveFirst) {
requires.splice(0, 0, {
name : names[0].trim(),
identifier : identifiers[0].trim()
});
}
// Convert back to separate lists for the names and identifiers, and add
// any additional names or identifiers that don't have a corresponding pair.
var sortedNames = requires.map(function(item) {
return item.name;
});
for (i = sortedNames.length; i < names.length; ++i) {
sortedNames.push(names[i].trim());
}
var sortedIdentifiers = requires.map(function(item) {
return item.identifier;
});
for (i = sortedIdentifiers.length; i < identifiers.length; ++i) {
sortedIdentifiers.push(identifiers[i].trim());
}
var outputNames = ']';
if (sortedNames.length > 0) {
outputNames = os.EOL + ' ' +
sortedNames.join(',' + os.EOL + ' ') +
os.EOL + ' ]';
}
var outputIdentifiers = '(';
if (sortedIdentifiers.length > 0) {
outputIdentifiers = '(' + os.EOL + ' ' +
sortedIdentifiers.join(',' + os.EOL + ' ');
}
contents = result[1] +
outputNames +
result[4].replace(/^[,\s]+/, ', ').trim() +
outputIdentifiers +
') {' +
result[6];
return fsWriteFile(file, contents);
});
});
});
function combineCesium(debug, optimizer, combineOutput) {
return requirejsOptimize('Cesium.js', {
wrap : true,
useStrict : true,
optimize : optimizer,
optimizeCss : 'standard',
pragmas : {
debug : debug
},
baseUrl : 'Source',
skipModuleInsertion : true,
name : removeExtension(path.relative('Source', require.resolve('almond'))),
include : 'main',
out : path.join(combineOutput, 'Cesium.js')
});
}
function combineWorkers(debug, optimizer, combineOutput) {
//This is done waterfall style for concurrency reasons.
return globby(['Source/Workers/cesiumWorkerBootstrapper.js',
'Source/Workers/transferTypedArrayTest.js',
'Source/ThirdParty/Workers/*.js'])
.then(function(files) {
return Promise.map(files, function(file) {
return requirejsOptimize(file, {
wrap : false,
useStrict : true,
optimize : optimizer,
optimizeCss : 'standard',
pragmas : {
debug : debug
},
baseUrl : 'Source',
skipModuleInsertion : true,
include : filePathToModuleId(path.relative('Source', file)),
out : path.join(combineOutput, path.relative('Source', file))
});
}, {concurrency : concurrency});
})
.then(function() {
return globby(['Source/Workers/*.js',
'!Source/Workers/cesiumWorkerBootstrapper.js',
'!Source/Workers/transferTypedArrayTest.js',
'!Source/Workers/createTaskProcessorWorker.js',
'!Source/ThirdParty/Workers/*.js']);
})
.then(function(files) {
return Promise.map(files, function(file) {
return requirejsOptimize(file, {
wrap : true,
useStrict : true,
optimize : optimizer,
optimizeCss : 'standard',
pragmas : {
debug : debug
},
baseUrl : 'Source',
include : filePathToModuleId(path.relative('Source', file)),
out : path.join(combineOutput, path.relative('Source', file))
});
}, {concurrency : concurrency});
});
}
function minifyCSS(outputDirectory) {
return globby('Source/**/*.css').then(function(files) {
return Promise.map(files, function(file) {
return requirejsOptimize(file, {
wrap : true,
useStrict : true,
optimizeCss : 'standard',
pragmas : {
debug : true
},
cssIn : file,
out : path.join(outputDirectory, path.relative('Source', file))
});
}, {concurrency : concurrency});
});
}
function combineJavaScript(options) {
var optimizer = options.optimizer;
var outputDirectory = options.outputDirectory;
var removePragmas = options.removePragmas;
var combineOutput = path.join('Build', 'combineOutput', optimizer);
var copyrightHeader = fs.readFileSync(path.join('Source', 'copyrightHeader.js'));
var promise = Promise.join(
combineCesium(!removePragmas, optimizer, combineOutput),
combineWorkers(!removePragmas, optimizer, combineOutput)
);
return promise.then(function() {
var promises = [];
//copy to build folder with copyright header added at the top
var stream = gulp.src([combineOutput + '/**'])
.pipe(gulpInsert.prepend(copyrightHeader))
.pipe(gulp.dest(outputDirectory));
promises.push(streamToPromise(stream));
var everythingElse = ['Source/**', '!**/*.js', '!**/*.glsl'];
if (optimizer === 'uglify2') {
promises.push(minifyCSS(outputDirectory));
everythingElse.push('!**/*.css');
}
stream = gulp.src(everythingElse, {nodir : true}).pipe(gulp.dest(outputDirectory));
promises.push(streamToPromise(stream));
return Promise.all(promises).then(function() {
rimraf.sync(combineOutput);
});
});
}
function glslToJavaScript(minify, minifyStateFilePath) {
fs.writeFileSync(minifyStateFilePath, minify);
var minifyStateFileLastModified = fs.existsSync(minifyStateFilePath) ? fs.statSync(minifyStateFilePath).mtime.getTime() : 0;
// collect all currently existing JS files into a set, later we will remove the ones
// we still are using from the set, then delete any files remaining in the set.
var leftOverJsFiles = {};
globby.sync(['Source/Shaders/**/*.js', 'Source/ThirdParty/Shaders/*.js']).forEach(function(file) {
leftOverJsFiles[path.normalize(file)] = true;
});
var builtinFunctions = [];
var builtinConstants = [];
var builtinStructs = [];
var glslFiles = globby.sync(['Source/Shaders/**/*.glsl', 'Source/ThirdParty/Shaders/*.glsl']);
glslFiles.forEach(function(glslFile) {
glslFile = path.normalize(glslFile);
var baseName = path.basename(glslFile, '.glsl');
var jsFile = path.join(path.dirname(glslFile), baseName) + '.js';
// identify built in functions, structs, and constants
var baseDir = path.join('Source', 'Shaders', 'Builtin');
if (glslFile.indexOf(path.normalize(path.join(baseDir, 'Functions'))) === 0) {
builtinFunctions.push(baseName);
}
else if (glslFile.indexOf(path.normalize(path.join(baseDir, 'Constants'))) === 0) {
builtinConstants.push(baseName);
}
else if (glslFile.indexOf(path.normalize(path.join(baseDir, 'Structs'))) === 0) {
builtinStructs.push(baseName);
}
delete leftOverJsFiles[jsFile];
var jsFileExists = fs.existsSync(jsFile);
var jsFileModified = jsFileExists ? fs.statSync(jsFile).mtime.getTime() : 0;
var glslFileModified = fs.statSync(glslFile).mtime.getTime();
if (jsFileExists && jsFileModified > glslFileModified && jsFileModified > minifyStateFileLastModified) {
return;
}
var contents = fs.readFileSync(glslFile, 'utf8');
contents = contents.replace(/\r\n/gm, '\n');
var copyrightComments = '';
var extractedCopyrightComments = contents.match(/\/\*\*(?:[^*\/]|\*(?!\/)|\n)*?@license(?:.|\n)*?\*\//gm);
if (extractedCopyrightComments) {
copyrightComments = extractedCopyrightComments.join('\n') + '\n';
}
if (minify) {
contents = glslStripComments(contents);
contents = contents.replace(/\s+$/gm, '').replace(/^\s+/gm, '').replace(/\n+/gm, '\n');
contents += '\n';
}
contents = contents.split('"').join('\\"').replace(/\n/gm, '\\n\\\n');
contents = copyrightComments + '\
//This file is automatically rebuilt by the Cesium build process.\n\
define(function() {\n\
\'use strict\';\n\
return "' + contents + '";\n\
});';
fs.writeFileSync(jsFile, contents);
});
// delete any left over JS files from old shaders
Object.keys(leftOverJsFiles).forEach(function(filepath) {
rimraf.sync(filepath);
});
var generateBuiltinContents = function(contents, builtins, path) {
var amdPath = contents.amdPath;
var amdClassName = contents.amdClassName;
var builtinLookup = contents.builtinLookup;
for (var i = 0; i < builtins.length; i++) {
var builtin = builtins[i];
amdPath = amdPath + ',\n \'./' + path + '/' + builtin + '\'';
amdClassName = amdClassName + ',\n ' + 'czm_' + builtin;
builtinLookup = builtinLookup + ',\n ' + 'czm_' + builtin + ' : ' + 'czm_' + builtin;
}
contents.amdPath = amdPath;
contents.amdClassName = amdClassName;
contents.builtinLookup = builtinLookup;
};
//generate the JS file for Built-in GLSL Functions, Structs, and Constants
var contents = {amdPath : '', amdClassName : '', builtinLookup : ''};
generateBuiltinContents(contents, builtinConstants, 'Constants');
generateBuiltinContents(contents, builtinStructs, 'Structs');
generateBuiltinContents(contents, builtinFunctions, 'Functions');
contents.amdPath = contents.amdPath.replace(',\n', '');
contents.amdClassName = contents.amdClassName.replace(',\n', '');
contents.builtinLookup = contents.builtinLookup.replace(',\n', '');
var fileContents = '\
//This file is automatically rebuilt by the Cesium build process.\n\
define([\n' +
contents.amdPath +
'\n ], function(\n' +
contents.amdClassName +
') {\n\
\'use strict\';\n\
return {\n' + contents.builtinLookup + '};\n\
});';
fs.writeFileSync(path.join('Source', 'Shaders', 'Builtin', 'CzmBuiltins.js'), fileContents);
}
function createCesiumJs() {
var moduleIds = [];
var parameters = [];
var assignments = [];
var nonIdentifierRegexp = /[^0-9a-zA-Z_$]/g;
globby.sync(sourceFiles).forEach(function(file) {
file = path.relative('Source', file);
var moduleId = file;
moduleId = filePathToModuleId(moduleId);
var assignmentName = "['" + path.basename(file, path.extname(file)) + "']";
if (moduleId.indexOf('Shaders/') === 0) {
assignmentName = '._shaders' + assignmentName;
}
var parameterName = moduleId.replace(nonIdentifierRegexp, '_');
moduleIds.push("'./" + moduleId + "'");
parameters.push(parameterName);
assignments.push('Cesium' + assignmentName + ' = ' + parameterName + ';');
});
var contents = '\
define([' + moduleIds.join(', ') + '], function(' + parameters.join(', ') + ') {\n\
\'use strict\';\n\
var Cesium = {\n\
VERSION : \'' + version + '\',\n\
_shaders : {}\n\
};\n\
' + assignments.join('\n ') + '\n\
return Cesium;\n\
});';
fs.writeFileSync('Source/Cesium.js', contents);
}
function createSpecList() {
var specFiles = globby.sync(['Specs/**/*.js', '!Specs/*.js']);
var specs = [];
specFiles.forEach(function(file) {
specs.push("'" + filePathToModuleId(file) + "'");
});
var contents = '/*eslint-disable no-unused-vars*/\n/*eslint-disable no-implicit-globals*/\nvar specs = [' + specs.join(',') + '];';
fs.writeFileSync(path.join('Specs', 'SpecList.js'), contents);
}
function createGalleryList() {
var demoObjects = [];
var demoJSONs = [];
var output = path.join('Apps', 'Sandcastle', 'gallery', 'gallery-index.js');
var fileList = ['Apps/Sandcastle/gallery/**/*.html'];
if (noDevelopmentGallery) {
fileList.push('!Apps/Sandcastle/gallery/development/**/*.html');
}
var helloWorld;
globby.sync(fileList).forEach(function(file) {
var demo = filePathToModuleId(path.relative('Apps/Sandcastle/gallery', file));
var demoObject = {
name : demo,
date : fs.statSync(file).mtime.getTime()
};
if (fs.existsSync(file.replace('.html', '') + '.jpg')) {
demoObject.img = demo + '.jpg';
}
demoObjects.push(demoObject);
if (demo === 'Hello World') {
helloWorld = demoObject;
}
});
demoObjects.sort(function(a, b) {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
}
return 0;
});
var helloWorldIndex = Math.max(demoObjects.indexOf(helloWorld), 0);
var i;
for (i = 0; i < demoObjects.length; ++i) {
demoJSONs[i] = JSON.stringify(demoObjects[i], null, 2);
}
var contents = '\
// This file is automatically rebuilt by the Cesium build process.\n\
var hello_world_index = ' + helloWorldIndex + ';\n\
var gallery_demos = [' + demoJSONs.join(', ') + '];';
fs.writeFileSync(output, contents);
}
function createJsHintOptions() {
var primary = JSON.parse(fs.readFileSync(path.join('Apps', '.jshintrc'), 'utf8'));
var gallery = JSON.parse(fs.readFileSync(path.join('Apps', 'Sandcastle', '.jshintrc'), 'utf8'));
primary.jasmine = false;
primary.predef = gallery.predef;
primary.unused = gallery.unused;
var contents = '\
// This file is automatically rebuilt by the Cesium build process.\n\
var sandcastleJsHintOptions = ' + JSON.stringify(primary, null, 4) + ';';
fs.writeFileSync(path.join('Apps', 'Sandcastle', 'jsHintOptions.js'), contents);
}
function buildSandcastle() {
var appStream = gulp.src([
'Apps/Sandcastle/**',
'!Apps/Sandcastle/images/**',
'!Apps/Sandcastle/gallery/**.jpg'
])
// Replace require Source with pre-built Cesium
.pipe(gulpReplace('../../../ThirdParty/requirejs-2.1.20/require.js', '../../../CesiumUnminified/Cesium.js'))
// Use unminified cesium instead of source
.pipe(gulpReplace('Source/Cesium', 'CesiumUnminified'))
// Fix relative paths for new location
.pipe(gulpReplace('../../Source', '../../../Source'))
.pipe(gulpReplace('../../ThirdParty', '../../../ThirdParty'))
.pipe(gulpReplace('../../SampleData', '../../../../Apps/SampleData'))
.pipe(gulpReplace('Build/Documentation', 'Documentation'))
.pipe(gulp.dest('Build/Apps/Sandcastle'));
var imageStream = gulp.src([
'Apps/Sandcastle/gallery/**.jpg',
'Apps/Sandcastle/images/**'
], {
base: 'Apps/Sandcastle',
buffer: false
})
.pipe(gulp.dest('Build/Apps/Sandcastle'));
return eventStream.merge(appStream, imageStream);
}
function buildCesiumViewer() {
var cesiumViewerOutputDirectory = 'Build/Apps/CesiumViewer';
var cesiumViewerStartup = path.join(cesiumViewerOutputDirectory, 'CesiumViewerStartup.js');
var cesiumViewerCss = path.join(cesiumViewerOutputDirectory, 'CesiumViewer.css');
mkdirp.sync(cesiumViewerOutputDirectory);
var promise = Promise.join(
requirejsOptimize('CesiumViewer', {
wrap : true,
useStrict : true,
optimizeCss : 'standard',
pragmas : {
debug : false
},
optimize : 'uglify2',
mainConfigFile : 'Apps/CesiumViewer/CesiumViewerStartup.js',
name : 'CesiumViewerStartup',
out : cesiumViewerStartup
}),
requirejsOptimize('CesiumViewer CSS', {
wrap : true,
useStrict : true,
optimizeCss : 'standard',
pragmas : {
debug : false
},
cssIn : 'Apps/CesiumViewer/CesiumViewer.css',
out : cesiumViewerCss
})
);
promise = promise.then(function() {
var copyrightHeader = fs.readFileSync(path.join('Source', 'copyrightHeader.js'));
var stream = eventStream.merge(
gulp.src(cesiumViewerStartup)
.pipe(gulpInsert.prepend(copyrightHeader))
.pipe(gulpReplace('../../Source', '.'))
.pipe(gulpReplace('../../ThirdParty/requirejs-2.1.20', '.')),
gulp.src(cesiumViewerCss)
.pipe(gulpReplace('../../Source', '.')),
gulp.src(['Apps/CesiumViewer/index.html'])
.pipe(gulpReplace('../../ThirdParty/requirejs-2.1.20', '.')),
gulp.src(['Apps/CesiumViewer/**',
'!Apps/CesiumViewer/index.html',
'!Apps/CesiumViewer/**/*.js',
'!Apps/CesiumViewer/**/*.css']),
gulp.src(['ThirdParty/requirejs-2.1.20/require.min.js'])
.pipe(gulpRename('require.js')),
gulp.src(['Build/Cesium/Assets/**',
'Build/Cesium/Workers/**',
'Build/Cesium/ThirdParty/Workers/**',
'Build/Cesium/Widgets/**',
'!Build/Cesium/Widgets/**/*.css'],
{
base : 'Build/Cesium',
nodir : true
}),
gulp.src(['Build/Cesium/Widgets/InfoBox/InfoBoxDescription.css'], {
base : 'Build/Cesium'
}),
gulp.src(['web.config'])
);
return streamToPromise(stream.pipe(gulp.dest(cesiumViewerOutputDirectory)));
});
return promise;
}
function filePathToModuleId(moduleId) {
return moduleId.substring(0, moduleId.lastIndexOf('.')).replace(/\\/g, '/');
}
function removeExtension(p) {
return p.slice(0, -path.extname(p).length);
}
function requirejsOptimize(name, config) {
console.log('Building ' + name);
return new Promise(function(resolve, reject) {
var cmd = 'npm run requirejs -- --' + new Buffer(JSON.stringify(config)).toString('base64') + ' --silent';
child_process.exec(cmd, function(e) {
if (e) {
console.log('Error ' + name);
reject(e);
return;
}
console.log('Finished ' + name);
resolve();
});
});
}
function streamToPromise(stream) {
return new Promise(function(resolve, reject) {
stream.on('finish', resolve);
stream.on('end', resolve);
stream.on('error', reject);
});
}
| gulpfile.js | /*jslint node: true, latedef: nofunc*/
/*eslint-env node*/
'use strict';
var fs = require('fs');
var path = require('path');
var os = require('os');
var child_process = require('child_process');
var crypto = require('crypto');
var zlib = require('zlib');
var readline = require('readline');
var request = require('request');
var globby = require('globby');
var gulpTap = require('gulp-tap');
var rimraf = require('rimraf');
var glslStripComments = require('glsl-strip-comments');
var mkdirp = require('mkdirp');
var eventStream = require('event-stream');
var gulp = require('gulp');
var gulpInsert = require('gulp-insert');
var gulpZip = require('gulp-zip');
var gulpRename = require('gulp-rename');
var gulpReplace = require('gulp-replace');
var Promise = require('bluebird');
var requirejs = require('requirejs');
var karma = require('karma').Server;
var yargs = require('yargs');
var aws = require('aws-sdk');
var mime = require('mime');
var compressible = require('compressible');
var packageJson = require('./package.json');
var version = packageJson.version;
if (/\.0$/.test(version)) {
version = version.substring(0, version.length - 2);
}
var karmaConfigFile = path.join(__dirname, 'Specs/karma.conf.js');
var travisDeployUrl = 'http://cesium-dev.s3-website-us-east-1.amazonaws.com/cesium/';
//Gulp doesn't seem to have a way to get the currently running tasks for setting
//per-task variables. We use the command line argument here to detect which task is being run.
var taskName = process.argv[2];
var noDevelopmentGallery = taskName === 'release' || taskName === 'makeZipFile';
var buildingRelease = noDevelopmentGallery;
var minifyShaders = taskName === 'minify' || taskName === 'minifyRelease' || taskName === 'release' || taskName === 'makeZipFile' || taskName === 'buildApps';
var concurrency = yargs.argv.concurrency;
if (!concurrency) {
concurrency = os.cpus().length;
}
//Since combine and minify run in parallel already, split concurrency in half when building both.
//This can go away when gulp 4 comes out because it allows for synchronous tasks.
if (buildingRelease) {
concurrency = concurrency / 2;
}
var sourceFiles = ['Source/**/*.js',
'!Source/*.js',
'!Source/Workers/**',
'!Source/ThirdParty/Workers/**',
'Source/Workers/createTaskProcessorWorker.js'];
var buildFiles = ['Specs/**/*.js',
'!Specs/SpecList.js',
'Source/Shaders/**/*.glsl'];
var filesToClean = ['Source/Cesium.js',
'Build',
'Instrumented',
'Source/Shaders/**/*.js',
'Source/ThirdParty/Shaders/*.js',
'Specs/SpecList.js',
'Apps/Sandcastle/jsHintOptions.js',
'Apps/Sandcastle/gallery/gallery-index.js',
'Cesium-*.zip'];
var filesToSortRequires = ['Source/**/*.js',
'!Source/Shaders/**',
'!Source/ThirdParty/**',
'!Source/Workers/cesiumWorkerBootstrapper.js',
'!Source/copyrightHeader.js',
'!Source/Workers/transferTypedArrayTest.js',
'Apps/**/*.js',
'!Apps/Sandcastle/ThirdParty/**',
'!Apps/Sandcastle/jsHintOptions.js',
'Specs/**/*.js',
'!Specs/spec-main.js',
'!Specs/SpecRunner.js',
'!Specs/SpecList.js',
'!Specs/karma.conf.js',
'!Apps/Sandcastle/Sandcastle-client.js',
'!Apps/Sandcastle/Sandcastle-header.js',
'!Apps/Sandcastle/Sandcastle-warn.js',
'!Apps/Sandcastle/gallery/gallery-index.js'];
gulp.task('default', ['combine']);
gulp.task('build', function(done) {
mkdirp.sync('Build');
glslToJavaScript(minifyShaders, 'Build/minifyShaders.state');
createCesiumJs();
createSpecList();
createGalleryList();
createJsHintOptions();
done();
});
gulp.task('build-watch', function() {
gulp.watch(buildFiles, ['build']);
});
gulp.task('buildApps', function() {
return Promise.join(
buildCesiumViewer(),
buildSandcastle()
);
});
gulp.task('clean', function(done) {
filesToClean.forEach(function(file) {
rimraf.sync(file);
});
done();
});
gulp.task('requirejs', function(done) {
var config = JSON.parse(new Buffer(process.argv[3].substring(2), 'base64').toString('utf8'));
// Disable module load timeout
config.waitSeconds = 0;
requirejs.optimize(config, function() {
done();
}, done);
});
gulp.task('cloc', ['build'], function() {
var cmdLine;
var clocPath = path.join('Tools', 'cloc-1.60', 'cloc-1.60.pl');
var cloc_definitions = path.join('Tools', 'cloc-1.60', 'cloc_definitions');
//Run cloc on primary Source files only
var source = new Promise(function(resolve, reject) {
var glsl = globby.sync(['Source/Shaders/*.glsl', 'Source/Shaders/**/*.glsl']).join(' ');
cmdLine = 'perl ' + clocPath + ' --quiet --progress-rate=0 --read-lang-def=' + cloc_definitions +
' Source/main.js Source/Core/ Source/DataSources/ Source/Renderer/ Source/Scene/ Source/Widgets/ Source/Workers/ ' + glsl;
child_process.exec(cmdLine, function(error, stdout, stderr) {
if (error) {
console.log(stderr);
return reject(error);
}
console.log('Source:');
console.log(stdout);
resolve();
});
});
//If running cloc on source succeeded, also run it on the tests.
return source.then(function() {
return new Promise(function(resolve, reject) {
cmdLine = 'perl ' + clocPath + ' --quiet --progress-rate=0 --read-lang-def=' + cloc_definitions + ' Specs/';
child_process.exec(cmdLine, function(error, stdout, stderr) {
if (error) {
console.log(stderr);
return reject(error);
}
console.log('Specs:');
console.log(stdout);
resolve();
});
});
});
});
gulp.task('combine', ['generateStubs'], function() {
var outputDirectory = path.join('Build', 'CesiumUnminified');
return combineJavaScript({
removePragmas : false,
optimizer : 'none',
outputDirectory : outputDirectory
});
});
gulp.task('combineRelease', ['generateStubs'], function() {
var outputDirectory = path.join('Build', 'CesiumUnminified');
return combineJavaScript({
removePragmas : true,
optimizer : 'none',
outputDirectory : outputDirectory
});
});
//Builds the documentation
gulp.task('generateDocumentation', function() {
var envPathSeperator = os.platform() === 'win32' ? ';' : ':';
return new Promise(function(resolve, reject) {
child_process.exec('jsdoc --configure Tools/jsdoc/conf.json', {
env : {
PATH : process.env.PATH + envPathSeperator + 'node_modules/.bin',
CESIUM_VERSION : version
}
}, function(error, stdout, stderr) {
if (error) {
console.log(stderr);
return reject(error);
}
console.log(stdout);
var stream = gulp.src('Documentation/Images/**').pipe(gulp.dest('Build/Documentation/Images'));
return streamToPromise(stream).then(resolve);
});
});
});
gulp.task('instrumentForCoverage', ['build'], function(done) {
var jscoveragePath = path.join('Tools', 'jscoverage-0.5.1', 'jscoverage.exe');
var cmdLine = jscoveragePath + ' Source Instrumented --no-instrument=./ThirdParty';
child_process.exec(cmdLine, function(error, stdout, stderr) {
if (error) {
console.log(stderr);
return done(error);
}
console.log(stdout);
done();
});
});
gulp.task('makeZipFile', ['release'], function() {
//For now we regenerate the JS glsl to force it to be unminified in the release zip
//See https://github.com/AnalyticalGraphicsInc/cesium/pull/3106#discussion_r42793558 for discussion.
glslToJavaScript(false, 'Build/minifyShaders.state');
var builtSrc = gulp.src([
'Build/Apps/**',
'Build/Cesium/**',
'Build/CesiumUnminified/**',
'Build/Documentation/**'
], {
base : '.'
});
var staticSrc = gulp.src([
'Apps/**',
'!Apps/Sandcastle/gallery/development/**',
'Source/**',
'Specs/**',
'ThirdParty/**',
'favicon.ico',
'gulpfile.js',
'server.js',
'package.json',
'LICENSE.md',
'CHANGES.md',
'README.md',
'web.config'
], {
base : '.',
nodir : true
});
var indexSrc = gulp.src('index.release.html').pipe(gulpRename('index.html'));
return eventStream.merge(builtSrc, staticSrc, indexSrc)
.pipe(gulpTap(function(file) {
// Work around an issue with gulp-zip where archives generated on Windows do
// not properly have their directory executable mode set.
// see https://github.com/sindresorhus/gulp-zip/issues/64#issuecomment-205324031
if (file.isDirectory()) {
file.stat.mode = parseInt('40777', 8);
}
}))
.pipe(gulpZip('Cesium-' + version + '.zip'))
.pipe(gulp.dest('.'));
});
gulp.task('minify', ['generateStubs'], function() {
return combineJavaScript({
removePragmas : false,
optimizer : 'uglify2',
outputDirectory : path.join('Build', 'Cesium')
});
});
gulp.task('minifyRelease', ['generateStubs'], function() {
return combineJavaScript({
removePragmas : true,
optimizer : 'uglify2',
outputDirectory : path.join('Build', 'Cesium')
});
});
function isTravisPullRequest() {
return process.env.TRAVIS_PULL_REQUEST !== undefined && process.env.TRAVIS_PULL_REQUEST !== 'false';
}
gulp.task('deploy-s3', function(done) {
if (isTravisPullRequest()) {
console.log('Skipping deployment for non-pull request.');
return;
}
var argv = yargs.usage('Usage: deploy-s3 -b [Bucket Name] -d [Upload Directory]')
.demand(['b', 'd']).argv;
var uploadDirectory = argv.d;
var bucketName = argv.b;
var cacheControl = argv.c ? argv.c : 'max-age=3600';
if (argv.confirm) {
// skip prompt for travis
deployCesium(bucketName, uploadDirectory, cacheControl, done);
return;
}
var iface = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// prompt for confirmation
iface.question('Files from your computer will be published to the ' + bucketName + ' bucket. Continue? [y/n] ', function(answer) {
iface.close();
if (answer === 'y') {
deployCesium(bucketName, uploadDirectory, cacheControl, done);
} else {
console.log('Deploy aborted by user.');
done();
}
});
});
// Deploy cesium to s3
function deployCesium(bucketName, uploadDirectory, cacheControl, done) {
var readFile = Promise.promisify(fs.readFile);
var gzip = Promise.promisify(zlib.gzip);
var getCredentials = Promise.promisify(aws.config.getCredentials, {context: aws.config});
var concurrencyLimit = 2000;
var s3 = new Promise.promisifyAll(new aws.S3({
maxRetries : 10,
retryDelayOptions : {
base : 500
}
}));
var existingBlobs = [];
var totalFiles = 0;
var uploaded = 0;
var skipped = 0;
var errors = [];
return getCredentials()
.then(function() {
var prefix = uploadDirectory + '/';
return listAll(s3, bucketName, prefix, existingBlobs)
.then(function() {
return globby([
'Apps/**',
'Build/**',
'Source/**',
'Specs/**',
'ThirdParty/**',
'*.md',
'favicon.ico',
'gulpfile.js',
'index.html',
'package.json',
'server.js',
'web.config',
'*.zip',
'*.tgz'
], {
dot : true, // include hidden files
nodir : true // only directory files
});
})
.then(function(files) {
return Promise.map(files, function(file) {
var blobName = uploadDirectory + '/' + file;
var mimeLookup = getMimeType(blobName);
var contentType = mimeLookup.type;
var compress = mimeLookup.compress;
var contentEncoding = compress || mimeLookup.isCompressed ? 'gzip' : undefined;
var etag;
totalFiles++;
return readFile(file)
.then(function(content) {
return compress ? gzip(content) : content;
})
.then(function(content) {
// compute hash and etag
var hash = crypto.createHash('md5').update(content).digest('hex');
etag = crypto.createHash('md5').update(content).digest('base64');
var index = existingBlobs.indexOf(blobName);
if (index <= -1) {
return content;
}
// remove files as we find them on disk
existingBlobs.splice(index, 1);
// get file info
return s3.headObjectAsync({
Bucket : bucketName,
Key : blobName
})
.then(function(data) {
if (data.ETag !== ('"' + hash + '"') ||
data.CacheControl !== cacheControl ||
data.ContentType !== contentType ||
data.ContentEncoding !== contentEncoding) {
return content;
}
// We don't need to upload this file again
skipped++;
return undefined;
})
.catch(function(error) {
errors.push(error);
});
})
.then(function(content) {
if (!content) {
return;
}
console.log('Uploading ' + blobName + '...');
var params = {
Bucket : bucketName,
Key : blobName,
Body : content,
ContentMD5 : etag,
ContentType : contentType,
ContentEncoding : contentEncoding,
CacheControl : cacheControl
};
return s3.putObjectAsync(params).then(function() {
uploaded++;
})
.catch(function(error) {
errors.push(error);
});
});
}, {concurrency : concurrencyLimit});
})
.then(function() {
console.log('Skipped ' + skipped + ' files and successfully uploaded ' + uploaded + ' files of ' + (totalFiles - skipped) + ' files.');
if (existingBlobs.length === 0) {
return;
}
var objectToDelete = [];
existingBlobs.forEach(function(file) {
//Don't delete generate zip files.
if (!/\.(zip|tgz)$/.test(file)) {
objectToDelete.push({Key : file});
}
});
if (objectToDelete.length > 0) {
console.log('Cleaning up old files...');
return s3.deleteObjectsAsync({
Bucket : bucketName,
Delete : {
Objects : objectToDelete
}
})
.then(function() {
console.log('Cleaned ' + existingBlobs.length + ' files.');
});
}
})
.catch(function(error) {
errors.push(error);
})
.then(function() {
if (errors.length === 0) {
done();
return;
}
console.log('Errors: ');
errors.map(function(e) {
console.log(e);
});
done(1);
});
})
.catch(function(error) {
console.log('Error: Could not load S3 credentials.');
done();
});
}
function getMimeType(filename) {
var ext = path.extname(filename);
if (ext === '.bin' || ext === '.terrain') {
return {type : 'application/octet-stream', compress : true, isCompressed : false};
} else if (ext === '.md' || ext === '.glsl') {
return {type : 'text/plain', compress : true, isCompressed : false};
} else if (ext === '.czml' || ext === '.geojson' || ext === '.json') {
return {type : 'application/json', compress : true, isCompressed : false};
} else if (ext === '.js') {
return {type : 'application/javascript', compress : true, isCompressed : false};
} else if (ext === '.svg') {
return {type : 'image/svg+xml', compress : true, isCompressed : false};
} else if (ext === '.woff') {
return {type : 'application/font-woff', compress : false, isCompressed : false};
}
var mimeType = mime.lookup(filename);
var compress = compressible(mimeType);
return {type : mimeType, compress : compress, isCompressed : false};
}
// get all files currently in bucket asynchronously
function listAll(s3, bucketName, prefix, files, marker) {
return s3.listObjectsAsync({
Bucket : bucketName,
MaxKeys : 1000,
Prefix : prefix,
Marker : marker
})
.then(function(data) {
var items = data.Contents;
for (var i = 0; i < items.length; i++) {
files.push(items[i].Key);
}
if (data.IsTruncated) {
// get next page of results
return listAll(s3, bucketName, prefix, files, files[files.length - 1]);
}
});
}
gulp.task('deploy-set-version', function() {
var version = yargs.argv.version;
if (version) {
// NPM versions can only contain alphanumeric and hyphen characters
packageJson.version += '-' + version.replace(/[^[0-9A-Za-z-]/g, '');
fs.writeFileSync('package.json', JSON.stringify(packageJson, undefined, 2));
}
});
gulp.task('deploy-status', function() {
if (isTravisPullRequest()) {
console.log('Skipping deployment status for non-pull request.');
return;
}
var status = yargs.argv.status;
var message = yargs.argv.message;
var deployUrl = travisDeployUrl + process.env.TRAVIS_BRANCH + '/';
var zipUrl = deployUrl + 'Cesium-' + packageJson.version + '.zip';
var npmUrl = deployUrl + 'cesium-' + packageJson.version + '.tgz';
return Promise.join(
setStatus(status, deployUrl, message, 'deployment'),
setStatus(status, zipUrl, message, 'zip file'),
setStatus(status, npmUrl, message, 'npm package')
);
});
function setStatus(state, targetUrl, description, context) {
// skip if the environment does not have the token
if (!process.env.TOKEN) {
return;
}
var requestPost = Promise.promisify(request.post);
return requestPost({
url: 'https://api.github.com/repos/' + process.env.TRAVIS_REPO_SLUG + '/statuses/' + process.env.TRAVIS_COMMIT,
json: true,
headers: {
'Authorization': 'token ' + process.env.TOKEN,
'User-Agent': 'Cesium'
},
body: {
state: state,
target_url: targetUrl,
description: description,
context: context
}
});
}
gulp.task('release', ['combine', 'minifyRelease', 'generateDocumentation']);
gulp.task('test', function(done) {
var argv = yargs.argv;
var enableAllBrowsers = argv.all ? true : false;
var includeCategory = argv.include ? argv.include : '';
var excludeCategory = argv.exclude ? argv.exclude : '';
var webglValidation = argv.webglValidation ? argv.webglValidation : false;
var webglStub = argv.webglStub ? argv.webglStub : false;
var release = argv.release ? argv.release : false;
var failTaskOnError = argv.failTaskOnError ? argv.failTaskOnError : false;
var suppressPassed = argv.suppressPassed ? argv.suppressPassed : false;
var browsers = ['Chrome'];
if (argv.browsers) {
browsers = argv.browsers.split(',');
}
var files = [
'Specs/karma-main.js',
{pattern : 'Source/**', included : false},
{pattern : 'Specs/**', included : false}
];
if (release) {
files.push({pattern : 'Build/**', included : false});
}
karma.start({
configFile: karmaConfigFile,
browsers : browsers,
specReporter: {
suppressErrorSummary: false,
suppressFailed: false,
suppressPassed: suppressPassed,
suppressSkipped: true
},
detectBrowsers : {
enabled: enableAllBrowsers
},
files: files,
client: {
args: [includeCategory, excludeCategory, webglValidation, webglStub, release]
}
}, function(e) {
return done(failTaskOnError ? e : undefined);
});
});
gulp.task('generateStubs', ['build'], function(done) {
mkdirp.sync(path.join('Build', 'Stubs'));
var contents = '\
/*global define,Cesium*/\n\
(function() {\n\
\'use strict\';\n';
var modulePathMappings = [];
globby.sync(sourceFiles).forEach(function(file) {
file = path.relative('Source', file);
var moduleId = filePathToModuleId(file);
contents += '\
define(\'' + moduleId + '\', function() {\n\
return Cesium[\'' + path.basename(file, path.extname(file)) + '\'];\n\
});\n\n';
modulePathMappings.push(' \'' + moduleId + '\' : \'../Stubs/Cesium\'');
});
contents += '})();';
var paths = '\
define(function() {\n\
\'use strict\';\n\
return {\n' + modulePathMappings.join(',\n') + '\n\
};\n\
});';
fs.writeFileSync(path.join('Build', 'Stubs', 'Cesium.js'), contents);
fs.writeFileSync(path.join('Build', 'Stubs', 'paths.js'), paths);
done();
});
gulp.task('sortRequires', function() {
var noModulesRegex = /[\s\S]*?define\(function\(\)/;
var requiresRegex = /([\s\S]*?(define|defineSuite|require)\((?:{[\s\S]*}, )?\[)([\S\s]*?)]([\s\S]*?function\s*)\(([\S\s]*?)\) {([\s\S]*)/;
var splitRegex = /,\s*/;
var fsReadFile = Promise.promisify(fs.readFile);
var fsWriteFile = Promise.promisify(fs.writeFile);
var files = globby.sync(filesToSortRequires);
return Promise.map(files, function(file) {
return fsReadFile(file).then(function(contents) {
var result = requiresRegex.exec(contents);
if (result === null) {
if (!noModulesRegex.test(contents)) {
console.log(file + ' does not have the expected syntax.');
}
return;
}
// In specs, the first require is significant,
// unless the spec is given an explicit name.
var preserveFirst = false;
if (result[2] === 'defineSuite' && result[4] === ', function') {
preserveFirst = true;
}
var names = result[3].split(splitRegex);
if (names.length === 1 && names[0].trim() === '') {
names.length = 0;
}
var i;
for (i = 0; i < names.length; ++i) {
if (names[i].indexOf('//') >= 0 || names[i].indexOf('/*') >= 0) {
console.log(file + ' contains comments in the require list. Skipping so nothing gets broken.');
return;
}
}
var identifiers = result[5].split(splitRegex);
if (identifiers.length === 1 && identifiers[0].trim() === '') {
identifiers.length = 0;
}
for (i = 0; i < identifiers.length; ++i) {
if (identifiers[i].indexOf('//') >= 0 || identifiers[i].indexOf('/*') >= 0) {
console.log(file + ' contains comments in the require list. Skipping so nothing gets broken.');
return;
}
}
var requires = [];
for (i = preserveFirst ? 1 : 0; i < names.length && i < identifiers.length; ++i) {
requires.push({
name : names[i].trim(),
identifier : identifiers[i].trim()
});
}
requires.sort(function(a, b) {
var aName = a.name.toLowerCase();
var bName = b.name.toLowerCase();
if (aName < bName) {
return -1;
} else if (aName > bName) {
return 1;
}
return 0;
});
if (preserveFirst) {
requires.splice(0, 0, {
name : names[0].trim(),
identifier : identifiers[0].trim()
});
}
// Convert back to separate lists for the names and identifiers, and add
// any additional names or identifiers that don't have a corresponding pair.
var sortedNames = requires.map(function(item) {
return item.name;
});
for (i = sortedNames.length; i < names.length; ++i) {
sortedNames.push(names[i].trim());
}
var sortedIdentifiers = requires.map(function(item) {
return item.identifier;
});
for (i = sortedIdentifiers.length; i < identifiers.length; ++i) {
sortedIdentifiers.push(identifiers[i].trim());
}
var outputNames = ']';
if (sortedNames.length > 0) {
outputNames = os.EOL + ' ' +
sortedNames.join(',' + os.EOL + ' ') +
os.EOL + ' ]';
}
var outputIdentifiers = '(';
if (sortedIdentifiers.length > 0) {
outputIdentifiers = '(' + os.EOL + ' ' +
sortedIdentifiers.join(',' + os.EOL + ' ');
}
contents = result[1] +
outputNames +
result[4].replace(/^[,\s]+/, ', ').trim() +
outputIdentifiers +
') {' +
result[6];
return fsWriteFile(file, contents);
});
});
});
function combineCesium(debug, optimizer, combineOutput) {
return requirejsOptimize('Cesium.js', {
wrap : true,
useStrict : true,
optimize : optimizer,
optimizeCss : 'standard',
pragmas : {
debug : debug
},
baseUrl : 'Source',
skipModuleInsertion : true,
name : removeExtension(path.relative('Source', require.resolve('almond'))),
include : 'main',
out : path.join(combineOutput, 'Cesium.js')
});
}
function combineWorkers(debug, optimizer, combineOutput) {
//This is done waterfall style for concurrency reasons.
return globby(['Source/Workers/cesiumWorkerBootstrapper.js',
'Source/Workers/transferTypedArrayTest.js',
'Source/ThirdParty/Workers/*.js'])
.then(function(files) {
return Promise.map(files, function(file) {
return requirejsOptimize(file, {
wrap : false,
useStrict : true,
optimize : optimizer,
optimizeCss : 'standard',
pragmas : {
debug : debug
},
baseUrl : 'Source',
skipModuleInsertion : true,
include : filePathToModuleId(path.relative('Source', file)),
out : path.join(combineOutput, path.relative('Source', file))
});
}, {concurrency : concurrency});
})
.then(function() {
return globby(['Source/Workers/*.js',
'!Source/Workers/cesiumWorkerBootstrapper.js',
'!Source/Workers/transferTypedArrayTest.js',
'!Source/Workers/createTaskProcessorWorker.js',
'!Source/ThirdParty/Workers/*.js']);
})
.then(function(files) {
return Promise.map(files, function(file) {
return requirejsOptimize(file, {
wrap : true,
useStrict : true,
optimize : optimizer,
optimizeCss : 'standard',
pragmas : {
debug : debug
},
baseUrl : 'Source',
include : filePathToModuleId(path.relative('Source', file)),
out : path.join(combineOutput, path.relative('Source', file))
});
}, {concurrency : concurrency});
});
}
function minifyCSS(outputDirectory) {
return globby('Source/**/*.css').then(function(files) {
return Promise.map(files, function(file) {
return requirejsOptimize(file, {
wrap : true,
useStrict : true,
optimizeCss : 'standard',
pragmas : {
debug : true
},
cssIn : file,
out : path.join(outputDirectory, path.relative('Source', file))
});
}, {concurrency : concurrency});
});
}
function combineJavaScript(options) {
var optimizer = options.optimizer;
var outputDirectory = options.outputDirectory;
var removePragmas = options.removePragmas;
var combineOutput = path.join('Build', 'combineOutput', optimizer);
var copyrightHeader = fs.readFileSync(path.join('Source', 'copyrightHeader.js'));
var promise = Promise.join(
combineCesium(!removePragmas, optimizer, combineOutput),
combineWorkers(!removePragmas, optimizer, combineOutput)
);
return promise.then(function() {
var promises = [];
//copy to build folder with copyright header added at the top
var stream = gulp.src([combineOutput + '/**'])
.pipe(gulpInsert.prepend(copyrightHeader))
.pipe(gulp.dest(outputDirectory));
promises.push(streamToPromise(stream));
var everythingElse = ['Source/**', '!**/*.js', '!**/*.glsl'];
if (optimizer === 'uglify2') {
promises.push(minifyCSS(outputDirectory));
everythingElse.push('!**/*.css');
}
stream = gulp.src(everythingElse, {nodir : true}).pipe(gulp.dest(outputDirectory));
promises.push(streamToPromise(stream));
return Promise.all(promises).then(function() {
rimraf.sync(combineOutput);
});
});
}
function glslToJavaScript(minify, minifyStateFilePath) {
fs.writeFileSync(minifyStateFilePath, minify);
var minifyStateFileLastModified = fs.existsSync(minifyStateFilePath) ? fs.statSync(minifyStateFilePath).mtime.getTime() : 0;
// collect all currently existing JS files into a set, later we will remove the ones
// we still are using from the set, then delete any files remaining in the set.
var leftOverJsFiles = {};
globby.sync(['Source/Shaders/**/*.js', 'Source/ThirdParty/Shaders/*.js']).forEach(function(file) {
leftOverJsFiles[path.normalize(file)] = true;
});
var builtinFunctions = [];
var builtinConstants = [];
var builtinStructs = [];
var glslFiles = globby.sync(['Source/Shaders/**/*.glsl', 'Source/ThirdParty/Shaders/*.glsl']);
glslFiles.forEach(function(glslFile) {
glslFile = path.normalize(glslFile);
var baseName = path.basename(glslFile, '.glsl');
var jsFile = path.join(path.dirname(glslFile), baseName) + '.js';
// identify built in functions, structs, and constants
var baseDir = path.join('Source', 'Shaders', 'Builtin');
if (glslFile.indexOf(path.normalize(path.join(baseDir, 'Functions'))) === 0) {
builtinFunctions.push(baseName);
}
else if (glslFile.indexOf(path.normalize(path.join(baseDir, 'Constants'))) === 0) {
builtinConstants.push(baseName);
}
else if (glslFile.indexOf(path.normalize(path.join(baseDir, 'Structs'))) === 0) {
builtinStructs.push(baseName);
}
delete leftOverJsFiles[jsFile];
var jsFileExists = fs.existsSync(jsFile);
var jsFileModified = jsFileExists ? fs.statSync(jsFile).mtime.getTime() : 0;
var glslFileModified = fs.statSync(glslFile).mtime.getTime();
if (jsFileExists && jsFileModified > glslFileModified && jsFileModified > minifyStateFileLastModified) {
return;
}
var contents = fs.readFileSync(glslFile, 'utf8');
contents = contents.replace(/\r\n/gm, '\n');
var copyrightComments = '';
var extractedCopyrightComments = contents.match(/\/\*\*(?:[^*\/]|\*(?!\/)|\n)*?@license(?:.|\n)*?\*\//gm);
if (extractedCopyrightComments) {
copyrightComments = extractedCopyrightComments.join('\n') + '\n';
}
if (minify) {
contents = glslStripComments(contents);
contents = contents.replace(/\s+$/gm, '').replace(/^\s+/gm, '').replace(/\n+/gm, '\n');
contents += '\n';
}
contents = contents.split('"').join('\\"').replace(/\n/gm, '\\n\\\n');
contents = copyrightComments + '\
//This file is automatically rebuilt by the Cesium build process.\n\
define(function() {\n\
\'use strict\';\n\
return "' + contents + '";\n\
});';
fs.writeFileSync(jsFile, contents);
});
// delete any left over JS files from old shaders
Object.keys(leftOverJsFiles).forEach(function(filepath) {
rimraf.sync(filepath);
});
var generateBuiltinContents = function(contents, builtins, path) {
var amdPath = contents.amdPath;
var amdClassName = contents.amdClassName;
var builtinLookup = contents.builtinLookup;
for (var i = 0; i < builtins.length; i++) {
var builtin = builtins[i];
amdPath = amdPath + ',\n \'./' + path + '/' + builtin + '\'';
amdClassName = amdClassName + ',\n ' + 'czm_' + builtin;
builtinLookup = builtinLookup + ',\n ' + 'czm_' + builtin + ' : ' + 'czm_' + builtin;
}
contents.amdPath = amdPath;
contents.amdClassName = amdClassName;
contents.builtinLookup = builtinLookup;
};
//generate the JS file for Built-in GLSL Functions, Structs, and Constants
var contents = {amdPath : '', amdClassName : '', builtinLookup : ''};
generateBuiltinContents(contents, builtinConstants, 'Constants');
generateBuiltinContents(contents, builtinStructs, 'Structs');
generateBuiltinContents(contents, builtinFunctions, 'Functions');
contents.amdPath = contents.amdPath.replace(',\n', '');
contents.amdClassName = contents.amdClassName.replace(',\n', '');
contents.builtinLookup = contents.builtinLookup.replace(',\n', '');
var fileContents = '\
//This file is automatically rebuilt by the Cesium build process.\n\
define([\n' +
contents.amdPath +
'\n ], function(\n' +
contents.amdClassName +
') {\n\
\'use strict\';\n\
return {\n' + contents.builtinLookup + '};\n\
});';
fs.writeFileSync(path.join('Source', 'Shaders', 'Builtin', 'CzmBuiltins.js'), fileContents);
}
function createCesiumJs() {
var moduleIds = [];
var parameters = [];
var assignments = [];
var nonIdentifierRegexp = /[^0-9a-zA-Z_$]/g;
globby.sync(sourceFiles).forEach(function(file) {
file = path.relative('Source', file);
var moduleId = file;
moduleId = filePathToModuleId(moduleId);
var assignmentName = "['" + path.basename(file, path.extname(file)) + "']";
if (moduleId.indexOf('Shaders/') === 0) {
assignmentName = '._shaders' + assignmentName;
}
var parameterName = moduleId.replace(nonIdentifierRegexp, '_');
moduleIds.push("'./" + moduleId + "'");
parameters.push(parameterName);
assignments.push('Cesium' + assignmentName + ' = ' + parameterName + ';');
});
var contents = '\
define([' + moduleIds.join(', ') + '], function(' + parameters.join(', ') + ') {\n\
\'use strict\';\n\
var Cesium = {\n\
VERSION : \'' + version + '\',\n\
_shaders : {}\n\
};\n\
' + assignments.join('\n ') + '\n\
return Cesium;\n\
});';
fs.writeFileSync('Source/Cesium.js', contents);
}
function createSpecList() {
var specFiles = globby.sync(['Specs/**/*.js', '!Specs/*.js']);
var specs = [];
specFiles.forEach(function(file) {
specs.push("'" + filePathToModuleId(file) + "'");
});
var contents = '/*eslint-disable no-unused-vars*/\n/*eslint-disable no-implicit-globals*/\nvar specs = [' + specs.join(',') + '];';
fs.writeFileSync(path.join('Specs', 'SpecList.js'), contents);
}
function createGalleryList() {
var demoObjects = [];
var demoJSONs = [];
var output = path.join('Apps', 'Sandcastle', 'gallery', 'gallery-index.js');
var fileList = ['Apps/Sandcastle/gallery/**/*.html'];
if (noDevelopmentGallery) {
fileList.push('!Apps/Sandcastle/gallery/development/**/*.html');
}
var helloWorld;
globby.sync(fileList).forEach(function(file) {
var demo = filePathToModuleId(path.relative('Apps/Sandcastle/gallery', file));
var demoObject = {
name : demo,
date : fs.statSync(file).mtime.getTime()
};
if (fs.existsSync(file.replace('.html', '') + '.jpg')) {
demoObject.img = demo + '.jpg';
}
demoObjects.push(demoObject);
if (demo === 'Hello World') {
helloWorld = demoObject;
}
});
demoObjects.sort(function(a, b) {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
}
return 0;
});
var helloWorldIndex = Math.max(demoObjects.indexOf(helloWorld), 0);
var i;
for (i = 0; i < demoObjects.length; ++i) {
demoJSONs[i] = JSON.stringify(demoObjects[i], null, 2);
}
var contents = '\
// This file is automatically rebuilt by the Cesium build process.\n\
var hello_world_index = ' + helloWorldIndex + ';\n\
var gallery_demos = [' + demoJSONs.join(', ') + '];';
fs.writeFileSync(output, contents);
}
function createJsHintOptions() {
var primary = JSON.parse(fs.readFileSync(path.join('Apps', '.jshintrc'), 'utf8'));
var gallery = JSON.parse(fs.readFileSync(path.join('Apps', 'Sandcastle', '.jshintrc'), 'utf8'));
primary.jasmine = false;
primary.predef = gallery.predef;
primary.unused = gallery.unused;
var contents = '\
// This file is automatically rebuilt by the Cesium build process.\n\
var sandcastleJsHintOptions = ' + JSON.stringify(primary, null, 4) + ';';
fs.writeFileSync(path.join('Apps', 'Sandcastle', 'jsHintOptions.js'), contents);
}
function buildSandcastle() {
return gulp.src([
'Apps/Sandcastle/**'
])
// Replace require Source with pre-built Cesium
.pipe(gulpReplace('../../../ThirdParty/requirejs-2.1.20/require.js', '../../../CesiumUnminified/Cesium.js'))
// Use unminified cesium instead of source
.pipe(gulpReplace('Source/Cesium', 'CesiumUnminified'))
// Fix relative paths for new location
.pipe(gulpReplace('../../Source', '../../../Source'))
.pipe(gulpReplace('../../ThirdParty', '../../../ThirdParty'))
.pipe(gulpReplace('../../SampleData', '../../../../Apps/SampleData'))
.pipe(gulpReplace('Build/Documentation', 'Documentation'))
.pipe(gulp.dest('Build/Apps/Sandcastle'));
}
function buildCesiumViewer() {
var cesiumViewerOutputDirectory = 'Build/Apps/CesiumViewer';
var cesiumViewerStartup = path.join(cesiumViewerOutputDirectory, 'CesiumViewerStartup.js');
var cesiumViewerCss = path.join(cesiumViewerOutputDirectory, 'CesiumViewer.css');
mkdirp.sync(cesiumViewerOutputDirectory);
var promise = Promise.join(
requirejsOptimize('CesiumViewer', {
wrap : true,
useStrict : true,
optimizeCss : 'standard',
pragmas : {
debug : false
},
optimize : 'uglify2',
mainConfigFile : 'Apps/CesiumViewer/CesiumViewerStartup.js',
name : 'CesiumViewerStartup',
out : cesiumViewerStartup
}),
requirejsOptimize('CesiumViewer CSS', {
wrap : true,
useStrict : true,
optimizeCss : 'standard',
pragmas : {
debug : false
},
cssIn : 'Apps/CesiumViewer/CesiumViewer.css',
out : cesiumViewerCss
})
);
promise = promise.then(function() {
var copyrightHeader = fs.readFileSync(path.join('Source', 'copyrightHeader.js'));
var stream = eventStream.merge(
gulp.src(cesiumViewerStartup)
.pipe(gulpInsert.prepend(copyrightHeader))
.pipe(gulpReplace('../../Source', '.'))
.pipe(gulpReplace('../../ThirdParty/requirejs-2.1.20', '.')),
gulp.src(cesiumViewerCss)
.pipe(gulpReplace('../../Source', '.')),
gulp.src(['Apps/CesiumViewer/index.html'])
.pipe(gulpReplace('../../ThirdParty/requirejs-2.1.20', '.')),
gulp.src(['Apps/CesiumViewer/**',
'!Apps/CesiumViewer/index.html',
'!Apps/CesiumViewer/**/*.js',
'!Apps/CesiumViewer/**/*.css']),
gulp.src(['ThirdParty/requirejs-2.1.20/require.min.js'])
.pipe(gulpRename('require.js')),
gulp.src(['Build/Cesium/Assets/**',
'Build/Cesium/Workers/**',
'Build/Cesium/ThirdParty/Workers/**',
'Build/Cesium/Widgets/**',
'!Build/Cesium/Widgets/**/*.css'],
{
base : 'Build/Cesium',
nodir : true
}),
gulp.src(['Build/Cesium/Widgets/InfoBox/InfoBoxDescription.css'], {
base : 'Build/Cesium'
}),
gulp.src(['web.config'])
);
return streamToPromise(stream.pipe(gulp.dest(cesiumViewerOutputDirectory)));
});
return promise;
}
function filePathToModuleId(moduleId) {
return moduleId.substring(0, moduleId.lastIndexOf('.')).replace(/\\/g, '/');
}
function removeExtension(p) {
return p.slice(0, -path.extname(p).length);
}
function requirejsOptimize(name, config) {
console.log('Building ' + name);
return new Promise(function(resolve, reject) {
var cmd = 'npm run requirejs -- --' + new Buffer(JSON.stringify(config)).toString('base64') + ' --silent';
child_process.exec(cmd, function(e) {
if (e) {
console.log('Error ' + name);
reject(e);
return;
}
console.log('Finished ' + name);
resolve();
});
});
}
function streamToPromise(stream) {
return new Promise(function(resolve, reject) {
stream.on('finish', resolve);
stream.on('end', resolve);
stream.on('error', reject);
});
}
| Copy images correctly
| gulpfile.js | Copy images correctly | <ide><path>ulpfile.js
<ide> }
<ide>
<ide> function buildSandcastle() {
<del> return gulp.src([
<del> 'Apps/Sandcastle/**'
<del> ])
<del> // Replace require Source with pre-built Cesium
<del> .pipe(gulpReplace('../../../ThirdParty/requirejs-2.1.20/require.js', '../../../CesiumUnminified/Cesium.js'))
<del> // Use unminified cesium instead of source
<del> .pipe(gulpReplace('Source/Cesium', 'CesiumUnminified'))
<del> // Fix relative paths for new location
<del> .pipe(gulpReplace('../../Source', '../../../Source'))
<del> .pipe(gulpReplace('../../ThirdParty', '../../../ThirdParty'))
<del> .pipe(gulpReplace('../../SampleData', '../../../../Apps/SampleData'))
<del> .pipe(gulpReplace('Build/Documentation', 'Documentation'))
<del> .pipe(gulp.dest('Build/Apps/Sandcastle'));
<add> var appStream = gulp.src([
<add> 'Apps/Sandcastle/**',
<add> '!Apps/Sandcastle/images/**',
<add> '!Apps/Sandcastle/gallery/**.jpg'
<add> ])
<add> // Replace require Source with pre-built Cesium
<add> .pipe(gulpReplace('../../../ThirdParty/requirejs-2.1.20/require.js', '../../../CesiumUnminified/Cesium.js'))
<add> // Use unminified cesium instead of source
<add> .pipe(gulpReplace('Source/Cesium', 'CesiumUnminified'))
<add> // Fix relative paths for new location
<add> .pipe(gulpReplace('../../Source', '../../../Source'))
<add> .pipe(gulpReplace('../../ThirdParty', '../../../ThirdParty'))
<add> .pipe(gulpReplace('../../SampleData', '../../../../Apps/SampleData'))
<add> .pipe(gulpReplace('Build/Documentation', 'Documentation'))
<add> .pipe(gulp.dest('Build/Apps/Sandcastle'));
<add>
<add> var imageStream = gulp.src([
<add> 'Apps/Sandcastle/gallery/**.jpg',
<add> 'Apps/Sandcastle/images/**'
<add> ], {
<add> base: 'Apps/Sandcastle',
<add> buffer: false
<add> })
<add> .pipe(gulp.dest('Build/Apps/Sandcastle'));
<add>
<add> return eventStream.merge(appStream, imageStream);
<ide> }
<ide>
<ide> function buildCesiumViewer() { |
|
Java | apache-2.0 | e901894996f7e25e8811b7ce0497cc30b22b4c56 | 0 | pkcool/qalingo-engine,qalingo/qalingo-engine,cloudbearings/qalingo-engine | /**
* Most of the code in the Qalingo project is copyrighted Hoteia and licensed
* under the Apache License Version 2.0 (release version 0.8.0)
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Hoteia, 2012-2014
* http://www.hoteia.com - http://twitter.com/hoteia - [email protected]
*
*/
package org.hoteia.qalingo.web.mvc.controller.common;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hoteia.qalingo.core.ModelConstants;
import org.hoteia.qalingo.core.domain.MarketArea;
import org.hoteia.qalingo.core.domain.Store;
import org.hoteia.qalingo.core.domain.Store_;
import org.hoteia.qalingo.core.domain.bean.GeolocData;
import org.hoteia.qalingo.core.domain.bean.GeolocatedStore;
import org.hoteia.qalingo.core.domain.enumtype.FoUrls;
import org.hoteia.qalingo.core.fetchplan.FetchPlan;
import org.hoteia.qalingo.core.fetchplan.SpecificFetchMode;
import org.hoteia.qalingo.core.i18n.enumtype.ScopeWebMessage;
import org.hoteia.qalingo.core.pojo.RequestData;
import org.hoteia.qalingo.core.service.RetailerService;
import org.hoteia.qalingo.core.web.mvc.viewbean.BreadcrumbViewBean;
import org.hoteia.qalingo.core.web.mvc.viewbean.MenuViewBean;
import org.hoteia.qalingo.core.web.mvc.viewbean.StoreLocatorCountryFilterBean;
import org.hoteia.qalingo.core.web.mvc.viewbean.StoreLocatorFilterBean;
import org.hoteia.qalingo.core.web.mvc.viewbean.StoreViewBean;
import org.hoteia.qalingo.core.web.servlet.ModelAndViewThemeDevice;
import org.hoteia.qalingo.web.mvc.controller.AbstractMCommerceController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
*
*/
@Controller("storeLocationController")
public class StoreLocationController extends AbstractMCommerceController {
@Autowired
protected RetailerService retailerService;
protected List<SpecificFetchMode> storeFetchPlans = new ArrayList<SpecificFetchMode>();;
public StoreLocationController() {
storeFetchPlans.add(new SpecificFetchMode(Store_.attributes.getName()));
storeFetchPlans.add(new SpecificFetchMode(Store_.assets.getName()));
}
@RequestMapping(FoUrls.STORE_LOCATION_URL)
public ModelAndView storeLocation(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
ModelAndViewThemeDevice modelAndView = new ModelAndViewThemeDevice(getCurrentVelocityPath(request), FoUrls.STORE_LOCATION.getVelocityPage());
final RequestData requestData = requestUtil.getRequestData(request);
final MarketArea marketArea = requestData.getMarketArea();
final Locale locale = requestData.getLocale();
final GeolocData geolocData = requestData.getGeolocData();
ObjectMapper mapper = new ObjectMapper();
List<StoreLocatorCountryFilterBean> countries = new ArrayList<StoreLocatorCountryFilterBean>();
if(geolocData != null){
String distance = getDistance();
List<Store> stores = new ArrayList<Store>();
final List<GeolocatedStore> geolocatedStores = retailerService.findStoresByGeolocAndCountry(marketArea.getGeolocCountryCode(), geolocData.getLatitude(), geolocData.getLongitude(), distance, 100);
if(geolocatedStores != null){
for (Iterator<GeolocatedStore> iterator = geolocatedStores.iterator(); iterator.hasNext();) {
GeolocatedStore geolocatedStore = (GeolocatedStore) iterator.next();
Store store = retailerService.getStoreById(geolocatedStore.getId(), new FetchPlan(storeFetchPlans));
stores.add(store);
}
} else {
// TRY FIRST LONG DISTANCE
Integer newDistance = Integer.parseInt(distance) * 2;
geolocatedStores = retailerService.findStoresByGeolocAndCountry(marketArea.getGeolocCountryCode(), geolocData.getLatitude(), geolocData.getLongitude(), newDistance.toString(), 100);
if(geolocatedStores != null){
for (Iterator<GeolocatedStore> iterator = geolocatedStores.iterator(); iterator.hasNext();) {
GeolocatedStore geolocatedStore = (GeolocatedStore) iterator.next();
Store store = retailerService.getStoreById(geolocatedStore.getId(), new FetchPlan(storeFetchPlans));
stores.add(store);
}
} else {
// TRY SECOND LONG DISTANCE
newDistance = newDistance * 2;
geolocatedStores = retailerService.findStoresByGeolocAndCountry(marketArea.getGeolocCountryCode(), geolocData.getLatitude(), geolocData.getLongitude(), newDistance.toString(), 100);
if(geolocatedStores != null){
for (Iterator<GeolocatedStore> iterator = geolocatedStores.iterator(); iterator.hasNext();) {
GeolocatedStore geolocatedStore = (GeolocatedStore) iterator.next();
Store store = retailerService.getStoreById(geolocatedStore.getId(), new FetchPlan(storeFetchPlans));
stores.add(store);
}
} else {
// TODO : ERROR MESSAGE IN IHM
}
}
}
if(stores != null){
final List<StoreViewBean> storeViewBeans = frontofficeViewBeanFactory.buildListViewBeanStore(requestUtil.getRequestData(request), stores);
modelAndView.addObject("stores", storeViewBeans);
final StoreLocatorFilterBean storeFilter = frontofficeViewBeanFactory.buildFilterBeanStoreLocator(storeViewBeans, locale);
countries = storeFilter.getCountries();
}
modelAndView.addObject("storeSearchUrl", urlService.generateUrl(FoUrls.STORE_SEARCH, requestData));
overrideDefaultMainContentTitle(request, modelAndView, FoUrls.STORE_LOCATION.getKey());
modelAndView.addObject(ModelConstants.BREADCRUMB_VIEW_BEAN, buildBreadcrumbViewBean(requestData));
}
try {
modelAndView.addObject("jsonStores", mapper.writeValueAsString(countries));
} catch (JsonProcessingException e) {
logger.warn(e.getMessage(), e);
}
return modelAndView;
}
protected String getDistance() {
return "50";
}
protected BreadcrumbViewBean buildBreadcrumbViewBean(final RequestData requestData){
final Locale locale = requestData.getLocale();
// BREADCRUMB
BreadcrumbViewBean breadcrumbViewBean = new BreadcrumbViewBean();
breadcrumbViewBean.setName(getSpecificMessage(ScopeWebMessage.HEADER_TITLE, FoUrls.STORE_LOCATION.getMessageKey(), locale));
List<MenuViewBean> menuViewBeans = breadcrumbViewBean.getMenus();
MenuViewBean menu = new MenuViewBean();
menu.setKey(FoUrls.HOME.getKey());
menu.setName(getSpecificMessage(ScopeWebMessage.HEADER_MENU, FoUrls.HOME.getMessageKey(), locale));
menu.setUrl(urlService.generateUrl(FoUrls.HOME, requestData));
menuViewBeans.add(menu);
menu = new MenuViewBean();
menu.setKey(FoUrls.STORE_LOCATION.getKey());
menu.setName(getSpecificMessage(ScopeWebMessage.HEADER_MENU, FoUrls.STORE_LOCATION.getMessageKey(), locale));
menu.setUrl(urlService.generateUrl(FoUrls.STORE_LOCATION, requestData));
menu.setActive(true);
menuViewBeans.add(menu);
breadcrumbViewBean.setMenus(menuViewBeans);
return breadcrumbViewBean;
}
} | apis/api-web/api-web-fo-mcommerce/src/main/java/org/hoteia/qalingo/web/mvc/controller/common/StoreLocationController.java | /**
* Most of the code in the Qalingo project is copyrighted Hoteia and licensed
* under the Apache License Version 2.0 (release version 0.8.0)
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Hoteia, 2012-2014
* http://www.hoteia.com - http://twitter.com/hoteia - [email protected]
*
*/
package org.hoteia.qalingo.web.mvc.controller.common;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hoteia.qalingo.core.ModelConstants;
import org.hoteia.qalingo.core.domain.MarketArea;
import org.hoteia.qalingo.core.domain.Store;
import org.hoteia.qalingo.core.domain.Store_;
import org.hoteia.qalingo.core.domain.bean.GeolocData;
import org.hoteia.qalingo.core.domain.bean.GeolocatedStore;
import org.hoteia.qalingo.core.domain.enumtype.FoUrls;
import org.hoteia.qalingo.core.fetchplan.FetchPlan;
import org.hoteia.qalingo.core.fetchplan.SpecificFetchMode;
import org.hoteia.qalingo.core.i18n.enumtype.ScopeWebMessage;
import org.hoteia.qalingo.core.pojo.RequestData;
import org.hoteia.qalingo.core.service.RetailerService;
import org.hoteia.qalingo.core.web.mvc.viewbean.BreadcrumbViewBean;
import org.hoteia.qalingo.core.web.mvc.viewbean.MenuViewBean;
import org.hoteia.qalingo.core.web.mvc.viewbean.StoreLocatorCountryFilterBean;
import org.hoteia.qalingo.core.web.mvc.viewbean.StoreLocatorFilterBean;
import org.hoteia.qalingo.core.web.mvc.viewbean.StoreViewBean;
import org.hoteia.qalingo.core.web.servlet.ModelAndViewThemeDevice;
import org.hoteia.qalingo.web.mvc.controller.AbstractMCommerceController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
*
*/
@Controller("storeLocationController")
public class StoreLocationController extends AbstractMCommerceController {
@Autowired
protected RetailerService retailerService;
protected List<SpecificFetchMode> storeFetchPlans = new ArrayList<SpecificFetchMode>();;
public StoreLocationController() {
storeFetchPlans.add(new SpecificFetchMode(Store_.attributes.getName()));
storeFetchPlans.add(new SpecificFetchMode(Store_.assets.getName()));
}
@RequestMapping(FoUrls.STORE_LOCATION_URL)
public ModelAndView storeLocation(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
ModelAndViewThemeDevice modelAndView = new ModelAndViewThemeDevice(getCurrentVelocityPath(request), FoUrls.STORE_LOCATION.getVelocityPage());
final RequestData requestData = requestUtil.getRequestData(request);
final MarketArea marketArea = requestData.getMarketArea();
final Locale locale = requestData.getLocale();
final GeolocData geolocData = requestData.getGeolocData();
ObjectMapper mapper = new ObjectMapper();
List<StoreLocatorCountryFilterBean> countries = new ArrayList<StoreLocatorCountryFilterBean>();
if(geolocData != null){
String distance = getDistance();
final List<GeolocatedStore> geolocatedStores = retailerService.findStoresByGeolocAndCountry(marketArea.getGeolocCountryCode(), geolocData.getLatitude(), geolocData.getLongitude(), distance, 100);
List<Store> stores = new ArrayList<Store>();
if(geolocatedStores != null){
for (Iterator<GeolocatedStore> iterator = geolocatedStores.iterator(); iterator.hasNext();) {
GeolocatedStore geolocatedStore = (GeolocatedStore) iterator.next();
Store store = retailerService.getStoreById(geolocatedStore.getId(), new FetchPlan(storeFetchPlans));
stores.add(store);
}
}
if(stores != null){
final List<StoreViewBean> storeViewBeans = frontofficeViewBeanFactory.buildListViewBeanStore(requestUtil.getRequestData(request), stores);
modelAndView.addObject("stores", storeViewBeans);
final StoreLocatorFilterBean storeFilter = frontofficeViewBeanFactory.buildFilterBeanStoreLocator(storeViewBeans, locale);
countries = storeFilter.getCountries();
}
modelAndView.addObject("storeSearchUrl", urlService.generateUrl(FoUrls.STORE_SEARCH, requestData));
overrideDefaultMainContentTitle(request, modelAndView, FoUrls.STORE_LOCATION.getKey());
modelAndView.addObject(ModelConstants.BREADCRUMB_VIEW_BEAN, buildBreadcrumbViewBean(requestData));
}
try {
modelAndView.addObject("jsonStores", mapper.writeValueAsString(countries));
} catch (JsonProcessingException e) {
logger.warn(e.getMessage(), e);
}
return modelAndView;
}
protected String getDistance() {
return "50";
}
protected BreadcrumbViewBean buildBreadcrumbViewBean(final RequestData requestData){
final Locale locale = requestData.getLocale();
// BREADCRUMB
BreadcrumbViewBean breadcrumbViewBean = new BreadcrumbViewBean();
breadcrumbViewBean.setName(getSpecificMessage(ScopeWebMessage.HEADER_TITLE, FoUrls.STORE_LOCATION.getMessageKey(), locale));
List<MenuViewBean> menuViewBeans = breadcrumbViewBean.getMenus();
MenuViewBean menu = new MenuViewBean();
menu.setKey(FoUrls.HOME.getKey());
menu.setName(getSpecificMessage(ScopeWebMessage.HEADER_MENU, FoUrls.HOME.getMessageKey(), locale));
menu.setUrl(urlService.generateUrl(FoUrls.HOME, requestData));
menuViewBeans.add(menu);
menu = new MenuViewBean();
menu.setKey(FoUrls.STORE_LOCATION.getKey());
menu.setName(getSpecificMessage(ScopeWebMessage.HEADER_MENU, FoUrls.STORE_LOCATION.getMessageKey(), locale));
menu.setUrl(urlService.generateUrl(FoUrls.STORE_LOCATION, requestData));
menu.setActive(true);
menuViewBeans.add(menu);
breadcrumbViewBean.setMenus(menuViewBeans);
return breadcrumbViewBean;
}
} | store locator | apis/api-web/api-web-fo-mcommerce/src/main/java/org/hoteia/qalingo/web/mvc/controller/common/StoreLocationController.java | store locator | <ide><path>pis/api-web/api-web-fo-mcommerce/src/main/java/org/hoteia/qalingo/web/mvc/controller/common/StoreLocationController.java
<ide> List<StoreLocatorCountryFilterBean> countries = new ArrayList<StoreLocatorCountryFilterBean>();
<ide> if(geolocData != null){
<ide> String distance = getDistance();
<add> List<Store> stores = new ArrayList<Store>();
<ide> final List<GeolocatedStore> geolocatedStores = retailerService.findStoresByGeolocAndCountry(marketArea.getGeolocCountryCode(), geolocData.getLatitude(), geolocData.getLongitude(), distance, 100);
<del> List<Store> stores = new ArrayList<Store>();
<ide> if(geolocatedStores != null){
<ide> for (Iterator<GeolocatedStore> iterator = geolocatedStores.iterator(); iterator.hasNext();) {
<ide> GeolocatedStore geolocatedStore = (GeolocatedStore) iterator.next();
<ide> Store store = retailerService.getStoreById(geolocatedStore.getId(), new FetchPlan(storeFetchPlans));
<ide> stores.add(store);
<add> }
<add> } else {
<add> // TRY FIRST LONG DISTANCE
<add> Integer newDistance = Integer.parseInt(distance) * 2;
<add> geolocatedStores = retailerService.findStoresByGeolocAndCountry(marketArea.getGeolocCountryCode(), geolocData.getLatitude(), geolocData.getLongitude(), newDistance.toString(), 100);
<add> if(geolocatedStores != null){
<add> for (Iterator<GeolocatedStore> iterator = geolocatedStores.iterator(); iterator.hasNext();) {
<add> GeolocatedStore geolocatedStore = (GeolocatedStore) iterator.next();
<add> Store store = retailerService.getStoreById(geolocatedStore.getId(), new FetchPlan(storeFetchPlans));
<add> stores.add(store);
<add> }
<add> } else {
<add> // TRY SECOND LONG DISTANCE
<add> newDistance = newDistance * 2;
<add> geolocatedStores = retailerService.findStoresByGeolocAndCountry(marketArea.getGeolocCountryCode(), geolocData.getLatitude(), geolocData.getLongitude(), newDistance.toString(), 100);
<add> if(geolocatedStores != null){
<add> for (Iterator<GeolocatedStore> iterator = geolocatedStores.iterator(); iterator.hasNext();) {
<add> GeolocatedStore geolocatedStore = (GeolocatedStore) iterator.next();
<add> Store store = retailerService.getStoreById(geolocatedStore.getId(), new FetchPlan(storeFetchPlans));
<add> stores.add(store);
<add> }
<add> } else {
<add> // TODO : ERROR MESSAGE IN IHM
<add> }
<ide> }
<ide> }
<ide> if(stores != null){ |
|
Java | agpl-3.0 | 27768ecaadedfefe7512a94b6ff14a76c9b77e6d | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 834f83e8-2e60-11e5-9284-b827eb9e62be | hello.java | 834a17e6-2e60-11e5-9284-b827eb9e62be | 834f83e8-2e60-11e5-9284-b827eb9e62be | hello.java | 834f83e8-2e60-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>834a17e6-2e60-11e5-9284-b827eb9e62be
<add>834f83e8-2e60-11e5-9284-b827eb9e62be |
|
JavaScript | unlicense | 0fe44fce2916d4edefc7f54cd90b114c387511f8 | 0 | TransforMap/demo.transformap.co,TransforMap/demo.transformap.co,species/transfor-map,species/transfor-map,species/transfor-map,TransforMap/demo.transformap.co,TransforMap/transfor-map,species/transfor-map,TransforMap/transfor-map,TransforMap/transfor-map,TransforMap/transfor-map,TransforMap/demo.transformap.co | /* this part must be in global namespace */
// fetch taxonomy, containing all translations, and implicit affiliations
// taken from Wikipedia:JSON
var url = "taxonomy.json";
var taxonomy;
var http_request = new XMLHttpRequest();
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
var done = 4, ok = 200;
if (http_request.readyState === done && http_request.status === ok) {
taxonomy = JSON.parse(http_request.responseText);
}
};
http_request.send(null);
function initMap(defaultlayer,base_maps,overlay_maps) {
map = new L.Map('map', {
center: new L.LatLng(47.07, 15.43),
zoom: 13,
layers: defaultlayer,
});
var ctrl = new L.Control.Layers(base_maps,overlay_maps)
map.addControl(ctrl);
L.LatLngBounds.prototype.toOverpassBBoxString = function (){
var a = this._southWest,
b = this._northEast;
return [a.lat, a.lng, b.lat, b.lng].join(",");
}
var path_style = L.Path.prototype._updateStyle;
L.Path.prototype._updateStyle = function () {
path_style.apply(this);
for (k in this.options.svg) {
this._path.setAttribute(k, this.options.svg[k]);
}
}
return map;
}
function addSearch() {
map.addControl( new L.Control.Search({
url: 'http://nominatim.openstreetmap.org/search?format=json&q={s}',
jsonpParam: 'json_callback',
propertyName: 'display_name',
propertyLoc: ['lat','lon'],
circleLocation: false,
markerLocation: false,
autoType: false,
autoCollapse: false,
minLength: 2,
zoom:12
}) );
}
function addLocate() {
lc = L.control.locate({
position: 'topleft',
showPopup: false,
strings: {
title: "Jump to my location!"
}
}
).addTo(map);
}
function parseOverpassJSON(overpassJSON, callbackNode, callbackWay, callbackRelation) {
var nodes = {}, ways = {};
for (var i = 0; i < overpassJSON.elements.length; i++) {
var p = overpassJSON.elements[i];
switch (p.type) {
case 'node':
p.coordinates = [p.lon, p.lat];
p.geometry = {type: 'Point', coordinates: p.coordinates};
nodes[p.id] = p;
// p has type=node, id, lat, lon, tags={k:v}, coordinates=[lon,lat], geometry
if (typeof callbackNode === 'function') callbackNode(p);
break;
case 'way':
p.coordinates = p.nodes.map(function (id) {
return nodes[id].coordinates;
});
p.geometry = {type: 'LineString', coordinates: p.coordinates};
ways[p.id] = p;
// p has type=way, id, tags={k:v}, nodes=[id], coordinates=[[lon,lat]], geometry
if (typeof callbackWay === 'function') callbackWay(p);
break;
case 'relation':
p.members.map(function (mem) {
mem.obj = (mem.type == 'way' ? ways : nodes)[mem.ref];
});
// p has type=relaton, id, tags={k:v}, members=[{role, obj}]
if (typeof callbackRelation === 'function') callbackRelation(p);
break;
}
}
}
var marker_table = {};
function loadPoi() {
if (map.getZoom() < 12 ) {
return;
}
var iconsize = 24;
function fillPopup(tags,type,id) {
var r = $('<table>');
var tags_to_ignore = [ "name" , "ref", "needs" ];
for (key in tags) {
if ( tags_to_ignore.indexOf(key) >= 0) {
continue;
} else if ( key == 'website' || key == 'url' || key == 'contact:website' || key == 'contact:url') { //TODO: , facebook, …
var value = tags[key];
var teststr=/^http/; //http[s] is implicit here
if ( ! teststr.test(value) )
value = "http://" + value;
var htlink = '<a href="' + value + '">' + value + '</a>';
r.append($('<tr>').append($('<th>').text(key)).append($('<td>').append(htlink)));
} else if (key == 'wikipedia') { // wikipedia - TODO key="wikipedia:de"
var value = tags[key];
var begin = "";
var teststr=/^http/; //http[s] is implicit here
if ( ! teststr.test(value) )
begin = "https://wikipedia.org/wiki/";
var htlink = '<a href="' + begin + value + '">' + value + '</a>';
r.append($('<tr>').append($('<th>').text(key)).append($('<td>').append(htlink)));
} else if (key == 'contact:email' || key == 'email') {
var value = tags[key];
var teststr=/^mailto:/;
if ( ! teststr.test(value) )
value = "mailto:" + value;
var htlink = '<a href="' + value + '">' + tags[key] + '</a>';
r.append($('<tr>').append($('<th>').text(key)).append($('<td>').append(htlink)));
} else {
var keytext = key;
var valuetext = tags[key];
/* display label:* instead of key */
var found = 0; // use for break outer loops
for ( groupname in taxonomy ) { // e.g. "fulfils_needs" : {}=group
group = taxonomy[groupname];
var count_items = group["items"].length;
for (var i = 0; i < count_items; i++) { // loop over each item in group["items"]
item = group["items"][i];
if(item["osm:key"] == keytext) {
keytext = "<em>" + item.label["en"] + "</em>"; //<em> for displaying a translated value
found = 1;
break;
}
}
if(found == 1)
break; // for ( groupname in taxonomy )
}
r.append($('<tr>').append($('<th>').append(keytext)).append($('<td>').text(valuetext)));
}
} // end for (key in tags)
r.append($('<tr>').append($('<th>').append(" ")).append($('<td>').append(" "))); // spacer
r.append($('<tr>').append($('<th>').text("OSM-Type:")).append($('<td>').text(type)));
r.append($('<tr>').append($('<th>').text("OSM-ID:")).append($('<td>').append('<a href="https://www.openstreetmap.org/' + type + "/" + id + '">' + id + '</a>')));
var s = $('<div>');
s.append(r);
var retval = $('<div>').append(s);
retval.prepend($('<h1>').text(tags["name"]));
return retval.html();
}
function bindPopupOnData(data) {
// first: check if no item with this osm-id exists...
var hashtable_key = data.type + data.id; // e.g. "node1546484546"
if(marker_table[hashtable_key] == 1) //object already there
return;
marker_table[hashtable_key] = 1;
// set icon dependent on tags
data.tags.needs = "";
for (key in data.tags) {
if ( key.indexOf("fulfils_needs:") >= 0 ) {
needs_value = key.substring(14);
if ( data.tags.needs != "" )
data.tags.needs = data.tags.needs + "; ";
data.tags.needs = data.tags.needs + needs_value;
}
}
var icon_url = "";
if (data.tags.needs.indexOf(";") >= 0) // more than one item, take generic icon
icon_url = "assets/transformap/pngs/" + iconsize + "/fulfils_needs.png";
else
icon_url = "assets/transformap/pngs/" + iconsize + "/fulfils_needs." + data.tags.needs + ".png";
if ((data.tags.needs.split(";").length - 1 == 1) && (data.tags.needs.indexOf("beverages") >= 0) && (data.tags.needs.indexOf("food") >= 0 ) ) //only the two items beverages food share the same icon
icon_url = "assets/transformap/pngs/" + iconsize + "/fulfils_needs.food.png";
if(!data.tags.needs)
icon_url = "assets/transformap/pngs/" + iconsize + "/unknown.png";
var needs_icon = L.icon({
iconUrl: icon_url,
iconSize: new L.Point(iconsize, iconsize),
iconAnchor: new L.Point(iconsize / 2, iconsize / 2),
});
var lmarker = L.marker([data.lat, data.lon], {
icon: needs_icon,
title: data.tags.name
});
lmarker.bindPopup(fillPopup(data.tags,data.type,data.id));
markers.addLayer(lmarker);
}
function nodeFunction(data) {
if (! data.tags || ! data.tags.name || data.tags.entrance ) return;
bindPopupOnData(data);
}
function wayFunction(data) {
//calculate centre of polygon
var centroid = $.geo.centroid(data.geometry);
//var style = {};
centroid.tags = data.tags;
centroid.id = data.id;
centroid.type = data.type;
centroid.lon = centroid.coordinates[0];
centroid.lat = centroid.coordinates[1];
bindPopupOnData(centroid);
return;
};
function relationFunction(data) {
// calculate mean coordinates as center
// for all members, calculate centroid
// then calculate mean over all nodes and centroids.
var centroids = [];
var sum_lon = 0;
var sum_lat = 0;
//console.log(data);
for (var i = 0; i < data.members.length; i++) {
var p = data.members[i];
var centroid;
switch (p.type) {
case 'node':
centroid = p.obj.coordinates;
centroids.push(centroid);
break;
case 'way':
// fixme test with relations and way-members
var centroid_point = $.geo.centroid(p.obj.geometry);
centroid = centroid_point.coordinates;
entroids.push(centroid);
break;
}
sum_lon += centroid[0];
sum_lat += centroid[1];
}
//console.log(centroids);
var sum_centroid = {
id : data.id,
lon : sum_lon / data.members.length,
lat : sum_lat / data.members.length,
tags : data.tags,
type : data.type
}
//console.log(sum_centroid);
bindPopupOnData(sum_centroid);
// todo: in the long term, all areas should be displayed as areas (as in overpass turbo)
}
function handleNodeWayRelations(data) {
parseOverpassJSON(data, nodeFunction, wayFunction, relationFunction);
}
var query = overpass_query;
var allUrl = query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());
$.getJSON(allUrl, handleNodeWayRelations);
}
| map.js | /* this part must be in global namespace */
// fetch taxonomy, containing all translations, and implicit affiliations
// taken from Wikipedia:JSON
var url = "taxonomy.json";
var taxonomy;
var http_request = new XMLHttpRequest();
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
var done = 4, ok = 200;
if (http_request.readyState === done && http_request.status === ok) {
taxonomy = JSON.parse(http_request.responseText);
}
};
http_request.send(null);
function initMap(defaultlayer,base_maps,overlay_maps) {
map = new L.Map('map', {
center: new L.LatLng(47.07, 15.43),
zoom: 13,
layers: defaultlayer,
});
var ctrl = new L.Control.Layers(base_maps,overlay_maps)
map.addControl(ctrl);
L.LatLngBounds.prototype.toOverpassBBoxString = function (){
var a = this._southWest,
b = this._northEast;
return [a.lat, a.lng, b.lat, b.lng].join(",");
}
var path_style = L.Path.prototype._updateStyle;
L.Path.prototype._updateStyle = function () {
path_style.apply(this);
for (k in this.options.svg) {
this._path.setAttribute(k, this.options.svg[k]);
}
}
return map;
}
function addSearch() {
map.addControl( new L.Control.Search({
url: 'http://nominatim.openstreetmap.org/search?format=json&q={s}',
jsonpParam: 'json_callback',
propertyName: 'display_name',
propertyLoc: ['lat','lon'],
circleLocation: false,
markerLocation: false,
autoType: false,
autoCollapse: false,
minLength: 2,
zoom:12
}) );
}
function addLocate() {
lc = L.control.locate({
position: 'topleft',
showPopup: false,
strings: {
title: "Jump to my location!"
}
}
).addTo(map);
}
function parseOverpassJSON(overpassJSON, callbackNode, callbackWay, callbackRelation) {
var nodes = {}, ways = {};
for (var i = 0; i < overpassJSON.elements.length; i++) {
var p = overpassJSON.elements[i];
switch (p.type) {
case 'node':
p.coordinates = [p.lon, p.lat];
p.geometry = {type: 'Point', coordinates: p.coordinates};
nodes[p.id] = p;
// p has type=node, id, lat, lon, tags={k:v}, coordinates=[lon,lat], geometry
if (typeof callbackNode === 'function') callbackNode(p);
break;
case 'way':
p.coordinates = p.nodes.map(function (id) {
return nodes[id].coordinates;
});
p.geometry = {type: 'LineString', coordinates: p.coordinates};
ways[p.id] = p;
// p has type=way, id, tags={k:v}, nodes=[id], coordinates=[[lon,lat]], geometry
if (typeof callbackWay === 'function') callbackWay(p);
break;
case 'relation':
p.members.map(function (mem) {
mem.obj = (mem.type == 'way' ? ways : nodes)[mem.ref];
});
// p has type=relaton, id, tags={k:v}, members=[{role, obj}]
if (typeof callbackRelation === 'function') callbackRelation(p);
break;
}
}
}
var marker_table = {};
function loadPoi() {
if (map.getZoom() < 12 ) {
return;
}
var iconsize = 24;
function fillPopup(tags,type,id) {
var r = $('<table>');
var tags_to_ignore = [ "name" , "ref", "needs" ];
for (key in tags) {
if ( tags_to_ignore.indexOf(key) >= 0) {
continue;
} else if ( key == 'website' || key == 'url' || key == 'contact:website' || key == 'contact:url') { //TODO: , facebook, …
var value = tags[key];
var teststr=/^http/; //http[s] is implicit here
if ( ! teststr.test(value) )
value = "http://" + value;
var htlink = '<a href="' + value + '">' + value + '</a>';
r.append($('<tr>').append($('<th>').text(key)).append($('<td>').append(htlink)));
} else if (key == 'wikipedia') { // wikipedia - TODO key="wikipedia:de"
var value = tags[key];
var begin = "";
var teststr=/^http/; //http[s] is implicit here
if ( ! teststr.test(value) )
begin = "https://wikipedia.org/wiki/";
var htlink = '<a href="' + begin + value + '">' + value + '</a>';
r.append($('<tr>').append($('<th>').text(key)).append($('<td>').append(htlink)));
} else if (key == 'contact:email' || key == 'email') {
var value = tags[key];
var teststr=/^mailto:/;
if ( ! teststr.test(value) )
value = "mailto:" + value;
var htlink = '<a href="' + value + '">' + tags[key] + '</a>';
r.append($('<tr>').append($('<th>').text(key)).append($('<td>').append(htlink)));
} else {
var keytext = key;
var valuetext = tags[key];
/* display label:* instead of key */
var found = 0; // use for break outer loops
for ( groupname in taxonomy ) { // e.g. "fulfils_needs" : {}=group
group = taxonomy[groupname];
var count_items = group["items"].length;
for (var i = 0; i < count_items; i++) { // loop over each item in group["items"]
item = group["items"][i];
if(item["osm:key"] == keytext) {
keytext = "<em>" + item.label["en"] + "</em>"; //<em> for displaying a translated value
found = 1;
break;
}
}
if(found == 1)
break; // for ( groupname in taxonomy )
}
r.append($('<tr>').append($('<th>').append(keytext)).append($('<td>').text(valuetext)));
}
} // end for (key in tags)
r.append($('<tr>').append($('<th>').append(" ")).append($('<td>').append(" "))); // spacer
r.append($('<tr>').append($('<th>').text("OSM-Type:")).append($('<td>').text(type)));
r.append($('<tr>').append($('<th>').text("OSM-ID:")).append($('<td>').append('<a href="https://www.openstreetmap.org/' + type + "/" + id + '">' + id + '</a>')));
var s = $('<div>');
s.append(r);
var retval = $('<div>').append(s);
retval.prepend($('<h1>').text(tags["name"]));
return retval.html();
}
function bindPopupOnData(data) {
// first: check if no item with this osm-id exists...
var hashtable_key = data.type + data.id;
if(marker_table[hashtable_key] == 1) //object already there
return;
marker_table[hashtable_key] = 1;
// set icon dependent on tags
data.tags.needs = "";
for (key in data.tags) {
if ( key.indexOf("fulfils_needs:") >= 0 ) {
needs_value = key.substring(14);
if ( data.tags.needs != "" )
data.tags.needs = data.tags.needs + "; ";
data.tags.needs = data.tags.needs + needs_value;
}
}
var icon_url = "";
if (data.tags.needs.indexOf(";") >= 0) // more than one item, take generic icon
icon_url = "assets/transformap/pngs/" + iconsize + "/fulfils_needs.png";
else
icon_url = "assets/transformap/pngs/" + iconsize + "/fulfils_needs." + data.tags.needs + ".png";
if ((data.tags.needs.split(";").length - 1 == 1) && (data.tags.needs.indexOf("beverages") >= 0) && (data.tags.needs.indexOf("food") >= 0 ) ) //only the two items beverages food share the same icon
icon_url = "assets/transformap/pngs/" + iconsize + "/fulfils_needs.food.png";
if(!data.tags.needs)
icon_url = "assets/transformap/pngs/" + iconsize + "/unknown.png";
var needs_icon = L.icon({
iconUrl: icon_url,
iconSize: new L.Point(iconsize, iconsize),
iconAnchor: new L.Point(iconsize / 2, iconsize / 2),
});
var lmarker = L.marker([data.lat, data.lon], {
icon: needs_icon,
title: data.tags.name
});
lmarker.bindPopup(fillPopup(data.tags,data.type,data.id));
markers.addLayer(lmarker);
}
function nodeFunction(data) {
if (! data.tags || ! data.tags.name || data.tags.entrance ) return;
bindPopupOnData(data);
}
function wayFunction(data) {
//calculate centre of polygon
var centroid = $.geo.centroid(data.geometry);
//var style = {};
centroid.tags = data.tags;
centroid.id = data.id;
centroid.type = data.type;
centroid.lon = centroid.coordinates[0];
centroid.lat = centroid.coordinates[1];
bindPopupOnData(centroid);
return;
};
function relationFunction(data) {
// calculate mean coordinates as center
// for all members, calculate centroid
// then calculate mean over all nodes and centroids.
var centroids = [];
var sum_lon = 0;
var sum_lat = 0;
//console.log(data);
for (var i = 0; i < data.members.length; i++) {
var p = data.members[i];
var centroid;
switch (p.type) {
case 'node':
centroid = p.obj.coordinates;
centroids.push(centroid);
break;
case 'way':
// fixme test with relations and way-members
var centroid_point = $.geo.centroid(p.obj.geometry);
centroid = centroid_point.coordinates;
entroids.push(centroid);
break;
}
sum_lon += centroid[0];
sum_lat += centroid[1];
}
//console.log(centroids);
var sum_centroid = {
id : data.id,
lon : sum_lon / data.members.length,
lat : sum_lat / data.members.length,
tags : data.tags,
type : data.type
}
//console.log(sum_centroid);
bindPopupOnData(sum_centroid);
// todo: in the long term, all areas should be displayed as areas (as in overpass turbo)
}
function handleNodeWayRelations(data) {
parseOverpassJSON(data, nodeFunction, wayFunction, relationFunction);
}
var query = overpass_query;
var allUrl = query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());
$.getJSON(allUrl, handleNodeWayRelations);
}
| comment
| map.js | comment | <ide><path>ap.js
<ide>
<ide> function bindPopupOnData(data) {
<ide> // first: check if no item with this osm-id exists...
<del> var hashtable_key = data.type + data.id;
<add> var hashtable_key = data.type + data.id; // e.g. "node1546484546"
<ide> if(marker_table[hashtable_key] == 1) //object already there
<ide> return;
<ide> marker_table[hashtable_key] = 1; |
|
Java | apache-2.0 | e959e16d98f0329533e1ba6a6a175789c64aebc6 | 0 | hurricup/intellij-community,blademainer/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,izonder/intellij-community,holmes/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,signed/intellij-community,tmpgit/intellij-community,supersven/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,signed/intellij-community,petteyg/intellij-community,slisson/intellij-community,FHannes/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,clumsy/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,kdwink/intellij-community,ibinti/intellij-community,hurricup/intellij-community,apixandru/intellij-community,retomerz/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,semonte/intellij-community,adedayo/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,supersven/intellij-community,xfournet/intellij-community,da1z/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,jagguli/intellij-community,semonte/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,supersven/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,asedunov/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,signed/intellij-community,signed/intellij-community,kdwink/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,signed/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,supersven/intellij-community,da1z/intellij-community,fnouama/intellij-community,ryano144/intellij-community,asedunov/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,robovm/robovm-studio,apixandru/intellij-community,petteyg/intellij-community,dslomov/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,supersven/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,dslomov/intellij-community,petteyg/intellij-community,allotria/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,supersven/intellij-community,da1z/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,da1z/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,holmes/intellij-community,fitermay/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,allotria/intellij-community,fnouama/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,xfournet/intellij-community,FHannes/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,ryano144/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,hurricup/intellij-community,izonder/intellij-community,kool79/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,allotria/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,ibinti/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,signed/intellij-community,slisson/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,kool79/intellij-community,semonte/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,kool79/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,samthor/intellij-community,petteyg/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,robovm/robovm-studio,blademainer/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,retomerz/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,semonte/intellij-community,amith01994/intellij-community,clumsy/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,asedunov/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,izonder/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,caot/intellij-community,allotria/intellij-community,fnouama/intellij-community,fnouama/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,wreckJ/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,asedunov/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,dslomov/intellij-community,caot/intellij-community,ahb0327/intellij-community,semonte/intellij-community,da1z/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,robovm/robovm-studio,amith01994/intellij-community,slisson/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,ibinti/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,samthor/intellij-community,fitermay/intellij-community,fitermay/intellij-community,caot/intellij-community,samthor/intellij-community,signed/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,caot/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,asedunov/intellij-community,apixandru/intellij-community,semonte/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,fnouama/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,kool79/intellij-community,tmpgit/intellij-community,da1z/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,slisson/intellij-community,asedunov/intellij-community,ryano144/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,dslomov/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,tmpgit/intellij-community,caot/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,slisson/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,xfournet/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,FHannes/intellij-community,signed/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,kool79/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,allotria/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,signed/intellij-community,allotria/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,caot/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,signed/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,holmes/intellij-community,retomerz/intellij-community,ryano144/intellij-community,holmes/intellij-community,supersven/intellij-community,da1z/intellij-community,adedayo/intellij-community,semonte/intellij-community,caot/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,petteyg/intellij-community,kool79/intellij-community,ibinti/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,allotria/intellij-community,fnouama/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,supersven/intellij-community,retomerz/intellij-community,kdwink/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,caot/intellij-community,robovm/robovm-studio,kool79/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,kool79/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,retomerz/intellij-community,apixandru/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,supersven/intellij-community,allotria/intellij-community,signed/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,slisson/intellij-community,FHannes/intellij-community,caot/intellij-community,da1z/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,retomerz/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,kool79/intellij-community,holmes/intellij-community | /*
* Copyright 2000-2015 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.keymap.impl;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.keymap.ex.KeymapManagerEx;
import com.intellij.openapi.options.ExternalizableSchemeAdapter;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashMap;
import gnu.trove.THashMap;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.lang.reflect.Field;
import java.util.*;
/**
* @author Eugene Belyaev
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public class KeymapImpl extends ExternalizableSchemeAdapter implements Keymap {
private static final Logger LOG = Logger.getInstance("#com.intellij.keymap.KeymapImpl");
@NonNls private static final String KEY_MAP = "keymap";
@NonNls private static final String KEYBOARD_SHORTCUT = "keyboard-shortcut";
@NonNls private static final String KEYBOARD_GESTURE_SHORTCUT = "keyboard-gesture-shortcut";
@NonNls private static final String KEYBOARD_GESTURE_KEY = "keystroke";
@NonNls private static final String KEYBOARD_GESTURE_MODIFIER = "modifier";
@NonNls private static final String KEYSTROKE_ATTRIBUTE = "keystroke";
@NonNls private static final String FIRST_KEYSTROKE_ATTRIBUTE = "first-keystroke";
@NonNls private static final String SECOND_KEYSTROKE_ATTRIBUTE = "second-keystroke";
@NonNls private static final String ACTION = "action";
@NonNls private static final String VERSION_ATTRIBUTE = "version";
@NonNls private static final String PARENT_ATTRIBUTE = "parent";
@NonNls private static final String NAME_ATTRIBUTE = "name";
@NonNls private static final String ID_ATTRIBUTE = "id";
@NonNls private static final String MOUSE_SHORTCUT = "mouse-shortcut";
@NonNls private static final String SHIFT = "shift";
@NonNls private static final String CONTROL = "control";
@NonNls private static final String META = "meta";
@NonNls private static final String ALT = "alt";
@NonNls private static final String ALT_GRAPH = "altGraph";
@NonNls private static final String DOUBLE_CLICK = "doubleClick";
@NonNls private static final String VIRTUAL_KEY_PREFIX = "VK_";
@NonNls private static final String EDITOR_ACTION_PREFIX = "Editor";
private KeymapImpl myParent;
private boolean myCanModify = true;
private final Map<String, LinkedHashSet<Shortcut>> myActionId2ListOfShortcuts = new THashMap<String, LinkedHashSet<Shortcut>>();
/**
* Don't use this field directly! Use it only through <code>getKeystroke2ListOfIds</code>.
*/
private Map<KeyStroke, List<String>> myKeystroke2ListOfIds = null;
private Map<KeyboardModifierGestureShortcut, List<String>> myGesture2ListOfIds = null;
// TODO[vova,anton] it should be final member
/**
* Don't use this field directly! Use it only through <code>getMouseShortcut2ListOfIds</code>.
*/
private Map<MouseShortcut, List<String>> myMouseShortcut2ListOfIds = null;
// TODO[vova,anton] it should be final member
private static final Map<Integer, String> ourNamesForKeycodes;
private static final Shortcut[] ourEmptyShortcutsArray = new Shortcut[0];
private final List<Listener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private KeymapManagerEx myKeymapManager;
static {
ourNamesForKeycodes = new HashMap<Integer, String>();
try {
Field[] fields = KeyEvent.class.getDeclaredFields();
for (Field field : fields) {
String fieldName = field.getName();
if (fieldName.startsWith(VIRTUAL_KEY_PREFIX)) {
int keyCode = field.getInt(KeyEvent.class);
ourNamesForKeycodes.put(keyCode, fieldName.substring(3));
}
}
}
catch (Exception e) {
LOG.error(e);
}
}
@Override
public String getPresentableName() {
return getName();
}
public KeymapImpl deriveKeymap() {
if (canModify()) {
return copy();
}
else {
KeymapImpl newKeymap = new KeymapImpl();
newKeymap.myParent = this;
newKeymap.myName = null;
newKeymap.myCanModify = canModify();
return newKeymap;
}
}
@NotNull
public KeymapImpl copy() {
KeymapImpl newKeymap = new KeymapImpl();
newKeymap.myParent = myParent;
newKeymap.myName = myName;
newKeymap.myCanModify = canModify();
newKeymap.cleanShortcutsCache();
for (Map.Entry<String, LinkedHashSet<Shortcut>> entry : myActionId2ListOfShortcuts.entrySet()) {
newKeymap.myActionId2ListOfShortcuts.put(entry.getKey(), new LinkedHashSet<Shortcut>(entry.getValue()));
}
return newKeymap;
}
public boolean equals(Object object) {
if (!(object instanceof Keymap)) return false;
KeymapImpl secondKeymap = (KeymapImpl)object;
if (!Comparing.equal(myName, secondKeymap.myName)) return false;
if (myCanModify != secondKeymap.myCanModify) return false;
if (!Comparing.equal(myParent, secondKeymap.myParent)) return false;
if (!Comparing.equal(myActionId2ListOfShortcuts, secondKeymap.myActionId2ListOfShortcuts)) return false;
return true;
}
public int hashCode() {
int hashCode = 0;
if (myName != null) {
hashCode += myName.hashCode();
}
return hashCode;
}
@Override
public Keymap getParent() {
return myParent;
}
@Override
public boolean canModify() {
return myCanModify;
}
public void setCanModify(boolean val) {
myCanModify = val;
}
protected Shortcut[] getParentShortcuts(String actionId) {
return myParent.getShortcuts(actionId);
}
@Override
public void addShortcut(String actionId, Shortcut shortcut) {
addShortcutSilently(actionId, shortcut, true);
fireShortcutChanged(actionId);
}
private void addShortcutSilently(String actionId, Shortcut shortcut, final boolean checkParentShortcut) {
LinkedHashSet<Shortcut> list = myActionId2ListOfShortcuts.get(actionId);
if (list == null) {
list = new LinkedHashSet<Shortcut>();
myActionId2ListOfShortcuts.put(actionId, list);
Shortcut[] boundShortcuts = getBoundShortcuts(actionId);
if (boundShortcuts != null) {
ContainerUtil.addAll(list, boundShortcuts);
}
else if (myParent != null) {
ContainerUtil.addAll(list, getParentShortcuts(actionId));
}
}
list.add(shortcut);
if (checkParentShortcut && myParent != null && areShortcutsEqual(getParentShortcuts(actionId), getShortcuts(actionId))) {
myActionId2ListOfShortcuts.remove(actionId);
}
cleanShortcutsCache();
}
private void cleanShortcutsCache() {
myKeystroke2ListOfIds = null;
myMouseShortcut2ListOfIds = null;
}
@Override
public void removeAllActionShortcuts(String actionId) {
Shortcut[] allShortcuts = getShortcuts(actionId);
for (Shortcut shortcut : allShortcuts) {
removeShortcut(actionId, shortcut);
}
}
@Override
public void removeShortcut(String actionId, Shortcut toDelete) {
LinkedHashSet<Shortcut> list = myActionId2ListOfShortcuts.get(actionId);
if (list != null) {
Iterator<Shortcut> it = list.iterator();
while (it.hasNext()) {
Shortcut each = it.next();
if (toDelete.equals(each)) {
it.remove();
if ((myParent != null && areShortcutsEqual(getParentShortcuts(actionId), getShortcuts(actionId)))
|| (myParent == null && list.isEmpty())) {
myActionId2ListOfShortcuts.remove(actionId);
}
break;
}
}
}
else {
Shortcut[] inherited = getBoundShortcuts(actionId);
if (inherited == null && myParent != null) {
inherited = getParentShortcuts(actionId);
}
if (inherited != null) {
boolean affected = false;
LinkedHashSet<Shortcut> newShortcuts = new LinkedHashSet<Shortcut>(inherited.length);
for (Shortcut eachInherited : inherited) {
if (toDelete.equals(eachInherited)) {
// skip this one
affected = true;
}
else {
newShortcuts.add(eachInherited);
}
}
if (affected) {
myActionId2ListOfShortcuts.put(actionId, newShortcuts);
}
}
}
cleanShortcutsCache();
fireShortcutChanged(actionId);
}
private Map<KeyStroke, List<String>> getKeystroke2ListOfIds() {
if (myKeystroke2ListOfIds != null) return myKeystroke2ListOfIds;
myKeystroke2ListOfIds = new THashMap<KeyStroke, List<String>>();
for (String id : ContainerUtil.concat(myActionId2ListOfShortcuts.keySet(), getKeymapManager().getBoundActions())) {
addKeystrokesMap(id, myKeystroke2ListOfIds);
}
return myKeystroke2ListOfIds;
}
private Map<KeyboardModifierGestureShortcut, List<String>> getGesture2ListOfIds() {
if (myGesture2ListOfIds == null) {
myGesture2ListOfIds = new THashMap<KeyboardModifierGestureShortcut, List<String>>();
fillShortcut2ListOfIds(myGesture2ListOfIds, KeyboardModifierGestureShortcut.class);
}
return myGesture2ListOfIds;
}
private <T extends Shortcut>void fillShortcut2ListOfIds(final Map<T,List<String>> map, final Class<T> shortcutClass) {
for (String id : ContainerUtil.concat(myActionId2ListOfShortcuts.keySet(), getKeymapManager().getBoundActions())) {
addAction2ShortcutsMap(id, map, shortcutClass);
}
}
private Map<MouseShortcut, List<String>> getMouseShortcut2ListOfIds() {
if (myMouseShortcut2ListOfIds == null) {
myMouseShortcut2ListOfIds = new THashMap<MouseShortcut, List<String>>();
fillShortcut2ListOfIds(myMouseShortcut2ListOfIds, MouseShortcut.class);
}
return myMouseShortcut2ListOfIds;
}
private <T extends Shortcut>void addAction2ShortcutsMap(final String actionId, final Map<T, List<String>> strokesMap, final Class<T> shortcutClass) {
LinkedHashSet<Shortcut> listOfShortcuts = _getShortcuts(actionId);
for (Shortcut shortcut : listOfShortcuts) {
if (!shortcutClass.isAssignableFrom(shortcut.getClass())) {
continue;
}
@SuppressWarnings({"unchecked"})
T t = (T)shortcut;
List<String> listOfIds = strokesMap.get(t);
if (listOfIds == null) {
listOfIds = new ArrayList<String>();
strokesMap.put(t, listOfIds);
}
// action may have more that 1 shortcut with same first keystroke
if (!listOfIds.contains(actionId)) {
listOfIds.add(actionId);
}
}
}
private void addKeystrokesMap(final String actionId, final Map<KeyStroke, List<String>> strokesMap) {
LinkedHashSet<Shortcut> listOfShortcuts = _getShortcuts(actionId);
for (Shortcut shortcut : listOfShortcuts) {
if (!(shortcut instanceof KeyboardShortcut)) {
continue;
}
KeyStroke firstKeyStroke = ((KeyboardShortcut)shortcut).getFirstKeyStroke();
List<String> listOfIds = strokesMap.get(firstKeyStroke);
if (listOfIds == null) {
listOfIds = new ArrayList<String>();
strokesMap.put(firstKeyStroke, listOfIds);
}
// action may have more that 1 shortcut with same first keystroke
if (!listOfIds.contains(actionId)) {
listOfIds.add(actionId);
}
}
}
private LinkedHashSet<Shortcut> _getShortcuts(final String actionId) {
KeymapManagerEx keymapManager = getKeymapManager();
LinkedHashSet<Shortcut> listOfShortcuts = myActionId2ListOfShortcuts.get(actionId);
if (listOfShortcuts != null) {
return listOfShortcuts;
}
else {
listOfShortcuts = new LinkedHashSet<Shortcut>();
}
final String actionBinding = keymapManager.getActionBinding(actionId);
if (actionBinding != null) {
listOfShortcuts.addAll(_getShortcuts(actionBinding));
}
return listOfShortcuts;
}
protected String[] getParentActionIds(KeyStroke firstKeyStroke) {
return myParent.getActionIds(firstKeyStroke);
}
protected String[] getParentActionIds(KeyboardModifierGestureShortcut gesture) {
return myParent.getActionIds(gesture);
}
private String[] getActionIds(KeyboardModifierGestureShortcut shortcut) {
// first, get keystrokes from own map
final Map<KeyboardModifierGestureShortcut, List<String>> map = getGesture2ListOfIds();
List<String> list = new ArrayList<String>();
for (Map.Entry<KeyboardModifierGestureShortcut, List<String>> entry : map.entrySet()) {
if (shortcut.startsWith(entry.getKey())) {
list.addAll(entry.getValue());
}
}
if (myParent != null) {
String[] ids = getParentActionIds(shortcut);
if (ids.length > 0) {
for (String id : ids) {
// add actions from parent keymap only if they are absent in this keymap
if (!myActionId2ListOfShortcuts.containsKey(id)) {
list.add(id);
}
}
}
}
return sortInOrderOfRegistration(ArrayUtil.toStringArray(list));
}
@Override
public String[] getActionIds(KeyStroke firstKeyStroke) {
// first, get keystrokes from own map
List<String> list = getKeystroke2ListOfIds().get(firstKeyStroke);
if (myParent != null) {
String[] ids = getParentActionIds(firstKeyStroke);
if (ids.length > 0) {
boolean originalListInstance = true;
for (String id : ids) {
// add actions from parent keymap only if they are absent in this keymap
// do not add parent bind actions, if bind-on action is overwritten in the child
if (!myActionId2ListOfShortcuts.containsKey(id) &&
!myActionId2ListOfShortcuts.containsKey(getActionBinding(id))) {
if (list == null) {
list = new ArrayList<String>();
originalListInstance = false;
}
else if (originalListInstance) {
list = new ArrayList<String>(list);
originalListInstance = false;
}
if (!list.contains(id)) list.add(id);
}
}
}
}
if (list == null) return ArrayUtil.EMPTY_STRING_ARRAY;
return sortInOrderOfRegistration(ArrayUtil.toStringArray(list));
}
@Override
public String[] getActionIds(KeyStroke firstKeyStroke, KeyStroke secondKeyStroke) {
String[] ids = getActionIds(firstKeyStroke);
ArrayList<String> actualBindings = new ArrayList<String>();
for (String id : ids) {
Shortcut[] shortcuts = getShortcuts(id);
for (Shortcut shortcut : shortcuts) {
if (!(shortcut instanceof KeyboardShortcut)) {
continue;
}
if (Comparing.equal(firstKeyStroke, ((KeyboardShortcut)shortcut).getFirstKeyStroke()) &&
Comparing.equal(secondKeyStroke, ((KeyboardShortcut)shortcut).getSecondKeyStroke())) {
actualBindings.add(id);
break;
}
}
}
return ArrayUtil.toStringArray(actualBindings);
}
@Override
public String[] getActionIds(final Shortcut shortcut) {
if (shortcut instanceof KeyboardShortcut) {
final KeyboardShortcut kb = (KeyboardShortcut)shortcut;
final KeyStroke first = kb.getFirstKeyStroke();
final KeyStroke second = kb.getSecondKeyStroke();
return second != null ? getActionIds(first, second) : getActionIds(first);
}
else if (shortcut instanceof MouseShortcut) {
return getActionIds((MouseShortcut)shortcut);
}
else if (shortcut instanceof KeyboardModifierGestureShortcut) {
return getActionIds((KeyboardModifierGestureShortcut)shortcut);
}
else {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
}
protected String[] getParentActionIds(MouseShortcut shortcut) {
return myParent.getActionIds(shortcut);
}
@Override
public String[] getActionIds(MouseShortcut shortcut) {
// first, get shortcuts from own map
List<String> list = getMouseShortcut2ListOfIds().get(shortcut);
if (myParent != null) {
String[] ids = getParentActionIds(shortcut);
if (ids.length > 0) {
boolean originalListInstance = true;
for (String id : ids) {
// add actions from parent keymap only if they are absent in this keymap
if (!myActionId2ListOfShortcuts.containsKey(id)) {
if (list == null) {
list = new ArrayList<String>();
originalListInstance = false;
}
else if (originalListInstance) {
list = new ArrayList<String>(list);
}
list.add(id);
}
}
}
}
if (list == null) {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
return sortInOrderOfRegistration(ArrayUtil.toStringArray(list));
}
private static String[] sortInOrderOfRegistration(String[] ids) {
Arrays.sort(ids, ActionManagerEx.getInstanceEx().getRegistrationOrderComparator());
return ids;
}
public boolean isActionBound(@NotNull final String actionId) {
return getKeymapManager().getBoundActions().contains(actionId);
}
@Nullable
public String getActionBinding(@NotNull final String actionId) {
return getKeymapManager().getActionBinding(actionId);
}
@NotNull
@Override
public Shortcut[] getShortcuts(String actionId) {
LinkedHashSet<Shortcut> shortcuts = myActionId2ListOfShortcuts.get(actionId);
if (shortcuts == null) {
Shortcut[] boundShortcuts = getBoundShortcuts(actionId);
if (boundShortcuts!= null) return boundShortcuts;
}
if (shortcuts == null) {
if (myParent != null) {
return getParentShortcuts(actionId);
}
else {
return ourEmptyShortcutsArray;
}
}
return shortcuts.isEmpty() ? ourEmptyShortcutsArray : shortcuts.toArray(new Shortcut[shortcuts.size()]);
}
@Nullable
private Shortcut[] getOwnShortcuts(String actionId) {
LinkedHashSet<Shortcut> own = myActionId2ListOfShortcuts.get(actionId);
if (own == null) return null;
return own.isEmpty() ? ourEmptyShortcutsArray : own.toArray(new Shortcut[own.size()]);
}
@Nullable
private Shortcut[] getBoundShortcuts(String actionId) {
KeymapManagerEx keymapManager = getKeymapManager();
boolean hasBoundedAction = keymapManager.getBoundActions().contains(actionId);
if (hasBoundedAction) {
return getOwnShortcuts(keymapManager.getActionBinding(actionId));
}
return null;
}
private KeymapManagerEx getKeymapManager() {
if (myKeymapManager == null) {
myKeymapManager = KeymapManagerEx.getInstanceEx();
}
return myKeymapManager;
}
/**
* @param keymapElement element which corresponds to "keymap" tag.
*/
public void readExternal(Element keymapElement, Keymap[] existingKeymaps) throws InvalidDataException {
// Check and convert parameters
if (!KEY_MAP.equals(keymapElement.getName())) {
throw new InvalidDataException("unknown element: " + keymapElement);
}
if (keymapElement.getAttributeValue(VERSION_ATTRIBUTE) == null) {
Converter01.convert(keymapElement);
}
//
String parentName = keymapElement.getAttributeValue(PARENT_ATTRIBUTE);
if (parentName != null) {
for (Keymap existingKeymap : existingKeymaps) {
if (parentName.equals(existingKeymap.getName())) {
myParent = (KeymapImpl)existingKeymap;
myCanModify = true;
break;
}
}
}
myName = keymapElement.getAttributeValue(NAME_ATTRIBUTE);
Map<String, ArrayList<Shortcut>> id2shortcuts = new HashMap<String, ArrayList<Shortcut>>();
final boolean skipInserts = SystemInfo.isMac && !ApplicationManager.getApplication().isUnitTestMode();
for (final Object o : keymapElement.getChildren()) {
Element actionElement = (Element)o;
if (ACTION.equals(actionElement.getName())) {
String id = actionElement.getAttributeValue(ID_ATTRIBUTE);
if (id == null) {
throw new InvalidDataException("Attribute 'id' cannot be null; Keymap's name=" + myName);
}
id2shortcuts.put(id, new ArrayList<Shortcut>(1));
for (final Object o1 : actionElement.getChildren()) {
Element shortcutElement = (Element)o1;
if (KEYBOARD_SHORTCUT.equals(shortcutElement.getName())) {
// Parse first keystroke
KeyStroke firstKeyStroke;
String firstKeyStrokeStr = shortcutElement.getAttributeValue(FIRST_KEYSTROKE_ATTRIBUTE);
if (skipInserts && firstKeyStrokeStr.contains("INSERT")) continue;
if (firstKeyStrokeStr != null) {
firstKeyStroke = ActionManagerEx.getKeyStroke(firstKeyStrokeStr);
if (firstKeyStroke == null) {
throw new InvalidDataException(
"Cannot parse first-keystroke: '" + firstKeyStrokeStr + "'; " + "Action's id=" + id + "; Keymap's name=" + myName);
}
}
else {
throw new InvalidDataException("Attribute 'first-keystroke' cannot be null; Action's id=" + id + "; Keymap's name=" + myName);
}
// Parse second keystroke
KeyStroke secondKeyStroke = null;
String secondKeyStrokeStr = shortcutElement.getAttributeValue(SECOND_KEYSTROKE_ATTRIBUTE);
if (secondKeyStrokeStr != null) {
secondKeyStroke = ActionManagerEx.getKeyStroke(secondKeyStrokeStr);
if (secondKeyStroke == null) {
throw new InvalidDataException(
"Wrong second-keystroke: '" + secondKeyStrokeStr + "'; Action's id=" + id + "; Keymap's name=" + myName);
}
}
Shortcut shortcut = new KeyboardShortcut(firstKeyStroke, secondKeyStroke);
ArrayList<Shortcut> shortcuts = id2shortcuts.get(id);
shortcuts.add(shortcut);
}
else if (KEYBOARD_GESTURE_SHORTCUT.equals(shortcutElement.getName())) {
KeyStroke stroke = null;
final String strokeText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_KEY);
if (strokeText != null) {
stroke = ActionManagerEx.getKeyStroke(strokeText);
}
final String modifierText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_MODIFIER);
KeyboardGestureAction.ModifierType modifier = null;
if (KeyboardGestureAction.ModifierType.dblClick.toString().equalsIgnoreCase(modifierText)) {
modifier = KeyboardGestureAction.ModifierType.dblClick;
}
else if (KeyboardGestureAction.ModifierType.hold.toString().equalsIgnoreCase(modifierText)) {
modifier = KeyboardGestureAction.ModifierType.hold;
}
if (stroke == null) {
throw new InvalidDataException("Wrong keystroke=" + strokeText + " action id=" + id + " keymap=" + myName);
}
if (modifier == null) {
throw new InvalidDataException("Wrong modifier=" + modifierText + " action id=" + id + " keymap=" + myName);
}
Shortcut shortcut = KeyboardModifierGestureShortcut.newInstance(modifier, stroke);
final ArrayList<Shortcut> shortcuts = id2shortcuts.get(id);
shortcuts.add(shortcut);
}
else if (MOUSE_SHORTCUT.equals(shortcutElement.getName())) {
String keystrokeString = shortcutElement.getAttributeValue(KEYSTROKE_ATTRIBUTE);
if (keystrokeString == null) {
throw new InvalidDataException("Attribute 'keystroke' cannot be null; Action's id=" + id + "; Keymap's name=" + myName);
}
try {
MouseShortcut shortcut = KeymapUtil.parseMouseShortcut(keystrokeString);
ArrayList<Shortcut> shortcuts = id2shortcuts.get(id);
shortcuts.add(shortcut);
}
catch (InvalidDataException exc) {
throw new InvalidDataException(
"Wrong mouse-shortcut: '" + keystrokeString + "'; Action's id=" + id + "; Keymap's name=" + myName);
}
}
else {
throw new InvalidDataException("unknown element: " + shortcutElement + "; Keymap's name=" + myName);
}
}
}
else {
throw new InvalidDataException("unknown element: " + actionElement + "; Keymap's name=" + myName);
}
}
// Add read shortcuts
for (String id : id2shortcuts.keySet()) {
myActionId2ListOfShortcuts.put(id, new LinkedHashSet<Shortcut>(2)); // It's a trick! After that parent's shortcuts are not added to the keymap
ArrayList<Shortcut> shortcuts = id2shortcuts.get(id);
for (Shortcut shortcut : shortcuts) {
addShortcutSilently(id, shortcut, false);
}
}
}
public Element writeExternal() {
Element keymapElement = new Element(KEY_MAP);
keymapElement.setAttribute(VERSION_ATTRIBUTE, Integer.toString(1));
keymapElement.setAttribute(NAME_ATTRIBUTE, myName);
if (myParent != null) {
keymapElement.setAttribute(PARENT_ATTRIBUTE, myParent.getName());
}
writeOwnActionIds(keymapElement);
return keymapElement;
}
private void writeOwnActionIds(final Element keymapElement) {
String[] ownActionIds = getOwnActionIds();
Arrays.sort(ownActionIds);
for (String actionId : ownActionIds) {
Element actionElement = new Element(ACTION);
actionElement.setAttribute(ID_ATTRIBUTE, actionId);
// Save keyboad shortcuts
Shortcut[] shortcuts = getShortcuts(actionId);
for (Shortcut shortcut : shortcuts) {
if (shortcut instanceof KeyboardShortcut) {
KeyboardShortcut keyboardShortcut = (KeyboardShortcut)shortcut;
Element element = new Element(KEYBOARD_SHORTCUT);
element.setAttribute(FIRST_KEYSTROKE_ATTRIBUTE, getKeyShortcutString(keyboardShortcut.getFirstKeyStroke()));
if (keyboardShortcut.getSecondKeyStroke() != null) {
element.setAttribute(SECOND_KEYSTROKE_ATTRIBUTE, getKeyShortcutString(keyboardShortcut.getSecondKeyStroke()));
}
actionElement.addContent(element);
}
else if (shortcut instanceof MouseShortcut) {
MouseShortcut mouseShortcut = (MouseShortcut)shortcut;
Element element = new Element(MOUSE_SHORTCUT);
element.setAttribute(KEYSTROKE_ATTRIBUTE, getMouseShortcutString(mouseShortcut));
actionElement.addContent(element);
}
else if (shortcut instanceof KeyboardModifierGestureShortcut) {
final KeyboardModifierGestureShortcut gesture = (KeyboardModifierGestureShortcut)shortcut;
final Element element = new Element(KEYBOARD_GESTURE_SHORTCUT);
element.setAttribute(KEYBOARD_GESTURE_SHORTCUT, getKeyShortcutString(gesture.getStroke()));
element.setAttribute(KEYBOARD_GESTURE_MODIFIER, gesture.getType().name());
actionElement.addContent(element);
}
else {
throw new IllegalStateException("unknown shortcut class: " + shortcut);
}
}
keymapElement.addContent(actionElement);
}
}
private static boolean areShortcutsEqual(Shortcut[] shortcuts1, Shortcut[] shortcuts2) {
if (shortcuts1.length != shortcuts2.length) {
return false;
}
for (Shortcut shortcut : shortcuts1) {
Shortcut parentShortcutEqual = null;
for (Shortcut parentShortcut : shortcuts2) {
if (shortcut.equals(parentShortcut)) {
parentShortcutEqual = parentShortcut;
break;
}
}
if (parentShortcutEqual == null) {
return false;
}
}
return true;
}
/**
* @return string representation of passed keystroke.
*/
public static String getKeyShortcutString(KeyStroke keyStroke) {
StringBuilder buf = new StringBuilder();
int modifiers = keyStroke.getModifiers();
if ((modifiers & InputEvent.SHIFT_MASK) != 0) {
buf.append(SHIFT);
buf.append(' ');
}
if ((modifiers & InputEvent.CTRL_MASK) != 0) {
buf.append(CONTROL);
buf.append(' ');
}
if ((modifiers & InputEvent.META_MASK) != 0) {
buf.append(META);
buf.append(' ');
}
if ((modifiers & InputEvent.ALT_MASK) != 0) {
buf.append(ALT);
buf.append(' ');
}
if ((modifiers & InputEvent.ALT_GRAPH_MASK) != 0) {
buf.append(ALT_GRAPH);
buf.append(' ');
}
buf.append(ourNamesForKeycodes.get(keyStroke.getKeyCode()));
return buf.toString();
}
/**
* @return string representation of passed mouse shortcut. This method should
* be used only for serializing of the <code>MouseShortcut</code>
*/
private static String getMouseShortcutString(MouseShortcut shortcut) {
StringBuilder buffer = new StringBuilder();
// modifiers
int modifiers = shortcut.getModifiers();
if ((MouseEvent.SHIFT_DOWN_MASK & modifiers) > 0) {
buffer.append(SHIFT);
buffer.append(' ');
}
if ((MouseEvent.CTRL_DOWN_MASK & modifiers) > 0) {
buffer.append(CONTROL);
buffer.append(' ');
}
if ((MouseEvent.META_DOWN_MASK & modifiers) > 0) {
buffer.append(META);
buffer.append(' ');
}
if ((MouseEvent.ALT_DOWN_MASK & modifiers) > 0) {
buffer.append(ALT);
buffer.append(' ');
}
if ((MouseEvent.ALT_GRAPH_DOWN_MASK & modifiers) > 0) {
buffer.append(ALT_GRAPH);
buffer.append(' ');
}
// button
buffer.append("button").append(shortcut.getButton()).append(' ');
if (shortcut.getClickCount() > 1) {
buffer.append(DOUBLE_CLICK);
}
return buffer.toString().trim(); // trim trailing space (if any)
}
/**
* @return IDs of the action which are specified in the keymap. It doesn't
* return IDs of action from parent keymap.
*/
public String[] getOwnActionIds() {
return myActionId2ListOfShortcuts.keySet().toArray(new String[myActionId2ListOfShortcuts.size()]);
}
public void clearOwnActionsIds() {
myActionId2ListOfShortcuts.clear();
cleanShortcutsCache();
}
public boolean hasOwnActionId(String actionId) {
return myActionId2ListOfShortcuts.containsKey(actionId);
}
public void clearOwnActionsId(String actionId) {
myActionId2ListOfShortcuts.remove(actionId);
cleanShortcutsCache();
}
@Override
public String[] getActionIds() {
ArrayList<String> ids = new ArrayList<String>();
if (myParent != null) {
String[] parentIds = getParentActionIds();
ContainerUtil.addAll(ids, parentIds);
}
String[] ownActionIds = getOwnActionIds();
for (String id : ownActionIds) {
if (!ids.contains(id)) {
ids.add(id);
}
}
return ArrayUtil.toStringArray(ids);
}
protected String[] getParentActionIds() {
return myParent.getActionIds();
}
@Override
public Map<String, ArrayList<KeyboardShortcut>> getConflicts(String actionId, KeyboardShortcut keyboardShortcut) {
HashMap<String, ArrayList<KeyboardShortcut>> result = new HashMap<String, ArrayList<KeyboardShortcut>>();
String[] actionIds = getActionIds(keyboardShortcut.getFirstKeyStroke());
for (String id : actionIds) {
if (id.equals(actionId)) {
continue;
}
if (actionId.startsWith(EDITOR_ACTION_PREFIX) && id.equals("$" + actionId.substring(6))) {
continue;
}
if (StringUtil.startsWithChar(actionId, '$') && id.equals(EDITOR_ACTION_PREFIX + actionId.substring(1))) {
continue;
}
final String useShortcutOf = myKeymapManager.getActionBinding(id);
if (useShortcutOf != null && useShortcutOf.equals(actionId)) {
continue;
}
Shortcut[] shortcuts = getShortcuts(id);
for (Shortcut shortcut1 : shortcuts) {
if (!(shortcut1 instanceof KeyboardShortcut)) {
continue;
}
KeyboardShortcut shortcut = (KeyboardShortcut)shortcut1;
if (!shortcut.getFirstKeyStroke().equals(keyboardShortcut.getFirstKeyStroke())) {
continue;
}
if (keyboardShortcut.getSecondKeyStroke() != null &&
shortcut.getSecondKeyStroke() != null &&
!keyboardShortcut.getSecondKeyStroke().equals(shortcut.getSecondKeyStroke())) {
continue;
}
ArrayList<KeyboardShortcut> list = result.get(id);
if (list == null) {
list = new ArrayList<KeyboardShortcut>();
result.put(id, list);
}
list.add(shortcut);
}
}
return result;
}
@Override
public void addShortcutChangeListener(Listener listener) {
myListeners.add(listener);
}
@Override
public void removeShortcutChangeListener(Listener listener) {
myListeners.remove(listener);
}
private void fireShortcutChanged(String actionId) {
for (Listener listener : myListeners) {
listener.onShortcutChanged(actionId);
}
}
@Override
public String[] getAbbreviations() {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
@Override
public void addAbbreviation(String actionId, String abbreviation) {
}
@Override
public void removeAbbreviation(String actionId, String abbreviation) {
}
@Override
public String toString() {
return getPresentableName();
}
}
| platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.java | /*
* Copyright 2000-2015 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.keymap.impl;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.keymap.ex.KeymapManagerEx;
import com.intellij.openapi.options.ExternalizableSchemeAdapter;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashMap;
import gnu.trove.THashMap;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.lang.reflect.Field;
import java.util.*;
/**
* @author Eugene Belyaev
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public class KeymapImpl extends ExternalizableSchemeAdapter implements Keymap {
private static final Logger LOG = Logger.getInstance("#com.intellij.keymap.KeymapImpl");
@NonNls private static final String KEY_MAP = "keymap";
@NonNls private static final String KEYBOARD_SHORTCUT = "keyboard-shortcut";
@NonNls private static final String KEYBOARD_GESTURE_SHORTCUT = "keyboard-gesture-shortcut";
@NonNls private static final String KEYBOARD_GESTURE_KEY = "keystroke";
@NonNls private static final String KEYBOARD_GESTURE_MODIFIER = "modifier";
@NonNls private static final String KEYSTROKE_ATTRIBUTE = "keystroke";
@NonNls private static final String FIRST_KEYSTROKE_ATTRIBUTE = "first-keystroke";
@NonNls private static final String SECOND_KEYSTROKE_ATTRIBUTE = "second-keystroke";
@NonNls private static final String ACTION = "action";
@NonNls private static final String VERSION_ATTRIBUTE = "version";
@NonNls private static final String PARENT_ATTRIBUTE = "parent";
@NonNls private static final String NAME_ATTRIBUTE = "name";
@NonNls private static final String ID_ATTRIBUTE = "id";
@NonNls private static final String MOUSE_SHORTCUT = "mouse-shortcut";
@NonNls private static final String SHIFT = "shift";
@NonNls private static final String CONTROL = "control";
@NonNls private static final String META = "meta";
@NonNls private static final String ALT = "alt";
@NonNls private static final String ALT_GRAPH = "altGraph";
@NonNls private static final String DOUBLE_CLICK = "doubleClick";
@NonNls private static final String VIRTUAL_KEY_PREFIX = "VK_";
@NonNls private static final String EDITOR_ACTION_PREFIX = "Editor";
private KeymapImpl myParent;
private boolean myCanModify = true;
private final Map<String, LinkedHashSet<Shortcut>> myActionId2ListOfShortcuts = new THashMap<String, LinkedHashSet<Shortcut>>();
/**
* Don't use this field directly! Use it only through <code>getKeystroke2ListOfIds</code>.
*/
private Map<KeyStroke, List<String>> myKeystroke2ListOfIds = null;
private Map<KeyboardModifierGestureShortcut, List<String>> myGesture2ListOfIds = null;
// TODO[vova,anton] it should be final member
/**
* Don't use this field directly! Use it only through <code>getMouseShortcut2ListOfIds</code>.
*/
private Map<MouseShortcut, List<String>> myMouseShortcut2ListOfIds = null;
// TODO[vova,anton] it should be final member
private static final Map<Integer, String> ourNamesForKeycodes;
private static final Shortcut[] ourEmptyShortcutsArray = new Shortcut[0];
private final List<Listener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private KeymapManagerEx myKeymapManager;
static {
ourNamesForKeycodes = new HashMap<Integer, String>();
try {
Field[] fields = KeyEvent.class.getDeclaredFields();
for (Field field : fields) {
String fieldName = field.getName();
if (fieldName.startsWith(VIRTUAL_KEY_PREFIX)) {
int keyCode = field.getInt(KeyEvent.class);
ourNamesForKeycodes.put(keyCode, fieldName.substring(3));
}
}
}
catch (Exception e) {
LOG.error(e);
}
}
@Override
public String getPresentableName() {
return getName();
}
public KeymapImpl deriveKeymap() {
if (canModify()) {
return copy();
}
else {
KeymapImpl newKeymap = new KeymapImpl();
newKeymap.myParent = this;
newKeymap.myName = null;
newKeymap.myCanModify = canModify();
return newKeymap;
}
}
@NotNull
public KeymapImpl copy() {
KeymapImpl newKeymap = new KeymapImpl();
newKeymap.myParent = myParent;
newKeymap.myName = myName;
newKeymap.myCanModify = canModify();
newKeymap.cleanShortcutsCache();
for (Map.Entry<String, LinkedHashSet<Shortcut>> entry : myActionId2ListOfShortcuts.entrySet()) {
newKeymap.myActionId2ListOfShortcuts.put(entry.getKey(), new LinkedHashSet<Shortcut>(entry.getValue()));
}
return newKeymap;
}
public boolean equals(Object object) {
if (!(object instanceof Keymap)) return false;
KeymapImpl secondKeymap = (KeymapImpl)object;
if (!Comparing.equal(myName, secondKeymap.myName)) return false;
if (myCanModify != secondKeymap.myCanModify) return false;
if (!Comparing.equal(myParent, secondKeymap.myParent)) return false;
if (!Comparing.equal(myActionId2ListOfShortcuts, secondKeymap.myActionId2ListOfShortcuts)) return false;
return true;
}
public int hashCode() {
int hashCode = 0;
if (myName != null) {
hashCode += myName.hashCode();
}
return hashCode;
}
@Override
public Keymap getParent() {
return myParent;
}
@Override
public boolean canModify() {
return myCanModify;
}
public void setCanModify(boolean val) {
myCanModify = val;
}
protected Shortcut[] getParentShortcuts(String actionId) {
return myParent.getShortcuts(actionId);
}
@Override
public void addShortcut(String actionId, Shortcut shortcut) {
addShortcutSilently(actionId, shortcut, true);
fireShortcutChanged(actionId);
}
private void addShortcutSilently(String actionId, Shortcut shortcut, final boolean checkParentShortcut) {
LinkedHashSet<Shortcut> list = myActionId2ListOfShortcuts.get(actionId);
if (list == null) {
list = new LinkedHashSet<Shortcut>();
myActionId2ListOfShortcuts.put(actionId, list);
Shortcut[] boundShortcuts = getBoundShortcuts(actionId);
if (boundShortcuts != null) {
ContainerUtil.addAll(list, boundShortcuts);
}
else if (myParent != null) {
ContainerUtil.addAll(list, getParentShortcuts(actionId));
}
}
list.add(shortcut);
if (checkParentShortcut && myParent != null && areShortcutsEqual(getParentShortcuts(actionId), getShortcuts(actionId))) {
myActionId2ListOfShortcuts.remove(actionId);
}
cleanShortcutsCache();
}
private void cleanShortcutsCache() {
myKeystroke2ListOfIds = null;
myMouseShortcut2ListOfIds = null;
}
@Override
public void removeAllActionShortcuts(String actionId) {
Shortcut[] allShortcuts = getShortcuts(actionId);
for (Shortcut shortcut : allShortcuts) {
removeShortcut(actionId, shortcut);
}
}
@Override
public void removeShortcut(String actionId, Shortcut toDelete) {
LinkedHashSet<Shortcut> list = myActionId2ListOfShortcuts.get(actionId);
if (list != null) {
Iterator<Shortcut> it = list.iterator();
while (it.hasNext()) {
Shortcut each = it.next();
if (toDelete.equals(each)) {
it.remove();
if ((myParent != null && areShortcutsEqual(getParentShortcuts(actionId), getShortcuts(actionId)))
|| (myParent == null && list.isEmpty())) {
myActionId2ListOfShortcuts.remove(actionId);
}
break;
}
}
}
else {
Shortcut[] inherited = getBoundShortcuts(actionId);
if (inherited == null && myParent != null) {
inherited = getParentShortcuts(actionId);
}
if (inherited != null) {
boolean affected = false;
LinkedHashSet<Shortcut> newShortcuts = new LinkedHashSet<Shortcut>(inherited.length);
for (Shortcut eachInherited : inherited) {
if (toDelete.equals(eachInherited)) {
// skip this one
affected = true;
}
else {
newShortcuts.add(eachInherited);
}
}
if (affected) {
myActionId2ListOfShortcuts.put(actionId, newShortcuts);
}
}
}
cleanShortcutsCache();
fireShortcutChanged(actionId);
}
private Map<KeyStroke, List<String>> getKeystroke2ListOfIds() {
if (myKeystroke2ListOfIds != null) return myKeystroke2ListOfIds;
myKeystroke2ListOfIds = new THashMap<KeyStroke, List<String>>();
for (String id : ContainerUtil.concat(myActionId2ListOfShortcuts.keySet(), getKeymapManager().getBoundActions())) {
addKeystrokesMap(id, myKeystroke2ListOfIds);
}
return myKeystroke2ListOfIds;
}
private Map<KeyboardModifierGestureShortcut, List<String>> getGesture2ListOfIds() {
if (myGesture2ListOfIds == null) {
myGesture2ListOfIds = new THashMap<KeyboardModifierGestureShortcut, List<String>>();
fillShortcut2ListOfIds(myGesture2ListOfIds, KeyboardModifierGestureShortcut.class);
}
return myGesture2ListOfIds;
}
private <T extends Shortcut>void fillShortcut2ListOfIds(final Map<T,List<String>> map, final Class<T> shortcutClass) {
for (String id : ContainerUtil.concat(myActionId2ListOfShortcuts.keySet(), getKeymapManager().getBoundActions())) {
addAction2ShortcutsMap(id, map, shortcutClass);
}
}
private Map<MouseShortcut, List<String>> getMouseShortcut2ListOfIds() {
if (myMouseShortcut2ListOfIds == null) {
myMouseShortcut2ListOfIds = new THashMap<MouseShortcut, List<String>>();
fillShortcut2ListOfIds(myMouseShortcut2ListOfIds, MouseShortcut.class);
}
return myMouseShortcut2ListOfIds;
}
private <T extends Shortcut>void addAction2ShortcutsMap(final String actionId, final Map<T, List<String>> strokesMap, final Class<T> shortcutClass) {
LinkedHashSet<Shortcut> listOfShortcuts = _getShortcuts(actionId);
for (Shortcut shortcut : listOfShortcuts) {
if (!shortcutClass.isAssignableFrom(shortcut.getClass())) {
continue;
}
@SuppressWarnings({"unchecked"})
T t = (T)shortcut;
List<String> listOfIds = strokesMap.get(t);
if (listOfIds == null) {
listOfIds = new ArrayList<String>();
strokesMap.put(t, listOfIds);
}
// action may have more that 1 shortcut with same first keystroke
if (!listOfIds.contains(actionId)) {
listOfIds.add(actionId);
}
}
}
private void addKeystrokesMap(final String actionId, final Map<KeyStroke, List<String>> strokesMap) {
LinkedHashSet<Shortcut> listOfShortcuts = _getShortcuts(actionId);
for (Shortcut shortcut : listOfShortcuts) {
if (!(shortcut instanceof KeyboardShortcut)) {
continue;
}
KeyStroke firstKeyStroke = ((KeyboardShortcut)shortcut).getFirstKeyStroke();
List<String> listOfIds = strokesMap.get(firstKeyStroke);
if (listOfIds == null) {
listOfIds = new ArrayList<String>();
strokesMap.put(firstKeyStroke, listOfIds);
}
// action may have more that 1 shortcut with same first keystroke
if (!listOfIds.contains(actionId)) {
listOfIds.add(actionId);
}
}
}
private LinkedHashSet<Shortcut> _getShortcuts(final String actionId) {
KeymapManagerEx keymapManager = getKeymapManager();
LinkedHashSet<Shortcut> listOfShortcuts = myActionId2ListOfShortcuts.get(actionId);
if (listOfShortcuts != null) {
return listOfShortcuts;
}
else {
listOfShortcuts = new LinkedHashSet<Shortcut>();
}
final String actionBinding = keymapManager.getActionBinding(actionId);
if (actionBinding != null) {
listOfShortcuts.addAll(_getShortcuts(actionBinding));
}
return listOfShortcuts;
}
protected String[] getParentActionIds(KeyStroke firstKeyStroke) {
return myParent.getActionIds(firstKeyStroke);
}
protected String[] getParentActionIds(KeyboardModifierGestureShortcut gesture) {
return myParent.getActionIds(gesture);
}
private String[] getActionIds(KeyboardModifierGestureShortcut shortcut) {
// first, get keystrokes from own map
final Map<KeyboardModifierGestureShortcut, List<String>> map = getGesture2ListOfIds();
List<String> list = new ArrayList<String>();
for (Map.Entry<KeyboardModifierGestureShortcut, List<String>> entry : map.entrySet()) {
if (shortcut.startsWith(entry.getKey())) {
list.addAll(entry.getValue());
}
}
if (myParent != null) {
String[] ids = getParentActionIds(shortcut);
if (ids.length > 0) {
for (String id : ids) {
// add actions from parent keymap only if they are absent in this keymap
if (!myActionId2ListOfShortcuts.containsKey(id)) {
list.add(id);
}
}
}
}
return sortInOrderOfRegistration(ArrayUtil.toStringArray(list));
}
@Override
public String[] getActionIds(KeyStroke firstKeyStroke) {
// first, get keystrokes from own map
List<String> list = getKeystroke2ListOfIds().get(firstKeyStroke);
if (myParent != null) {
String[] ids = getParentActionIds(firstKeyStroke);
if (ids.length > 0) {
boolean originalListInstance = true;
for (String id : ids) {
// add actions from parent keymap only if they are absent in this keymap
// do not add parent bind actions, if bind-on action is overwritten in the child
if (!myActionId2ListOfShortcuts.containsKey(id) &&
!myActionId2ListOfShortcuts.containsKey(getActionBinding(id))) {
if (list == null) {
list = new ArrayList<String>();
originalListInstance = false;
}
else if (originalListInstance) {
list = new ArrayList<String>(list);
originalListInstance = false;
}
if (!list.contains(id)) list.add(id);
}
}
}
}
if (list == null) return ArrayUtil.EMPTY_STRING_ARRAY;
return sortInOrderOfRegistration(ArrayUtil.toStringArray(list));
}
@Override
public String[] getActionIds(KeyStroke firstKeyStroke, KeyStroke secondKeyStroke) {
String[] ids = getActionIds(firstKeyStroke);
ArrayList<String> actualBindings = new ArrayList<String>();
for (String id : ids) {
Shortcut[] shortcuts = getShortcuts(id);
for (Shortcut shortcut : shortcuts) {
if (!(shortcut instanceof KeyboardShortcut)) {
continue;
}
if (Comparing.equal(firstKeyStroke, ((KeyboardShortcut)shortcut).getFirstKeyStroke()) &&
Comparing.equal(secondKeyStroke, ((KeyboardShortcut)shortcut).getSecondKeyStroke())) {
actualBindings.add(id);
break;
}
}
}
return ArrayUtil.toStringArray(actualBindings);
}
@Override
public String[] getActionIds(final Shortcut shortcut) {
if (shortcut instanceof KeyboardShortcut) {
final KeyboardShortcut kb = (KeyboardShortcut)shortcut;
final KeyStroke first = kb.getFirstKeyStroke();
final KeyStroke second = kb.getSecondKeyStroke();
return second != null ? getActionIds(first, second) : getActionIds(first);
}
else if (shortcut instanceof MouseShortcut) {
return getActionIds((MouseShortcut)shortcut);
}
else if (shortcut instanceof KeyboardModifierGestureShortcut) {
return getActionIds((KeyboardModifierGestureShortcut)shortcut);
}
else {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
}
protected String[] getParentActionIds(MouseShortcut shortcut) {
return myParent.getActionIds(shortcut);
}
@Override
public String[] getActionIds(MouseShortcut shortcut) {
// first, get shortcuts from own map
List<String> list = getMouseShortcut2ListOfIds().get(shortcut);
if (myParent != null) {
String[] ids = getParentActionIds(shortcut);
if (ids.length > 0) {
boolean originalListInstance = true;
for (String id : ids) {
// add actions from parent keymap only if they are absent in this keymap
if (!myActionId2ListOfShortcuts.containsKey(id)) {
if (list == null) {
list = new ArrayList<String>();
originalListInstance = false;
}
else if (originalListInstance) {
list = new ArrayList<String>(list);
}
list.add(id);
}
}
}
}
if (list == null) {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
return sortInOrderOfRegistration(ArrayUtil.toStringArray(list));
}
private static String[] sortInOrderOfRegistration(String[] ids) {
Arrays.sort(ids, ActionManagerEx.getInstanceEx().getRegistrationOrderComparator());
return ids;
}
public boolean isActionBound(@NotNull final String actionId) {
return getKeymapManager().getBoundActions().contains(actionId);
}
@Nullable
public String getActionBinding(@NotNull final String actionId) {
return getKeymapManager().getActionBinding(actionId);
}
@NotNull
@Override
public Shortcut[] getShortcuts(String actionId) {
LinkedHashSet<Shortcut> shortcuts = myActionId2ListOfShortcuts.get(actionId);
if (shortcuts == null) {
Shortcut[] boundShortcuts = getBoundShortcuts(actionId);
if (boundShortcuts!= null) return boundShortcuts;
}
if (shortcuts == null) {
if (myParent != null) {
return getParentShortcuts(actionId);
}
else {
return ourEmptyShortcutsArray;
}
}
return shortcuts.isEmpty() ? ourEmptyShortcutsArray : shortcuts.toArray(new Shortcut[shortcuts.size()]);
}
@Nullable
private Shortcut[] getOwnShortcuts(String actionId) {
LinkedHashSet<Shortcut> own = myActionId2ListOfShortcuts.get(actionId);
if (own == null) return null;
return own.isEmpty() ? ourEmptyShortcutsArray : own.toArray(new Shortcut[own.size()]);
}
@Nullable
private Shortcut[] getBoundShortcuts(String actionId) {
KeymapManagerEx keymapManager = getKeymapManager();
boolean hasBoundedAction = keymapManager.getBoundActions().contains(actionId);
if (hasBoundedAction) {
return getOwnShortcuts(keymapManager.getActionBinding(actionId));
}
return null;
}
private KeymapManagerEx getKeymapManager() {
if (myKeymapManager == null) {
myKeymapManager = KeymapManagerEx.getInstanceEx();
}
return myKeymapManager;
}
/**
* @param keymapElement element which corresponds to "keymap" tag.
*/
public void readExternal(Element keymapElement, Keymap[] existingKeymaps) throws InvalidDataException {
// Check and convert parameters
if (!KEY_MAP.equals(keymapElement.getName())) {
throw new InvalidDataException("unknown element: " + keymapElement);
}
if (keymapElement.getAttributeValue(VERSION_ATTRIBUTE) == null) {
Converter01.convert(keymapElement);
}
//
String parentName = keymapElement.getAttributeValue(PARENT_ATTRIBUTE);
if (parentName != null) {
for (Keymap existingKeymap : existingKeymaps) {
if (parentName.equals(existingKeymap.getName())) {
myParent = (KeymapImpl)existingKeymap;
myCanModify = true;
break;
}
}
}
myName = keymapElement.getAttributeValue(NAME_ATTRIBUTE);
Map<String, ArrayList<Shortcut>> id2shortcuts = new HashMap<String, ArrayList<Shortcut>>();
final boolean skipInserts = SystemInfo.isMac && !ApplicationManager.getApplication().isUnitTestMode();
for (final Object o : keymapElement.getChildren()) {
Element actionElement = (Element)o;
if (ACTION.equals(actionElement.getName())) {
String id = actionElement.getAttributeValue(ID_ATTRIBUTE);
if (id == null) {
throw new InvalidDataException("Attribute 'id' cannot be null; Keymap's name=" + myName);
}
id2shortcuts.put(id, new ArrayList<Shortcut>(1));
for (final Object o1 : actionElement.getChildren()) {
Element shortcutElement = (Element)o1;
if (KEYBOARD_SHORTCUT.equals(shortcutElement.getName())) {
// Parse first keystroke
KeyStroke firstKeyStroke;
String firstKeyStrokeStr = shortcutElement.getAttributeValue(FIRST_KEYSTROKE_ATTRIBUTE);
if (skipInserts && firstKeyStrokeStr.contains("INSERT")) continue;
if (firstKeyStrokeStr != null) {
firstKeyStroke = ActionManagerEx.getKeyStroke(firstKeyStrokeStr);
if (firstKeyStroke == null) {
throw new InvalidDataException(
"Cannot parse first-keystroke: '" + firstKeyStrokeStr + "'; " + "Action's id=" + id + "; Keymap's name=" + myName);
}
}
else {
throw new InvalidDataException("Attribute 'first-keystroke' cannot be null; Action's id=" + id + "; Keymap's name=" + myName);
}
// Parse second keystroke
KeyStroke secondKeyStroke = null;
String secondKeyStrokeStr = shortcutElement.getAttributeValue(SECOND_KEYSTROKE_ATTRIBUTE);
if (secondKeyStrokeStr != null) {
secondKeyStroke = ActionManagerEx.getKeyStroke(secondKeyStrokeStr);
if (secondKeyStroke == null) {
throw new InvalidDataException(
"Wrong second-keystroke: '" + secondKeyStrokeStr + "'; Action's id=" + id + "; Keymap's name=" + myName);
}
}
Shortcut shortcut = new KeyboardShortcut(firstKeyStroke, secondKeyStroke);
ArrayList<Shortcut> shortcuts = id2shortcuts.get(id);
shortcuts.add(shortcut);
}
else if (KEYBOARD_GESTURE_SHORTCUT.equals(shortcutElement.getName())) {
KeyStroke stroke = null;
final String strokeText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_KEY);
if (strokeText != null) {
stroke = ActionManagerEx.getKeyStroke(strokeText);
}
final String modifierText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_MODIFIER);
KeyboardGestureAction.ModifierType modifier = null;
if (KeyboardGestureAction.ModifierType.dblClick.toString().equalsIgnoreCase(modifierText)) {
modifier = KeyboardGestureAction.ModifierType.dblClick;
}
else if (KeyboardGestureAction.ModifierType.hold.toString().equalsIgnoreCase(modifierText)) {
modifier = KeyboardGestureAction.ModifierType.hold;
}
if (stroke == null) {
throw new InvalidDataException("Wrong keystroke=" + strokeText + " action id=" + id + " keymap=" + myName);
}
if (modifier == null) {
throw new InvalidDataException("Wrong modifier=" + modifierText + " action id=" + id + " keymap=" + myName);
}
Shortcut shortcut = KeyboardModifierGestureShortcut.newInstance(modifier, stroke);
final ArrayList<Shortcut> shortcuts = id2shortcuts.get(id);
shortcuts.add(shortcut);
}
else if (MOUSE_SHORTCUT.equals(shortcutElement.getName())) {
String keystrokeString = shortcutElement.getAttributeValue(KEYSTROKE_ATTRIBUTE);
if (keystrokeString == null) {
throw new InvalidDataException("Attribute 'keystroke' cannot be null; Action's id=" + id + "; Keymap's name=" + myName);
}
try {
MouseShortcut shortcut = KeymapUtil.parseMouseShortcut(keystrokeString);
ArrayList<Shortcut> shortcuts = id2shortcuts.get(id);
shortcuts.add(shortcut);
}
catch (InvalidDataException exc) {
throw new InvalidDataException(
"Wrong mouse-shortcut: '" + keystrokeString + "'; Action's id=" + id + "; Keymap's name=" + myName);
}
}
else {
throw new InvalidDataException("unknown element: " + shortcutElement + "; Keymap's name=" + myName);
}
}
}
else {
throw new InvalidDataException("unknown element: " + actionElement + "; Keymap's name=" + myName);
}
}
// Add read shortcuts
for (String id : id2shortcuts.keySet()) {
myActionId2ListOfShortcuts.put(id, new LinkedHashSet<Shortcut>(2)); // It's a trick! After that parent's shortcuts are not added to the keymap
ArrayList<Shortcut> shortcuts = id2shortcuts.get(id);
for (Shortcut shortcut : shortcuts) {
addShortcutSilently(id, shortcut, false);
}
}
}
public Element writeExternal() {
Element keymapElement = new Element(KEY_MAP);
keymapElement.setAttribute(VERSION_ATTRIBUTE, Integer.toString(1));
keymapElement.setAttribute(NAME_ATTRIBUTE, myName);
if (myParent != null) {
keymapElement.setAttribute(PARENT_ATTRIBUTE, myParent.getName());
}
writeOwnActionIds(keymapElement);
return keymapElement;
}
private void writeOwnActionIds(final Element keymapElement) {
String[] ownActionIds = getOwnActionIds();
Arrays.sort(ownActionIds);
for (String actionId : ownActionIds) {
Element actionElement = new Element(ACTION);
actionElement.setAttribute(ID_ATTRIBUTE, actionId);
// Save keyboad shortcuts
Shortcut[] shortcuts = getShortcuts(actionId);
for (Shortcut shortcut : shortcuts) {
if (shortcut instanceof KeyboardShortcut) {
KeyboardShortcut keyboardShortcut = (KeyboardShortcut)shortcut;
Element element = new Element(KEYBOARD_SHORTCUT);
element.setAttribute(FIRST_KEYSTROKE_ATTRIBUTE, getKeyShortcutString(keyboardShortcut.getFirstKeyStroke()));
if (keyboardShortcut.getSecondKeyStroke() != null) {
element.setAttribute(SECOND_KEYSTROKE_ATTRIBUTE, getKeyShortcutString(keyboardShortcut.getSecondKeyStroke()));
}
actionElement.addContent(element);
}
else if (shortcut instanceof MouseShortcut) {
MouseShortcut mouseShortcut = (MouseShortcut)shortcut;
Element element = new Element(MOUSE_SHORTCUT);
element.setAttribute(KEYSTROKE_ATTRIBUTE, getMouseShortcutString(mouseShortcut));
actionElement.addContent(element);
}
else if (shortcut instanceof KeyboardModifierGestureShortcut) {
final KeyboardModifierGestureShortcut gesture = (KeyboardModifierGestureShortcut)shortcut;
final Element element = new Element(KEYBOARD_GESTURE_SHORTCUT);
element.setAttribute(KEYBOARD_GESTURE_SHORTCUT, getKeyShortcutString(gesture.getStroke()));
element.setAttribute(KEYBOARD_GESTURE_MODIFIER, gesture.getType().name());
actionElement.addContent(element);
}
else {
throw new IllegalStateException("unknown shortcut class: " + shortcut);
}
}
keymapElement.addContent(actionElement);
}
}
private static boolean areShortcutsEqual(Shortcut[] shortcuts1, Shortcut[] shortcuts2) {
if (shortcuts1.length != shortcuts2.length) {
return false;
}
for (Shortcut shortcut : shortcuts1) {
Shortcut parentShortcutEqual = null;
for (Shortcut parentShortcut : shortcuts2) {
if (shortcut.equals(parentShortcut)) {
parentShortcutEqual = parentShortcut;
break;
}
}
if (parentShortcutEqual == null) {
return false;
}
}
return true;
}
/**
* @return string representation of passed keystroke.
*/
public static String getKeyShortcutString(KeyStroke keyStroke) {
StringBuffer buf = new StringBuffer();
int modifiers = keyStroke.getModifiers();
if ((modifiers & InputEvent.SHIFT_MASK) != 0) {
buf.append(SHIFT);
buf.append(' ');
}
if ((modifiers & InputEvent.CTRL_MASK) != 0) {
buf.append(CONTROL);
buf.append(' ');
}
if ((modifiers & InputEvent.META_MASK) != 0) {
buf.append(META);
buf.append(' ');
}
if ((modifiers & InputEvent.ALT_MASK) != 0) {
buf.append(ALT);
buf.append(' ');
}
if ((modifiers & InputEvent.ALT_GRAPH_MASK) != 0) {
buf.append(ALT_GRAPH);
buf.append(' ');
}
buf.append(ourNamesForKeycodes.get(keyStroke.getKeyCode()));
return buf.toString();
}
/**
* @return string representation of passed mouse shortcut. This method should
* be used only for serializing of the <code>MouseShortcut</code>
*/
private static String getMouseShortcutString(MouseShortcut shortcut) {
StringBuffer buffer = new StringBuffer();
// modifiers
int modifiers = shortcut.getModifiers();
if ((MouseEvent.SHIFT_DOWN_MASK & modifiers) > 0) {
buffer.append(SHIFT);
buffer.append(' ');
}
if ((MouseEvent.CTRL_DOWN_MASK & modifiers) > 0) {
buffer.append(CONTROL);
buffer.append(' ');
}
if ((MouseEvent.META_DOWN_MASK & modifiers) > 0) {
buffer.append(META);
buffer.append(' ');
}
if ((MouseEvent.ALT_DOWN_MASK & modifiers) > 0) {
buffer.append(ALT);
buffer.append(' ');
}
if ((MouseEvent.ALT_GRAPH_DOWN_MASK & modifiers) > 0) {
buffer.append(ALT_GRAPH);
buffer.append(' ');
}
// button
buffer.append("button").append(shortcut.getButton()).append(' ');
if (shortcut.getClickCount() > 1) {
buffer.append(DOUBLE_CLICK);
}
return buffer.toString().trim(); // trim trailing space (if any)
}
/**
* @return IDs of the action which are specified in the keymap. It doesn't
* return IDs of action from parent keymap.
*/
public String[] getOwnActionIds() {
return myActionId2ListOfShortcuts.keySet().toArray(new String[myActionId2ListOfShortcuts.size()]);
}
public void clearOwnActionsIds() {
myActionId2ListOfShortcuts.clear();
cleanShortcutsCache();
}
public boolean hasOwnActionId(String actionId) {
return myActionId2ListOfShortcuts.containsKey(actionId);
}
public void clearOwnActionsId(String actionId) {
myActionId2ListOfShortcuts.remove(actionId);
cleanShortcutsCache();
}
@Override
public String[] getActionIds() {
ArrayList<String> ids = new ArrayList<String>();
if (myParent != null) {
String[] parentIds = getParentActionIds();
ContainerUtil.addAll(ids, parentIds);
}
String[] ownActionIds = getOwnActionIds();
for (String id : ownActionIds) {
if (!ids.contains(id)) {
ids.add(id);
}
}
return ArrayUtil.toStringArray(ids);
}
protected String[] getParentActionIds() {
return myParent.getActionIds();
}
@Override
public Map<String, ArrayList<KeyboardShortcut>> getConflicts(String actionId, KeyboardShortcut keyboardShortcut) {
HashMap<String, ArrayList<KeyboardShortcut>> result = new HashMap<String, ArrayList<KeyboardShortcut>>();
String[] actionIds = getActionIds(keyboardShortcut.getFirstKeyStroke());
for (String id : actionIds) {
if (id.equals(actionId)) {
continue;
}
if (actionId.startsWith(EDITOR_ACTION_PREFIX) && id.equals("$" + actionId.substring(6))) {
continue;
}
if (StringUtil.startsWithChar(actionId, '$') && id.equals(EDITOR_ACTION_PREFIX + actionId.substring(1))) {
continue;
}
final String useShortcutOf = myKeymapManager.getActionBinding(id);
if (useShortcutOf != null && useShortcutOf.equals(actionId)) {
continue;
}
Shortcut[] shortcuts = getShortcuts(id);
for (Shortcut shortcut1 : shortcuts) {
if (!(shortcut1 instanceof KeyboardShortcut)) {
continue;
}
KeyboardShortcut shortcut = (KeyboardShortcut)shortcut1;
if (!shortcut.getFirstKeyStroke().equals(keyboardShortcut.getFirstKeyStroke())) {
continue;
}
if (keyboardShortcut.getSecondKeyStroke() != null &&
shortcut.getSecondKeyStroke() != null &&
!keyboardShortcut.getSecondKeyStroke().equals(shortcut.getSecondKeyStroke())) {
continue;
}
ArrayList<KeyboardShortcut> list = result.get(id);
if (list == null) {
list = new ArrayList<KeyboardShortcut>();
result.put(id, list);
}
list.add(shortcut);
}
}
return result;
}
@Override
public void addShortcutChangeListener(Listener listener) {
myListeners.add(listener);
}
@Override
public void removeShortcutChangeListener(Listener listener) {
myListeners.remove(listener);
}
private void fireShortcutChanged(String actionId) {
for (Listener listener : myListeners) {
listener.onShortcutChanged(actionId);
}
}
@Override
public String[] getAbbreviations() {
return new String[0];
}
@Override
public void addAbbreviation(String actionId, String abbreviation) {
}
@Override
public void removeAbbreviation(String actionId, String abbreviation) {
}
@Override
public String toString() {
return getPresentableName();
}
}
| cleanup
| platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.java | cleanup | <ide><path>latform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.java
<ide> * @return string representation of passed keystroke.
<ide> */
<ide> public static String getKeyShortcutString(KeyStroke keyStroke) {
<del> StringBuffer buf = new StringBuffer();
<add> StringBuilder buf = new StringBuilder();
<ide> int modifiers = keyStroke.getModifiers();
<ide> if ((modifiers & InputEvent.SHIFT_MASK) != 0) {
<ide> buf.append(SHIFT);
<ide> * be used only for serializing of the <code>MouseShortcut</code>
<ide> */
<ide> private static String getMouseShortcutString(MouseShortcut shortcut) {
<del> StringBuffer buffer = new StringBuffer();
<add> StringBuilder buffer = new StringBuilder();
<ide>
<ide> // modifiers
<ide>
<ide>
<ide> @Override
<ide> public String[] getAbbreviations() {
<del> return new String[0];
<add> return ArrayUtil.EMPTY_STRING_ARRAY;
<ide> }
<ide>
<ide> @Override |
|
JavaScript | mit | a3ee329d2708093e97f46a7db1ec3bb2cefc45e4 | 0 | xavierdutreilh/wintersmith-sitemap,xavierdutreilh/wintersmith-sitemap | 'use strict';
const path = require('path');
module.exports = function(env, callback) {
class Sitemap extends env.plugins.Page {
getFilename() {
return 'sitemap.xml';
}
getView() {
// jshint maxparams: 5
return (env, locals, contents, templates, callback) => {
const filepath = {
'full': path.join(__dirname, 'templates', 'sitemap.jade'),
'relative': path.join('templates', 'sitemap.jade'),
};
env.plugins.JadeTemplate.fromFile(filepath, (error, template) => {
let context = {
'entries': env.helpers.contents.list(contents).filter((content) => (
content instanceof env.plugins.MarkdownPage &&
!content.metadata.noindex
)),
'page': this,
};
env.utils.extend(context, locals);
template.render(context, callback);
});
};
}
}
env.registerGenerator('sitemap', (contents, callback) => {
callback(null, {'sitemap.xml': new Sitemap()});
});
callback();
};
| lib/index.js | 'use strict';
const path = require('path');
module.exports = function(env, callback) {
class Sitemap extends env.plugins.Page {
getFilename() {
return 'sitemap.xml';
}
getEntries(contents) {
return env.helpers.contents.list(contents).filter((content) => (
content instanceof env.plugins.MarkdownPage &&
!content.metadata.noindex
));
}
getView() {
// jshint maxparams: 5
return (env, locals, contents, templates, callback) => {
const filepath = {
'full': path.join(__dirname, 'templates', 'sitemap.jade'),
'relative': path.join('templates', 'sitemap.jade'),
};
env.plugins.JadeTemplate.fromFile(filepath, (error, template) => {
let context = {
'entries': this.getEntries(contents),
'page': this,
};
env.utils.extend(context, locals);
template.render(context, callback);
});
};
}
}
env.registerGenerator('sitemap', (contents, callback) => {
callback(null, {'sitemap.xml': new Sitemap()});
});
callback();
};
| Clean up index file
| lib/index.js | Clean up index file | <ide><path>ib/index.js
<ide> class Sitemap extends env.plugins.Page {
<ide> getFilename() {
<ide> return 'sitemap.xml';
<del> }
<del>
<del> getEntries(contents) {
<del> return env.helpers.contents.list(contents).filter((content) => (
<del> content instanceof env.plugins.MarkdownPage &&
<del> !content.metadata.noindex
<del> ));
<ide> }
<ide>
<ide> getView() {
<ide>
<ide> env.plugins.JadeTemplate.fromFile(filepath, (error, template) => {
<ide> let context = {
<del> 'entries': this.getEntries(contents),
<add> 'entries': env.helpers.contents.list(contents).filter((content) => (
<add> content instanceof env.plugins.MarkdownPage &&
<add> !content.metadata.noindex
<add> )),
<ide> 'page': this,
<ide> };
<ide> |
|
JavaScript | mit | 3c32d5d70c087744f0a2c2a7b91404e8e24bff5f | 0 | romkor/angular-wheel | (function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['angular'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS style for Browserify
module.exports = factory;
} else {
// Browser globals
factory(angular);
}
}(function () {
'use strict';
// define eveWheel module
var eveWheelModule = angular.module('eveWheel', []),
// Directives generator, idea borrowed from ngSwipe module
makeWheelDirective = function (directiveName, direction) {
direction = direction || 0;
eveWheelModule.directive(directiveName, ['$parse', function ($parse) {
return function (scope, element, attr) {
var wheelHandler = $parse(attr[directiveName]),
onWheel = function (event) {
event = event || window.event;
var delta = (event.deltaY * -1 || event.detail * -1 || event.wheelDelta) > 0 ? 1 : -1;
if (direction === 0 || direction === delta) {
scope.$apply(function () {
element.triggerHandler("evewheel");
wheelHandler(scope, {
$event: event,
$delta: delta
});
});
}
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
},
wheelEvent;
if (document.hasOwnProperty('onwheel')) {
// IE9+, FF17+
wheelEvent = "wheel";
} else if (document.hasOwnProperty('onmousewheel')) {
// deprecated
wheelEvent = "mousewheel";
} else {
// 3.5 <= Firefox < 17
wheelEvent = "MozMousePixelScroll";
}
element.bind(wheelEvent, onWheel);
element.bind('$destroy', function() {
element.unbind(wheelEvent, onWheel);
});
};
}]);
};
makeWheelDirective('eveWheel');
makeWheelDirective('eveWheelNext', 1);
makeWheelDirective('eveWheelPrev', -1);
}));
| src/angular-wheel.js | 'use strict';
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['angular'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS style for Browserify
module.exports = factory;
} else {
// Browser globals
factory(angular);
}
}(function () {
// define eveWheel module
var eveWheelModule = angular.module('eveWheel', []);
function makeWheelDirective(directiveName, direction) {
direction = direction || 0;
eveWheelModule.directive(directiveName, ['$parse', function ($parse) {
return function (scope, element, attr) {
var wheelHandler = $parse(attr[directiveName]);
if ('onwheel' in document) {
// IE9+, FF17+
element.bind("wheel", onWheel)
} else if ('onmousewheel' in document) {
// deprecated
element.bind("mousewheel", onWheel)
} else {
// 3.5 <= Firefox < 17
element.bind("MozMousePixelScroll", onWheel)
}
function onWheel(event) {
event = event || window.event;
var delta = (event.deltaY || event.detail || event.wheelDelta) > 0 ? 1 : -1;
if (direction === 0 || direction === delta) {
scope.$apply(function () {
element.triggerHandler("evewheel");
wheelHandler(scope, {
$event: event,
$delta: delta
});
});
}
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
}
}
}])
}
makeWheelDirective('eveWheel');
makeWheelDirective('eveWheelNext', 1);
makeWheelDirective('eveWheelPrev', -1);
}));
| Updated directive.
Added $destroy binding.
| src/angular-wheel.js | Updated directive. Added $destroy binding. | <ide><path>rc/angular-wheel.js
<del>'use strict';
<ide> (function (factory) {
<add> 'use strict';
<ide> if (typeof define === 'function' && define.amd) {
<ide> // AMD. Register as an anonymous module.
<ide> define(['angular'], factory);
<ide> factory(angular);
<ide> }
<ide> }(function () {
<add> 'use strict';
<add> // define eveWheel module
<add> var eveWheelModule = angular.module('eveWheel', []),
<ide>
<del> // define eveWheel module
<del> var eveWheelModule = angular.module('eveWheel', []);
<add> // Directives generator, idea borrowed from ngSwipe module
<add> makeWheelDirective = function (directiveName, direction) {
<ide>
<del> function makeWheelDirective(directiveName, direction) {
<add> direction = direction || 0;
<ide>
<del> direction = direction || 0;
<add> eveWheelModule.directive(directiveName, ['$parse', function ($parse) {
<ide>
<del> eveWheelModule.directive(directiveName, ['$parse', function ($parse) {
<add> return function (scope, element, attr) {
<ide>
<del> return function (scope, element, attr) {
<add> var wheelHandler = $parse(attr[directiveName]),
<add> onWheel = function (event) {
<add> event = event || window.event;
<ide>
<del> var wheelHandler = $parse(attr[directiveName]);
<add> var delta = (event.deltaY * -1 || event.detail * -1 || event.wheelDelta) > 0 ? 1 : -1;
<ide>
<del> if ('onwheel' in document) {
<del> // IE9+, FF17+
<del> element.bind("wheel", onWheel)
<del> } else if ('onmousewheel' in document) {
<del> // deprecated
<del> element.bind("mousewheel", onWheel)
<del> } else {
<del> // 3.5 <= Firefox < 17
<del> element.bind("MozMousePixelScroll", onWheel)
<del> }
<add> if (direction === 0 || direction === delta) {
<add> scope.$apply(function () {
<add> element.triggerHandler("evewheel");
<add> wheelHandler(scope, {
<add> $event: event,
<add> $delta: delta
<add> });
<add> });
<add> }
<ide>
<del> function onWheel(event) {
<del> event = event || window.event;
<add> event.preventDefault ? event.preventDefault() : (event.returnValue = false);
<add> },
<add> wheelEvent;
<ide>
<del> var delta = (event.deltaY || event.detail || event.wheelDelta) > 0 ? 1 : -1;
<del>
<del> if (direction === 0 || direction === delta) {
<del> scope.$apply(function () {
<del> element.triggerHandler("evewheel");
<del> wheelHandler(scope, {
<del> $event: event,
<del> $delta: delta
<del> });
<del> });
<add> if (document.hasOwnProperty('onwheel')) {
<add> // IE9+, FF17+
<add> wheelEvent = "wheel";
<add> } else if (document.hasOwnProperty('onmousewheel')) {
<add> // deprecated
<add> wheelEvent = "mousewheel";
<add> } else {
<add> // 3.5 <= Firefox < 17
<add> wheelEvent = "MozMousePixelScroll";
<ide> }
<ide>
<del> event.preventDefault ? event.preventDefault() : (event.returnValue = false);
<del> }
<del> }
<add> element.bind(wheelEvent, onWheel);
<ide>
<del> }])
<add> element.bind('$destroy', function() {
<add> element.unbind(wheelEvent, onWheel);
<add> });
<ide>
<del> }
<add> };
<add>
<add> }]);
<add> };
<ide>
<ide> makeWheelDirective('eveWheel');
<ide> |
|
JavaScript | mit | d7dabed3231937fe8f15aa8c23ee2848b4525ede | 0 | JamesSkemp/VideoGamesSpa,JamesSkemp/VideoGamesSpa | app.controller('HomeController', function ($scope) {
// todo not sure what I want on the page yet, since we didn't have it before
});
app.controller('GamesController', function ($scope, $http, JsonCache) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.games = [];
$scope.consoles = [];
$http.get('Content/json/VideoGames.json', { cache: JsonCache }).success(function (data) {
$scope.games = data.VideoGames;
for (var g = 0; g < data.VideoGames.length; g++) {
var console = data.VideoGames[g].System;
if ($scope.consoles.indexOf(console) == -1) {
$scope.consoles.push(console);
}
}
$scope.consoles.sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
});
$scope.numberOfPages = function () {
return Math.ceil($scope.games.length / $scope.pageSize);
};
});
app.controller('ProfileController', function ($scope, $route, $http, JsonCache, $templateCache, $window) {
var psnDataUrl = "Content/json/_psnProfile.xml.json";
var xblDataUrl = "Content/json/_xblProfile.xml.json";
var getPsnData = function () {
$http.get(psnDataUrl, { cache: JsonCache }).success(function (data) {
$scope.psnProfile = [];
$scope.psnProfile = data.PsnProfile;
$scope.psnPointsPercent = 100 * data.PsnProfile.Points / data.PsnProfile.PossiblePoints;
$scope.psnTrophiesPercent = 100 * data.PsnProfile.Trophies / data.PsnProfile.PossibleTrophies;
$scope.psnTrophiesBronzePercent = 100 * data.PsnProfile.TrophiesBronze / data.PsnProfile.PossibleTrophiesBronze;
$scope.psnTrophiesSilverPercent = 100 * data.PsnProfile.TrophiesSilver / data.PsnProfile.PossibleTrophiesSilver;
$scope.psnTrophiesGoldPercent = 100 * data.PsnProfile.TrophiesGold / data.PsnProfile.PossibleTrophiesGold;
$scope.psnTrophiesPlatinumPercent = 100 * data.PsnProfile.TrophiesPlatinum / data.PsnProfile.PossibleTrophiesPlatinum;
$scope.psnPointsGoal1 = $scope.percentGoal(data.PsnProfile.Points, data.PsnProfile.PossiblePoints, 1);
$scope.psnPointsGoal2 = $scope.percentGoal(data.PsnProfile.Points, data.PsnProfile.PossiblePoints, 2);
$scope.psnTrophiesGoal1 = $scope.percentGoal(data.PsnProfile.Trophies, data.PsnProfile.PossibleTrophies, 1);
$scope.psnTrophiesGoal2 = $scope.percentGoal(data.PsnProfile.Trophies, data.PsnProfile.PossibleTrophies, 2);
});
};
var getXblData = function () {
$http.get(xblDataUrl, { cache: JsonCache }).success(function (data) {
$scope.xblProfile = [];
$scope.xblProfile = data.XblProfile;
$scope.xblPointsPercent = 100 * data.XblProfile.GamerScore / data.XblProfile.PossibleGamerScore;
$scope.xblAchievementsPercent = 100 * data.XblProfile.Achievements / data.XblProfile.PossibleAchievements;
$scope.xblGamerscoreGoal1 = $scope.percentGoal(data.XblProfile.GamerScore, data.XblProfile.PossibleGamerScore, 1);
$scope.xblGamerscoreGoal2 = $scope.percentGoal(data.XblProfile.GamerScore, data.XblProfile.PossibleGamerScore, 2);
$scope.xblAchievementsGoal1 = $scope.percentGoal(data.XblProfile.Achievements, data.XblProfile.PossibleAchievements, 1);
$scope.xblAchievementsGoal2 = $scope.percentGoal(data.XblProfile.Achievements, data.XblProfile.PossibleAchievements, 2);
});
};
$scope.psnProfile = [];
$scope.xblProfile = [];
getPsnData();
getXblData();
$scope.percentClass = function (percent) {
return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
};
$scope.quantityToPercent = function (obtained, total, percent, outputType) {
if (total * percent / 100 <= obtained) {
return "";
} else {
var numberAtPercent = Math.ceil(total * percent / 100);
var trophyInfo = "";
if (outputType == "psnPoints") {
trophyInfo = $scope.trophiesToPointsGoal(numberAtPercent - obtained);
}
return percent + "% = " + numberAtPercent + " (" + (numberAtPercent - obtained) + trophyInfo + ")";
}
};
$scope.percentGoal = function (obtained, total, goal) {
var currentPercent = Math.floor(obtained / total * 100);
var goalPercent = 0;
if (goal == 1) {
// Goal one is the next percent.
for (var i = 1; i <= 100; i = i + 1) {
if (currentPercent < i) {
goalPercent = i;
break;
}
}
} else {
// Goal two is the next percent evently divisible by 5.
currentPercent = currentPercent + 1;
for (var i = 5; i <= 100; i = i + 5) {
if (currentPercent < i) {
goalPercent = i;
break;
}
}
}
return goalPercent;
};
$scope.trophiesToPointsGoal = function (goal) {
var output = "";
if (goal > 0) {
var bronze = 15, silver = 30, gold = 90;
var totalBronze = Math.round(goal / bronze);
var totalSilver = Math.round(goal / silver);
var totalGold = Math.round(goal / gold);
if (totalBronze > 0) {
output += " / " + totalBronze + " bronze";
if (totalSilver > 0) {
output += " | " + totalSilver + " silver";
if (totalGold > 0) {
output += " | " + totalGold + " gold";
}
}
}
}
return output;
};
//console.log($route);
//console.log($templateCache.info());
});
app.controller('BasicsController', function ($scope, $http, JsonCache, $window) {
$scope.psnGamesBasic = [];
$scope.xblGamesBasic = [];
$http.get('Content/json/_psnGamesBasic.xml.json', { cache: JsonCache }).success(function (data) {
$scope.psnGamesBasic = data.PsnGamesBasic;
});
$http.get('Content/json/_xblGamesBasic.xml.json', { cache: JsonCache }).success(function (data) {
$scope.xblGamesBasic = data.XblGamesBasic;
});
$scope.percentClass = function (percent) {
return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
};
$scope.extractDate = function (date) {
if (date.length > 6) {
var uglyDate = new Date(parseInt(date.substr(6)));
return uglyDate;
}
return "";
}
});
app.controller('PsnBasicsController', function ($scope, $http, JsonCache, $window) {
$scope.psnGamesBasic = [];
$http.get('Content/json/_psnGamesBasic.xml.json', { cache: JsonCache }).success(function (data) {
$scope.psnGamesBasic = data.PsnGamesBasic;
});
$scope.percentClass = function (percent) {
return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
};
$scope.extractDate = function (date) {
if (date.length > 6) {
var uglyDate = new Date(parseInt(date.substr(6)));
return uglyDate;
}
return "";
}
});
app.controller('XblBasicsController', function ($scope, $http, JsonCache, $window) {
$scope.xblGamesBasic = [];
$http.get('Content/json/_xblGamesBasic.xml.json', { cache: JsonCache }).success(function (data) {
$scope.xblGamesBasic = data.XblGamesBasic;
});
$scope.percentClass = function (percent) {
return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
};
$scope.extractDate = function (date) {
if (date.length > 6) {
var uglyDate = new Date(parseInt(date.substr(6)));
return uglyDate;
}
return "";
}
});
app.controller('PsnGameController', function ($scope, $http, JsonCache, $routeParams) {
$scope.test = [];
$scope.test.enabled = [];
var gameId = ($routeParams.gameId) ? ($routeParams.gameId) : "";
if (gameId != "") {
$http.get('Content/json/_psnGames.xml.json', { cache: JsonCache }).success(function (data) {
for (var i = 0; i < data.PsnGames.length; i++) {
if (data.PsnGames[i].Id == gameId) {
$scope.game = data.PsnGames[i];
$scope.test.additionalPoints = 0;
$scope.test.additionalAccomplishments = 0;
$scope.test.newPointsPercent = $scope.game.PointsPercentage;
$scope.test.newItemsPercent = $scope.game.TrophyPercentage;
$scope.graphicUrl = 'Content/images/psn/' + $scope.game.Id + '.png';
$scope.platform = $scope.game.Platform.replace("psp2", "PlayStation Vita").replace("ps3", "PlayStation 3").replace("ps4", "PlayStation 4").replace(",", ", ");
break;
}
}
});
}
$scope.testEnabled = function (itemId) {
if ($scope.test.enabled.indexOf(itemId) == -1) {
return "";
} else {
return "enabled";
}
};
$scope.testItem = function (trophy) {
if ($scope.test.enabled.indexOf(trophy.Id) == -1) {
$scope.test.additionalPoints += 1 * $scope.trophyTypeToPoints(trophy.Type);
$scope.test.additionalAccomplishments += 1;
$scope.test.enabled.push(trophy.Id);
} else {
$scope.test.additionalPoints -= 1 * $scope.trophyTypeToPoints(trophy.Type);
$scope.test.additionalAccomplishments -= 1;
$scope.test.enabled.splice($scope.test.enabled.indexOf(trophy.Id), 1);
}
$scope.test.newPointsPercent = Math.round(($scope.test.additionalPoints + $scope.game.EarnedPoints) / $scope.game.PossiblePoints * 100 * 1000) / 1000;
$scope.test.newItemsPercent = Math.round(($scope.test.additionalAccomplishments + $scope.game.EarnedTrophies) / $scope.game.PossibleTrophies * 100 * 1000) / 1000;
};
$scope.newPoints = function () {
if ($scope.test.additionalPoints == 0) {
return "";
} else {
return "(+" + $scope.test.additionalPoints + ")";
}
};
$scope.newItems = function () {
if ($scope.test.additionalAccomplishments == 0) {
return "";
} else {
return "(+" + $scope.test.additionalAccomplishments + ")";
}
};
$scope.percentClass = function (percent) {
return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
};
$scope.extractDate = function (date) {
if (date != null) {
var uglyDate = new Date(parseInt(date.substr(6)));
return uglyDate;
}
return "";
};
$scope.trophyTypeToPoints = function (trophyType) {
switch (trophyType) {
case "BRONZE":
return 15;
case "SILVER":
return 30;
case "GOLD":
return 90;
case "PLATINUM":
return 180;
default:
return 0;
}
};
$scope.wasEarned = function (accomplishment) {
return accomplishment.Earned != null;
};
$scope.notEarned = function (accomplishment) {
return accomplishment.Earned == null;
};
});
app.controller('XblGameController', function ($scope, $http, JsonCache, $routeParams) {
$scope.test = [];
$scope.test.enabled = [];
var gameId = ($routeParams.gameId) ? ($routeParams.gameId) : "";
if (gameId != "") {
$http.get('Content/json/_xblGames.xml.json', { cache: JsonCache }).success(function (data) {
for (var i = 0; i < data.XblGames.length; i++) {
if (data.XblGames[i].Id == gameId) {
$scope.game = data.XblGames[i];
$scope.test.additionalPoints = 0;
$scope.test.additionalAccomplishments = 0;
$scope.test.newPointsPercent = $scope.game.GamerscorePercentage;
$scope.test.newItemsPercent = $scope.game.AchievementPercentage;
$scope.graphicUrl = 'Content/images/xbl/' + $scope.game.Id + '.jpg';
break;
}
}
});
}
$scope.testEnabled = function (itemId) {
if ($scope.test.enabled.indexOf(itemId) == -1) {
return "";
} else {
return "enabled";
}
};
$scope.testItem = function (achievement) {
if ($scope.test.enabled.indexOf(achievement.Id) == -1) {
$scope.test.additionalPoints += 1 * achievement.GamerScore;
$scope.test.additionalAccomplishments += 1;
$scope.test.enabled.push(achievement.Id);
} else {
$scope.test.additionalPoints -= 1 * achievement.GamerScore;
$scope.test.additionalAccomplishments -= 1;
$scope.test.enabled.splice($scope.test.enabled.indexOf(achievement.Id), 1);
}
$scope.test.newPointsPercent = Math.round(($scope.test.additionalPoints + $scope.game.EarnedGamerScore) / $scope.game.PossibleGamerScore * 100 * 1000) / 1000;
$scope.test.newItemsPercent = Math.round(($scope.test.additionalAccomplishments + $scope.game.EarnedAchievements) / $scope.game.PossibleAchievements * 100 * 1000) / 1000;
};
$scope.newPoints = function () {
if ($scope.test.additionalPoints == 0) {
return "";
} else {
return "(+" + $scope.test.additionalPoints + ")";
}
};
$scope.newItems = function () {
if ($scope.test.additionalAccomplishments == 0) {
return "";
} else {
return "(+" + $scope.test.additionalAccomplishments + ")";
}
};
$scope.percentClass = function (percent) {
return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
};
$scope.extractDate = function (date) {
if (date != null) {
var uglyDate = new Date(parseInt(date.substr(6)));
return uglyDate;
}
return "";
}
$scope.secretTitle = function (accomplishment) {
return accomplishment.Title.length > 0 ? accomplishment.Title : "Secret achievement";
};
$scope.wasEarned = function (accomplishment) {
return accomplishment.Earned != null;
};
$scope.notEarned = function (accomplishment) {
return accomplishment.Earned == null;
};
});
app.controller('StatsController', function ($scope) { });
app.controller('NavbarController', function ($scope, $location) {
$scope.getClass = function (path) {
if ($location.path().substr(0, path.length) == path) {
return true
} else {
return false;
}
};
});
// From http://jsfiddle.net/2ZzZB/56/
app.filter('startFrom', function () {
return function (input, start) {
start = +start; //parse to int
return input.slice(start);
};
}); | SimpleWebsite/app/controllers/controllers.js | app.controller('HomeController', function ($scope) {
// todo not sure what I want on the page yet, since we didn't have it before
});
app.controller('GamesController', function ($scope, $http, JsonCache) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.games = [];
$scope.consoles = [];
$http.get('Content/json/VideoGames.json', { cache: JsonCache }).success(function (data) {
$scope.games = data.VideoGames;
for (var g = 0; g < data.VideoGames.length; g++) {
var console = data.VideoGames[g].System;
if ($scope.consoles.indexOf(console) == -1) {
$scope.consoles.push(console);
}
}
$scope.consoles.sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
});
$scope.numberOfPages = function () {
return Math.ceil($scope.games.length / $scope.pageSize);
};
});
app.controller('ProfileController', function ($scope, $route, $http, JsonCache, $templateCache, $window) {
var psnDataUrl = "Content/json/_psnProfile.xml.json";
var xblDataUrl = "Content/json/_xblProfile.xml.json";
var getPsnData = function () {
$http.get(psnDataUrl, { cache: JsonCache }).success(function (data) {
$scope.psnProfile = [];
$scope.psnProfile = data.PsnProfile;
$scope.psnPointsPercent = 100 * data.PsnProfile.Points / data.PsnProfile.PossiblePoints;
$scope.psnTrophiesPercent = 100 * data.PsnProfile.Trophies / data.PsnProfile.PossibleTrophies;
$scope.psnTrophiesBronzePercent = 100 * data.PsnProfile.TrophiesBronze / data.PsnProfile.PossibleTrophiesBronze;
$scope.psnTrophiesSilverPercent = 100 * data.PsnProfile.TrophiesSilver / data.PsnProfile.PossibleTrophiesSilver;
$scope.psnTrophiesGoldPercent = 100 * data.PsnProfile.TrophiesGold / data.PsnProfile.PossibleTrophiesGold;
$scope.psnTrophiesPlatinumPercent = 100 * data.PsnProfile.TrophiesPlatinum / data.PsnProfile.PossibleTrophiesPlatinum;
$scope.psnPointsGoal1 = $scope.percentGoal(data.PsnProfile.Points, data.PsnProfile.PossiblePoints, 1);
$scope.psnPointsGoal2 = $scope.percentGoal(data.PsnProfile.Points, data.PsnProfile.PossiblePoints, 2);
$scope.psnTrophiesGoal1 = $scope.percentGoal(data.PsnProfile.Trophies, data.PsnProfile.PossibleTrophies, 1);
$scope.psnTrophiesGoal2 = $scope.percentGoal(data.PsnProfile.Trophies, data.PsnProfile.PossibleTrophies, 2);
});
};
var getXblData = function () {
$http.get(xblDataUrl, { cache: JsonCache }).success(function (data) {
$scope.xblProfile = [];
$scope.xblProfile = data.XblProfile;
$scope.xblPointsPercent = 100 * data.XblProfile.GamerScore / data.XblProfile.PossibleGamerScore;
$scope.xblAchievementsPercent = 100 * data.XblProfile.Achievements / data.XblProfile.PossibleAchievements;
$scope.xblGamerscoreGoal1 = $scope.percentGoal(data.XblProfile.GamerScore, data.XblProfile.PossibleGamerScore, 1);
$scope.xblGamerscoreGoal2 = $scope.percentGoal(data.XblProfile.GamerScore, data.XblProfile.PossibleGamerScore, 2);
$scope.xblAchievementsGoal1 = $scope.percentGoal(data.XblProfile.Achievements, data.XblProfile.PossibleAchievements, 1);
$scope.xblAchievementsGoal2 = $scope.percentGoal(data.XblProfile.Achievements, data.XblProfile.PossibleAchievements, 2);
});
};
$scope.psnProfile = [];
$scope.xblProfile = [];
getPsnData();
getXblData();
$scope.percentClass = function (percent) {
return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
};
$scope.quantityToPercent = function (obtained, total, percent, outputType) {
if (total * percent / 100 <= obtained) {
return "";
} else {
var numberAtPercent = Math.ceil(total * percent / 100);
var trophyInfo = "";
if (outputType == "psnPoints") {
trophyInfo = $scope.trophiesToPointsGoal(numberAtPercent - obtained);
}
return percent + "% = " + numberAtPercent + " (" + (numberAtPercent - obtained) + trophyInfo + ")";
}
};
$scope.percentGoal = function (obtained, total, goal) {
var currentPercent = Math.floor(obtained / total * 100);
var goalPercent = 0;
if (goal == 1) {
// Goal one is the next percent.
for (var i = 1; i <= 100; i = i + 1) {
if (currentPercent < i) {
goalPercent = i;
break;
}
}
} else {
// Goal two is the next percent evently divisible by 5.
currentPercent = currentPercent + 1;
for (var i = 5; i <= 100; i = i + 5) {
if (currentPercent < i) {
goalPercent = i;
break;
}
}
}
return goalPercent;
};
$scope.trophiesToPointsGoal = function (goal) {
var output = "";
if (goal > 0) {
var bronze = 15, silver = 30, gold = 90;
var totalBronze = Math.round(goal / bronze);
var totalSilver = Math.round(goal / silver);
var totalGold = Math.round(goal / gold);
if (totalBronze > 0) {
output += " / " + totalBronze + " bronze";
if (totalSilver > 0) {
output += " | " + totalSilver + " silver";
if (totalGold > 0) {
output += " | " + totalGold + " gold";
}
}
}
}
return output;
};
//console.log($route);
//console.log($templateCache.info());
});
app.controller('BasicsController', function ($scope, $http, JsonCache, $window) {
$scope.psnGamesBasic = [];
$scope.xblGamesBasic = [];
$http.get('Content/json/_psnGamesBasic.xml.json', { cache: JsonCache }).success(function (data) {
$scope.psnGamesBasic = data.PsnGamesBasic;
});
$http.get('Content/json/_xblGamesBasic.xml.json', { cache: JsonCache }).success(function (data) {
$scope.xblGamesBasic = data.XblGamesBasic;
});
$scope.percentClass = function (percent) {
return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
};
$scope.extractDate = function (date) {
if (date.length > 6) {
var uglyDate = new Date(parseInt(date.substr(6)));
return uglyDate;
}
return "";
}
});
app.controller('PsnBasicsController', function ($scope, $http, JsonCache, $window) {
$scope.psnGamesBasic = [];
$http.get('Content/json/_psnGamesBasic.xml.json', { cache: JsonCache }).success(function (data) {
$scope.psnGamesBasic = data.PsnGamesBasic;
});
$scope.percentClass = function (percent) {
return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
};
$scope.extractDate = function (date) {
if (date.length > 6) {
var uglyDate = new Date(parseInt(date.substr(6)));
return uglyDate;
}
return "";
}
});
app.controller('XblBasicsController', function ($scope, $http, JsonCache, $window) {
$scope.xblGamesBasic = [];
$http.get('Content/json/_xblGamesBasic.xml.json', { cache: JsonCache }).success(function (data) {
$scope.xblGamesBasic = data.XblGamesBasic;
});
$scope.percentClass = function (percent) {
return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
};
$scope.extractDate = function (date) {
if (date.length > 6) {
var uglyDate = new Date(parseInt(date.substr(6)));
return uglyDate;
}
return "";
}
});
app.controller('PsnGameController', function ($scope, $http, JsonCache, $routeParams) {
$scope.test = [];
$scope.test.enabled = [];
var gameId = ($routeParams.gameId) ? ($routeParams.gameId) : "";
if (gameId != "") {
$http.get('Content/json/_psnGames.xml.json', { cache: JsonCache }).success(function (data) {
for (var i = 0; i < data.PsnGames.length; i++) {
if (data.PsnGames[i].Id == gameId) {
$scope.game = data.PsnGames[i];
$scope.test.additionalPoints = 0;
$scope.test.additionalAccomplishments = 0;
$scope.test.newPointsPercent = $scope.game.PointsPercentage;
$scope.test.newItemsPercent = $scope.game.TrophyPercentage;
$scope.graphicUrl = 'Content/images/psn/' + $scope.game.Id + '.png';
$scope.platform = $scope.game.Platform.replace("psp2", "PlayStation Vita").replace("ps3", "PlayStation 3").replace(",", ", ");
break;
}
}
});
}
$scope.testEnabled = function (itemId) {
if ($scope.test.enabled.indexOf(itemId) == -1) {
return "";
} else {
return "enabled";
}
};
$scope.testItem = function (trophy) {
if ($scope.test.enabled.indexOf(trophy.Id) == -1) {
$scope.test.additionalPoints += 1 * $scope.trophyTypeToPoints(trophy.Type);
$scope.test.additionalAccomplishments += 1;
$scope.test.enabled.push(trophy.Id);
} else {
$scope.test.additionalPoints -= 1 * $scope.trophyTypeToPoints(trophy.Type);
$scope.test.additionalAccomplishments -= 1;
$scope.test.enabled.splice($scope.test.enabled.indexOf(trophy.Id), 1);
}
$scope.test.newPointsPercent = Math.round(($scope.test.additionalPoints + $scope.game.EarnedPoints) / $scope.game.PossiblePoints * 100 * 1000) / 1000;
$scope.test.newItemsPercent = Math.round(($scope.test.additionalAccomplishments + $scope.game.EarnedTrophies) / $scope.game.PossibleTrophies * 100 * 1000) / 1000;
};
$scope.newPoints = function () {
if ($scope.test.additionalPoints == 0) {
return "";
} else {
return "(+" + $scope.test.additionalPoints + ")";
}
};
$scope.newItems = function () {
if ($scope.test.additionalAccomplishments == 0) {
return "";
} else {
return "(+" + $scope.test.additionalAccomplishments + ")";
}
};
$scope.percentClass = function (percent) {
return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
};
$scope.extractDate = function (date) {
if (date != null) {
var uglyDate = new Date(parseInt(date.substr(6)));
return uglyDate;
}
return "";
};
$scope.trophyTypeToPoints = function (trophyType) {
switch (trophyType) {
case "BRONZE":
return 15;
case "SILVER":
return 30;
case "GOLD":
return 90;
case "PLATINUM":
return 180;
default:
return 0;
}
};
$scope.wasEarned = function (accomplishment) {
return accomplishment.Earned != null;
};
$scope.notEarned = function (accomplishment) {
return accomplishment.Earned == null;
};
});
app.controller('XblGameController', function ($scope, $http, JsonCache, $routeParams) {
$scope.test = [];
$scope.test.enabled = [];
var gameId = ($routeParams.gameId) ? ($routeParams.gameId) : "";
if (gameId != "") {
$http.get('Content/json/_xblGames.xml.json', { cache: JsonCache }).success(function (data) {
for (var i = 0; i < data.XblGames.length; i++) {
if (data.XblGames[i].Id == gameId) {
$scope.game = data.XblGames[i];
$scope.test.additionalPoints = 0;
$scope.test.additionalAccomplishments = 0;
$scope.test.newPointsPercent = $scope.game.GamerscorePercentage;
$scope.test.newItemsPercent = $scope.game.AchievementPercentage;
$scope.graphicUrl = 'Content/images/xbl/' + $scope.game.Id + '.jpg';
break;
}
}
});
}
$scope.testEnabled = function (itemId) {
if ($scope.test.enabled.indexOf(itemId) == -1) {
return "";
} else {
return "enabled";
}
};
$scope.testItem = function (achievement) {
if ($scope.test.enabled.indexOf(achievement.Id) == -1) {
$scope.test.additionalPoints += 1 * achievement.GamerScore;
$scope.test.additionalAccomplishments += 1;
$scope.test.enabled.push(achievement.Id);
} else {
$scope.test.additionalPoints -= 1 * achievement.GamerScore;
$scope.test.additionalAccomplishments -= 1;
$scope.test.enabled.splice($scope.test.enabled.indexOf(achievement.Id), 1);
}
$scope.test.newPointsPercent = Math.round(($scope.test.additionalPoints + $scope.game.EarnedGamerScore) / $scope.game.PossibleGamerScore * 100 * 1000) / 1000;
$scope.test.newItemsPercent = Math.round(($scope.test.additionalAccomplishments + $scope.game.EarnedAchievements) / $scope.game.PossibleAchievements * 100 * 1000) / 1000;
};
$scope.newPoints = function () {
if ($scope.test.additionalPoints == 0) {
return "";
} else {
return "(+" + $scope.test.additionalPoints + ")";
}
};
$scope.newItems = function () {
if ($scope.test.additionalAccomplishments == 0) {
return "";
} else {
return "(+" + $scope.test.additionalAccomplishments + ")";
}
};
$scope.percentClass = function (percent) {
return { percent0: percent >= 0, percent25: percent >= 25, percent50: percent >= 50, percent75: percent >= 75, percent100: percent >= 100 }
};
$scope.extractDate = function (date) {
if (date != null) {
var uglyDate = new Date(parseInt(date.substr(6)));
return uglyDate;
}
return "";
}
$scope.secretTitle = function (accomplishment) {
return accomplishment.Title.length > 0 ? accomplishment.Title : "Secret achievement";
};
$scope.wasEarned = function (accomplishment) {
return accomplishment.Earned != null;
};
$scope.notEarned = function (accomplishment) {
return accomplishment.Earned == null;
};
});
app.controller('StatsController', function ($scope) { });
app.controller('NavbarController', function ($scope, $location) {
$scope.getClass = function (path) {
if ($location.path().substr(0, path.length) == path) {
return true
} else {
return false;
}
};
});
// From http://jsfiddle.net/2ZzZB/56/
app.filter('startFrom', function () {
return function (input, start) {
start = +start; //parse to int
return input.slice(start);
};
}); | Added PlayStation 4 platform support (simple replace for name).
| SimpleWebsite/app/controllers/controllers.js | Added PlayStation 4 platform support (simple replace for name). | <ide><path>impleWebsite/app/controllers/controllers.js
<ide> $scope.test.newPointsPercent = $scope.game.PointsPercentage;
<ide> $scope.test.newItemsPercent = $scope.game.TrophyPercentage;
<ide> $scope.graphicUrl = 'Content/images/psn/' + $scope.game.Id + '.png';
<del> $scope.platform = $scope.game.Platform.replace("psp2", "PlayStation Vita").replace("ps3", "PlayStation 3").replace(",", ", ");
<add> $scope.platform = $scope.game.Platform.replace("psp2", "PlayStation Vita").replace("ps3", "PlayStation 3").replace("ps4", "PlayStation 4").replace(",", ", ");
<ide> break;
<ide> }
<ide> } |
|
Java | mit | 50191a797d9d17b6aed90d6a97998d3e8ef3b9c5 | 0 | GlowstoneMC/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,GlowstoneMC/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus | package net.glowstone.block;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import net.glowstone.block.blocktype.BlockAnvil;
import net.glowstone.block.blocktype.BlockBanner;
import net.glowstone.block.blocktype.BlockBeacon;
import net.glowstone.block.blocktype.BlockBed;
import net.glowstone.block.blocktype.BlockBrewingStand;
import net.glowstone.block.blocktype.BlockButton;
import net.glowstone.block.blocktype.BlockCactus;
import net.glowstone.block.blocktype.BlockCarpet;
import net.glowstone.block.blocktype.BlockCarrot;
import net.glowstone.block.blocktype.BlockCauldron;
import net.glowstone.block.blocktype.BlockChest;
import net.glowstone.block.blocktype.BlockChorusFlower;
import net.glowstone.block.blocktype.BlockChorusPlant;
import net.glowstone.block.blocktype.BlockCocoa;
import net.glowstone.block.blocktype.BlockConcretePowder;
import net.glowstone.block.blocktype.BlockCrops;
import net.glowstone.block.blocktype.BlockDaylightDetector;
import net.glowstone.block.blocktype.BlockDeadBush;
import net.glowstone.block.blocktype.BlockDirectDrops;
import net.glowstone.block.blocktype.BlockDirt;
import net.glowstone.block.blocktype.BlockDispenser;
import net.glowstone.block.blocktype.BlockDoor;
import net.glowstone.block.blocktype.BlockDoublePlant;
import net.glowstone.block.blocktype.BlockDoubleSlab;
import net.glowstone.block.blocktype.BlockDropless;
import net.glowstone.block.blocktype.BlockDropper;
import net.glowstone.block.blocktype.BlockEnchantmentTable;
import net.glowstone.block.blocktype.BlockEndRod;
import net.glowstone.block.blocktype.BlockEnderChest;
import net.glowstone.block.blocktype.BlockEnderPortalFrame;
import net.glowstone.block.blocktype.BlockFalling;
import net.glowstone.block.blocktype.BlockFence;
import net.glowstone.block.blocktype.BlockFenceGate;
import net.glowstone.block.blocktype.BlockFire;
import net.glowstone.block.blocktype.BlockFlowerPot;
import net.glowstone.block.blocktype.BlockFurnace;
import net.glowstone.block.blocktype.BlockGrass;
import net.glowstone.block.blocktype.BlockGravel;
import net.glowstone.block.blocktype.BlockHay;
import net.glowstone.block.blocktype.BlockHopper;
import net.glowstone.block.blocktype.BlockHugeMushroom;
import net.glowstone.block.blocktype.BlockIce;
import net.glowstone.block.blocktype.BlockIronTrapDoor;
import net.glowstone.block.blocktype.BlockJukebox;
import net.glowstone.block.blocktype.BlockLadder;
import net.glowstone.block.blocktype.BlockLamp;
import net.glowstone.block.blocktype.BlockLava;
import net.glowstone.block.blocktype.BlockLeaves;
import net.glowstone.block.blocktype.BlockLever;
import net.glowstone.block.blocktype.BlockLitRedstoneOre;
import net.glowstone.block.blocktype.BlockLog;
import net.glowstone.block.blocktype.BlockLog2;
import net.glowstone.block.blocktype.BlockMagma;
import net.glowstone.block.blocktype.BlockMelon;
import net.glowstone.block.blocktype.BlockMobSpawner;
import net.glowstone.block.blocktype.BlockMonsterEgg;
import net.glowstone.block.blocktype.BlockMushroom;
import net.glowstone.block.blocktype.BlockMycel;
import net.glowstone.block.blocktype.BlockNeedsAttached;
import net.glowstone.block.blocktype.BlockNetherWart;
import net.glowstone.block.blocktype.BlockNote;
import net.glowstone.block.blocktype.BlockObserver;
import net.glowstone.block.blocktype.BlockOre;
import net.glowstone.block.blocktype.BlockPiston;
import net.glowstone.block.blocktype.BlockPotato;
import net.glowstone.block.blocktype.BlockPumpkin;
import net.glowstone.block.blocktype.BlockPumpkinBase;
import net.glowstone.block.blocktype.BlockPurpurPillar;
import net.glowstone.block.blocktype.BlockQuartz;
import net.glowstone.block.blocktype.BlockRails;
import net.glowstone.block.blocktype.BlockRandomDrops;
import net.glowstone.block.blocktype.BlockRedstone;
import net.glowstone.block.blocktype.BlockRedstoneComparator;
import net.glowstone.block.blocktype.BlockRedstoneOre;
import net.glowstone.block.blocktype.BlockRedstoneRepeater;
import net.glowstone.block.blocktype.BlockRedstoneTorch;
import net.glowstone.block.blocktype.BlockSapling;
import net.glowstone.block.blocktype.BlockSign;
import net.glowstone.block.blocktype.BlockSkull;
import net.glowstone.block.blocktype.BlockSlab;
import net.glowstone.block.blocktype.BlockSnow;
import net.glowstone.block.blocktype.BlockSnowBlock;
import net.glowstone.block.blocktype.BlockSoil;
import net.glowstone.block.blocktype.BlockSponge;
import net.glowstone.block.blocktype.BlockStairs;
import net.glowstone.block.blocktype.BlockStem;
import net.glowstone.block.blocktype.BlockStone;
import net.glowstone.block.blocktype.BlockSugarCane;
import net.glowstone.block.blocktype.BlockTallGrass;
import net.glowstone.block.blocktype.BlockTnt;
import net.glowstone.block.blocktype.BlockTorch;
import net.glowstone.block.blocktype.BlockType;
import net.glowstone.block.blocktype.BlockVine;
import net.glowstone.block.blocktype.BlockWater;
import net.glowstone.block.blocktype.BlockWeb;
import net.glowstone.block.blocktype.BlockWoodenTrapDoor;
import net.glowstone.block.blocktype.BlockWorkbench;
import net.glowstone.block.itemtype.ItemArmorStand;
import net.glowstone.block.itemtype.ItemBanner;
import net.glowstone.block.itemtype.ItemBoat;
import net.glowstone.block.itemtype.ItemBucket;
import net.glowstone.block.itemtype.ItemChorusFruit;
import net.glowstone.block.itemtype.ItemDye;
import net.glowstone.block.itemtype.ItemEndCrystal;
import net.glowstone.block.itemtype.ItemEnderPearl;
import net.glowstone.block.itemtype.ItemFilledBucket;
import net.glowstone.block.itemtype.ItemFirework;
import net.glowstone.block.itemtype.ItemFishCooked;
import net.glowstone.block.itemtype.ItemFishRaw;
import net.glowstone.block.itemtype.ItemFlintAndSteel;
import net.glowstone.block.itemtype.ItemFood;
import net.glowstone.block.itemtype.ItemFoodSeeds;
import net.glowstone.block.itemtype.ItemGoldenApple;
import net.glowstone.block.itemtype.ItemHoe;
import net.glowstone.block.itemtype.ItemItemFrame;
import net.glowstone.block.itemtype.ItemKnowledgeBook;
import net.glowstone.block.itemtype.ItemMilk;
import net.glowstone.block.itemtype.ItemMinecart;
import net.glowstone.block.itemtype.ItemPainting;
import net.glowstone.block.itemtype.ItemPlaceAs;
import net.glowstone.block.itemtype.ItemPoisonousPotato;
import net.glowstone.block.itemtype.ItemRawChicken;
import net.glowstone.block.itemtype.ItemRottenFlesh;
import net.glowstone.block.itemtype.ItemSeeds;
import net.glowstone.block.itemtype.ItemShovel;
import net.glowstone.block.itemtype.ItemSign;
import net.glowstone.block.itemtype.ItemSoup;
import net.glowstone.block.itemtype.ItemSpawn;
import net.glowstone.block.itemtype.ItemSpiderEye;
import net.glowstone.block.itemtype.ItemType;
import net.glowstone.block.itemtype.ItemWrittenBook;
import net.glowstone.entity.objects.GlowMinecart;
import net.glowstone.inventory.ToolType;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Sound;
import org.bukkit.TreeSpecies;
/**
* The lookup table for block and item types.
*/
public final class ItemTable {
private static final ItemTable INSTANCE = new ItemTable();
static {
INSTANCE.registerBuiltins();
}
private final EnumMap<Material, ItemType> materialToType = new EnumMap<>(Material.class);
private final Map<NamespacedKey, ItemType> extraTypes = new HashMap<>();
private int nextBlockId;
private int nextItemId;
////////////////////////////////////////////////////////////////////////////
// Data
private ItemTable() {
}
public static ItemTable instance() {
return INSTANCE;
}
////////////////////////////////////////////////////////////////////////////
// Registration
private void registerBuiltins() {
reg(Material.FLOWER_POT, new BlockFlowerPot());
reg(Material.JUKEBOX, new BlockJukebox());
reg(Material.NOTE_BLOCK, new BlockNote());
reg(Material.MOB_SPAWNER, new BlockMobSpawner());
reg(Material.MONSTER_EGGS, new BlockMonsterEgg());
reg(Material.DRAGON_EGG, new BlockFalling(Material.DRAGON_EGG));
reg(Material.SIGN_POST, new BlockSign(), Sound.BLOCK_WOOD_BREAK);
reg(Material.WALL_SIGN, new BlockSign(), Sound.BLOCK_WOOD_BREAK);
reg(Material.WORKBENCH, new BlockWorkbench(), Sound.BLOCK_WOOD_BREAK);
reg(Material.ENDER_CHEST, new BlockEnderChest());
reg(Material.CHEST, new BlockChest(), Sound.BLOCK_WOOD_BREAK);
reg(Material.TRAPPED_CHEST, new BlockChest(true), Sound.BLOCK_WOOD_BREAK);
reg(Material.DISPENSER, new BlockDispenser());
reg(Material.DROPPER, new BlockDropper());
reg(Material.BOOKSHELF, new BlockDirectDrops(Material.BOOK, 3), Sound.BLOCK_WOOD_BREAK);
reg(Material.CLAY, new BlockDirectDrops(Material.CLAY_BALL, 4), Sound.BLOCK_GRAVEL_BREAK);
reg(Material.HARD_CLAY, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.STAINED_CLAY, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.WOODEN_DOOR, new BlockDoor(Material.WOOD_DOOR), Sound.BLOCK_WOOD_BREAK);
reg(Material.IRON_DOOR_BLOCK, new BlockDoor(Material.IRON_DOOR));
reg(Material.SPRUCE_DOOR, new BlockDoor(Material.SPRUCE_DOOR_ITEM));
reg(Material.BIRCH_DOOR, new BlockDoor(Material.BIRCH_DOOR_ITEM));
reg(Material.JUNGLE_DOOR, new BlockDoor(Material.JUNGLE_DOOR_ITEM));
reg(Material.ACACIA_DOOR, new BlockDoor(Material.ACACIA_DOOR_ITEM));
reg(Material.DARK_OAK_DOOR, new BlockDoor(Material.DARK_OAK_DOOR_ITEM));
reg(Material.DOUBLE_STEP, new BlockDoubleSlab());
reg(Material.DOUBLE_STONE_SLAB2, new BlockDoubleSlab());
reg(Material.WOOD_DOUBLE_STEP, new BlockDoubleSlab(), Sound.BLOCK_WOOD_BREAK);
reg(Material.PURPUR_DOUBLE_SLAB, new BlockDoubleSlab());
reg(Material.SOIL, new BlockSoil(), Sound.BLOCK_GRAVEL_BREAK);
reg(Material.GLASS, new BlockDropless());
reg(Material.THIN_GLASS, new BlockDropless());
reg(Material.STAINED_GLASS, new BlockDropless());
reg(Material.STAINED_GLASS_PANE, new BlockDropless());
reg(Material.GLOWSTONE, new BlockRandomDrops(Material.GLOWSTONE_DUST, 2, 4));
reg(Material.MYCEL, new BlockMycel(), Sound.BLOCK_GRAVEL_BREAK);
reg(Material.GRASS, new BlockGrass(), Sound.BLOCK_GRASS_BREAK);
reg(Material.DIRT, new BlockDirt(), Sound.BLOCK_GRAVEL_BREAK);
reg(Material.GRAVEL, new BlockGravel(), Sound.BLOCK_GRAVEL_BREAK);
reg(Material.SAND, new BlockFalling(Material.SAND), Sound.BLOCK_SAND_BREAK);
reg(Material.ANVIL, new BlockAnvil());
reg(Material.ICE, new BlockIce());
reg(Material.PACKED_ICE, new BlockDropless());
reg(Material.SNOW, new BlockSnow(), Sound.BLOCK_SNOW_BREAK);
reg(Material.SNOW_BLOCK, new BlockSnowBlock(), Sound.BLOCK_SNOW_BREAK);
reg(Material.PRISMARINE, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.RED_SANDSTONE, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.SANDSTONE, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.NETHER_BRICK, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.NETHER_FENCE, new BlockFence(Material.NETHER_FENCE, ToolType.PICKAXE));
reg(Material.FENCE, new BlockFence(Material.FENCE));
reg(Material.NETHERRACK, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.IRON_FENCE, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.BRICK, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.SMOOTH_BRICK, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.ENDER_STONE, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.COBBLESTONE, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.COBBLE_WALL, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.MOSSY_COBBLESTONE, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.STONE, new BlockStone());
reg(Material.OBSIDIAN, new BlockDirectDrops(ToolType.DIAMOND_PICKAXE));
reg(Material.COAL_ORE, new BlockOre(Material.COAL, ToolType.PICKAXE));
reg(Material.COAL_BLOCK, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.IRON_ORE, new BlockDirectDrops(ToolType.STONE_PICKAXE));
reg(Material.IRON_BLOCK, new BlockDirectDrops(ToolType.STONE_PICKAXE));
reg(Material.GOLD_ORE, new BlockDirectDrops(ToolType.IRON_PICKAXE));
reg(Material.GOLD_BLOCK, new BlockDirectDrops(ToolType.IRON_PICKAXE));
reg(Material.DIAMOND_ORE, new BlockOre(Material.DIAMOND, ToolType.IRON_PICKAXE));
reg(Material.DIAMOND_BLOCK, new BlockDirectDrops(ToolType.IRON_PICKAXE));
reg(Material.EMERALD_ORE, new BlockOre(Material.EMERALD, ToolType.IRON_PICKAXE));
reg(Material.EMERALD_BLOCK, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.LAPIS_ORE, new BlockOre(Material.INK_SACK, ToolType.STONE_PICKAXE, 4, 4, 8));
reg(Material.LAPIS_BLOCK, new BlockDirectDrops(ToolType.STONE_PICKAXE));
reg(Material.QUARTZ_ORE, new BlockOre(Material.QUARTZ, ToolType.PICKAXE));
reg(Material.REDSTONE_ORE, new BlockRedstoneOre());
reg(Material.GLOWING_REDSTONE_ORE, new BlockLitRedstoneOre());
reg(Material.REDSTONE_BLOCK, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.CARROT, new BlockCarrot(), Sound.BLOCK_GRASS_BREAK);
reg(Material.COCOA, new BlockCocoa(), Sound.BLOCK_WOOD_BREAK);
reg(Material.DEAD_BUSH, new BlockDeadBush(), Sound.BLOCK_GRASS_BREAK);
reg(Material.LONG_GRASS, new BlockTallGrass(), Sound.BLOCK_GRASS_BREAK);
reg(Material.HUGE_MUSHROOM_1, new BlockHugeMushroom(true), Sound.BLOCK_WOOD_BREAK);
reg(Material.HUGE_MUSHROOM_2, new BlockHugeMushroom(false), Sound.BLOCK_WOOD_BREAK);
reg(Material.LEAVES, new BlockLeaves(), Sound.BLOCK_GRASS_BREAK);
reg(Material.LEAVES_2, new BlockLeaves(), Sound.BLOCK_GRASS_BREAK);
reg(Material.MELON_BLOCK, new BlockMelon(), Sound.BLOCK_WOOD_BREAK);
reg(Material.MELON_STEM, new BlockStem(Material.MELON_STEM), Sound.BLOCK_GRASS_BREAK);
reg(Material.NETHER_WARTS, new BlockNetherWart(), Sound.BLOCK_GRASS_BREAK);
reg(Material.POTATO, new BlockPotato(), Sound.BLOCK_GRASS_BREAK);
reg(Material.PUMPKIN_STEM, new BlockStem(Material.PUMPKIN_STEM), Sound.BLOCK_GRASS_BREAK);
reg(Material.CROPS, new BlockCrops(), Sound.BLOCK_GRASS_BREAK);
reg(Material.CAKE_BLOCK, new BlockDropless(), Sound.BLOCK_CLOTH_BREAK);
reg(Material.WEB, new BlockWeb());
reg(Material.FIRE, new BlockFire());
reg(Material.ENDER_PORTAL_FRAME, new BlockEnderPortalFrame());
reg(Material.FENCE_GATE, new BlockFenceGate());
reg(Material.ACACIA_FENCE_GATE, new BlockFenceGate());
reg(Material.BIRCH_FENCE_GATE, new BlockFenceGate());
reg(Material.DARK_OAK_FENCE_GATE, new BlockFenceGate());
reg(Material.JUNGLE_FENCE_GATE, new BlockFenceGate());
reg(Material.SPRUCE_FENCE_GATE, new BlockFenceGate());
reg(Material.TRAP_DOOR, new BlockWoodenTrapDoor(), Sound.BLOCK_WOOD_BREAK);
reg(Material.IRON_TRAPDOOR, new BlockIronTrapDoor());
reg(Material.FURNACE, new BlockFurnace());
reg(Material.BURNING_FURNACE, new BlockFurnace());
reg(Material.LEVER, new BlockLever());
reg(Material.HOPPER, new BlockHopper());
reg(Material.PISTON_BASE, new BlockPiston(false));
reg(Material.PISTON_STICKY_BASE, new BlockPiston(true));
reg(Material.ACACIA_STAIRS, new BlockStairs());
reg(Material.BIRCH_WOOD_STAIRS, new BlockStairs(), Sound.BLOCK_WOOD_BREAK);
reg(Material.BRICK_STAIRS, new BlockStairs());
reg(Material.COBBLESTONE_STAIRS, new BlockStairs());
reg(Material.DARK_OAK_STAIRS, new BlockStairs());
reg(Material.JUNGLE_WOOD_STAIRS, new BlockStairs(), Sound.BLOCK_WOOD_BREAK);
reg(Material.NETHER_BRICK_STAIRS, new BlockStairs());
reg(Material.QUARTZ_STAIRS, new BlockStairs());
reg(Material.SANDSTONE_STAIRS, new BlockStairs());
reg(Material.RED_SANDSTONE_STAIRS, new BlockStairs());
reg(Material.SPRUCE_WOOD_STAIRS, new BlockStairs(), Sound.BLOCK_WOOD_BREAK);
reg(Material.SMOOTH_STAIRS, new BlockStairs());
reg(Material.WOOD_STAIRS, new BlockStairs(), Sound.BLOCK_WOOD_BREAK);
reg(Material.PURPUR_STAIRS, new BlockStairs());
reg(Material.STEP, new BlockSlab());
reg(Material.WOOD_STEP, new BlockSlab(), Sound.BLOCK_WOOD_BREAK);
reg(Material.STONE_SLAB2, new BlockSlab());
reg(Material.PURPUR_SLAB, new BlockSlab());
reg(Material.HAY_BLOCK, new BlockHay());
reg(Material.QUARTZ_BLOCK, new BlockQuartz());
reg(Material.LOG, new BlockLog(), Sound.BLOCK_WOOD_BREAK);
reg(Material.LOG_2, new BlockLog2(), Sound.BLOCK_WOOD_BREAK);
reg(Material.LADDER, new BlockLadder(), Sound.BLOCK_WOOD_BREAK);
reg(Material.VINE, new BlockVine());
reg(Material.STONE_BUTTON, new BlockButton(Material.STONE_BUTTON));
reg(Material.WOOD_BUTTON, new BlockButton(Material.WOOD_BUTTON), Sound.BLOCK_WOOD_BREAK);
reg(Material.BED_BLOCK, new BlockBed());
reg(Material.SKULL, new BlockSkull());
reg(Material.TORCH, new BlockTorch());
reg(Material.GOLD_PLATE, new BlockDirectDrops(Material.GOLD_PLATE, ToolType.PICKAXE));
reg(Material.IRON_PLATE, new BlockDirectDrops(Material.IRON_PLATE, ToolType.PICKAXE));
reg(Material.STONE_PLATE, new BlockDirectDrops(Material.STONE_PLATE, ToolType.PICKAXE));
reg(Material.DAYLIGHT_DETECTOR, new BlockDaylightDetector());
reg(Material.DAYLIGHT_DETECTOR_INVERTED, new BlockDaylightDetector());
reg(Material.YELLOW_FLOWER, new BlockNeedsAttached());
reg(Material.RED_ROSE, new BlockNeedsAttached());
reg(Material.BROWN_MUSHROOM, new BlockMushroom(Material.BROWN_MUSHROOM));
reg(Material.RED_MUSHROOM, new BlockMushroom(Material.RED_MUSHROOM));
reg(Material.SUGAR_CANE_BLOCK, new BlockSugarCane(), Sound.BLOCK_GRASS_BREAK);
reg(Material.SAPLING, new BlockSapling());
reg(Material.RAILS, new BlockRails());
reg(Material.ACTIVATOR_RAIL, new BlockRails());
reg(Material.DETECTOR_RAIL, new BlockRails());
reg(Material.POWERED_RAIL, new BlockRails());
reg(Material.CARPET, new BlockCarpet(), Sound.BLOCK_CLOTH_BREAK);
reg(Material.ENCHANTMENT_TABLE, new BlockEnchantmentTable());
reg(Material.BREWING_STAND, new BlockBrewingStand());
reg(Material.CACTUS, new BlockCactus());
reg(Material.WATER, new BlockWater());
reg(Material.STATIONARY_WATER, new BlockWater());
reg(Material.LAVA, new BlockLava());
reg(Material.STATIONARY_LAVA, new BlockLava());
reg(Material.CAULDRON, new BlockCauldron());
reg(Material.STANDING_BANNER, new BlockBanner());
reg(Material.WALL_BANNER, new BlockBanner());
reg(Material.SPONGE, new BlockSponge());
reg(Material.TNT, new BlockTnt());
reg(Material.DOUBLE_PLANT, new BlockDoublePlant());
reg(Material.PUMPKIN, new BlockPumpkin());
reg(Material.JACK_O_LANTERN, new BlockPumpkinBase(Material.JACK_O_LANTERN));
reg(Material.SEA_LANTERN, new BlockRandomDrops(Material.PRISMARINE_CRYSTALS, 2, 3));
reg(Material.REDSTONE_LAMP_ON, new BlockLamp());
reg(Material.REDSTONE_LAMP_OFF, new BlockLamp());
reg(Material.REDSTONE_WIRE, new BlockRedstone());
reg(Material.REDSTONE_TORCH_ON, new BlockRedstoneTorch());
reg(Material.REDSTONE_TORCH_OFF, new BlockRedstoneTorch());
reg(Material.DIODE_BLOCK_ON, new BlockRedstoneRepeater());
reg(Material.DIODE_BLOCK_OFF, new BlockRedstoneRepeater());
reg(Material.MAGMA, new BlockMagma());
reg(Material.NETHER_WART_BLOCK, new BlockDirectDrops(Material.NETHER_WART_BLOCK, ToolType
.AXE));
reg(Material.RED_NETHER_BRICK, new BlockDirectDrops(Material.RED_NETHER_BRICK, ToolType
.PICKAXE));
reg(Material.BONE_BLOCK, new BlockDirectDrops(Material.BONE_BLOCK, ToolType.PICKAXE));
reg(Material.OBSERVER, new BlockObserver());
reg(Material.REDSTONE_COMPARATOR_ON, new BlockRedstoneComparator());
reg(Material.REDSTONE_COMPARATOR_OFF, new BlockRedstoneComparator());
reg(Material.BEACON, new BlockBeacon());
reg(Material.PURPUR_PILLAR, new BlockPurpurPillar());
reg(Material.PURPUR_BLOCK, new BlockDirectDrops(Material.PURPUR_BLOCK, ToolType.PICKAXE));
reg(Material.END_ROD, new BlockEndRod());
reg(Material.CONCRETE, new BlockDirectDrops(Material.CONCRETE));
reg(Material.CONCRETE_POWDER, new BlockConcretePowder());
reg(Material.WHITE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
.WHITE_GLAZED_TERRACOTTA));
reg(Material.BLACK_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
.BLACK_GLAZED_TERRACOTTA));
reg(Material.BLUE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.BLUE_GLAZED_TERRACOTTA));
reg(Material.BROWN_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
.BROWN_GLAZED_TERRACOTTA));
reg(Material.CYAN_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.CYAN_GLAZED_TERRACOTTA));
reg(Material.GRAY_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.GRAY_GLAZED_TERRACOTTA));
reg(Material.GREEN_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
.GREEN_GLAZED_TERRACOTTA));
reg(Material.LIGHT_BLUE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
.LIGHT_BLUE_GLAZED_TERRACOTTA));
reg(Material.LIME_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.LIME_GLAZED_TERRACOTTA));
reg(Material.MAGENTA_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
.MAGENTA_GLAZED_TERRACOTTA));
reg(Material.ORANGE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
.ORANGE_GLAZED_TERRACOTTA));
reg(Material.PINK_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.PINK_GLAZED_TERRACOTTA));
reg(Material.PURPLE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
.PURPLE_GLAZED_TERRACOTTA));
reg(Material.RED_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.RED_GLAZED_TERRACOTTA));
reg(Material.SILVER_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
.SILVER_GLAZED_TERRACOTTA));
reg(Material.YELLOW_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
.YELLOW_GLAZED_TERRACOTTA));
reg(Material.CHORUS_FLOWER, new BlockChorusFlower());
reg(Material.CHORUS_PLANT, new BlockChorusPlant());
reg(Material.FLINT_AND_STEEL, new ItemFlintAndSteel());
reg(Material.SIGN, new ItemSign());
reg(Material.REDSTONE, new ItemPlaceAs(Material.REDSTONE_WIRE));
reg(Material.SUGAR_CANE, new ItemPlaceAs(Material.SUGAR_CANE_BLOCK));
reg(Material.DIODE, new ItemPlaceAs(Material.DIODE_BLOCK_OFF));
reg(Material.BREWING_STAND_ITEM, new ItemPlaceAs(Material.BREWING_STAND));
reg(Material.CAULDRON_ITEM, new ItemPlaceAs(Material.CAULDRON));
reg(Material.FLOWER_POT_ITEM, new ItemPlaceAs(Material.FLOWER_POT));
reg(Material.SKULL_ITEM, new ItemPlaceAs(Material.SKULL));
reg(Material.REDSTONE_COMPARATOR, new ItemPlaceAs(Material.REDSTONE_COMPARATOR_OFF));
reg(Material.BED, new ItemPlaceAs(Material.BED_BLOCK));
reg(Material.BUCKET, new ItemBucket());
reg(Material.WATER_BUCKET, new ItemFilledBucket(Material.WATER));
reg(Material.LAVA_BUCKET, new ItemFilledBucket(Material.LAVA));
reg(Material.WOOD_HOE, new ItemHoe());
reg(Material.STONE_HOE, new ItemHoe());
reg(Material.IRON_HOE, new ItemHoe());
reg(Material.GOLD_HOE, new ItemHoe());
reg(Material.DIAMOND_HOE, new ItemHoe());
reg(Material.WOOD_SPADE, new ItemShovel());
reg(Material.STONE_SPADE, new ItemShovel());
reg(Material.IRON_SPADE, new ItemShovel());
reg(Material.GOLD_SPADE, new ItemShovel());
reg(Material.DIAMOND_SPADE, new ItemShovel());
reg(Material.MONSTER_EGG, new ItemSpawn());
reg(Material.SEEDS, new ItemSeeds(Material.CROPS, Material.SOIL));
reg(Material.MELON_SEEDS, new ItemSeeds(Material.MELON_STEM, Material.SOIL));
reg(Material.PUMPKIN_SEEDS, new ItemSeeds(Material.PUMPKIN_STEM, Material.SOIL));
reg(Material.NETHER_STALK, new ItemSeeds(Material.NETHER_WARTS, Material.SOUL_SAND));
reg(Material.CARROT_ITEM, new ItemFoodSeeds(Material.CARROT, Material.SOIL, 3, 3.6f));
reg(Material.POTATO_ITEM, new ItemFoodSeeds(Material.POTATO, Material.SOIL, 1, 0.6f));
reg(Material.INK_SACK, new ItemDye());
reg(Material.BANNER, new ItemBanner());
reg(Material.WOOD_DOOR, new ItemPlaceAs(Material.WOODEN_DOOR));
reg(Material.IRON_DOOR, new ItemPlaceAs(Material.IRON_DOOR_BLOCK));
reg(Material.SPRUCE_DOOR_ITEM, new ItemPlaceAs(Material.SPRUCE_DOOR));
reg(Material.BIRCH_DOOR_ITEM, new ItemPlaceAs(Material.BIRCH_DOOR));
reg(Material.JUNGLE_DOOR_ITEM, new ItemPlaceAs(Material.JUNGLE_DOOR));
reg(Material.ACACIA_DOOR_ITEM, new ItemPlaceAs(Material.ACACIA_DOOR));
reg(Material.DARK_OAK_DOOR_ITEM, new ItemPlaceAs(Material.DARK_OAK_DOOR));
reg(Material.WRITTEN_BOOK, new ItemWrittenBook());
reg(Material.ITEM_FRAME, new ItemItemFrame());
reg(Material.APPLE, new ItemFood(4, 2.4f));
reg(Material.BAKED_POTATO, new ItemFood(5, 6f));
reg(Material.BREAD, new ItemFood(5, 6f));
reg(Material.COOKED_CHICKEN, new ItemFood(6, 7.2f));
reg(Material.COOKED_FISH, new ItemFishCooked());
reg(Material.COOKED_MUTTON, new ItemFood(6, 9.6f));
reg(Material.COOKED_BEEF, new ItemFood(8, 12.8f));
reg(Material.COOKED_RABBIT, new ItemFood(5, 6f));
reg(Material.COOKIE, new ItemFood(2, 0.4f));
reg(Material.GOLDEN_APPLE, new ItemGoldenApple());
reg(Material.GOLDEN_CARROT, new ItemFood(6, 14.4f));
reg(Material.GRILLED_PORK, new ItemFood(8, 12.8f));
reg(Material.MELON, new ItemFood(2, 1.2f));
reg(Material.BEETROOT, new ItemFood(1, 1.2f));
reg(Material.BEETROOT_SOUP, new ItemSoup(6, 7.2f));
reg(Material.MUSHROOM_SOUP, new ItemSoup(6, 7.2f));
reg(Material.POISONOUS_POTATO, new ItemPoisonousPotato());
reg(Material.PUMPKIN_PIE, new ItemFood(8, 4.8f));
reg(Material.RABBIT_STEW, new ItemSoup(10, 12f));
reg(Material.RAW_BEEF, new ItemFood(3, 1.8f));
reg(Material.RAW_CHICKEN, new ItemRawChicken());
reg(Material.RAW_FISH, new ItemFishRaw());
reg(Material.MUTTON, new ItemFood(2, 1.2f));
reg(Material.PORK, new ItemFood(3, 1.8f));
reg(Material.RABBIT, new ItemFood(3, 1.8f));
reg(Material.ROTTEN_FLESH, new ItemRottenFlesh());
reg(Material.SPIDER_EYE, new ItemSpiderEye());
reg(Material.CHORUS_FRUIT, new ItemChorusFruit());
reg(Material.ARMOR_STAND, new ItemArmorStand());
reg(Material.MILK_BUCKET, new ItemMilk());
reg(Material.MINECART, new ItemMinecart(GlowMinecart.MinecartType.RIDEABLE));
reg(Material.COMMAND_MINECART, new ItemMinecart(GlowMinecart.MinecartType.COMMAND));
reg(Material.EXPLOSIVE_MINECART, new ItemMinecart(GlowMinecart.MinecartType.TNT));
reg(Material.HOPPER_MINECART, new ItemMinecart(GlowMinecart.MinecartType.HOPPER));
reg(Material.POWERED_MINECART, new ItemMinecart(GlowMinecart.MinecartType.FURNACE));
reg(Material.STORAGE_MINECART, new ItemMinecart(GlowMinecart.MinecartType.CHEST));
reg(Material.END_CRYSTAL, new ItemEndCrystal());
reg(Material.BOAT, new ItemBoat(TreeSpecies.GENERIC));
reg(Material.BOAT_SPRUCE, new ItemBoat(TreeSpecies.REDWOOD));
reg(Material.BOAT_BIRCH, new ItemBoat(TreeSpecies.BIRCH));
reg(Material.BOAT_JUNGLE, new ItemBoat(TreeSpecies.JUNGLE));
reg(Material.BOAT_ACACIA, new ItemBoat(TreeSpecies.ACACIA));
reg(Material.BOAT_DARK_OAK, new ItemBoat(TreeSpecies.DARK_OAK));
reg(Material.PAINTING, new ItemPainting());
reg(Material.FIREWORK, new ItemFirework());
reg(Material.ENDER_PEARL, new ItemEnderPearl());
reg(Material.KNOWLEDGE_BOOK, new ItemKnowledgeBook());
}
private void reg(Material material, ItemType type) {
if (material.isBlock() != type instanceof BlockType) {
throw new IllegalArgumentException(
"Cannot mismatch item and block: " + material + ", " + type);
}
if (materialToType.containsKey(material)) {
throw new IllegalArgumentException(
"Cannot use " + type + " for " + material + ", is already " + materialToType
.get(material));
}
materialToType.put(material, type);
type.setMaterial(material);
if (material.isBlock()) {
nextBlockId = Math.max(nextBlockId, material.getId() + 1);
if (type.getClass() != BlockType.class) {
((BlockType) type).setPlaceSound(Sound.BLOCK_STONE_BREAK);
}
} else {
nextItemId = Math.max(nextItemId, material.getId() + 1);
}
}
private void reg(Material material, ItemType type, Sound sound) {
if (material.isBlock() != type instanceof BlockType) {
throw new IllegalArgumentException(
"Cannot mismatch item and block: " + material + ", " + type);
}
if (materialToType.containsKey(material)) {
throw new IllegalArgumentException(
"Cannot use " + type + " for " + material + ", is already " + materialToType
.get(material));
}
materialToType.put(material, type);
type.setMaterial(material);
if (material.isBlock()) {
nextBlockId = Math.max(nextBlockId, material.getId() + 1);
((BlockType) type).setPlaceSound(sound);
} else {
nextItemId = Math.max(nextItemId, material.getId() + 1);
}
}
/**
* Register a new, non-Vanilla ItemType. It will be assigned an ID automatically.
*
* @param key the namespaced key of the ItemType
* @param type the ItemType to register.
* @return if the registration was successful
*/
public boolean register(NamespacedKey key, ItemType type) {
int id;
boolean block = type instanceof BlockType;
if (block) {
id = nextBlockId;
} else {
id = nextItemId;
}
if (extraTypes.putIfAbsent(key, type) == null) {
type.setId(id);
if (block) {
nextBlockId++;
} else {
nextItemId++;
}
return true;
} else {
return false;
}
}
private ItemType createDefault(Material material) {
if (material == null || material == Material.AIR) {
return null;
}
ItemType result;
if (material.isBlock()) {
result = new BlockType();
} else {
result = new ItemType();
}
reg(material, result);
return result;
}
////////////////////////////////////////////////////////////////////////////
// Type access
@Deprecated
public ItemType getItem(int id) {
return getItem(Material.getMaterial(id));
}
/**
* Returns the {@link ItemType} for a {@link Material}, or null if not a block.
*
* @param mat a {@link Material}
* @return {@code mat} as an {@link ItemType}
*/
public ItemType getItem(Material mat) {
ItemType type = materialToType.get(mat);
if (type == null) {
type = createDefault(mat);
}
return type;
}
@Deprecated
public BlockType getBlock(int id) {
return getBlock(Material.getMaterial(id));
}
/**
* Returns the {@link BlockType} for a {@link Material}, or null if not a block.
*
* @param mat a {@link Material}
* @return {@code mat} as a {@link BlockType}, or null if {@code mat} isn't a block
*/
public BlockType getBlock(Material mat) {
ItemType itemType = getItem(mat);
if (itemType instanceof BlockType) {
return (BlockType) itemType;
}
return null;
}
}
| src/main/java/net/glowstone/block/ItemTable.java | package net.glowstone.block;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import net.glowstone.block.blocktype.BlockAnvil;
import net.glowstone.block.blocktype.BlockBanner;
import net.glowstone.block.blocktype.BlockBeacon;
import net.glowstone.block.blocktype.BlockBed;
import net.glowstone.block.blocktype.BlockBrewingStand;
import net.glowstone.block.blocktype.BlockButton;
import net.glowstone.block.blocktype.BlockCactus;
import net.glowstone.block.blocktype.BlockCarpet;
import net.glowstone.block.blocktype.BlockCarrot;
import net.glowstone.block.blocktype.BlockCauldron;
import net.glowstone.block.blocktype.BlockChest;
import net.glowstone.block.blocktype.BlockChorusFlower;
import net.glowstone.block.blocktype.BlockChorusPlant;
import net.glowstone.block.blocktype.BlockCocoa;
import net.glowstone.block.blocktype.BlockConcretePowder;
import net.glowstone.block.blocktype.BlockCrops;
import net.glowstone.block.blocktype.BlockDaylightDetector;
import net.glowstone.block.blocktype.BlockDeadBush;
import net.glowstone.block.blocktype.BlockDirectDrops;
import net.glowstone.block.blocktype.BlockDirt;
import net.glowstone.block.blocktype.BlockDispenser;
import net.glowstone.block.blocktype.BlockDoor;
import net.glowstone.block.blocktype.BlockDoublePlant;
import net.glowstone.block.blocktype.BlockDoubleSlab;
import net.glowstone.block.blocktype.BlockDropless;
import net.glowstone.block.blocktype.BlockDropper;
import net.glowstone.block.blocktype.BlockEnchantmentTable;
import net.glowstone.block.blocktype.BlockEndRod;
import net.glowstone.block.blocktype.BlockEnderChest;
import net.glowstone.block.blocktype.BlockEnderPortalFrame;
import net.glowstone.block.blocktype.BlockFalling;
import net.glowstone.block.blocktype.BlockFence;
import net.glowstone.block.blocktype.BlockFenceGate;
import net.glowstone.block.blocktype.BlockFire;
import net.glowstone.block.blocktype.BlockFlowerPot;
import net.glowstone.block.blocktype.BlockFurnace;
import net.glowstone.block.blocktype.BlockGrass;
import net.glowstone.block.blocktype.BlockGravel;
import net.glowstone.block.blocktype.BlockHay;
import net.glowstone.block.blocktype.BlockHopper;
import net.glowstone.block.blocktype.BlockHugeMushroom;
import net.glowstone.block.blocktype.BlockIce;
import net.glowstone.block.blocktype.BlockIronTrapDoor;
import net.glowstone.block.blocktype.BlockJukebox;
import net.glowstone.block.blocktype.BlockLadder;
import net.glowstone.block.blocktype.BlockLamp;
import net.glowstone.block.blocktype.BlockLava;
import net.glowstone.block.blocktype.BlockLeaves;
import net.glowstone.block.blocktype.BlockLever;
import net.glowstone.block.blocktype.BlockLitRedstoneOre;
import net.glowstone.block.blocktype.BlockLog;
import net.glowstone.block.blocktype.BlockLog2;
import net.glowstone.block.blocktype.BlockMagma;
import net.glowstone.block.blocktype.BlockMelon;
import net.glowstone.block.blocktype.BlockMobSpawner;
import net.glowstone.block.blocktype.BlockMonsterEgg;
import net.glowstone.block.blocktype.BlockMushroom;
import net.glowstone.block.blocktype.BlockMycel;
import net.glowstone.block.blocktype.BlockNeedsAttached;
import net.glowstone.block.blocktype.BlockNetherWart;
import net.glowstone.block.blocktype.BlockNote;
import net.glowstone.block.blocktype.BlockObserver;
import net.glowstone.block.blocktype.BlockOre;
import net.glowstone.block.blocktype.BlockPiston;
import net.glowstone.block.blocktype.BlockPotato;
import net.glowstone.block.blocktype.BlockPumpkin;
import net.glowstone.block.blocktype.BlockPumpkinBase;
import net.glowstone.block.blocktype.BlockPurpurPillar;
import net.glowstone.block.blocktype.BlockQuartz;
import net.glowstone.block.blocktype.BlockRails;
import net.glowstone.block.blocktype.BlockRandomDrops;
import net.glowstone.block.blocktype.BlockRedstone;
import net.glowstone.block.blocktype.BlockRedstoneComparator;
import net.glowstone.block.blocktype.BlockRedstoneOre;
import net.glowstone.block.blocktype.BlockRedstoneRepeater;
import net.glowstone.block.blocktype.BlockRedstoneTorch;
import net.glowstone.block.blocktype.BlockSapling;
import net.glowstone.block.blocktype.BlockSign;
import net.glowstone.block.blocktype.BlockSkull;
import net.glowstone.block.blocktype.BlockSlab;
import net.glowstone.block.blocktype.BlockSnow;
import net.glowstone.block.blocktype.BlockSnowBlock;
import net.glowstone.block.blocktype.BlockSoil;
import net.glowstone.block.blocktype.BlockSponge;
import net.glowstone.block.blocktype.BlockStairs;
import net.glowstone.block.blocktype.BlockStem;
import net.glowstone.block.blocktype.BlockStone;
import net.glowstone.block.blocktype.BlockSugarCane;
import net.glowstone.block.blocktype.BlockTallGrass;
import net.glowstone.block.blocktype.BlockTnt;
import net.glowstone.block.blocktype.BlockTorch;
import net.glowstone.block.blocktype.BlockType;
import net.glowstone.block.blocktype.BlockVine;
import net.glowstone.block.blocktype.BlockWater;
import net.glowstone.block.blocktype.BlockWeb;
import net.glowstone.block.blocktype.BlockWoodenTrapDoor;
import net.glowstone.block.blocktype.BlockWorkbench;
import net.glowstone.block.itemtype.ItemArmorStand;
import net.glowstone.block.itemtype.ItemBanner;
import net.glowstone.block.itemtype.ItemBoat;
import net.glowstone.block.itemtype.ItemBucket;
import net.glowstone.block.itemtype.ItemChorusFruit;
import net.glowstone.block.itemtype.ItemDye;
import net.glowstone.block.itemtype.ItemEndCrystal;
import net.glowstone.block.itemtype.ItemEnderPearl;
import net.glowstone.block.itemtype.ItemFilledBucket;
import net.glowstone.block.itemtype.ItemFirework;
import net.glowstone.block.itemtype.ItemFishCooked;
import net.glowstone.block.itemtype.ItemFishRaw;
import net.glowstone.block.itemtype.ItemFlintAndSteel;
import net.glowstone.block.itemtype.ItemFood;
import net.glowstone.block.itemtype.ItemFoodSeeds;
import net.glowstone.block.itemtype.ItemGoldenApple;
import net.glowstone.block.itemtype.ItemHoe;
import net.glowstone.block.itemtype.ItemItemFrame;
import net.glowstone.block.itemtype.ItemKnowledgeBook;
import net.glowstone.block.itemtype.ItemMilk;
import net.glowstone.block.itemtype.ItemMinecart;
import net.glowstone.block.itemtype.ItemPainting;
import net.glowstone.block.itemtype.ItemPlaceAs;
import net.glowstone.block.itemtype.ItemPoisonousPotato;
import net.glowstone.block.itemtype.ItemRawChicken;
import net.glowstone.block.itemtype.ItemRottenFlesh;
import net.glowstone.block.itemtype.ItemSeeds;
import net.glowstone.block.itemtype.ItemShovel;
import net.glowstone.block.itemtype.ItemSign;
import net.glowstone.block.itemtype.ItemSoup;
import net.glowstone.block.itemtype.ItemSpawn;
import net.glowstone.block.itemtype.ItemSpiderEye;
import net.glowstone.block.itemtype.ItemType;
import net.glowstone.block.itemtype.ItemWrittenBook;
import net.glowstone.entity.objects.GlowMinecart;
import net.glowstone.inventory.ToolType;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Sound;
import org.bukkit.TreeSpecies;
/**
* The lookup table for block and item types.
*/
public final class ItemTable {
private static final ItemTable INSTANCE = new ItemTable();
static {
INSTANCE.registerBuiltins();
}
private final EnumMap<Material, ItemType> materialToType = new EnumMap<>(Material.class);
private final Map<NamespacedKey, ItemType> extraTypes = new HashMap<>();
private int nextBlockId;
private int nextItemId;
////////////////////////////////////////////////////////////////////////////
// Data
private ItemTable() {
}
public static ItemTable instance() {
return INSTANCE;
}
////////////////////////////////////////////////////////////////////////////
// Registration
private void registerBuiltins() {
reg(Material.FLOWER_POT, new BlockFlowerPot());
reg(Material.JUKEBOX, new BlockJukebox());
reg(Material.NOTE_BLOCK, new BlockNote());
reg(Material.MOB_SPAWNER, new BlockMobSpawner());
reg(Material.MONSTER_EGGS, new BlockMonsterEgg());
reg(Material.DRAGON_EGG, new BlockFalling(Material.DRAGON_EGG));
reg(Material.SIGN_POST, new BlockSign(), Sound.BLOCK_WOOD_BREAK);
reg(Material.WALL_SIGN, new BlockSign(), Sound.BLOCK_WOOD_BREAK);
reg(Material.WORKBENCH, new BlockWorkbench(), Sound.BLOCK_WOOD_BREAK);
reg(Material.ENDER_CHEST, new BlockEnderChest());
reg(Material.CHEST, new BlockChest(), Sound.BLOCK_WOOD_BREAK);
reg(Material.TRAPPED_CHEST, new BlockChest(true), Sound.BLOCK_WOOD_BREAK);
reg(Material.DISPENSER, new BlockDispenser());
reg(Material.DROPPER, new BlockDropper());
reg(Material.BOOKSHELF, new BlockDirectDrops(Material.BOOK, 3), Sound.BLOCK_WOOD_BREAK);
reg(Material.CLAY, new BlockDirectDrops(Material.CLAY_BALL, 4), Sound.BLOCK_GRAVEL_BREAK);
reg(Material.HARD_CLAY, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.STAINED_CLAY, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.WOODEN_DOOR, new BlockDoor(Material.WOOD_DOOR), Sound.BLOCK_WOOD_BREAK);
reg(Material.IRON_DOOR_BLOCK, new BlockDoor(Material.IRON_DOOR));
reg(Material.SPRUCE_DOOR, new BlockDoor(Material.SPRUCE_DOOR_ITEM));
reg(Material.BIRCH_DOOR, new BlockDoor(Material.BIRCH_DOOR_ITEM));
reg(Material.JUNGLE_DOOR, new BlockDoor(Material.JUNGLE_DOOR_ITEM));
reg(Material.ACACIA_DOOR, new BlockDoor(Material.ACACIA_DOOR_ITEM));
reg(Material.DARK_OAK_DOOR, new BlockDoor(Material.DARK_OAK_DOOR_ITEM));
reg(Material.DOUBLE_STEP, new BlockDoubleSlab());
reg(Material.DOUBLE_STONE_SLAB2, new BlockDoubleSlab());
reg(Material.WOOD_DOUBLE_STEP, new BlockDoubleSlab(), Sound.BLOCK_WOOD_BREAK);
reg(Material.PURPUR_DOUBLE_SLAB, new BlockDoubleSlab());
reg(Material.SOIL, new BlockSoil(), Sound.BLOCK_GRAVEL_BREAK);
reg(Material.GLASS, new BlockDropless());
reg(Material.THIN_GLASS, new BlockDropless());
reg(Material.STAINED_GLASS, new BlockDropless());
reg(Material.STAINED_GLASS_PANE, new BlockDropless());
reg(Material.GLOWSTONE, new BlockRandomDrops(Material.GLOWSTONE_DUST, 2, 4));
reg(Material.MYCEL, new BlockMycel(), Sound.BLOCK_GRAVEL_BREAK);
reg(Material.GRASS, new BlockGrass(), Sound.BLOCK_GRASS_BREAK);
reg(Material.DIRT, new BlockDirt(), Sound.BLOCK_GRAVEL_BREAK);
reg(Material.GRAVEL, new BlockGravel(), Sound.BLOCK_GRAVEL_BREAK);
reg(Material.SAND, new BlockFalling(Material.SAND), Sound.BLOCK_SAND_BREAK);
reg(Material.ANVIL, new BlockAnvil());
reg(Material.ICE, new BlockIce());
reg(Material.PACKED_ICE, new BlockDropless());
reg(Material.SNOW, new BlockSnow(), Sound.BLOCK_SNOW_BREAK);
reg(Material.SNOW_BLOCK, new BlockSnowBlock(), Sound.BLOCK_SNOW_BREAK);
reg(Material.PRISMARINE, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.RED_SANDSTONE, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.SANDSTONE, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.NETHER_BRICK, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.NETHER_FENCE, new BlockFence(Material.NETHER_FENCE, ToolType.PICKAXE));
reg(Material.FENCE, new BlockFence(Material.FENCE));
reg(Material.NETHERRACK, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.IRON_FENCE, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.BRICK, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.SMOOTH_BRICK, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.ENDER_STONE, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.COBBLESTONE, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.COBBLE_WALL, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.MOSSY_COBBLESTONE, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.STONE, new BlockStone());
reg(Material.OBSIDIAN, new BlockDirectDrops(ToolType.DIAMOND_PICKAXE));
reg(Material.COAL_ORE, new BlockOre(Material.COAL, ToolType.PICKAXE));
reg(Material.COAL_BLOCK, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.IRON_ORE, new BlockDirectDrops(ToolType.STONE_PICKAXE));
reg(Material.IRON_BLOCK, new BlockDirectDrops(ToolType.STONE_PICKAXE));
reg(Material.GOLD_ORE, new BlockDirectDrops(ToolType.IRON_PICKAXE));
reg(Material.GOLD_BLOCK, new BlockDirectDrops(ToolType.IRON_PICKAXE));
reg(Material.DIAMOND_ORE, new BlockOre(Material.DIAMOND, ToolType.IRON_PICKAXE));
reg(Material.DIAMOND_BLOCK, new BlockDirectDrops(ToolType.IRON_PICKAXE));
reg(Material.EMERALD_ORE, new BlockOre(Material.EMERALD, ToolType.IRON_PICKAXE));
reg(Material.EMERALD_BLOCK, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.LAPIS_ORE, new BlockOre(Material.INK_SACK, ToolType.STONE_PICKAXE, 4, 4, 8));
reg(Material.LAPIS_BLOCK, new BlockDirectDrops(ToolType.STONE_PICKAXE));
reg(Material.QUARTZ_ORE, new BlockOre(Material.QUARTZ, ToolType.PICKAXE));
reg(Material.REDSTONE_ORE, new BlockRedstoneOre());
reg(Material.GLOWING_REDSTONE_ORE, new BlockLitRedstoneOre());
reg(Material.REDSTONE_BLOCK, new BlockDirectDrops(ToolType.PICKAXE));
reg(Material.CARROT, new BlockCarrot(), Sound.BLOCK_GRASS_BREAK);
reg(Material.COCOA, new BlockCocoa(), Sound.BLOCK_WOOD_BREAK);
reg(Material.DEAD_BUSH, new BlockDeadBush(), Sound.BLOCK_GRASS_BREAK);
reg(Material.LONG_GRASS, new BlockTallGrass(), Sound.BLOCK_GRASS_BREAK);
reg(Material.HUGE_MUSHROOM_1, new BlockHugeMushroom(true), Sound.BLOCK_WOOD_BREAK);
reg(Material.HUGE_MUSHROOM_2, new BlockHugeMushroom(false), Sound.BLOCK_WOOD_BREAK);
reg(Material.LEAVES, new BlockLeaves(), Sound.BLOCK_GRASS_BREAK);
reg(Material.LEAVES_2, new BlockLeaves(), Sound.BLOCK_GRASS_BREAK);
reg(Material.MELON_BLOCK, new BlockMelon(), Sound.BLOCK_WOOD_BREAK);
reg(Material.MELON_STEM, new BlockStem(Material.MELON_STEM), Sound.BLOCK_GRASS_BREAK);
reg(Material.NETHER_WARTS, new BlockNetherWart(), Sound.BLOCK_GRASS_BREAK);
reg(Material.POTATO, new BlockPotato(), Sound.BLOCK_GRASS_BREAK);
reg(Material.PUMPKIN_STEM, new BlockStem(Material.PUMPKIN_STEM), Sound.BLOCK_GRASS_BREAK);
reg(Material.CROPS, new BlockCrops(), Sound.BLOCK_GRASS_BREAK);
reg(Material.CAKE_BLOCK, new BlockDropless(), Sound.BLOCK_CLOTH_BREAK);
reg(Material.WEB, new BlockWeb());
reg(Material.FIRE, new BlockFire());
reg(Material.ENDER_PORTAL_FRAME, new BlockEnderPortalFrame());
reg(Material.FENCE_GATE, new BlockFenceGate());
reg(Material.ACACIA_FENCE_GATE, new BlockFenceGate());
reg(Material.BIRCH_FENCE_GATE, new BlockFenceGate());
reg(Material.DARK_OAK_FENCE_GATE, new BlockFenceGate());
reg(Material.JUNGLE_FENCE_GATE, new BlockFenceGate());
reg(Material.SPRUCE_FENCE_GATE, new BlockFenceGate());
reg(Material.TRAP_DOOR, new BlockWoodenTrapDoor(), Sound.BLOCK_WOOD_BREAK);
reg(Material.IRON_TRAPDOOR, new BlockIronTrapDoor());
reg(Material.FURNACE, new BlockFurnace());
reg(Material.BURNING_FURNACE, new BlockFurnace());
reg(Material.LEVER, new BlockLever());
reg(Material.HOPPER, new BlockHopper());
reg(Material.PISTON_BASE, new BlockPiston(false));
reg(Material.PISTON_STICKY_BASE, new BlockPiston(true));
reg(Material.ACACIA_STAIRS, new BlockStairs());
reg(Material.BIRCH_WOOD_STAIRS, new BlockStairs(), Sound.BLOCK_WOOD_BREAK);
reg(Material.BRICK_STAIRS, new BlockStairs());
reg(Material.COBBLESTONE_STAIRS, new BlockStairs());
reg(Material.DARK_OAK_STAIRS, new BlockStairs());
reg(Material.JUNGLE_WOOD_STAIRS, new BlockStairs(), Sound.BLOCK_WOOD_BREAK);
reg(Material.NETHER_BRICK_STAIRS, new BlockStairs());
reg(Material.QUARTZ_STAIRS, new BlockStairs());
reg(Material.SANDSTONE_STAIRS, new BlockStairs());
reg(Material.RED_SANDSTONE_STAIRS, new BlockStairs());
reg(Material.SPRUCE_WOOD_STAIRS, new BlockStairs(), Sound.BLOCK_WOOD_BREAK);
reg(Material.SMOOTH_STAIRS, new BlockStairs());
reg(Material.WOOD_STAIRS, new BlockStairs(), Sound.BLOCK_WOOD_BREAK);
reg(Material.PURPUR_STAIRS, new BlockStairs());
reg(Material.STEP, new BlockSlab());
reg(Material.WOOD_STEP, new BlockSlab(), Sound.BLOCK_WOOD_BREAK);
reg(Material.STONE_SLAB2, new BlockSlab());
reg(Material.PURPUR_SLAB, new BlockSlab());
reg(Material.HAY_BLOCK, new BlockHay());
reg(Material.QUARTZ_BLOCK, new BlockQuartz());
reg(Material.LOG, new BlockLog(), Sound.BLOCK_WOOD_BREAK);
reg(Material.LOG_2, new BlockLog2(), Sound.BLOCK_WOOD_BREAK);
reg(Material.LADDER, new BlockLadder(), Sound.BLOCK_WOOD_BREAK);
reg(Material.VINE, new BlockVine());
reg(Material.STONE_BUTTON, new BlockButton(Material.STONE_BUTTON));
reg(Material.WOOD_BUTTON, new BlockButton(Material.WOOD_BUTTON), Sound.BLOCK_WOOD_BREAK);
reg(Material.BED_BLOCK, new BlockBed());
reg(Material.SKULL, new BlockSkull());
reg(Material.TORCH, new BlockTorch());
reg(Material.GOLD_PLATE, new BlockDirectDrops(Material.GOLD_PLATE, ToolType.PICKAXE));
reg(Material.IRON_PLATE, new BlockDirectDrops(Material.IRON_PLATE, ToolType.PICKAXE));
reg(Material.STONE_PLATE, new BlockDirectDrops(Material.STONE_PLATE, ToolType.PICKAXE));
reg(Material.DAYLIGHT_DETECTOR, new BlockDaylightDetector());
reg(Material.DAYLIGHT_DETECTOR_INVERTED, new BlockDaylightDetector());
reg(Material.YELLOW_FLOWER, new BlockNeedsAttached());
reg(Material.RED_ROSE, new BlockNeedsAttached());
reg(Material.BROWN_MUSHROOM, new BlockMushroom(Material.BROWN_MUSHROOM));
reg(Material.RED_MUSHROOM, new BlockMushroom(Material.RED_MUSHROOM));
reg(Material.SUGAR_CANE_BLOCK, new BlockSugarCane(), Sound.BLOCK_GRASS_BREAK);
reg(Material.SAPLING, new BlockSapling());
reg(Material.RAILS, new BlockRails());
reg(Material.ACTIVATOR_RAIL, new BlockRails());
reg(Material.DETECTOR_RAIL, new BlockRails());
reg(Material.POWERED_RAIL, new BlockRails());
reg(Material.CARPET, new BlockCarpet(), Sound.BLOCK_CLOTH_BREAK);
reg(Material.ENCHANTMENT_TABLE, new BlockEnchantmentTable());
reg(Material.BREWING_STAND, new BlockBrewingStand());
reg(Material.CACTUS, new BlockCactus());
reg(Material.WATER, new BlockWater());
reg(Material.STATIONARY_WATER, new BlockWater());
reg(Material.LAVA, new BlockLava());
reg(Material.STATIONARY_LAVA, new BlockLava());
reg(Material.CAULDRON, new BlockCauldron());
reg(Material.STANDING_BANNER, new BlockBanner());
reg(Material.WALL_BANNER, new BlockBanner());
reg(Material.SPONGE, new BlockSponge());
reg(Material.TNT, new BlockTnt());
reg(Material.DOUBLE_PLANT, new BlockDoublePlant());
reg(Material.PUMPKIN, new BlockPumpkin());
reg(Material.JACK_O_LANTERN, new BlockPumpkinBase(Material.JACK_O_LANTERN));
reg(Material.SEA_LANTERN, new BlockRandomDrops(Material.PRISMARINE_CRYSTALS, 2, 3));
reg(Material.REDSTONE_LAMP_ON, new BlockLamp());
reg(Material.REDSTONE_LAMP_OFF, new BlockLamp());
reg(Material.REDSTONE_WIRE, new BlockRedstone());
reg(Material.REDSTONE_TORCH_ON, new BlockRedstoneTorch());
reg(Material.REDSTONE_TORCH_OFF, new BlockRedstoneTorch());
reg(Material.DIODE_BLOCK_ON, new BlockRedstoneRepeater());
reg(Material.DIODE_BLOCK_OFF, new BlockRedstoneRepeater());
reg(Material.MAGMA, new BlockMagma());
reg(Material.NETHER_WART_BLOCK, new BlockDirectDrops(Material.NETHER_WART_BLOCK, ToolType.AXE));
reg(Material.RED_NETHER_BRICK, new BlockDirectDrops(Material.RED_NETHER_BRICK, ToolType.PICKAXE));
reg(Material.BONE_BLOCK, new BlockDirectDrops(Material.BONE_BLOCK, ToolType.PICKAXE));
reg(Material.OBSERVER, new BlockObserver());
reg(Material.REDSTONE_COMPARATOR_ON, new BlockRedstoneComparator());
reg(Material.REDSTONE_COMPARATOR_OFF, new BlockRedstoneComparator());
reg(Material.BEACON, new BlockBeacon());
reg(Material.PURPUR_PILLAR, new BlockPurpurPillar());
reg(Material.PURPUR_BLOCK, new BlockDirectDrops(Material.PURPUR_BLOCK, ToolType.PICKAXE));
reg(Material.END_ROD, new BlockEndRod());
reg(Material.CONCRETE, new BlockDirectDrops(Material.CONCRETE));
reg(Material.CONCRETE_POWDER, new BlockConcretePowder());
reg(Material.WHITE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.WHITE_GLAZED_TERRACOTTA));
reg(Material.BLACK_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.BLACK_GLAZED_TERRACOTTA));
reg(Material.BLUE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.BLUE_GLAZED_TERRACOTTA));
reg(Material.BROWN_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.BROWN_GLAZED_TERRACOTTA));
reg(Material.CYAN_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.CYAN_GLAZED_TERRACOTTA));
reg(Material.GRAY_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.GRAY_GLAZED_TERRACOTTA));
reg(Material.GREEN_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.GREEN_GLAZED_TERRACOTTA));
reg(Material.LIGHT_BLUE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.LIGHT_BLUE_GLAZED_TERRACOTTA));
reg(Material.LIME_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.LIME_GLAZED_TERRACOTTA));
reg(Material.MAGENTA_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.MAGENTA_GLAZED_TERRACOTTA));
reg(Material.ORANGE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.ORANGE_GLAZED_TERRACOTTA));
reg(Material.PINK_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.PINK_GLAZED_TERRACOTTA));
reg(Material.PURPLE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.PURPLE_GLAZED_TERRACOTTA));
reg(Material.RED_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.RED_GLAZED_TERRACOTTA));
reg(Material.SILVER_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.SILVER_GLAZED_TERRACOTTA));
reg(Material.YELLOW_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.YELLOW_GLAZED_TERRACOTTA));
reg(Material.CHORUS_FLOWER, new BlockChorusFlower());
reg(Material.CHORUS_PLANT, new BlockChorusPlant());
reg(Material.FLINT_AND_STEEL, new ItemFlintAndSteel());
reg(Material.SIGN, new ItemSign());
reg(Material.REDSTONE, new ItemPlaceAs(Material.REDSTONE_WIRE));
reg(Material.SUGAR_CANE, new ItemPlaceAs(Material.SUGAR_CANE_BLOCK));
reg(Material.DIODE, new ItemPlaceAs(Material.DIODE_BLOCK_OFF));
reg(Material.BREWING_STAND_ITEM, new ItemPlaceAs(Material.BREWING_STAND));
reg(Material.CAULDRON_ITEM, new ItemPlaceAs(Material.CAULDRON));
reg(Material.FLOWER_POT_ITEM, new ItemPlaceAs(Material.FLOWER_POT));
reg(Material.SKULL_ITEM, new ItemPlaceAs(Material.SKULL));
reg(Material.REDSTONE_COMPARATOR, new ItemPlaceAs(Material.REDSTONE_COMPARATOR_OFF));
reg(Material.BED, new ItemPlaceAs(Material.BED_BLOCK));
reg(Material.BUCKET, new ItemBucket());
reg(Material.WATER_BUCKET, new ItemFilledBucket(Material.WATER));
reg(Material.LAVA_BUCKET, new ItemFilledBucket(Material.LAVA));
reg(Material.WOOD_HOE, new ItemHoe());
reg(Material.STONE_HOE, new ItemHoe());
reg(Material.IRON_HOE, new ItemHoe());
reg(Material.GOLD_HOE, new ItemHoe());
reg(Material.DIAMOND_HOE, new ItemHoe());
reg(Material.WOOD_SPADE, new ItemShovel());
reg(Material.STONE_SPADE, new ItemShovel());
reg(Material.IRON_SPADE, new ItemShovel());
reg(Material.GOLD_SPADE, new ItemShovel());
reg(Material.DIAMOND_SPADE, new ItemShovel());
reg(Material.MONSTER_EGG, new ItemSpawn());
reg(Material.SEEDS, new ItemSeeds(Material.CROPS, Material.SOIL));
reg(Material.MELON_SEEDS, new ItemSeeds(Material.MELON_STEM, Material.SOIL));
reg(Material.PUMPKIN_SEEDS, new ItemSeeds(Material.PUMPKIN_STEM, Material.SOIL));
reg(Material.NETHER_STALK, new ItemSeeds(Material.NETHER_WARTS, Material.SOUL_SAND));
reg(Material.CARROT_ITEM, new ItemFoodSeeds(Material.CARROT, Material.SOIL, 3, 3.6f));
reg(Material.POTATO_ITEM, new ItemFoodSeeds(Material.POTATO, Material.SOIL, 1, 0.6f));
reg(Material.INK_SACK, new ItemDye());
reg(Material.BANNER, new ItemBanner());
reg(Material.WOOD_DOOR, new ItemPlaceAs(Material.WOODEN_DOOR));
reg(Material.IRON_DOOR, new ItemPlaceAs(Material.IRON_DOOR_BLOCK));
reg(Material.SPRUCE_DOOR_ITEM, new ItemPlaceAs(Material.SPRUCE_DOOR));
reg(Material.BIRCH_DOOR_ITEM, new ItemPlaceAs(Material.BIRCH_DOOR));
reg(Material.JUNGLE_DOOR_ITEM, new ItemPlaceAs(Material.JUNGLE_DOOR));
reg(Material.ACACIA_DOOR_ITEM, new ItemPlaceAs(Material.ACACIA_DOOR));
reg(Material.DARK_OAK_DOOR_ITEM, new ItemPlaceAs(Material.DARK_OAK_DOOR));
reg(Material.WRITTEN_BOOK, new ItemWrittenBook());
reg(Material.ITEM_FRAME, new ItemItemFrame());
reg(Material.APPLE, new ItemFood(4, 2.4f));
reg(Material.BAKED_POTATO, new ItemFood(5, 6f));
reg(Material.BREAD, new ItemFood(5, 6f));
reg(Material.COOKED_CHICKEN, new ItemFood(6, 7.2f));
reg(Material.COOKED_FISH, new ItemFishCooked());
reg(Material.COOKED_MUTTON, new ItemFood(6, 9.6f));
reg(Material.COOKED_BEEF, new ItemFood(8, 12.8f));
reg(Material.COOKED_RABBIT, new ItemFood(5, 6f));
reg(Material.COOKIE, new ItemFood(2, 0.4f));
reg(Material.GOLDEN_APPLE, new ItemGoldenApple());
reg(Material.GOLDEN_CARROT, new ItemFood(6, 14.4f));
reg(Material.GRILLED_PORK, new ItemFood(8, 12.8f));
reg(Material.MELON, new ItemFood(2, 1.2f));
reg(Material.BEETROOT, new ItemFood(1, 1.2f));
reg(Material.BEETROOT_SOUP, new ItemSoup(6, 7.2f));
reg(Material.MUSHROOM_SOUP, new ItemSoup(6, 7.2f));
reg(Material.POISONOUS_POTATO, new ItemPoisonousPotato());
reg(Material.PUMPKIN_PIE, new ItemFood(8, 4.8f));
reg(Material.RABBIT_STEW, new ItemSoup(10, 12f));
reg(Material.RAW_BEEF, new ItemFood(3, 1.8f));
reg(Material.RAW_CHICKEN, new ItemRawChicken());
reg(Material.RAW_FISH, new ItemFishRaw());
reg(Material.MUTTON, new ItemFood(2, 1.2f));
reg(Material.PORK, new ItemFood(3, 1.8f));
reg(Material.RABBIT, new ItemFood(3, 1.8f));
reg(Material.ROTTEN_FLESH, new ItemRottenFlesh());
reg(Material.SPIDER_EYE, new ItemSpiderEye());
reg(Material.CHORUS_FRUIT, new ItemChorusFruit());
reg(Material.ARMOR_STAND, new ItemArmorStand());
reg(Material.MILK_BUCKET, new ItemMilk());
reg(Material.MINECART, new ItemMinecart(GlowMinecart.MinecartType.RIDEABLE));
reg(Material.COMMAND_MINECART, new ItemMinecart(GlowMinecart.MinecartType.COMMAND));
reg(Material.EXPLOSIVE_MINECART, new ItemMinecart(GlowMinecart.MinecartType.TNT));
reg(Material.HOPPER_MINECART, new ItemMinecart(GlowMinecart.MinecartType.HOPPER));
reg(Material.POWERED_MINECART, new ItemMinecart(GlowMinecart.MinecartType.FURNACE));
reg(Material.STORAGE_MINECART, new ItemMinecart(GlowMinecart.MinecartType.CHEST));
reg(Material.END_CRYSTAL, new ItemEndCrystal());
reg(Material.BOAT, new ItemBoat(TreeSpecies.GENERIC));
reg(Material.BOAT_SPRUCE, new ItemBoat(TreeSpecies.REDWOOD));
reg(Material.BOAT_BIRCH, new ItemBoat(TreeSpecies.BIRCH));
reg(Material.BOAT_JUNGLE, new ItemBoat(TreeSpecies.JUNGLE));
reg(Material.BOAT_ACACIA, new ItemBoat(TreeSpecies.ACACIA));
reg(Material.BOAT_DARK_OAK, new ItemBoat(TreeSpecies.DARK_OAK));
reg(Material.PAINTING, new ItemPainting());
reg(Material.FIREWORK, new ItemFirework());
reg(Material.ENDER_PEARL, new ItemEnderPearl());
reg(Material.KNOWLEDGE_BOOK, new ItemKnowledgeBook());
}
private void reg(Material material, ItemType type) {
if (material.isBlock() != type instanceof BlockType) {
throw new IllegalArgumentException("Cannot mismatch item and block: " + material + ", " + type);
}
if (materialToType.containsKey(material)) {
throw new IllegalArgumentException("Cannot use " + type + " for " + material + ", is already " + materialToType
.get(material));
}
materialToType.put(material, type);
type.setMaterial(material);
if (material.isBlock()) {
nextBlockId = Math.max(nextBlockId, material.getId() + 1);
if (type.getClass() != BlockType.class) {
((BlockType) type).setPlaceSound(Sound.BLOCK_STONE_BREAK);
}
} else {
nextItemId = Math.max(nextItemId, material.getId() + 1);
}
}
private void reg(Material material, ItemType type, Sound sound) {
if (material.isBlock() != type instanceof BlockType) {
throw new IllegalArgumentException("Cannot mismatch item and block: " + material + ", " + type);
}
if (materialToType.containsKey(material)) {
throw new IllegalArgumentException("Cannot use " + type + " for " + material + ", is already " + materialToType
.get(material));
}
materialToType.put(material, type);
type.setMaterial(material);
if (material.isBlock()) {
nextBlockId = Math.max(nextBlockId, material.getId() + 1);
((BlockType) type).setPlaceSound(sound);
} else {
nextItemId = Math.max(nextItemId, material.getId() + 1);
}
}
/**
* Register a new, non-Vanilla ItemType. It will be assigned an ID automatically.
*
* @param key the namespaced key of the ItemType
* @param type the ItemType to register.
* @return if the registration was successful
*/
public boolean register(NamespacedKey key, ItemType type) {
int id;
boolean block = type instanceof BlockType;
if (block) {
id = nextBlockId;
} else {
id = nextItemId;
}
if (extraTypes.putIfAbsent(key, type) == null) {
type.setId(id);
if (block) {
nextBlockId++;
} else {
nextItemId++;
}
return true;
} else {
return false;
}
}
private ItemType createDefault(Material material) {
if (material == null || material == Material.AIR) {
return null;
}
ItemType result;
if (material.isBlock()) {
result = new BlockType();
} else {
result = new ItemType();
}
reg(material, result);
return result;
}
////////////////////////////////////////////////////////////////////////////
// Type access
@Deprecated
public ItemType getItem(int id) {
return getItem(Material.getMaterial(id));
}
public ItemType getItem(Material mat) {
ItemType type = materialToType.get(mat);
if (type == null) {
type = createDefault(mat);
}
return type;
}
@Deprecated
public BlockType getBlock(int id) {
return getBlock(Material.getMaterial(id));
}
public BlockType getBlock(Material mat) {
ItemType itemType = getItem(mat);
if (itemType instanceof BlockType) {
return (BlockType) itemType;
}
return null;
}
}
| Fix CheckStyle issues in block/ItemTable.java (#680)
| src/main/java/net/glowstone/block/ItemTable.java | Fix CheckStyle issues in block/ItemTable.java (#680) | <ide><path>rc/main/java/net/glowstone/block/ItemTable.java
<ide> reg(Material.DIODE_BLOCK_ON, new BlockRedstoneRepeater());
<ide> reg(Material.DIODE_BLOCK_OFF, new BlockRedstoneRepeater());
<ide> reg(Material.MAGMA, new BlockMagma());
<del> reg(Material.NETHER_WART_BLOCK, new BlockDirectDrops(Material.NETHER_WART_BLOCK, ToolType.AXE));
<del> reg(Material.RED_NETHER_BRICK, new BlockDirectDrops(Material.RED_NETHER_BRICK, ToolType.PICKAXE));
<add> reg(Material.NETHER_WART_BLOCK, new BlockDirectDrops(Material.NETHER_WART_BLOCK, ToolType
<add> .AXE));
<add> reg(Material.RED_NETHER_BRICK, new BlockDirectDrops(Material.RED_NETHER_BRICK, ToolType
<add> .PICKAXE));
<ide> reg(Material.BONE_BLOCK, new BlockDirectDrops(Material.BONE_BLOCK, ToolType.PICKAXE));
<ide> reg(Material.OBSERVER, new BlockObserver());
<ide> reg(Material.REDSTONE_COMPARATOR_ON, new BlockRedstoneComparator());
<ide> reg(Material.END_ROD, new BlockEndRod());
<ide> reg(Material.CONCRETE, new BlockDirectDrops(Material.CONCRETE));
<ide> reg(Material.CONCRETE_POWDER, new BlockConcretePowder());
<del> reg(Material.WHITE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.WHITE_GLAZED_TERRACOTTA));
<del> reg(Material.BLACK_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.BLACK_GLAZED_TERRACOTTA));
<add> reg(Material.WHITE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
<add> .WHITE_GLAZED_TERRACOTTA));
<add> reg(Material.BLACK_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
<add> .BLACK_GLAZED_TERRACOTTA));
<ide> reg(Material.BLUE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.BLUE_GLAZED_TERRACOTTA));
<del> reg(Material.BROWN_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.BROWN_GLAZED_TERRACOTTA));
<add> reg(Material.BROWN_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
<add> .BROWN_GLAZED_TERRACOTTA));
<ide> reg(Material.CYAN_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.CYAN_GLAZED_TERRACOTTA));
<ide> reg(Material.GRAY_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.GRAY_GLAZED_TERRACOTTA));
<del> reg(Material.GREEN_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.GREEN_GLAZED_TERRACOTTA));
<del> reg(Material.LIGHT_BLUE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.LIGHT_BLUE_GLAZED_TERRACOTTA));
<add> reg(Material.GREEN_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
<add> .GREEN_GLAZED_TERRACOTTA));
<add> reg(Material.LIGHT_BLUE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
<add> .LIGHT_BLUE_GLAZED_TERRACOTTA));
<ide> reg(Material.LIME_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.LIME_GLAZED_TERRACOTTA));
<del> reg(Material.MAGENTA_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.MAGENTA_GLAZED_TERRACOTTA));
<del> reg(Material.ORANGE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.ORANGE_GLAZED_TERRACOTTA));
<add> reg(Material.MAGENTA_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
<add> .MAGENTA_GLAZED_TERRACOTTA));
<add> reg(Material.ORANGE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
<add> .ORANGE_GLAZED_TERRACOTTA));
<ide> reg(Material.PINK_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.PINK_GLAZED_TERRACOTTA));
<del> reg(Material.PURPLE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.PURPLE_GLAZED_TERRACOTTA));
<add> reg(Material.PURPLE_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
<add> .PURPLE_GLAZED_TERRACOTTA));
<ide> reg(Material.RED_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.RED_GLAZED_TERRACOTTA));
<del> reg(Material.SILVER_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.SILVER_GLAZED_TERRACOTTA));
<del> reg(Material.YELLOW_GLAZED_TERRACOTTA, new BlockDirectDrops(Material.YELLOW_GLAZED_TERRACOTTA));
<add> reg(Material.SILVER_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
<add> .SILVER_GLAZED_TERRACOTTA));
<add> reg(Material.YELLOW_GLAZED_TERRACOTTA, new BlockDirectDrops(Material
<add> .YELLOW_GLAZED_TERRACOTTA));
<ide> reg(Material.CHORUS_FLOWER, new BlockChorusFlower());
<ide> reg(Material.CHORUS_PLANT, new BlockChorusPlant());
<ide>
<ide>
<ide> private void reg(Material material, ItemType type) {
<ide> if (material.isBlock() != type instanceof BlockType) {
<del> throw new IllegalArgumentException("Cannot mismatch item and block: " + material + ", " + type);
<add> throw new IllegalArgumentException(
<add> "Cannot mismatch item and block: " + material + ", " + type);
<ide> }
<ide>
<ide> if (materialToType.containsKey(material)) {
<del> throw new IllegalArgumentException("Cannot use " + type + " for " + material + ", is already " + materialToType
<del> .get(material));
<add> throw new IllegalArgumentException(
<add> "Cannot use " + type + " for " + material + ", is already " + materialToType
<add> .get(material));
<ide> }
<ide>
<ide> materialToType.put(material, type);
<ide>
<ide> private void reg(Material material, ItemType type, Sound sound) {
<ide> if (material.isBlock() != type instanceof BlockType) {
<del> throw new IllegalArgumentException("Cannot mismatch item and block: " + material + ", " + type);
<add> throw new IllegalArgumentException(
<add> "Cannot mismatch item and block: " + material + ", " + type);
<ide> }
<ide>
<ide> if (materialToType.containsKey(material)) {
<del> throw new IllegalArgumentException("Cannot use " + type + " for " + material + ", is already " + materialToType
<del> .get(material));
<add> throw new IllegalArgumentException(
<add> "Cannot use " + type + " for " + material + ", is already " + materialToType
<add> .get(material));
<ide> }
<ide>
<ide> materialToType.put(material, type);
<ide> return getItem(Material.getMaterial(id));
<ide> }
<ide>
<add> /**
<add> * Returns the {@link ItemType} for a {@link Material}, or null if not a block.
<add> *
<add> * @param mat a {@link Material}
<add> * @return {@code mat} as an {@link ItemType}
<add> */
<ide> public ItemType getItem(Material mat) {
<ide> ItemType type = materialToType.get(mat);
<ide> if (type == null) {
<ide> return getBlock(Material.getMaterial(id));
<ide> }
<ide>
<add> /**
<add> * Returns the {@link BlockType} for a {@link Material}, or null if not a block.
<add> *
<add> * @param mat a {@link Material}
<add> * @return {@code mat} as a {@link BlockType}, or null if {@code mat} isn't a block
<add> */
<ide> public BlockType getBlock(Material mat) {
<ide> ItemType itemType = getItem(mat);
<ide> if (itemType instanceof BlockType) { |
|
Java | apache-2.0 | fab4ab6153a033ed3eee17fa962e2b94a4015cf7 | 0 | hdost/gerrit,gcoders/gerrit,dwhipstock/gerrit,jackminicloud/test,WANdisco/gerrit,pkdevbox/gerrit,netroby/gerrit,renchaorevee/gerrit,midnightradio/gerrit,Saulis/gerrit,thinkernel/gerrit,gcoders/gerrit,Distrotech/gerrit,hdost/gerrit,gerrit-review/gerrit,joshuawilson/merrit,pkdevbox/gerrit,MerritCR/merrit,WANdisco/gerrit,Distrotech/gerrit,thinkernel/gerrit,netroby/gerrit,qtproject/qtqa-gerrit,joshuawilson/merrit,Seinlin/gerrit,MerritCR/merrit,netroby/gerrit,gracefullife/gerrit,thinkernel/gerrit,Distrotech/gerrit,quyixia/gerrit,gracefullife/gerrit,Team-OctOS/host_gerrit,supriyantomaftuh/gerrit,ckamm/gerrit,qtproject/qtqa-gerrit,TonyChai24/test,thinkernel/gerrit,qtproject/qtqa-gerrit,anminhsu/gerrit,WANdisco/gerrit,renchaorevee/gerrit,ckamm/gerrit,Team-OctOS/host_gerrit,bpollack/gerrit,anminhsu/gerrit,bootstraponline-archive/gerrit-mirror,Seinlin/gerrit,Distrotech/gerrit,dwhipstock/gerrit,TonyChai24/test,thesamet/gerrit,Seinlin/gerrit,Team-OctOS/host_gerrit,gcoders/gerrit,Seinlin/gerrit,hdost/gerrit,basilgor/gerrit,WANdisco/gerrit,ckamm/gerrit,dwhipstock/gerrit,bpollack/gerrit,gerrit-review/gerrit,gcoders/gerrit,MerritCR/merrit,hdost/gerrit,Team-OctOS/host_gerrit,GerritCodeReview/gerrit,hdost/gerrit,netroby/gerrit,Distrotech/gerrit,jackminicloud/test,anminhsu/gerrit,anminhsu/gerrit,bootstraponline-archive/gerrit-mirror,gracefullife/gerrit,Distrotech/gerrit,renchaorevee/gerrit,supriyantomaftuh/gerrit,GerritCodeReview/gerrit,joshuawilson/merrit,bpollack/gerrit,MerritCR/merrit,TonyChai24/test,Saulis/gerrit,WANdisco/gerrit,Overruler/gerrit,renchaorevee/gerrit,MerritCR/merrit,MerritCR/merrit,thesamet/gerrit,basilgor/gerrit,bpollack/gerrit,Overruler/gerrit,dwhipstock/gerrit,dwhipstock/gerrit,gerrit-review/gerrit,pkdevbox/gerrit,Overruler/gerrit,midnightradio/gerrit,quyixia/gerrit,anminhsu/gerrit,supriyantomaftuh/gerrit,Team-OctOS/host_gerrit,dwhipstock/gerrit,TonyChai24/test,Seinlin/gerrit,gcoders/gerrit,GerritCodeReview/gerrit,TonyChai24/test,MerritCR/merrit,gcoders/gerrit,netroby/gerrit,thesamet/gerrit,Saulis/gerrit,Team-OctOS/host_gerrit,midnightradio/gerrit,gracefullife/gerrit,zommarin/gerrit,qtproject/qtqa-gerrit,zommarin/gerrit,Overruler/gerrit,bpollack/gerrit,joshuawilson/merrit,WANdisco/gerrit,WANdisco/gerrit,quyixia/gerrit,gerrit-review/gerrit,Seinlin/gerrit,netroby/gerrit,quyixia/gerrit,bootstraponline-archive/gerrit-mirror,thesamet/gerrit,pkdevbox/gerrit,renchaorevee/gerrit,GerritCodeReview/gerrit,thesamet/gerrit,basilgor/gerrit,supriyantomaftuh/gerrit,Saulis/gerrit,thinkernel/gerrit,quyixia/gerrit,TonyChai24/test,MerritCR/merrit,pkdevbox/gerrit,midnightradio/gerrit,ckamm/gerrit,pkdevbox/gerrit,hdost/gerrit,qtproject/qtqa-gerrit,bootstraponline-archive/gerrit-mirror,pkdevbox/gerrit,gerrit-review/gerrit,gracefullife/gerrit,renchaorevee/gerrit,jackminicloud/test,GerritCodeReview/gerrit,jackminicloud/test,Overruler/gerrit,basilgor/gerrit,joshuawilson/merrit,zommarin/gerrit,thinkernel/gerrit,Saulis/gerrit,zommarin/gerrit,Saulis/gerrit,quyixia/gerrit,Overruler/gerrit,Seinlin/gerrit,GerritCodeReview/gerrit,renchaorevee/gerrit,gcoders/gerrit,midnightradio/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,bpollack/gerrit,Distrotech/gerrit,anminhsu/gerrit,hdost/gerrit,bootstraponline-archive/gerrit-mirror,supriyantomaftuh/gerrit,anminhsu/gerrit,jackminicloud/test,jackminicloud/test,thesamet/gerrit,jackminicloud/test,thesamet/gerrit,midnightradio/gerrit,quyixia/gerrit,zommarin/gerrit,joshuawilson/merrit,basilgor/gerrit,supriyantomaftuh/gerrit,joshuawilson/merrit,GerritCodeReview/gerrit,TonyChai24/test,bootstraponline-archive/gerrit-mirror,ckamm/gerrit,joshuawilson/merrit,gerrit-review/gerrit,supriyantomaftuh/gerrit,qtproject/qtqa-gerrit,Team-OctOS/host_gerrit,netroby/gerrit,dwhipstock/gerrit,thinkernel/gerrit,qtproject/qtqa-gerrit | // Copyright (C) 2011 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.schema;
import com.google.gerrit.common.data.AccessSection;
import com.google.gerrit.common.data.GlobalCapability;
import com.google.gerrit.common.data.PermissionRule;
import com.google.gerrit.common.data.PermissionRule.Action;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.client.AccountGroupName;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.SystemConfig;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.GerritPersonIdent;
import com.google.gerrit.server.config.AllProjectsNameProvider;
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.gerrit.server.git.LocalDiskRepositoryManager;
import com.google.gerrit.server.git.MetaDataUpdate;
import com.google.gerrit.server.git.ProjectConfig;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collections;
public class Schema_57 extends SchemaVersion {
private final SitePaths site;
private final LocalDiskRepositoryManager mgr;
private final PersonIdent serverUser;
@Inject
Schema_57(Provider<Schema_56> prior, SitePaths site,
LocalDiskRepositoryManager mgr, @GerritPersonIdent PersonIdent serverUser) {
super(prior);
this.site = site;
this.mgr = mgr;
this.serverUser = serverUser;
}
@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException {
SystemConfig sc = db.systemConfig().get(new SystemConfig.Key());
Project.NameKey allProjects = sc.wildProjectName;
FileBasedConfig cfg = new FileBasedConfig(site.gerrit_config, FS.DETECTED);
boolean cfgDirty = false;
try {
cfg.load();
} catch (ConfigInvalidException err) {
throw new OrmException("Cannot read " + site.gerrit_config, err);
} catch (IOException err) {
throw new OrmException("Cannot read " + site.gerrit_config, err);
}
if (!allProjects.get().equals(AllProjectsNameProvider.DEFAULT)) {
ui.message("Setting gerrit.allProjects = " + allProjects.get());
cfg.setString("gerrit", null, "allProjects", allProjects.get());
cfgDirty = true;
}
try {
Repository git = mgr.openRepository(allProjects);
try {
MetaDataUpdate md =
new MetaDataUpdate(GitReferenceUpdated.DISABLED, allProjects, git);
md.getCommitBuilder().setAuthor(serverUser);
md.getCommitBuilder().setCommitter(serverUser);
ProjectConfig config = ProjectConfig.read(md);
AccessSection cap = config.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true);
// Move the Administrators group reference to All-Projects.
cap.getPermission(GlobalCapability.ADMINISTRATE_SERVER, true)
.add(new PermissionRule(config.resolve(db.accountGroups().get(sc.adminGroupId))));
// Move the repository.*.createGroup to Create Project.
String[] createGroupList = cfg.getStringList("repository", "*", "createGroup");
// Prepare the account_group_includes query
PreparedStatement stmt = ((JdbcSchema) db).getConnection().
prepareStatement("SELECT * FROM account_group_includes WHERE group_id = ?");
for (String name : createGroupList) {
AccountGroup.NameKey key = new AccountGroup.NameKey(name);
AccountGroupName groupName = db.accountGroupNames().get(key);
if (groupName == null) {
continue;
}
AccountGroup group = db.accountGroups().get(groupName.getId());
if (group == null) {
continue;
}
cap.getPermission(GlobalCapability.CREATE_PROJECT, true)
.add(new PermissionRule(config.resolve(group)));
}
if (createGroupList.length != 0) {
ui.message("Moved repository.*.createGroup to 'Create Project' capability");
cfg.unset("repository", "*", "createGroup");
cfgDirty = true;
}
AccountGroup batch = db.accountGroups().get(sc.batchUsersGroupId);
stmt.setInt(1, sc.batchUsersGroupId.get());
if (batch != null
&& db.accountGroupMembers().byGroup(sc.batchUsersGroupId).toList().isEmpty()
&& stmt.executeQuery().first() != false) {
// If the batch user group is not used, delete it.
//
db.accountGroups().delete(Collections.singleton(batch));
AccountGroupName name = db.accountGroupNames().get(batch.getNameKey());
if (name != null) {
db.accountGroupNames().delete(Collections.singleton(name));
}
} else if (batch != null) {
cap.getPermission(GlobalCapability.PRIORITY, true)
.getRule(config.resolve(batch), true)
.setAction(Action.BATCH);
}
md.setMessage("Upgrade to Gerrit Code Review schema 57\n");
config.commit(md);
} catch (SQLException err) {
throw new OrmException( "Cannot read account_group_includes", err);
} finally {
git.close();
}
} catch (ConfigInvalidException err) {
throw new OrmException("Cannot read " + allProjects, err);
} catch (IOException err) {
throw new OrmException("Cannot update " + allProjects, err);
}
if (cfgDirty) {
try {
cfg.save();
} catch (IOException err) {
throw new OrmException("Cannot update " + site.gerrit_config, err);
}
}
// We cannot set the columns to NULL, so use 0 and a DELETED tag.
sc.adminGroupId = new AccountGroup.Id(0);
sc.adminGroupUUID = new AccountGroup.UUID("DELETED");
sc.anonymousGroupId = new AccountGroup.Id(0);
sc.registeredGroupId = new AccountGroup.Id(0);
sc.wildProjectName = new Project.NameKey("DELETED");
sc.ownerGroupId = new AccountGroup.Id(0);
sc.batchUsersGroupId = new AccountGroup.Id(0);
sc.batchUsersGroupUUID = new AccountGroup.UUID("DELETED");
sc.registerEmailPrivateKey = "DELETED";
db.systemConfig().update(Collections.singleton(sc));
}
}
| gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_57.java | // Copyright (C) 2011 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.schema;
import com.google.gerrit.common.data.AccessSection;
import com.google.gerrit.common.data.GlobalCapability;
import com.google.gerrit.common.data.PermissionRule;
import com.google.gerrit.common.data.PermissionRule.Action;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.client.AccountGroupName;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.SystemConfig;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.GerritPersonIdent;
import com.google.gerrit.server.config.AllProjectsNameProvider;
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.gerrit.server.git.LocalDiskRepositoryManager;
import com.google.gerrit.server.git.MetaDataUpdate;
import com.google.gerrit.server.git.ProjectConfig;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collections;
public class Schema_57 extends SchemaVersion {
private final SitePaths site;
private final LocalDiskRepositoryManager mgr;
private final PersonIdent serverUser;
@Inject
Schema_57(Provider<Schema_56> prior, SitePaths site,
LocalDiskRepositoryManager mgr, @GerritPersonIdent PersonIdent serverUser) {
super(prior);
this.site = site;
this.mgr = mgr;
this.serverUser = serverUser;
}
@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException {
SystemConfig sc = db.systemConfig().get(new SystemConfig.Key());
Project.NameKey allProjects = sc.wildProjectName;
FileBasedConfig cfg = new FileBasedConfig(site.gerrit_config, FS.DETECTED);
boolean cfgDirty = false;
try {
cfg.load();
} catch (ConfigInvalidException err) {
throw new OrmException("Cannot read " + site.gerrit_config, err);
} catch (IOException err) {
throw new OrmException("Cannot read " + site.gerrit_config, err);
}
if (!allProjects.get().equals(AllProjectsNameProvider.DEFAULT)) {
ui.message("Setting gerrit.allProjects = " + allProjects.get());
cfg.setString("gerrit", null, "allProjects", allProjects.get());
cfgDirty = true;
}
try {
Repository git = mgr.openRepository(allProjects);
try {
MetaDataUpdate md =
new MetaDataUpdate(GitReferenceUpdated.DISABLED, allProjects, git);
md.getCommitBuilder().setAuthor(serverUser);
md.getCommitBuilder().setCommitter(serverUser);
ProjectConfig config = ProjectConfig.read(md);
AccessSection cap = config.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true);
// Move the Administrators group reference to All-Projects.
cap.getPermission(GlobalCapability.ADMINISTRATE_SERVER, true)
.add(new PermissionRule(config.resolve(db.accountGroups().get(sc.adminGroupId))));
// Move the repository.*.createGroup to Create Project.
String[] createGroupList = cfg.getStringList("repository", "*", "createGroup");
// Prepare the account_group_includes query
PreparedStatement stmt = ((JdbcSchema) db).getConnection().
prepareStatement("SELECT * FROM account_group_includes WHERE group_id = ?");
for (String name : createGroupList) {
AccountGroup.NameKey key = new AccountGroup.NameKey(name);
AccountGroupName groupName = db.accountGroupNames().get(key);
if (groupName == null) {
continue;
}
AccountGroup group = db.accountGroups().get(groupName.getId());
if (group == null) {
continue;
}
cap.getPermission(GlobalCapability.CREATE_PROJECT, true)
.add(new PermissionRule(config.resolve(group)));
}
if (createGroupList.length != 0) {
ui.message("Moved repository.*.createGroup to 'Create Project' capability");
cfg.unset("repository", "*", "createGroup");
cfgDirty = true;
}
AccountGroup batch = db.accountGroups().get(sc.batchUsersGroupId);
stmt.setInt(0, sc.batchUsersGroupId.get());
if (batch != null
&& db.accountGroupMembers().byGroup(sc.batchUsersGroupId).toList().isEmpty()
&& stmt.executeQuery().first() != false) {
// If the batch user group is not used, delete it.
//
db.accountGroups().delete(Collections.singleton(batch));
AccountGroupName name = db.accountGroupNames().get(batch.getNameKey());
if (name != null) {
db.accountGroupNames().delete(Collections.singleton(name));
}
} else if (batch != null) {
cap.getPermission(GlobalCapability.PRIORITY, true)
.getRule(config.resolve(batch), true)
.setAction(Action.BATCH);
}
md.setMessage("Upgrade to Gerrit Code Review schema 57\n");
config.commit(md);
} catch (SQLException err) {
throw new OrmException( "Cannot read account_group_includes", err);
} finally {
git.close();
}
} catch (ConfigInvalidException err) {
throw new OrmException("Cannot read " + allProjects, err);
} catch (IOException err) {
throw new OrmException("Cannot update " + allProjects, err);
}
if (cfgDirty) {
try {
cfg.save();
} catch (IOException err) {
throw new OrmException("Cannot update " + site.gerrit_config, err);
}
}
// We cannot set the columns to NULL, so use 0 and a DELETED tag.
sc.adminGroupId = new AccountGroup.Id(0);
sc.adminGroupUUID = new AccountGroup.UUID("DELETED");
sc.anonymousGroupId = new AccountGroup.Id(0);
sc.registeredGroupId = new AccountGroup.Id(0);
sc.wildProjectName = new Project.NameKey("DELETED");
sc.ownerGroupId = new AccountGroup.Id(0);
sc.batchUsersGroupId = new AccountGroup.Id(0);
sc.batchUsersGroupUUID = new AccountGroup.UUID("DELETED");
sc.registerEmailPrivateKey = "DELETED";
db.systemConfig().update(Collections.singleton(sc));
}
}
| Migration v57 setInt parameter trivial fix
The first parameter for setInt in sql API starts from 1.
See: http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setInt(int,int)
Change-Id: I725e9ea30e78a5b0adaa1b3b58bf30e02cd3d759
| gerrit-server/src/main/java/com/google/gerrit/server/schema/Schema_57.java | Migration v57 setInt parameter trivial fix | <ide><path>errit-server/src/main/java/com/google/gerrit/server/schema/Schema_57.java
<ide> }
<ide>
<ide> AccountGroup batch = db.accountGroups().get(sc.batchUsersGroupId);
<del> stmt.setInt(0, sc.batchUsersGroupId.get());
<add> stmt.setInt(1, sc.batchUsersGroupId.get());
<ide> if (batch != null
<ide> && db.accountGroupMembers().byGroup(sc.batchUsersGroupId).toList().isEmpty()
<ide> && stmt.executeQuery().first() != false) { |
|
Java | apache-2.0 | a5a898a06bf1e538c8cc8cf3924294a9e085c042 | 0 | spring-cloud/spring-cloud-sleuth,spring-cloud/spring-cloud-sleuth,spring-cloud/spring-cloud-sleuth,marcingrzejszczak/spring-cloud-sleuth,marcingrzejszczak/spring-cloud-sleuth,spring-cloud/spring-cloud-sleuth,spring-cloud/spring-cloud-sleuth,marcingrzejszczak/spring-cloud-sleuth,marcingrzejszczak/spring-cloud-sleuth | /*
* Copyright 2013-2016 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.springframework.cloud.sleuth.trace;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.springframework.cloud.sleuth.*;
import org.springframework.cloud.sleuth.log.Slf4jSpanLogger;
import org.springframework.cloud.sleuth.sampler.AlwaysSampler;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then;
/**
* @author Marcin Grzejszczak
*/
public class CustomLoggerTests {
CustomSpanLogger spanLogger = new CustomSpanLogger();
Tracer tracer = new DefaultTracer(new AlwaysSampler(), new Random(),
new DefaultSpanNamer(), this.spanLogger, new NoOpSpanReporter(), new TraceKeys());
// https://github.com/spring-cloud/spring-cloud-sleuth/issues/547
@Test
public void should_pass_baggage_to_custom_span_logger() {
Span parent = Span.builder().spanId(1).traceId(2).baggage("foo", "bar").build();
Span child = this.tracer.createSpan("child", parent);
then(child).hasBaggageItem("foo", "bar");
then(this.spanLogger.called.get()).isTrue();
TestSpanContextHolder.removeCurrentSpan();
}
}
class CustomSpanLogger extends Slf4jSpanLogger {
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
final AtomicBoolean called = new AtomicBoolean();
public CustomSpanLogger() {
super("");
}
@Override public void logStartedSpan(Span parent, Span span) {
super.logStartedSpan(parent, span);
called.set(true);
then(parent).hasBaggageItem("foo", "bar");
then(span).hasBaggageItem("foo", "bar");
log.info("Baggage item foo=>bar found");
log.info("Parent's baggage: " + parent.getBaggage());
log.info("Child's baggage: " + span.getBaggage());
}
}
| spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/trace/CustomLoggerTests.java | /*
* Copyright 2013-2016 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.springframework.cloud.sleuth.trace;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.springframework.cloud.sleuth.DefaultSpanNamer;
import org.springframework.cloud.sleuth.NoOpSpanReporter;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.TraceKeys;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.cloud.sleuth.log.Slf4jSpanLogger;
import org.springframework.cloud.sleuth.sampler.AlwaysSampler;
import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then;
/**
* @author Marcin Grzejszczak
*/
public class CustomLoggerTests {
CustomSpanLogger spanLogger = new CustomSpanLogger();
Tracer tracer = new DefaultTracer(new AlwaysSampler(), new Random(),
new DefaultSpanNamer(), this.spanLogger, new NoOpSpanReporter(), new TraceKeys());
// https://github.com/spring-cloud/spring-cloud-sleuth/issues/547
@Test
public void should_pass_baggage_to_custom_span_logger() {
Span parent = Span.builder().spanId(1).traceId(2).baggage("foo", "bar").build();
Span child = this.tracer.createSpan("child", parent);
then(child).hasBaggageItem("foo", "bar");
then(this.spanLogger.called.get()).isTrue();
}
}
class CustomSpanLogger extends Slf4jSpanLogger {
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
final AtomicBoolean called = new AtomicBoolean();
public CustomSpanLogger() {
super("");
}
@Override public void logStartedSpan(Span parent, Span span) {
super.logStartedSpan(parent, span);
called.set(true);
then(parent).hasBaggageItem("foo", "bar");
then(span).hasBaggageItem("foo", "bar");
log.info("Baggage item foo=>bar found");
log.info("Parent's baggage: " + parent.getBaggage());
log.info("Child's baggage: " + span.getBaggage());
}
}
| Trying to fix flickering tests
| spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/trace/CustomLoggerTests.java | Trying to fix flickering tests | <ide><path>pring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/trace/CustomLoggerTests.java
<ide>
<ide> package org.springframework.cloud.sleuth.trace;
<ide>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>import org.junit.Test;
<add>import org.springframework.cloud.sleuth.*;
<add>import org.springframework.cloud.sleuth.log.Slf4jSpanLogger;
<add>import org.springframework.cloud.sleuth.sampler.AlwaysSampler;
<add>
<ide> import java.lang.invoke.MethodHandles;
<ide> import java.util.Random;
<ide> import java.util.concurrent.atomic.AtomicBoolean;
<del>
<del>import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<del>import org.junit.Test;
<del>import org.springframework.cloud.sleuth.DefaultSpanNamer;
<del>import org.springframework.cloud.sleuth.NoOpSpanReporter;
<del>import org.springframework.cloud.sleuth.Span;
<del>import org.springframework.cloud.sleuth.TraceKeys;
<del>import org.springframework.cloud.sleuth.Tracer;
<del>import org.springframework.cloud.sleuth.log.Slf4jSpanLogger;
<del>import org.springframework.cloud.sleuth.sampler.AlwaysSampler;
<ide>
<ide> import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then;
<ide>
<ide>
<ide> then(child).hasBaggageItem("foo", "bar");
<ide> then(this.spanLogger.called.get()).isTrue();
<add> TestSpanContextHolder.removeCurrentSpan();
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | d389b8539d7dbb05410b7fc36c0f3a919f8240d9 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | /*
* Copyright 2000-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.jetbrains.python.packaging;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.python.packaging.ui.PyCondaManagementService;
import com.jetbrains.python.packaging.ui.PyPackageManagementService;
import com.jetbrains.python.sdk.PythonSdkType;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
/**
* @author yole
*/
public class PyPackageManagersImpl extends PyPackageManagers {
private final Map<String, PyPackageManagerImpl> myInstances = new HashMap<>();
@NotNull
public synchronized PyPackageManager forSdk(@NotNull final Sdk sdk) {
final String key = PythonSdkType.getSdkKey(sdk);
PyPackageManagerImpl manager = myInstances.get(key);
if (manager == null) {
final VirtualFile homeDirectory = sdk.getHomeDirectory();
if (PythonSdkType.isRemote(sdk)) {
manager = new PyRemotePackageManagerImpl(sdk);
}
else if (PyCondaPackageManagerImpl.isConda(sdk) &&
homeDirectory != null &&
PyCondaPackageService.getCondaExecutable(homeDirectory) != null) {
manager = new PyCondaPackageManagerImpl(sdk);
}
else {
manager = new PyPackageManagerImpl(sdk);
}
myInstances.put(key, manager);
}
return manager;
}
public PyPackageManagementService getManagementService(Project project, Sdk sdk) {
if (PyCondaPackageManagerImpl.isConda(sdk)) {
return new PyCondaManagementService(project, sdk);
}
return new PyPackageManagementService(project, sdk);
}
@Override
public void clearCache(@NotNull Sdk sdk) {
final String key = PythonSdkType.getSdkKey(sdk);
myInstances.remove(key);
}
}
| python/src/com/jetbrains/python/packaging/PyPackageManagersImpl.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.jetbrains.python.packaging;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.python.packaging.ui.PyCondaManagementService;
import com.jetbrains.python.packaging.ui.PyPackageManagementService;
import com.jetbrains.python.sdk.PythonSdkType;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
/**
* @author yole
*/
public class PyPackageManagersImpl extends PyPackageManagers {
private final Map<String, PyPackageManagerImpl> myInstances = new HashMap<>();
@NotNull
public synchronized PyPackageManager forSdk(@NotNull final Sdk sdk) {
final String key = PythonSdkType.getSdkKey(sdk);
PyPackageManagerImpl manager = myInstances.get(key);
if (manager == null) {
final VirtualFile homeDirectory = sdk.getHomeDirectory();
if (PythonSdkType.isRemote(sdk)) {
manager = new PyRemotePackageManagerImpl(sdk);
}
else if (PyCondaPackageManagerImpl.isConda(sdk) &&
homeDirectory != null &&
PyCondaPackageService.getCondaExecutable(homeDirectory) != null) {
manager = new PyCondaPackageManagerImpl(sdk);
}
else {
manager = new PyPackageManagerImpl(sdk);
}
myInstances.put(key, manager);
}
return manager;
}
public PyPackageManagementService getManagementService(Project project, Sdk sdk) {
if (PyCondaPackageManagerImpl.isConda(sdk)) {
return new PyCondaManagementService(project, sdk);
}
return new PyPackageManagementService(project, sdk);
}
@Override
public void clearCache(@NotNull Sdk sdk) {
final String key = PythonSdkType.getSdkKey(sdk);
if (myInstances.containsKey(key)) {
myInstances.remove(key);
}
}
}
| Removed unnecessary Map.containsKey() before remove()
| python/src/com/jetbrains/python/packaging/PyPackageManagersImpl.java | Removed unnecessary Map.containsKey() before remove() | <ide><path>ython/src/com/jetbrains/python/packaging/PyPackageManagersImpl.java
<ide> @Override
<ide> public void clearCache(@NotNull Sdk sdk) {
<ide> final String key = PythonSdkType.getSdkKey(sdk);
<del> if (myInstances.containsKey(key)) {
<del> myInstances.remove(key);
<del> }
<add> myInstances.remove(key);
<ide> }
<ide> } |
|
Java | mit | 34dadfacdf46931f1b63019ff958cd9f22edd1cb | 0 | andresdominguez/ng-sort | package com.andresdominguez.ngsort;
import com.google.common.collect.Lists;
import com.intellij.lang.javascript.psi.JSParameterList;
import com.intellij.lang.javascript.psi.JSProperty;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class SortArgsAction extends AnAction {
@Override
public void actionPerformed(AnActionEvent e) {
final Editor editor = e.getData(PlatformDataKeys.EDITOR);
PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE);
if (editor == null || psiFile == null) {
return;
}
final List<CommentAndParamList> list = findAllCommentsAndParams(psiFile);
if (list.size() == 0) {
return;
}
final Document document = editor.getDocument();
CommandProcessor.getInstance().executeCommand(getEventProject(e), new Runnable() {
@Override
public void run() {
for (CommentAndParamList commentAndParamList : list) {
new NgSorter(document, commentAndParamList).sort();
}
}
}, "ng sort", null);
}
@Nullable
private CommentAndParamList findCommentAndParamList(PsiElement ngInjectElement) {
PsiComment comment = PsiTreeUtil.getParentOfType(ngInjectElement, PsiComment.class);
JSProperty jsProperty = PsiTreeUtil.getParentOfType(ngInjectElement, JSProperty.class);
Collection<JSParameterList> parameterLists = PsiTreeUtil.findChildrenOfType(jsProperty, JSParameterList.class);
if (parameterLists.size() != 1) {
return null;
}
JSParameterList parameterList = parameterLists.iterator().next();
return new CommentAndParamList(parameterList, comment);
}
@NotNull
private List<CommentAndParamList> findAllCommentsAndParams(PsiFile psiFile) {
List<CommentAndParamList> list = Lists.newArrayList();
for (Integer index : findNgInjectIndices(psiFile)) {
CommentAndParamList commentAndParamList = findCommentAndParamList(psiFile.findElementAt(index));
if (commentAndParamList != null) {
list.add(commentAndParamList);
}
}
Collections.reverse(list);
return list;
}
List<Integer> findNgInjectIndices(PsiFile psiFile) {
String text = psiFile.getText();
List<Integer> indices = Lists.newArrayList();
int index = text.indexOf("@ngInject");
while (index != -1) {
indices.add(index);
index = text.indexOf("@ngInject", index + 1);
}
return indices;
}
}
| src/com/andresdominguez/ngsort/SortArgsAction.java | package com.andresdominguez.ngsort;
import com.google.common.collect.Lists;
import com.intellij.lang.javascript.psi.JSParameterList;
import com.intellij.lang.javascript.psi.JSProperty;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class SortArgsAction extends AnAction {
@Override
public void actionPerformed(AnActionEvent e) {
final Editor editor = e.getData(PlatformDataKeys.EDITOR);
PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE);
if (editor == null || psiFile == null) {
return;
}
final List<CommentAndParamList> list = findAllCommentsAndParams(psiFile);
if (list.size() == 0) {
return;
}
final Document document = editor.getDocument();
CommandProcessor.getInstance().executeCommand(getEventProject(e), new Runnable() {
@Override
public void run() {
for (CommentAndParamList commentAndParamList : list) {
new NgSorter(document, commentAndParamList).sort();
}
}
}, "ng sort", null);
}
@Nullable
private CommentAndParamList findCommentAndParamList(PsiElement ngInjectElement) {
PsiComment comment = PsiTreeUtil.getParentOfType(ngInjectElement, PsiComment.class);
JSProperty jsProperty = PsiTreeUtil.getParentOfType(ngInjectElement, JSProperty.class);
Collection<JSParameterList> parameterLists = PsiTreeUtil.findChildrenOfType(jsProperty, JSParameterList.class);
if (parameterLists.size() != 1) {
return null;
}
JSParameterList parameterList = parameterLists.iterator().next();
return new CommentAndParamList(parameterList, comment);
}
@NotNull
private List<CommentAndParamList> findAllCommentsAndParams(PsiFile psiFile) {
List<CommentAndParamList> list = Lists.newArrayList();
for (Integer index : findNgInjectIndices(psiFile)) {
CommentAndParamList commentAndParamList = findCommentAndParamList(psiFile.findElementAt(index));
if (commentAndParamList != null) {
list.add(commentAndParamList);
}
}
Collections.reverse(list);
return list;
}
List<Integer> findNgInjectIndices(PsiFile psiFile) {
String text = psiFile.getText();
List<Integer> indices = Lists.newArrayList();
int index = text.indexOf("@ngInject");
while (index != -1) {
indices.add(index);
index = text.indexOf("@ngInject", index + 1);
}
return indices;
}
}
| remove unused
| src/com/andresdominguez/ngsort/SortArgsAction.java | remove unused | <ide><path>rc/com/andresdominguez/ngsort/SortArgsAction.java
<ide> import org.jetbrains.annotations.NotNull;
<ide> import org.jetbrains.annotations.Nullable;
<ide>
<del>import java.util.ArrayList;
<ide> import java.util.Collection;
<ide> import java.util.Collections;
<ide> import java.util.List; |
|
Java | mit | bec0da201f8d2800e39c13e7f7b50842dcd8a409 | 0 | jonafanho/Minecraft-Transit-Railway,jonafanho/Minecraft-Transit-Railway,jonafanho/Minecraft-Transit-Railway | package mtr.screen;
import com.mojang.blaze3d.vertex.PoseStack;
import mtr.client.ClientData;
import mtr.client.IDrawing;
import mtr.data.*;
import mtr.mappings.UtilitiesClient;
import mtr.packet.PacketTrainDataGuiClient;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.Button;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TranslatableComponent;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class EditDepotScreen extends EditNameColorScreenBase<Depot> {
private final int sliderX;
private final int sliderWidthWithText;
private final int rightPanelsX;
private final boolean showScheduleControls;
private final Map<Long, Siding> sidingsInDepot;
private final WidgetShorterSlider[] sliders = new WidgetShorterSlider[Depot.HOURS_IN_DAY];
private final Button buttonEditInstructions;
private final Button buttonGenerateRoute;
private final Button buttonClearTrains;
private static final int PANELS_START = SQUARE_SIZE * 2 + TEXT_FIELD_PADDING;
private static final int SLIDER_WIDTH = 64;
private static final int MAX_TRAINS_PER_HOUR = 5;
private static final int SECONDS_PER_MC_HOUR = Depot.TICKS_PER_HOUR / 20;
public EditDepotScreen(Depot depot, TransportMode transportMode, DashboardScreen dashboardScreen) {
super(depot, dashboardScreen, "gui.mtr.depot_name", "gui.mtr.depot_color");
sidingsInDepot = ClientData.DATA_CACHE.requestDepotIdToSidings(depot.id);
font = Minecraft.getInstance().font;
sliderX = font.width(getTimeString(0)) + TEXT_PADDING * 2;
sliderWidthWithText = SLIDER_WIDTH + TEXT_PADDING + font.width(getSliderString(0));
rightPanelsX = sliderX + SLIDER_WIDTH + TEXT_PADDING * 2 + font.width(getSliderString(1));
showScheduleControls = !transportMode.continuousMovement;
for (int i = 0; i < Depot.HOURS_IN_DAY; i++) {
final int currentIndex = i;
sliders[currentIndex] = new WidgetShorterSlider(sliderX, SLIDER_WIDTH, MAX_TRAINS_PER_HOUR * 2, EditDepotScreen::getSliderString, value -> {
for (int j = 0; j < Depot.HOURS_IN_DAY; j++) {
if (j != currentIndex) {
sliders[j].setValue(value);
}
}
});
}
buttonEditInstructions = new Button(0, 0, 0, SQUARE_SIZE, new TranslatableComponent("gui.mtr.edit_instructions"), button -> {
if (minecraft != null) {
saveData();
final List<NameColorDataBase> routes = new ArrayList<>(ClientData.getFilteredDataSet(transportMode, ClientData.ROUTES));
Collections.sort(routes);
UtilitiesClient.setScreen(minecraft, new DashboardListSelectorScreen(this, routes, data.routeIds, false, true));
}
});
buttonGenerateRoute = new Button(0, 0, 0, SQUARE_SIZE, new TranslatableComponent("gui.mtr.refresh_path"), button -> {
saveData();
depot.clientPathGenerationSuccessfulSegments = -1;
PacketTrainDataGuiClient.generatePathC2S(depot.id);
});
buttonClearTrains = new Button(0, 0, 0, SQUARE_SIZE, new TranslatableComponent("gui.mtr.clear_vehicles"), button -> {
sidingsInDepot.values().forEach(Siding::clearTrains);
PacketTrainDataGuiClient.clearTrainsC2S(sidingsInDepot.values());
});
}
@Override
protected void init() {
setPositionsAndInit(rightPanelsX, width / 4 * 3, width);
final int buttonWidth = (width - rightPanelsX) / 2;
IDrawing.setPositionAndWidth(buttonEditInstructions, rightPanelsX, PANELS_START, buttonWidth * 2);
IDrawing.setPositionAndWidth(buttonGenerateRoute, rightPanelsX, PANELS_START + SQUARE_SIZE, buttonWidth * (showScheduleControls ? 1 : 2));
IDrawing.setPositionAndWidth(buttonClearTrains, rightPanelsX + buttonWidth, PANELS_START + SQUARE_SIZE, buttonWidth);
if (showScheduleControls) {
for (WidgetShorterSlider slider : sliders) {
addDrawableChild(slider);
}
}
for (int i = 0; i < Depot.HOURS_IN_DAY; i++) {
sliders[i].setValue(data.getFrequency(i));
}
addDrawableChild(buttonEditInstructions);
addDrawableChild(buttonGenerateRoute);
if (showScheduleControls) {
addDrawableChild(buttonClearTrains);
}
}
@Override
public void tick() {
super.tick();
buttonGenerateRoute.active = data.clientPathGenerationSuccessfulSegments >= 0;
}
@Override
public void render(PoseStack matrices, int mouseX, int mouseY, float delta) {
try {
renderBackground(matrices);
vLine(matrices, rightPanelsX - 1, -1, height, ARGB_WHITE_TRANSLUCENT);
renderTextFields(matrices);
final int lineHeight = Math.min(SQUARE_SIZE, (height - SQUARE_SIZE) / Depot.HOURS_IN_DAY);
for (int i = 0; i < Depot.HOURS_IN_DAY; i++) {
if (showScheduleControls) {
drawString(matrices, font, getTimeString(i), TEXT_PADDING, SQUARE_SIZE + lineHeight * i + (int) ((lineHeight - TEXT_HEIGHT) / 2F), ARGB_WHITE);
}
sliders[i].y = SQUARE_SIZE + lineHeight * i;
sliders[i].setHeight(lineHeight);
}
super.render(matrices, mouseX, mouseY, delta);
font.draw(matrices, new TranslatableComponent("gui.mtr.sidings_in_depot", sidingsInDepot.size()), rightPanelsX + TEXT_PADDING, PANELS_START + SQUARE_SIZE * 2 + TEXT_PADDING, ARGB_WHITE);
final String[] stringSplit = getSuccessfulSegmentsText().getString().split("\\|");
for (int i = 0; i < stringSplit.length; i++) {
font.draw(matrices, stringSplit[i], rightPanelsX + TEXT_PADDING, PANELS_START + SQUARE_SIZE * 3 + TEXT_PADDING + (TEXT_HEIGHT + TEXT_PADDING) * i, ARGB_WHITE);
}
if (showScheduleControls) {
drawCenteredString(matrices, font, new TranslatableComponent("gui.mtr.game_time"), sliderX / 2, TEXT_PADDING, ARGB_LIGHT_GRAY);
drawCenteredString(matrices, font, new TranslatableComponent("gui.mtr.vehicles_per_hour"), sliderX + sliderWidthWithText / 2, TEXT_PADDING, ARGB_LIGHT_GRAY);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void saveData() {
super.saveData();
for (int i = 0; i < Depot.HOURS_IN_DAY; i++) {
data.setFrequency(sliders[i].getIntValue(), i);
}
data.setData(packet -> PacketTrainDataGuiClient.sendUpdate(PACKET_UPDATE_DEPOT, packet));
}
private Component getSuccessfulSegmentsText() {
final int successfulSegments = data.clientPathGenerationSuccessfulSegments;
if (successfulSegments < 0) {
return new TranslatableComponent("gui.mtr.generating_path");
} else if (successfulSegments == 0) {
return new TranslatableComponent("gui.mtr.path_not_generated");
} else {
final List<String> stationNames = new ArrayList<>();
final List<String> routeNames = new ArrayList<>();
final String depotName = IGui.textOrUntitled(IGui.formatStationName(data.name));
if (successfulSegments == 1) {
RailwayData.useRoutesAndStationsFromIndex(0, data.routeIds, ClientData.DATA_CACHE, (currentStationIndex, thisRoute, nextRoute, thisStation, nextStation, lastStation) -> {
stationNames.add(IGui.textOrUntitled(thisStation == null ? "" : IGui.formatStationName(thisStation.name)));
routeNames.add(IGui.textOrUntitled(thisRoute == null ? "" : IGui.formatStationName(thisRoute.name)));
});
stationNames.add("-");
routeNames.add("-");
return new TranslatableComponent("gui.mtr.path_not_found_between", routeNames.get(0), depotName, stationNames.get(0));
} else {
int sum = 0;
for (int i = 0; i < data.routeIds.size(); i++) {
final Route thisRoute = ClientData.DATA_CACHE.routeIdMap.get(data.routeIds.get(i));
final Route nextRoute = i < data.routeIds.size() - 1 ? ClientData.DATA_CACHE.routeIdMap.get(data.routeIds.get(i + 1)) : null;
if (thisRoute != null) {
sum += thisRoute.platformIds.size();
if (!thisRoute.platformIds.isEmpty() && nextRoute != null && !nextRoute.platformIds.isEmpty() && thisRoute.platformIds.get(thisRoute.platformIds.size() - 1).equals(nextRoute.platformIds.get(0))) {
sum--;
}
}
}
if (successfulSegments >= sum + 2) {
return new TranslatableComponent("gui.mtr.path_found");
} else {
RailwayData.useRoutesAndStationsFromIndex(successfulSegments - 2, data.routeIds, ClientData.DATA_CACHE, (currentStationIndex, thisRoute, nextRoute, thisStation, nextStation, lastStation) -> {
stationNames.add(IGui.textOrUntitled(thisStation == null ? "" : IGui.formatStationName(thisStation.name)));
if (nextStation == null) {
RailwayData.useRoutesAndStationsFromIndex(successfulSegments - 1, data.routeIds, ClientData.DATA_CACHE, (currentStationIndex1, thisRoute1, nextRoute1, thisStation1, nextStation1, lastStation1) -> stationNames.add(IGui.textOrUntitled(thisStation1 == null ? "" : IGui.formatStationName(thisStation1.name))));
} else {
stationNames.add(IGui.textOrUntitled(IGui.formatStationName(nextStation.name)));
}
routeNames.add(IGui.textOrUntitled(IGui.formatStationName(thisRoute.name)));
});
stationNames.add("-");
stationNames.add("-");
routeNames.add("-");
if (successfulSegments < sum + 1) {
return new TranslatableComponent("gui.mtr.path_not_found_between", routeNames.get(0), stationNames.get(0), stationNames.get(1));
} else {
return new TranslatableComponent("gui.mtr.path_not_found_between", routeNames.get(0), stationNames.get(0), depotName);
}
}
}
}
}
private static String getSliderString(int value) {
final String headwayText;
if (value == 0) {
headwayText = "";
} else {
headwayText = " (" + RailwayData.round((float) Depot.TRAIN_FREQUENCY_MULTIPLIER * SECONDS_PER_MC_HOUR / value, 1) + new TranslatableComponent("gui.mtr.s").getString() + ")";
}
return value / (float) Depot.TRAIN_FREQUENCY_MULTIPLIER + new TranslatableComponent("gui.mtr.tph").getString() + headwayText;
}
private static String getTimeString(int hour) {
final String hourString = StringUtils.leftPad(String.valueOf(hour), 2, "0");
return String.format("%s:00-%s:59", hourString, hourString);
}
}
| common/src/main/java/mtr/screen/EditDepotScreen.java | package mtr.screen;
import com.mojang.blaze3d.vertex.PoseStack;
import mtr.client.ClientData;
import mtr.client.IDrawing;
import mtr.data.*;
import mtr.mappings.UtilitiesClient;
import mtr.packet.PacketTrainDataGuiClient;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.Button;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TranslatableComponent;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class EditDepotScreen extends EditNameColorScreenBase<Depot> {
private final int sliderX;
private final int sliderWidthWithText;
private final int rightPanelsX;
private final boolean showScheduleControls;
private final Map<Long, Siding> sidingsInDepot;
private final WidgetShorterSlider[] sliders = new WidgetShorterSlider[Depot.HOURS_IN_DAY];
private final Button buttonEditInstructions;
private final Button buttonGenerateRoute;
private final Button buttonClearTrains;
private static final int PANELS_START = SQUARE_SIZE * 2 + TEXT_FIELD_PADDING;
private static final int SLIDER_WIDTH = 64;
private static final int MAX_TRAINS_PER_HOUR = 5;
private static final int SECONDS_PER_MC_HOUR = Depot.TICKS_PER_HOUR / 20;
public EditDepotScreen(Depot depot, TransportMode transportMode, DashboardScreen dashboardScreen) {
super(depot, dashboardScreen, "gui.mtr.depot_name", "gui.mtr.depot_color");
sidingsInDepot = ClientData.DATA_CACHE.requestDepotIdToSidings(depot.id);
font = Minecraft.getInstance().font;
sliderX = font.width(getTimeString(0)) + TEXT_PADDING * 2;
sliderWidthWithText = SLIDER_WIDTH + TEXT_PADDING + font.width(getSliderString(0));
rightPanelsX = sliderX + SLIDER_WIDTH + TEXT_PADDING * 2 + font.width(getSliderString(1));
showScheduleControls = !transportMode.continuousMovement;
for (int i = 0; i < Depot.HOURS_IN_DAY; i++) {
final int currentIndex = i;
sliders[currentIndex] = new WidgetShorterSlider(sliderX, SLIDER_WIDTH, MAX_TRAINS_PER_HOUR * 2, EditDepotScreen::getSliderString, value -> {
for (int j = 0; j < Depot.HOURS_IN_DAY; j++) {
if (j != currentIndex) {
sliders[j].setValue(value);
}
}
});
}
buttonEditInstructions = new Button(0, 0, 0, SQUARE_SIZE, new TranslatableComponent("gui.mtr.edit_instructions"), button -> {
if (minecraft != null) {
saveData();
final List<NameColorDataBase> routes = new ArrayList<>(ClientData.getFilteredDataSet(transportMode, ClientData.ROUTES));
Collections.sort(routes);
UtilitiesClient.setScreen(minecraft, new DashboardListSelectorScreen(this, routes, data.routeIds, false, true));
}
});
buttonGenerateRoute = new Button(0, 0, 0, SQUARE_SIZE, new TranslatableComponent("gui.mtr.refresh_path"), button -> {
saveData();
depot.clientPathGenerationSuccessfulSegments = -1;
PacketTrainDataGuiClient.generatePathC2S(depot.id);
});
buttonClearTrains = new Button(0, 0, 0, SQUARE_SIZE, new TranslatableComponent("gui.mtr.clear_vehicles"), button -> {
sidingsInDepot.values().forEach(Siding::clearTrains);
PacketTrainDataGuiClient.clearTrainsC2S(sidingsInDepot.values());
});
}
@Override
protected void init() {
setPositionsAndInit(rightPanelsX, width / 4 * 3, width);
final int buttonWidth = (width - rightPanelsX) / 2;
IDrawing.setPositionAndWidth(buttonEditInstructions, rightPanelsX, PANELS_START, buttonWidth * 2);
IDrawing.setPositionAndWidth(buttonGenerateRoute, rightPanelsX, PANELS_START + SQUARE_SIZE, buttonWidth * (showScheduleControls ? 1 : 2));
IDrawing.setPositionAndWidth(buttonClearTrains, rightPanelsX + buttonWidth, PANELS_START + SQUARE_SIZE, buttonWidth);
if (showScheduleControls) {
for (WidgetShorterSlider slider : sliders) {
addDrawableChild(slider);
}
}
for (int i = 0; i < Depot.HOURS_IN_DAY; i++) {
sliders[i].setValue(data.getFrequency(i));
}
addDrawableChild(buttonEditInstructions);
addDrawableChild(buttonGenerateRoute);
if (showScheduleControls) {
addDrawableChild(buttonClearTrains);
}
}
@Override
public void tick() {
super.tick();
buttonGenerateRoute.active = data.clientPathGenerationSuccessfulSegments >= 0;
}
@Override
public void render(PoseStack matrices, int mouseX, int mouseY, float delta) {
try {
renderBackground(matrices);
vLine(matrices, rightPanelsX - 1, -1, height, ARGB_WHITE_TRANSLUCENT);
renderTextFields(matrices);
final int lineHeight = Math.min(SQUARE_SIZE, (height - SQUARE_SIZE) / Depot.HOURS_IN_DAY);
for (int i = 0; i < Depot.HOURS_IN_DAY; i++) {
if (showScheduleControls) {
drawString(matrices, font, getTimeString(i), TEXT_PADDING, SQUARE_SIZE + lineHeight * i + (int) ((lineHeight - TEXT_HEIGHT) / 2F), ARGB_WHITE);
}
sliders[i].y = SQUARE_SIZE + lineHeight * i;
sliders[i].setHeight(lineHeight);
}
super.render(matrices, mouseX, mouseY, delta);
font.draw(matrices, new TranslatableComponent("gui.mtr.sidings_in_depot", sidingsInDepot.size()), rightPanelsX + TEXT_PADDING, PANELS_START + SQUARE_SIZE * 2 + TEXT_PADDING, ARGB_WHITE);
final String[] stringSplit = getSuccessfulSegmentsText().getString().split("\\|");
for (int i = 0; i < stringSplit.length; i++) {
font.draw(matrices, stringSplit[i], rightPanelsX + TEXT_PADDING, PANELS_START + SQUARE_SIZE * 3 + TEXT_PADDING + (TEXT_HEIGHT + TEXT_PADDING) * i, ARGB_WHITE);
}
if (showScheduleControls) {
drawCenteredString(matrices, font, new TranslatableComponent("gui.mtr.game_time"), sliderX / 2, TEXT_PADDING, ARGB_LIGHT_GRAY);
drawCenteredString(matrices, font, new TranslatableComponent("gui.mtr.vehicles_per_hour"), sliderX + sliderWidthWithText / 2, TEXT_PADDING, ARGB_LIGHT_GRAY);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void saveData() {
super.saveData();
for (int i = 0; i < Depot.HOURS_IN_DAY; i++) {
data.setFrequency(sliders[i].getIntValue(), i);
}
data.setData(packet -> PacketTrainDataGuiClient.sendUpdate(PACKET_UPDATE_DEPOT, packet));
}
private Component getSuccessfulSegmentsText() {
final int successfulSegments = data.clientPathGenerationSuccessfulSegments;
if (successfulSegments < 0) {
return new TranslatableComponent("gui.mtr.generating_path");
} else if (successfulSegments == 0) {
return new TranslatableComponent("gui.mtr.path_not_generated");
} else {
final List<String> stationNames = new ArrayList<>();
final List<String> routeNames = new ArrayList<>();
final String depotName = IGui.textOrUntitled(IGui.formatStationName(data.name));
if (successfulSegments == 1) {
RailwayData.useRoutesAndStationsFromIndex(0, data.routeIds, ClientData.DATA_CACHE, (currentStationIndex, thisRoute, nextRoute, thisStation, nextStation, lastStation) -> {
stationNames.add(IGui.textOrUntitled(IGui.formatStationName(thisStation.name)));
routeNames.add(IGui.textOrUntitled(IGui.formatStationName(thisRoute.name)));
});
stationNames.add("-");
routeNames.add("-");
return new TranslatableComponent("gui.mtr.path_not_found_between", routeNames.get(0), depotName, stationNames.get(0));
} else {
int sum = 0;
for (int i = 0; i < data.routeIds.size(); i++) {
final Route thisRoute = ClientData.DATA_CACHE.routeIdMap.get(data.routeIds.get(i));
final Route nextRoute = i < data.routeIds.size() - 1 ? ClientData.DATA_CACHE.routeIdMap.get(data.routeIds.get(i + 1)) : null;
if (thisRoute != null) {
sum += thisRoute.platformIds.size();
if (!thisRoute.platformIds.isEmpty() && nextRoute != null && !nextRoute.platformIds.isEmpty() && thisRoute.platformIds.get(thisRoute.platformIds.size() - 1).equals(nextRoute.platformIds.get(0))) {
sum--;
}
}
}
if (successfulSegments >= sum + 2) {
return new TranslatableComponent("gui.mtr.path_found");
} else {
RailwayData.useRoutesAndStationsFromIndex(successfulSegments - 2, data.routeIds, ClientData.DATA_CACHE, (currentStationIndex, thisRoute, nextRoute, thisStation, nextStation, lastStation) -> {
stationNames.add(IGui.textOrUntitled(IGui.formatStationName(thisStation.name)));
if (nextStation == null) {
RailwayData.useRoutesAndStationsFromIndex(successfulSegments - 1, data.routeIds, ClientData.DATA_CACHE, (currentStationIndex1, thisRoute1, nextRoute1, thisStation1, nextStation1, lastStation1) -> stationNames.add(IGui.textOrUntitled(IGui.formatStationName(thisStation1.name))));
} else {
stationNames.add(IGui.textOrUntitled(IGui.formatStationName(nextStation.name)));
}
routeNames.add(IGui.textOrUntitled(IGui.formatStationName(thisRoute.name)));
});
stationNames.add("-");
stationNames.add("-");
routeNames.add("-");
if (successfulSegments < sum + 1) {
return new TranslatableComponent("gui.mtr.path_not_found_between", routeNames.get(0), stationNames.get(0), stationNames.get(1));
} else {
return new TranslatableComponent("gui.mtr.path_not_found_between", routeNames.get(0), stationNames.get(0), depotName);
}
}
}
}
}
private static String getSliderString(int value) {
final String headwayText;
if (value == 0) {
headwayText = "";
} else {
headwayText = " (" + RailwayData.round((float) Depot.TRAIN_FREQUENCY_MULTIPLIER * SECONDS_PER_MC_HOUR / value, 1) + new TranslatableComponent("gui.mtr.s").getString() + ")";
}
return value / (float) Depot.TRAIN_FREQUENCY_MULTIPLIER + new TranslatableComponent("gui.mtr.tph").getString() + headwayText;
}
private static String getTimeString(int hour) {
final String hourString = StringUtils.leftPad(String.valueOf(hour), 2, "0");
return String.format("%s:00-%s:59", hourString, hourString);
}
}
| Fixed depot screen not catching null stations
| common/src/main/java/mtr/screen/EditDepotScreen.java | Fixed depot screen not catching null stations | <ide><path>ommon/src/main/java/mtr/screen/EditDepotScreen.java
<ide>
<ide> if (successfulSegments == 1) {
<ide> RailwayData.useRoutesAndStationsFromIndex(0, data.routeIds, ClientData.DATA_CACHE, (currentStationIndex, thisRoute, nextRoute, thisStation, nextStation, lastStation) -> {
<del> stationNames.add(IGui.textOrUntitled(IGui.formatStationName(thisStation.name)));
<del> routeNames.add(IGui.textOrUntitled(IGui.formatStationName(thisRoute.name)));
<add> stationNames.add(IGui.textOrUntitled(thisStation == null ? "" : IGui.formatStationName(thisStation.name)));
<add> routeNames.add(IGui.textOrUntitled(thisRoute == null ? "" : IGui.formatStationName(thisRoute.name)));
<ide> });
<ide> stationNames.add("-");
<ide> routeNames.add("-");
<ide> return new TranslatableComponent("gui.mtr.path_found");
<ide> } else {
<ide> RailwayData.useRoutesAndStationsFromIndex(successfulSegments - 2, data.routeIds, ClientData.DATA_CACHE, (currentStationIndex, thisRoute, nextRoute, thisStation, nextStation, lastStation) -> {
<del> stationNames.add(IGui.textOrUntitled(IGui.formatStationName(thisStation.name)));
<add> stationNames.add(IGui.textOrUntitled(thisStation == null ? "" : IGui.formatStationName(thisStation.name)));
<ide> if (nextStation == null) {
<del> RailwayData.useRoutesAndStationsFromIndex(successfulSegments - 1, data.routeIds, ClientData.DATA_CACHE, (currentStationIndex1, thisRoute1, nextRoute1, thisStation1, nextStation1, lastStation1) -> stationNames.add(IGui.textOrUntitled(IGui.formatStationName(thisStation1.name))));
<add> RailwayData.useRoutesAndStationsFromIndex(successfulSegments - 1, data.routeIds, ClientData.DATA_CACHE, (currentStationIndex1, thisRoute1, nextRoute1, thisStation1, nextStation1, lastStation1) -> stationNames.add(IGui.textOrUntitled(thisStation1 == null ? "" : IGui.formatStationName(thisStation1.name))));
<ide> } else {
<ide> stationNames.add(IGui.textOrUntitled(IGui.formatStationName(nextStation.name)));
<ide> } |
|
Java | mit | c49d042d056c2488a8628806f16602faf7d340af | 0 | TeamWizardry/TMT-Refraction | package com.teamwizardry.refraction.api.beam;
import com.teamwizardry.librarianlib.client.fx.particle.ParticleBuilder;
import com.teamwizardry.librarianlib.client.fx.particle.ParticleSpawner;
import com.teamwizardry.librarianlib.client.fx.particle.functions.InterpFadeInOut;
import com.teamwizardry.librarianlib.common.network.PacketHandler;
import com.teamwizardry.librarianlib.common.util.bitsaving.IllegalValueSetException;
import com.teamwizardry.librarianlib.common.util.math.interpolate.StaticInterp;
import com.teamwizardry.refraction.Refraction;
import com.teamwizardry.refraction.api.Constants;
import com.teamwizardry.refraction.api.beam.Effect.EffectType;
import com.teamwizardry.refraction.api.internal.PacketLaserFX;
import com.teamwizardry.refraction.api.raytrace.EntityTrace;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
// TODO: make sparkles configurable + whether to spawn them at the end or beginning of a beam.
public class Beam implements INBTSerializable<NBTTagCompound> {
/**
* The initial position the beams comes from.
*/
public Vec3d initLoc;
/**
* The vector that specifies the inclination of the beam.
* Set it to your final location and it'll work.
*/
public Vec3d slope;
/**
* The destination of the beam. Don't touch this, just set the slope to the final loc
* and let this class handle it unless you know what you're doing.
*/
public Vec3d finalLoc;
/**
* The color of the beam including it's alpha.
*/
@NotNull
public Color color = Color.WHITE;
/**
* The world the beam will spawn in.
*/
@NotNull
public World world;
/**
* The effect the beam will produce across itself or at it's destination
*/
@Nullable
public Effect effect;
/**
* Specify whether this beam will be aesthetic only or not.
* If not, it will run the effect dictated by the color unless the effect is changed.
*/
public boolean enableEffect = true;
/**
* If true, the beam will phase through entities.
*/
public boolean ignoreEntities = false;
/**
* The raytrace produced from the beam after it spawns.
* Contains some neat methods you can use.
*/
public RayTraceResult trace;
/**
* The range of the raytrace. Will default to Beam_RANGE unless otherwise specified.
*/
public double range = Constants.BEAM_RANGE;
/**
* A unique identifier for a beam. Used for uniqueness checks.
*/
@NotNull
public UUID uuid = UUID.randomUUID();
/**
* The number of times this beam has bounced or been reflected.
*/
public int bouncedTimes = 0;
/**
* The amount of times this beam is allowed to bounce or reflect.
*/
public int allowedBounceTimes = Constants.BEAM_BOUNCE_LIMIT;
/**
* Will spawn a particle at the beginning of the beam for pretties.
*/
private boolean spawnSparkle = false;
public Beam(@NotNull World world, @NotNull Vec3d initLoc, @NotNull Vec3d slope, @NotNull Color color) {
this.world = world;
this.initLoc = initLoc;
this.slope = slope;
this.finalLoc = slope.normalize().scale(128).add(initLoc);
this.color = color;
}
public Beam(World world, double initX, double initY, double initZ, double slopeX, double slopeY, double slopeZ, Color color) {
this(world, new Vec3d(initX, initY, initZ), new Vec3d(slopeX, slopeY, slopeZ), color);
}
public Beam(World world, double initX, double initY, double initZ, double slopeX, double slopeY, double slopeZ, float red, float green, float blue, float alpha) {
this(world, initX, initY, initZ, slopeX, slopeY, slopeZ, new Color(red, green, blue, alpha));
}
public Beam(NBTTagCompound compound) {
deserializeNBT(compound);
}
/**
* Will create a beam that's exactly like the one passed.
*
* @return The new beam created. Can be modified as needed.
*/
public Beam createSimilarBeam() {
return createSimilarBeam(initLoc, finalLoc);
}
/**
* Will create a beam that's exactly like the one passed except in color.
*
* @return The new beam created. Can be modified as needed.
*/
public Beam createSimilarBeam(Color color) {
return createSimilarBeam(initLoc, finalLoc, color);
}
/**
* Will create a similar beam that starts from the position this beam ended at
* and will set it's slope to the one specified. So it's a new beam from the position
* you last hit to the new one you specify.
*
* @param slope The slope or destination or final location the beam will point to.
* @return The new beam created. Can be modified as needed.
*/
public Beam createSimilarBeam(Vec3d slope) {
return createSimilarBeam(finalLoc, slope);
}
/**
* Will create a similar beam that starts and ends in the positions you specify
*
* @param init The initial location or origin to spawn the beam from.
* @param dir The direction or slope or final destination or location the beam will point to.
* @return The new beam created. Can be modified as needed.
*/
public Beam createSimilarBeam(Vec3d init, Vec3d dir) {
return createSimilarBeam(init, dir, color);
}
/**
* Will create a similar beam that starts and ends in the positions you specify, with a custom color.
*
* @param init The initial location or origin to spawn the beam from.
* @param dir The direction or slope or final destination or location the beam will point to.
* @return The new beam created. Can be modified as needed.
*/
public Beam createSimilarBeam(Vec3d init, Vec3d dir, Color color) {
return new Beam(world, init, dir, color)
.setIgnoreEntities(ignoreEntities)
.setEnableEffect(enableEffect)
.setUUID(uuid)
.setAllowedBounceTimes(allowedBounceTimes)
.setBouncedTimes(bouncedTimes)
.incrementBouncedTimes();
}
/**
* Will create a tiny particle at it's end for pretties.
*
* @return The new beam created. Can be modified as needed.
*/
public Beam spawnParticle() {
this.spawnSparkle = true;
return this;
}
/**
* Will set the amount of times this beam has already bounced or been reflected
*
* @param bouncedTimes The amount of times this beam has bounced or been reflected
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setBouncedTimes(int bouncedTimes) {
this.bouncedTimes = bouncedTimes;
return this;
}
/**
* Will set the amount of times this beam will be allowed to bounce or reflect.
*
* @param allowedBounceTimes The amount of times this beam is allowed to bounce or reflect
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setAllowedBounceTimes(int allowedBounceTimes) {
this.allowedBounceTimes = allowedBounceTimes;
return this;
}
/**
* Will change the slope or destination or final location the beam will point to.
*
* @param slope The final location or destination.
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setSlope(@NotNull Vec3d slope) {
this.slope = slope;
this.finalLoc = slope.normalize().scale(128).add(initLoc);
return this;
}
/**
* Will increment the amount of times this beam has bounced or reflected
*
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam incrementBouncedTimes() {
bouncedTimes++;
return this;
}
/**
* Will change the color of the beam with the alpha.
*
* @param color The color of the new beam.
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setColor(@NotNull Color color) {
this.color = color;
return this;
}
/**
* If set to true, the beam will phase through entities.
*
* @param ignoreEntities The boolean that will specify if the beam should phase through blocks or not. Default false.
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setIgnoreEntities(boolean ignoreEntities) {
this.ignoreEntities = ignoreEntities;
return this;
}
/**
* If set to false, the beam will be an aesthetic only beam that will not produce any effect.
*
* @param enableEffect The boolean that will specify if the beam should enable it's effect or not. Default true.
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setEnableEffect(boolean enableEffect) {
this.enableEffect = enableEffect;
return this;
}
/**
* Will set the beam's new starting position or origin and will continue on towards the slope still specified.
*
* @param initLoc The new initial location to set the beam to start from.
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setInitLoc(@NotNull Vec3d initLoc) {
this.initLoc = initLoc;
this.finalLoc = slope.normalize().scale(128).add(initLoc);
return this;
}
/**
* Will set the beam's effect if you don't want it to autodetect the effect by itself from the color
* you specified.
*
* @param effect The new effect this beam will produce.
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setEffect(@Nullable Effect effect) {
this.effect = effect;
return this;
}
/**
* Will set the range the raytrace will attempt.
*
* @param range The new range of the beam. Default: Constants.BEAM_RANGE
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setRange(double range) {
this.range = range;
return this;
}
public UUID getUUID() {
return this.uuid;
}
public Beam setUUID(UUID uuid) {
this.uuid = uuid;
return this;
}
private Beam initializeVariables() {
// EFFECT CHECKING //
if (effect == null && enableEffect) {
Effect tempEffect = EffectTracker.getEffect(this);
if (tempEffect != null) {
if (tempEffect.getCooldown() == 0) effect = tempEffect;
else if (ThreadLocalRandom.current().nextInt(0, tempEffect.getCooldown()) == 0) effect = tempEffect;
}
} else if (effect != null && !enableEffect) effect = null;
// EFFECT CHECKING //
// BEAM PHASING CHECKS //
EntityTrace entityTrace = new EntityTrace(world, initLoc, slope).setRange(range);
if (ignoreEntities || (effect != null && effect.getType() == EffectType.BEAM)) // If anyone of these are true, phase beam
trace = entityTrace.setIgnoreEntities(true).cast();
else trace = entityTrace.setIgnoreEntities(false).cast();
// BEAM PHASING CHECKS //
if (trace != null && trace.hitVec != null) this.finalLoc = trace.hitVec;
return this;
}
/**
* Will spawn the final complete beam.
*/
public void spawn() {
if (world.isRemote) return;
if (color.getAlpha() <= 1) return;
if (bouncedTimes > allowedBounceTimes) return;
initializeVariables();
if (trace == null) return;
if (trace.hitVec == null) return;
if (finalLoc == null) return;
// EFFECT HANDLING //
boolean pass = true;
// IBeamHandler handling
if (trace.typeOfHit == RayTraceResult.Type.BLOCK) {
IBlockState state = world.getBlockState(trace.getBlockPos());
if (state.getBlock() instanceof IBeamHandler) {
ReflectionTracker.getInstance(world).recieveBeam(world, trace.getBlockPos(), (IBeamHandler) state.getBlock(), this);
pass = false;
}
}
// Effect handling
if (effect != null) {
if (effect.getType() == EffectType.BEAM)
EffectTracker.addEffect(world, this);
else if (pass) {
if (effect.getType() == EffectType.SINGLE) {
if (trace.typeOfHit != RayTraceResult.Type.MISS)
EffectTracker.addEffect(world, trace.hitVec, effect);
else if (trace.typeOfHit == RayTraceResult.Type.BLOCK) {
BlockPos pos = trace.getBlockPos();
EffectTracker.addEffect(world, new Vec3d(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5), effect);
}
}
}
}
// EFFECT HANDLING
// PLAYER REFLECTING
if (trace.typeOfHit == RayTraceResult.Type.ENTITY && trace.entityHit instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer) trace.entityHit;
if (player.getItemStackFromSlot(EntityEquipmentSlot.HEAD) != null
&& player.getItemStackFromSlot(EntityEquipmentSlot.CHEST) != null
&& player.getItemStackFromSlot(EntityEquipmentSlot.LEGS) != null
&& player.getItemStackFromSlot(EntityEquipmentSlot.FEET) != null)
createSimilarBeam(player.getLook(1)).setIgnoreEntities(true).spawnParticle().spawn();
}
// PLAYER REFLECTING
// PARTICLES
if (spawnSparkle) {
ParticleBuilder reflectionSparkle = new ParticleBuilder(2);
reflectionSparkle.setAlphaFunction(new InterpFadeInOut(0.1f, 0.1f));
reflectionSparkle.setRender(new ResourceLocation(Refraction.MOD_ID, "particles/glow"));
reflectionSparkle.disableRandom();
reflectionSparkle.disableMotionCalculation();
reflectionSparkle.setScale((float) (ThreadLocalRandom.current().nextDouble(1, 1.3)));
reflectionSparkle.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), ThreadLocalRandom.current().nextInt(18, 20)));
ParticleSpawner.spawn(reflectionSparkle, world, new StaticInterp<>(initLoc), 1);
}
// PARTICLES
// Particle packet sender
PacketHandler.NETWORK.sendToAllAround(new PacketLaserFX(initLoc, finalLoc, color), new NetworkRegistry.TargetPoint(world.provider.getDimension(), initLoc.xCoord, initLoc.yCoord, initLoc.zCoord, 256));
}
@Override
public boolean equals(Object other) {
return other instanceof Beam && ((Beam) other).uuid.equals(uuid);
}
@Override
public int hashCode() {
return uuid.hashCode();
}
@Override
public NBTTagCompound serializeNBT() {
NBTTagCompound compound = new NBTTagCompound();
compound.setDouble("init_loc_x", initLoc.xCoord);
compound.setDouble("init_loc_y", initLoc.yCoord);
compound.setDouble("init_loc_z", initLoc.zCoord);
compound.setDouble("slope_x", slope.xCoord);
compound.setDouble("slope_y", slope.yCoord);
compound.setDouble("slope_z", slope.zCoord);
compound.setInteger("color", color.getRGB());
compound.setInteger("color_alpha", color.getAlpha());
compound.setInteger("world", world.provider.getDimension());
compound.setUniqueId("uuid", uuid);
compound.setBoolean("ignore_entities", ignoreEntities);
compound.setBoolean("enable_effect", enableEffect);
return compound;
}
@Override
public void deserializeNBT(NBTTagCompound nbt) {
if (nbt.hasKey("world"))
world = FMLCommonHandler.instance().getMinecraftServerInstance().worldServerForDimension(nbt.getInteger("dim"));
else throw new NullPointerException("'world' key not found or missing in deserialized beam object.");
if (nbt.hasKey("init_loc_x") && nbt.hasKey("init_loc_y") && nbt.hasKey("init_loc_z"))
initLoc = new Vec3d(nbt.getDouble("init_loc_x"), nbt.getDouble("init_loc_y"), nbt.getDouble("init_loc_z"));
else throw new NullPointerException("'init_loc' key not found or missing in deserialized beam object.");
if (nbt.hasKey("slope_loc_x") && nbt.hasKey("slope_loc_y") && nbt.hasKey("slope_loc_z")) {
slope = new Vec3d(nbt.getDouble("slope_x"), nbt.getDouble("slope_y"), nbt.getDouble("slope_z"));
finalLoc = slope.normalize().scale(128).add(initLoc);
} else throw new NullPointerException("'slope' key not found or missing in deserialized beam object.");
if (nbt.hasKey("color")) {
color = new Color(nbt.getInteger("color"));
color = new Color(color.getRed(), color.getGreen(), color.getBlue(), nbt.getInteger("color_alpha"));
} else
throw new NullPointerException("'color' or 'color_alpha' keys not found or missing in deserialized beam object.");
if (nbt.hasKey("uuid")) if (nbt.hasKey("uuid")) uuid = nbt.getUniqueId("uuid");
else throw new IllegalValueSetException("'uuid' key not found or missing in deserialized beam object.");
if (nbt.hasKey("ignore_entities")) ignoreEntities = nbt.getBoolean("ignore_entities");
if (nbt.hasKey("enable_effect")) enableEffect = nbt.getBoolean("enable_effect");
}
}
| src/main/java/com/teamwizardry/refraction/api/beam/Beam.java | package com.teamwizardry.refraction.api.beam;
import com.teamwizardry.librarianlib.client.fx.particle.ParticleBuilder;
import com.teamwizardry.librarianlib.client.fx.particle.ParticleSpawner;
import com.teamwizardry.librarianlib.client.fx.particle.functions.InterpFadeInOut;
import com.teamwizardry.librarianlib.common.network.PacketHandler;
import com.teamwizardry.librarianlib.common.util.bitsaving.IllegalValueSetException;
import com.teamwizardry.librarianlib.common.util.math.interpolate.StaticInterp;
import com.teamwizardry.refraction.Refraction;
import com.teamwizardry.refraction.api.Constants;
import com.teamwizardry.refraction.api.beam.Effect.EffectType;
import com.teamwizardry.refraction.api.internal.PacketLaserFX;
import com.teamwizardry.refraction.api.raytrace.EntityTrace;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
public class Beam implements INBTSerializable<NBTTagCompound> {
/**
* The initial position the beams comes from.
*/
public Vec3d initLoc;
/**
* The vector that specifies the inclination of the beam.
* Set it to your final location and it'll work.
*/
public Vec3d slope;
/**
* The destination of the beam. Don't touch this, just set the slope to the final loc
* and let this class handle it unless you know what you're doing.
*/
public Vec3d finalLoc;
/**
* The color of the beam including it's alpha.
*/
@NotNull
public Color color = Color.WHITE;
/**
* The world the beam will spawn in.
*/
@NotNull
public World world;
/**
* The effect the beam will produce across itself or at it's destination
*/
@Nullable
public Effect effect;
/**
* Specify whether this beam will be aesthetic only or not.
* If not, it will run the effect dictated by the color unless the effect is changed.
*/
public boolean enableEffect = true;
/**
* If true, the beam will phase through entities.
*/
public boolean ignoreEntities = false;
/**
* The raytrace produced from the beam after it spawns.
* Contains some neat methods you can use.
*/
public RayTraceResult trace;
/**
* The range of the raytrace. Will default to Beam_RANGE unless otherwise specified.
*/
public double range = Constants.BEAM_RANGE;
/**
* A unique identifier for a beam. Used for uniqueness checks.
*/
@NotNull
public UUID uuid = UUID.randomUUID();
/**
* The number of times this beam has bounced or been reflected.
*/
public int bouncedTimes = 0;
/**
* The amount of times this beam is allowed to bounce or reflect.
*/
public int allowedBounceTimes = Constants.BEAM_BOUNCE_LIMIT;
/**
* Will spawn a particle at the beginning of the beam for pretties.
*/
private boolean spawnSparkle = false;
public Beam(@NotNull World world, @NotNull Vec3d initLoc, @NotNull Vec3d slope, @NotNull Color color) {
this.world = world;
this.initLoc = initLoc;
this.slope = slope;
this.finalLoc = slope.normalize().scale(128).add(initLoc);
this.color = color;
}
public Beam(World world, double initX, double initY, double initZ, double slopeX, double slopeY, double slopeZ, Color color) {
this(world, new Vec3d(initX, initY, initZ), new Vec3d(slopeX, slopeY, slopeZ), color);
}
public Beam(World world, double initX, double initY, double initZ, double slopeX, double slopeY, double slopeZ, float red, float green, float blue, float alpha) {
this(world, initX, initY, initZ, slopeX, slopeY, slopeZ, new Color(red, green, blue, alpha));
}
public Beam(NBTTagCompound compound) {
deserializeNBT(compound);
}
/**
* Will create a beam that's exactly like the one passed.
*
* @return The new beam created. Can be modified as needed.
*/
public Beam createSimilarBeam() {
return createSimilarBeam(initLoc, finalLoc);
}
/**
* Will create a beam that's exactly like the one passed except in color.
*
* @return The new beam created. Can be modified as needed.
*/
public Beam createSimilarBeam(Color color) {
return createSimilarBeam(initLoc, finalLoc, color);
}
/**
* Will create a similar beam that starts from the position this beam ended at
* and will set it's slope to the one specified. So it's a new beam from the position
* you last hit to the new one you specify.
*
* @param slope The slope or destination or final location the beam will point to.
* @return The new beam created. Can be modified as needed.
*/
public Beam createSimilarBeam(Vec3d slope) {
return createSimilarBeam(finalLoc, slope);
}
/**
* Will create a similar beam that starts and ends in the positions you specify
*
* @param init The initial location or origin to spawn the beam from.
* @param dir The direction or slope or final destination or location the beam will point to.
* @return The new beam created. Can be modified as needed.
*/
public Beam createSimilarBeam(Vec3d init, Vec3d dir) {
return createSimilarBeam(init, dir, color);
}
/**
* Will create a similar beam that starts and ends in the positions you specify, with a custom color.
*
* @param init The initial location or origin to spawn the beam from.
* @param dir The direction or slope or final destination or location the beam will point to.
* @return The new beam created. Can be modified as needed.
*/
public Beam createSimilarBeam(Vec3d init, Vec3d dir, Color color) {
return new Beam(world, init, dir, color)
.setIgnoreEntities(ignoreEntities)
.setEnableEffect(enableEffect)
.setUUID(uuid)
.setAllowedBounceTimes(allowedBounceTimes)
.setBouncedTimes(bouncedTimes)
.incrementBouncedTimes();
}
/**
* Will create a tiny particle at it's end for pretties.
*
* @return The new beam created. Can be modified as needed.
*/
public Beam spawnParticle() {
this.spawnSparkle = true;
return this;
}
/**
* Will set the amount of times this beam has already bounced or been reflected
*
* @param bouncedTimes The amount of times this beam has bounced or been reflected
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setBouncedTimes(int bouncedTimes) {
this.bouncedTimes = bouncedTimes;
return this;
}
/**
* Will set the amount of times this beam will be allowed to bounce or reflect.
*
* @param allowedBounceTimes The amount of times this beam is allowed to bounce or reflect
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setAllowedBounceTimes(int allowedBounceTimes) {
this.allowedBounceTimes = allowedBounceTimes;
return this;
}
/**
* Will change the slope or destination or final location the beam will point to.
*
* @param slope The final location or destination.
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setSlope(@NotNull Vec3d slope) {
this.slope = slope;
this.finalLoc = slope.normalize().scale(128).add(initLoc);
return this;
}
/**
* Will increment the amount of times this beam has bounced or reflected
*
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam incrementBouncedTimes() {
bouncedTimes++;
return this;
}
/**
* Will change the color of the beam with the alpha.
*
* @param color The color of the new beam.
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setColor(@NotNull Color color) {
this.color = color;
return this;
}
/**
* If set to true, the beam will phase through entities.
*
* @param ignoreEntities The boolean that will specify if the beam should phase through blocks or not. Default false.
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setIgnoreEntities(boolean ignoreEntities) {
this.ignoreEntities = ignoreEntities;
return this;
}
/**
* If set to false, the beam will be an aesthetic only beam that will not produce any effect.
*
* @param enableEffect The boolean that will specify if the beam should enable it's effect or not. Default true.
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setEnableEffect(boolean enableEffect) {
this.enableEffect = enableEffect;
return this;
}
/**
* Will set the beam's new starting position or origin and will continue on towards the slope still specified.
*
* @param initLoc The new initial location to set the beam to start from.
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setInitLoc(@NotNull Vec3d initLoc) {
this.initLoc = initLoc;
this.finalLoc = slope.normalize().scale(128).add(initLoc);
return this;
}
/**
* Will set the beam's effect if you don't want it to autodetect the effect by itself from the color
* you specified.
*
* @param effect The new effect this beam will produce.
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setEffect(@Nullable Effect effect) {
this.effect = effect;
return this;
}
/**
* Will set the range the raytrace will attempt.
*
* @param range The new range of the beam. Default: Constants.BEAM_RANGE
* @return This beam itself for the convenience of editing a beam in one line/chain.
*/
public Beam setRange(double range) {
this.range = range;
return this;
}
public UUID getUUID() {
return this.uuid;
}
public Beam setUUID(UUID uuid) {
this.uuid = uuid;
return this;
}
private Beam initializeVariables() {
// EFFECT CHECKING //
if (effect == null && enableEffect) {
Effect tempEffect = EffectTracker.getEffect(this);
if (tempEffect != null) {
if (tempEffect.getCooldown() == 0) effect = tempEffect;
else if (ThreadLocalRandom.current().nextInt(0, tempEffect.getCooldown()) == 0) effect = tempEffect;
}
} else if (effect != null && !enableEffect) effect = null;
// EFFECT CHECKING //
// BEAM PHASING CHECKS //
EntityTrace entityTrace = new EntityTrace(world, initLoc, slope).setRange(range);
if (ignoreEntities || (effect != null && effect.getType() == EffectType.BEAM)) // If anyone of these are true, phase beam
trace = entityTrace.setIgnoreEntities(true).cast();
else trace = entityTrace.setIgnoreEntities(false).cast();
// BEAM PHASING CHECKS //
if (trace != null && trace.hitVec != null) this.finalLoc = trace.hitVec;
return this;
}
/**
* Will spawn the final complete beam.
*/
public void spawn() {
if (world.isRemote) return;
if (color.getAlpha() <= 1) return;
if (bouncedTimes > allowedBounceTimes) return;
initializeVariables();
if (trace == null) return;
if (trace.hitVec == null) return;
if (finalLoc == null) return;
// EFFECT HANDLING //
boolean pass = true;
// IBeamHandler handling
if (trace.typeOfHit == RayTraceResult.Type.BLOCK) {
IBlockState state = world.getBlockState(trace.getBlockPos());
if (state.getBlock() instanceof IBeamHandler) {
ReflectionTracker.getInstance(world).recieveBeam(world, trace.getBlockPos(), (IBeamHandler) state.getBlock(), this);
pass = false;
}
}
// Effect handling
if (effect != null) {
if (effect.getType() == EffectType.BEAM)
EffectTracker.addEffect(world, this);
else if (pass) {
if (effect.getType() == EffectType.SINGLE) {
if (trace.typeOfHit != RayTraceResult.Type.MISS)
EffectTracker.addEffect(world, trace.hitVec, effect);
else if (trace.typeOfHit == RayTraceResult.Type.BLOCK) {
BlockPos pos = trace.getBlockPos();
EffectTracker.addEffect(world, new Vec3d(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5), effect);
}
}
}
}
// EFFECT HANDLING
// PLAYER REFLECTING
if (trace.typeOfHit == RayTraceResult.Type.ENTITY && trace.entityHit instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer) trace.entityHit;
if (player.getItemStackFromSlot(EntityEquipmentSlot.HEAD) != null
&& player.getItemStackFromSlot(EntityEquipmentSlot.CHEST) != null
&& player.getItemStackFromSlot(EntityEquipmentSlot.LEGS) != null
&& player.getItemStackFromSlot(EntityEquipmentSlot.FEET) != null)
createSimilarBeam(player.getLook(1)).setIgnoreEntities(true).spawn();
}
// PLAYER REFLECTING
// PARTICLES
if (spawnSparkle) {
ParticleBuilder reflectionSparkle = new ParticleBuilder(2);
reflectionSparkle.setAlphaFunction(new InterpFadeInOut(0.1f, 0.1f));
reflectionSparkle.setRender(new ResourceLocation(Refraction.MOD_ID, "particles/glow"));
reflectionSparkle.disableRandom();
reflectionSparkle.disableMotionCalculation();
reflectionSparkle.setScale((float) (ThreadLocalRandom.current().nextDouble(0.8, 1) / color.getAlpha()));
reflectionSparkle.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), ThreadLocalRandom.current().nextInt(10, 15)));
ParticleSpawner.spawn(reflectionSparkle, world, new StaticInterp<>(initLoc), 1);
}
// PARTICLES
// Particle packet sender
PacketHandler.NETWORK.sendToAllAround(new PacketLaserFX(initLoc, finalLoc, color), new NetworkRegistry.TargetPoint(world.provider.getDimension(), initLoc.xCoord, initLoc.yCoord, initLoc.zCoord, 256));
}
@Override
public boolean equals(Object other) {
return other instanceof Beam && ((Beam) other).uuid.equals(uuid);
}
@Override
public int hashCode() {
return uuid.hashCode();
}
@Override
public NBTTagCompound serializeNBT() {
NBTTagCompound compound = new NBTTagCompound();
compound.setDouble("init_loc_x", initLoc.xCoord);
compound.setDouble("init_loc_y", initLoc.yCoord);
compound.setDouble("init_loc_z", initLoc.zCoord);
compound.setDouble("slope_x", slope.xCoord);
compound.setDouble("slope_y", slope.yCoord);
compound.setDouble("slope_z", slope.zCoord);
compound.setInteger("color", color.getRGB());
compound.setInteger("color_alpha", color.getAlpha());
compound.setInteger("world", world.provider.getDimension());
compound.setUniqueId("uuid", uuid);
compound.setBoolean("ignore_entities", ignoreEntities);
compound.setBoolean("enable_effect", enableEffect);
return compound;
}
@Override
public void deserializeNBT(NBTTagCompound nbt) {
if (nbt.hasKey("world"))
world = FMLCommonHandler.instance().getMinecraftServerInstance().worldServerForDimension(nbt.getInteger("dim"));
else throw new NullPointerException("'world' key not found or missing in deserialized beam object.");
if (nbt.hasKey("init_loc_x") && nbt.hasKey("init_loc_y") && nbt.hasKey("init_loc_z"))
initLoc = new Vec3d(nbt.getDouble("init_loc_x"), nbt.getDouble("init_loc_y"), nbt.getDouble("init_loc_z"));
else throw new NullPointerException("'init_loc' key not found or missing in deserialized beam object.");
if (nbt.hasKey("slope_loc_x") && nbt.hasKey("slope_loc_y") && nbt.hasKey("slope_loc_z")) {
slope = new Vec3d(nbt.getDouble("slope_x"), nbt.getDouble("slope_y"), nbt.getDouble("slope_z"));
finalLoc = slope.normalize().scale(128).add(initLoc);
} else throw new NullPointerException("'slope' key not found or missing in deserialized beam object.");
if (nbt.hasKey("color")) {
color = new Color(nbt.getInteger("color"));
color = new Color(color.getRed(), color.getGreen(), color.getBlue(), nbt.getInteger("color_alpha"));
} else
throw new NullPointerException("'color' or 'color_alpha' keys not found or missing in deserialized beam object.");
if (nbt.hasKey("uuid")) if (nbt.hasKey("uuid")) uuid = nbt.getUniqueId("uuid");
else throw new IllegalValueSetException("'uuid' key not found or missing in deserialized beam object.");
if (nbt.hasKey("ignore_entities")) ignoreEntities = nbt.getBoolean("ignore_entities");
if (nbt.hasKey("enable_effect")) enableEffect = nbt.getBoolean("enable_effect");
}
}
| adjust sparkle numbers
| src/main/java/com/teamwizardry/refraction/api/beam/Beam.java | adjust sparkle numbers | <ide><path>rc/main/java/com/teamwizardry/refraction/api/beam/Beam.java
<ide> import java.util.UUID;
<ide> import java.util.concurrent.ThreadLocalRandom;
<ide>
<add>// TODO: make sparkles configurable + whether to spawn them at the end or beginning of a beam.
<ide> public class Beam implements INBTSerializable<NBTTagCompound> {
<ide>
<ide> /**
<ide> && player.getItemStackFromSlot(EntityEquipmentSlot.CHEST) != null
<ide> && player.getItemStackFromSlot(EntityEquipmentSlot.LEGS) != null
<ide> && player.getItemStackFromSlot(EntityEquipmentSlot.FEET) != null)
<del> createSimilarBeam(player.getLook(1)).setIgnoreEntities(true).spawn();
<add> createSimilarBeam(player.getLook(1)).setIgnoreEntities(true).spawnParticle().spawn();
<ide> }
<ide> // PLAYER REFLECTING
<ide>
<ide> reflectionSparkle.setRender(new ResourceLocation(Refraction.MOD_ID, "particles/glow"));
<ide> reflectionSparkle.disableRandom();
<ide> reflectionSparkle.disableMotionCalculation();
<del> reflectionSparkle.setScale((float) (ThreadLocalRandom.current().nextDouble(0.8, 1) / color.getAlpha()));
<del> reflectionSparkle.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), ThreadLocalRandom.current().nextInt(10, 15)));
<add> reflectionSparkle.setScale((float) (ThreadLocalRandom.current().nextDouble(1, 1.3)));
<add> reflectionSparkle.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), ThreadLocalRandom.current().nextInt(18, 20)));
<ide> ParticleSpawner.spawn(reflectionSparkle, world, new StaticInterp<>(initLoc), 1);
<ide> }
<ide> // PARTICLES |
|
JavaScript | apache-2.0 | c7c8b2650c707e13bca790a1fcc2679e098ba883 | 0 | Goyatuzo/LurkerBot,Goyatuzo/LurkerBot | "use strict";
var fs = require('fs');
var mkdirp = require('mkdirp');
function _twoDigits(num) {
var s = num.toString();
return ("0" + s).slice(-2);
}
function _getCurrTimeString() {
var d = new Date();
var hours = _twoDigits(d.getHours());
var mins = _twoDigits(d.getMinutes());
var secs = _twoDigits(d.getSeconds());
return hours + ":" + mins + ":" + secs;
}
function _lineFormat(line) {
var t = _getCurrTimeString();
return `[${t}] ${line}`;
}
class Logger {
constructor() {
this.norm = [];
this.warning = [];
this.err = [];
mkdirp('output', function (err) {
if (err) throw err;
});
var curr = new Date();
var fileName = `${curr.getFullYear()}-${curr.getMonth()}-${curr.getDate()} ${curr.getHours()}:${curr.getMinutes()}:${curr.getSeconds()}`;
this.wstream = fs.createWriteStream(`output/${fileName}.log`);
}
log(line) {
var toPrint = _lineFormat(line);
this.norm.push(toPrint);
console.log(toPrint);
this.wstream.write(toPrint + '\n');
}
warn(line) {
var toPrint = _lineFormat("WARNING: " + line);
this.warning.push(toPrint);
console.log(toPrint);
this.wstream.write(toPrint + '\n');
}
error(line) {
var toPrint = _lineFormat("ERROR: " + line);
this.err.push(toPrint);
console.log(toPrint);
this.wstream.write(toPrint + '\n');
}
}
var logger = new Logger();
// Print node.js version.
for (var dependency in process.versions) {
logger.log(dependency + ": " + process.versions[dependency]);
}
module.exports = logger;
| src/logger.js | "use strict";
var fs = require('fs');
var mkdirp = require('mkdirp');
function _twoDigits(num) {
var s = num.toString();
return ("0" + s).slice(-2);
}
function _getCurrTimeString() {
var d = new Date();
var hours = _twoDigits(d.getHours());
var mins = _twoDigits(d.getMinutes());
var secs = _twoDigits(d.getSeconds());
return hours + ":" + mins + ":" + secs;
}
function _lineFormat(line) {
var t = _getCurrTimeString();
return `[${t}] ${line}`;
}
class Logger {
constructor() {
this.norm = [];
this.warning = [];
this.err = [];
mkdirp('output', function (err) {
if (err) throw err;
});
var curr = new Date();
var fileName = `${curr.getFullYear()}-${curr.getMonth()}-${curr.getDate()}-${curr.getHours()}-${curr.getMinutes()}-${curr.getSeconds()}`;
this.wstream = fs.createWriteStream(`output/${fileName}.log`);
}
log(line) {
var toPrint = _lineFormat(line);
this.norm.push(toPrint);
console.log(toPrint);
this.wstream.write(toPrint + '\n');
}
warn(line) {
var toPrint = _lineFormat("WARNING: " + line);
this.warning.push(toPrint);
console.log(toPrint);
this.wstream.write(toPrint + '\n');
}
error(line) {
var toPrint = _lineFormat("ERROR: " + line);
this.err.push(toPrint);
console.log(toPrint);
this.wstream.write(toPrint + '\n');
}
}
var logger = new Logger();
// Print node.js version.
for (var dependency in process.versions) {
logger.log(dependency + ": " + process.versions[dependency]);
}
module.exports = logger;
| More legible log file names.
| src/logger.js | More legible log file names. | <ide><path>rc/logger.js
<ide>
<ide> var curr = new Date();
<ide>
<del> var fileName = `${curr.getFullYear()}-${curr.getMonth()}-${curr.getDate()}-${curr.getHours()}-${curr.getMinutes()}-${curr.getSeconds()}`;
<add> var fileName = `${curr.getFullYear()}-${curr.getMonth()}-${curr.getDate()} ${curr.getHours()}:${curr.getMinutes()}:${curr.getSeconds()}`;
<ide>
<ide> this.wstream = fs.createWriteStream(`output/${fileName}.log`);
<ide> } |
|
Java | mit | c239f0253b8abb779612a179d6179cfd049b2600 | 0 | AllForFun/modpack,AllForFun/modpack | package com.allforfunmc.allforfuncore;
import java.util.ArrayList;
import java.util.Random;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@Mod(modid = "AllForFunCore", name = "AllForFun's Modpack Core", version = "1")
public class Core {
/**
* @see Debug.Debug
* @deprecated
* Removing in ONE week
*/
@Deprecated
public static final Boolean BooleanDebugMode = true;
/**
* @see Debug.Debug
* @deprecated
* Removing in ONE week
*/
@Deprecated
public static void Debug(Object Message){
if(Core.BooleanDebugMode) {System.out.println(Message);}
}
/**
* @see Debug.Debug
* @deprecated
* Removing in ONE week
*/
@Deprecated
public static void Debug(Exception Error){
if(Core.BooleanDebugMode) {
System.out.println("=======Error=======");
System.out.println(Error.getMessage());
System.out.println(Error.getStackTrace());
System.out.println("=======Error=======");}
}
public static DebugMode debugMode = DebugMode.None;
@Instance(value = "GenericModID")
public static Core instance;
@SidedProxy(clientSide = "com.allforfunmc.allforfuncore.ClientProxy", serverSide = "com.allforfunmc.allforfuncore.CommonProxy")
public static CommonProxy proxy;
@EventHandler()
public void preInit(FMLPreInitializationEvent event) {
Config Config = new Config(event);
Config.load();
}
@EventHandler()
public void load(FMLInitializationEvent event) {
proxy.registerRenderers();
}
@EventHandler()
public void postInit(FMLInitializationEvent event) {
}
// Below is custom code for the mod -- used in all of AllForFun's Mods.
public static final CreativeTabs AllForFunItems = new CreativeTabs(CreativeTabs.getNextID(), "AllForFun's Items") {
@Override
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return com.allforfunmc.refineddiamond.Code.refinedDiamond;
}
};
public static final CreativeTabs AllForFunFood = new CreativeTabs(CreativeTabs.getNextID(), "AllForFun's Food") {
@Override
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return com.allforfunmc.chocolatestuff.Code.chocolateBar;
}
};
public static final CreativeTabs AllForFunArmor = new CreativeTabs(CreativeTabs.getNextID(), "AllForFun's Armor") {
@Override
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return com.allforfunmc.moreoresandmore.Main.armorCobbleChest;
}
};
public static final CreativeTabs AllForFunBlocks = new CreativeTabs(CreativeTabs.getNextID(), "AllForFun's Blocks") {
@Override
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return Item.getItemFromBlock(com.allforfunmc.refineddiamond.Code.Refined_Diamond_Block);
}
};
public static final CreativeTabs AllForFunTools = new CreativeTabs(CreativeTabs.getNextID(), "AllForFun's Tools") {
@Override
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return com.allforfunmc.refineddiamond.Code.MeltingPick;
}
};
/**
* Get drops of an ore
*
* @param Item
* to drop
* @param Fortune
* of pickaxe (6th param of getDrops)
* @return List of items to drop.
*/
public static final ArrayList<ItemStack> getOreDrops(Item itemDropped, int fortune) {
ArrayList<ItemStack> drops = new ArrayList<ItemStack>();
drops.add(new ItemStack(itemDropped, 1));
if (fortune >= 0 && Core.Random.nextBoolean()) {
drops.add(new ItemStack(itemDropped, 1));
}
if (fortune >= 2 && Random.nextBoolean()) {
drops.add(new ItemStack(itemDropped, 1));
}
if (fortune >= 3 && drops.size() < 3 && Random.nextBoolean()) {
drops.add(new ItemStack(itemDropped, 1));
}
return drops;
}
public static int NullID;
public static Random Random = new Random();
} | src/main/java/com/allforfunmc/allforfuncore/Core.java | package com.allforfunmc.allforfuncore;
import java.util.ArrayList;
import java.util.Random;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@Mod(modid = "AllForFunCore", name = "AllForFun's Modpack Core", version = "1")
public class Core {
@Deprecated
public static final Boolean BooleanDebugMode = true;
@Deprecated
public static void Debug(Object Message){
if(Core.BooleanDebugMode) {System.out.println(Message);}
}
@Deprecated
public static void Debug(Exception Error){
if(Core.BooleanDebugMode) {
System.out.println("=======Error=======");
System.out.println(Error.getMessage());
System.out.println(Error.getStackTrace());
System.out.println("=======Error=======");}
}
public static DebugMode debugMode = DebugMode.None;
@Instance(value = "GenericModID")
public static Core instance;
@SidedProxy(clientSide = "com.allforfunmc.allforfuncore.ClientProxy", serverSide = "com.allforfunmc.allforfuncore.CommonProxy")
public static CommonProxy proxy;
@EventHandler()
public void preInit(FMLPreInitializationEvent event) {
Config Config = new Config(event);
Config.load();
}
@EventHandler()
public void load(FMLInitializationEvent event) {
proxy.registerRenderers();
}
@EventHandler()
public void postInit(FMLInitializationEvent event) {
}
// Below is custom code for the mod -- used in all of AllForFun's Mods.
public static final CreativeTabs AllForFunItems = new CreativeTabs(CreativeTabs.getNextID(), "AllForFun's Items") {
@Override
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return com.allforfunmc.refineddiamond.Code.refinedDiamond;
}
};
public static final CreativeTabs AllForFunFood = new CreativeTabs(CreativeTabs.getNextID(), "AllForFun's Food") {
@Override
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return com.allforfunmc.chocolatestuff.Code.chocolateBar;
}
};
public static final CreativeTabs AllForFunArmor = new CreativeTabs(CreativeTabs.getNextID(), "AllForFun's Armor") {
@Override
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return com.allforfunmc.moreoresandmore.Main.armorCobbleChest;
}
};
public static final CreativeTabs AllForFunBlocks = new CreativeTabs(CreativeTabs.getNextID(), "AllForFun's Blocks") {
@Override
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return Item.getItemFromBlock(com.allforfunmc.refineddiamond.Code.Refined_Diamond_Block);
}
};
public static final CreativeTabs AllForFunTools = new CreativeTabs(CreativeTabs.getNextID(), "AllForFun's Tools") {
@Override
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return com.allforfunmc.refineddiamond.Code.MeltingPick;
}
};
/**
* Get drops of an ore
*
* @param Item
* to drop
* @param Fortune
* of pickaxe (6th param of getDrops)
* @return List of items to drop.
*/
public static final ArrayList<ItemStack> getOreDrops(Item itemDropped, int fortune) {
ArrayList<ItemStack> drops = new ArrayList<ItemStack>();
drops.add(new ItemStack(itemDropped, 1));
if (fortune >= 0 && Core.Random.nextBoolean()) {
drops.add(new ItemStack(itemDropped, 1));
}
if (fortune >= 2 && Random.nextBoolean()) {
drops.add(new ItemStack(itemDropped, 1));
}
if (fortune >= 3 && drops.size() < 3 && Random.nextBoolean()) {
drops.add(new ItemStack(itemDropped, 1));
}
return drops;
}
public static int NullID;
public static Random Random = new Random();
} | It's Deprecated
| src/main/java/com/allforfunmc/allforfuncore/Core.java | It's Deprecated | <ide><path>rc/main/java/com/allforfunmc/allforfuncore/Core.java
<ide>
<ide> @Mod(modid = "AllForFunCore", name = "AllForFun's Modpack Core", version = "1")
<ide> public class Core {
<add> /**
<add> * @see Debug.Debug
<add> * @deprecated
<add> * Removing in ONE week
<add> */
<ide> @Deprecated
<ide> public static final Boolean BooleanDebugMode = true;
<add> /**
<add> * @see Debug.Debug
<add> * @deprecated
<add> * Removing in ONE week
<add> */
<ide> @Deprecated
<ide> public static void Debug(Object Message){
<ide> if(Core.BooleanDebugMode) {System.out.println(Message);}
<ide> }
<add> /**
<add> * @see Debug.Debug
<add> * @deprecated
<add> * Removing in ONE week
<add> */
<ide> @Deprecated
<ide> public static void Debug(Exception Error){
<ide> if(Core.BooleanDebugMode) { |
|
Java | mit | dea9e8631e5b835904901b5c3fb44083bc9157c6 | 0 | begeekmyfriend/yasea,illuminoo/yasea,begeekmyfriend/yasea,begeekmyfriend/yasea,illuminoo/yasea,illuminoo/yasea,begeekmyfriend/yasea,begeekmyfriend/yasea,illuminoo/yasea,begeekmyfriend/yasea,illuminoo/yasea,illuminoo/yasea | app/src/main/java/com/seu/magicfilter/base/MagicCameraInputFilter.java | package com.seu.magicfilter.base;
import java.nio.FloatBuffer;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import net.ossrs.yasea.R;
import com.seu.magicfilter.base.gpuimage.GPUImageFilter;
import com.seu.magicfilter.utils.OpenGlUtils;
public class MagicCameraInputFilter extends GPUImageFilter{
private float[] mTextureTransformMatrix;
private int mTextureTransformMatrixLocation;
private int mSingleStepOffsetLocation;
private int mParamsLocation;
private int[] mFrameBuffers = null;
private int[] mFrameBufferTextures = null;
private int mFrameWidth = -1;
private int mFrameHeight = -1;
public MagicCameraInputFilter(){
super(OpenGlUtils.readShaderFromRawResource(R.raw.default_vertex) ,
OpenGlUtils.readShaderFromRawResource(R.raw.default_fragment));
}
protected void onInit() {
super.onInit();
mTextureTransformMatrixLocation = GLES20.glGetUniformLocation(mGLProgId, "textureTransform");
mSingleStepOffsetLocation = GLES20.glGetUniformLocation(getProgram(), "singleStepOffset");
mParamsLocation = GLES20.glGetUniformLocation(getProgram(), "params");
setBeautyLevel(0);
}
public void setTextureTransformMatrix(float[] mtx){
mTextureTransformMatrix = mtx;
}
@Override
public int onDrawFrame(int textureId) {
GLES20.glUseProgram(mGLProgId);
runPendingOnDrawTasks();
if(!isInitialized()) {
return OpenGlUtils.NOT_INIT;
}
mGLCubeBuffer.position(0);
GLES20.glVertexAttribPointer(mGLAttribPosition, 2, GLES20.GL_FLOAT, false, 0, mGLCubeBuffer);
GLES20.glEnableVertexAttribArray(mGLAttribPosition);
mGLTextureBuffer.position(0);
GLES20.glVertexAttribPointer(mGLAttribTextureCoordinate, 2, GLES20.GL_FLOAT, false, 0, mGLTextureBuffer);
GLES20.glEnableVertexAttribArray(mGLAttribTextureCoordinate);
GLES20.glUniformMatrix4fv(mTextureTransformMatrixLocation, 1, false, mTextureTransformMatrix, 0);
if(textureId != OpenGlUtils.NO_TEXTURE){
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureId);
GLES20.glUniform1i(mGLUniformTexture, 0);
}
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
GLES20.glDisableVertexAttribArray(mGLAttribPosition);
GLES20.glDisableVertexAttribArray(mGLAttribTextureCoordinate);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
return OpenGlUtils.ON_DRAWN;
}
@Override
public int onDrawFrame(int textureId, FloatBuffer vertexBuffer, FloatBuffer textureBuffer) {
GLES20.glUseProgram(mGLProgId);
runPendingOnDrawTasks();
if(!isInitialized()) {
return OpenGlUtils.NOT_INIT;
}
vertexBuffer.position(0);
GLES20.glVertexAttribPointer(mGLAttribPosition, 2, GLES20.GL_FLOAT, false, 0, vertexBuffer);
GLES20.glEnableVertexAttribArray(mGLAttribPosition);
textureBuffer.position(0);
GLES20.glVertexAttribPointer(mGLAttribTextureCoordinate, 2, GLES20.GL_FLOAT, false, 0, textureBuffer);
GLES20.glEnableVertexAttribArray(mGLAttribTextureCoordinate);
GLES20.glUniformMatrix4fv(mTextureTransformMatrixLocation, 1, false, mTextureTransformMatrix, 0);
if(textureId != OpenGlUtils.NO_TEXTURE){
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureId);
GLES20.glUniform1i(mGLUniformTexture, 0);
}
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
GLES20.glDisableVertexAttribArray(mGLAttribPosition);
GLES20.glDisableVertexAttribArray(mGLAttribTextureCoordinate);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
return OpenGlUtils.ON_DRAWN;
}
public int onDrawToTexture(final int textureId) {
if(mFrameBuffers == null)
return OpenGlUtils.NO_TEXTURE;
runPendingOnDrawTasks();
GLES20.glViewport(0, 0, mFrameWidth, mFrameHeight);
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBuffers[0]);
GLES20.glUseProgram(mGLProgId);
if(!isInitialized()) {
return OpenGlUtils.NOT_INIT;
}
mGLCubeBuffer.position(0);
GLES20.glVertexAttribPointer(mGLAttribPosition, 2, GLES20.GL_FLOAT, false, 0, mGLCubeBuffer);
GLES20.glEnableVertexAttribArray(mGLAttribPosition);
mGLTextureBuffer.position(0);
GLES20.glVertexAttribPointer(mGLAttribTextureCoordinate, 2, GLES20.GL_FLOAT, false, 0, mGLTextureBuffer);
GLES20.glEnableVertexAttribArray(mGLAttribTextureCoordinate);
GLES20.glUniformMatrix4fv(mTextureTransformMatrixLocation, 1, false, mTextureTransformMatrix, 0);
if(textureId != OpenGlUtils.NO_TEXTURE){
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureId);
GLES20.glUniform1i(mGLUniformTexture, 0);
}
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
GLES20.glDisableVertexAttribArray(mGLAttribPosition);
GLES20.glDisableVertexAttribArray(mGLAttribTextureCoordinate);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
//GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
GLES20.glViewport(0, 0, mOutputWidth, mOutputHeight);
return mFrameBufferTextures[0];
}
public void initCameraFrameBuffer(int width, int height) {
if(mFrameBuffers != null && (mFrameWidth != width || mFrameHeight != height))
destroyFramebuffers();
if (mFrameBuffers == null) {
mFrameWidth = width;
mFrameHeight = height;
mFrameBuffers = new int[1];
mFrameBufferTextures = new int[1];
GLES20.glGenFramebuffers(1, mFrameBuffers, 0);
GLES20.glGenTextures(1, mFrameBufferTextures, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mFrameBufferTextures[0]);
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, width, height, 0,
GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBuffers[0]);
GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
GLES20.GL_TEXTURE_2D, mFrameBufferTextures[0], 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
}
}
public void destroyFramebuffers() {
if (mFrameBufferTextures != null) {
GLES20.glDeleteTextures(1, mFrameBufferTextures, 0);
mFrameBufferTextures = null;
}
if (mFrameBuffers != null) {
GLES20.glDeleteFramebuffers(1, mFrameBuffers, 0);
mFrameBuffers = null;
}
mFrameWidth = -1;
mFrameHeight = -1;
}
private void setTexelSize(final float w, final float h) {
setFloatVec2(mSingleStepOffsetLocation, new float[] {2.0f / w, 2.0f / h});
}
@Override
public void onInputSizeChanged(final int width, final int height) {
super.onInputSizeChanged(width, height);
setTexelSize(width, height);
}
public void setBeautyLevel(int level){
switch (level) {
case 0:
setFloat(mParamsLocation, 0.0f);
break;
case 1:
setFloat(mParamsLocation, 1.0f);
break;
case 2:
setFloat(mParamsLocation, 0.8f);
break;
case 3:
setFloat(mParamsLocation,0.6f);
break;
case 4:
setFloat(mParamsLocation, 0.4f);
break;
case 5:
setFloat(mParamsLocation,0.33f);
break;
default:
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
destroyFramebuffers();
}
}
| Romove
Signed-off-by: Leo Ma <[email protected]>
| app/src/main/java/com/seu/magicfilter/base/MagicCameraInputFilter.java | Romove | <ide><path>pp/src/main/java/com/seu/magicfilter/base/MagicCameraInputFilter.java
<del>package com.seu.magicfilter.base;
<del>
<del>import java.nio.FloatBuffer;
<del>
<del>import android.opengl.GLES11Ext;
<del>import android.opengl.GLES20;
<del>
<del>import net.ossrs.yasea.R;
<del>
<del>import com.seu.magicfilter.base.gpuimage.GPUImageFilter;
<del>import com.seu.magicfilter.utils.OpenGlUtils;
<del>
<del>public class MagicCameraInputFilter extends GPUImageFilter{
<del>
<del> private float[] mTextureTransformMatrix;
<del> private int mTextureTransformMatrixLocation;
<del> private int mSingleStepOffsetLocation;
<del> private int mParamsLocation;
<del>
<del> private int[] mFrameBuffers = null;
<del> private int[] mFrameBufferTextures = null;
<del> private int mFrameWidth = -1;
<del> private int mFrameHeight = -1;
<del>
<del> public MagicCameraInputFilter(){
<del> super(OpenGlUtils.readShaderFromRawResource(R.raw.default_vertex) ,
<del> OpenGlUtils.readShaderFromRawResource(R.raw.default_fragment));
<del> }
<del>
<del> protected void onInit() {
<del> super.onInit();
<del> mTextureTransformMatrixLocation = GLES20.glGetUniformLocation(mGLProgId, "textureTransform");
<del> mSingleStepOffsetLocation = GLES20.glGetUniformLocation(getProgram(), "singleStepOffset");
<del> mParamsLocation = GLES20.glGetUniformLocation(getProgram(), "params");
<del> setBeautyLevel(0);
<del> }
<del>
<del> public void setTextureTransformMatrix(float[] mtx){
<del> mTextureTransformMatrix = mtx;
<del> }
<del>
<del> @Override
<del> public int onDrawFrame(int textureId) {
<del> GLES20.glUseProgram(mGLProgId);
<del> runPendingOnDrawTasks();
<del> if(!isInitialized()) {
<del> return OpenGlUtils.NOT_INIT;
<del> }
<del> mGLCubeBuffer.position(0);
<del> GLES20.glVertexAttribPointer(mGLAttribPosition, 2, GLES20.GL_FLOAT, false, 0, mGLCubeBuffer);
<del> GLES20.glEnableVertexAttribArray(mGLAttribPosition);
<del> mGLTextureBuffer.position(0);
<del> GLES20.glVertexAttribPointer(mGLAttribTextureCoordinate, 2, GLES20.GL_FLOAT, false, 0, mGLTextureBuffer);
<del> GLES20.glEnableVertexAttribArray(mGLAttribTextureCoordinate);
<del> GLES20.glUniformMatrix4fv(mTextureTransformMatrixLocation, 1, false, mTextureTransformMatrix, 0);
<del>
<del> if(textureId != OpenGlUtils.NO_TEXTURE){
<del> GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
<del> GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureId);
<del> GLES20.glUniform1i(mGLUniformTexture, 0);
<del> }
<del>
<del> GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
<del> GLES20.glDisableVertexAttribArray(mGLAttribPosition);
<del> GLES20.glDisableVertexAttribArray(mGLAttribTextureCoordinate);
<del> GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
<del> return OpenGlUtils.ON_DRAWN;
<del> }
<del>
<del> @Override
<del> public int onDrawFrame(int textureId, FloatBuffer vertexBuffer, FloatBuffer textureBuffer) {
<del> GLES20.glUseProgram(mGLProgId);
<del> runPendingOnDrawTasks();
<del> if(!isInitialized()) {
<del> return OpenGlUtils.NOT_INIT;
<del> }
<del> vertexBuffer.position(0);
<del> GLES20.glVertexAttribPointer(mGLAttribPosition, 2, GLES20.GL_FLOAT, false, 0, vertexBuffer);
<del> GLES20.glEnableVertexAttribArray(mGLAttribPosition);
<del> textureBuffer.position(0);
<del> GLES20.glVertexAttribPointer(mGLAttribTextureCoordinate, 2, GLES20.GL_FLOAT, false, 0, textureBuffer);
<del> GLES20.glEnableVertexAttribArray(mGLAttribTextureCoordinate);
<del> GLES20.glUniformMatrix4fv(mTextureTransformMatrixLocation, 1, false, mTextureTransformMatrix, 0);
<del>
<del> if(textureId != OpenGlUtils.NO_TEXTURE){
<del> GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
<del> GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureId);
<del> GLES20.glUniform1i(mGLUniformTexture, 0);
<del> }
<del>
<del> GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
<del> GLES20.glDisableVertexAttribArray(mGLAttribPosition);
<del> GLES20.glDisableVertexAttribArray(mGLAttribTextureCoordinate);
<del> GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
<del> return OpenGlUtils.ON_DRAWN;
<del> }
<del>
<del> public int onDrawToTexture(final int textureId) {
<del> if(mFrameBuffers == null)
<del> return OpenGlUtils.NO_TEXTURE;
<del> runPendingOnDrawTasks();
<del> GLES20.glViewport(0, 0, mFrameWidth, mFrameHeight);
<del> GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBuffers[0]);
<del> GLES20.glUseProgram(mGLProgId);
<del> if(!isInitialized()) {
<del> return OpenGlUtils.NOT_INIT;
<del> }
<del> mGLCubeBuffer.position(0);
<del> GLES20.glVertexAttribPointer(mGLAttribPosition, 2, GLES20.GL_FLOAT, false, 0, mGLCubeBuffer);
<del> GLES20.glEnableVertexAttribArray(mGLAttribPosition);
<del> mGLTextureBuffer.position(0);
<del> GLES20.glVertexAttribPointer(mGLAttribTextureCoordinate, 2, GLES20.GL_FLOAT, false, 0, mGLTextureBuffer);
<del> GLES20.glEnableVertexAttribArray(mGLAttribTextureCoordinate);
<del> GLES20.glUniformMatrix4fv(mTextureTransformMatrixLocation, 1, false, mTextureTransformMatrix, 0);
<del>
<del> if(textureId != OpenGlUtils.NO_TEXTURE){
<del> GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
<del> GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureId);
<del> GLES20.glUniform1i(mGLUniformTexture, 0);
<del> }
<del>
<del> GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
<del> GLES20.glDisableVertexAttribArray(mGLAttribPosition);
<del> GLES20.glDisableVertexAttribArray(mGLAttribTextureCoordinate);
<del> GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
<del> //GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
<del> GLES20.glViewport(0, 0, mOutputWidth, mOutputHeight);
<del> return mFrameBufferTextures[0];
<del> }
<del>
<del> public void initCameraFrameBuffer(int width, int height) {
<del> if(mFrameBuffers != null && (mFrameWidth != width || mFrameHeight != height))
<del> destroyFramebuffers();
<del> if (mFrameBuffers == null) {
<del> mFrameWidth = width;
<del> mFrameHeight = height;
<del> mFrameBuffers = new int[1];
<del> mFrameBufferTextures = new int[1];
<del>
<del> GLES20.glGenFramebuffers(1, mFrameBuffers, 0);
<del> GLES20.glGenTextures(1, mFrameBufferTextures, 0);
<del> GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mFrameBufferTextures[0]);
<del> GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, width, height, 0,
<del> GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null);
<del> GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
<del> GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
<del> GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
<del> GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
<del> GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
<del> GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
<del> GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
<del> GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
<del> GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFrameBuffers[0]);
<del> GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
<del> GLES20.GL_TEXTURE_2D, mFrameBufferTextures[0], 0);
<del> GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
<del> GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
<del> }
<del> }
<del>
<del> public void destroyFramebuffers() {
<del> if (mFrameBufferTextures != null) {
<del> GLES20.glDeleteTextures(1, mFrameBufferTextures, 0);
<del> mFrameBufferTextures = null;
<del> }
<del> if (mFrameBuffers != null) {
<del> GLES20.glDeleteFramebuffers(1, mFrameBuffers, 0);
<del> mFrameBuffers = null;
<del> }
<del> mFrameWidth = -1;
<del> mFrameHeight = -1;
<del> }
<del>
<del> private void setTexelSize(final float w, final float h) {
<del> setFloatVec2(mSingleStepOffsetLocation, new float[] {2.0f / w, 2.0f / h});
<del> }
<del>
<del> @Override
<del> public void onInputSizeChanged(final int width, final int height) {
<del> super.onInputSizeChanged(width, height);
<del> setTexelSize(width, height);
<del> }
<del>
<del> public void setBeautyLevel(int level){
<del> switch (level) {
<del> case 0:
<del> setFloat(mParamsLocation, 0.0f);
<del> break;
<del> case 1:
<del> setFloat(mParamsLocation, 1.0f);
<del> break;
<del> case 2:
<del> setFloat(mParamsLocation, 0.8f);
<del> break;
<del> case 3:
<del> setFloat(mParamsLocation,0.6f);
<del> break;
<del> case 4:
<del> setFloat(mParamsLocation, 0.4f);
<del> break;
<del> case 5:
<del> setFloat(mParamsLocation,0.33f);
<del> break;
<del> default:
<del> break;
<del> }
<del> }
<del>
<del> @Override
<del> protected void onDestroy() {
<del> super.onDestroy();
<del> destroyFramebuffers();
<del> }
<del>} |
||
JavaScript | bsd-3-clause | 109c6f9044b8641cfd4008329940581a55be27da | 0 | CartoDB/Windshaft,CartoDB/Windshaft,CartoDB/Windshaft | var mapnik = require('@carto/mapnik');
var blend = mapnik.blend;
var Timer = require('../../stats/timer');
function ImageRenderer(imageBuffer, options) {
this.imageBuffer = imageBuffer;
this.options = options || {};
this.options.tileSize = this.options.tileSize || 256;
this.options.format = this.options.format || 'png8:m=h';
}
module.exports = ImageRenderer;
var PLAIN_IMAGE_HEADERS = { 'Content-Type': 'image/png' };
ImageRenderer.prototype.getTile = function(z, x, y, callback) {
var timer = new Timer();
timer.start('render');
timer.end('render');
try {
mapnik.Image.fromBytes(this.imageBuffer, (err, image) => {
if (err) {
return callback(err);
}
const tiles = getTilesFromImage(image, x, y, this.imageBuffer, this.options.tileSize);
const blendOptions = {
format: 'png',
width: this.options.tileSize,
height: this.options.tileSize,
reencode: true
};
blend(tiles, blendOptions, function (err, buffer) {
if (err) {
return callback(err);
}
return callback(null, buffer, PLAIN_IMAGE_HEADERS, {});
});
});
} catch (error) {
return callback(error);
}
};
ImageRenderer.prototype.getMetadata = function(callback) {
return callback(null, {});
};
ImageRenderer.prototype.close = function() {
this.cachedTile = null;
};
function getTilesFromImage(image, x, y, imageBuffer, tileSize) {
let tiles = [];
const imageWidth = image.width();
const imageHeight = image.height();
let coveredHeight = 0;
let tY = 0;
while(coveredHeight < tileSize) {
let tX = 0;
const yPos = tY * imageHeight - (y * tileSize % imageHeight);
let coveredWidth = 0;
while (coveredWidth < tileSize) {
const xPos = tX * imageWidth - (x * tileSize % imageWidth);
tiles.push({
buffer: imageBuffer,
headers: {},
stats: {},
x: xPos,
y: yPos,
reencode: true
});
coveredWidth += (xPos < 0) ? (imageWidth + xPos) : imageWidth;
tX++;
}
coveredHeight += (yPos < 0) ? (imageHeight + yPos) : imageHeight;
tY++;
}
return tiles;
}
| lib/windshaft/renderers/plain/image_renderer.js | var mapnik = require('@carto/mapnik');
var blend = mapnik.blend;
var Timer = require('../../stats/timer');
function ImageRenderer(imageBuffer, options) {
this.imageBuffer = imageBuffer;
this.options = options || {};
this.options.tileSize = this.options.tileSize || 256;
this.options.format = this.options.format || 'png8:m=h';
}
module.exports = ImageRenderer;
var PLAIN_IMAGE_HEADERS = { 'Content-Type': 'image/png' };
ImageRenderer.prototype.getTile = function(z, x, y, callback) {
var timer = new Timer();
timer.start('render');
timer.end('render');
var TILE_SIZE = this.options.tileSize;
mapnik.Image.fromBytes(this.imageBuffer, (err, image) => {
if (err) {
return callback(err);
}
let tiles = [];
const imageWidth = image.width();
const imageHeight = image.height();
let coveredHeight = 0;
let tY = 0;
while(coveredHeight < TILE_SIZE) {
let tX = 0;
const yPos = tY * imageHeight - (y * TILE_SIZE % imageHeight);
let coveredWidth = 0;
while (coveredWidth < TILE_SIZE) {
const xPos = tX * imageWidth - (x * TILE_SIZE % imageWidth);
tiles.push({
buffer: this.imageBuffer,
headers: {},
stats: {},
x: xPos,
y: yPos,
reencode: true
});
coveredWidth += (xPos < 0) ? (imageWidth + xPos) : imageWidth;
tX++;
}
coveredHeight += (yPos < 0) ? (imageHeight + yPos) : imageHeight;
tY++;
}
const blendOptions = {
format: 'png',
width: TILE_SIZE,
height: TILE_SIZE,
reencode: true
};
blend(tiles, blendOptions, function (err, buffer) {
if (err) {
return callback(err);
}
return callback(null, buffer, PLAIN_IMAGE_HEADERS, {});
});
});
};
ImageRenderer.prototype.getMetadata = function(callback) {
return callback(null, {});
};
ImageRenderer.prototype.close = function() {
this.cachedTile = null;
};
| handle sync errors and extract getTilesFromImage from getTile function
| lib/windshaft/renderers/plain/image_renderer.js | handle sync errors and extract getTilesFromImage from getTile function | <ide><path>ib/windshaft/renderers/plain/image_renderer.js
<ide> timer.start('render');
<ide> timer.end('render');
<ide>
<del> var TILE_SIZE = this.options.tileSize;
<del>
<del> mapnik.Image.fromBytes(this.imageBuffer, (err, image) => {
<del> if (err) {
<del> return callback(err);
<del> }
<del>
<del> let tiles = [];
<del> const imageWidth = image.width();
<del> const imageHeight = image.height();
<del>
<del> let coveredHeight = 0;
<del>
<del> let tY = 0;
<del> while(coveredHeight < TILE_SIZE) {
<del> let tX = 0;
<del> const yPos = tY * imageHeight - (y * TILE_SIZE % imageHeight);
<del>
<del> let coveredWidth = 0;
<del>
<del> while (coveredWidth < TILE_SIZE) {
<del> const xPos = tX * imageWidth - (x * TILE_SIZE % imageWidth);
<del> tiles.push({
<del> buffer: this.imageBuffer,
<del> headers: {},
<del> stats: {},
<del> x: xPos,
<del> y: yPos,
<del> reencode: true
<del> });
<del>
<del> coveredWidth += (xPos < 0) ? (imageWidth + xPos) : imageWidth;
<del> tX++;
<del> }
<del>
<del> coveredHeight += (yPos < 0) ? (imageHeight + yPos) : imageHeight;
<del> tY++;
<del> }
<del>
<del> const blendOptions = {
<del> format: 'png',
<del> width: TILE_SIZE,
<del> height: TILE_SIZE,
<del> reencode: true
<del> };
<del>
<del> blend(tiles, blendOptions, function (err, buffer) {
<add> try {
<add> mapnik.Image.fromBytes(this.imageBuffer, (err, image) => {
<ide> if (err) {
<ide> return callback(err);
<ide> }
<ide>
<del> return callback(null, buffer, PLAIN_IMAGE_HEADERS, {});
<add> const tiles = getTilesFromImage(image, x, y, this.imageBuffer, this.options.tileSize);
<add>
<add> const blendOptions = {
<add> format: 'png',
<add> width: this.options.tileSize,
<add> height: this.options.tileSize,
<add> reencode: true
<add> };
<add>
<add> blend(tiles, blendOptions, function (err, buffer) {
<add> if (err) {
<add> return callback(err);
<add> }
<add>
<add> return callback(null, buffer, PLAIN_IMAGE_HEADERS, {});
<add> });
<ide> });
<del> });
<add> } catch (error) {
<add> return callback(error);
<add> }
<ide> };
<ide>
<ide> ImageRenderer.prototype.getMetadata = function(callback) {
<ide> ImageRenderer.prototype.close = function() {
<ide> this.cachedTile = null;
<ide> };
<add>
<add>function getTilesFromImage(image, x, y, imageBuffer, tileSize) {
<add> let tiles = [];
<add> const imageWidth = image.width();
<add> const imageHeight = image.height();
<add>
<add> let coveredHeight = 0;
<add>
<add> let tY = 0;
<add> while(coveredHeight < tileSize) {
<add> let tX = 0;
<add> const yPos = tY * imageHeight - (y * tileSize % imageHeight);
<add>
<add> let coveredWidth = 0;
<add>
<add> while (coveredWidth < tileSize) {
<add> const xPos = tX * imageWidth - (x * tileSize % imageWidth);
<add> tiles.push({
<add> buffer: imageBuffer,
<add> headers: {},
<add> stats: {},
<add> x: xPos,
<add> y: yPos,
<add> reencode: true
<add> });
<add>
<add> coveredWidth += (xPos < 0) ? (imageWidth + xPos) : imageWidth;
<add> tX++;
<add> }
<add>
<add> coveredHeight += (yPos < 0) ? (imageHeight + yPos) : imageHeight;
<add> tY++;
<add> }
<add>
<add> return tiles;
<add>} |
|
Java | mit | c9f750b602b208e1097aa820fd90c18336dc0cd5 | 0 | ALeggeUp/confagrid,ALeggeUp/confagrid,ALeggeUp/confagrid,ALeggeUp/confagrid,ALeggeUp/confagrid | /*
* DirectedAcyclicWordGraph.java
*
* Copyright (C) 2017 [ A Legge Up ] <[email protected]>
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package com.aleggeup.confagrid.words;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
public class DirectedAcyclicWordGraph {
private final WordList wordList;
private final int verticiesCount;
private final List<List<Integer>> adjacentVerticies;
private final int[] indegrees;
private final int[] ranks;
private int edgesCount;
public DirectedAcyclicWordGraph(final WordList wordList) {
this.wordList = wordList;
verticiesCount = wordList.size();
edgesCount = 0;
adjacentVerticies = new ArrayList<List<Integer>>();
indegrees = new int[verticiesCount];
ranks = new int[verticiesCount];
for (int i = 0; i < verticiesCount; ++i) {
adjacentVerticies.add(new ArrayList<Integer>());
}
}
protected void addEdgesFromPhrase(final Phrase phrase) {
Word tail = null;
for (final Iterator<Word> iterator = phrase.iterator(); iterator.hasNext();) {
final Word word = iterator.next();
if (tail == null) {
tail = word;
} else {
addEdge(tail, word);
tail = word;
}
}
}
protected void addEdge(final Word tail, final Word head) {
final int tailId = wordList.getWordId(tail);
final int headId = wordList.getWordId(head);
if (!adjacentVerticies.get(tailId).contains(Integer.valueOf(headId))) {
adjacentVerticies.get(tailId).add(Integer.valueOf(headId));
++indegrees[headId];
++edgesCount;
}
}
protected boolean hasOrder() {
final Deque<Integer> queue = new ArrayDeque<>();
final Deque<Integer> order = new ArrayDeque<>();
final int[] indegreesDiff = new int[verticiesCount];
final int[] groups = new int[verticiesCount];
for (int i = 0; i < verticiesCount; ++i) {
indegreesDiff[i] = indegrees[i];
}
for (int i = 0; i < verticiesCount; ++i) {
if (indegreesDiff[i] == 0) {
queue.push(i);
}
}
int count = 0;
int group = 0;
while (!queue.isEmpty()) {
final int value = queue.pop().intValue();
order.push(value);
ranks[value] = count++;
groups[value] = group;
boolean newGroup = false;
for (final Integer v : adjacentVerticies.get(value)) {
indegreesDiff[v.intValue()]--;
if (indegreesDiff[v.intValue()] == 0) {
newGroup = true;
queue.push(v);
}
}
if (newGroup) {
group++;
}
}
for (int i = 0; i < verticiesCount; ++i) {
System.out.println(String.format("%d: %d -- %s", i, groups[i], wordList.getReverseLookup()[i].toString()));
}
return count == verticiesCount;
}
public int getVerticiesCount() {
return verticiesCount;
}
public int getEdgesCount() {
return edgesCount;
}
}
| src/main/java/com/aleggeup/confagrid/words/DirectedAcyclicWordGraph.java | /*
* DirectedAcyclicWordGraph.java
*
* Copyright (C) 2017 [ A Legge Up ] <[email protected]>
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package com.aleggeup.confagrid.words;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
public class DirectedAcyclicWordGraph {
private final WordList wordList;
private final int verticiesCount;
private final List<List<Integer>> adjacentVerticies;
private final int[] indegrees;
private final int[] ranks;
private int edgesCount;
public DirectedAcyclicWordGraph(final WordList wordList) {
this.wordList = wordList;
verticiesCount = wordList.size();
edgesCount = 0;
adjacentVerticies = new ArrayList<List<Integer>>();
indegrees = new int[verticiesCount];
ranks = new int[verticiesCount];
for (int i = 0; i < verticiesCount; ++i) {
adjacentVerticies.add(new ArrayList<Integer>());
}
}
protected void addEdgesFromPhrase(final Phrase phrase) {
Word tail = null;
for (final Iterator<Word> iterator = phrase.iterator(); iterator.hasNext();) {
final Word word = iterator.next();
if (tail == null) {
tail = word;
} else {
addEdge(tail, word);
tail = word;
}
}
}
protected void addEdge(final Word tail, final Word head) {
final int tailId = wordList.getWordId(tail);
final int headId = wordList.getWordId(head);
if (!adjacentVerticies.get(tailId).contains(Integer.valueOf(headId))) {
adjacentVerticies.get(tailId).add(Integer.valueOf(headId));
++indegrees[headId];
++edgesCount;
}
}
protected boolean hasOrder() {
final Deque<Integer> queue = new ArrayDeque<>();
final Deque<Integer> order = new ArrayDeque<>();
final int[] indegreesDiff = new int[verticiesCount];
for (int i = 0; i < verticiesCount; ++i) {
indegreesDiff[i] = indegrees[i];
}
int count = 0;
for (int i = 0; i < verticiesCount; ++i) {
if (indegreesDiff[i] == 0) {
queue.push(i);
}
}
while (!queue.isEmpty()) {
final int value = queue.pop().intValue();
order.push(value);
ranks[value] = count++;
for (final Integer v : adjacentVerticies.get(value)) {
indegreesDiff[v.intValue()]--;
if (indegreesDiff[v.intValue()] == 0) {
queue.push(v);
}
}
}
return count == verticiesCount;
}
public int getVerticiesCount() {
return verticiesCount;
}
public int getEdgesCount() {
return edgesCount;
}
}
| Group words based on adjacent words from an edge
| src/main/java/com/aleggeup/confagrid/words/DirectedAcyclicWordGraph.java | Group words based on adjacent words from an edge | <ide><path>rc/main/java/com/aleggeup/confagrid/words/DirectedAcyclicWordGraph.java
<ide> final Deque<Integer> queue = new ArrayDeque<>();
<ide> final Deque<Integer> order = new ArrayDeque<>();
<ide> final int[] indegreesDiff = new int[verticiesCount];
<add> final int[] groups = new int[verticiesCount];
<ide>
<ide> for (int i = 0; i < verticiesCount; ++i) {
<ide> indegreesDiff[i] = indegrees[i];
<ide> }
<ide>
<del> int count = 0;
<ide> for (int i = 0; i < verticiesCount; ++i) {
<ide> if (indegreesDiff[i] == 0) {
<ide> queue.push(i);
<ide> }
<ide> }
<ide>
<add> int count = 0;
<add> int group = 0;
<ide> while (!queue.isEmpty()) {
<ide> final int value = queue.pop().intValue();
<ide> order.push(value);
<ide> ranks[value] = count++;
<add> groups[value] = group;
<ide>
<add> boolean newGroup = false;
<ide> for (final Integer v : adjacentVerticies.get(value)) {
<ide> indegreesDiff[v.intValue()]--;
<ide> if (indegreesDiff[v.intValue()] == 0) {
<add> newGroup = true;
<ide> queue.push(v);
<ide> }
<ide> }
<add>
<add> if (newGroup) {
<add> group++;
<add> }
<add> }
<add>
<add> for (int i = 0; i < verticiesCount; ++i) {
<add> System.out.println(String.format("%d: %d -- %s", i, groups[i], wordList.getReverseLookup()[i].toString()));
<ide> }
<ide>
<ide> return count == verticiesCount; |
|
Java | apache-2.0 | error: pathspec 'tests/src/main/java/io/atomix/protocols/raft/RaftFuzzTest.java' did not match any file(s) known to git
| 9ceac6ae666fcecc9760ad3ae1ddea5dbf1c2fcd | 1 | atomix/atomix,atomix/atomix,kuujo/copycat,kuujo/copycat | /*
* Copyright 2017-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.protocols.raft;
import com.google.common.collect.Maps;
import io.atomix.messaging.Endpoint;
import io.atomix.messaging.netty.NettyMessagingManager;
import io.atomix.protocols.raft.cluster.MemberId;
import io.atomix.protocols.raft.cluster.RaftMember;
import io.atomix.protocols.raft.cluster.impl.DefaultRaftMember;
import io.atomix.protocols.raft.operation.OperationId;
import io.atomix.protocols.raft.operation.OperationType;
import io.atomix.protocols.raft.operation.RaftOperation;
import io.atomix.protocols.raft.operation.impl.DefaultOperationId;
import io.atomix.protocols.raft.protocol.AppendRequest;
import io.atomix.protocols.raft.protocol.AppendResponse;
import io.atomix.protocols.raft.protocol.CloseSessionRequest;
import io.atomix.protocols.raft.protocol.CloseSessionResponse;
import io.atomix.protocols.raft.protocol.CommandRequest;
import io.atomix.protocols.raft.protocol.CommandResponse;
import io.atomix.protocols.raft.protocol.ConfigureRequest;
import io.atomix.protocols.raft.protocol.ConfigureResponse;
import io.atomix.protocols.raft.protocol.InstallRequest;
import io.atomix.protocols.raft.protocol.InstallResponse;
import io.atomix.protocols.raft.protocol.JoinRequest;
import io.atomix.protocols.raft.protocol.JoinResponse;
import io.atomix.protocols.raft.protocol.KeepAliveRequest;
import io.atomix.protocols.raft.protocol.KeepAliveResponse;
import io.atomix.protocols.raft.protocol.LeaveRequest;
import io.atomix.protocols.raft.protocol.LeaveResponse;
import io.atomix.protocols.raft.protocol.LocalRaftProtocolFactory;
import io.atomix.protocols.raft.protocol.MetadataRequest;
import io.atomix.protocols.raft.protocol.MetadataResponse;
import io.atomix.protocols.raft.protocol.OpenSessionRequest;
import io.atomix.protocols.raft.protocol.OpenSessionResponse;
import io.atomix.protocols.raft.protocol.PollRequest;
import io.atomix.protocols.raft.protocol.PollResponse;
import io.atomix.protocols.raft.protocol.PublishRequest;
import io.atomix.protocols.raft.protocol.QueryRequest;
import io.atomix.protocols.raft.protocol.QueryResponse;
import io.atomix.protocols.raft.protocol.RaftClientMessagingProtocol;
import io.atomix.protocols.raft.protocol.RaftClientProtocol;
import io.atomix.protocols.raft.protocol.RaftResponse;
import io.atomix.protocols.raft.protocol.RaftServerMessagingProtocol;
import io.atomix.protocols.raft.protocol.RaftServerProtocol;
import io.atomix.protocols.raft.protocol.ReconfigureRequest;
import io.atomix.protocols.raft.protocol.ReconfigureResponse;
import io.atomix.protocols.raft.protocol.ResetRequest;
import io.atomix.protocols.raft.protocol.VoteRequest;
import io.atomix.protocols.raft.protocol.VoteResponse;
import io.atomix.protocols.raft.proxy.CommunicationStrategy;
import io.atomix.protocols.raft.proxy.RaftProxy;
import io.atomix.protocols.raft.service.AbstractRaftService;
import io.atomix.protocols.raft.service.Commit;
import io.atomix.protocols.raft.service.RaftServiceExecutor;
import io.atomix.protocols.raft.session.SessionId;
import io.atomix.protocols.raft.storage.RaftStorage;
import io.atomix.protocols.raft.storage.log.entry.CloseSessionEntry;
import io.atomix.protocols.raft.storage.log.entry.CommandEntry;
import io.atomix.protocols.raft.storage.log.entry.ConfigurationEntry;
import io.atomix.protocols.raft.storage.log.entry.InitializeEntry;
import io.atomix.protocols.raft.storage.log.entry.KeepAliveEntry;
import io.atomix.protocols.raft.storage.log.entry.MetadataEntry;
import io.atomix.protocols.raft.storage.log.entry.OpenSessionEntry;
import io.atomix.protocols.raft.storage.log.entry.QueryEntry;
import io.atomix.protocols.raft.storage.snapshot.SnapshotReader;
import io.atomix.protocols.raft.storage.snapshot.SnapshotWriter;
import io.atomix.protocols.raft.storage.system.Configuration;
import io.atomix.serializer.Serializer;
import io.atomix.serializer.kryo.KryoNamespace;
import io.atomix.storage.StorageLevel;
import io.atomix.utils.concurrent.Scheduled;
import io.atomix.utils.concurrent.Scheduler;
import io.atomix.utils.concurrent.SingleThreadContext;
import io.atomix.utils.concurrent.ThreadContext;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* Raft fuzz test.
*/
public class RaftFuzzTest implements Runnable {
private static final boolean USE_NETTY = true;
private static final int ITERATIONS = 1000;
private static final String CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final CommunicationStrategy COMMUNICATION_STRATEGY = CommunicationStrategy.ANY;
/**
* Runs the test.
*/
public static void main(String[] args) {
new RaftFuzzTest().run();
}
private static final Serializer protocolSerializer = Serializer.using(KryoNamespace.newBuilder()
.register(OpenSessionRequest.class)
.register(OpenSessionResponse.class)
.register(CloseSessionRequest.class)
.register(CloseSessionResponse.class)
.register(KeepAliveRequest.class)
.register(KeepAliveResponse.class)
.register(QueryRequest.class)
.register(QueryResponse.class)
.register(CommandRequest.class)
.register(CommandResponse.class)
.register(MetadataRequest.class)
.register(MetadataResponse.class)
.register(JoinRequest.class)
.register(JoinResponse.class)
.register(LeaveRequest.class)
.register(LeaveResponse.class)
.register(ConfigureRequest.class)
.register(ConfigureResponse.class)
.register(ReconfigureRequest.class)
.register(ReconfigureResponse.class)
.register(InstallRequest.class)
.register(InstallResponse.class)
.register(PollRequest.class)
.register(PollResponse.class)
.register(VoteRequest.class)
.register(VoteResponse.class)
.register(AppendRequest.class)
.register(AppendResponse.class)
.register(PublishRequest.class)
.register(ResetRequest.class)
.register(RaftResponse.Status.class)
.register(RaftError.class)
.register(RaftError.Type.class)
.register(RaftOperation.class)
.register(ReadConsistency.class)
.register(byte[].class)
.register(long[].class)
.register(CloseSessionEntry.class)
.register(CommandEntry.class)
.register(ConfigurationEntry.class)
.register(InitializeEntry.class)
.register(KeepAliveEntry.class)
.register(MetadataEntry.class)
.register(OpenSessionEntry.class)
.register(QueryEntry.class)
.register(RaftOperation.class)
.register(DefaultOperationId.class)
.register(OperationType.class)
.register(ReadConsistency.class)
.register(ArrayList.class)
.register(Collections.emptyList().getClass())
.register(HashSet.class)
.register(DefaultRaftMember.class)
.register(MemberId.class)
.register(SessionId.class)
.register(RaftMember.Type.class)
.register(RaftMember.Status.class)
.register(Instant.class)
.register(Configuration.class)
.build());
private static final Serializer storageSerializer = Serializer.using(KryoNamespace.newBuilder()
.register(CloseSessionEntry.class)
.register(CommandEntry.class)
.register(ConfigurationEntry.class)
.register(InitializeEntry.class)
.register(KeepAliveEntry.class)
.register(MetadataEntry.class)
.register(OpenSessionEntry.class)
.register(QueryEntry.class)
.register(RaftOperation.class)
.register(DefaultOperationId.class)
.register(OperationType.class)
.register(ReadConsistency.class)
.register(ArrayList.class)
.register(HashSet.class)
.register(DefaultRaftMember.class)
.register(MemberId.class)
.register(RaftMember.Type.class)
.register(RaftMember.Status.class)
.register(Instant.class)
.register(Configuration.class)
.register(byte[].class)
.register(long[].class)
.build());
private static final Serializer clientSerializer = Serializer.using(KryoNamespace.newBuilder()
.register(ReadConsistency.class)
.register(Maps.immutableEntry("", "").getClass())
.build());
private int nextId;
private int port = 5000;
private List<RaftMember> members = new ArrayList<>();
private List<RaftClient> clients = new ArrayList<>();
private List<RaftServer> servers = new ArrayList<>();
private Map<Integer, Scheduled> shutdownTimers = new ConcurrentHashMap<>();
private Map<Integer, Scheduled> restartTimers = new ConcurrentHashMap<>();
private LocalRaftProtocolFactory protocolFactory;
private List<NettyMessagingManager> messagingManagers = new ArrayList<>();
private Map<MemberId, Endpoint> endpointMap = new ConcurrentHashMap<>();
private static final String[] KEYS = new String[1024];
private final Random random = new Random();
static {
for (int i = 0; i < 1024; i++) {
KEYS[i] = UUID.randomUUID().toString();
}
}
@Override
public void run() {
for (int i = 0; i < ITERATIONS; i++) {
try {
runFuzzTest();
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
/**
* Returns a random map key.
*/
private String randomKey() {
return KEYS[randomNumber(KEYS.length)];
}
/**
* Returns a random query consistency level.
*/
private ReadConsistency randomConsistency() {
return ReadConsistency.values()[randomNumber(ReadConsistency.values().length)];
}
/**
* Returns a random number within the given range.
*/
private int randomNumber(int limit) {
return random.nextInt(limit);
}
/**
* Returns a random boolean.
*/
private boolean randomBoolean() {
return randomNumber(2) == 1;
}
/**
* Returns a random string up to the given length.
*/
private String randomString(int maxLength) {
int length = randomNumber(maxLength) + 1;
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
sb.append(CHARS.charAt(random.nextInt(CHARS.length())));
}
return sb.toString();
}
/**
* Runs a single fuzz test.
*/
private void runFuzzTest() throws Exception {
reset();
createServers(randomNumber(5) + 3);
final Object lock = new Object();
final AtomicLong index = new AtomicLong();
final Map<Integer, Long> indexes = new HashMap<>();
ThreadContext context = new SingleThreadContext("fuzz-test");
int clients = randomNumber(10) + 1;
for (int i = 0; i < clients; i++) {
ReadConsistency consistency = randomConsistency();
RaftClient client = createClient();
RaftProxy proxy = createProxy(client, consistency);
Scheduler scheduler = new SingleThreadContext("fuzz-test-" + i);
final int clientId = i;
scheduler.schedule(Duration.ofMillis((100 * clients) + (randomNumber(50) - 25)), Duration.ofMillis((100 * clients) + (randomNumber(50) - 25)), () -> {
long lastLinearizableIndex = index.get();
int type = randomNumber(4);
switch (type) {
case 0:
proxy.<Map.Entry<String, String>, Long>invoke(PUT, clientSerializer::encode, Maps.immutableEntry(randomKey(), randomString(1024 * 16)), clientSerializer::decode).thenAccept(result -> {
synchronized (lock) {
if (result < lastLinearizableIndex) {
System.out.println(result + " is less than last linearizable index " + lastLinearizableIndex);
System.exit(1);
} else if (result > index.get()) {
index.set(result);
}
Long lastSequentialIndex = indexes.get(clientId);
if (lastSequentialIndex == null) {
indexes.put(clientId, result);
} else if (result < lastSequentialIndex) {
System.out.println(result + " is less than last sequential index " + lastSequentialIndex);
System.exit(1);
} else {
indexes.put(clientId, lastSequentialIndex);
}
}
});
break;
case 1:
proxy.invoke(GET, clientSerializer::encode, randomKey(), clientSerializer::decode);
break;
case 2:
proxy.<String, Long>invoke(REMOVE, clientSerializer::encode, randomKey(), clientSerializer::decode).thenAccept(result -> {
synchronized (lock) {
if (result < lastLinearizableIndex) {
System.out.println(result + " is less than last linearizable index " + lastLinearizableIndex);
System.exit(1);
} else if (result > index.get()) {
index.set(result);
}
Long lastSequentialIndex = indexes.get(clientId);
if (lastSequentialIndex == null) {
indexes.put(clientId, result);
} else if (result < lastSequentialIndex) {
System.out.println(result + " is less than last sequential index " + lastSequentialIndex);
System.exit(1);
} else {
indexes.put(clientId, lastSequentialIndex);
}
}
});
break;
case 3:
proxy.<Long>invoke(INDEX, clientSerializer::decode).thenAccept(result -> {
synchronized (lock) {
switch (consistency) {
case LINEARIZABLE:
case LINEARIZABLE_LEASE:
if (result < lastLinearizableIndex) {
System.out.println(result + " is less than last linearizable index " + lastLinearizableIndex);
System.exit(1);
} else if (result > index.get()) {
index.set(result);
}
case SEQUENTIAL:
Long lastSequentialIndex = indexes.get(clientId);
if (lastSequentialIndex == null) {
indexes.put(clientId, result);
} else if (result < lastSequentialIndex) {
System.out.println(result + " is less than last sequential index " + lastSequentialIndex);
System.exit(1);
} else {
indexes.put(clientId, lastSequentialIndex);
}
}
}
});
}
});
}
scheduleRestarts(context);
Thread.sleep(Duration.ofMinutes(15).toMillis());
}
/**
* Schedules a random number of servers to be shutdown for a period of time and then restarted.
*/
private void scheduleRestarts(ThreadContext context) {
if (shutdownTimers.isEmpty() && restartTimers.isEmpty()) {
int shutdownCount = randomNumber(servers.size() - 2) + 1;
boolean remove = randomBoolean();
for (int i = 0; i < shutdownCount; i++) {
scheduleRestart(remove, i, context);
}
}
}
/**
* Schedules the given server to be shutdown for a period of time and then restarted.
*/
private void scheduleRestart(boolean remove, int serverIndex, ThreadContext context) {
shutdownTimers.put(serverIndex, context.schedule(Duration.ofSeconds(randomNumber(120) + 10), () -> {
shutdownTimers.remove(serverIndex);
RaftServer server = servers.get(serverIndex);
CompletableFuture<Void> leaveFuture;
if (remove) {
System.out.println("Removing server: " + server.cluster().getMember().memberId());
leaveFuture = server.leave();
} else {
System.out.println("Shutting down server: " + server.cluster().getMember().memberId());
leaveFuture = server.shutdown();
}
leaveFuture.whenComplete((result, error) -> {
restartTimers.put(serverIndex, context.schedule(Duration.ofSeconds(randomNumber(120) + 10), () -> {
restartTimers.remove(serverIndex);
RaftServer newServer = createServer(server.cluster().getMember());
servers.set(serverIndex, newServer);
CompletableFuture<RaftServer> joinFuture;
if (remove) {
System.out.println("Adding server: " + newServer.cluster().getMember().memberId());
joinFuture = newServer.join(members.get(members.size() - 1).memberId());
} else {
System.out.println("Bootstrapping server: " + newServer.cluster().getMember().memberId());
joinFuture = newServer.bootstrap(members.stream().map(RaftMember::memberId).collect(Collectors.toList()));
}
joinFuture.whenComplete((result2, error2) -> {
scheduleRestarts(context);
});
}));
});
}));
}
/**
* Shuts down clients and servers.
*/
private void reset() throws Exception {
for (Scheduled shutdownTimer : shutdownTimers.values()) {
shutdownTimer.cancel();
}
shutdownTimers.clear();
for (Scheduled restartTimer : restartTimers.values()) {
restartTimer.cancel();
}
restartTimers.clear();
clients.forEach(c -> {
try {
c.close().get(10, TimeUnit.SECONDS);
} catch (Exception e) {
}
});
servers.forEach(s -> {
try {
if (s.isRunning()) {
s.shutdown().get(10, TimeUnit.SECONDS);
}
} catch (Exception e) {
}
});
Path directory = Paths.get("target/fuzz-logs/");
if (Files.exists(directory)) {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
members = new ArrayList<>();
port = 5000;
clients = new ArrayList<>();
servers = new ArrayList<>();
protocolFactory = new LocalRaftProtocolFactory(protocolSerializer);
}
/**
* Returns the next unique member identifier.
*
* @return The next unique member identifier.
*/
private MemberId nextMemberId() {
return MemberId.from(String.valueOf(++nextId));
}
/**
* Returns the next server address.
*
* @param type The startup member type.
* @return The next server address.
*/
private RaftMember nextMember(RaftMember.Type type) {
return new TestMember(nextMemberId(), type);
}
/**
* Creates a set of Raft servers.
*/
private List<RaftServer> createServers(int nodes) throws Exception {
List<RaftServer> servers = new ArrayList<>();
for (int i = 0; i < nodes; i++) {
members.add(nextMember(RaftMember.Type.ACTIVE));
}
CountDownLatch latch = new CountDownLatch(nodes);
for (int i = 0; i < nodes; i++) {
RaftServer server = createServer(members.get(i));
server.bootstrap(members.stream().map(RaftMember::memberId).collect(Collectors.toList())).thenRun(latch::countDown);
servers.add(server);
}
latch.await(30000, TimeUnit.MILLISECONDS);
return servers;
}
/**
* Creates a Raft server.
*/
private RaftServer createServer(RaftMember member) {
RaftServerProtocol protocol;
if (USE_NETTY) {
try {
Endpoint endpoint = new Endpoint(InetAddress.getLocalHost(), ++port);
NettyMessagingManager messagingManager = new NettyMessagingManager(endpoint);
messagingManagers.add(messagingManager);
endpointMap.put(member.memberId(), endpoint);
protocol = new RaftServerMessagingProtocol(messagingManager, protocolSerializer, endpointMap::get);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
} else {
protocol = protocolFactory.newServerProtocol(member.memberId());
}
RaftServer.Builder builder = RaftServer.newBuilder(member.memberId())
.withType(member.getType())
.withProtocol(protocol)
.withStorage(RaftStorage.newBuilder()
.withStorageLevel(StorageLevel.DISK)
.withDirectory(new File(String.format("target/fuzz-logs/%s", member.memberId())))
.withSerializer(storageSerializer)
.withMaxSegmentSize(1024 * 1024)
.build())
.addService("test", FuzzStateMachine::new);
RaftServer server = builder.build();
servers.add(server);
return server;
}
/**
* Creates a Raft client.
*/
private RaftClient createClient() throws Exception {
MemberId memberId = nextMemberId();
RaftClientProtocol protocol;
if (USE_NETTY) {
Endpoint endpoint = new Endpoint(InetAddress.getLocalHost(), ++port);
NettyMessagingManager messagingManager = new NettyMessagingManager(endpoint);
endpointMap.put(memberId, endpoint);
protocol = new RaftClientMessagingProtocol(messagingManager, protocolSerializer, endpointMap::get);
} else {
protocol = protocolFactory.newClientProtocol(memberId);
}
RaftClient client = RaftClient.newBuilder()
.withMemberId(memberId)
.withProtocol(protocol)
.build();
client.connect(members.stream().map(RaftMember::memberId).collect(Collectors.toList())).join();
clients.add(client);
return client;
}
/**
* Creates a test session.
*/
private RaftProxy createProxy(RaftClient client, ReadConsistency consistency) {
return client.newProxyBuilder()
.withName("test")
.withServiceType("test")
.withReadConsistency(consistency)
.withCommunicationStrategy(COMMUNICATION_STRATEGY)
.build()
.open()
.join();
}
private static final OperationId PUT = OperationId.command("put");
private static final OperationId GET = OperationId.query("get");
private static final OperationId REMOVE = OperationId.command("remove");
private static final OperationId INDEX = OperationId.command("index");
/**
* Fuzz test state machine.
*/
public class FuzzStateMachine extends AbstractRaftService {
private Map<String, String> map = new HashMap<>();
@Override
protected void configure(RaftServiceExecutor executor) {
executor.register(PUT, clientSerializer::decode, this::put, clientSerializer::encode);
executor.register(GET, clientSerializer::decode, this::get, clientSerializer::encode);
executor.register(REMOVE, clientSerializer::decode, this::remove, clientSerializer::encode);
executor.register(INDEX, this::index, clientSerializer::encode);
}
@Override
public void snapshot(SnapshotWriter writer) {
writer.writeInt(map.size());
for (Map.Entry<String, String> entry : map.entrySet()) {
writer.writeString(entry.getKey());
writer.writeString(entry.getValue());
}
}
@Override
public void install(SnapshotReader reader) {
map = new HashMap<>();
int size = reader.readInt();
for (int i = 0; i < size; i++) {
String key = reader.readString();
String value = reader.readString();
map.put(key, value);
}
}
protected long put(Commit<Map.Entry<String, String>> commit) {
map.put(commit.value().getKey(), commit.value().getValue());
return commit.index();
}
protected String get(Commit<String> commit) {
return map.get(commit.value());
}
protected long remove(Commit<String> commit) {
map.remove(commit.value());
return commit.index();
}
protected long index(Commit<Void> commit) {
return commit.index();
}
}
/**
* Test member.
*/
public static class TestMember implements RaftMember {
private final MemberId memberId;
private final Type type;
public TestMember(MemberId memberId, Type type) {
this.memberId = memberId;
this.type = type;
}
@Override
public MemberId memberId() {
return memberId;
}
@Override
public int hash() {
return memberId.hashCode();
}
@Override
public Type getType() {
return type;
}
@Override
public void addTypeChangeListener(Consumer<Type> listener) {
}
@Override
public void removeTypeChangeListener(Consumer<Type> listener) {
}
@Override
public Status getStatus() {
return Status.AVAILABLE;
}
@Override
public Instant getLastUpdated() {
return Instant.now();
}
@Override
public void addStatusChangeListener(Consumer<Status> listener) {
}
@Override
public void removeStatusChangeListener(Consumer<Status> listener) {
}
@Override
public CompletableFuture<Void> promote() {
return null;
}
@Override
public CompletableFuture<Void> promote(Type type) {
return null;
}
@Override
public CompletableFuture<Void> demote() {
return null;
}
@Override
public CompletableFuture<Void> demote(Type type) {
return null;
}
@Override
public CompletableFuture<Void> remove() {
return null;
}
}
}
| tests/src/main/java/io/atomix/protocols/raft/RaftFuzzTest.java | Add Raft fuzz test.
| tests/src/main/java/io/atomix/protocols/raft/RaftFuzzTest.java | Add Raft fuzz test. | <ide><path>ests/src/main/java/io/atomix/protocols/raft/RaftFuzzTest.java
<add>/*
<add> * Copyright 2017-present Open Networking Laboratory
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * 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, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package io.atomix.protocols.raft;
<add>
<add>import com.google.common.collect.Maps;
<add>import io.atomix.messaging.Endpoint;
<add>import io.atomix.messaging.netty.NettyMessagingManager;
<add>import io.atomix.protocols.raft.cluster.MemberId;
<add>import io.atomix.protocols.raft.cluster.RaftMember;
<add>import io.atomix.protocols.raft.cluster.impl.DefaultRaftMember;
<add>import io.atomix.protocols.raft.operation.OperationId;
<add>import io.atomix.protocols.raft.operation.OperationType;
<add>import io.atomix.protocols.raft.operation.RaftOperation;
<add>import io.atomix.protocols.raft.operation.impl.DefaultOperationId;
<add>import io.atomix.protocols.raft.protocol.AppendRequest;
<add>import io.atomix.protocols.raft.protocol.AppendResponse;
<add>import io.atomix.protocols.raft.protocol.CloseSessionRequest;
<add>import io.atomix.protocols.raft.protocol.CloseSessionResponse;
<add>import io.atomix.protocols.raft.protocol.CommandRequest;
<add>import io.atomix.protocols.raft.protocol.CommandResponse;
<add>import io.atomix.protocols.raft.protocol.ConfigureRequest;
<add>import io.atomix.protocols.raft.protocol.ConfigureResponse;
<add>import io.atomix.protocols.raft.protocol.InstallRequest;
<add>import io.atomix.protocols.raft.protocol.InstallResponse;
<add>import io.atomix.protocols.raft.protocol.JoinRequest;
<add>import io.atomix.protocols.raft.protocol.JoinResponse;
<add>import io.atomix.protocols.raft.protocol.KeepAliveRequest;
<add>import io.atomix.protocols.raft.protocol.KeepAliveResponse;
<add>import io.atomix.protocols.raft.protocol.LeaveRequest;
<add>import io.atomix.protocols.raft.protocol.LeaveResponse;
<add>import io.atomix.protocols.raft.protocol.LocalRaftProtocolFactory;
<add>import io.atomix.protocols.raft.protocol.MetadataRequest;
<add>import io.atomix.protocols.raft.protocol.MetadataResponse;
<add>import io.atomix.protocols.raft.protocol.OpenSessionRequest;
<add>import io.atomix.protocols.raft.protocol.OpenSessionResponse;
<add>import io.atomix.protocols.raft.protocol.PollRequest;
<add>import io.atomix.protocols.raft.protocol.PollResponse;
<add>import io.atomix.protocols.raft.protocol.PublishRequest;
<add>import io.atomix.protocols.raft.protocol.QueryRequest;
<add>import io.atomix.protocols.raft.protocol.QueryResponse;
<add>import io.atomix.protocols.raft.protocol.RaftClientMessagingProtocol;
<add>import io.atomix.protocols.raft.protocol.RaftClientProtocol;
<add>import io.atomix.protocols.raft.protocol.RaftResponse;
<add>import io.atomix.protocols.raft.protocol.RaftServerMessagingProtocol;
<add>import io.atomix.protocols.raft.protocol.RaftServerProtocol;
<add>import io.atomix.protocols.raft.protocol.ReconfigureRequest;
<add>import io.atomix.protocols.raft.protocol.ReconfigureResponse;
<add>import io.atomix.protocols.raft.protocol.ResetRequest;
<add>import io.atomix.protocols.raft.protocol.VoteRequest;
<add>import io.atomix.protocols.raft.protocol.VoteResponse;
<add>import io.atomix.protocols.raft.proxy.CommunicationStrategy;
<add>import io.atomix.protocols.raft.proxy.RaftProxy;
<add>import io.atomix.protocols.raft.service.AbstractRaftService;
<add>import io.atomix.protocols.raft.service.Commit;
<add>import io.atomix.protocols.raft.service.RaftServiceExecutor;
<add>import io.atomix.protocols.raft.session.SessionId;
<add>import io.atomix.protocols.raft.storage.RaftStorage;
<add>import io.atomix.protocols.raft.storage.log.entry.CloseSessionEntry;
<add>import io.atomix.protocols.raft.storage.log.entry.CommandEntry;
<add>import io.atomix.protocols.raft.storage.log.entry.ConfigurationEntry;
<add>import io.atomix.protocols.raft.storage.log.entry.InitializeEntry;
<add>import io.atomix.protocols.raft.storage.log.entry.KeepAliveEntry;
<add>import io.atomix.protocols.raft.storage.log.entry.MetadataEntry;
<add>import io.atomix.protocols.raft.storage.log.entry.OpenSessionEntry;
<add>import io.atomix.protocols.raft.storage.log.entry.QueryEntry;
<add>import io.atomix.protocols.raft.storage.snapshot.SnapshotReader;
<add>import io.atomix.protocols.raft.storage.snapshot.SnapshotWriter;
<add>import io.atomix.protocols.raft.storage.system.Configuration;
<add>import io.atomix.serializer.Serializer;
<add>import io.atomix.serializer.kryo.KryoNamespace;
<add>import io.atomix.storage.StorageLevel;
<add>import io.atomix.utils.concurrent.Scheduled;
<add>import io.atomix.utils.concurrent.Scheduler;
<add>import io.atomix.utils.concurrent.SingleThreadContext;
<add>import io.atomix.utils.concurrent.ThreadContext;
<add>
<add>import java.io.File;
<add>import java.io.IOException;
<add>import java.net.InetAddress;
<add>import java.net.UnknownHostException;
<add>import java.nio.file.FileVisitResult;
<add>import java.nio.file.Files;
<add>import java.nio.file.Path;
<add>import java.nio.file.Paths;
<add>import java.nio.file.SimpleFileVisitor;
<add>import java.nio.file.attribute.BasicFileAttributes;
<add>import java.time.Duration;
<add>import java.time.Instant;
<add>import java.util.ArrayList;
<add>import java.util.Collections;
<add>import java.util.HashMap;
<add>import java.util.HashSet;
<add>import java.util.List;
<add>import java.util.Map;
<add>import java.util.Random;
<add>import java.util.UUID;
<add>import java.util.concurrent.CompletableFuture;
<add>import java.util.concurrent.ConcurrentHashMap;
<add>import java.util.concurrent.CountDownLatch;
<add>import java.util.concurrent.TimeUnit;
<add>import java.util.concurrent.atomic.AtomicLong;
<add>import java.util.function.Consumer;
<add>import java.util.stream.Collectors;
<add>
<add>/**
<add> * Raft fuzz test.
<add> */
<add>public class RaftFuzzTest implements Runnable {
<add>
<add> private static final boolean USE_NETTY = true;
<add>
<add> private static final int ITERATIONS = 1000;
<add> private static final String CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
<add>
<add> private static final CommunicationStrategy COMMUNICATION_STRATEGY = CommunicationStrategy.ANY;
<add>
<add> /**
<add> * Runs the test.
<add> */
<add> public static void main(String[] args) {
<add> new RaftFuzzTest().run();
<add> }
<add>
<add> private static final Serializer protocolSerializer = Serializer.using(KryoNamespace.newBuilder()
<add> .register(OpenSessionRequest.class)
<add> .register(OpenSessionResponse.class)
<add> .register(CloseSessionRequest.class)
<add> .register(CloseSessionResponse.class)
<add> .register(KeepAliveRequest.class)
<add> .register(KeepAliveResponse.class)
<add> .register(QueryRequest.class)
<add> .register(QueryResponse.class)
<add> .register(CommandRequest.class)
<add> .register(CommandResponse.class)
<add> .register(MetadataRequest.class)
<add> .register(MetadataResponse.class)
<add> .register(JoinRequest.class)
<add> .register(JoinResponse.class)
<add> .register(LeaveRequest.class)
<add> .register(LeaveResponse.class)
<add> .register(ConfigureRequest.class)
<add> .register(ConfigureResponse.class)
<add> .register(ReconfigureRequest.class)
<add> .register(ReconfigureResponse.class)
<add> .register(InstallRequest.class)
<add> .register(InstallResponse.class)
<add> .register(PollRequest.class)
<add> .register(PollResponse.class)
<add> .register(VoteRequest.class)
<add> .register(VoteResponse.class)
<add> .register(AppendRequest.class)
<add> .register(AppendResponse.class)
<add> .register(PublishRequest.class)
<add> .register(ResetRequest.class)
<add> .register(RaftResponse.Status.class)
<add> .register(RaftError.class)
<add> .register(RaftError.Type.class)
<add> .register(RaftOperation.class)
<add> .register(ReadConsistency.class)
<add> .register(byte[].class)
<add> .register(long[].class)
<add> .register(CloseSessionEntry.class)
<add> .register(CommandEntry.class)
<add> .register(ConfigurationEntry.class)
<add> .register(InitializeEntry.class)
<add> .register(KeepAliveEntry.class)
<add> .register(MetadataEntry.class)
<add> .register(OpenSessionEntry.class)
<add> .register(QueryEntry.class)
<add> .register(RaftOperation.class)
<add> .register(DefaultOperationId.class)
<add> .register(OperationType.class)
<add> .register(ReadConsistency.class)
<add> .register(ArrayList.class)
<add> .register(Collections.emptyList().getClass())
<add> .register(HashSet.class)
<add> .register(DefaultRaftMember.class)
<add> .register(MemberId.class)
<add> .register(SessionId.class)
<add> .register(RaftMember.Type.class)
<add> .register(RaftMember.Status.class)
<add> .register(Instant.class)
<add> .register(Configuration.class)
<add> .build());
<add>
<add> private static final Serializer storageSerializer = Serializer.using(KryoNamespace.newBuilder()
<add> .register(CloseSessionEntry.class)
<add> .register(CommandEntry.class)
<add> .register(ConfigurationEntry.class)
<add> .register(InitializeEntry.class)
<add> .register(KeepAliveEntry.class)
<add> .register(MetadataEntry.class)
<add> .register(OpenSessionEntry.class)
<add> .register(QueryEntry.class)
<add> .register(RaftOperation.class)
<add> .register(DefaultOperationId.class)
<add> .register(OperationType.class)
<add> .register(ReadConsistency.class)
<add> .register(ArrayList.class)
<add> .register(HashSet.class)
<add> .register(DefaultRaftMember.class)
<add> .register(MemberId.class)
<add> .register(RaftMember.Type.class)
<add> .register(RaftMember.Status.class)
<add> .register(Instant.class)
<add> .register(Configuration.class)
<add> .register(byte[].class)
<add> .register(long[].class)
<add> .build());
<add>
<add> private static final Serializer clientSerializer = Serializer.using(KryoNamespace.newBuilder()
<add> .register(ReadConsistency.class)
<add> .register(Maps.immutableEntry("", "").getClass())
<add> .build());
<add>
<add> private int nextId;
<add> private int port = 5000;
<add> private List<RaftMember> members = new ArrayList<>();
<add> private List<RaftClient> clients = new ArrayList<>();
<add> private List<RaftServer> servers = new ArrayList<>();
<add> private Map<Integer, Scheduled> shutdownTimers = new ConcurrentHashMap<>();
<add> private Map<Integer, Scheduled> restartTimers = new ConcurrentHashMap<>();
<add> private LocalRaftProtocolFactory protocolFactory;
<add> private List<NettyMessagingManager> messagingManagers = new ArrayList<>();
<add> private Map<MemberId, Endpoint> endpointMap = new ConcurrentHashMap<>();
<add> private static final String[] KEYS = new String[1024];
<add> private final Random random = new Random();
<add>
<add> static {
<add> for (int i = 0; i < 1024; i++) {
<add> KEYS[i] = UUID.randomUUID().toString();
<add> }
<add> }
<add>
<add> @Override
<add> public void run() {
<add> for (int i = 0; i < ITERATIONS; i++) {
<add> try {
<add> runFuzzTest();
<add> } catch (Exception e) {
<add> e.printStackTrace();
<add> return;
<add> }
<add> }
<add> }
<add>
<add> /**
<add> * Returns a random map key.
<add> */
<add> private String randomKey() {
<add> return KEYS[randomNumber(KEYS.length)];
<add> }
<add>
<add> /**
<add> * Returns a random query consistency level.
<add> */
<add> private ReadConsistency randomConsistency() {
<add> return ReadConsistency.values()[randomNumber(ReadConsistency.values().length)];
<add> }
<add>
<add> /**
<add> * Returns a random number within the given range.
<add> */
<add> private int randomNumber(int limit) {
<add> return random.nextInt(limit);
<add> }
<add>
<add> /**
<add> * Returns a random boolean.
<add> */
<add> private boolean randomBoolean() {
<add> return randomNumber(2) == 1;
<add> }
<add>
<add> /**
<add> * Returns a random string up to the given length.
<add> */
<add> private String randomString(int maxLength) {
<add> int length = randomNumber(maxLength) + 1;
<add> StringBuilder sb = new StringBuilder(length);
<add> for (int i = 0; i < length; i++) {
<add> sb.append(CHARS.charAt(random.nextInt(CHARS.length())));
<add> }
<add> return sb.toString();
<add> }
<add>
<add> /**
<add> * Runs a single fuzz test.
<add> */
<add> private void runFuzzTest() throws Exception {
<add> reset();
<add>
<add> createServers(randomNumber(5) + 3);
<add>
<add> final Object lock = new Object();
<add> final AtomicLong index = new AtomicLong();
<add> final Map<Integer, Long> indexes = new HashMap<>();
<add>
<add> ThreadContext context = new SingleThreadContext("fuzz-test");
<add>
<add> int clients = randomNumber(10) + 1;
<add> for (int i = 0; i < clients; i++) {
<add> ReadConsistency consistency = randomConsistency();
<add> RaftClient client = createClient();
<add> RaftProxy proxy = createProxy(client, consistency);
<add> Scheduler scheduler = new SingleThreadContext("fuzz-test-" + i);
<add>
<add> final int clientId = i;
<add> scheduler.schedule(Duration.ofMillis((100 * clients) + (randomNumber(50) - 25)), Duration.ofMillis((100 * clients) + (randomNumber(50) - 25)), () -> {
<add> long lastLinearizableIndex = index.get();
<add> int type = randomNumber(4);
<add> switch (type) {
<add> case 0:
<add> proxy.<Map.Entry<String, String>, Long>invoke(PUT, clientSerializer::encode, Maps.immutableEntry(randomKey(), randomString(1024 * 16)), clientSerializer::decode).thenAccept(result -> {
<add> synchronized (lock) {
<add> if (result < lastLinearizableIndex) {
<add> System.out.println(result + " is less than last linearizable index " + lastLinearizableIndex);
<add> System.exit(1);
<add> } else if (result > index.get()) {
<add> index.set(result);
<add> }
<add>
<add> Long lastSequentialIndex = indexes.get(clientId);
<add> if (lastSequentialIndex == null) {
<add> indexes.put(clientId, result);
<add> } else if (result < lastSequentialIndex) {
<add> System.out.println(result + " is less than last sequential index " + lastSequentialIndex);
<add> System.exit(1);
<add> } else {
<add> indexes.put(clientId, lastSequentialIndex);
<add> }
<add> }
<add> });
<add> break;
<add> case 1:
<add> proxy.invoke(GET, clientSerializer::encode, randomKey(), clientSerializer::decode);
<add> break;
<add> case 2:
<add> proxy.<String, Long>invoke(REMOVE, clientSerializer::encode, randomKey(), clientSerializer::decode).thenAccept(result -> {
<add> synchronized (lock) {
<add> if (result < lastLinearizableIndex) {
<add> System.out.println(result + " is less than last linearizable index " + lastLinearizableIndex);
<add> System.exit(1);
<add> } else if (result > index.get()) {
<add> index.set(result);
<add> }
<add>
<add> Long lastSequentialIndex = indexes.get(clientId);
<add> if (lastSequentialIndex == null) {
<add> indexes.put(clientId, result);
<add> } else if (result < lastSequentialIndex) {
<add> System.out.println(result + " is less than last sequential index " + lastSequentialIndex);
<add> System.exit(1);
<add> } else {
<add> indexes.put(clientId, lastSequentialIndex);
<add> }
<add> }
<add> });
<add> break;
<add> case 3:
<add> proxy.<Long>invoke(INDEX, clientSerializer::decode).thenAccept(result -> {
<add> synchronized (lock) {
<add> switch (consistency) {
<add> case LINEARIZABLE:
<add> case LINEARIZABLE_LEASE:
<add> if (result < lastLinearizableIndex) {
<add> System.out.println(result + " is less than last linearizable index " + lastLinearizableIndex);
<add> System.exit(1);
<add> } else if (result > index.get()) {
<add> index.set(result);
<add> }
<add> case SEQUENTIAL:
<add> Long lastSequentialIndex = indexes.get(clientId);
<add> if (lastSequentialIndex == null) {
<add> indexes.put(clientId, result);
<add> } else if (result < lastSequentialIndex) {
<add> System.out.println(result + " is less than last sequential index " + lastSequentialIndex);
<add> System.exit(1);
<add> } else {
<add> indexes.put(clientId, lastSequentialIndex);
<add> }
<add> }
<add> }
<add> });
<add> }
<add> });
<add> }
<add>
<add> scheduleRestarts(context);
<add>
<add> Thread.sleep(Duration.ofMinutes(15).toMillis());
<add> }
<add>
<add> /**
<add> * Schedules a random number of servers to be shutdown for a period of time and then restarted.
<add> */
<add> private void scheduleRestarts(ThreadContext context) {
<add> if (shutdownTimers.isEmpty() && restartTimers.isEmpty()) {
<add> int shutdownCount = randomNumber(servers.size() - 2) + 1;
<add> boolean remove = randomBoolean();
<add> for (int i = 0; i < shutdownCount; i++) {
<add> scheduleRestart(remove, i, context);
<add> }
<add> }
<add> }
<add>
<add> /**
<add> * Schedules the given server to be shutdown for a period of time and then restarted.
<add> */
<add> private void scheduleRestart(boolean remove, int serverIndex, ThreadContext context) {
<add> shutdownTimers.put(serverIndex, context.schedule(Duration.ofSeconds(randomNumber(120) + 10), () -> {
<add> shutdownTimers.remove(serverIndex);
<add> RaftServer server = servers.get(serverIndex);
<add> CompletableFuture<Void> leaveFuture;
<add> if (remove) {
<add> System.out.println("Removing server: " + server.cluster().getMember().memberId());
<add> leaveFuture = server.leave();
<add> } else {
<add> System.out.println("Shutting down server: " + server.cluster().getMember().memberId());
<add> leaveFuture = server.shutdown();
<add> }
<add> leaveFuture.whenComplete((result, error) -> {
<add> restartTimers.put(serverIndex, context.schedule(Duration.ofSeconds(randomNumber(120) + 10), () -> {
<add> restartTimers.remove(serverIndex);
<add> RaftServer newServer = createServer(server.cluster().getMember());
<add> servers.set(serverIndex, newServer);
<add> CompletableFuture<RaftServer> joinFuture;
<add> if (remove) {
<add> System.out.println("Adding server: " + newServer.cluster().getMember().memberId());
<add> joinFuture = newServer.join(members.get(members.size() - 1).memberId());
<add> } else {
<add> System.out.println("Bootstrapping server: " + newServer.cluster().getMember().memberId());
<add> joinFuture = newServer.bootstrap(members.stream().map(RaftMember::memberId).collect(Collectors.toList()));
<add> }
<add> joinFuture.whenComplete((result2, error2) -> {
<add> scheduleRestarts(context);
<add> });
<add> }));
<add> });
<add> }));
<add> }
<add>
<add> /**
<add> * Shuts down clients and servers.
<add> */
<add> private void reset() throws Exception {
<add> for (Scheduled shutdownTimer : shutdownTimers.values()) {
<add> shutdownTimer.cancel();
<add> }
<add> shutdownTimers.clear();
<add>
<add> for (Scheduled restartTimer : restartTimers.values()) {
<add> restartTimer.cancel();
<add> }
<add> restartTimers.clear();
<add>
<add> clients.forEach(c -> {
<add> try {
<add> c.close().get(10, TimeUnit.SECONDS);
<add> } catch (Exception e) {
<add> }
<add> });
<add>
<add> servers.forEach(s -> {
<add> try {
<add> if (s.isRunning()) {
<add> s.shutdown().get(10, TimeUnit.SECONDS);
<add> }
<add> } catch (Exception e) {
<add> }
<add> });
<add>
<add> Path directory = Paths.get("target/fuzz-logs/");
<add> if (Files.exists(directory)) {
<add> Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
<add> @Override
<add> public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
<add> Files.delete(file);
<add> return FileVisitResult.CONTINUE;
<add> }
<add>
<add> @Override
<add> public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
<add> Files.delete(dir);
<add> return FileVisitResult.CONTINUE;
<add> }
<add> });
<add> }
<add>
<add> members = new ArrayList<>();
<add> port = 5000;
<add> clients = new ArrayList<>();
<add> servers = new ArrayList<>();
<add> protocolFactory = new LocalRaftProtocolFactory(protocolSerializer);
<add> }
<add>
<add> /**
<add> * Returns the next unique member identifier.
<add> *
<add> * @return The next unique member identifier.
<add> */
<add> private MemberId nextMemberId() {
<add> return MemberId.from(String.valueOf(++nextId));
<add> }
<add>
<add> /**
<add> * Returns the next server address.
<add> *
<add> * @param type The startup member type.
<add> * @return The next server address.
<add> */
<add> private RaftMember nextMember(RaftMember.Type type) {
<add> return new TestMember(nextMemberId(), type);
<add> }
<add>
<add> /**
<add> * Creates a set of Raft servers.
<add> */
<add> private List<RaftServer> createServers(int nodes) throws Exception {
<add> List<RaftServer> servers = new ArrayList<>();
<add>
<add> for (int i = 0; i < nodes; i++) {
<add> members.add(nextMember(RaftMember.Type.ACTIVE));
<add> }
<add>
<add> CountDownLatch latch = new CountDownLatch(nodes);
<add> for (int i = 0; i < nodes; i++) {
<add> RaftServer server = createServer(members.get(i));
<add> server.bootstrap(members.stream().map(RaftMember::memberId).collect(Collectors.toList())).thenRun(latch::countDown);
<add> servers.add(server);
<add> }
<add>
<add> latch.await(30000, TimeUnit.MILLISECONDS);
<add>
<add> return servers;
<add> }
<add>
<add> /**
<add> * Creates a Raft server.
<add> */
<add> private RaftServer createServer(RaftMember member) {
<add> RaftServerProtocol protocol;
<add> if (USE_NETTY) {
<add> try {
<add> Endpoint endpoint = new Endpoint(InetAddress.getLocalHost(), ++port);
<add> NettyMessagingManager messagingManager = new NettyMessagingManager(endpoint);
<add> messagingManagers.add(messagingManager);
<add> endpointMap.put(member.memberId(), endpoint);
<add> protocol = new RaftServerMessagingProtocol(messagingManager, protocolSerializer, endpointMap::get);
<add> } catch (UnknownHostException e) {
<add> throw new RuntimeException(e);
<add> }
<add> } else {
<add> protocol = protocolFactory.newServerProtocol(member.memberId());
<add> }
<add>
<add> RaftServer.Builder builder = RaftServer.newBuilder(member.memberId())
<add> .withType(member.getType())
<add> .withProtocol(protocol)
<add> .withStorage(RaftStorage.newBuilder()
<add> .withStorageLevel(StorageLevel.DISK)
<add> .withDirectory(new File(String.format("target/fuzz-logs/%s", member.memberId())))
<add> .withSerializer(storageSerializer)
<add> .withMaxSegmentSize(1024 * 1024)
<add> .build())
<add> .addService("test", FuzzStateMachine::new);
<add>
<add> RaftServer server = builder.build();
<add> servers.add(server);
<add> return server;
<add> }
<add>
<add> /**
<add> * Creates a Raft client.
<add> */
<add> private RaftClient createClient() throws Exception {
<add> MemberId memberId = nextMemberId();
<add>
<add> RaftClientProtocol protocol;
<add> if (USE_NETTY) {
<add> Endpoint endpoint = new Endpoint(InetAddress.getLocalHost(), ++port);
<add> NettyMessagingManager messagingManager = new NettyMessagingManager(endpoint);
<add> endpointMap.put(memberId, endpoint);
<add> protocol = new RaftClientMessagingProtocol(messagingManager, protocolSerializer, endpointMap::get);
<add> } else {
<add> protocol = protocolFactory.newClientProtocol(memberId);
<add> }
<add>
<add> RaftClient client = RaftClient.newBuilder()
<add> .withMemberId(memberId)
<add> .withProtocol(protocol)
<add> .build();
<add>
<add> client.connect(members.stream().map(RaftMember::memberId).collect(Collectors.toList())).join();
<add> clients.add(client);
<add> return client;
<add> }
<add>
<add> /**
<add> * Creates a test session.
<add> */
<add> private RaftProxy createProxy(RaftClient client, ReadConsistency consistency) {
<add> return client.newProxyBuilder()
<add> .withName("test")
<add> .withServiceType("test")
<add> .withReadConsistency(consistency)
<add> .withCommunicationStrategy(COMMUNICATION_STRATEGY)
<add> .build()
<add> .open()
<add> .join();
<add> }
<add>
<add> private static final OperationId PUT = OperationId.command("put");
<add> private static final OperationId GET = OperationId.query("get");
<add> private static final OperationId REMOVE = OperationId.command("remove");
<add> private static final OperationId INDEX = OperationId.command("index");
<add>
<add> /**
<add> * Fuzz test state machine.
<add> */
<add> public class FuzzStateMachine extends AbstractRaftService {
<add> private Map<String, String> map = new HashMap<>();
<add>
<add> @Override
<add> protected void configure(RaftServiceExecutor executor) {
<add> executor.register(PUT, clientSerializer::decode, this::put, clientSerializer::encode);
<add> executor.register(GET, clientSerializer::decode, this::get, clientSerializer::encode);
<add> executor.register(REMOVE, clientSerializer::decode, this::remove, clientSerializer::encode);
<add> executor.register(INDEX, this::index, clientSerializer::encode);
<add> }
<add>
<add> @Override
<add> public void snapshot(SnapshotWriter writer) {
<add> writer.writeInt(map.size());
<add> for (Map.Entry<String, String> entry : map.entrySet()) {
<add> writer.writeString(entry.getKey());
<add> writer.writeString(entry.getValue());
<add> }
<add> }
<add>
<add> @Override
<add> public void install(SnapshotReader reader) {
<add> map = new HashMap<>();
<add> int size = reader.readInt();
<add> for (int i = 0; i < size; i++) {
<add> String key = reader.readString();
<add> String value = reader.readString();
<add> map.put(key, value);
<add> }
<add> }
<add>
<add> protected long put(Commit<Map.Entry<String, String>> commit) {
<add> map.put(commit.value().getKey(), commit.value().getValue());
<add> return commit.index();
<add> }
<add>
<add> protected String get(Commit<String> commit) {
<add> return map.get(commit.value());
<add> }
<add>
<add> protected long remove(Commit<String> commit) {
<add> map.remove(commit.value());
<add> return commit.index();
<add> }
<add>
<add> protected long index(Commit<Void> commit) {
<add> return commit.index();
<add> }
<add> }
<add>
<add> /**
<add> * Test member.
<add> */
<add> public static class TestMember implements RaftMember {
<add> private final MemberId memberId;
<add> private final Type type;
<add>
<add> public TestMember(MemberId memberId, Type type) {
<add> this.memberId = memberId;
<add> this.type = type;
<add> }
<add>
<add> @Override
<add> public MemberId memberId() {
<add> return memberId;
<add> }
<add>
<add> @Override
<add> public int hash() {
<add> return memberId.hashCode();
<add> }
<add>
<add> @Override
<add> public Type getType() {
<add> return type;
<add> }
<add>
<add> @Override
<add> public void addTypeChangeListener(Consumer<Type> listener) {
<add>
<add> }
<add>
<add> @Override
<add> public void removeTypeChangeListener(Consumer<Type> listener) {
<add>
<add> }
<add>
<add> @Override
<add> public Status getStatus() {
<add> return Status.AVAILABLE;
<add> }
<add>
<add> @Override
<add> public Instant getLastUpdated() {
<add> return Instant.now();
<add> }
<add>
<add> @Override
<add> public void addStatusChangeListener(Consumer<Status> listener) {
<add>
<add> }
<add>
<add> @Override
<add> public void removeStatusChangeListener(Consumer<Status> listener) {
<add>
<add> }
<add>
<add> @Override
<add> public CompletableFuture<Void> promote() {
<add> return null;
<add> }
<add>
<add> @Override
<add> public CompletableFuture<Void> promote(Type type) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public CompletableFuture<Void> demote() {
<add> return null;
<add> }
<add>
<add> @Override
<add> public CompletableFuture<Void> demote(Type type) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public CompletableFuture<Void> remove() {
<add> return null;
<add> }
<add> }
<add>
<add>} |
|
Java | mit | b966f43763a5af0e30d36734aae050cc9d26ca87 | 0 | sormuras/bach,sormuras/bach | import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.System.Logger.Level;
import java.math.BigInteger;
import java.net.URI;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Deque;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.StringJoiner;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import java.util.spi.ToolProvider;
import java.util.stream.Stream;
import jdk.jfr.Category;
import jdk.jfr.Event;
import jdk.jfr.Label;
import jdk.jfr.Name;
import jdk.jfr.Recording;
import jdk.jfr.StackTrace;
public record Bach(
Options options, Logbook logbook, Paths paths, Externals externals, Tools tools) {
public static void main(String... args) {
var bach = Bach.of(args);
var code = bach.main();
System.exit(code);
}
public static Bach of(String... args) {
return Bach.of(System.out::println, System.err::println, args);
}
public static Bach of(Consumer<String> out, Consumer<String> err, String... args) {
var options = Options.of(args);
var properties = PathSupport.properties(options.__chroot.resolve("bach.properties"));
var programs = new TreeMap<Path, URI>();
for (var key : properties.stringPropertyNames()) {
if (key.startsWith(".bach/external-tool-program/")) {
var to = Path.of(key).normalize();
var from = URI.create(properties.getProperty(key));
programs.put(to, from);
}
}
return new Bach(
options,
new Logbook(out, err, options.__logbook_threshold, new ConcurrentLinkedDeque<>()),
new Paths(options.__chroot, options.__destination),
new Externals(programs),
new Tools(
ToolFinder.compose(
ToolFinder.ofProperties(options.__chroot.resolve(".bach/tool-provider")),
ToolFinder.ofPrograms(
options.__chroot.resolve(".bach/external-tool-program"),
Path.of(System.getProperty("java.home"), "bin", "java"),
"java.args"),
ToolFinder.of(
new ToolFinder.Provider("banner", Tools::banner),
new ToolFinder.Provider("build", Tools::build),
new ToolFinder.Provider("checksum", Tools::checksum),
new ToolFinder.Provider("compile", Tools::compile),
new ToolFinder.Provider("download", Tools::download),
new ToolFinder.Provider("info", Tools::info)),
ToolFinder.ofSystem())));
}
private static final AtomicReference<Bach> INSTANCE = new AtomicReference<>();
public static Bach getBach() {
var bach = INSTANCE.get();
if (bach != null) return bach;
throw new IllegalStateException();
}
public Bach {
if (!INSTANCE.compareAndSet(null, this)) throw new IllegalStateException();
}
public boolean is(Flag flag) {
return options.flags.contains(flag);
}
public void banner(String text) {
var line = "=".repeat(text.length());
logbook.out.accept("""
%s
%s
%s""".formatted(line, text, line));
}
public void build() {
run("banner", banner -> banner.with("BUILD"));
run("info");
run("compile");
}
public void info() {
var out = logbook.out();
out.accept("bach.paths = %s".formatted(paths));
if (!is(Flag.VERBOSE)) return;
tools.finder().tree(out);
Stream.of(
ToolCall.of("jar").with("--version"),
ToolCall.of("javac").with("--version"),
ToolCall.of("javadoc").with("--version"))
.parallel()
.forEach(call -> run(call, true));
Stream.of(
ToolCall.of("jdeps").with("--version"),
ToolCall.of("jlink").with("--version"),
ToolCall.of("jmod").with("--version"),
ToolCall.of("jpackage").with("--version"))
.sequential()
.forEach(call -> run(call, true));
}
public void checksum(Path path, String algorithm) {
var checksum = PathSupport.computeChecksum(path, algorithm);
logbook.out().accept("%s %s".formatted(checksum, path));
}
public void checksum(Path path, String algorithm, String expected) {
var computed = PathSupport.computeChecksum(path, algorithm);
if (computed.equalsIgnoreCase(expected)) return;
throw new AssertionError(
"""
Checksum %s mismatch for %s!
computed: %s
expected: %s
"""
.formatted(algorithm, path, computed, expected));
}
public void compile() {
logbook.log(Level.WARNING, "TODO compile()");
}
public void download(Map<Path, URI> map) {
map.entrySet().stream().parallel().forEach(entry -> download(entry.getKey(), entry.getValue()));
}
public void download(Path to, URI from) {
if (Files.exists(to)) return;
logbook.log(Level.DEBUG, "Downloading %s".formatted(from));
try (var stream = from.toURL().openStream()) {
var parent = to.getParent();
if (parent != null) Files.createDirectories(parent);
var size = Files.copy(stream, to);
logbook.log(Level.DEBUG, "Downloaded %,7d %s".formatted(size, to.getFileName()));
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
private int main() {
if (options.calls().isEmpty()) {
logbook.out().accept("Usage: java Bach.java [OPTIONS] TOOL-NAME [TOOL-ARGS...]");
logbook.out().accept("Available tools include:");
tools.finder().tree(logbook.out());
return 1;
}
try (var recording = new Recording()) {
recording.start();
run("banner", "BEGIN");
options.calls().forEach(call -> run(call, true));
run("banner", "END.");
recording.stop();
var jfr = Files.createDirectories(paths.out()).resolve("bach-logbook.jfr");
recording.dump(jfr);
var logfile = paths.out().resolve("bach-logbook.md");
logbook.out.accept("-> %s".formatted(jfr.toUri()));
logbook.out.accept("-> %s".formatted(logfile.toUri()));
var duration = Duration.between(recording.getStartTime(), recording.getStopTime());
logbook.out.accept(
"Run took %d.%02d seconds".formatted(duration.toSeconds(), duration.toMillis()));
Files.write(logfile, logbook.toMarkdownLines());
return 0;
} catch (Exception exception) {
logbook.log(Level.ERROR, exception.toString());
return -1;
}
}
public void run(String name, Object... arguments) {
run(ToolCall.of(name, arguments));
}
public void run(String name, UnaryOperator<ToolCall> operator) {
run(operator.apply(ToolCall.of(name)));
}
public void run(ToolCall call) {
run(call, is(Flag.VERBOSE));
}
public void run(ToolCall call, boolean verbose) {
var event = new RunEvent();
event.name = call.name();
event.args = String.join(" ", call.arguments());
if (!event.name.equals("banner")) {
var line = new StringJoiner(" ");
line.add(event.name);
if (!event.args.isEmpty()) {
var arguments =
verbose || event.args.length() <= 100
? event.args
: event.args.substring(0, 95) + "[...]";
line.add(arguments);
}
logbook.log(Level.INFO, " " + line);
}
var start = Instant.now();
var tool = tools.finder().find(call.name()).orElseThrow();
var out = new StringWriter();
var err = new StringWriter();
var args = call.arguments().toArray(String[]::new);
event.begin();
event.code = tool.run(new PrintWriter(out), new PrintWriter(err), args);
event.end();
event.out = out.toString().strip();
event.err = err.toString().strip();
event.commit();
if (verbose) {
if (!event.out.isEmpty()) logbook.out().accept(event.out.indent(2).stripTrailing());
if (!event.err.isEmpty()) logbook.err().accept(event.err.indent(2).stripTrailing());
}
}
public record Paths(Path root, Path out) {}
public record Externals(Map<Path, URI> programs) {}
public record Tools(ToolFinder finder) {
static int banner(PrintWriter out, PrintWriter err, String... args) {
if (args.length == 0) {
err.println("Usage: banner TEXT");
return 1;
}
Bach.getBach().banner(String.join(" ", args));
return 0;
}
static int build(PrintWriter out, PrintWriter err, String... args) {
Bach.getBach().build();
return 0;
}
static int checksum(PrintWriter out, PrintWriter err, String... args) {
if (args.length < 2 || args.length > 3) {
err.println("Usage: checksum FILE ALGORITHM [EXPECTED-CHECKSUM]");
return 1;
}
var file = Path.of(args[0]);
var algorithm = args[1];
if (args.length == 2) Bach.getBach().checksum(file, algorithm);
if (args.length == 3) Bach.getBach().checksum(file, algorithm, args[2]);
return 0;
}
static int compile(PrintWriter out, PrintWriter err, String... args) {
Bach.getBach().compile();
return 0;
}
static int download(PrintWriter out, PrintWriter err, String... args) {
var bach = Bach.getBach();
if (args.length == 0) { // everything
bach.download(bach.externals().programs());
return 0;
}
if (args.length == 2) {
var to = Path.of(args[0]);
var from = URI.create(args[1]);
bach.download(to, from);
return 0;
}
err.println("Usage: download TO-PATH FROM-URI");
return 1;
}
static int info(PrintWriter out, PrintWriter err, String... args) {
Bach.getBach().info();
return 0;
}
}
public enum Flag {
VERBOSE
}
public record Options(
Set<Flag> flags,
Level __logbook_threshold,
Path __chroot,
Path __destination,
List<ToolCall> calls) {
static Options of(String... args) {
var flags = EnumSet.noneOf(Flag.class);
var level = Level.INFO;
var root = Path.of("");
var destination = Path.of(".bach", "out");
var arguments = new ArrayDeque<>(List.of(args));
var calls = new ArrayList<ToolCall>();
while (!arguments.isEmpty()) {
var argument = arguments.removeFirst();
if (argument.startsWith("--")) {
if (argument.equals("--verbose")) {
flags.add(Flag.VERBOSE);
continue;
}
var delimiter = argument.indexOf('=', 2);
var key = delimiter == -1 ? argument : argument.substring(0, delimiter);
var value = delimiter == -1 ? arguments.removeFirst() : argument.substring(delimiter + 1);
if (key.equals("--logbook-threshold")) {
level = Level.valueOf(value);
continue;
}
if (key.equals("--chroot")) {
root = Path.of(value).normalize();
continue;
}
if (key.equals("--destination")) {
destination = Path.of(value).normalize();
continue;
}
throw new IllegalArgumentException("Unsupported option `%s`".formatted(key));
}
calls.add(new ToolCall(argument, arguments.stream().toList()));
break;
}
return new Options(
Set.copyOf(flags), level, root, root.resolve(destination), List.copyOf(calls));
}
}
public record Logbook(
Consumer<String> out, Consumer<String> err, Level threshold, Deque<LogEvent> logs) {
public void log(Level level, String message) {
var event = new LogEvent();
event.level = level.name();
event.message = message;
event.commit();
logs.add(event);
if (level.getSeverity() < threshold.getSeverity()) return;
var consumer = level.getSeverity() <= Level.INFO.getSeverity() ? out : err;
consumer.accept(message);
}
public List<String> toMarkdownLines() {
try {
var lines = new ArrayList<>(List.of("# Logbook"));
lines.add("");
lines.add("## Log Events");
lines.add("");
lines.add("```text");
logs.forEach(log -> lines.add("[%c] %s".formatted(log.level.charAt(0), log.message)));
lines.add("```");
return List.copyOf(lines);
} catch (Exception exception) {
throw new RuntimeException("Failed to read recorded events?", exception);
}
}
}
public record ToolCall(String name, List<String> arguments) {
public static ToolCall of(String name, Object... arguments) {
if (arguments.length == 0) return new ToolCall(name, List.of());
if (arguments.length == 1) return new ToolCall(name, List.of(arguments[0].toString()));
return new ToolCall(name, List.of()).with(Stream.of(arguments));
}
public ToolCall with(Stream<?> objects) {
var strings = objects.map(Object::toString);
return new ToolCall(name, Stream.concat(arguments.stream(), strings).toList());
}
public ToolCall with(Object argument) {
return with(Stream.of(argument));
}
public ToolCall with(String key, Object value, Object... values) {
var call = with(Stream.of(key, value));
return values.length == 0 ? call : call.with(Stream.of(values));
}
public ToolCall withFindFiles(String glob) {
return withFindFiles(Path.of(""), glob);
}
public ToolCall withFindFiles(Path start, String glob) {
return withFindFiles(start, "glob", glob);
}
public ToolCall withFindFiles(Path start, String syntax, String pattern) {
var syntaxAndPattern = syntax + ':' + pattern;
var matcher = start.getFileSystem().getPathMatcher(syntaxAndPattern);
return withFindFiles(start, Integer.MAX_VALUE, matcher);
}
public ToolCall withFindFiles(Path start, int maxDepth, PathMatcher matcher) {
try (var files = Files.find(start, maxDepth, (p, a) -> matcher.matches(p))) {
return with(files);
} catch (Exception exception) {
throw new RuntimeException("Find files failed in: " + start, exception);
}
}
}
/**
* A finder of tool providers.
*
* <p>What {@link java.lang.module.ModuleFinder ModuleFinder} is to {@link
* java.lang.module.ModuleReference ModuleReference}, is {@link ToolFinder} to {@link
* ToolProvider}.
*/
@FunctionalInterface
public interface ToolFinder {
List<ToolProvider> findAll();
default Optional<ToolProvider> find(String name) {
return findAll().stream().filter(tool -> tool.name().equals(name)).findFirst();
}
default String title() {
return getClass().getSimpleName();
}
default void tree(Consumer<String> out) {
visit(0, (depth, finder) -> tree(out, depth, finder));
}
private void tree(Consumer<String> out, int depth, ToolFinder finder) {
var indent = " ".repeat(depth);
out.accept(indent + finder.title());
if (finder instanceof CompositeToolFinder) return;
finder.findAll().stream()
.sorted(Comparator.comparing(ToolProvider::name))
.forEach(tool -> out.accept(indent + " - " + tool.name()));
}
default void visit(int depth, BiConsumer<Integer, ToolFinder> visitor) {
visitor.accept(depth, this);
}
static ToolFinder of(ToolProvider... providers) {
record DirectToolFinder(List<ToolProvider> findAll) implements ToolFinder {
@Override
public String title() {
return "DirectToolFinder (%d)".formatted(findAll.size());
}
}
return new DirectToolFinder(List.of(providers));
}
static ToolFinder of(ClassLoader loader) {
return ToolFinder.of(ServiceLoader.load(ToolProvider.class, loader));
}
static ToolFinder of(ServiceLoader<ToolProvider> loader) {
record ServiceLoaderToolFinder(ServiceLoader<ToolProvider> loader) implements ToolFinder {
@Override
public List<ToolProvider> findAll() {
synchronized (loader) {
return loader.stream().map(ServiceLoader.Provider::get).toList();
}
}
}
return new ServiceLoaderToolFinder(loader);
}
static ToolFinder ofSystem() {
return ToolFinder.of(ClassLoader.getSystemClassLoader());
}
static ToolFinder ofProperties(Path directory) {
record PropertiesToolProvider(String name, Properties properties) implements ToolProvider {
@Override
public int run(PrintWriter out, PrintWriter err, String... args) {
var numbers = properties.stringPropertyNames().stream().map(Integer::valueOf).sorted();
for (var number : numbers.map(Object::toString).map(properties::getProperty).toList()) {
var lines = number.lines().map(String::trim).toList();
var name = lines.get(0);
if (name.toUpperCase().startsWith("GOTO")) throw new Error("GOTO IS TOO BASIC!");
var call = ToolCall.of(name).with(lines.stream().skip(1));
Bach.getBach().run(call);
}
return 0;
}
}
record PropertiesToolFinder(Path directory) implements ToolFinder {
@Override
public String title() {
return "PropertiesToolFinder (%s)".formatted(directory);
}
@Override
public List<ToolProvider> findAll() {
if (!Files.isDirectory(directory)) return List.of();
var list = new ArrayList<ToolProvider>();
try (var paths = Files.newDirectoryStream(directory, "*.properties")) {
for (var path : paths) {
if (Files.isDirectory(path)) continue;
var filename = path.getFileName().toString();
var name = filename.substring(0, filename.length() - ".properties".length());
var properties = PathSupport.properties(path);
list.add(new PropertiesToolProvider(name, properties));
}
} catch (Exception exception) {
throw new RuntimeException(exception);
}
return List.copyOf(list);
}
}
return new PropertiesToolFinder(directory);
}
static ToolFinder ofPrograms(Path directory, Path java, String argsfile) {
record ProgramToolFinder(Path path, Path java, String argsfile) implements ToolFinder {
@Override
public List<ToolProvider> findAll() {
var name = path.normalize().toAbsolutePath().getFileName().toString();
return find(name).map(List::of).orElseGet(List::of);
}
@Override
public Optional<ToolProvider> find(String name) {
var directory = path.normalize().toAbsolutePath();
if (!Files.isDirectory(directory)) return Optional.empty();
if (!name.equals(directory.getFileName().toString())) return Optional.empty();
var command = new ArrayList<String>();
command.add(java.toString());
var args = directory.resolve(argsfile);
if (Files.isRegularFile(args)) {
command.add("@" + args);
return Optional.of(new ExecuteProgramToolProvider(name, command));
}
var jars = PathSupport.list(directory, PathSupport::isJarFile);
if (jars.size() == 1) {
command.add("-jar");
command.add(jars.get(0).toString());
return Optional.of(new ExecuteProgramToolProvider(name, command));
}
var javas = PathSupport.list(directory, PathSupport::isJavaFile);
if (javas.size() == 1) {
command.add(javas.get(0).toString());
return Optional.of(new ExecuteProgramToolProvider(name, command));
}
throw new UnsupportedOperationException("Unknown program layout in " + directory.toUri());
}
}
record ProgramsToolFinder(Path path, Path java, String argsfile) implements ToolFinder {
@Override
public String title() {
return "ProgramsToolFinder (%s -> %s)".formatted(path, java);
}
@Override
public List<ToolProvider> findAll() {
return PathSupport.list(path, Files::isDirectory).stream()
.map(directory -> new ProgramToolFinder(directory, java, argsfile))
.map(ToolFinder::findAll)
.flatMap(List::stream)
.toList();
}
}
return new ProgramsToolFinder(directory, java, argsfile);
}
static ToolFinder compose(ToolFinder... finders) {
return new CompositeToolFinder(List.of(finders));
}
record CompositeToolFinder(List<ToolFinder> finders) implements ToolFinder {
@Override
public String title() {
return "CompositeToolFinder (%d)".formatted(finders.size());
}
@Override
public List<ToolProvider> findAll() {
return finders.stream().flatMap(finder -> finder.findAll().stream()).toList();
}
@Override
public Optional<ToolProvider> find(String name) {
for (var finder : finders) {
var tool = finder.find(name);
if (tool.isPresent()) return tool;
}
return Optional.empty();
}
@Override
public void visit(int depth, BiConsumer<Integer, ToolFinder> visitor) {
visitor.accept(depth, this);
depth++;
for (var finder : finders) finder.visit(depth, visitor);
}
}
record Provider(String name, ToolFunction function) implements ToolProvider {
@FunctionalInterface
public interface ToolFunction {
int run(PrintWriter out, PrintWriter err, String... args);
}
@Override
public int run(PrintWriter out, PrintWriter err, String... args) {
return function.run(out, err, args);
}
}
record ExecuteProgramToolProvider(String name, List<String> command) implements ToolProvider {
@Override
public int run(PrintWriter out, PrintWriter err, String... arguments) {
var builder = new ProcessBuilder(command);
builder.command().addAll(List.of(arguments));
try {
var process = builder.start();
new Thread(new StreamLineConsumer(process.getInputStream(), out::println)).start();
new Thread(new StreamLineConsumer(process.getErrorStream(), err::println)).start();
return process.waitFor();
} catch (Exception exception) {
exception.printStackTrace(err);
return -1;
}
}
}
}
record StreamLineConsumer(InputStream stream, Consumer<String> consumer) implements Runnable {
public void run() {
new BufferedReader(new InputStreamReader(stream)).lines().forEach(consumer);
}
}
static final class PathSupport {
static String computeChecksum(Path path, String algorithm) {
if (Files.notExists(path)) throw new RuntimeException(path.toString());
try {
if ("size".equalsIgnoreCase(algorithm)) return Long.toString(Files.size(path));
var md = MessageDigest.getInstance(algorithm);
try (var source = new BufferedInputStream(new FileInputStream(path.toFile()));
var target = new DigestOutputStream(OutputStream.nullOutputStream(), md)) {
source.transferTo(target);
}
return String.format(
"%0" + (md.getDigestLength() * 2) + "x", new BigInteger(1, md.digest()));
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
static Properties properties(Path path) {
var properties = new Properties();
if (Files.exists(path)) {
try {
properties.load(new FileInputStream(path.toFile()));
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
return properties;
}
static boolean isJarFile(Path path) {
return nameOrElse(path, "").endsWith(".jar") && Files.isRegularFile(path);
}
static boolean isJavaFile(Path path) {
return nameOrElse(path, "").endsWith(".java") && Files.isRegularFile(path);
}
static boolean isModuleInfoJavaFile(Path path) {
return "module-info.java".equals(name(path)) && Files.isRegularFile(path);
}
static List<Path> list(Path directory, DirectoryStream.Filter<? super Path> filter) {
if (Files.notExists(directory)) return List.of();
var paths = new TreeSet<>(Comparator.comparing(Path::toString));
try (var stream = Files.newDirectoryStream(directory, filter)) {
stream.forEach(paths::add);
} catch (Exception exception) {
throw new RuntimeException(exception);
}
return List.copyOf(paths);
}
static String name(Path path) {
return nameOrElse(path, null);
}
static String nameOrElse(Path path, String defautName) {
var normalized = path.normalize();
var candidate = normalized.toString().isEmpty() ? normalized.toAbsolutePath() : normalized;
var name = candidate.getFileName();
return Optional.ofNullable(name).map(Path::toString).orElse(defautName);
}
}
@Category("Bach")
@Name("Bach.LogEvent")
@Label("Log")
@StackTrace(false)
static final class LogEvent extends Event {
String level;
String message;
}
@Category("Bach")
@Name("Bach.RunEvent")
@Label("Run")
@StackTrace(false)
static final class RunEvent extends Event {
String name;
String args;
int code;
String out;
String err;
}
}
| src/Bach.java | import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.System.Logger.Level;
import java.math.BigInteger;
import java.net.URI;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Deque;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.StringJoiner;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import java.util.spi.ToolProvider;
import java.util.stream.Stream;
import jdk.jfr.Category;
import jdk.jfr.Event;
import jdk.jfr.Label;
import jdk.jfr.Name;
import jdk.jfr.Recording;
import jdk.jfr.StackTrace;
public record Bach(
Options options, Logbook logbook, Paths paths, Externals externals, Tools tools) {
public static void main(String... args) {
var bach = Bach.of(args);
var code = bach.main();
System.exit(code);
}
public static Bach of(String... args) {
return Bach.of(System.out::println, System.err::println, args);
}
public static Bach of(Consumer<String> out, Consumer<String> err, String... args) {
var options = Options.of(args);
var properties = PathSupport.properties(options.__chroot.resolve("bach.properties"));
var programs = new TreeMap<Path, URI>();
for (var key : properties.stringPropertyNames()) {
if (key.startsWith(".bach/external-tool-program/")) {
var to = Path.of(key).normalize();
var from = URI.create(properties.getProperty(key));
programs.put(to, from);
}
}
return new Bach(
options,
new Logbook(out, err, options.__logbook_threshold, new ConcurrentLinkedDeque<>()),
new Paths(options.__chroot, options.__destination),
new Externals(programs),
new Tools(
ToolFinder.compose(
ToolFinder.ofProperties(options.__chroot.resolve(".bach/tool-provider")),
ToolFinder.ofPrograms(
options.__chroot.resolve(".bach/external-tool-program"),
Path.of(System.getProperty("java.home"), "bin", "java"),
"java.args"),
ToolFinder.of(
new ToolFinder.Provider("banner", Tools::banner),
new ToolFinder.Provider("build", Tools::build),
new ToolFinder.Provider("checksum", Tools::checksum),
new ToolFinder.Provider("compile", Tools::compile),
new ToolFinder.Provider("download", Tools::download),
new ToolFinder.Provider("info", Tools::info)),
ToolFinder.ofSystem())));
}
private static final AtomicReference<Bach> INSTANCE = new AtomicReference<>();
public static Bach getBach() {
var bach = INSTANCE.get();
if (bach != null) return bach;
throw new IllegalStateException();
}
public Bach {
if (!INSTANCE.compareAndSet(null, this)) throw new IllegalStateException();
}
public boolean is(Flag flag) {
return options.flags.contains(flag);
}
public void banner(String text) {
var line = "=".repeat(text.length());
logbook.out.accept("""
%s
%s
%s""".formatted(line, text, line));
}
public void build() {
run("banner", banner -> banner.with("BUILD"));
run("info");
run("compile");
}
public void info() {
var out = logbook.out();
out.accept("bach.paths = %s".formatted(paths));
if (!is(Flag.VERBOSE)) return;
tools.finder().tree(out);
Stream.of(
ToolCall.of("jar").with("--version"),
ToolCall.of("javac").with("--version"),
ToolCall.of("javadoc").with("--version"))
.sequential()
.forEach(call -> run(call, true));
Stream.of(
ToolCall.of("jdeps").with("--version"),
ToolCall.of("jlink").with("--version"),
ToolCall.of("jmod").with("--version"),
ToolCall.of("jpackage").with("--version"))
.parallel()
.forEach(call -> run(call, true));
}
public void checksum(Path path, String algorithm) {
var checksum = PathSupport.computeChecksum(path, algorithm);
logbook.out().accept("%s %s".formatted(checksum, path));
}
public void checksum(Path path, String algorithm, String expected) {
var computed = PathSupport.computeChecksum(path, algorithm);
if (computed.equalsIgnoreCase(expected)) return;
throw new AssertionError(
"""
Checksum %s mismatch for %s!
computed: %s
expected: %s
"""
.formatted(algorithm, path, computed, expected));
}
public void compile() {
logbook.log(Level.WARNING, "TODO compile()");
}
public void download(Map<Path, URI> map) {
map.entrySet().stream().parallel().forEach(entry -> download(entry.getKey(), entry.getValue()));
}
public void download(Path to, URI from) {
if (Files.exists(to)) return;
logbook.log(Level.DEBUG, "Downloading %s".formatted(from));
try (var stream = from.toURL().openStream()) {
var parent = to.getParent();
if (parent != null) Files.createDirectories(parent);
var size = Files.copy(stream, to);
logbook.log(Level.DEBUG, "Downloaded %,7d %s".formatted(size, to.getFileName()));
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
private int main() {
if (options.calls().isEmpty()) {
logbook.out().accept("Usage: java Bach.java [OPTIONS] TOOL-NAME [TOOL-ARGS...]");
logbook.out().accept("Available tools include:");
tools.finder().tree(logbook.out());
return 1;
}
try (var recording = new Recording()) {
recording.start();
run("banner", "BEGIN");
options.calls().forEach(call -> run(call, true));
run("banner", "END.");
recording.stop();
var jfr = Files.createDirectories(paths.out()).resolve("bach-logbook.jfr");
recording.dump(jfr);
var logfile = paths.out().resolve("bach-logbook.md");
logbook.out.accept("-> %s".formatted(jfr.toUri()));
logbook.out.accept("-> %s".formatted(logfile.toUri()));
var duration = Duration.between(recording.getStartTime(), recording.getStopTime());
logbook.out.accept(
"Run took %d.%02d seconds".formatted(duration.toSeconds(), duration.toMillis()));
Files.write(logfile, logbook.toMarkdownLines());
return 0;
} catch (Exception exception) {
logbook.log(Level.ERROR, exception.toString());
return -1;
}
}
public void run(String name, Object... arguments) {
run(ToolCall.of(name, arguments));
}
public void run(String name, UnaryOperator<ToolCall> operator) {
run(operator.apply(ToolCall.of(name)));
}
public void run(ToolCall call) {
run(call, is(Flag.VERBOSE));
}
public void run(ToolCall call, boolean verbose) {
var event = new RunEvent();
event.name = call.name();
event.args = String.join(" ", call.arguments());
if (!event.name.equals("banner")) {
var line = new StringJoiner(" ");
line.add(event.name);
if (!event.args.isEmpty()) {
var arguments =
verbose || event.args.length() <= 100
? event.args
: event.args.substring(0, 95) + "[...]";
line.add(arguments);
}
logbook.log(Level.INFO, " " + line);
}
var start = Instant.now();
var tool = tools.finder().find(call.name()).orElseThrow();
var out = new StringWriter();
var err = new StringWriter();
var args = call.arguments().toArray(String[]::new);
event.begin();
event.code = tool.run(new PrintWriter(out), new PrintWriter(err), args);
event.end();
event.out = out.toString().strip();
event.err = err.toString().strip();
event.commit();
if (verbose) {
if (!event.out.isEmpty()) logbook.out().accept(event.out.indent(2).stripTrailing());
if (!event.err.isEmpty()) logbook.err().accept(event.err.indent(2).stripTrailing());
}
}
public record Paths(Path root, Path out) {}
public record Externals(Map<Path, URI> programs) {}
public record Tools(ToolFinder finder) {
static int banner(PrintWriter out, PrintWriter err, String... args) {
if (args.length == 0) {
err.println("Usage: banner TEXT");
return 1;
}
Bach.getBach().banner(String.join(" ", args));
return 0;
}
static int build(PrintWriter out, PrintWriter err, String... args) {
Bach.getBach().build();
return 0;
}
static int checksum(PrintWriter out, PrintWriter err, String... args) {
if (args.length < 2 || args.length > 3) {
err.println("Usage: checksum FILE ALGORITHM [EXPECTED-CHECKSUM]");
return 1;
}
var file = Path.of(args[0]);
var algorithm = args[1];
if (args.length == 2) Bach.getBach().checksum(file, algorithm);
if (args.length == 3) Bach.getBach().checksum(file, algorithm, args[2]);
return 0;
}
static int compile(PrintWriter out, PrintWriter err, String... args) {
Bach.getBach().compile();
return 0;
}
static int download(PrintWriter out, PrintWriter err, String... args) {
var bach = Bach.getBach();
if (args.length == 0) { // everything
bach.download(bach.externals().programs());
return 0;
}
if (args.length == 2) {
var to = Path.of(args[0]);
var from = URI.create(args[1]);
bach.download(to, from);
return 0;
}
err.println("Usage: download TO-PATH FROM-URI");
return 1;
}
static int info(PrintWriter out, PrintWriter err, String... args) {
Bach.getBach().info();
return 0;
}
}
public enum Flag {
VERBOSE
}
public record Options(
Set<Flag> flags,
Level __logbook_threshold,
Path __chroot,
Path __destination,
List<ToolCall> calls) {
static Options of(String... args) {
var flags = EnumSet.noneOf(Flag.class);
var level = Level.INFO;
var root = Path.of("");
var destination = Path.of(".bach", "out");
var arguments = new ArrayDeque<>(List.of(args));
var calls = new ArrayList<ToolCall>();
while (!arguments.isEmpty()) {
var argument = arguments.removeFirst();
if (argument.startsWith("--")) {
if (argument.equals("--verbose")) {
flags.add(Flag.VERBOSE);
continue;
}
var delimiter = argument.indexOf('=', 2);
var key = delimiter == -1 ? argument : argument.substring(0, delimiter);
var value = delimiter == -1 ? arguments.removeFirst() : argument.substring(delimiter + 1);
if (key.equals("--logbook-threshold")) {
level = Level.valueOf(value);
continue;
}
if (key.equals("--chroot")) {
root = Path.of(value).normalize();
continue;
}
if (key.equals("--destination")) {
destination = Path.of(value).normalize();
continue;
}
throw new IllegalArgumentException("Unsupported option `%s`".formatted(key));
}
calls.add(new ToolCall(argument, arguments.stream().toList()));
break;
}
return new Options(
Set.copyOf(flags), level, root, root.resolve(destination), List.copyOf(calls));
}
}
public record Logbook(
Consumer<String> out, Consumer<String> err, Level threshold, Deque<LogEvent> logs) {
public void log(Level level, String message) {
var event = new LogEvent();
event.level = level.name();
event.message = message;
event.commit();
logs.add(event);
if (level.getSeverity() < threshold.getSeverity()) return;
var consumer = level.getSeverity() <= Level.INFO.getSeverity() ? out : err;
consumer.accept(message);
}
public List<String> toMarkdownLines() {
try {
var lines = new ArrayList<>(List.of("# Logbook"));
lines.add("");
lines.add("## Log Events");
lines.add("");
lines.add("```text");
logs.forEach(log -> lines.add("[%c] %s".formatted(log.level.charAt(0), log.message)));
lines.add("```");
return List.copyOf(lines);
} catch (Exception exception) {
throw new RuntimeException("Failed to read recorded events?", exception);
}
}
}
public record ToolCall(String name, List<String> arguments) {
public static ToolCall of(String name, Object... arguments) {
if (arguments.length == 0) return new ToolCall(name, List.of());
if (arguments.length == 1) return new ToolCall(name, List.of(arguments[0].toString()));
return new ToolCall(name, List.of()).with(Stream.of(arguments));
}
public ToolCall with(Stream<?> objects) {
var strings = objects.map(Object::toString);
return new ToolCall(name, Stream.concat(arguments.stream(), strings).toList());
}
public ToolCall with(Object argument) {
return with(Stream.of(argument));
}
public ToolCall with(String key, Object value, Object... values) {
var call = with(Stream.of(key, value));
return values.length == 0 ? call : call.with(Stream.of(values));
}
public ToolCall withFindFiles(String glob) {
return withFindFiles(Path.of(""), glob);
}
public ToolCall withFindFiles(Path start, String glob) {
return withFindFiles(start, "glob", glob);
}
public ToolCall withFindFiles(Path start, String syntax, String pattern) {
var syntaxAndPattern = syntax + ':' + pattern;
var matcher = start.getFileSystem().getPathMatcher(syntaxAndPattern);
return withFindFiles(start, Integer.MAX_VALUE, matcher);
}
public ToolCall withFindFiles(Path start, int maxDepth, PathMatcher matcher) {
try (var files = Files.find(start, maxDepth, (p, a) -> matcher.matches(p))) {
return with(files);
} catch (Exception exception) {
throw new RuntimeException("Find files failed in: " + start, exception);
}
}
}
/**
* A finder of tool providers.
*
* <p>What {@link java.lang.module.ModuleFinder ModuleFinder} is to {@link
* java.lang.module.ModuleReference ModuleReference}, is {@link ToolFinder} to {@link
* ToolProvider}.
*/
@FunctionalInterface
public interface ToolFinder {
List<ToolProvider> findAll();
default Optional<ToolProvider> find(String name) {
return findAll().stream().filter(tool -> tool.name().equals(name)).findFirst();
}
default String title() {
return getClass().getSimpleName();
}
default void tree(Consumer<String> out) {
visit(0, (depth, finder) -> tree(out, depth, finder));
}
private void tree(Consumer<String> out, int depth, ToolFinder finder) {
var indent = " ".repeat(depth);
out.accept(indent + finder.title());
if (finder instanceof CompositeToolFinder) return;
finder.findAll().stream()
.sorted(Comparator.comparing(ToolProvider::name))
.forEach(tool -> out.accept(indent + " - " + tool.name()));
}
default void visit(int depth, BiConsumer<Integer, ToolFinder> visitor) {
visitor.accept(depth, this);
}
static ToolFinder of(ToolProvider... providers) {
record DirectToolFinder(List<ToolProvider> findAll) implements ToolFinder {
@Override
public String title() {
return "DirectToolFinder (%d)".formatted(findAll.size());
}
}
return new DirectToolFinder(List.of(providers));
}
static ToolFinder of(ClassLoader loader) {
return ToolFinder.of(ServiceLoader.load(ToolProvider.class, loader));
}
static ToolFinder of(ServiceLoader<ToolProvider> loader) {
record ServiceLoaderToolFinder(ServiceLoader<ToolProvider> loader) implements ToolFinder {
@Override
public List<ToolProvider> findAll() {
synchronized (loader) {
return loader.stream().map(ServiceLoader.Provider::get).toList();
}
}
}
return new ServiceLoaderToolFinder(loader);
}
static ToolFinder ofSystem() {
return ToolFinder.of(ClassLoader.getSystemClassLoader());
}
static ToolFinder ofProperties(Path directory) {
record PropertiesToolProvider(String name, Properties properties) implements ToolProvider {
@Override
public int run(PrintWriter out, PrintWriter err, String... args) {
var numbers = properties.stringPropertyNames().stream().map(Integer::valueOf).sorted();
for (var number : numbers.map(Object::toString).map(properties::getProperty).toList()) {
var lines = number.lines().map(String::trim).toList();
var name = lines.get(0);
if (name.toUpperCase().startsWith("GOTO")) throw new Error("GOTO IS TOO BASIC!");
var call = ToolCall.of(name).with(lines.stream().skip(1));
Bach.getBach().run(call);
}
return 0;
}
}
record PropertiesToolFinder(Path directory) implements ToolFinder {
@Override
public String title() {
return "PropertiesToolFinder (%s)".formatted(directory);
}
@Override
public List<ToolProvider> findAll() {
if (!Files.isDirectory(directory)) return List.of();
var list = new ArrayList<ToolProvider>();
try (var paths = Files.newDirectoryStream(directory, "*.properties")) {
for (var path : paths) {
if (Files.isDirectory(path)) continue;
var filename = path.getFileName().toString();
var name = filename.substring(0, filename.length() - ".properties".length());
var properties = PathSupport.properties(path);
list.add(new PropertiesToolProvider(name, properties));
}
} catch (Exception exception) {
throw new RuntimeException(exception);
}
return List.copyOf(list);
}
}
return new PropertiesToolFinder(directory);
}
static ToolFinder ofPrograms(Path directory, Path java, String argsfile) {
record ProgramToolFinder(Path path, Path java, String argsfile) implements ToolFinder {
@Override
public List<ToolProvider> findAll() {
var name = path.normalize().toAbsolutePath().getFileName().toString();
return find(name).map(List::of).orElseGet(List::of);
}
@Override
public Optional<ToolProvider> find(String name) {
var directory = path.normalize().toAbsolutePath();
if (!Files.isDirectory(directory)) return Optional.empty();
if (!name.equals(directory.getFileName().toString())) return Optional.empty();
var command = new ArrayList<String>();
command.add(java.toString());
var args = directory.resolve(argsfile);
if (Files.isRegularFile(args)) {
command.add("@" + args);
return Optional.of(new ExecuteProgramToolProvider(name, command));
}
var jars = PathSupport.list(directory, PathSupport::isJarFile);
if (jars.size() == 1) {
command.add("-jar");
command.add(jars.get(0).toString());
return Optional.of(new ExecuteProgramToolProvider(name, command));
}
var javas = PathSupport.list(directory, PathSupport::isJavaFile);
if (javas.size() == 1) {
command.add(javas.get(0).toString());
return Optional.of(new ExecuteProgramToolProvider(name, command));
}
throw new UnsupportedOperationException("Unknown program layout in " + directory.toUri());
}
}
record ProgramsToolFinder(Path path, Path java, String argsfile) implements ToolFinder {
@Override
public String title() {
return "ProgramsToolFinder (%s -> %s)".formatted(path, java);
}
@Override
public List<ToolProvider> findAll() {
return PathSupport.list(path, Files::isDirectory).stream()
.map(directory -> new ProgramToolFinder(directory, java, argsfile))
.map(ToolFinder::findAll)
.flatMap(List::stream)
.toList();
}
}
return new ProgramsToolFinder(directory, java, argsfile);
}
static ToolFinder compose(ToolFinder... finders) {
return new CompositeToolFinder(List.of(finders));
}
record CompositeToolFinder(List<ToolFinder> finders) implements ToolFinder {
@Override
public String title() {
return "CompositeToolFinder (%d)".formatted(finders.size());
}
@Override
public List<ToolProvider> findAll() {
return finders.stream().flatMap(finder -> finder.findAll().stream()).toList();
}
@Override
public Optional<ToolProvider> find(String name) {
for (var finder : finders) {
var tool = finder.find(name);
if (tool.isPresent()) return tool;
}
return Optional.empty();
}
@Override
public void visit(int depth, BiConsumer<Integer, ToolFinder> visitor) {
visitor.accept(depth, this);
depth++;
for (var finder : finders) finder.visit(depth, visitor);
}
}
record Provider(String name, ToolFunction function) implements ToolProvider {
@FunctionalInterface
public interface ToolFunction {
int run(PrintWriter out, PrintWriter err, String... args);
}
@Override
public int run(PrintWriter out, PrintWriter err, String... args) {
return function.run(out, err, args);
}
}
record ExecuteProgramToolProvider(String name, List<String> command) implements ToolProvider {
@Override
public int run(PrintWriter out, PrintWriter err, String... arguments) {
var builder = new ProcessBuilder(command);
builder.command().addAll(List.of(arguments));
try {
var process = builder.start();
new Thread(new StreamLineConsumer(process.getInputStream(), out::println)).start();
new Thread(new StreamLineConsumer(process.getErrorStream(), err::println)).start();
return process.waitFor();
} catch (Exception exception) {
exception.printStackTrace(err);
return -1;
}
}
}
}
record StreamLineConsumer(InputStream stream, Consumer<String> consumer) implements Runnable {
public void run() {
new BufferedReader(new InputStreamReader(stream)).lines().forEach(consumer);
}
}
static final class PathSupport {
static String computeChecksum(Path path, String algorithm) {
if (Files.notExists(path)) throw new RuntimeException(path.toString());
try {
if ("size".equalsIgnoreCase(algorithm)) return Long.toString(Files.size(path));
var md = MessageDigest.getInstance(algorithm);
try (var source = new BufferedInputStream(new FileInputStream(path.toFile()));
var target = new DigestOutputStream(OutputStream.nullOutputStream(), md)) {
source.transferTo(target);
}
return String.format(
"%0" + (md.getDigestLength() * 2) + "x", new BigInteger(1, md.digest()));
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
static Properties properties(Path path) {
var properties = new Properties();
if (Files.exists(path)) {
try {
properties.load(new FileInputStream(path.toFile()));
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
return properties;
}
static boolean isJarFile(Path path) {
return nameOrElse(path, "").endsWith(".jar") && Files.isRegularFile(path);
}
static boolean isJavaFile(Path path) {
return nameOrElse(path, "").endsWith(".java") && Files.isRegularFile(path);
}
static boolean isModuleInfoJavaFile(Path path) {
return "module-info.java".equals(name(path)) && Files.isRegularFile(path);
}
static List<Path> list(Path directory, DirectoryStream.Filter<? super Path> filter) {
if (Files.notExists(directory)) return List.of();
var paths = new TreeSet<>(Comparator.comparing(Path::toString));
try (var stream = Files.newDirectoryStream(directory, filter)) {
stream.forEach(paths::add);
} catch (Exception exception) {
throw new RuntimeException(exception);
}
return List.copyOf(paths);
}
static String name(Path path) {
return nameOrElse(path, null);
}
static String nameOrElse(Path path, String defautName) {
var normalized = path.normalize();
var candidate = normalized.toString().isEmpty() ? normalized.toAbsolutePath() : normalized;
var name = candidate.getFileName();
return Optional.ofNullable(name).map(Path::toString).orElse(defautName);
}
}
@Category("Bach")
@Name("Bach.LogEvent")
@Label("Log")
@StackTrace(false)
static final class LogEvent extends Event {
String level;
String message;
}
@Category("Bach")
@Name("Bach.RunEvent")
@Label("Run")
@StackTrace(false)
static final class RunEvent extends Event {
String name;
String args;
int code;
String out;
String err;
}
}
| Flip streaming mode
| src/Bach.java | Flip streaming mode | <ide><path>rc/Bach.java
<ide> ToolCall.of("jar").with("--version"),
<ide> ToolCall.of("javac").with("--version"),
<ide> ToolCall.of("javadoc").with("--version"))
<del> .sequential()
<add> .parallel()
<ide> .forEach(call -> run(call, true));
<ide>
<ide> Stream.of(
<ide> ToolCall.of("jlink").with("--version"),
<ide> ToolCall.of("jmod").with("--version"),
<ide> ToolCall.of("jpackage").with("--version"))
<del> .parallel()
<add> .sequential()
<ide> .forEach(call -> run(call, true));
<ide> }
<ide> |
|
Java | epl-1.0 | ac7db0f484baf3062b049282cf9e567c7f79b69b | 0 | zsmartsystems/com.zsmartsystems.zigbee | /**
* Copyright (c) 2016-2019 by the respective copyright holders.
* 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 com.zsmartsystems.zigbee;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Method;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.awaitility.Awaitility;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import com.zsmartsystems.zigbee.ZigBeeNode.ZigBeeNodeState;
import com.zsmartsystems.zigbee.app.ZigBeeNetworkExtension;
import com.zsmartsystems.zigbee.app.otaserver.ZigBeeOtaUpgradeExtension;
import com.zsmartsystems.zigbee.aps.ZigBeeApsFrame;
import com.zsmartsystems.zigbee.database.ZigBeeNetworkDataStore;
import com.zsmartsystems.zigbee.database.ZigBeeNetworkDatabaseManager;
import com.zsmartsystems.zigbee.security.ZigBeeKey;
import com.zsmartsystems.zigbee.serialization.DefaultDeserializer;
import com.zsmartsystems.zigbee.serialization.DefaultSerializer;
import com.zsmartsystems.zigbee.transaction.ZigBeeTransactionManager;
import com.zsmartsystems.zigbee.transport.ZigBeeTransportState;
import com.zsmartsystems.zigbee.transport.ZigBeeTransportTransmit;
import com.zsmartsystems.zigbee.zcl.ZclCluster;
import com.zsmartsystems.zigbee.zcl.ZclCommand;
import com.zsmartsystems.zigbee.zcl.ZclFieldSerializer;
import com.zsmartsystems.zigbee.zcl.ZclFrameType;
import com.zsmartsystems.zigbee.zcl.ZclHeader;
import com.zsmartsystems.zigbee.zcl.clusters.ZclColorControlCluster;
import com.zsmartsystems.zigbee.zcl.clusters.ZclElectricalMeasurementCluster;
import com.zsmartsystems.zigbee.zcl.clusters.ZclIasZoneCluster;
import com.zsmartsystems.zigbee.zcl.clusters.ZclLevelControlCluster;
import com.zsmartsystems.zigbee.zcl.clusters.ZclMeteringCluster;
import com.zsmartsystems.zigbee.zcl.clusters.ZclOnOffCluster;
import com.zsmartsystems.zigbee.zcl.clusters.ZclOtaUpgradeCluster;
import com.zsmartsystems.zigbee.zcl.clusters.ZclThermostatCluster;
import com.zsmartsystems.zigbee.zcl.clusters.general.ReadAttributesCommand;
import com.zsmartsystems.zigbee.zcl.clusters.onoff.OnCommand;
import com.zsmartsystems.zigbee.zdo.command.ManagementPermitJoiningRequest;
/**
* Tests for {@link ZigBeeNetworkManager}
*
* @author Chris Jackson
*
*/
public class ZigBeeNetworkManagerTest implements ZigBeeNetworkNodeListener, ZigBeeNetworkStateListener,
ZigBeeNetworkEndpointListener, ZigBeeCommandListener {
private static int TIMEOUT = 5000;
private ZigBeeNetworkNodeListener mockedNodeListener;
private List<ZigBeeNode> nodeNodeListenerCapture;
private ArgumentCaptor<ZigBeeApsFrame> mockedApsFrameListener;
private List<ZigBeeNetworkState> networkStateListenerCapture;
private ZigBeeTransportTransmit mockedTransport;
private ZigBeeNetworkStateListener mockedStateListener;
private List<ZigBeeCommand> commandListenerCapture;
@Test
public void testAddRemoveNode() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
ZigBeeNode node1 = new ZigBeeNode(Mockito.mock(ZigBeeNetworkManager.class),
new IeeeAddress("1234567890ABCDEF"));
node1.setNetworkAddress(1234);
ZigBeeNode node2 = new ZigBeeNode(Mockito.mock(ZigBeeNetworkManager.class),
new IeeeAddress("123456789ABCDEF0"));
node2.setNetworkAddress(5678);
// Add a node and make sure it's in the list
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "networkState", ZigBeeNetworkState.ONLINE);
networkManager.addNode(node1);
assertEquals(1, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.timeout(TIMEOUT)).nodeAdded(node1);
// Add it again to make sure it's not duplicated, but we get the added callback again as discovery is incomplete
networkManager.addNode(node1);
assertEquals(1, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.timeout(TIMEOUT).times(2)).nodeAdded(node1);
Mockito.verify(mockedNodeListener, Mockito.times(0)).nodeUpdated(node1);
Set<Object> completeList = Collections.synchronizedSet(new HashSet<>());
completeList.add(new IeeeAddress("1234567890ABCDEF"));
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "nodeDiscoveryComplete", completeList);
// Add it again to make sure it's not duplicated and we get the updated callback
networkManager.addNode(node1);
assertEquals(1, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.times(2)).nodeAdded(node1);
Mockito.verify(mockedNodeListener, Mockito.timeout(TIMEOUT)).nodeUpdated(node1);
// Add a null node to make sure it's not added and we get the updated callback
networkManager.addNode(null);
assertEquals(1, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.times(2)).nodeAdded(node1);
// Add a new node to make sure it's added
networkManager.addNode(node2);
assertEquals(2, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.timeout(TIMEOUT)).nodeAdded(node2);
ZigBeeNode foundNode = networkManager.getNode(1234);
assertNotNull(foundNode);
assertTrue(node1.equals(foundNode));
// Remove it and make sure it's gone
networkManager.removeNode(node1);
assertEquals(1, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.timeout(TIMEOUT)).nodeRemoved(node1);
// Remove again to make sure we're ok
networkManager.removeNode(node1);
assertEquals(1, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.times(1)).nodeRemoved(node1);
// Remove a null node to make sure we're ok
networkManager.removeNode(null);
assertEquals(1, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.times(1)).nodeRemoved(node1);
// Really check it's gone
foundNode = networkManager.getNode(1234);
assertNull(networkManager.getNode(1234));
// Check we can also get using the IEEE address
foundNode = networkManager.getNode(new IeeeAddress("123456789ABCDEF0"));
assertTrue(node2.equals(foundNode));
// Check we don't return false address
foundNode = networkManager.getNode(new IeeeAddress("123456789ABCDEF1"));
assertNull(foundNode);
// Remove the listener
networkManager.addNetworkNodeListener(null);
networkManager.removeNetworkNodeListener(null);
networkManager.removeNetworkNodeListener(mockedNodeListener);
networkManager.shutdown();
}
@Test
public void testAddExistingNode() throws Exception {
String address = "123456789ABCDEF0";
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
ZigBeeNode node1 = new ZigBeeNode(Mockito.mock(ZigBeeNetworkManager.class), new IeeeAddress(address));
node1.setNetworkAddress(1234);
ZigBeeNode node2 = new ZigBeeNode(Mockito.mock(ZigBeeNetworkManager.class), new IeeeAddress(address));
node2.setNetworkAddress(5678);
networkManager.addNode(node1);
assertEquals(1, networkManager.getNodes().size());
ZigBeeNode nodeWeGot = networkManager.getNode(new IeeeAddress(address));
assertEquals(Integer.valueOf(1234), nodeWeGot.getNetworkAddress());
networkManager.addNode(node2);
assertEquals(1, networkManager.getNodes().size());
assertEquals(Integer.valueOf(5678), nodeWeGot.getNetworkAddress());
}
@Test
public void testAddRemoveGroup() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
networkManager.addGroup(new ZigBeeGroupAddress(1));
assertEquals(1, networkManager.getGroups().size());
networkManager.addGroup(new ZigBeeGroupAddress(1));
assertEquals(1, networkManager.getGroups().size());
networkManager.addGroup(new ZigBeeGroupAddress(2));
assertEquals(2, networkManager.getGroups().size());
networkManager.removeGroup(2);
assertEquals(1, networkManager.getGroups().size());
assertNull(networkManager.getGroup(1).getLabel());
ZigBeeGroupAddress group = networkManager.getGroup(1);
assertEquals(1, group.getGroupId());
group.setLabel("Group Label");
networkManager.updateGroup(group);
assertEquals(1, networkManager.getGroups().size());
assertEquals("Group Label", networkManager.getGroup(1).getLabel());
}
@Test
public void testSendCommandZCL() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
networkManager.setSerializer(DefaultSerializer.class, DefaultDeserializer.class);
ZigBeeEndpointAddress deviceAddress = new ZigBeeEndpointAddress(1234, 56);
OnCommand cmd = new OnCommand();
cmd.setClusterId(6);
cmd.setDestinationAddress(deviceAddress);
cmd.setTransactionId(22);
boolean error = false;
networkManager.sendCommand(cmd);
assertFalse(error);
assertEquals(1, mockedApsFrameListener.getAllValues().size());
ZigBeeApsFrame apsFrame = mockedApsFrameListener.getValue();
assertEquals(ZigBeeNwkAddressMode.DEVICE, apsFrame.getAddressMode());
assertEquals(1234, apsFrame.getDestinationAddress());
assertEquals(0, apsFrame.getSourceAddress());
assertEquals(0x104, apsFrame.getProfile());
assertEquals(6, apsFrame.getCluster());
assertEquals(56, apsFrame.getDestinationEndpoint());
}
@Test
public void testReceiveZclCommand() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
networkManager.setSerializer(DefaultSerializer.class, DefaultDeserializer.class);
ZigBeeEndpoint endpoint = Mockito.mock(ZigBeeEndpoint.class);
ZclCluster cluster = new ZclOnOffCluster(endpoint);
Mockito.when(endpoint.getOutputCluster(6)).thenReturn(cluster);
ZigBeeNode node = Mockito.mock(ZigBeeNode.class);
Mockito.when(node.getIeeeAddress()).thenReturn(new IeeeAddress("1111111111111111"));
Mockito.when(node.getNetworkAddress()).thenReturn(1234);
Mockito.when(node.getEndpoint(5)).thenReturn(endpoint);
networkManager.addNode(node);
ZigBeeApsFrame apsFrame = new ZigBeeApsFrame();
apsFrame.setSourceAddress(1234);
apsFrame.setDestinationAddress(0);
apsFrame.setApsCounter(1);
apsFrame.setCluster(6);
apsFrame.setDestinationEndpoint(2);
apsFrame.setProfile(0x104);
apsFrame.setSourceEndpoint(5);
ZclHeader zclHeader = new ZclHeader();
zclHeader.setCommandId(0);
zclHeader.setFrameType(ZclFrameType.ENTIRE_PROFILE_COMMAND);
zclHeader.setSequenceNumber(1);
DefaultSerializer serializer = new DefaultSerializer();
ZclFieldSerializer fieldSerializer = new ZclFieldSerializer(serializer);
apsFrame.setPayload(zclHeader.serialize(fieldSerializer, new int[] {}));
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "networkState", ZigBeeNetworkState.ONLINE);
networkManager.receiveCommand(apsFrame);
Awaitility.await().until(() -> commandListenerUpdated());
ReadAttributesCommand response = (ReadAttributesCommand) commandListenerCapture.get(0);
assertEquals(6, (int) response.getClusterId());
assertEquals(0, (int) response.getCommandId());
assertEquals(1, (int) response.getTransactionId());
assertEquals(new ZigBeeEndpointAddress(1234, 5), response.getSourceAddress());
}
@Test
public void testNetworkStateListener() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeTransactionManager transactionManager = Mockito.mock(ZigBeeTransactionManager.class);
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "transactionManager", transactionManager);
ZigBeeNetworkStateListener stateListener = Mockito.mock(ZigBeeNetworkStateListener.class);
manager.addNetworkStateListener(stateListener);
Mockito.when(mockedTransport.getNwkAddress()).thenReturn(Integer.valueOf(123));
Mockito.when(mockedTransport.getIeeeAddress()).thenReturn(new IeeeAddress("1234567890ABCDEF"));
// Default state is uninitialised
assertEquals(ZigBeeNetworkState.UNINITIALISED, manager.getNetworkState());
// This will be ignored as an illegal state transition
manager.setTransportState(ZigBeeTransportState.ONLINE);
manager.setTransportState(ZigBeeTransportState.INITIALISING);
Mockito.verify(stateListener, Mockito.timeout(TIMEOUT)).networkStateUpdated(ZigBeeNetworkState.INITIALISING);
manager.setTransportState(ZigBeeTransportState.ONLINE);
Mockito.verify(stateListener, Mockito.timeout(TIMEOUT)).networkStateUpdated(ZigBeeNetworkState.ONLINE);
manager.setTransportState(ZigBeeTransportState.ONLINE);
ArgumentCaptor<ZigBeeCommand> mockedTransactionCaptor = ArgumentCaptor.forClass(ZigBeeCommand.class);
Mockito.verify(transactionManager, Mockito.timeout(TIMEOUT).atLeast(1))
.sendTransaction(mockedTransactionCaptor.capture());
Mockito.verify(stateListener, Mockito.timeout(TIMEOUT)).networkStateUpdated(ZigBeeNetworkState.ONLINE);
manager.setTransportState(ZigBeeTransportState.ONLINE);
Mockito.verify(stateListener, Mockito.timeout(TIMEOUT)).networkStateUpdated(ZigBeeNetworkState.ONLINE);
assertTrue(mockedTransactionCaptor.getValue() instanceof ManagementPermitJoiningRequest);
ManagementPermitJoiningRequest joinRequest = (ManagementPermitJoiningRequest) mockedTransactionCaptor
.getValue();
assertEquals(Integer.valueOf(0), joinRequest.getPermitDuration());
assertEquals(Integer.valueOf(123), manager.getLocalNwkAddress());
assertEquals(new IeeeAddress("1234567890ABCDEF"), manager.getLocalIeeeAddress());
manager.removeNetworkStateListener(mockedStateListener);
}
@Test
public void testSetChannel() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
assertEquals(ZigBeeStatus.SUCCESS, networkManager.setZigBeeChannel(ZigBeeChannel.CHANNEL_11));
assertEquals(ZigBeeChannel.CHANNEL_11, networkManager.getZigBeeChannel());
}
@Test
public void testSetPanId() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
assertEquals(ZigBeeStatus.INVALID_ARGUMENTS, networkManager.setZigBeePanId(-1));
assertEquals(ZigBeeStatus.INVALID_ARGUMENTS, networkManager.setZigBeePanId(0x11111));
assertEquals(ZigBeeStatus.SUCCESS, networkManager.setZigBeePanId(10));
assertEquals(0xABCD, networkManager.getZigBeePanId());
}
@Test
public void testSetExtendedPanId() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
ExtendedPanId panId = new ExtendedPanId("1");
assertEquals(ZigBeeStatus.SUCCESS, networkManager.setZigBeeExtendedPanId(panId));
assertEquals(new ExtendedPanId("1"), networkManager.getZigBeeExtendedPanId());
networkManager.removeNetworkStateListener(this);
networkManager.removeCommandListener(this);
}
@Test
public void setZigBeeInstallKey() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeKey key = new ZigBeeKey();
assertEquals(ZigBeeStatus.INVALID_ARGUMENTS, manager.setZigBeeInstallKey(key));
key.setAddress(new IeeeAddress());
manager.setZigBeeInstallKey(key);
}
@Test
public void setZigBeeLinkKey() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeKey key = new ZigBeeKey();
manager.setZigBeeLinkKey(key);
Mockito.verify(mockedTransport, Mockito.times(1)).setTcLinkKey(key);
}
@Test
public void getZigBeeLinkKey() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeKey key = new ZigBeeKey();
Mockito.when(mockedTransport.getTcLinkKey()).thenReturn(key);
assertEquals(key, manager.getZigBeeLinkKey());
}
@Test
public void setZigBeeNetworkKey() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeKey key = new ZigBeeKey();
manager.setZigBeeNetworkKey(key);
Mockito.verify(mockedTransport, Mockito.times(1)).setZigBeeNetworkKey(key);
}
@Test
public void getZigBeeNetworkKey() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeKey key = new ZigBeeKey();
Mockito.when(mockedTransport.getZigBeeNetworkKey()).thenReturn(key);
assertEquals(key, manager.getZigBeeNetworkKey());
}
@Test
public void testPermitJoin() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
ZigBeeTransactionManager transactionManager = Mockito.mock(ZigBeeTransactionManager.class);
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "transactionManager", transactionManager);
assertEquals(ZigBeeStatus.SUCCESS, networkManager.permitJoin(0));
Mockito.verify(transactionManager, Mockito.times(2)).sendTransaction(ArgumentMatchers.any(ZigBeeCommand.class));
assertEquals(ZigBeeStatus.SUCCESS, networkManager.permitJoin(254));
Mockito.verify(transactionManager, Mockito.times(4)).sendTransaction(ArgumentMatchers.any(ZigBeeCommand.class));
assertEquals(ZigBeeStatus.INVALID_ARGUMENTS, networkManager.permitJoin(255));
Mockito.verify(transactionManager, Mockito.times(4)).sendTransaction(ArgumentMatchers.any(ZigBeeCommand.class));
// Check that the unicast sends 1 frame
networkManager.permitJoin(new ZigBeeEndpointAddress(1), 1);
Mockito.verify(transactionManager, Mockito.times(5)).sendTransaction(ArgumentMatchers.any(ZigBeeCommand.class));
// Check that the broadcast sends 2 frames
networkManager.permitJoin(1);
Mockito.verify(transactionManager, Mockito.times(7)).sendTransaction(ArgumentMatchers.any(ZigBeeCommand.class));
}
private ZigBeeNetworkManager mockZigBeeNetworkManager() throws Exception {
mockedTransport = Mockito.mock(ZigBeeTransportTransmit.class);
mockedStateListener = Mockito.mock(ZigBeeNetworkStateListener.class);
mockedNodeListener = Mockito.mock(ZigBeeNetworkNodeListener.class);
nodeNodeListenerCapture = new ArrayList<>();
networkStateListenerCapture = new ArrayList<>();
final ZigBeeNetworkManager networkManager = new ZigBeeNetworkManager(mockedTransport);
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "databaseManager",
Mockito.mock(ZigBeeNetworkDatabaseManager.class));
networkManager.addNetworkNodeListener(mockedNodeListener);
commandListenerCapture = new ArrayList<>();
networkManager.addNetworkNodeListener(this);
networkManager.addNetworkStateListener(this);
networkManager.addCommandListener(this);
networkManager.setSerializer(DefaultSerializer.class, DefaultDeserializer.class);
Mockito.when(mockedTransport.setZigBeeChannel(ArgumentMatchers.any(ZigBeeChannel.class)))
.thenReturn(ZigBeeStatus.SUCCESS);
Mockito.when(mockedTransport.setZigBeePanId(ArgumentMatchers.anyInt())).thenReturn(ZigBeeStatus.SUCCESS);
Mockito.when(mockedTransport.setZigBeeExtendedPanId(ArgumentMatchers.any(ExtendedPanId.class)))
.thenReturn(ZigBeeStatus.SUCCESS);
Mockito.when(mockedTransport.getZigBeePanId()).thenReturn(0xFFFFABCD);
Mockito.when(mockedTransport.getZigBeeChannel()).thenReturn(ZigBeeChannel.CHANNEL_11);
Mockito.when(mockedTransport.getZigBeeExtendedPanId()).thenReturn(new ExtendedPanId("1"));
mockedApsFrameListener = ArgumentCaptor.forClass(ZigBeeApsFrame.class);
Mockito.doNothing().when(mockedTransport).sendCommand(ArgumentMatchers.anyInt(),
mockedApsFrameListener.capture());
return networkManager;
}
@Override
public void deviceAdded(ZigBeeEndpoint device) {
}
@Override
public void deviceUpdated(ZigBeeEndpoint device) {
}
@Override
public void deviceRemoved(ZigBeeEndpoint device) {
}
@Override
public void networkStateUpdated(ZigBeeNetworkState state) {
networkStateListenerCapture.add(state);
}
@Override
public void nodeAdded(ZigBeeNode node) {
nodeNodeListenerCapture.add(node);
}
@Override
public void nodeUpdated(ZigBeeNode node) {
nodeNodeListenerCapture.add(node);
}
@Override
public void nodeRemoved(ZigBeeNode node) {
nodeNodeListenerCapture.add(node);
}
@Override
public void commandReceived(ZigBeeCommand command) {
commandListenerCapture.add(command);
}
private Callable<Integer> stateListenerUpdated() {
return new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return networkStateListenerCapture.size(); // The condition that must be fulfilled
}
};
}
private Callable<Integer> commandListenerUpdated() {
return new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return commandListenerCapture.size(); // The condition that must be fulfilled
}
};
}
private ZigBeeCommand getZigBeeCommand(ZigBeeApsFrame apsFrame) throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
ZigBeeEndpoint endpoint = Mockito.mock(ZigBeeEndpoint.class);
ZclCluster cluster;
cluster = new ZclOnOffCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0006)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0006)).thenReturn(cluster);
cluster = new ZclLevelControlCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0008)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0008)).thenReturn(cluster);
cluster = new ZclOtaUpgradeCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0019)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0019)).thenReturn(cluster);
cluster = new ZclThermostatCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0201)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0201)).thenReturn(cluster);
cluster = new ZclColorControlCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0300)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0300)).thenReturn(cluster);
cluster = new ZclIasZoneCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0500)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0500)).thenReturn(cluster);
cluster = new ZclMeteringCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0702)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0702)).thenReturn(cluster);
cluster = new ZclElectricalMeasurementCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0B04)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0B04)).thenReturn(cluster);
ZigBeeNode node = Mockito.mock(ZigBeeNode.class);
Mockito.when(node.getIeeeAddress()).thenReturn(new IeeeAddress("1111111111111111"));
Mockito.when(node.getNetworkAddress()).thenReturn(0);
Mockito.when(node.getEndpoint(1)).thenReturn(endpoint);
networkManager.addNode(node);
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "networkState", ZigBeeNetworkState.ONLINE);
networkManager.receiveCommand(apsFrame);
Awaitility.await().until(() -> commandListenerUpdated());
if (commandListenerCapture.size() == 0) {
return null;
}
return commandListenerCapture.get(0);
}
/**
* Return a ZigBeeApsFrame from a log entry for an APS frame
*
* @param log the log line
* @return the {@link ZigBeeApsFrame}
*/
private ZigBeeApsFrame getApsFrame(String log) {
ZigBeeApsFrame apsFrame = new ZigBeeApsFrame();
String[] segments = log.substring(16, log.length() - 1).split(", ");
for (String segment : segments) {
String[] key = segment.split("=");
if (key.length == 1 || key[1] == null || key[1].equals("null")) {
continue;
}
switch (key[0]) {
case "sourceAddress":
String[] sourceAddress = key[1].split("/");
apsFrame.setSourceAddress(Integer.parseInt(sourceAddress[0]));
apsFrame.setSourceEndpoint(Integer.parseInt(sourceAddress[1]));
break;
case "destinationAddress":
String[] destAddress = key[1].split("/");
apsFrame.setDestinationAddress(Integer.parseInt(destAddress[0]));
apsFrame.setDestinationEndpoint(Integer.parseInt(destAddress[1]));
break;
case "profile":
apsFrame.setProfile(Integer.parseInt(key[1], 16));
break;
case "cluster":
apsFrame.setCluster(Integer.parseInt(key[1], 16));
break;
case "addressMode":
ZigBeeNwkAddressMode addressMode = ZigBeeNwkAddressMode.valueOf(key[1]);
apsFrame.setAddressMode(addressMode);
break;
case "radius":
apsFrame.setRadius(Integer.parseInt(key[1]));
break;
case "apsSecurity":
apsFrame.setSecurityEnabled(Boolean.valueOf(key[1]));
break;
case "apsCounter":
apsFrame.setApsCounter(Integer.parseInt(key[1], 16));
break;
case "payload":
String split[] = key[1].trim().split(" ");
int[] payload = new int[split.length];
int cnt = 0;
for (String val : split) {
payload[cnt++] = Integer.parseInt(val, 16);
}
apsFrame.setPayload(payload);
break;
}
}
return apsFrame;
}
@Test
public void testExtensions() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeNetworkDatabaseManager databaseManager = Mockito.mock(ZigBeeNetworkDatabaseManager.class);
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "databaseManager", databaseManager);
manager.addExtension(new ZigBeeOtaUpgradeExtension());
ZigBeeNetworkExtension returnedExtension = manager.getExtension(ZigBeeOtaUpgradeExtension.class);
assertTrue(returnedExtension instanceof ZigBeeOtaUpgradeExtension);
manager.shutdown();
Mockito.verify(databaseManager, Mockito.times(1)).shutdown();
assertEquals(ZigBeeNetworkState.SHUTDOWN, manager.getNetworkState());
}
@Test
public void initialize() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
Mockito.when(mockedTransport.initialize()).thenReturn(ZigBeeStatus.COMMUNICATION_ERROR);
ZigBeeTransportTransmit transport = Mockito.mock(ZigBeeTransportTransmit.class);
Mockito.when(transport.initialize()).thenReturn(ZigBeeStatus.COMMUNICATION_ERROR);
ZigBeeNetworkDatabaseManager databaseManager = Mockito.mock(ZigBeeNetworkDatabaseManager.class);
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "databaseManager", databaseManager);
ZigBeeNetworkDataStore dataStore = Mockito.mock(ZigBeeNetworkDataStore.class);
manager.setNetworkDataStore(dataStore);
Mockito.verify(databaseManager, Mockito.times(1)).setDataStore(dataStore);
assertEquals(ZigBeeStatus.COMMUNICATION_ERROR, manager.initialize());
Mockito.verify(databaseManager, Mockito.times(1)).startup();
Mockito.when(mockedTransport.initialize()).thenReturn(ZigBeeStatus.SUCCESS);
Mockito.when(mockedTransport.getNwkAddress()).thenReturn(Integer.valueOf(123));
Mockito.when(mockedTransport.getIeeeAddress()).thenReturn(new IeeeAddress("1234567890ABCDEF"));
manager = mockZigBeeNetworkManager();
Mockito.when(mockedTransport.initialize()).thenReturn(ZigBeeStatus.SUCCESS);
Mockito.when(mockedTransport.getNwkAddress()).thenReturn(Integer.valueOf(123));
Mockito.when(mockedTransport.getIeeeAddress()).thenReturn(new IeeeAddress("1234567890ABCDEF"));
Mockito.when(transport.initialize()).thenReturn(ZigBeeStatus.SUCCESS);
Mockito.when(transport.getNwkAddress()).thenReturn(Integer.valueOf(123));
Mockito.when(transport.getIeeeAddress()).thenReturn(new IeeeAddress("1234567890ABCDEF"));
Mockito.when(mockedTransport.initialize()).thenReturn(ZigBeeStatus.SUCCESS);
Mockito.when(mockedTransport.getNwkAddress()).thenReturn(Integer.valueOf(123));
Mockito.when(mockedTransport.getIeeeAddress()).thenReturn(new IeeeAddress("1234567890ABCDEF"));
databaseManager = Mockito.mock(ZigBeeNetworkDatabaseManager.class);
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "databaseManager", databaseManager);
assertEquals(ZigBeeStatus.SUCCESS, manager.initialize());
Mockito.verify(databaseManager, Mockito.times(1)).startup();
ZigBeeNode node = manager.getNode(new IeeeAddress("1234567890ABCDEF"));
assertNotNull(node);
assertEquals(Integer.valueOf(123), node.getNetworkAddress());
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "networkState", ZigBeeNetworkState.INITIALISING);
assertEquals(ZigBeeStatus.INVALID_STATE, manager.initialize());
assertEquals(ZigBeeNetworkState.INITIALISING, manager.getNetworkState());
manager.shutdown();
Mockito.verify(mockedTransport, Mockito.timeout(TIMEOUT).times(1)).shutdown();
Mockito.verify(databaseManager, Mockito.times(1)).shutdown();
assertEquals(ZigBeeNetworkState.SHUTDOWN, manager.getNetworkState());
}
@Test
public void startup() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
Mockito.when(mockedTransport.initialize()).thenReturn(ZigBeeStatus.COMMUNICATION_ERROR);
assertEquals(ZigBeeStatus.INVALID_STATE, manager.startup(true));
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "networkState", ZigBeeNetworkState.INITIALISING);
assertEquals(mockedTransport, manager.getZigBeeTransport());
Mockito.when(mockedTransport.startup(false)).thenReturn(ZigBeeStatus.COMMUNICATION_ERROR);
Mockito.when(mockedTransport.startup(true)).thenReturn(ZigBeeStatus.SUCCESS);
assertEquals(ZigBeeStatus.COMMUNICATION_ERROR, manager.startup(false));
Mockito.verify(mockedTransport, Mockito.times(1)).startup(false);
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "networkState", ZigBeeNetworkState.INITIALISING);
manager.setTransportState(ZigBeeTransportState.OFFLINE);
assertEquals(ZigBeeNetworkState.INITIALISING, manager.getNetworkState());
assertEquals(ZigBeeStatus.SUCCESS, manager.startup(true));
Mockito.verify(mockedTransport, Mockito.times(1)).startup(true);
Awaitility.await().until(() -> stateListenerUpdated());
assertEquals(ZigBeeNetworkState.ONLINE, manager.getNetworkState());
manager.setTransportState(ZigBeeTransportState.OFFLINE);
Awaitility.await().until(() -> stateListenerUpdated());
assertEquals(ZigBeeNetworkState.OFFLINE, manager.getNetworkState());
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "networkState", ZigBeeNetworkState.ONLINE);
assertEquals(ZigBeeNetworkState.ONLINE, manager.getNetworkState());
assertEquals(ZigBeeStatus.SUCCESS, manager.reinitialize());
Awaitility.await().until(() -> stateListenerUpdated());
assertEquals(ZigBeeNetworkState.INITIALISING, manager.getNetworkState());
}
@Test
public void getTransportVersionString() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
Mockito.when(mockedTransport.initialize()).thenReturn(ZigBeeStatus.COMMUNICATION_ERROR);
Mockito.when(mockedTransport.getVersionString()).thenReturn("Version!");
assertEquals("Version!", manager.getTransportVersionString());
}
@Test
public void nodeStatusUpdate() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeNode node = Mockito.mock(ZigBeeNode.class);
Mockito.when(node.getIeeeAddress()).thenReturn(new IeeeAddress("1234567890ABCDEF"));
manager.addNode(node);
ZigBeeAnnounceListener announceListener = Mockito.mock(ZigBeeAnnounceListener.class);
manager.addAnnounceListener(announceListener);
assertEquals(1, ((Collection<ZigBeeAnnounceListener>) TestUtilities.getField(ZigBeeNetworkManager.class,
manager, "announceListeners")).size());
manager.addAnnounceListener(announceListener);
assertEquals(1, ((Collection<ZigBeeAnnounceListener>) TestUtilities.getField(ZigBeeNetworkManager.class,
manager, "announceListeners")).size());
manager.nodeStatusUpdate(ZigBeeNodeStatus.DEVICE_LEFT, 1234, new IeeeAddress("123456789ABCDEF0"));
Mockito.verify(node, Mockito.times(0)).setNodeState(ArgumentMatchers.any(ZigBeeNodeState.class));
Mockito.verify(announceListener, Mockito.timeout(TIMEOUT).times(1)).deviceStatusUpdate(
ArgumentMatchers.any(ZigBeeNodeStatus.class), ArgumentMatchers.any(Integer.class),
ArgumentMatchers.any(IeeeAddress.class));
manager.nodeStatusUpdate(ZigBeeNodeStatus.DEVICE_LEFT, 1234, new IeeeAddress("1234567890ABCDEF"));
Mockito.verify(node, Mockito.times(1)).setNodeState(ZigBeeNodeState.OFFLINE);
Mockito.verify(announceListener, Mockito.timeout(TIMEOUT).times(2)).deviceStatusUpdate(
ArgumentMatchers.any(ZigBeeNodeStatus.class), ArgumentMatchers.any(Integer.class),
ArgumentMatchers.any(IeeeAddress.class));
manager.removeAnnounceListener(announceListener);
}
private Map<String, String> splitPacket(String packet) {
Map<String, String> tokens = new HashMap<>();
int start = 0;
while (start < packet.length()) {
for (int pos = start; pos < packet.length(); pos++) {
if (packet.charAt(pos) != ' ') {
start = pos;
break;
}
}
int end = start;
for (int pos = start; pos < packet.length(); pos++) {
if (packet.charAt(pos) == '=') {
end = pos;
break;
}
}
String key = packet.substring(start, end);
start = end + 1;
int bracket = 0;
end = packet.length();
for (int pos = start; pos < packet.length(); pos++) {
if (packet.charAt(pos) == '[') {
bracket++;
}
if (packet.charAt(pos) == ']') {
bracket--;
}
if ((packet.charAt(pos) == ',' && bracket == 0) || pos == packet.length()) {
end = pos;
break;
}
}
tokens.put(key, packet.substring(start, end));
start = end + 1;
}
return tokens;
}
private Map<String, String> getZclFrameTokens(String log) {
Map<String, String> tokens = new HashMap<>();
tokens.put("class", log.substring(0, log.indexOf(' ')));
String packet = (log.substring(log.indexOf(" [") + 2, log.length() - 1));
tokens.putAll(splitPacket(packet.substring(packet.indexOf(", ") + 2)));
// String[] segments = log.substring(log.indexOf(" [") + 2, log.length() - 1).split(", ");
// for (String segment : segments) {
// String[] key = segment.split("=");
// if (key.length == 2) {
// tokens.put(key[0], key[1]);
// }
// }
return tokens;
}
private String uppercaseFirst(String input) {
return input.substring(0, 1).toUpperCase() + input.substring(1);
}
public void processLogEntry(String apsString, String zclString) throws Exception {
System.out.println("---> Processing log");
System.out.println(" => " + apsString);
System.out.println(" => " + zclString);
ZigBeeApsFrame apsFrame = getApsFrame(apsString);
System.out.println(" <- " + apsFrame);
ZigBeeCommand command = getZigBeeCommand(apsFrame);
System.out.println(" <- " + command);
assertNotNull(apsFrame);
assertNotNull(command);
Map<String, String> tokens = getZclFrameTokens(zclString);
assertEquals(command.getClass().getSimpleName(), tokens.get("class"));
if (command instanceof ZclCommand) {
assertEquals((Integer) Integer.parseInt(tokens.get("TID"), 16), command.getTransactionId());
}
assertEquals((Integer) Integer.parseInt(tokens.get("cluster"), 16), command.getClusterId());
tokens.remove("class");
tokens.remove("TID");
tokens.remove("cluster");
for (String token : tokens.keySet()) {
System.out.println(" get" + uppercaseFirst(token));
Method method = command.getClass().getMethod("get" + uppercaseFirst(token));
assertEquals(method.getName(), "get" + uppercaseFirst(token));
Object data = method.invoke(command);
Object convertedData;
if (data == null) {
convertedData = null;
} else {
convertedData = convertData(tokens.get(token), data.getClass());
if (convertedData == null) {
System.out.println(" No data conversion in " + data.getClass().getSimpleName() + " "
+ command.getClass().getSimpleName() + ".get" + uppercaseFirst(token) + "(). Data is "
+ tokens.get(token) + ". Using obj.toString().equals();");
convertedData = tokens.get(token);
data = data.toString();
}
}
assertEquals(convertedData, data);
}
}
private Object convertData(String data, Class clazz) {
return null;
}
@Test
public void processLogs() throws Exception {
File dir = FileSystems.getDefault().getPath("./src/test/resource/logs").toFile();
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File file : directoryListing) {
System.out.println("-> Processing log file " + file.toString());
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
String apsString = null;
String zclString = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("#") || line.length() == 0) {
continue;
}
if (apsString == null) {
apsString = line;
continue;
}
if (zclString == null) {
zclString = line;
processLogEntry(apsString, zclString);
apsString = null;
zclString = null;
}
}
br.close();
}
}
}
@Test
public void scheduleTask() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
ScheduledExecutorService scheduler = Mockito.mock(ScheduledExecutorService.class);
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "executorService", scheduler);
assertNull(networkManager.scheduleTask(Mockito.mock(Runnable.class), 0, 0));
assertNull(networkManager.scheduleTask(Mockito.mock(Runnable.class), 0, 1));
assertNull(networkManager.scheduleTask(Mockito.mock(Runnable.class), 0));
networkManager.executeTask(Mockito.mock(Runnable.class));
assertNull(networkManager.rescheduleTask(Mockito.mock(ScheduledFuture.class), Mockito.mock(Runnable.class), 0));
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "networkState", ZigBeeNetworkState.ONLINE);
networkManager.scheduleTask(Mockito.mock(Runnable.class), 0, 0);
Mockito.verify(scheduler, Mockito.times(2)).schedule(ArgumentMatchers.any(Runnable.class),
ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit.class));
networkManager.scheduleTask(Mockito.mock(Runnable.class), 0, 1);
Mockito.verify(scheduler, Mockito.times(2)).scheduleAtFixedRate(ArgumentMatchers.any(Runnable.class),
ArgumentMatchers.anyLong(), ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit.class));
networkManager.scheduleTask(Mockito.mock(Runnable.class), 0);
Mockito.verify(scheduler, Mockito.times(3)).schedule(ArgumentMatchers.any(Runnable.class),
ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit.class));
networkManager.executeTask(Mockito.mock(Runnable.class));
Mockito.verify(scheduler, Mockito.times(1)).execute(ArgumentMatchers.any(Runnable.class));
networkManager.rescheduleTask(Mockito.mock(ScheduledFuture.class), Mockito.mock(Runnable.class), 0);
Mockito.verify(scheduler, Mockito.times(4)).schedule(ArgumentMatchers.any(Runnable.class),
ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit.class));
}
}
| com.zsmartsystems.zigbee/src/test/java/com/zsmartsystems/zigbee/ZigBeeNetworkManagerTest.java | /**
* Copyright (c) 2016-2019 by the respective copyright holders.
* 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 com.zsmartsystems.zigbee;
import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Method;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.awaitility.Awaitility;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import com.zsmartsystems.zigbee.ZigBeeNode.ZigBeeNodeState;
import com.zsmartsystems.zigbee.app.ZigBeeNetworkExtension;
import com.zsmartsystems.zigbee.app.otaserver.ZigBeeOtaUpgradeExtension;
import com.zsmartsystems.zigbee.aps.ZigBeeApsFrame;
import com.zsmartsystems.zigbee.database.ZigBeeNetworkDataStore;
import com.zsmartsystems.zigbee.database.ZigBeeNetworkDatabaseManager;
import com.zsmartsystems.zigbee.security.ZigBeeKey;
import com.zsmartsystems.zigbee.serialization.DefaultDeserializer;
import com.zsmartsystems.zigbee.serialization.DefaultSerializer;
import com.zsmartsystems.zigbee.transaction.ZigBeeTransactionManager;
import com.zsmartsystems.zigbee.transport.ZigBeeTransportState;
import com.zsmartsystems.zigbee.transport.ZigBeeTransportTransmit;
import com.zsmartsystems.zigbee.zcl.ZclCluster;
import com.zsmartsystems.zigbee.zcl.ZclCommand;
import com.zsmartsystems.zigbee.zcl.ZclFieldSerializer;
import com.zsmartsystems.zigbee.zcl.ZclFrameType;
import com.zsmartsystems.zigbee.zcl.ZclHeader;
import com.zsmartsystems.zigbee.zcl.clusters.ZclColorControlCluster;
import com.zsmartsystems.zigbee.zcl.clusters.ZclElectricalMeasurementCluster;
import com.zsmartsystems.zigbee.zcl.clusters.ZclIasZoneCluster;
import com.zsmartsystems.zigbee.zcl.clusters.ZclLevelControlCluster;
import com.zsmartsystems.zigbee.zcl.clusters.ZclMeteringCluster;
import com.zsmartsystems.zigbee.zcl.clusters.ZclOnOffCluster;
import com.zsmartsystems.zigbee.zcl.clusters.ZclOtaUpgradeCluster;
import com.zsmartsystems.zigbee.zcl.clusters.ZclThermostatCluster;
import com.zsmartsystems.zigbee.zcl.clusters.general.ReadAttributesCommand;
import com.zsmartsystems.zigbee.zcl.clusters.onoff.OnCommand;
import com.zsmartsystems.zigbee.zdo.command.ManagementPermitJoiningRequest;
/**
* Tests for {@link ZigBeeNetworkManager}
*
* @author Chris Jackson
*
*/
public class ZigBeeNetworkManagerTest implements ZigBeeNetworkNodeListener, ZigBeeNetworkStateListener,
ZigBeeNetworkEndpointListener, ZigBeeCommandListener {
private static int TIMEOUT = 5000;
private ZigBeeNetworkNodeListener mockedNodeListener;
private List<ZigBeeNode> nodeNodeListenerCapture;
private ArgumentCaptor<ZigBeeApsFrame> mockedApsFrameListener;
private List<ZigBeeNetworkState> networkStateListenerCapture;
private ZigBeeTransportTransmit mockedTransport;
private ZigBeeNetworkStateListener mockedStateListener;
private List<ZigBeeCommand> commandListenerCapture;
@Test
public void testAddRemoveNode() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
ZigBeeNode node1 = new ZigBeeNode(Mockito.mock(ZigBeeNetworkManager.class),
new IeeeAddress("1234567890ABCDEF"));
node1.setNetworkAddress(1234);
ZigBeeNode node2 = new ZigBeeNode(Mockito.mock(ZigBeeNetworkManager.class),
new IeeeAddress("123456789ABCDEF0"));
node2.setNetworkAddress(5678);
// Add a node and make sure it's in the list
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "networkState", ZigBeeNetworkState.ONLINE);
networkManager.addNode(node1);
assertEquals(1, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.timeout(TIMEOUT)).nodeAdded(node1);
// Add it again to make sure it's not duplicated, but we get the added callback again as discovery is incomplete
networkManager.addNode(node1);
assertEquals(1, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.timeout(TIMEOUT).times(2)).nodeAdded(node1);
Mockito.verify(mockedNodeListener, Mockito.times(0)).nodeUpdated(node1);
Set<Object> completeList = Collections.synchronizedSet(new HashSet<>());
completeList.add(new IeeeAddress("1234567890ABCDEF"));
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "nodeDiscoveryComplete", completeList);
// Add it again to make sure it's not duplicated and we get the updated callback
networkManager.addNode(node1);
assertEquals(1, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.times(2)).nodeAdded(node1);
Mockito.verify(mockedNodeListener, Mockito.timeout(TIMEOUT)).nodeUpdated(node1);
// Add a null node to make sure it's not added and we get the updated callback
networkManager.addNode(null);
assertEquals(1, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.times(2)).nodeAdded(node1);
// Add a new node to make sure it's added
networkManager.addNode(node2);
assertEquals(2, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.timeout(TIMEOUT)).nodeAdded(node2);
ZigBeeNode foundNode = networkManager.getNode(1234);
assertNotNull(foundNode);
assertTrue(node1.equals(foundNode));
// Remove it and make sure it's gone
networkManager.removeNode(node1);
assertEquals(1, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.timeout(TIMEOUT)).nodeRemoved(node1);
// Remove again to make sure we're ok
networkManager.removeNode(node1);
assertEquals(1, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.times(1)).nodeRemoved(node1);
// Remove a null node to make sure we're ok
networkManager.removeNode(null);
assertEquals(1, networkManager.getNodes().size());
Mockito.verify(mockedNodeListener, Mockito.times(1)).nodeRemoved(node1);
// Really check it's gone
foundNode = networkManager.getNode(1234);
assertNull(networkManager.getNode(1234));
// Check we can also get using the IEEE address
foundNode = networkManager.getNode(new IeeeAddress("123456789ABCDEF0"));
assertTrue(node2.equals(foundNode));
// Check we don't return false address
foundNode = networkManager.getNode(new IeeeAddress("123456789ABCDEF1"));
assertNull(foundNode);
// Remove the listener
networkManager.addNetworkNodeListener(null);
networkManager.removeNetworkNodeListener(null);
networkManager.removeNetworkNodeListener(mockedNodeListener);
networkManager.shutdown();
}
@Test
public void testAddExistingNode() throws Exception {
String address = "123456789ABCDEF0";
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
ZigBeeNode node1 = new ZigBeeNode(Mockito.mock(ZigBeeNetworkManager.class), new IeeeAddress(address));
node1.setNetworkAddress(1234);
ZigBeeNode node2 = new ZigBeeNode(Mockito.mock(ZigBeeNetworkManager.class), new IeeeAddress(address));
node2.setNetworkAddress(5678);
networkManager.addNode(node1);
assertEquals(1, networkManager.getNodes().size());
ZigBeeNode nodeWeGot = networkManager.getNode(new IeeeAddress(address));
assertEquals(Integer.valueOf(1234), nodeWeGot.getNetworkAddress());
networkManager.addNode(node2);
assertEquals(1, networkManager.getNodes().size());
assertEquals(Integer.valueOf(5678), nodeWeGot.getNetworkAddress());
}
@Test
public void testAddRemoveGroup() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
networkManager.addGroup(new ZigBeeGroupAddress(1));
assertEquals(1, networkManager.getGroups().size());
networkManager.addGroup(new ZigBeeGroupAddress(1));
assertEquals(1, networkManager.getGroups().size());
networkManager.addGroup(new ZigBeeGroupAddress(2));
assertEquals(2, networkManager.getGroups().size());
networkManager.removeGroup(2);
assertEquals(1, networkManager.getGroups().size());
assertNull(networkManager.getGroup(1).getLabel());
ZigBeeGroupAddress group = networkManager.getGroup(1);
assertEquals(1, group.getGroupId());
group.setLabel("Group Label");
networkManager.updateGroup(group);
assertEquals(1, networkManager.getGroups().size());
assertEquals("Group Label", networkManager.getGroup(1).getLabel());
}
@Test
public void testSendCommandZCL() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
networkManager.setSerializer(DefaultSerializer.class, DefaultDeserializer.class);
ZigBeeEndpointAddress deviceAddress = new ZigBeeEndpointAddress(1234, 56);
OnCommand cmd = new OnCommand();
cmd.setClusterId(6);
cmd.setDestinationAddress(deviceAddress);
cmd.setTransactionId(22);
boolean error = false;
networkManager.sendCommand(cmd);
assertFalse(error);
assertEquals(1, mockedApsFrameListener.getAllValues().size());
ZigBeeApsFrame apsFrame = mockedApsFrameListener.getValue();
assertEquals(ZigBeeNwkAddressMode.DEVICE, apsFrame.getAddressMode());
assertEquals(1234, apsFrame.getDestinationAddress());
assertEquals(0, apsFrame.getSourceAddress());
assertEquals(0x104, apsFrame.getProfile());
assertEquals(6, apsFrame.getCluster());
assertEquals(56, apsFrame.getDestinationEndpoint());
}
@Test
public void testReceiveZclCommand() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
networkManager.setSerializer(DefaultSerializer.class, DefaultDeserializer.class);
ZigBeeEndpoint endpoint = Mockito.mock(ZigBeeEndpoint.class);
ZclCluster cluster = new ZclOnOffCluster(endpoint);
Mockito.when(endpoint.getOutputCluster(6)).thenReturn(cluster);
ZigBeeNode node = Mockito.mock(ZigBeeNode.class);
Mockito.when(node.getIeeeAddress()).thenReturn(new IeeeAddress("1111111111111111"));
Mockito.when(node.getNetworkAddress()).thenReturn(1234);
Mockito.when(node.getEndpoint(5)).thenReturn(endpoint);
networkManager.addNode(node);
ZigBeeApsFrame apsFrame = new ZigBeeApsFrame();
apsFrame.setSourceAddress(1234);
apsFrame.setDestinationAddress(0);
apsFrame.setApsCounter(1);
apsFrame.setCluster(6);
apsFrame.setDestinationEndpoint(2);
apsFrame.setProfile(0x104);
apsFrame.setSourceEndpoint(5);
ZclHeader zclHeader = new ZclHeader();
zclHeader.setCommandId(0);
zclHeader.setFrameType(ZclFrameType.ENTIRE_PROFILE_COMMAND);
zclHeader.setSequenceNumber(1);
DefaultSerializer serializer = new DefaultSerializer();
ZclFieldSerializer fieldSerializer = new ZclFieldSerializer(serializer);
apsFrame.setPayload(zclHeader.serialize(fieldSerializer, new int[] {}));
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "networkState", ZigBeeNetworkState.ONLINE);
networkManager.receiveCommand(apsFrame);
Awaitility.await().until(() -> commandListenerUpdated());
ReadAttributesCommand response = (ReadAttributesCommand) commandListenerCapture.get(0);
assertEquals(6, (int) response.getClusterId());
assertEquals(0, (int) response.getCommandId());
assertEquals(1, (int) response.getTransactionId());
assertEquals(new ZigBeeEndpointAddress(1234, 5), response.getSourceAddress());
}
@Test
public void testNetworkStateListener() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeTransactionManager transactionManager = Mockito.mock(ZigBeeTransactionManager.class);
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "transactionManager", transactionManager);
ZigBeeNetworkStateListener stateListener = Mockito.mock(ZigBeeNetworkStateListener.class);
manager.addNetworkStateListener(stateListener);
Mockito.when(mockedTransport.getNwkAddress()).thenReturn(Integer.valueOf(123));
Mockito.when(mockedTransport.getIeeeAddress()).thenReturn(new IeeeAddress("1234567890ABCDEF"));
// Default state is uninitialised
assertEquals(ZigBeeNetworkState.UNINITIALISED, manager.getNetworkState());
// This will be ignored as an illegal state transition
manager.setTransportState(ZigBeeTransportState.ONLINE);
manager.setTransportState(ZigBeeTransportState.INITIALISING);
Mockito.verify(stateListener, Mockito.timeout(TIMEOUT)).networkStateUpdated(ZigBeeNetworkState.INITIALISING);
manager.setTransportState(ZigBeeTransportState.ONLINE);
Mockito.verify(stateListener, Mockito.timeout(TIMEOUT)).networkStateUpdated(ZigBeeNetworkState.ONLINE);
manager.setTransportState(ZigBeeTransportState.ONLINE);
ArgumentCaptor<ZigBeeCommand> mockedTransactionCaptor = ArgumentCaptor.forClass(ZigBeeCommand.class);
Mockito.verify(transactionManager, Mockito.timeout(TIMEOUT).atLeast(1))
.sendTransaction(mockedTransactionCaptor.capture());
Mockito.verify(stateListener, Mockito.timeout(TIMEOUT)).networkStateUpdated(ZigBeeNetworkState.ONLINE);
manager.setTransportState(ZigBeeTransportState.ONLINE);
Mockito.verify(stateListener, Mockito.timeout(TIMEOUT)).networkStateUpdated(ZigBeeNetworkState.ONLINE);
assertTrue(mockedTransactionCaptor.getValue() instanceof ManagementPermitJoiningRequest);
ManagementPermitJoiningRequest joinRequest = (ManagementPermitJoiningRequest) mockedTransactionCaptor
.getValue();
assertEquals(Integer.valueOf(0), joinRequest.getPermitDuration());
assertEquals(Integer.valueOf(123), manager.getLocalNwkAddress());
assertEquals(new IeeeAddress("1234567890ABCDEF"), manager.getLocalIeeeAddress());
manager.removeNetworkStateListener(mockedStateListener);
}
@Test
public void testSetChannel() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
assertEquals(ZigBeeStatus.SUCCESS, networkManager.setZigBeeChannel(ZigBeeChannel.CHANNEL_11));
assertEquals(ZigBeeChannel.CHANNEL_11, networkManager.getZigBeeChannel());
}
@Test
public void testSetPanId() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
assertEquals(ZigBeeStatus.INVALID_ARGUMENTS, networkManager.setZigBeePanId(-1));
assertEquals(ZigBeeStatus.INVALID_ARGUMENTS, networkManager.setZigBeePanId(0x11111));
assertEquals(ZigBeeStatus.SUCCESS, networkManager.setZigBeePanId(10));
assertEquals(0xABCD, networkManager.getZigBeePanId());
}
@Test
public void testSetExtendedPanId() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
ExtendedPanId panId = new ExtendedPanId("1");
assertEquals(ZigBeeStatus.SUCCESS, networkManager.setZigBeeExtendedPanId(panId));
assertEquals(new ExtendedPanId("1"), networkManager.getZigBeeExtendedPanId());
networkManager.removeNetworkStateListener(this);
networkManager.removeCommandListener(this);
}
@Test
public void setZigBeeInstallKey() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeKey key = new ZigBeeKey();
assertEquals(ZigBeeStatus.INVALID_ARGUMENTS, manager.setZigBeeInstallKey(key));
key.setAddress(new IeeeAddress());
manager.setZigBeeInstallKey(key);
}
@Test
public void setZigBeeLinkKey() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeKey key = new ZigBeeKey();
manager.setZigBeeLinkKey(key);
Mockito.verify(mockedTransport, Mockito.times(1)).setTcLinkKey(key);
}
@Test
public void getZigBeeLinkKey() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeKey key = new ZigBeeKey();
Mockito.when(mockedTransport.getTcLinkKey()).thenReturn(key);
assertEquals(key, manager.getZigBeeLinkKey());
}
@Test
public void setZigBeeNetworkKey() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeKey key = new ZigBeeKey();
manager.setZigBeeNetworkKey(key);
Mockito.verify(mockedTransport, Mockito.times(1)).setZigBeeNetworkKey(key);
}
@Test
public void getZigBeeNetworkKey() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeKey key = new ZigBeeKey();
Mockito.when(mockedTransport.getZigBeeNetworkKey()).thenReturn(key);
assertEquals(key, manager.getZigBeeNetworkKey());
}
@Test
public void testPermitJoin() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
ZigBeeTransactionManager transactionManager = Mockito.mock(ZigBeeTransactionManager.class);
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "transactionManager", transactionManager);
assertEquals(ZigBeeStatus.SUCCESS, networkManager.permitJoin(0));
Mockito.verify(transactionManager, Mockito.times(2)).sendTransaction(ArgumentMatchers.any(ZigBeeCommand.class));
assertEquals(ZigBeeStatus.SUCCESS, networkManager.permitJoin(254));
Mockito.verify(transactionManager, Mockito.times(4)).sendTransaction(ArgumentMatchers.any(ZigBeeCommand.class));
assertEquals(ZigBeeStatus.INVALID_ARGUMENTS, networkManager.permitJoin(255));
Mockito.verify(transactionManager, Mockito.times(4)).sendTransaction(ArgumentMatchers.any(ZigBeeCommand.class));
// Check that the unicast sends 1 frame
networkManager.permitJoin(new ZigBeeEndpointAddress(1), 1);
Mockito.verify(transactionManager, Mockito.times(5)).sendTransaction(ArgumentMatchers.any(ZigBeeCommand.class));
// Check that the broadcast sends 2 frames
networkManager.permitJoin(1);
Mockito.verify(transactionManager, Mockito.times(7)).sendTransaction(ArgumentMatchers.any(ZigBeeCommand.class));
}
private ZigBeeNetworkManager mockZigBeeNetworkManager() throws Exception {
mockedTransport = Mockito.mock(ZigBeeTransportTransmit.class);
mockedStateListener = Mockito.mock(ZigBeeNetworkStateListener.class);
mockedNodeListener = Mockito.mock(ZigBeeNetworkNodeListener.class);
nodeNodeListenerCapture = new ArrayList<>();
networkStateListenerCapture = new ArrayList<>();
final ZigBeeNetworkManager networkManager = new ZigBeeNetworkManager(mockedTransport);
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "databaseManager",
Mockito.mock(ZigBeeNetworkDatabaseManager.class));
networkManager.addNetworkNodeListener(mockedNodeListener);
commandListenerCapture = new ArrayList<>();
networkManager.addNetworkNodeListener(this);
networkManager.addNetworkStateListener(this);
networkManager.addCommandListener(this);
networkManager.setSerializer(DefaultSerializer.class, DefaultDeserializer.class);
Mockito.when(mockedTransport.setZigBeeChannel(ArgumentMatchers.any(ZigBeeChannel.class)))
.thenReturn(ZigBeeStatus.SUCCESS);
Mockito.when(mockedTransport.setZigBeePanId(ArgumentMatchers.anyInt())).thenReturn(ZigBeeStatus.SUCCESS);
Mockito.when(mockedTransport.setZigBeeExtendedPanId(ArgumentMatchers.any(ExtendedPanId.class)))
.thenReturn(ZigBeeStatus.SUCCESS);
Mockito.when(mockedTransport.getZigBeePanId()).thenReturn(0xFFFFABCD);
Mockito.when(mockedTransport.getZigBeeChannel()).thenReturn(ZigBeeChannel.CHANNEL_11);
Mockito.when(mockedTransport.getZigBeeExtendedPanId()).thenReturn(new ExtendedPanId("1"));
mockedApsFrameListener = ArgumentCaptor.forClass(ZigBeeApsFrame.class);
Mockito.doNothing().when(mockedTransport).sendCommand(ArgumentMatchers.anyInt(),
mockedApsFrameListener.capture());
return networkManager;
}
@Override
public void deviceAdded(ZigBeeEndpoint device) {
}
@Override
public void deviceUpdated(ZigBeeEndpoint device) {
}
@Override
public void deviceRemoved(ZigBeeEndpoint device) {
}
@Override
public void networkStateUpdated(ZigBeeNetworkState state) {
networkStateListenerCapture.add(state);
}
@Override
public void nodeAdded(ZigBeeNode node) {
nodeNodeListenerCapture.add(node);
}
@Override
public void nodeUpdated(ZigBeeNode node) {
nodeNodeListenerCapture.add(node);
}
@Override
public void nodeRemoved(ZigBeeNode node) {
nodeNodeListenerCapture.add(node);
}
@Override
public void commandReceived(ZigBeeCommand command) {
commandListenerCapture.add(command);
}
private Callable<Integer> stateListenerUpdated() {
return new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return networkStateListenerCapture.size(); // The condition that must be fulfilled
}
};
}
private Callable<Integer> commandListenerUpdated() {
return new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return commandListenerCapture.size(); // The condition that must be fulfilled
}
};
}
private ZigBeeCommand getZigBeeCommand(ZigBeeApsFrame apsFrame) throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
ZigBeeEndpoint endpoint = Mockito.mock(ZigBeeEndpoint.class);
ZclCluster cluster;
cluster = new ZclOnOffCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0006)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0006)).thenReturn(cluster);
cluster = new ZclLevelControlCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0008)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0008)).thenReturn(cluster);
cluster = new ZclOtaUpgradeCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0019)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0019)).thenReturn(cluster);
cluster = new ZclThermostatCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0201)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0201)).thenReturn(cluster);
cluster = new ZclColorControlCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0300)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0300)).thenReturn(cluster);
cluster = new ZclIasZoneCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0500)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0500)).thenReturn(cluster);
cluster = new ZclMeteringCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0702)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0702)).thenReturn(cluster);
cluster = new ZclElectricalMeasurementCluster(endpoint);
Mockito.when(endpoint.getInputCluster(0x0B04)).thenReturn(cluster);
Mockito.when(endpoint.getOutputCluster(0x0B04)).thenReturn(cluster);
ZigBeeNode node = Mockito.mock(ZigBeeNode.class);
Mockito.when(node.getIeeeAddress()).thenReturn(new IeeeAddress("1111111111111111"));
Mockito.when(node.getNetworkAddress()).thenReturn(0);
Mockito.when(node.getEndpoint(1)).thenReturn(endpoint);
networkManager.addNode(node);
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "networkState", ZigBeeNetworkState.ONLINE);
networkManager.receiveCommand(apsFrame);
Awaitility.await().until(() -> commandListenerUpdated());
if (commandListenerCapture.size() == 0) {
return null;
}
return commandListenerCapture.get(0);
}
/**
* Return a ZigBeeApsFrame from a log entry for an APS frame
*
* @param log the log line
* @return the {@link ZigBeeApsFrame}
*/
private ZigBeeApsFrame getApsFrame(String log) {
ZigBeeApsFrame apsFrame = new ZigBeeApsFrame();
String[] segments = log.substring(16, log.length() - 1).split(", ");
for (String segment : segments) {
String[] key = segment.split("=");
if (key.length == 1 || key[1] == null || key[1].equals("null")) {
continue;
}
switch (key[0]) {
case "sourceAddress":
String[] sourceAddress = key[1].split("/");
apsFrame.setSourceAddress(Integer.parseInt(sourceAddress[0]));
apsFrame.setSourceEndpoint(Integer.parseInt(sourceAddress[1]));
break;
case "destinationAddress":
String[] destAddress = key[1].split("/");
apsFrame.setDestinationAddress(Integer.parseInt(destAddress[0]));
apsFrame.setDestinationEndpoint(Integer.parseInt(destAddress[1]));
break;
case "profile":
apsFrame.setProfile(Integer.parseInt(key[1], 16));
break;
case "cluster":
apsFrame.setCluster(Integer.parseInt(key[1], 16));
break;
case "addressMode":
ZigBeeNwkAddressMode addressMode = ZigBeeNwkAddressMode.valueOf(key[1]);
apsFrame.setAddressMode(addressMode);
break;
case "radius":
apsFrame.setRadius(Integer.parseInt(key[1]));
break;
case "apsSecurity":
apsFrame.setSecurityEnabled(Boolean.valueOf(key[1]));
break;
case "apsCounter":
apsFrame.setApsCounter(Integer.parseInt(key[1], 16));
break;
case "payload":
String split[] = key[1].trim().split(" ");
int[] payload = new int[split.length];
int cnt = 0;
for (String val : split) {
payload[cnt++] = Integer.parseInt(val, 16);
}
apsFrame.setPayload(payload);
break;
}
}
return apsFrame;
}
@Test
public void testExtensions() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeNetworkDatabaseManager databaseManager = Mockito.mock(ZigBeeNetworkDatabaseManager.class);
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "databaseManager", databaseManager);
manager.addExtension(new ZigBeeOtaUpgradeExtension());
ZigBeeNetworkExtension returnedExtension = manager.getExtension(ZigBeeOtaUpgradeExtension.class);
assertTrue(returnedExtension instanceof ZigBeeOtaUpgradeExtension);
manager.shutdown();
Mockito.verify(databaseManager, Mockito.times(1)).shutdown();
}
@Test
public void initialize() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
Mockito.when(mockedTransport.initialize()).thenReturn(ZigBeeStatus.COMMUNICATION_ERROR);
ZigBeeTransportTransmit transport = Mockito.mock(ZigBeeTransportTransmit.class);
Mockito.when(transport.initialize()).thenReturn(ZigBeeStatus.COMMUNICATION_ERROR);
ZigBeeNetworkDatabaseManager databaseManager = Mockito.mock(ZigBeeNetworkDatabaseManager.class);
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "databaseManager", databaseManager);
ZigBeeNetworkDataStore dataStore = Mockito.mock(ZigBeeNetworkDataStore.class);
manager.setNetworkDataStore(dataStore);
Mockito.verify(databaseManager, Mockito.times(1)).setDataStore(dataStore);
assertEquals(ZigBeeStatus.COMMUNICATION_ERROR, manager.initialize());
Mockito.verify(databaseManager, Mockito.times(1)).startup();
Mockito.when(mockedTransport.initialize()).thenReturn(ZigBeeStatus.SUCCESS);
Mockito.when(mockedTransport.getNwkAddress()).thenReturn(Integer.valueOf(123));
Mockito.when(mockedTransport.getIeeeAddress()).thenReturn(new IeeeAddress("1234567890ABCDEF"));
manager = mockZigBeeNetworkManager();
Mockito.when(mockedTransport.initialize()).thenReturn(ZigBeeStatus.SUCCESS);
Mockito.when(mockedTransport.getNwkAddress()).thenReturn(Integer.valueOf(123));
Mockito.when(mockedTransport.getIeeeAddress()).thenReturn(new IeeeAddress("1234567890ABCDEF"));
Mockito.when(transport.initialize()).thenReturn(ZigBeeStatus.SUCCESS);
Mockito.when(transport.getNwkAddress()).thenReturn(Integer.valueOf(123));
Mockito.when(transport.getIeeeAddress()).thenReturn(new IeeeAddress("1234567890ABCDEF"));
Mockito.when(mockedTransport.initialize()).thenReturn(ZigBeeStatus.SUCCESS);
Mockito.when(mockedTransport.getNwkAddress()).thenReturn(Integer.valueOf(123));
Mockito.when(mockedTransport.getIeeeAddress()).thenReturn(new IeeeAddress("1234567890ABCDEF"));
databaseManager = Mockito.mock(ZigBeeNetworkDatabaseManager.class);
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "databaseManager", databaseManager);
assertEquals(ZigBeeStatus.SUCCESS, manager.initialize());
Mockito.verify(databaseManager, Mockito.times(1)).startup();
ZigBeeNode node = manager.getNode(new IeeeAddress("1234567890ABCDEF"));
assertNotNull(node);
assertEquals(Integer.valueOf(123), node.getNetworkAddress());
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "networkState", ZigBeeNetworkState.INITIALISING);
assertEquals(ZigBeeStatus.INVALID_STATE, manager.initialize());
assertEquals(ZigBeeNetworkState.INITIALISING, manager.getNetworkState());
manager.shutdown();
Mockito.verify(mockedTransport, Mockito.timeout(TIMEOUT).times(1)).shutdown();
Mockito.verify(databaseManager, Mockito.times(1)).shutdown();
assertEquals(ZigBeeNetworkState.SHUTDOWN, manager.getNetworkState());
}
@Test
public void startup() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
Mockito.when(mockedTransport.initialize()).thenReturn(ZigBeeStatus.COMMUNICATION_ERROR);
assertEquals(ZigBeeStatus.INVALID_STATE, manager.startup(true));
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "networkState", ZigBeeNetworkState.INITIALISING);
assertEquals(mockedTransport, manager.getZigBeeTransport());
Mockito.when(mockedTransport.startup(false)).thenReturn(ZigBeeStatus.COMMUNICATION_ERROR);
Mockito.when(mockedTransport.startup(true)).thenReturn(ZigBeeStatus.SUCCESS);
assertEquals(ZigBeeStatus.COMMUNICATION_ERROR, manager.startup(false));
Mockito.verify(mockedTransport, Mockito.times(1)).startup(false);
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "networkState", ZigBeeNetworkState.INITIALISING);
manager.setTransportState(ZigBeeTransportState.OFFLINE);
assertEquals(ZigBeeNetworkState.INITIALISING, manager.getNetworkState());
assertEquals(ZigBeeStatus.SUCCESS, manager.startup(true));
Mockito.verify(mockedTransport, Mockito.times(1)).startup(true);
Awaitility.await().until(() -> stateListenerUpdated());
assertEquals(ZigBeeNetworkState.ONLINE, manager.getNetworkState());
manager.setTransportState(ZigBeeTransportState.OFFLINE);
Awaitility.await().until(() -> stateListenerUpdated());
assertEquals(ZigBeeNetworkState.OFFLINE, manager.getNetworkState());
TestUtilities.setField(ZigBeeNetworkManager.class, manager, "networkState", ZigBeeNetworkState.ONLINE);
assertEquals(ZigBeeNetworkState.ONLINE, manager.getNetworkState());
assertEquals(ZigBeeStatus.SUCCESS, manager.reinitialize());
Awaitility.await().until(() -> stateListenerUpdated());
assertEquals(ZigBeeNetworkState.INITIALISING, manager.getNetworkState());
}
@Test
public void getTransportVersionString() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
Mockito.when(mockedTransport.initialize()).thenReturn(ZigBeeStatus.COMMUNICATION_ERROR);
Mockito.when(mockedTransport.getVersionString()).thenReturn("Version!");
assertEquals("Version!", manager.getTransportVersionString());
}
@Test
public void nodeStatusUpdate() throws Exception {
ZigBeeNetworkManager manager = mockZigBeeNetworkManager();
ZigBeeNode node = Mockito.mock(ZigBeeNode.class);
Mockito.when(node.getIeeeAddress()).thenReturn(new IeeeAddress("1234567890ABCDEF"));
manager.addNode(node);
ZigBeeAnnounceListener announceListener = Mockito.mock(ZigBeeAnnounceListener.class);
manager.addAnnounceListener(announceListener);
assertEquals(1, ((Collection<ZigBeeAnnounceListener>) TestUtilities.getField(ZigBeeNetworkManager.class,
manager, "announceListeners")).size());
manager.addAnnounceListener(announceListener);
assertEquals(1, ((Collection<ZigBeeAnnounceListener>) TestUtilities.getField(ZigBeeNetworkManager.class,
manager, "announceListeners")).size());
manager.nodeStatusUpdate(ZigBeeNodeStatus.DEVICE_LEFT, 1234, new IeeeAddress("123456789ABCDEF0"));
Mockito.verify(node, Mockito.times(0)).setNodeState(ArgumentMatchers.any(ZigBeeNodeState.class));
Mockito.verify(announceListener, Mockito.timeout(TIMEOUT).times(1)).deviceStatusUpdate(
ArgumentMatchers.any(ZigBeeNodeStatus.class), ArgumentMatchers.any(Integer.class),
ArgumentMatchers.any(IeeeAddress.class));
manager.nodeStatusUpdate(ZigBeeNodeStatus.DEVICE_LEFT, 1234, new IeeeAddress("1234567890ABCDEF"));
Mockito.verify(node, Mockito.times(1)).setNodeState(ZigBeeNodeState.OFFLINE);
Mockito.verify(announceListener, Mockito.timeout(TIMEOUT).times(2)).deviceStatusUpdate(
ArgumentMatchers.any(ZigBeeNodeStatus.class), ArgumentMatchers.any(Integer.class),
ArgumentMatchers.any(IeeeAddress.class));
manager.removeAnnounceListener(announceListener);
}
private Map<String, String> splitPacket(String packet) {
Map<String, String> tokens = new HashMap<>();
int start = 0;
while (start < packet.length()) {
for (int pos = start; pos < packet.length(); pos++) {
if (packet.charAt(pos) != ' ') {
start = pos;
break;
}
}
int end = start;
for (int pos = start; pos < packet.length(); pos++) {
if (packet.charAt(pos) == '=') {
end = pos;
break;
}
}
String key = packet.substring(start, end);
start = end + 1;
int bracket = 0;
end = packet.length();
for (int pos = start; pos < packet.length(); pos++) {
if (packet.charAt(pos) == '[') {
bracket++;
}
if (packet.charAt(pos) == ']') {
bracket--;
}
if ((packet.charAt(pos) == ',' && bracket == 0) || pos == packet.length()) {
end = pos;
break;
}
}
tokens.put(key, packet.substring(start, end));
start = end + 1;
}
return tokens;
}
private Map<String, String> getZclFrameTokens(String log) {
Map<String, String> tokens = new HashMap<>();
tokens.put("class", log.substring(0, log.indexOf(' ')));
String packet = (log.substring(log.indexOf(" [") + 2, log.length() - 1));
tokens.putAll(splitPacket(packet.substring(packet.indexOf(", ") + 2)));
// String[] segments = log.substring(log.indexOf(" [") + 2, log.length() - 1).split(", ");
// for (String segment : segments) {
// String[] key = segment.split("=");
// if (key.length == 2) {
// tokens.put(key[0], key[1]);
// }
// }
return tokens;
}
private String uppercaseFirst(String input) {
return input.substring(0, 1).toUpperCase() + input.substring(1);
}
public void processLogEntry(String apsString, String zclString) throws Exception {
System.out.println("---> Processing log");
System.out.println(" => " + apsString);
System.out.println(" => " + zclString);
ZigBeeApsFrame apsFrame = getApsFrame(apsString);
System.out.println(" <- " + apsFrame);
ZigBeeCommand command = getZigBeeCommand(apsFrame);
System.out.println(" <- " + command);
assertNotNull(apsFrame);
assertNotNull(command);
Map<String, String> tokens = getZclFrameTokens(zclString);
assertEquals(command.getClass().getSimpleName(), tokens.get("class"));
if (command instanceof ZclCommand) {
assertEquals((Integer) Integer.parseInt(tokens.get("TID"), 16), command.getTransactionId());
}
assertEquals((Integer) Integer.parseInt(tokens.get("cluster"), 16), command.getClusterId());
tokens.remove("class");
tokens.remove("TID");
tokens.remove("cluster");
for (String token : tokens.keySet()) {
System.out.println(" get" + uppercaseFirst(token));
Method method = command.getClass().getMethod("get" + uppercaseFirst(token));
assertEquals(method.getName(), "get" + uppercaseFirst(token));
Object data = method.invoke(command);
Object convertedData;
if (data == null) {
convertedData = null;
} else {
convertedData = convertData(tokens.get(token), data.getClass());
if (convertedData == null) {
System.out.println(" No data conversion in " + data.getClass().getSimpleName() + " "
+ command.getClass().getSimpleName() + ".get" + uppercaseFirst(token) + "(). Data is "
+ tokens.get(token) + ". Using obj.toString().equals();");
convertedData = tokens.get(token);
data = data.toString();
}
}
assertEquals(convertedData, data);
}
}
private Object convertData(String data, Class clazz) {
return null;
}
@Test
public void processLogs() throws Exception {
File dir = FileSystems.getDefault().getPath("./src/test/resource/logs").toFile();
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File file : directoryListing) {
System.out.println("-> Processing log file " + file.toString());
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
String apsString = null;
String zclString = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("#") || line.length() == 0) {
continue;
}
if (apsString == null) {
apsString = line;
continue;
}
if (zclString == null) {
zclString = line;
processLogEntry(apsString, zclString);
apsString = null;
zclString = null;
}
}
br.close();
}
}
}
@Test
public void scheduleTask() throws Exception {
ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
ScheduledExecutorService scheduler = Mockito.mock(ScheduledExecutorService.class);
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "executorService", scheduler);
assertNull(networkManager.scheduleTask(Mockito.mock(Runnable.class), 0, 0));
assertNull(networkManager.scheduleTask(Mockito.mock(Runnable.class), 0, 1));
assertNull(networkManager.scheduleTask(Mockito.mock(Runnable.class), 0));
networkManager.executeTask(Mockito.mock(Runnable.class));
assertNull(networkManager.rescheduleTask(Mockito.mock(ScheduledFuture.class), Mockito.mock(Runnable.class), 0));
TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "networkState", ZigBeeNetworkState.ONLINE);
networkManager.scheduleTask(Mockito.mock(Runnable.class), 0, 0);
Mockito.verify(scheduler, Mockito.times(2)).schedule(ArgumentMatchers.any(Runnable.class),
ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit.class));
networkManager.scheduleTask(Mockito.mock(Runnable.class), 0, 1);
Mockito.verify(scheduler, Mockito.times(2)).scheduleAtFixedRate(ArgumentMatchers.any(Runnable.class),
ArgumentMatchers.anyLong(), ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit.class));
networkManager.scheduleTask(Mockito.mock(Runnable.class), 0);
Mockito.verify(scheduler, Mockito.times(3)).schedule(ArgumentMatchers.any(Runnable.class),
ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit.class));
networkManager.executeTask(Mockito.mock(Runnable.class));
Mockito.verify(scheduler, Mockito.times(1)).execute(ArgumentMatchers.any(Runnable.class));
networkManager.rescheduleTask(Mockito.mock(ScheduledFuture.class), Mockito.mock(Runnable.class), 0);
Mockito.verify(scheduler, Mockito.times(4)).schedule(ArgumentMatchers.any(Runnable.class),
ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit.class));
}
}
| Add shutdown test (#631)
Signed-off-by: Chris Jackson <[email protected]> | com.zsmartsystems.zigbee/src/test/java/com/zsmartsystems/zigbee/ZigBeeNetworkManagerTest.java | Add shutdown test (#631) | <ide><path>om.zsmartsystems.zigbee/src/test/java/com/zsmartsystems/zigbee/ZigBeeNetworkManagerTest.java
<ide> */
<ide> package com.zsmartsystems.zigbee;
<ide>
<del>import static org.junit.Assert.*;
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertFalse;
<add>import static org.junit.Assert.assertNotNull;
<add>import static org.junit.Assert.assertNull;
<add>import static org.junit.Assert.assertTrue;
<ide>
<ide> import java.io.BufferedReader;
<ide> import java.io.File;
<ide>
<ide> manager.shutdown();
<ide> Mockito.verify(databaseManager, Mockito.times(1)).shutdown();
<add>
<add> assertEquals(ZigBeeNetworkState.SHUTDOWN, manager.getNetworkState());
<ide> }
<ide>
<ide> @Test |
|
JavaScript | mit | b3c2c0bd38abeb28fe63b7a19923e9fe6852dd7e | 0 | appac/cornelius | let prune = function () {}
prune.prototype.searchResults = function (data) {
let resultsCount = data.search_player_all.queryResults.totalSize;
let prunedResults = [];
if (resultsCount > 1) {
let searchResults = data.search_player_all.queryResults.row;
for (let i = 0; i < searchResults.length; i++) {
let player = searchResults[i];
let prunedPlayer = this.playerData(player);
prunedResults.push(prunedPlayer);
}
} else {
let player = data.search_player_all.queryResults.row;
let prunedPlayer = this.playerData(player);
prunedResults.push(prunedPlayer);
}
return prunedResults;
}
prune.prototype.playerData = function (data) {
let player = {
id: data.player_id,
name: {
full: data.name_display_first_last,
first: data.name_first,
last: data.name_last,
roster: data.name_display_roster
},
position: {
id: data.position_id,
code: data.position
},
team: {
id: data.team_id,
name: data.team_full,
abbrev: data.team_abbrev,
code: data.team_code,
league: data.league
},
date: {
pro_debut: data.pro_debut_date,
birth: data.birth_date
},
geo: {
city: data.birth_city,
state: data.birth_city,
country: data.birth_country,
high_school: data.high_school,
college: data.college
},
attribute: {
bats: data.bats,
throws: data.throws,
weight: data.weight,
height: {
feet: data.height_feet,
inches: data.height_inches
}
}
};
return player;
}
prune.prototype.rosterData = function (data) {
let prunedData = [];
let roster = data.roster_all.queryResults.row;
roster.forEach(function (player) {
let name = player.player_html;
name = name.replace(/\,/g,"").split(' ').reverse().join(' ');
let prunedPlayer = {
id: player.player_id,
name: name
}
prunedData.push(prunedPlayer);
});
return prunedData;
}
module.exports = new prune; | utils/prune/index.js | let prune = function () {}
prune.prototype.searchResults = function (data) {
let resultsCount = data.search_player_all.queryResults.totalSize;
let prunedResults = [];
if (resultsCount > 1) {
let searchResults = data.search_player_all.queryResults.row;
searchResults.forEach(function (player) {
let prunedPlayer = prunePlayerData(player);
prunedResults.push(prunedPlayer);
});
} else {
let player = data.search_player_all.queryResults.row;
let prunedPlayer = prunePlayerData(player);
prunedResults.push(prunedPlayer);
}
return prunedResults;
}
prune.prototype.playerData = function (data) {
let player = {
id: data.player_id,
name: {
full: data.name_display_first_last,
first: data.name_first,
last: data.name_last,
roster: data.name_display_roster
},
position: {
id: data.position_id,
code: data.position
},
team: {
id: data.team_id,
name: data.team_full,
abbrev: data.team_abbrev,
code: data.team_code,
league: data.league
},
date: {
pro_debut: data.pro_debut_date,
birth: data.birth_date
},
geo: {
city: data.birth_city,
state: data.birth_city,
country: data.birth_country,
high_school: data.high_school,
college: data.college
},
attribute: {
bats: data.bats,
throws: data.throws,
weight: data.weight,
height: {
feet: data.height_feet,
inches: data.height_inches
}
}
};
return player;
}
prune.prototype.rosterData = function (data) {
let prunedData = [];
let roster = data.roster_all.queryResults.row;
roster.forEach(function (player) {
let name = player.player_html;
name = name.replace(/\,/g,"").split(' ').reverse().join(' ');
let prunedPlayer = {
id: player.player_id,
name: name
}
prunedData.push(prunedPlayer);
});
return prunedData;
}
module.exports = new prune; | correct reference to prune.playerData within prune.searchData
switched forEach to regular for loop, to maintain context | utils/prune/index.js | correct reference to prune.playerData within prune.searchData | <ide><path>tils/prune/index.js
<ide> prune.prototype.searchResults = function (data) {
<ide> let resultsCount = data.search_player_all.queryResults.totalSize;
<ide> let prunedResults = [];
<del>
<add>
<ide> if (resultsCount > 1) {
<ide> let searchResults = data.search_player_all.queryResults.row;
<ide>
<del> searchResults.forEach(function (player) {
<del> let prunedPlayer = prunePlayerData(player);
<add> for (let i = 0; i < searchResults.length; i++) {
<add> let player = searchResults[i];
<add> let prunedPlayer = this.playerData(player);
<ide> prunedResults.push(prunedPlayer);
<del> });
<add> }
<ide> } else {
<ide> let player = data.search_player_all.queryResults.row;
<del> let prunedPlayer = prunePlayerData(player);
<add> let prunedPlayer = this.playerData(player);
<ide>
<ide> prunedResults.push(prunedPlayer);
<ide> } |
|
Java | mit | b46b6fce35becbed7eb4ba9ddd67aa29adf3069d | 0 | kaltsimon/Chasing-Pictures-front-end,kaltsimon/Chasing-Pictures-front-end,ChasingPictures/front-end,ChasingPictures/front-end,kaltsimon/Chasing-Pictures-front-end,ChasingPictures/front-end | package de.fu_berlin.cdv.chasingpictures.util;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.widget.Toast;
import xdroid.toaster.Toaster;
/**
* Class that provides utility methods.
*
* @author Simon Kalt
*/
public class Utilities {
/**
* @param context The current context
* @param formatString The message to be displayed
* @param args Arguments to be formatted into the string
* @deprecated Use {@link #showError(Context, int, Object...)} if possible.
*/
@Deprecated
public static void showError(Context context, String formatString, Object... args) {
String message = args.length == 0 ? formatString : String.format(formatString, args);
Toaster.toast(message);
}
/**
* Displays an error to the user.
* Currently does the same thing as {@link #showToast(Context, int, Object...)} but
* could later be changed to look differently.
*
* @param context The current context
* @param resID A string resource to be displayed
* @param args Arguments to be formatted into the string
*/
public static void showError(Context context, @StringRes int resID, Object... args) {
showToast(context, resID, args);
}
/**
* Displays a message to the user.
*
* @param context The current context
* @param resID A string resource to be displayed
* @param args Arguments to be formatted into the string
*/
public static void showToast(Context context, @StringRes final int resID, final Object... args) {
String message = context.getString(resID);
message = args.length == 0 ? message : String.format(message, args);
Toaster.toast(message);
}
}
| ChasingPictures/app/src/main/java/de/fu_berlin/cdv/chasingpictures/util/Utilities.java | package de.fu_berlin.cdv.chasingpictures.util;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.widget.Toast;
import xdroid.toaster.Toaster;
/**
* Class that provides utility methods.
*
* @author Simon Kalt
*/
public class Utilities {
/**
* @param context The current context
* @param formatString The message to be displayed
* @param args Arguments to be formatted into the string
* @deprecated Use {@link #showError(Context, int, Object...)} if possible.
*/
@Deprecated
public static void showError(Context context, String formatString, Object... args) {
String message = args.length == 0 ? formatString : String.format(formatString, args);
Toaster.toast(message);
}
/**
* Displays an error to the user.
* Currently does the same thing as {@link #showToast(Context, int, Object...)} but
* could later be changed to look differently.
*
* @param context The current context
* @param resID A string resource to be displayed
* @param args Arguments to be formatted into the string
*/
public static void showError(Context context, @StringRes int resID, Object... args) {
showToast(context, resID, args);
}
/**
* Displays a message to the user.
*
* @param context The current context
* @param resID A string resource to be displayed
* @param args Arguments to be formatted into the string
*/
public static void showToast(Context context, @StringRes final int resID, final Object... args) {
String message = context.getString(resID);
message = args.length == 0 ? message : String.format(message, args);
Toaster.toast(message);
}
/**
* Displays a message to the user.
*
* @param context The current context
* @param resID A string resource to be displayed
* @param handler The handler to post {@link Toast#show()} to
* @param args Arguments to be formatted into the string
*/
public static void showToast(Context context, @StringRes final int resID, @Nullable Handler handler, final Object... args) {
@SuppressLint("ShowToast")
final Toast toast = Toast.makeText(
context,
String.format(context.getString(resID), args),
Toast.LENGTH_SHORT
);
// Display on main looper.
if (handler != null) {
handler.post(new Runnable() {
@Override
public void run() {
toast.show();
}
});
} else {
toast.show();
}
}
}
| Remove obsolete utility method
| ChasingPictures/app/src/main/java/de/fu_berlin/cdv/chasingpictures/util/Utilities.java | Remove obsolete utility method | <ide><path>hasingPictures/app/src/main/java/de/fu_berlin/cdv/chasingpictures/util/Utilities.java
<ide> message = args.length == 0 ? message : String.format(message, args);
<ide> Toaster.toast(message);
<ide> }
<del>
<del> /**
<del> * Displays a message to the user.
<del> *
<del> * @param context The current context
<del> * @param resID A string resource to be displayed
<del> * @param handler The handler to post {@link Toast#show()} to
<del> * @param args Arguments to be formatted into the string
<del> */
<del> public static void showToast(Context context, @StringRes final int resID, @Nullable Handler handler, final Object... args) {
<del> @SuppressLint("ShowToast")
<del> final Toast toast = Toast.makeText(
<del> context,
<del> String.format(context.getString(resID), args),
<del> Toast.LENGTH_SHORT
<del> );
<del>
<del> // Display on main looper.
<del> if (handler != null) {
<del> handler.post(new Runnable() {
<del> @Override
<del> public void run() {
<del> toast.show();
<del> }
<del> });
<del> } else {
<del> toast.show();
<del> }
<del> }
<ide> } |
|
JavaScript | mit | c27279c047c303e47cc8dfba0d2f917b3084844c | 0 | Hanul/UPPERCASE.JS,Hanul/UJS,Hanul/UJS,Hanul/UPPERCASE.JS,Hanul/UJS,Hanul/UPPERCASE.JS | /*
* CPU clustering work.
*/
global.CPU_CLUSTERING = METHOD(function(m) {
'use strict';
var
//IMPORT: cluster
cluster = require('cluster'),
// cpu count
cpuCount = require('os').cpus().length,
// worker id
workerId = 1,
// get worker id.
getWorkerId;
cluster.schedulingPolicy = cluster.SCHED_RR;
m.getWorkerId = getWorkerId = function() {
return workerId;
};
return {
run : function(work) {
//REQUIRED: work
// when master
if (cluster.isMaster) {
RUN(function() {
var
// pids
pids = {},
// fork.
fork = function() {
var
// new worker
newWorker = cluster.fork();
pids[newWorker.id] = newWorker.process.pid;
// receive data from new worker.
newWorker.on('message', function(data) {
if (data === '__GET_PIDS') {
newWorker.send(STRINGIFY({
methodName : '__GET_PIDS',
data : pids
}));
}
else {
// send data to all workers except new worker.
EACH(cluster.workers, function(worker) {
if (worker !== newWorker) {
worker.send(data);
}
});
}
});
};
// fork workers.
REPEAT(cpuCount, function() {
fork();
});
cluster.on('exit', function(worker, code, signal) {
SHOW_ERROR('[UJS-CPU_CLUSTERING] WORKER #' + worker.id + ' died. (' + (signal !== undefined ? signal : code) + '). restarting...');
fork();
});
});
}
// when worker
else {
RUN(function() {
var
// method map
methodMap = {},
// run methods.
runMethods = function(methodName, data) {
var
// methods
methods = methodMap[methodName];
if (methods !== undefined) {
EACH(methods, function(method) {
// run method.
method(data);
});
}
},
// on.
on,
// off.
off,
// broadcast.
broadcast,
// get pids.
getPids;
workerId = cluster.worker.id;
// receive data.
process.on('message', function(paramsStr) {
var
// params
params = PARSE_STR(paramsStr);
if (params !== undefined) {
runMethods(params.methodName, params.data);
}
});
m.on = on = function(methodName, method) {
var
// methods
methods = methodMap[methodName];
if (methods === undefined) {
methods = methodMap[methodName] = [];
}
methods.push(method);
};
// save shared value.
on('__SHARED_STORE_SAVE', SHARED_STORE.save);
// remove shared value.
on('__SHARED_STORE_REMOVE', SHARED_STORE.remove);
// clear shared store.
on('__SHARED_STORE_CLEAR', SHARED_STORE.clear);
// save cpu shared value.
on('__CPU_SHARED_STORE_SAVE', CPU_SHARED_STORE.save);
// remove cpu shared value.
on('__CPU_SHARED_STORE_REMOVE', CPU_SHARED_STORE.remove);
// clear cpu shared store.
on('__CPU_SHARED_STORE_CLEAR', CPU_SHARED_STORE.clear);
// save shared data.
on('__SHARED_DB_SAVE', SHARED_DB.save);
// update shared data.
on('__SHARED_DB_UPDATE', SHARED_DB.update);
// remove shared data.
on('__SHARED_DB_REMOVE', SHARED_DB.remove);
// clear shared db.
on('__SHARED_DB_CLEAR', SHARED_DB.clear);
// save cpu shared data.
on('__CPU_SHARED_DB_SAVE', CPU_SHARED_DB.save);
// update cpu shared data.
on('__CPU_SHARED_DB_UPDATE', CPU_SHARED_DB.update);
// remove cpu shared data.
on('__CPU_SHARED_DB_REMOVE', CPU_SHARED_DB.remove);
// clear cpu shared db.
on('__CPU_SHARED_DB_CLEAR', CPU_SHARED_DB.clear);
m.off = off = function(methodName) {
delete methodMap[methodName];
};
m.broadcast = broadcast = function(params) {
//REQUIRED: params
//REQUIRED: params.methodName
//REQUIRED: params.data
process.send(STRINGIFY(params));
};
on('__GET_PIDS', function(data) {
if (m.__GET_PIDS_CALLBACK !== undefined) {
m.__GET_PIDS_CALLBACK(data);
}
});
m.getPids = getPids = function(callback) {
process.send('__GET_PIDS');
m.__GET_PIDS_CALLBACK = callback;
};
work();
console.log(CONSOLE_GREEN('[UJS-CPU_CLUSTERING] RUNNING WORKER... (ID:' + workerId + ')'));
});
}
}
};
});
| SRC/NODE/CLUSTERING/CPU_CLUSTERING.js | /*
* CPU clustering work.
*/
global.CPU_CLUSTERING = METHOD(function(m) {
'use strict';
var
//IMPORT: cluster
cluster = require('cluster'),
// cpu count
cpuCount = require('os').cpus().length,
// worker id
workerId = 1,
// get worker id.
getWorkerId;
cluster.schedulingPolicy = cluster.SCHED_RR;
m.getWorkerId = getWorkerId = function() {
return workerId;
};
return {
run : function(work) {
//REQUIRED: work
// when master
if (cluster.isMaster) {
RUN(function() {
var
// pids
pids = {},
// fork.
fork = function() {
var
// new worker
newWorker = cluster.fork();
pids[newWorker.id] = newWorker.process.pid;
// receive data from new worker.
newWorker.on('message', function(data) {
if (data === '__GET_PIDS') {
newWorker.send(STRINGIFY({
methodName : '__GET_PIDS',
data : pids
}));
}
else {
// send data to all workers except new worker.
EACH(cluster.workers, function(worker) {
if (worker !== newWorker) {
worker.send(data);
}
});
}
});
};
// fork workers.
REPEAT(cpuCount, function() {
fork();
});
cluster.on('exit', function(worker, code, signal) {
SHOW_ERROR('[UJS-CPU_CLUSTERING] WORKER #' + worker.id + ' died. (' + (signal !== undefined ? signal : code) + '). restarting...');
fork();
});
});
}
// when worker
else {
RUN(function() {
var
// method map
methodMap = {},
// run methods.
runMethods = function(methodName, data) {
var
// methods
methods = methodMap[methodName];
if (methods !== undefined) {
EACH(methods, function(method) {
// run method.
method(data);
});
}
},
// on.
on,
// off.
off,
// broadcast.
broadcast,
// get all shared store storages.
getAllSharedStoreStorages,
// get all shared db storages.
getAllSharedDBStorages,
// get pids.
getPids;
workerId = cluster.worker.id;
// receive data.
process.on('message', function(paramsStr) {
var
// params
params = PARSE_STR(paramsStr);
if (params !== undefined) {
runMethods(params.methodName, params.data);
}
});
m.on = on = function(methodName, method) {
var
// methods
methods = methodMap[methodName];
if (methods === undefined) {
methods = methodMap[methodName] = [];
}
methods.push(method);
};
// save shared value.
on('__SHARED_STORE_SAVE', SHARED_STORE.save);
// remove shared value.
on('__SHARED_STORE_REMOVE', SHARED_STORE.remove);
// clear shared store.
on('__SHARED_STORE_CLEAR', SHARED_STORE.clear);
// save cpu shared value.
on('__CPU_SHARED_STORE_SAVE', CPU_SHARED_STORE.save);
// remove cpu shared value.
on('__CPU_SHARED_STORE_REMOVE', CPU_SHARED_STORE.remove);
// clear cpu shared store.
on('__CPU_SHARED_STORE_CLEAR', CPU_SHARED_STORE.clear);
// save shared data.
on('__SHARED_DB_SAVE', SHARED_DB.save);
// update shared data.
on('__SHARED_DB_UPDATE', SHARED_DB.update);
// remove shared data.
on('__SHARED_DB_REMOVE', SHARED_DB.remove);
// clear shared db.
on('__SHARED_DB_CLEAR', SHARED_DB.clear);
// save cpu shared data.
on('__CPU_SHARED_DB_SAVE', CPU_SHARED_DB.save);
// update cpu shared data.
on('__CPU_SHARED_DB_UPDATE', CPU_SHARED_DB.update);
// remove cpu shared data.
on('__CPU_SHARED_DB_REMOVE', CPU_SHARED_DB.remove);
// clear cpu shared db.
on('__CPU_SHARED_DB_CLEAR', CPU_SHARED_DB.clear);
m.off = off = function(methodName) {
delete methodMap[methodName];
};
m.broadcast = broadcast = function(params) {
//REQUIRED: params
//REQUIRED: params.methodName
//REQUIRED: params.data
process.send(STRINGIFY(params));
};
on('__GET_SHARED_STORE_STORAGES', function(requestWorkerId) {
broadcast({
methodName : '__SEND_SHARED_STORE_STORAGES',
data : {
requestWorkerId : requestWorkerId,
storages : SHARED_STORE.getStorages(),
workerId : getWorkerId()
}
});
});
on('__SEND_SHARED_STORE_STORAGES', function(data) {
if (data.requestWorkerId === getWorkerId()) {
if (m.__GET_SHARED_STORE_STORAGES_CALLBACK !== undefined) {
m.__GET_SHARED_STORE_STORAGES_CALLBACK(data);
}
}
});
m.getAllSharedStoreStorages = getAllSharedStoreStorages = function(callback) {
var
// all shared store storages
allSharedStoreStorages = {};
allSharedStoreStorages[getWorkerId()] = SHARED_STORE.getStorages();
broadcast({
methodName : '__GET_SHARED_STORE_STORAGES',
data : getWorkerId()
});
m.__GET_SHARED_STORE_STORAGES_CALLBACK = function(data) {
allSharedStoreStorages[data.workerId] = data.storages;
if (COUNT_PROPERTIES(allSharedStoreStorages) === cpuCount) {
callback(allSharedStoreStorages);
}
};
};
on('__GET_SHARED_DB_STORAGES', function(requestWorkerId) {
broadcast({
methodName : '__SEND_SHARED_DB_STORAGES',
data : {
requestWorkerId : requestWorkerId,
storages : SHARED_DB.getStorages(),
workerId : getWorkerId()
}
});
});
on('__SEND_SHARED_DB_STORAGES', function(data) {
if (data.requestWorkerId === getWorkerId()) {
if (m.__GET_SHARED_DB_STORAGES_CALLBACK !== undefined) {
m.__GET_SHARED_DB_STORAGES_CALLBACK(data);
}
}
});
m.getAllSharedDBStorages = getAllSharedDBStorages = function(callback) {
var
// all shared db storages
allSharedDBStorages = {};
allSharedDBStorages[getWorkerId()] = SHARED_DB.getStorages();
broadcast({
methodName : '__GET_SHARED_DB_STORAGES',
data : getWorkerId()
});
m.__GET_SHARED_DB_STORAGES_CALLBACK = function(data) {
allSharedDBStorages[data.workerId] = data.storages;
if (COUNT_PROPERTIES(allSharedDBStorages) === cpuCount) {
callback(allSharedDBStorages);
}
};
};
on('__GET_PIDS', function(data) {
if (m.__GET_PIDS_CALLBACK !== undefined) {
m.__GET_PIDS_CALLBACK(data);
}
});
m.getPids = getPids = function(callback) {
process.send('__GET_PIDS');
m.__GET_PIDS_CALLBACK = callback;
};
work();
console.log(CONSOLE_GREEN('[UJS-CPU_CLUSTERING] RUNNING WORKER... (ID:' + workerId + ')'));
});
}
}
};
});
| no message
| SRC/NODE/CLUSTERING/CPU_CLUSTERING.js | no message | <ide><path>RC/NODE/CLUSTERING/CPU_CLUSTERING.js
<ide> // broadcast.
<ide> broadcast,
<ide>
<del> // get all shared store storages.
<del> getAllSharedStoreStorages,
<del>
<del> // get all shared db storages.
<del> getAllSharedDBStorages,
<del>
<ide> // get pids.
<ide> getPids;
<ide>
<ide> //REQUIRED: params.data
<ide>
<ide> process.send(STRINGIFY(params));
<del> };
<del>
<del> on('__GET_SHARED_STORE_STORAGES', function(requestWorkerId) {
<del> broadcast({
<del> methodName : '__SEND_SHARED_STORE_STORAGES',
<del> data : {
<del> requestWorkerId : requestWorkerId,
<del> storages : SHARED_STORE.getStorages(),
<del> workerId : getWorkerId()
<del> }
<del> });
<del> });
<del>
<del> on('__SEND_SHARED_STORE_STORAGES', function(data) {
<del> if (data.requestWorkerId === getWorkerId()) {
<del> if (m.__GET_SHARED_STORE_STORAGES_CALLBACK !== undefined) {
<del> m.__GET_SHARED_STORE_STORAGES_CALLBACK(data);
<del> }
<del> }
<del> });
<del>
<del> m.getAllSharedStoreStorages = getAllSharedStoreStorages = function(callback) {
<del>
<del> var
<del> // all shared store storages
<del> allSharedStoreStorages = {};
<del>
<del> allSharedStoreStorages[getWorkerId()] = SHARED_STORE.getStorages();
<del>
<del> broadcast({
<del> methodName : '__GET_SHARED_STORE_STORAGES',
<del> data : getWorkerId()
<del> });
<del>
<del> m.__GET_SHARED_STORE_STORAGES_CALLBACK = function(data) {
<del>
<del> allSharedStoreStorages[data.workerId] = data.storages;
<del>
<del> if (COUNT_PROPERTIES(allSharedStoreStorages) === cpuCount) {
<del> callback(allSharedStoreStorages);
<del> }
<del> };
<del> };
<del>
<del> on('__GET_SHARED_DB_STORAGES', function(requestWorkerId) {
<del> broadcast({
<del> methodName : '__SEND_SHARED_DB_STORAGES',
<del> data : {
<del> requestWorkerId : requestWorkerId,
<del> storages : SHARED_DB.getStorages(),
<del> workerId : getWorkerId()
<del> }
<del> });
<del> });
<del>
<del> on('__SEND_SHARED_DB_STORAGES', function(data) {
<del> if (data.requestWorkerId === getWorkerId()) {
<del> if (m.__GET_SHARED_DB_STORAGES_CALLBACK !== undefined) {
<del> m.__GET_SHARED_DB_STORAGES_CALLBACK(data);
<del> }
<del> }
<del> });
<del>
<del> m.getAllSharedDBStorages = getAllSharedDBStorages = function(callback) {
<del>
<del> var
<del> // all shared db storages
<del> allSharedDBStorages = {};
<del>
<del> allSharedDBStorages[getWorkerId()] = SHARED_DB.getStorages();
<del>
<del> broadcast({
<del> methodName : '__GET_SHARED_DB_STORAGES',
<del> data : getWorkerId()
<del> });
<del>
<del> m.__GET_SHARED_DB_STORAGES_CALLBACK = function(data) {
<del>
<del> allSharedDBStorages[data.workerId] = data.storages;
<del>
<del> if (COUNT_PROPERTIES(allSharedDBStorages) === cpuCount) {
<del> callback(allSharedDBStorages);
<del> }
<del> };
<ide> };
<ide>
<ide> on('__GET_PIDS', function(data) { |
|
Java | apache-2.0 | f2690cbcff59b0b6aadd9f759ba6047db8f219ef | 0 | SacredScriptureFoundation/sacredscripture | /*
* Copyright (c) 2014 Sacred Scripture Foundation.
* "All scripture is given by inspiration of God, and is profitable for
* doctrine, for reproof, for correction, for instruction in righteousness:
* That the man of God may be perfect, throughly furnished unto all good
* works." (2 Tim 3:16-17)
*
* 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.sacredscripture.platform.impl.bible.batch;
import org.sacredscripture.platform.bible.service.AddBookTypeGroupRequest;
import org.sacredscripture.platform.bible.service.AddBookTypeRequest;
import org.sacredscripture.platform.bible.service.BibleMaintenanceService;
import org.sacredscripture.platform.xml.canon.XmlBookType;
import org.sacredscripture.platform.xml.canon.XmlCanon;
import org.sacredscripture.platform.xml.canon.XmlGroupType;
import java.io.File;
import java.util.List;
import java.util.Properties;
import javax.batch.api.AbstractBatchlet;
import javax.batch.runtime.BatchRuntime;
import javax.batch.runtime.context.JobContext;
import javax.ejb.EJB;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.inject.Named;
import javax.xml.bind.JAXBContext;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
* This class is the batchlet that populates the canon from XML.
*
* @author Paul Benedict
* @see XmlCanon
* @since Sacred Scripture Platform 1.0
*/
@Dependent
@Named("LoadCanonBatchlet")
public class LoadCanonBatchlet extends AbstractBatchlet {
/**
* Batch parameter specifying the XML document path.
*/
public static final String PARAMETER_DOC_PATH = "docPath";
private static final Logger log = LogManager.getLogger(LoadCanonBatchlet.class);
private static final String LOG_MSG_CREATING_BOOK = "Creating book \"%s\" in group \"%s\"";
private static final String LOG_MSG_CREATING_GROUP = "Creating group \"%s\" under parent \"%s\"";
@Inject
JobContext jobContext;
@EJB
private BibleMaintenanceService service;
private void createBookType(XmlBookType book, XmlGroupType group) {
log.debug(String.format(LOG_MSG_CREATING_BOOK, book.getCode().value(), group.getCode()));
AddBookTypeRequest req = new AddBookTypeRequest();
req.setCode(book.getCode().value());
req.setGroupCode(group.getCode());
service.add(req);
}
private void createGroup(XmlGroupType group, String parentCode) {
log.debug(String.format(LOG_MSG_CREATING_GROUP, group.getCode(), parentCode));
AddBookTypeGroupRequest req = new AddBookTypeGroupRequest();
req.setCode(group.getCode());
req.setParentCode(parentCode);
service.add(req);
}
private void createGroups(List<XmlGroupType> groups, String parentCode) {
for (XmlGroupType group : groups) {
createGroup(group, parentCode);
createGroups(group.getGroup(), group.getCode());
for (XmlBookType book : group.getBook()) {
createBookType(book, group);
}
}
}
@Override
public String process() throws Exception {
Properties params = BatchRuntime.getJobOperator().getParameters(jobContext.getExecutionId());
File f = new File(params.getProperty(PARAMETER_DOC_PATH));
JAXBContext jc = JAXBContext.newInstance(XmlCanon.class);
XmlCanon canon = (XmlCanon) jc.createUnmarshaller().unmarshal(f);
createGroups(canon.getGroup(), null);
return "SUCCESS";
}
}
| batch/batch-ejb/src/main/java/org/sacredscripture/platform/impl/bible/batch/LoadCanonBatchlet.java | /*
* Copyright (c) 2014 Sacred Scripture Foundation.
* "All scripture is given by inspiration of God, and is profitable for
* doctrine, for reproof, for correction, for instruction in righteousness:
* That the man of God may be perfect, throughly furnished unto all good
* works." (2 Tim 3:16-17)
*
* 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.sacredscripture.platform.impl.bible.batch;
import org.sacredscripture.platform.bible.service.AddBookTypeGroupRequest;
import org.sacredscripture.platform.bible.service.AddBookTypeRequest;
import org.sacredscripture.platform.bible.service.BibleMaintenanceService;
import org.sacredscripture.platform.xml.canon.XmlBookType;
import org.sacredscripture.platform.xml.canon.XmlCanon;
import org.sacredscripture.platform.xml.canon.XmlGroupType;
import java.io.File;
import java.util.List;
import java.util.Properties;
import javax.batch.api.AbstractBatchlet;
import javax.batch.runtime.BatchRuntime;
import javax.batch.runtime.context.JobContext;
import javax.ejb.EJB;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.inject.Named;
import javax.xml.bind.JAXBContext;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
@Dependent
@Named("LoadCanonBatchlet")
public class LoadCanonBatchlet extends AbstractBatchlet {
/**
* Batch parameter specifying the XML document path.
*/
public static final String PARAMETER_DOC_PATH = "docPath";
private static final Logger log = LogManager.getLogger(LoadCanonBatchlet.class);
private static final String LOG_MSG_CREATING_BOOK = "Creating book \"%s\" in group \"%s\"";
private static final String LOG_MSG_CREATING_GROUP = "Creating group \"%s\" under parent \"%s\"";
@Inject
JobContext jobContext;
@EJB
private BibleMaintenanceService service;
private void createBookType(XmlBookType book, XmlGroupType group) {
log.debug(String.format(LOG_MSG_CREATING_BOOK, book.getCode().value(), group.getCode()));
AddBookTypeRequest req = new AddBookTypeRequest();
req.setCode(book.getCode().value());
req.setGroupCode(group.getCode());
service.add(req);
}
private void createGroup(XmlGroupType group, String parentCode) {
log.debug(String.format(LOG_MSG_CREATING_GROUP, group.getCode(), parentCode));
AddBookTypeGroupRequest req = new AddBookTypeGroupRequest();
req.setCode(group.getCode());
req.setParentCode(parentCode);
service.add(req);
}
private void createGroups(List<XmlGroupType> groups, String parentCode) {
for (XmlGroupType group : groups) {
createGroup(group, parentCode);
createGroups(group.getGroup(), group.getCode());
for (XmlBookType book : group.getBook()) {
createBookType(book, group);
}
}
}
@Override
public String process() throws Exception {
Properties params = BatchRuntime.getJobOperator().getParameters(jobContext.getExecutionId());
File f = new File(params.getProperty(PARAMETER_DOC_PATH));
JAXBContext jc = JAXBContext.newInstance(XmlCanon.class);
XmlCanon canon = (XmlCanon) jc.createUnmarshaller().unmarshal(f);
createGroups(canon.getGroup(), null);
return "SUCCESS";
}
}
| Add javadoc | batch/batch-ejb/src/main/java/org/sacredscripture/platform/impl/bible/batch/LoadCanonBatchlet.java | Add javadoc | <ide><path>atch/batch-ejb/src/main/java/org/sacredscripture/platform/impl/bible/batch/LoadCanonBatchlet.java
<ide> import org.apache.log4j.LogManager;
<ide> import org.apache.log4j.Logger;
<ide>
<add>/**
<add> * This class is the batchlet that populates the canon from XML.
<add> *
<add> * @author Paul Benedict
<add> * @see XmlCanon
<add> * @since Sacred Scripture Platform 1.0
<add> */
<ide> @Dependent
<ide> @Named("LoadCanonBatchlet")
<ide> public class LoadCanonBatchlet extends AbstractBatchlet { |
|
Java | agpl-3.0 | f54c360c2697b2b6307f962333a8f9313a74f3bf | 0 | battlecode/battlecode-server,battlecode/battlecode-server | package battlecode.analysis;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.*;
import java.util.zip.GZIPInputStream;
import javax.swing.JFileChooser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import battlecode.common.MapLocation;
import battlecode.common.RobotType;
import battlecode.engine.signal.Signal;
import battlecode.serial.*;
import battlecode.server.proxy.Proxy;
import battlecode.server.proxy.ProxyFactory;
import battlecode.server.proxy.XStreamProxy;
import battlecode.world.GameMap;
import battlecode.world.signal.*;
public class AwesomenessAnalyzer {
private static final float TOWER_AWESOMENESS = 500;
private static final float ARCHON_DEATH_AWESOMENESS = 250;
private static final float ARCHON_AWESOMENESS = 100;
private static final float DEATH_AWESOMENESS = 50;
private static final float ATTACK_AWESOMENESS = 10;
private static final float SPAWN_AWESOMENESS = 5;
private static final float EQUIP_AWESOMENESS = 1;
private static final float EVOLVE_AWESOMENESS = 5;
private static final float ACTIVE_AWESOMENESS = 1;
private static final float ARCHON_AWESOMENESS_MULTIPLIER = 2.f;
private static final float WOUT_AWESOMENESS_MULTIPLIER = .3f;
private static final float RADIUS_IN_STDEVS = 1.4f;
private String filename;
private ArrayList<GameData> games;
private static Options options() {
Options options = new Options();
options.addOption("directory", true, "run mode");
return options;
}
public AwesomenessAnalyzer(String filename) {
this.filename = filename;
games = new ArrayList<GameData>();
}
private class Event {
public float awesomeness;
public float x;
public float y;
public Event(float awesomeness, MapLocation location) {
this.awesomeness = awesomeness;
x = location.x + 0.5f; // Center of square
y = location.y + 0.5f; // Center of square
}
}
private class RobotStat {
public static final int COUNTDOWN = 20;
public MapLocation location;
public int idleCountdown;
public float robotAwesomeness;
public RobotType type;
public RobotStat(MapLocation location, RobotType type) {
this.location = location;
idleCountdown = COUNTDOWN;
transform(type);
}
public void transform(RobotType type) {
this.type=type;
if(type.equals(RobotType.ARCHON))
robotAwesomeness=ARCHON_AWESOMENESS_MULTIPLIER;
//else if(type.equals(RobotType.WOUT))
// robotAwesomeness=WOUT_AWESOMENESS_MULTIPLIER;
else
robotAwesomeness=1.f;
}
public void resetCountDown() {
idleCountdown = COUNTDOWN;
}
}
private class GameData {
public ArrayList<Object> data;
public ArrayList<AwesomenessSignal> stats;
public float totalAwesomeness;
// Maps robotID to location
private HashMap<Integer, RobotStat> robots;
private float centerX;
private float centerY;
private float radius;
public GameData() {
data = new ArrayList<Object>();
stats = new ArrayList<AwesomenessSignal>();
robots = new HashMap<Integer, RobotStat>();
}
public void addData(Object o) {
data.add(o);
if (o instanceof MatchHeader) {
visitHeader((MatchHeader)o);
System.out.println("Center: " +centerX+" "+centerY+" "+radius);
} else if (o instanceof RoundDelta) {
stats.add(visitRound((RoundDelta)o));
}
}
public void postProcess() {
final int WAKE_DELAY = 400;
// Wait some rounds before moving camera
for (int i = 0; i < WAKE_DELAY && i < stats.size(); i++) {
AwesomenessSignal s = stats.get(i);
s.centerX = (i * s.centerX + (WAKE_DELAY - i) * centerX) / WAKE_DELAY;
s.centerY = (i * s.centerY + (WAKE_DELAY - i) * centerY) / WAKE_DELAY;
s.radius = (i * s.radius + (WAKE_DELAY - i) * radius) / WAKE_DELAY;
}
}
public void reduceJitter(int begin, int end) {
// Ramer-Douglas-Peucker curve simplification algorithm
AwesomenessSignal first = stats.get(begin);
AwesomenessSignal last = stats.get(end);
int farthest=-1;
double dist, farthestDist=10.;
int i;
for(i=begin+1;i<end;i++) {
double x=(first.centerX*(end-i)+last.centerX*(i-begin))/(end-begin);
double y=(first.centerY*(end-i)+last.centerY*(i-begin))/(end-begin);
double r=(first.radius*(end-i)+last.radius*(i-begin))/(end-begin);
AwesomenessSignal s = stats.get(i);
x-=s.centerX;
y-=s.centerY;
r-=s.radius;
// we care more about getting the right camera
// angle when there is more stuff going on
dist=s.totalAwesomeness*s.totalAwesomeness*(x*x+y*y+r*r/2.)/(s.radius*s.radius);
//System.out.println(dist);
if(dist>farthestDist) {
farthestDist=dist;
farthest=i;
}
}
//System.out.println("reduceJitter "+begin+"-"+end+" farthestDist "+farthestDist);
if(farthest==-1) {
for(i=begin+1;i<end;i++) {
AwesomenessSignal s = stats.get(i);
s.centerX=(first.centerX*(end-i)+last.centerX*(i-begin))/(end-begin);
s.centerY=(first.centerY*(end-i)+last.centerY*(i-begin))/(end-begin);
s.radius=(first.radius*(end-i)+last.radius*(i-begin))/(end-begin);
}
}
else {
reduceJitter(begin,farthest);
reduceJitter(farthest,end);
}
}
public void smoothStats() {
// exponential smoothing
float [] old1 = new float[stats.size()];
float [] oldX = new float[stats.size()];
float [] oldY = new float[stats.size()];
float [] oldR2 = new float[stats.size()];
float [] new1 = new float[stats.size()];
float [] newX = new float[stats.size()];
float [] newY = new float[stats.size()];
float [] newR2 = new float[stats.size()];
float [] tmp;
float xOffset = stats.get(0).centerX;
float yOffset = stats.get(0).centerY;
// convert from awesomeness stats to sums
final float decay = .95f;
final float norm = (1.f-decay)/2.f;
int i, j;
for(i=0;i<stats.size();i++) {
AwesomenessSignal s = stats.get(i);
old1[i] = s.totalAwesomeness;
float dx = s.centerX-xOffset;
float dy = s.centerY-yOffset;
oldX[i] = dx * s.totalAwesomeness;
oldY[i] = dy * s.totalAwesomeness;
float stdev = s.radius/RADIUS_IN_STDEVS;
oldR2[i] = s.totalAwesomeness * (stdev * stdev + dx * dx + dy * dy);
}
// If we do n passes, then we get a convolution function
// that has continuous n-1st derivative
for(j=0;j<2;j++) {
float s1=0.f, sx=0.f, sy=0.f, sr2=0.f;
for(i=0;i<stats.size();i++) {
s1+=old1[i]*norm;
sx+=oldX[i]*norm;
sy+=oldY[i]*norm;
sr2+=oldR2[i]*norm;
new1[i]=s1;
newX[i]=sx;
newY[i]=sy;
newR2[i]=sr2;
s1*=.95;
sx*=.95;
sy*=.95;
sr2*=.95;
}
s1=0.f; sx=0.f; sy=0.f; sr2=0.f;
for(i=stats.size()-1;i>=0;i--) {
s1+=old1[i]*norm;
sx+=oldX[i]*norm;
sy+=oldY[i]*norm;
sr2+=oldR2[i]*norm;
new1[i]+=s1;
newX[i]+=sx;
newY[i]+=sy;
newR2[i]+=sr2;
s1*=.95;
sx*=.95;
sy*=.95;
sr2*=.95;
}
tmp = old1;
old1 = new1;
new1 = tmp;
tmp = oldX;
oldX = newX;
newX = tmp;
tmp = oldY;
oldY = newY;
newY = tmp;
tmp = oldR2;
oldR2 = newR2;
newR2 = tmp;
}
// now back to awesomeness
for(i=0;i<stats.size();i++) {
AwesomenessSignal s = stats.get(i);
s.totalAwesomeness = old1[i];
s.centerX = oldX[i]/old1[i]+xOffset;
s.centerY = oldY[i]/old1[i]+yOffset;
//System.out.println(old1[i]+" "+oldX[i]+" "+oldY[i]+" "+oldR2[i]);
s.radius=RADIUS_IN_STDEVS*(float)Math.sqrt((oldR2[i]-(oldX[i]*oldX[i]+oldY[i]*oldY[i])/old1[i])/old1[i]);
}
/*
for(i=0;i<stats.size();i++) {
System.out.println(i+" "+stats.get(i).radius);
}
*/
reduceJitter(0,stats.size()-1);
/*
for(i=0;i<stats.size();i++) {
System.out.println(i+" "+stats.get(i).radius);
}
*/
/*
float total = 0.0f;
float min = Float.MAX_VALUE;
float max = Float.MIN_VALUE;
int awesomeRound = 0;
final int LOOK_BACK = 5;
final int LOOK_FORWARD = 10;
final AwesomenessSignal[] rounds = new AwesomenessSignal[stats.size()];
stats.toArray(rounds);
for (int i = 0; i < rounds.length; i++) {
int n = 0;
float sum = 0;
float centerXSum = 0;
float centerYSum = 0;
float radiusSum = 0;
// Sum elements before i
for (int j = i - LOOK_BACK; j < i; j++) {
if (j >= 0) {
n++;
AwesomenessSignal s = rounds[j];
float awesomeness = s.totalAwesomeness;
sum += awesomeness;
centerXSum += s.centerX * awesomeness;
centerYSum += s.centerY * awesomeness;
radiusSum += s.radius * awesomeness;
}
}
// Sum elements after i
for (int j = i + 1; j <= i + LOOK_FORWARD && j < rounds.length; j++) {
n++;
AwesomenessSignal s = rounds[j];
float awesomeness = s.totalAwesomeness;
sum += awesomeness;
centerXSum += s.centerX * awesomeness;
centerYSum += s.centerY * awesomeness;
radiusSum += s.radius * awesomeness;
}
// Weight current value higher than others
AwesomenessSignal s = rounds[i];
float newAwesomeness = (sum + s.totalAwesomeness * n) / (2 * n);
s.updateAwesomeness(newAwesomeness);
s.centerX = (centerXSum + s.centerX * sum) / (2 * sum);
s.centerY = (centerYSum + s.centerY * sum) / (2 * sum);
s.radius = (radiusSum + s.radius * sum) / (2 * sum);
total += newAwesomeness;
if (newAwesomeness < min)
min = newAwesomeness;
if (newAwesomeness > max) {
max = newAwesomeness;
awesomeRound = i;
}
}
//System.out.println("Smooth: " + total + " " + totalAwesomeness + " " + min + " " + max);
//System.out.println("AwesomeRound: " + (awesomeRound + 1));
for(int i=0;i<stats.size();i++) {
System.out.println(i+" "+stats.get(i).radius);
}
*/
}
public List<Object> getOutput() {
// Copy data
ArrayList<Object> output = new ArrayList<Object>(data);
// Insert awesomeness stats into RoundDelta
int statNum = 0;
for (ListIterator<Object> iter = output.listIterator(); iter.hasNext();) {
Object round = iter.next();
if (round instanceof RoundDelta) {
RoundDelta rd = (RoundDelta)round;
//iter.add(stats.get(statNum++));
//Signal[] oldSignals = rd.getSignals();
Signal[] oldSignals = stripIndicatorStrings(rd.getSignals());
final int len = oldSignals.length;
Signal[] newSignals = new Signal[len + 1];
System.arraycopy(oldSignals, 0, newSignals, 1, len);
newSignals[0] = stats.get(statNum++);
rd.setSignals(newSignals);
}
}
return output;
}
public void renormalize() {
final AwesomenessSignal[] rounds = new AwesomenessSignal[stats.size()];
stats.toArray(rounds);
// Calculate average awesomeness
float ave = 0.0f;
for (int i = 0; i < rounds.length; i++) {
ave += rounds[i].totalAwesomeness;
}
ave = ave / rounds.length;
// Renormalize
for (int i = 0; i < rounds.length; i++) {
rounds[i].renormalize(ave);
}
System.out.println("Renormalizing: " + ave);
}
public String toString() {
return "AwesomenessSignal: ave=" + (totalAwesomeness / stats.size());
}
private Signal[] stripIndicatorStrings(Signal[] signals) {
ArrayList<Signal> strippedSignals = new ArrayList<Signal>(signals.length);
for (Signal s : signals)
if (!(s instanceof IndicatorStringSignal))
strippedSignals.add(s);
Signal[] out = new Signal[strippedSignals.size()];
strippedSignals.toArray(out);
return out;
}
private void visitHeader(MatchHeader header) {
final GameMap map = (GameMap)header.getMap();
final float halfWidth = ((float)map.getWidth()) / 2.0f;
final float halfHeight = ((float)map.getHeight()) / 2.0f;
final MapLocation origin = map.getMapOrigin();
centerX = origin.x + halfWidth;
centerY = origin.y + halfHeight;
radius = (float)Math.sqrt(halfWidth * halfWidth + halfHeight * halfHeight);
hulls = new ConvexHullData [] { new ConvexHullData(), new ConvexHullData() };
}
private class ConvexHullData {
public ConvexHullData() {}
public ConvexHullData(MapLocation [][] hulls) {
int i;
long dx, dy;
for(MapLocation [] hull : hulls) {
MapLocation oldLoc = hull[hull.length-1];
for(MapLocation newLoc : hull) {
dx = newLoc.x-oldLoc.x;
dy = newLoc.y-oldLoc.y;
area_2+=(newLoc.y+oldLoc.y)*dx;
sum_X_6+=-(newLoc.x*newLoc.x+newLoc.x*oldLoc.x+oldLoc.x*oldLoc.x)*dy;
sum_Y_6+=(newLoc.y*newLoc.y+newLoc.y*oldLoc.y+oldLoc.y*oldLoc.y)*dx;
oldLoc=newLoc;
}
}
}
// area times 2
public long area_2;
// integral of X times 6
public long sum_X_6;
// integral of Y times 6
public long sum_Y_6;
}
private ConvexHullData [] hulls;
private AwesomenessSignal visitRound(RoundDelta round) {
final Signal[] signals = round.getSignals();
ArrayList<Event> events = new ArrayList<Event>(signals.length);
RobotStat r;
// Add awesomeness for events
for (int i = 0; i < signals.length; i++) {
Signal signal = signals[i];
if (signal instanceof SpawnSignal) {
SpawnSignal s = (SpawnSignal)signal;
final int parent = s.getParentID();
if (parent != 0) {
robots.get(parent).resetCountDown();
}
MapLocation loc = s.getLoc();
if (loc != null) {
r = new RobotStat(loc,s.getType());
robots.put(s.getRobotID(), r);
events.add(new Event(SPAWN_AWESOMENESS*r.robotAwesomeness, loc));
}
} else if(signal instanceof MovementSignal) {
MovementSignal s = (MovementSignal)signal;
RobotStat robot = robots.get(s.getRobotID());
robot.resetCountDown();
robot.location = s.getNewLoc();
} else if(signal instanceof AttackSignal) {
AttackSignal s = (AttackSignal)signal;
r = robots.get(s.getRobotID());
r.resetCountDown();
MapLocation loc = s.getTargetLoc();
if (loc != null) {
events.add(new Event(ATTACK_AWESOMENESS*r.robotAwesomeness, s.getTargetLoc()));
}
} else if(signal instanceof DeathSignal) {
DeathSignal s = (DeathSignal)signal;
r = robots.remove(s.getObjectID());
float awesomeness = DEATH_AWESOMENESS*r.robotAwesomeness;
if (r.location != null) {
events.add(new Event(awesomeness, r.location));
}
}
}
// Add awesomeness for active robots
for (RobotStat robot : robots.values()) {
if (robot.idleCountdown-- > 0) {
events.add(new Event(ACTIVE_AWESOMENESS, robot.location));
}
}
// Calculate stats
float sum = 0;
float centerX = 0;
float centerY = 0;
float radius = 0;
if (events.size() <= 0) {
centerX = this.centerX;
centerY = this.centerY;
radius = this.radius;
} else {
// Calculate sum, center
for (Event event : events) {
sum += event.awesomeness;
centerX += event.x;
centerY += event.y;
}
centerX /= events.size();
centerY /= events.size();
// Calculate std dev
for (Event event: events) {
float diffX = event.x - centerX;
float diffY = event.y - centerY;
radius += event.awesomeness * (diffX * diffX + diffY * diffY);
}
radius = (float)Math.sqrt(radius / sum);
}
// Convert std dev to actual radius
radius *= RADIUS_IN_STDEVS;
// Enforce min radius
if (radius < 4) {
radius = 4;
//System.err.println("Warning: Std dev too small: " + radius);
}
// Enforce max radius
if (radius > this.radius) {
radius = this.radius;
}
//System.out.println(sum);
totalAwesomeness += sum;
return new AwesomenessSignal(sum, centerX, centerY, radius);
}
}
public void analyze() {
ObjectInputStream input = null;
try {
input = XStreamProxy.getXStream().createObjectInputStream(new GZIPInputStream(new FileInputStream(filename)));
} catch (Exception e) {
System.err.println("Error: couldn't open match file " + filename);
e.printStackTrace();
System.exit(-1);
}
System.out.println("Analyzing: " + filename);
try {
GameData gameData = new GameData();
games.add(gameData);
// Initialize first Game
Object o = input.readObject();
if (o == null || !(o instanceof MatchHeader)) {
System.err.println("Error: Missing MatchHeader.");
System.exit(-2);
}
gameData.addData(o);
while ((o = input.readObject()) != null) {
if (o instanceof MatchHeader) {
// New Game
gameData = new GameData();
games.add(gameData);
}
gameData.addData(o);
}
} catch(EOFException e) {
// Done parsing
} catch(IOException e) {
e.printStackTrace();
System.exit(-2);
} catch(ClassNotFoundException e) {
e.printStackTrace();
System.exit(-2);
}
for (GameData game : games) {
game.postProcess();
}
System.out.println(games);
}
public void smoothStats() {
for (GameData game: games) {
game.smoothStats();
}
}
public void dumpFile() {
try {
Proxy output = ProxyFactory.createProxyFromFile(filename + ".analyzed");
output.open();
for (GameData game : games) {
game.renormalize();
for (Object data : game.getOutput()) {
output.writeObject(data);
}
}
output.close();
} catch(IOException e) {
e.printStackTrace();
System.exit(-2);
}
}
public static void analyze(String file) {
AwesomenessAnalyzer analyzer = new AwesomenessAnalyzer(file);
analyzer.analyze();
analyzer.smoothStats();
//for (int i = 0; i < 16; i++)
// analyzer.smoothStats();
analyzer.dumpFile();
}
public static void main(String[] args) {
CommandLineParser parser = new GnuParser();
JFileChooser chooser = new JFileChooser();
CommandLine cmd = null;
try {
cmd = parser.parse(options(), args);
} catch (ParseException e) {
e.printStackTrace();
return;
}
String directory = cmd.getOptionValue("directory");
System.out.println("selected dir: " + directory);
if(cmd.hasOption("directory"))
{
File dir = new File(directory);
String[] children = dir.list();
if (children == null)
{
// Either dir does not exist or is not a directory
}
else {
for (int i=0; i<children.length; i++)
{ // Get filename of file or directory
String filename = children[i];
File file = new File(directory + "/" + filename);
//String type = chooser.getTypeDescription(file);
//System.out.println(directory + "/" + filename + " " + type);
if(filename.endsWith(".rms"))
//if(type.compareTo("RMS File")==0)
{
System.out.println("is an rms file");
analyze(file.getAbsolutePath());
}
}
}
}
else
{
if (args.length < 1) {
System.err.println("Error: No filenames specified in arguments");
System.exit(-1);
}
for (String arg: args) {
analyze(arg);
}
}
}
}
| src/main/battlecode/analysis/AwesomenessAnalyzer.java | package battlecode.analysis;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.*;
import java.util.zip.GZIPInputStream;
import javax.swing.JFileChooser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import battlecode.common.MapLocation;
import battlecode.common.RobotType;
import battlecode.engine.signal.Signal;
import battlecode.serial.*;
import battlecode.server.proxy.Proxy;
import battlecode.server.proxy.ProxyFactory;
import battlecode.server.proxy.XStreamProxy;
import battlecode.world.GameMap;
import battlecode.world.signal.*;
public class AwesomenessAnalyzer {
private static final float TOWER_AWESOMENESS = 500;
private static final float ARCHON_DEATH_AWESOMENESS = 250;
private static final float ARCHON_AWESOMENESS = 100;
private static final float DEATH_AWESOMENESS = 50;
private static final float ATTACK_AWESOMENESS = 10;
private static final float SPAWN_AWESOMENESS = 5;
private static final float EQUIP_AWESOMENESS = 1;
private static final float EVOLVE_AWESOMENESS = 5;
private static final float ACTIVE_AWESOMENESS = 1;
private static final float ARCHON_AWESOMENESS_MULTIPLIER = 2.f;
private static final float WOUT_AWESOMENESS_MULTIPLIER = .3f;
private static final float RADIUS_IN_STDEVS = 1.4f;
private String filename;
private ArrayList<GameData> games;
private static Options options() {
Options options = new Options();
options.addOption("directory", true, "run mode");
return options;
}
public AwesomenessAnalyzer(String filename) {
this.filename = filename;
games = new ArrayList<GameData>();
}
private class Event {
public float awesomeness;
public float x;
public float y;
public Event(float awesomeness, MapLocation location) {
this.awesomeness = awesomeness;
x = location.x + 0.5f; // Center of square
y = location.y + 0.5f; // Center of square
}
}
private class RobotStat {
public static final int COUNTDOWN = 20;
public MapLocation location;
public int idleCountdown;
public float robotAwesomeness;
public RobotType type;
public RobotStat(MapLocation location, RobotType type) {
this.location = location;
idleCountdown = COUNTDOWN;
transform(type);
}
public void transform(RobotType type) {
this.type=type;
if(type.equals(RobotType.ARCHON))
robotAwesomeness=ARCHON_AWESOMENESS_MULTIPLIER;
//else if(type.equals(RobotType.WOUT))
// robotAwesomeness=WOUT_AWESOMENESS_MULTIPLIER;
else
robotAwesomeness=1.f;
}
public void resetCountDown() {
idleCountdown = COUNTDOWN;
}
}
private class GameData {
public ArrayList<Object> data;
public ArrayList<AwesomenessSignal> stats;
public float totalAwesomeness;
// Maps robotID to location
private HashMap<Integer, RobotStat> robots;
private float centerX;
private float centerY;
private float radius;
public GameData() {
data = new ArrayList<Object>();
stats = new ArrayList<AwesomenessSignal>();
robots = new HashMap<Integer, RobotStat>();
}
public void addData(Object o) {
data.add(o);
if (o instanceof MatchHeader) {
visitHeader((MatchHeader)o);
System.out.println("Center: " +centerX+" "+centerY+" "+radius);
} else if (o instanceof RoundDelta) {
stats.add(visitRound((RoundDelta)o));
}
}
public void postProcess() {
final int WAKE_DELAY = 400;
// Wait some rounds before moving camera
for (int i = 0; i < WAKE_DELAY && i < stats.size(); i++) {
AwesomenessSignal s = stats.get(i);
s.centerX = (i * s.centerX + (WAKE_DELAY - i) * centerX) / WAKE_DELAY;
s.centerY = (i * s.centerY + (WAKE_DELAY - i) * centerY) / WAKE_DELAY;
s.radius = (i * s.radius + (WAKE_DELAY - i) * radius) / WAKE_DELAY;
}
}
public void reduceJitter(int begin, int end) {
// Ramer-Douglas-Peucker curve simplification algorithm
AwesomenessSignal first = stats.get(begin);
AwesomenessSignal last = stats.get(end);
int farthest=-1;
double dist, farthestDist=10.;
int i;
for(i=begin+1;i<end;i++) {
double x=(first.centerX*(end-i)+last.centerX*(i-begin))/(end-begin);
double y=(first.centerY*(end-i)+last.centerY*(i-begin))/(end-begin);
double r=(first.radius*(end-i)+last.radius*(i-begin))/(end-begin);
AwesomenessSignal s = stats.get(i);
x-=s.centerX;
y-=s.centerY;
r-=s.radius;
// we care more about getting the right camera
// angle when there is more stuff going on
dist=s.totalAwesomeness*s.totalAwesomeness*(x*x+y*y+r*r/2.)/(s.radius*s.radius);
//System.out.println(dist);
if(dist>farthestDist) {
farthestDist=dist;
farthest=i;
}
}
//System.out.println("reduceJitter "+begin+"-"+end+" farthestDist "+farthestDist);
if(farthest==-1) {
for(i=begin+1;i<end;i++) {
AwesomenessSignal s = stats.get(i);
s.centerX=(first.centerX*(end-i)+last.centerX*(i-begin))/(end-begin);
s.centerY=(first.centerY*(end-i)+last.centerY*(i-begin))/(end-begin);
s.radius=(first.radius*(end-i)+last.radius*(i-begin))/(end-begin);
}
}
else {
reduceJitter(begin,farthest);
reduceJitter(farthest,end);
}
}
public void smoothStats() {
// exponential smoothing
float [] old1 = new float[stats.size()];
float [] oldX = new float[stats.size()];
float [] oldY = new float[stats.size()];
float [] oldR2 = new float[stats.size()];
float [] new1 = new float[stats.size()];
float [] newX = new float[stats.size()];
float [] newY = new float[stats.size()];
float [] newR2 = new float[stats.size()];
float [] tmp;
float xOffset = stats.get(0).centerX;
float yOffset = stats.get(0).centerY;
// convert from awesomeness stats to sums
final float decay = .95f;
final float norm = (1.f-decay)/2.f;
int i, j;
for(i=0;i<stats.size();i++) {
AwesomenessSignal s = stats.get(i);
old1[i] = s.totalAwesomeness;
float dx = s.centerX-xOffset;
float dy = s.centerY-yOffset;
oldX[i] = dx * s.totalAwesomeness;
oldY[i] = dy * s.totalAwesomeness;
float stdev = s.radius/RADIUS_IN_STDEVS;
oldR2[i] = s.totalAwesomeness * (stdev * stdev + dx * dx + dy * dy);
}
// If we do n passes, then we get a convolution function
// that has continuous n-1st derivative
for(j=0;j<2;j++) {
float s1=0.f, sx=0.f, sy=0.f, sr2=0.f;
for(i=0;i<stats.size();i++) {
s1+=old1[i]*norm;
sx+=oldX[i]*norm;
sy+=oldY[i]*norm;
sr2+=oldR2[i]*norm;
new1[i]=s1;
newX[i]=sx;
newY[i]=sy;
newR2[i]=sr2;
s1*=.95;
sx*=.95;
sy*=.95;
sr2*=.95;
}
s1=0.f; sx=0.f; sy=0.f; sr2=0.f;
for(i=stats.size()-1;i>=0;i--) {
s1+=old1[i]*norm;
sx+=oldX[i]*norm;
sy+=oldY[i]*norm;
sr2+=oldR2[i]*norm;
new1[i]+=s1;
newX[i]+=sx;
newY[i]+=sy;
newR2[i]+=sr2;
s1*=.95;
sx*=.95;
sy*=.95;
sr2*=.95;
}
tmp = old1;
old1 = new1;
new1 = tmp;
tmp = oldX;
oldX = newX;
newX = tmp;
tmp = oldY;
oldY = newY;
newY = tmp;
tmp = oldR2;
oldR2 = newR2;
newR2 = tmp;
}
// now back to awesomeness
for(i=0;i<stats.size();i++) {
AwesomenessSignal s = stats.get(i);
s.totalAwesomeness = old1[i];
s.centerX = oldX[i]/old1[i]+xOffset;
s.centerY = oldY[i]/old1[i]+yOffset;
//System.out.println(old1[i]+" "+oldX[i]+" "+oldY[i]+" "+oldR2[i]);
s.radius=RADIUS_IN_STDEVS*(float)Math.sqrt((oldR2[i]-(oldX[i]*oldX[i]+oldY[i]*oldY[i])/old1[i])/old1[i]);
}
/*
for(i=0;i<stats.size();i++) {
System.out.println(i+" "+stats.get(i).radius);
}
*/
reduceJitter(0,stats.size()-1);
/*
for(i=0;i<stats.size();i++) {
System.out.println(i+" "+stats.get(i).radius);
}
*/
/*
float total = 0.0f;
float min = Float.MAX_VALUE;
float max = Float.MIN_VALUE;
int awesomeRound = 0;
final int LOOK_BACK = 5;
final int LOOK_FORWARD = 10;
final AwesomenessSignal[] rounds = new AwesomenessSignal[stats.size()];
stats.toArray(rounds);
for (int i = 0; i < rounds.length; i++) {
int n = 0;
float sum = 0;
float centerXSum = 0;
float centerYSum = 0;
float radiusSum = 0;
// Sum elements before i
for (int j = i - LOOK_BACK; j < i; j++) {
if (j >= 0) {
n++;
AwesomenessSignal s = rounds[j];
float awesomeness = s.totalAwesomeness;
sum += awesomeness;
centerXSum += s.centerX * awesomeness;
centerYSum += s.centerY * awesomeness;
radiusSum += s.radius * awesomeness;
}
}
// Sum elements after i
for (int j = i + 1; j <= i + LOOK_FORWARD && j < rounds.length; j++) {
n++;
AwesomenessSignal s = rounds[j];
float awesomeness = s.totalAwesomeness;
sum += awesomeness;
centerXSum += s.centerX * awesomeness;
centerYSum += s.centerY * awesomeness;
radiusSum += s.radius * awesomeness;
}
// Weight current value higher than others
AwesomenessSignal s = rounds[i];
float newAwesomeness = (sum + s.totalAwesomeness * n) / (2 * n);
s.updateAwesomeness(newAwesomeness);
s.centerX = (centerXSum + s.centerX * sum) / (2 * sum);
s.centerY = (centerYSum + s.centerY * sum) / (2 * sum);
s.radius = (radiusSum + s.radius * sum) / (2 * sum);
total += newAwesomeness;
if (newAwesomeness < min)
min = newAwesomeness;
if (newAwesomeness > max) {
max = newAwesomeness;
awesomeRound = i;
}
}
//System.out.println("Smooth: " + total + " " + totalAwesomeness + " " + min + " " + max);
//System.out.println("AwesomeRound: " + (awesomeRound + 1));
for(int i=0;i<stats.size();i++) {
System.out.println(i+" "+stats.get(i).radius);
}
*/
}
public List<Object> getOutput() {
// Copy data
ArrayList<Object> output = new ArrayList<Object>(data);
// Insert awesomeness stats into RoundDelta
int statNum = 0;
for (ListIterator<Object> iter = output.listIterator(); iter.hasNext();) {
Object round = iter.next();
if (round instanceof RoundDelta) {
RoundDelta rd = (RoundDelta)round;
//iter.add(stats.get(statNum++));
//Signal[] oldSignals = rd.getSignals();
Signal[] oldSignals = stripIndicatorStrings(rd.getSignals());
final int len = oldSignals.length;
Signal[] newSignals = new Signal[len + 1];
System.arraycopy(oldSignals, 0, newSignals, 1, len);
newSignals[0] = stats.get(statNum++);
rd.setSignals(newSignals);
}
}
return output;
}
public void renormalize() {
final AwesomenessSignal[] rounds = new AwesomenessSignal[stats.size()];
stats.toArray(rounds);
// Calculate average awesomeness
float ave = 0.0f;
for (int i = 0; i < rounds.length; i++) {
ave += rounds[i].totalAwesomeness;
}
ave = ave / rounds.length;
// Renormalize
for (int i = 0; i < rounds.length; i++) {
rounds[i].renormalize(ave);
}
System.out.println("Renormalizing: " + ave);
}
public String toString() {
return "AwesomenessSignal: ave=" + (totalAwesomeness / stats.size());
}
private Signal[] stripIndicatorStrings(Signal[] signals) {
ArrayList<Signal> strippedSignals = new ArrayList<Signal>(signals.length);
for (Signal s : signals)
if (!(s instanceof IndicatorStringSignal))
strippedSignals.add(s);
Signal[] out = new Signal[strippedSignals.size()];
strippedSignals.toArray(out);
return out;
}
private void visitHeader(MatchHeader header) {
final GameMap map = (GameMap)header.getMap();
final float halfWidth = ((float)map.getWidth()) / 2.0f;
final float halfHeight = ((float)map.getHeight()) / 2.0f;
final MapLocation origin = map.getMapOrigin();
centerX = origin.x + halfWidth;
centerY = origin.y + halfHeight;
radius = (float)Math.sqrt(halfWidth * halfWidth + halfHeight * halfHeight);
hulls = new ConvexHullData [] { new ConvexHullData(), new ConvexHullData() };
}
private class ConvexHullData {
public ConvexHullData() {}
public ConvexHullData(MapLocation [][] hulls) {
int i;
long dx, dy;
for(MapLocation [] hull : hulls) {
MapLocation oldLoc = hull[hull.length-1];
for(MapLocation newLoc : hull) {
dx = newLoc.x-oldLoc.x;
dy = newLoc.y-oldLoc.y;
area_2+=(newLoc.y+oldLoc.y)*dx;
sum_X_6+=-(newLoc.x*newLoc.x+newLoc.x*oldLoc.x+oldLoc.x*oldLoc.x)*dy;
sum_Y_6+=(newLoc.y*newLoc.y+newLoc.y*oldLoc.y+oldLoc.y*oldLoc.y)*dx;
oldLoc=newLoc;
}
}
}
// area times 2
public long area_2;
// integral of X times 6
public long sum_X_6;
// integral of Y times 6
public long sum_Y_6;
}
private ConvexHullData [] hulls;
private AwesomenessSignal visitRound(RoundDelta round) {
final Signal[] signals = round.getSignals();
ArrayList<Event> events = new ArrayList<Event>(signals.length);
RobotStat r;
// Add awesomeness for events
for (int i = 0; i < signals.length; i++) {
Signal signal = signals[i];
if (signal instanceof SpawnSignal) {
SpawnSignal s = (SpawnSignal)signal;
final int parent = s.getParentID();
if (parent != 0) {
robots.get(parent).resetCountDown();
}
MapLocation loc = s.getLoc();
r = new RobotStat(loc,s.getType());
robots.put(s.getRobotID(), r);
events.add(new Event(SPAWN_AWESOMENESS*r.robotAwesomeness, loc));
} else if(signal instanceof MovementSignal) {
MovementSignal s = (MovementSignal)signal;
RobotStat robot = robots.get(s.getRobotID());
robot.resetCountDown();
robot.location = s.getNewLoc();
} else if(signal instanceof AttackSignal) {
AttackSignal s = (AttackSignal)signal;
r = robots.get(s.getRobotID());
r.resetCountDown();
events.add(new Event(ATTACK_AWESOMENESS*r.robotAwesomeness, s.getTargetLoc()));
} else if(signal instanceof DeathSignal) {
DeathSignal s = (DeathSignal)signal;
r = robots.remove(s.getObjectID());
float awesomeness = DEATH_AWESOMENESS*r.robotAwesomeness;
events.add(new Event(awesomeness, r.location));
}
}
// Add awesomeness for active robots
for (RobotStat robot : robots.values()) {
if (robot.idleCountdown-- > 0) {
events.add(new Event(ACTIVE_AWESOMENESS, robot.location));
}
}
// Calculate stats
float sum = 0;
float centerX = 0;
float centerY = 0;
float radius = 0;
if (events.size() <= 0) {
centerX = this.centerX;
centerY = this.centerY;
radius = this.radius;
} else {
// Calculate sum, center
for (Event event : events) {
sum += event.awesomeness;
centerX += event.x;
centerY += event.y;
}
centerX /= events.size();
centerY /= events.size();
// Calculate std dev
for (Event event: events) {
float diffX = event.x - centerX;
float diffY = event.y - centerY;
radius += event.awesomeness * (diffX * diffX + diffY * diffY);
}
radius = (float)Math.sqrt(radius / sum);
}
// Convert std dev to actual radius
radius *= RADIUS_IN_STDEVS;
// Enforce min radius
if (radius < 4) {
radius = 4;
//System.err.println("Warning: Std dev too small: " + radius);
}
// Enforce max radius
if (radius > this.radius) {
radius = this.radius;
}
//System.out.println(sum);
totalAwesomeness += sum;
return new AwesomenessSignal(sum, centerX, centerY, radius);
}
}
public void analyze() {
ObjectInputStream input = null;
try {
input = XStreamProxy.getXStream().createObjectInputStream(new GZIPInputStream(new FileInputStream(filename)));
} catch (Exception e) {
System.err.println("Error: couldn't open match file " + filename);
e.printStackTrace();
System.exit(-1);
}
System.out.println("Analyzing: " + filename);
try {
GameData gameData = new GameData();
games.add(gameData);
// Initialize first Game
Object o = input.readObject();
if (o == null || !(o instanceof MatchHeader)) {
System.err.println("Error: Missing MatchHeader.");
System.exit(-2);
}
gameData.addData(o);
while ((o = input.readObject()) != null) {
if (o instanceof MatchHeader) {
// New Game
gameData = new GameData();
games.add(gameData);
}
gameData.addData(o);
}
} catch(EOFException e) {
// Done parsing
} catch(IOException e) {
e.printStackTrace();
System.exit(-2);
} catch(ClassNotFoundException e) {
e.printStackTrace();
System.exit(-2);
}
for (GameData game : games) {
game.postProcess();
}
System.out.println(games);
}
public void smoothStats() {
for (GameData game: games) {
game.smoothStats();
}
}
public void dumpFile() {
try {
Proxy output = ProxyFactory.createProxyFromFile(filename + ".analyzed");
output.open();
for (GameData game : games) {
game.renormalize();
for (Object data : game.getOutput()) {
output.writeObject(data);
}
}
output.close();
} catch(IOException e) {
e.printStackTrace();
System.exit(-2);
}
}
public static void analyze(String file) {
AwesomenessAnalyzer analyzer = new AwesomenessAnalyzer(file);
analyzer.analyze();
analyzer.smoothStats();
//for (int i = 0; i < 16; i++)
// analyzer.smoothStats();
analyzer.dumpFile();
}
public static void main(String[] args) {
CommandLineParser parser = new GnuParser();
JFileChooser chooser = new JFileChooser();
CommandLine cmd = null;
try {
cmd = parser.parse(options(), args);
} catch (ParseException e) {
e.printStackTrace();
return;
}
String directory = cmd.getOptionValue("directory");
System.out.println("selected dir: " + directory);
if(cmd.hasOption("directory"))
{
File dir = new File(directory);
String[] children = dir.list();
if (children == null)
{
// Either dir does not exist or is not a directory
}
else {
for (int i=0; i<children.length; i++)
{ // Get filename of file or directory
String filename = children[i];
File file = new File(directory + "/" + filename);
//String type = chooser.getTypeDescription(file);
//System.out.println(directory + "/" + filename + " " + type);
if(filename.endsWith(".rms"))
//if(type.compareTo("RMS File")==0)
{
System.out.println("is an rms file");
analyze(file.getAbsolutePath());
}
}
}
}
else
{
if (args.length < 1) {
System.err.println("Error: No filenames specified in arguments");
System.exit(-1);
}
for (String arg: args) {
analyze(arg);
}
}
}
}
| fixed awesomeness analyzer
| src/main/battlecode/analysis/AwesomenessAnalyzer.java | fixed awesomeness analyzer | <ide><path>rc/main/battlecode/analysis/AwesomenessAnalyzer.java
<ide> }
<ide>
<ide> MapLocation loc = s.getLoc();
<del> r = new RobotStat(loc,s.getType());
<del> robots.put(s.getRobotID(), r);
<del> events.add(new Event(SPAWN_AWESOMENESS*r.robotAwesomeness, loc));
<add> if (loc != null) {
<add> r = new RobotStat(loc,s.getType());
<add> robots.put(s.getRobotID(), r);
<add> events.add(new Event(SPAWN_AWESOMENESS*r.robotAwesomeness, loc));
<add> }
<ide> } else if(signal instanceof MovementSignal) {
<ide> MovementSignal s = (MovementSignal)signal;
<ide> RobotStat robot = robots.get(s.getRobotID());
<ide> AttackSignal s = (AttackSignal)signal;
<ide> r = robots.get(s.getRobotID());
<ide> r.resetCountDown();
<del> events.add(new Event(ATTACK_AWESOMENESS*r.robotAwesomeness, s.getTargetLoc()));
<add> MapLocation loc = s.getTargetLoc();
<add> if (loc != null) {
<add> events.add(new Event(ATTACK_AWESOMENESS*r.robotAwesomeness, s.getTargetLoc()));
<add> }
<ide> } else if(signal instanceof DeathSignal) {
<ide> DeathSignal s = (DeathSignal)signal;
<ide> r = robots.remove(s.getObjectID());
<ide> float awesomeness = DEATH_AWESOMENESS*r.robotAwesomeness;
<del> events.add(new Event(awesomeness, r.location));
<add> if (r.location != null) {
<add> events.add(new Event(awesomeness, r.location));
<add> }
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 62904e89d07e167670dfc272421452cdc3974679 | 0 | tuijldert/jitsi,HelioGuilherme66/jitsi,ibauersachs/jitsi,jibaro/jitsi,gpolitis/jitsi,bebo/jitsi,bebo/jitsi,martin7890/jitsi,damencho/jitsi,ringdna/jitsi,pplatek/jitsi,jitsi/jitsi,marclaporte/jitsi,dkcreinoso/jitsi,dkcreinoso/jitsi,damencho/jitsi,jibaro/jitsi,level7systems/jitsi,pplatek/jitsi,ringdna/jitsi,level7systems/jitsi,bhatvv/jitsi,bhatvv/jitsi,jitsi/jitsi,jitsi/jitsi,HelioGuilherme66/jitsi,ringdna/jitsi,pplatek/jitsi,damencho/jitsi,bhatvv/jitsi,procandi/jitsi,mckayclarey/jitsi,procandi/jitsi,cobratbq/jitsi,HelioGuilherme66/jitsi,gpolitis/jitsi,procandi/jitsi,martin7890/jitsi,martin7890/jitsi,pplatek/jitsi,damencho/jitsi,bebo/jitsi,iant-gmbh/jitsi,level7systems/jitsi,Metaswitch/jitsi,damencho/jitsi,cobratbq/jitsi,pplatek/jitsi,laborautonomo/jitsi,laborautonomo/jitsi,ringdna/jitsi,laborautonomo/jitsi,marclaporte/jitsi,HelioGuilherme66/jitsi,mckayclarey/jitsi,martin7890/jitsi,laborautonomo/jitsi,procandi/jitsi,martin7890/jitsi,gpolitis/jitsi,dkcreinoso/jitsi,iant-gmbh/jitsi,mckayclarey/jitsi,level7systems/jitsi,iant-gmbh/jitsi,HelioGuilherme66/jitsi,gpolitis/jitsi,iant-gmbh/jitsi,cobratbq/jitsi,459below/jitsi,bhatvv/jitsi,jibaro/jitsi,bhatvv/jitsi,459below/jitsi,bebo/jitsi,459below/jitsi,jitsi/jitsi,459below/jitsi,gpolitis/jitsi,Metaswitch/jitsi,tuijldert/jitsi,dkcreinoso/jitsi,ibauersachs/jitsi,laborautonomo/jitsi,bebo/jitsi,jibaro/jitsi,cobratbq/jitsi,mckayclarey/jitsi,jitsi/jitsi,ibauersachs/jitsi,procandi/jitsi,marclaporte/jitsi,marclaporte/jitsi,level7systems/jitsi,tuijldert/jitsi,dkcreinoso/jitsi,tuijldert/jitsi,mckayclarey/jitsi,tuijldert/jitsi,Metaswitch/jitsi,iant-gmbh/jitsi,459below/jitsi,jibaro/jitsi,Metaswitch/jitsi,marclaporte/jitsi,ibauersachs/jitsi,cobratbq/jitsi,ringdna/jitsi,ibauersachs/jitsi | /*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.media;
import java.net.*;
import java.util.*;
import javax.sdp.*;
import javax.media.Time;
import net.java.sip.communicator.impl.media.device.*;
import net.java.sip.communicator.service.media.*;
import net.java.sip.communicator.service.media.event.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.*;
/**
* The service is meant to be a wrapper of media libraries such as JMF,
* (J)FFMPEG, JMFPAPI, and others. It takes care of all media play and capture
* as well as media transport (e.g. over RTP).
*
* Before being able to use this service calls would have to make sure that it
* is initialized (i.e. consult the isInitialized() method).
*
* @author Emil Ivov
* @author Martin Andre
* @author Ryan Ricard
* @author Symphorien Wanko
*/
public class MediaServiceImpl
implements MediaService
{
/**
* Our logger.
*/
private Logger logger = Logger.getLogger(MediaServiceImpl.class);
/**
* The SdpFactory instance that we use for construction of all sdp
* descriptions.
*/
private SdpFactory sdpFactory = null;
/**
* A flag indicating whether the media service implementation is ready
* to be used.
*/
private boolean isStarted = false;
/**
* A flag indicating whether the media service implementation is currently
* in the process of being started.
*/
private boolean isStarting = false;
/**
* The lock object that we use for synchronization during startup.
*/
private Object startingLock = new Object();
/**
* Our event dispatcher.
*/
private MediaEventDispatcher mediaDispatcher = new MediaEventDispatcher();
/**
* Our configuration helper.
*/
private DeviceConfiguration deviceConfiguration = new DeviceConfiguration();
/**
* Our media control helper. The media control instance that we will be
* using for reading media for all calls that do not have a custom media
* control mapping.
*/
private MediaControl defaultMediaControl = new MediaControl();
/**
* Mappings of calls to instances of <tt>MediaControl</tt>. In case a call
* has been mapped to a media control instance, it is going to be used for
* retrieving media that we are going to be sending inside this call.
* Calls that have custom media control mappings are for example calls that
* have been answered by a mailbox plug-in and that will be using a file
* as their sound source.
*/
private Map callMediaControlMappings = new Hashtable();
/**
* Mappings of calls to custom data sinks. Used by mailbox plug-ins for
* sending audio/video flows to a file instead of the sound card or the
* screen.
*/
private Map callDataSinkMappings = new Hashtable();
/**
* Currently open call sessions.
*/
private Map activeCallSessions = new Hashtable();
/**
* Default constructor
*/
public MediaServiceImpl()
{
}
/**
* Implements <tt>getSupportedAudioEncodings</tt> from interface
* <tt>MediaService</tt>
*
* @return an array of Strings containing audio formats in the order of
* preference.
*/
public String[] getSupportedAudioEncodings()
{
return defaultMediaControl.getSupportedAudioEncodings();
}
/**
* Implements <tt>getSupportedVideoEncodings</tt> from interface
* <tt>MediaService</tt>
*
* @return an array of Strings containing video formats in the order of
* preference.
*/
public String[] getSupportedVideoEncodings()
{
return defaultMediaControl.getSupportedAudioEncodings();
}
/**
* Creates a call session for <tt>call</tt>. The method allocates audio
* and video ports which won't be released until the corresponding call
* gets into a DISCONNECTED state. If a session already exists for call,
* it is returned and no new session is created.
* <p>
* @param call the Call that we'll be encapsulating in the newly created
* session.
* @return a <tt>CallSession</tt> encapsulating <tt>call</tt>.
* @throws MediaException with code IO_ERROR if we fail allocating ports.
*/
public CallSession createCallSession(Call call)
throws MediaException
{
waitUntilStarted();
assertStarted();
//if we have this call mapped to a custom data destination, pass that
//destination on to the callSession.
CallSessionImpl callSession = new CallSessionImpl(
call, this, (URL)callDataSinkMappings.get(call));
// commented out because it leaks memory, and activeCallSessions isn't
// used anyway (by Michael Koch)
// activeCallSessions.put(call, callSession);
/** @todo make sure you remove the session once its over. */
return callSession;
}
/**
* A <tt>RtpFlow</tt> is an object which role is to handle media data
* transfer, capture and playback. It's build between two points, a local
* and a remote. The media transfered will be in a format specified by the
* <tt>mediaEncodings</tt> parameter.
*
* @param localIP local address of this RtpFlow
* @param localPort local port of this RtpFlow
* @param remoteIP remote address of this RtpFlow
* @param remotePort remote port of this RtpFlow
* @param mediaEncodings format used to encode data on this flow
* @return rtpFlow the newly created <tt>RtpFlow</tt>
* @throws MediaException if operation fails
*/
public RtpFlow createRtpFlow(String localIP,
int localPort,
String remoteIP,
int remotePort,
Map mediaEncodings)
throws MediaException
{
waitUntilStarted();
assertStarted();
RtpFlowImpl rtpFlow = new RtpFlowImpl(this, localIP, remoteIP,
localPort, remotePort, new Hashtable(mediaEncodings));
return rtpFlow;
}
/**
* Adds a listener that will be listening for incoming media and changes
* in the state of the media listener.
*
* @param listener the listener to register
*/
public void addMediaListener(MediaListener listener)
{
mediaDispatcher.addMediaListener(listener);
}
/**
* Removes a listener that was listening for incoming media and changes
* in the state of the media listener
* @param listener the listener to remove
*/
public void removeMediaListener(MediaListener listener)
{
mediaDispatcher.removeMediaListener(listener);
}
/**
* Initializes the service implementation, and puts it in a state where it
* could interoperate with other services.
*/
public void start()
{
new DeviceConfigurationThread().run();
}
/**
* Releases all resources and prepares for shutdown.
*/
public void stop()
{
try
{
this.closeCaptureDevices();
}
catch (MediaException ex)
{
logger.error("Failed to properly close capture devices.", ex);
}
isStarted = false;
}
/**
* Returns true if the media service implementation is initialized and ready
* for use by other services, and false otherwise.
*
* @return true if the media manager is initialized and false otherwise.
*/
public boolean isStarted()
{
return isStarted;
}
/**
* Verifies whether the media service is started and ready for use and
* throws an exception otherwise.
*
* @throws MediaException if the media service is not started and ready for
* use.
*/
protected void assertStarted()
throws MediaException
{
if (!isStarted()) {
logger.error("The MediaServiceImpl had not been properly started! "
+ "Impossible to continue.");
throw new MediaException(
"The MediaManager had not been properly started! "
+ "Impossible to continue."
, MediaException.SERVICE_NOT_STARTED);
}
}
/**
* Open capture devices specified by configuration service.
*
* @throws MediaException if opening the devices fails.
*/
private void openCaptureDevices()
throws MediaException
{
defaultMediaControl.initCaptureDevices();
}
/**
* Close capture devices specified by configuration service.
*
* @throws MediaException if opening the devices fails.
*/
private void closeCaptureDevices()
throws MediaException
{
defaultMediaControl.closeCaptureDevices();
}
/**
* Makes the service implementation close all release any devices or other
* resources that it might have allocated and prepare for shutdown/garbage
* collection.
*/
public void shutdown() {
isStarted = false;
return;
}
/**
* A valid instance of an SDP factory that call session may use for
* manipulating sdp data.
*
* @return a valid instance of an SDP factory that call session may use for
* manipulating sdp data.
*/
public SdpFactory getSdpFactory()
{
return sdpFactory;
}
/**
* A valid instance of the Media Control that the call session may use to
* query for supported audio video encodings.
*
* @return the default instance of the Media Control that the call session
* may use to query for supported audio video encodings.
*/
public MediaControl getMediaControl()
{
return defaultMediaControl;
}
/**
* The MediaControl instance that is mapped to <tt>call</tt>. If
* <tt>call</tt> is not mapped to a particular <tt>MediaControl</tt>
* instance, the default instance will be returned
*
* @param call the call whose MediaControl we will fetch
* @return the instance of MediaControl that is mapped to <tt>call</tt>
* or the <tt>defaultMediaControl</tt> if no custom one is registered for
* <tt>call</tt>.
*/
public MediaControl getMediaControl(Call call)
{
if (callMediaControlMappings.containsKey(call))
{
return (MediaControl)callMediaControlMappings.get(call);
}
else
{
return defaultMediaControl;
}
}
/**
* A valid instance of the DeviceConfiguration that a call session may use
* to query for supported support of audio/video capture.
*
* @return a valid instance of the DeviceConfiguration that a call session
* may use to query for supported support of audio/video capture.
*/
public DeviceConfiguration getDeviceConfiguration()
{
return deviceConfiguration;
}
/**
* We use this thread to detect, initialize and configure all capture
* devices.
*/
private class DeviceConfigurationThread
extends Thread
{
/**
* Sets a thread name and gives the thread a daemon status.
*/
public DeviceConfigurationThread()
{
super("DeviceConfigurationThread");
setDaemon(true);
}
/**
* Initializes device configuration.
*/
public void run()
{
synchronized(startingLock)
{
isStarting = true;
try
{
deviceConfiguration.initialize();
defaultMediaControl.initialize(deviceConfiguration);
sdpFactory = SdpFactory.getInstance();
isStarted = true;
}
catch (Exception ex)
{
logger.error("Failed to initialize media control", ex);
isStarted = false;
}
isStarting = false;
startingLock.notifyAll();
}
}
}
/**
* A utility method that would block until the media service has been
* started or, in case it already is started, return immediately.
*/
private void waitUntilStarted()
{
synchronized(startingLock)
{
if(!isStarting)
{
return;
}
try
{
startingLock.wait();
}
catch (InterruptedException ex)
{
logger.warn("Interrupted while waiting for the stack to start",
ex);
}
}
}
/**
* Sets the data source for <tt>call</tt> to the URL <tt>dataSourceURL</tt>
* instead of the default data source. This is used (for instance)
* to play audio from a file instead of from a the microphone.
*
* @param call the <tt>Call</tt> whose data source will be changed
* @param dataSourceURL the <tt>URL</tt> of the new data source
*/
public void setCallDataSource(Call call, URL dataSourceURL)
throws MediaException
{
//create a new instance of MediaControl for this call
MediaControl callMediaControl = new MediaControl();
callMediaControl.initDataSourceFromURL(dataSourceURL);
callMediaControlMappings.put(call, callMediaControl);
}
/**
* Returns the duration (in milliseconds) of the data source
* being used for the given call. If the data source is not time-based,
* IE a microphone, or the duration cannot be determined, returns -1
*
* @param call the call whose data source duration will be retrieved
* @return -1 or the duration of the data source
*/
public double getDataSourceDurationSeconds(Call call)
{
Time duration = getMediaControl(call).getOutputDuration();
if (duration == javax.media.Duration.DURATION_UNKNOWN)
return -1;
else return duration.getSeconds();
}
/**
* Unsets the data source for <tt>call</tt>, which will now use the default
* data source.
*
* @param call the call whose data source mapping will be released
*/
public void unsetCallDataSource(Call call)
{
callMediaControlMappings.remove(call);
}
/**
* Sets the Data Destination for <tt>call</tt> to the URL
* <tt>dataSinkURL</tt> instead of the default data destination. This is
* used (for instance) to record incoming data to a file instead of sending
* it to the speakers/screen.
*
* @param call the call whose data destination will be changed
* @param dataSinkURL the URL of the new data sink.
*/
public void setCallDataSink(Call call, URL dataSinkURL)
{
callDataSinkMappings.put(call, dataSinkURL);
}
/**
* Unsets the data destination for <tt>call</tt>, which will now send data
* to the default destination.
*
* @param call the call whose data destination mapping will be released
*/
public void unsetCallDataSink(Call call)
{
callDataSinkMappings.remove(call);
}
//------------------ main method for testing ---------------------------------
/**
* This method is here most probably only temporarily for the sake of
* testing. @todo remove main method.
*
* @param args String[]
*
* @throws java.lang.Throwable if it doesn't feel like executing today.
*/
public static void main(String[] args)
throws Throwable
{
MediaServiceImpl msimpl = new MediaServiceImpl();
msimpl.start();
System.out.println("done");
}
}
| src/net/java/sip/communicator/impl/media/MediaServiceImpl.java | /*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.media;
import java.net.*;
import java.util.*;
import javax.sdp.*;
import javax.media.Time;
import net.java.sip.communicator.impl.media.device.*;
import net.java.sip.communicator.service.media.*;
import net.java.sip.communicator.service.media.event.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.*;
/**
* The service is meant to be a wrapper of media libraries such as JMF,
* (J)FFMPEG, JMFPAPI, and others. It takes care of all media play and capture
* as well as media transport (e.g. over RTP).
*
* Before being able to use this service calls would have to make sure that it
* is initialized (i.e. consult the isInitialized() method).
*
* @author Emil Ivov
* @author Martin Andre
* @author Ryan Ricard
* @author Symphorien Wanko
*/
public class MediaServiceImpl
implements MediaService
{
/**
* Our logger.
*/
private Logger logger = Logger.getLogger(MediaServiceImpl.class);
/**
* The SdpFactory instance that we use for construction of all sdp
* descriptions.
*/
private SdpFactory sdpFactory = null;
/**
* A flag indicating whether the media service implementation is ready
* to be used.
*/
private boolean isStarted = false;
/**
* A flag indicating whether the media service implementation is currently
* in the process of being started.
*/
private boolean isStarting = false;
/**
* The lock object that we use for synchronization during startup.
*/
private Object startingLock = new Object();
/**
* Our event dispatcher.
*/
private MediaEventDispatcher mediaDispatcher = new MediaEventDispatcher();
/**
* Our configuration helper.
*/
private DeviceConfiguration deviceConfiguration = new DeviceConfiguration();
/**
* Our media control helper. The media control instance that we will be
* using for reading media for all calls that do not have a custom media
* control mapping.
*/
private MediaControl defaultMediaControl = new MediaControl();
/**
* Mappings of calls to instances of <tt>MediaControl</tt>. In case a call
* has been mapped to a media control instance, it is going to be used for
* retrieving media that we are going to be sending inside this call.
* Calls that have custom media control mappings are for example calls that
* have been answered by a mailbox plug-in and that will be using a file
* as their sound source.
*/
private Map callMediaControlMappings = new Hashtable();
/**
* Mappings of calls to custom data sinks. Used by mailbox plug-ins for
* sending audio/video flows to a file instead of the sound card or the
* screen.
*/
private Map callDataSinkMappings = new Hashtable();
/**
* Currently open call sessions.
*/
private Map activeCallSessions = new Hashtable();
/**
* Default constructor
*/
public MediaServiceImpl()
{
}
/**
* Implements <tt>getSupportedAudioEncodings</tt> from interface
* <tt>MediaService</tt>
*
* @return an array of Strings containing audio formats in the order of
* preference.
*/
public String[] getSupportedAudioEncodings()
{
return defaultMediaControl.getSupportedAudioEncodings();
}
/**
* Implements <tt>getSupportedVideoEncodings</tt> from interface
* <tt>MediaService</tt>
*
* @return an array of Strings containing video formats in the order of
* preference.
*/
public String[] getSupportedVideoEncodings()
{
return defaultMediaControl.getSupportedAudioEncodings();
}
/**
* Creates a call session for <tt>call</tt>. The method allocates audio
* and video ports which won't be released until the corresponding call
* gets into a DISCONNECTED state. If a session already exists for call,
* it is returned and no new session is created.
* <p>
* @param call the Call that we'll be encapsulating in the newly created
* session.
* @return a <tt>CallSession</tt> encapsulating <tt>call</tt>.
* @throws MediaException with code IO_ERROR if we fail allocating ports.
*/
public CallSession createCallSession(Call call)
throws MediaException
{
waitUntilStarted();
assertStarted();
//if we have this call mapped to a custom data destination, pass that
//destination on to the callSession.
CallSessionImpl callSession = new CallSessionImpl(
call, this, (URL)callDataSinkMappings.get(call));
activeCallSessions.put(call, callSession);
/** @todo make sure you remove the session once its over. */
return callSession;
}
/**
* A <tt>RtpFlow</tt> is an object which role is to handle media data
* transfer, capture and playback. It's build between two points, a local
* and a remote. The media transfered will be in a format specified by the
* <tt>mediaEncodings</tt> parameter.
*
* @param localIP local address of this RtpFlow
* @param localPort local port of this RtpFlow
* @param remoteIP remote address of this RtpFlow
* @param remotePort remote port of this RtpFlow
* @param mediaEncodings format used to encode data on this flow
* @return rtpFlow the newly created <tt>RtpFlow</tt>
* @throws MediaException if operation fails
*/
public RtpFlow createRtpFlow(String localIP,
int localPort,
String remoteIP,
int remotePort,
Map mediaEncodings)
throws MediaException
{
waitUntilStarted();
assertStarted();
RtpFlowImpl rtpFlow = new RtpFlowImpl(this, localIP, remoteIP,
localPort, remotePort, new Hashtable(mediaEncodings));
return rtpFlow;
}
/**
* Adds a listener that will be listening for incoming media and changes
* in the state of the media listener.
*
* @param listener the listener to register
*/
public void addMediaListener(MediaListener listener)
{
mediaDispatcher.addMediaListener(listener);
}
/**
* Removes a listener that was listening for incoming media and changes
* in the state of the media listener
* @param listener the listener to remove
*/
public void removeMediaListener(MediaListener listener)
{
mediaDispatcher.removeMediaListener(listener);
}
/**
* Initializes the service implementation, and puts it in a state where it
* could interoperate with other services.
*/
public void start()
{
new DeviceConfigurationThread().run();
}
/**
* Releases all resources and prepares for shutdown.
*/
public void stop()
{
try
{
this.closeCaptureDevices();
}
catch (MediaException ex)
{
logger.error("Failed to properly close capture devices.", ex);
}
isStarted = false;
}
/**
* Returns true if the media service implementation is initialized and ready
* for use by other services, and false otherwise.
*
* @return true if the media manager is initialized and false otherwise.
*/
public boolean isStarted()
{
return isStarted;
}
/**
* Verifies whether the media service is started and ready for use and
* throws an exception otherwise.
*
* @throws MediaException if the media service is not started and ready for
* use.
*/
protected void assertStarted()
throws MediaException
{
if (!isStarted()) {
logger.error("The MediaServiceImpl had not been properly started! "
+ "Impossible to continue.");
throw new MediaException(
"The MediaManager had not been properly started! "
+ "Impossible to continue."
, MediaException.SERVICE_NOT_STARTED);
}
}
/**
* Open capture devices specified by configuration service.
*
* @throws MediaException if opening the devices fails.
*/
private void openCaptureDevices()
throws MediaException
{
defaultMediaControl.initCaptureDevices();
}
/**
* Close capture devices specified by configuration service.
*
* @throws MediaException if opening the devices fails.
*/
private void closeCaptureDevices()
throws MediaException
{
defaultMediaControl.closeCaptureDevices();
}
/**
* Makes the service implementation close all release any devices or other
* resources that it might have allocated and prepare for shutdown/garbage
* collection.
*/
public void shutdown() {
isStarted = false;
return;
}
/**
* A valid instance of an SDP factory that call session may use for
* manipulating sdp data.
*
* @return a valid instance of an SDP factory that call session may use for
* manipulating sdp data.
*/
public SdpFactory getSdpFactory()
{
return sdpFactory;
}
/**
* A valid instance of the Media Control that the call session may use to
* query for supported audio video encodings.
*
* @return the default instance of the Media Control that the call session
* may use to query for supported audio video encodings.
*/
public MediaControl getMediaControl()
{
return defaultMediaControl;
}
/**
* The MediaControl instance that is mapped to <tt>call</tt>. If
* <tt>call</tt> is not mapped to a particular <tt>MediaControl</tt>
* instance, the default instance will be returned
*
* @param call the call whose MediaControl we will fetch
* @return the instance of MediaControl that is mapped to <tt>call</tt>
* or the <tt>defaultMediaControl</tt> if no custom one is registered for
* <tt>call</tt>.
*/
public MediaControl getMediaControl(Call call)
{
if (callMediaControlMappings.containsKey(call))
{
return (MediaControl)callMediaControlMappings.get(call);
}
else
{
return defaultMediaControl;
}
}
/**
* A valid instance of the DeviceConfiguration that a call session may use
* to query for supported support of audio/video capture.
*
* @return a valid instance of the DeviceConfiguration that a call session
* may use to query for supported support of audio/video capture.
*/
public DeviceConfiguration getDeviceConfiguration()
{
return deviceConfiguration;
}
/**
* We use this thread to detect, initialize and configure all capture
* devices.
*/
private class DeviceConfigurationThread
extends Thread
{
/**
* Sets a thread name and gives the thread a daemon status.
*/
public DeviceConfigurationThread()
{
super("DeviceConfigurationThread");
setDaemon(true);
}
/**
* Initializes device configuration.
*/
public void run()
{
synchronized(startingLock)
{
isStarting = true;
try
{
deviceConfiguration.initialize();
defaultMediaControl.initialize(deviceConfiguration);
sdpFactory = SdpFactory.getInstance();
isStarted = true;
}
catch (Exception ex)
{
logger.error("Failed to initialize media control", ex);
isStarted = false;
}
isStarting = false;
startingLock.notifyAll();
}
}
}
/**
* A utility method that would block until the media service has been
* started or, in case it already is started, return immediately.
*/
private void waitUntilStarted()
{
synchronized(startingLock)
{
if(!isStarting)
{
return;
}
try
{
startingLock.wait();
}
catch (InterruptedException ex)
{
logger.warn("Interrupted while waiting for the stack to start",
ex);
}
}
}
/**
* Sets the data source for <tt>call</tt> to the URL <tt>dataSourceURL</tt>
* instead of the default data source. This is used (for instance)
* to play audio from a file instead of from a the microphone.
*
* @param call the <tt>Call</tt> whose data source will be changed
* @param dataSourceURL the <tt>URL</tt> of the new data source
*/
public void setCallDataSource(Call call, URL dataSourceURL)
throws MediaException
{
//create a new instance of MediaControl for this call
MediaControl callMediaControl = new MediaControl();
callMediaControl.initDataSourceFromURL(dataSourceURL);
callMediaControlMappings.put(call, callMediaControl);
}
/**
* Returns the duration (in milliseconds) of the data source
* being used for the given call. If the data source is not time-based,
* IE a microphone, or the duration cannot be determined, returns -1
*
* @param call the call whose data source duration will be retrieved
* @return -1 or the duration of the data source
*/
public double getDataSourceDurationSeconds(Call call)
{
Time duration = getMediaControl(call).getOutputDuration();
if (duration == javax.media.Duration.DURATION_UNKNOWN)
return -1;
else return duration.getSeconds();
}
/**
* Unsets the data source for <tt>call</tt>, which will now use the default
* data source.
*
* @param call the call whose data source mapping will be released
*/
public void unsetCallDataSource(Call call)
{
callMediaControlMappings.remove(call);
}
/**
* Sets the Data Destination for <tt>call</tt> to the URL
* <tt>dataSinkURL</tt> instead of the default data destination. This is
* used (for instance) to record incoming data to a file instead of sending
* it to the speakers/screen.
*
* @param call the call whose data destination will be changed
* @param dataSinkURL the URL of the new data sink.
*/
public void setCallDataSink(Call call, URL dataSinkURL)
{
callDataSinkMappings.put(call, dataSinkURL);
}
/**
* Unsets the data destination for <tt>call</tt>, which will now send data
* to the default destination.
*
* @param call the call whose data destination mapping will be released
*/
public void unsetCallDataSink(Call call)
{
callDataSinkMappings.remove(call);
}
//------------------ main method for testing ---------------------------------
/**
* This method is here most probably only temporarily for the sake of
* testing. @todo remove main method.
*
* @param args String[]
*
* @throws java.lang.Throwable if it doesn't feel like executing today.
*/
public static void main(String[] args)
throws Throwable
{
MediaServiceImpl msimpl = new MediaServiceImpl();
msimpl.start();
System.out.println("done");
}
}
| Fixing a memory leak in the media package (Report and fix thereof by Michael Koch)
| src/net/java/sip/communicator/impl/media/MediaServiceImpl.java | Fixing a memory leak in the media package (Report and fix thereof by Michael Koch) | <ide><path>rc/net/java/sip/communicator/impl/media/MediaServiceImpl.java
<ide> CallSessionImpl callSession = new CallSessionImpl(
<ide> call, this, (URL)callDataSinkMappings.get(call));
<ide>
<del> activeCallSessions.put(call, callSession);
<del>
<add> // commented out because it leaks memory, and activeCallSessions isn't
<add> // used anyway (by Michael Koch)
<add> // activeCallSessions.put(call, callSession);
<ide> /** @todo make sure you remove the session once its over. */
<ide>
<ide> return callSession; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.