lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
mit
5c6ddd762a41cf0bbe417e37155b2aa89bf5da4f
0
unbroken-dome/jsonwebtoken
package org.unbrokendome.jsonwebtoken.impl; import org.unbrokendome.jsonwebtoken.BinaryData; import org.unbrokendome.jsonwebtoken.JoseHeader; import org.unbrokendome.jsonwebtoken.Jws; import org.unbrokendome.jsonwebtoken.JwtDecodingProcessor; import org.unbrokendome.jsonwebtoken.encoding.HeaderDeserializer; import org.unbrokendome.jsonwebtoken.encoding.JwsDecoder; import org.unbrokendome.jsonwebtoken.encoding.JwtMalformedTokenException; import org.unbrokendome.jsonwebtoken.encoding.payload.PayloadDeserializer; import org.unbrokendome.jsonwebtoken.signature.JwsSignatureException; import org.unbrokendome.jsonwebtoken.signature.JwsUnsupportedAlgorithmException; import org.unbrokendome.jsonwebtoken.signature.VerificationKeyResolver; import org.unbrokendome.jsonwebtoken.signature.Verifier; import java.security.Key; import java.util.List; import java.util.Map; public final class DefaultJwtDecodingProcessor implements JwtDecodingProcessor { private final List<PayloadDeserializer<?>> payloadDeserializers; private final Map<String, VerifierWithKeyResolver<?>> verifiers; private final HeaderDeserializer headerDeserializer; private final JwsDecoder jwsDecoder; public DefaultJwtDecodingProcessor(List<PayloadDeserializer<?>> payloadDeserializers, Map<String, VerifierWithKeyResolver<?>> verifiers, HeaderDeserializer headerDeserializer, JwsDecoder jwsDecoder) { this.payloadDeserializers = payloadDeserializers; this.verifiers = verifiers; this.headerDeserializer = headerDeserializer; this.jwsDecoder = jwsDecoder; } @Override public <T> T decode(String encodedToken, Class<T> payloadType) throws JwtMalformedTokenException, JwsUnsupportedAlgorithmException, JwsSignatureException { Jws jws = jwsDecoder.decode(encodedToken); JoseHeader header = headerDeserializer.deserialize(jws.getHeader()); T payload = deserializePayload(jws.getPayload(), payloadType); verifySignature(jws, header, payload); return payload; } private <T> T deserializePayload(BinaryData payloadBytes, Class<T> payloadType) throws JwtMalformedTokenException { PayloadDeserializer<T> payloadSerializer = findPayloadSerializerForType(payloadType); try { return payloadSerializer.deserialize(payloadBytes, payloadType); } catch (Exception ex) { throw new JwtMalformedTokenException("Error deserializing JWT payload", ex); } } private <T> PayloadDeserializer<T> findPayloadSerializerForType(Class<T> payloadType) { PayloadDeserializer<?> payloadDeserializer = payloadDeserializers .stream() .filter(ps -> ps.supports(payloadType)) .findFirst() .orElseThrow( () -> new IllegalStateException("No payload serializer could handle the payload of type: " + payloadType)); // noinspection unchecked return (PayloadDeserializer<T>) payloadDeserializer; } private void verifySignature(Jws jws, JoseHeader header, Object payload) throws JwsUnsupportedAlgorithmException, JwsSignatureException { VerifierWithKeyResolver<?> verifierWithKeyResolver = getVerifierAndKeyResolver(header); VerificationKeyResolver<?> verificationKeyResolver = verifierWithKeyResolver.getVerificationKeyResolver(); // noinspection rawtypes Verifier verifier = verifierWithKeyResolver.getVerifier(); Key verificationKey = verificationKeyResolver.getVerificationKey(header, payload); //noinspection unchecked verifier.verify(jws.getHeader(), jws.getPayload(), jws.getSignature(), verificationKey); } private VerifierWithKeyResolver<?> getVerifierAndKeyResolver(JoseHeader header) throws JwsUnsupportedAlgorithmException { String algorithmName = header.getAlgorithm(); VerifierWithKeyResolver<?> verifierWithKeyResolver = verifiers.get(algorithmName); if (verifierWithKeyResolver == null) { throw new JwsUnsupportedAlgorithmException(algorithmName); } return verifierWithKeyResolver; } }
src/main/java/org/unbrokendome/jsonwebtoken/impl/DefaultJwtDecodingProcessor.java
package org.unbrokendome.jsonwebtoken.impl; import org.unbrokendome.jsonwebtoken.BinaryData; import org.unbrokendome.jsonwebtoken.JoseHeader; import org.unbrokendome.jsonwebtoken.Jws; import org.unbrokendome.jsonwebtoken.JwtDecodingProcessor; import org.unbrokendome.jsonwebtoken.encoding.HeaderDeserializer; import org.unbrokendome.jsonwebtoken.encoding.JwsDecoder; import org.unbrokendome.jsonwebtoken.encoding.JwtMalformedTokenException; import org.unbrokendome.jsonwebtoken.encoding.payload.PayloadDeserializer; import org.unbrokendome.jsonwebtoken.signature.JwsSignatureException; import org.unbrokendome.jsonwebtoken.signature.JwsUnsupportedAlgorithmException; import org.unbrokendome.jsonwebtoken.signature.VerificationKeyResolver; import org.unbrokendome.jsonwebtoken.signature.Verifier; import java.security.Key; import java.util.List; import java.util.Map; public final class DefaultJwtDecodingProcessor implements JwtDecodingProcessor { private final List<PayloadDeserializer<?>> payloadDeserializers; private final Map<String, VerifierWithKeyResolver<?>> verifiers; private final HeaderDeserializer headerDeserializer; private final JwsDecoder jwsDecoder; public DefaultJwtDecodingProcessor(List<PayloadDeserializer<?>> payloadDeserializers, Map<String, VerifierWithKeyResolver<?>> verifiers, HeaderDeserializer headerDeserializer, JwsDecoder jwsDecoder) { this.payloadDeserializers = payloadDeserializers; this.verifiers = verifiers; this.headerDeserializer = headerDeserializer; this.jwsDecoder = jwsDecoder; } @Override public <T> T decode(String encodedToken, Class<T> payloadType) throws JwtMalformedTokenException, JwsUnsupportedAlgorithmException, JwsSignatureException { Jws jws = jwsDecoder.decode(encodedToken); JoseHeader header = headerDeserializer.deserialize(jws.getHeader()); T payload = deserializePayload(jws.getPayload(), payloadType); verifySignature(jws, header, payload); return payload; } private <T> T deserializePayload(BinaryData payloadBytes, Class<T> payloadType) { PayloadDeserializer<T> payloadSerializer = findPayloadSerializerForType(payloadType); return payloadSerializer.deserialize(payloadBytes, payloadType); } private <T> PayloadDeserializer<T> findPayloadSerializerForType(Class<T> payloadType) { PayloadDeserializer<?> payloadDeserializer = payloadDeserializers .stream() .filter(ps -> ps.supports(payloadType)) .findFirst() .orElseThrow( () -> new IllegalStateException("No payload serializer could handle the payload of type: " + payloadType)); // noinspection unchecked return (PayloadDeserializer<T>) payloadDeserializer; } private void verifySignature(Jws jws, JoseHeader header, Object payload) throws JwsUnsupportedAlgorithmException, JwsSignatureException { VerifierWithKeyResolver<?> verifierWithKeyResolver = getVerifierAndKeyResolver(header); VerificationKeyResolver<?> verificationKeyResolver = verifierWithKeyResolver.getVerificationKeyResolver(); // noinspection rawtypes Verifier verifier = verifierWithKeyResolver.getVerifier(); Key verificationKey = verificationKeyResolver.getVerificationKey(header, payload); //noinspection unchecked verifier.verify(jws.getHeader(), jws.getPayload(), jws.getSignature(), verificationKey); } private VerifierWithKeyResolver<?> getVerifierAndKeyResolver(JoseHeader header) throws JwsUnsupportedAlgorithmException { String algorithmName = header.getAlgorithm(); VerifierWithKeyResolver<?> verifierWithKeyResolver = verifiers.get(algorithmName); if (verifierWithKeyResolver == null) { throw new JwsUnsupportedAlgorithmException(algorithmName); } return verifierWithKeyResolver; } }
Throw a JwtMalformedTokenException if any exception is thrown during payload deserialization (e.g. invalid base64 string)
src/main/java/org/unbrokendome/jsonwebtoken/impl/DefaultJwtDecodingProcessor.java
Throw a JwtMalformedTokenException if any exception is thrown during payload deserialization (e.g. invalid base64 string)
<ide><path>rc/main/java/org/unbrokendome/jsonwebtoken/impl/DefaultJwtDecodingProcessor.java <ide> } <ide> <ide> <del> private <T> T deserializePayload(BinaryData payloadBytes, Class<T> payloadType) { <add> private <T> T deserializePayload(BinaryData payloadBytes, Class<T> payloadType) throws JwtMalformedTokenException { <ide> PayloadDeserializer<T> payloadSerializer = findPayloadSerializerForType(payloadType); <del> return payloadSerializer.deserialize(payloadBytes, payloadType); <add> <add> try { <add> return payloadSerializer.deserialize(payloadBytes, payloadType); <add> } catch (Exception ex) { <add> throw new JwtMalformedTokenException("Error deserializing JWT payload", ex); <add> } <ide> } <ide> <ide>
Java
apache-2.0
0fd0dce5804cecbf18983a5e8fae9dd80f3fd4ab
0
allotria/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,caot/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,ernestp/consulo,xfournet/intellij-community,ernestp/consulo,da1z/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,robovm/robovm-studio,xfournet/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,adedayo/intellij-community,apixandru/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,slisson/intellij-community,retomerz/intellij-community,jagguli/intellij-community,supersven/intellij-community,kool79/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,FHannes/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,allotria/intellij-community,semonte/intellij-community,ibinti/intellij-community,izonder/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,signed/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,ibinti/intellij-community,amith01994/intellij-community,petteyg/intellij-community,ernestp/consulo,SerCeMan/intellij-community,holmes/intellij-community,ryano144/intellij-community,hurricup/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,kdwink/intellij-community,dslomov/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,supersven/intellij-community,dslomov/intellij-community,samthor/intellij-community,caot/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,blademainer/intellij-community,xfournet/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,suncycheng/intellij-community,holmes/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,da1z/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,signed/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,kool79/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,ernestp/consulo,nicolargo/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,caot/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,caot/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,ibinti/intellij-community,samthor/intellij-community,asedunov/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,FHannes/intellij-community,da1z/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,vladmm/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,kool79/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,izonder/intellij-community,samthor/intellij-community,robovm/robovm-studio,da1z/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,slisson/intellij-community,retomerz/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,holmes/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,ryano144/intellij-community,signed/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,izonder/intellij-community,signed/intellij-community,supersven/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,asedunov/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,vladmm/intellij-community,semonte/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,consulo/consulo,jagguli/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,allotria/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,caot/intellij-community,fitermay/intellij-community,holmes/intellij-community,kool79/intellij-community,kdwink/intellij-community,slisson/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,robovm/robovm-studio,vladmm/intellij-community,jagguli/intellij-community,allotria/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,consulo/consulo,ol-loginov/intellij-community,caot/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,jagguli/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,izonder/intellij-community,dslomov/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,signed/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,FHannes/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,allotria/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,holmes/intellij-community,supersven/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,da1z/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,samthor/intellij-community,samthor/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,samthor/intellij-community,hurricup/intellij-community,kdwink/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,vvv1559/intellij-community,supersven/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,supersven/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,samthor/intellij-community,vladmm/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,caot/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,da1z/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,diorcety/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,fnouama/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,caot/intellij-community,holmes/intellij-community,diorcety/intellij-community,semonte/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,dslomov/intellij-community,slisson/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,hurricup/intellij-community,asedunov/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,consulo/consulo,slisson/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,vladmm/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,da1z/intellij-community,robovm/robovm-studio,ernestp/consulo,diorcety/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,FHannes/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,semonte/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,supersven/intellij-community,slisson/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,dslomov/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,apixandru/intellij-community,signed/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,adedayo/intellij-community,semonte/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,caot/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,izonder/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,consulo/consulo,ahb0327/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,slisson/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,samthor/intellij-community,supersven/intellij-community,FHannes/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,muntasirsyed/intellij-community,xfournet/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,allotria/intellij-community,kool79/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,SerCeMan/intellij-community,caot/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,asedunov/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,nicolargo/intellij-community,semonte/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,tmpgit/intellij-community,signed/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,holmes/intellij-community,amith01994/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,caot/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,supersven/intellij-community,blademainer/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,da1z/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,signed/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,FHannes/intellij-community,kdwink/intellij-community,ibinti/intellij-community,blademainer/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,semonte/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,blademainer/intellij-community,robovm/robovm-studio,slisson/intellij-community,clumsy/intellij-community,fitermay/intellij-community,slisson/intellij-community,petteyg/intellij-community,signed/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,retomerz/intellij-community,retomerz/intellij-community,retomerz/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,caot/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,tmpgit/intellij-community
/* * Copyright 2000-2012 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. */ /** * @author: Eugene Zhuravlev * Date: Jan 17, 2003 * Time: 1:42:26 PM */ package com.intellij.compiler.impl; import com.intellij.CommonBundle; import com.intellij.compiler.*; import com.intellij.compiler.make.CacheCorruptedException; import com.intellij.compiler.make.CacheUtils; import com.intellij.compiler.make.ChangedConstantsDependencyProcessor; import com.intellij.compiler.make.DependencyCache; import com.intellij.compiler.progress.CompilerTask; import com.intellij.compiler.server.BuildManager; import com.intellij.compiler.server.CustomBuilderMessageHandler; import com.intellij.compiler.server.DefaultMessageHandler; import com.intellij.diagnostic.IdeErrorsDialog; import com.intellij.diagnostic.PluginException; import com.intellij.openapi.application.*; import com.intellij.openapi.compiler.*; import com.intellij.openapi.compiler.Compiler; import com.intellij.openapi.compiler.ex.CompileContextEx; import com.intellij.openapi.compiler.ex.CompilerPathsEx; import com.intellij.openapi.compiler.generic.GenericCompiler; import com.intellij.openapi.deployment.DeploymentUtil; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.module.LanguageLevelUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.ex.ProjectRootManagerEx; import com.intellij.openapi.roots.ui.configuration.CommonContentEntriesEditor; import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.newvfs.ManagingFS; import com.intellij.openapi.vfs.newvfs.RefreshQueue; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.openapi.wm.WindowManager; import com.intellij.packaging.artifacts.Artifact; import com.intellij.packaging.artifacts.ArtifactManager; import com.intellij.packaging.impl.artifacts.ArtifactImpl; import com.intellij.packaging.impl.artifacts.ArtifactUtil; import com.intellij.packaging.impl.compiler.ArtifactCompileScope; import com.intellij.packaging.impl.compiler.ArtifactCompilerUtil; import com.intellij.packaging.impl.compiler.ArtifactsCompiler; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.PsiDocumentManager; import com.intellij.util.Chunk; import com.intellij.util.Function; import com.intellij.util.StringBuilderSpinAllocator; import com.intellij.util.ThrowableRunnable; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashMap; import com.intellij.util.containers.MultiMap; import com.intellij.util.containers.OrderedSet; import com.intellij.util.messages.MessageBus; import gnu.trove.THashSet; import gnu.trove.TIntHashSet; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import org.jetbrains.jps.api.CmdlineProtoUtil; import org.jetbrains.jps.api.CmdlineRemoteProto; import org.jetbrains.jps.api.RequestFuture; import org.jetbrains.jps.incremental.Utils; import javax.swing.*; import java.io.*; import java.util.*; import java.util.concurrent.TimeUnit; import static org.jetbrains.jps.api.CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.TargetTypeBuildScope; public class CompileDriver { private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.CompileDriver"); // to be used in tests only for debug output public static volatile boolean ourDebugMode = false; private final Project myProject; private final Map<Pair<IntermediateOutputCompiler, Module>, Pair<VirtualFile, VirtualFile>> myGenerationCompilerModuleToOutputDirMap; // [IntermediateOutputCompiler, Module] -> [ProductionSources, TestSources] private final String myCachesDirectoryPath; private boolean myShouldClearOutputDirectory; private final Map<Module, String> myModuleOutputPaths = new HashMap<Module, String>(); private final Map<Module, String> myModuleTestOutputPaths = new HashMap<Module, String>(); @NonNls private static final String VERSION_FILE_NAME = "version.dat"; @NonNls private static final String LOCK_FILE_NAME = "in_progress.dat"; private static final boolean GENERATE_CLASSPATH_INDEX = "true".equals(System.getProperty("generate.classpath.index")); private static final String PROP_PERFORM_INITIAL_REFRESH = "compiler.perform.outputs.refresh.on.start"; private static final Key<Boolean> REFRESH_DONE_KEY = Key.create("_compiler.initial.refresh.done_"); private static final Key<Boolean> COMPILATION_STARTED_AUTOMATICALLY = Key.create("compilation_started_automatically"); private static final FileProcessingCompilerAdapterFactory FILE_PROCESSING_COMPILER_ADAPTER_FACTORY = new FileProcessingCompilerAdapterFactory() { public FileProcessingCompilerAdapter create(CompileContext context, FileProcessingCompiler compiler) { return new FileProcessingCompilerAdapter(context, compiler); } }; private static final FileProcessingCompilerAdapterFactory FILE_PACKAGING_COMPILER_ADAPTER_FACTORY = new FileProcessingCompilerAdapterFactory() { public FileProcessingCompilerAdapter create(CompileContext context, FileProcessingCompiler compiler) { return new PackagingCompilerAdapter(context, (PackagingCompiler)compiler); } }; private CompilerFilter myCompilerFilter = CompilerFilter.ALL; private static final CompilerFilter SOURCE_PROCESSING_ONLY = new CompilerFilter() { public boolean acceptCompiler(Compiler compiler) { return compiler instanceof SourceProcessingCompiler; } }; private static final CompilerFilter ALL_EXCEPT_SOURCE_PROCESSING = new CompilerFilter() { public boolean acceptCompiler(Compiler compiler) { return !SOURCE_PROCESSING_ONLY.acceptCompiler(compiler); } }; private Set<File> myAllOutputDirectories; private static final long ONE_MINUTE_MS = 60L /*sec*/ * 1000L /*millisec*/; public CompileDriver(Project project) { myProject = project; myCachesDirectoryPath = CompilerPaths.getCacheStoreDirectory(myProject).getPath().replace('/', File.separatorChar); myShouldClearOutputDirectory = CompilerWorkspaceConfiguration.getInstance(myProject).CLEAR_OUTPUT_DIRECTORY; myGenerationCompilerModuleToOutputDirMap = new HashMap<Pair<IntermediateOutputCompiler, Module>, Pair<VirtualFile, VirtualFile>>(); if (!useOutOfProcessBuild()) { final LocalFileSystem lfs = LocalFileSystem.getInstance(); final IntermediateOutputCompiler[] generatingCompilers = CompilerManager.getInstance(myProject).getCompilers(IntermediateOutputCompiler.class, myCompilerFilter); final Module[] allModules = ModuleManager.getInstance(myProject).getModules(); final CompilerConfiguration config = CompilerConfiguration.getInstance(project); for (Module module : allModules) { for (IntermediateOutputCompiler compiler : generatingCompilers) { final VirtualFile productionOutput = lookupVFile(lfs, CompilerPaths.getGenerationOutputPath(compiler, module, false)); final VirtualFile testOutput = lookupVFile(lfs, CompilerPaths.getGenerationOutputPath(compiler, module, true)); final Pair<IntermediateOutputCompiler, Module> pair = new Pair<IntermediateOutputCompiler, Module>(compiler, module); final Pair<VirtualFile, VirtualFile> outputs = new Pair<VirtualFile, VirtualFile>(productionOutput, testOutput); myGenerationCompilerModuleToOutputDirMap.put(pair, outputs); } if (config.getAnnotationProcessingConfiguration(module).isEnabled()) { final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); if (path != null) { lookupVFile(lfs, path); // ensure the file is created and added to VFS } } } } } public void setCompilerFilter(CompilerFilter compilerFilter) { myCompilerFilter = compilerFilter == null? CompilerFilter.ALL : compilerFilter; } public void rebuild(CompileStatusNotification callback) { final CompileScope compileScope; ProjectCompileScope projectScope = new ProjectCompileScope(myProject); if (useOutOfProcessBuild()) { compileScope = projectScope; } else { CompileScope scopeWithArtifacts = ArtifactCompileScope.createScopeWithArtifacts(projectScope, ArtifactUtil.getArtifactWithOutputPaths(myProject), false); compileScope = addAdditionalRoots(scopeWithArtifacts, ALL_EXCEPT_SOURCE_PROCESSING); } doRebuild(callback, null, true, compileScope); } public void make(CompileScope scope, CompileStatusNotification callback) { if (!useOutOfProcessBuild()) { scope = addAdditionalRoots(scope, ALL_EXCEPT_SOURCE_PROCESSING); } if (validateCompilerConfiguration(scope, false)) { startup(scope, false, false, callback, null, true); } else { callback.finished(true, 0, 0, DummyCompileContext.getInstance()); } } public boolean isUpToDate(CompileScope scope) { if (LOG.isDebugEnabled()) { LOG.debug("isUpToDate operation started"); } if (!useOutOfProcessBuild()) { scope = addAdditionalRoots(scope, ALL_EXCEPT_SOURCE_PROCESSING); } final CompilerTask task = new CompilerTask(myProject, "Classes up-to-date check", true, false, false, isCompilationStartedAutomatically(scope)); final DependencyCache cache = useOutOfProcessBuild()? null : createDependencyCache(); final CompileContextImpl compileContext = new CompileContextImpl(myProject, task, scope, cache, true, false); if (!useOutOfProcessBuild()) { checkCachesVersion(compileContext, ManagingFS.getInstance().getCreationTimestamp()); if (compileContext.isRebuildRequested()) { if (LOG.isDebugEnabled()) { LOG.debug("Rebuild requested, up-to-date=false"); } return false; } for (Map.Entry<Pair<IntermediateOutputCompiler, Module>, Pair<VirtualFile, VirtualFile>> entry : myGenerationCompilerModuleToOutputDirMap.entrySet()) { final Pair<VirtualFile, VirtualFile> outputs = entry.getValue(); final Pair<IntermediateOutputCompiler, Module> key = entry.getKey(); final Module module = key.getSecond(); compileContext.assignModule(outputs.getFirst(), module, false, key.getFirst()); compileContext.assignModule(outputs.getSecond(), module, true, key.getFirst()); } } final Ref<ExitStatus> result = new Ref<ExitStatus>(); final Runnable compileWork; if (useOutOfProcessBuild()) { compileWork = new Runnable() { public void run() { final ProgressIndicator indicator = compileContext.getProgressIndicator(); if (indicator.isCanceled() || myProject.isDisposed()) { return; } try { final RequestFuture future = compileInExternalProcess(compileContext, true); if (future != null) { while (!future.waitFor(200L , TimeUnit.MILLISECONDS)) { if (indicator.isCanceled()) { future.cancel(false); } } } } catch (Throwable e) { LOG.error(e); } finally { result.set(COMPILE_SERVER_BUILD_STATUS.get(compileContext)); CompilerCacheManager.getInstance(myProject).flushCaches(); } } }; } else { compileWork = new Runnable() { public void run() { try { myAllOutputDirectories = getAllOutputDirectories(compileContext); // need this for updating zip archives experiment, uncomment if the feature is turned on //myOutputFinder = new OutputPathFinder(myAllOutputDirectories); result.set(doCompile(compileContext, false, false, true)); } finally { CompilerCacheManager.getInstance(myProject).flushCaches(); } } }; } task.start(compileWork, null); if (LOG.isDebugEnabled()) { LOG.debug("isUpToDate operation finished"); } return ExitStatus.UP_TO_DATE.equals(result.get()); } private DependencyCache createDependencyCache() { return new DependencyCache(myCachesDirectoryPath + File.separator + ".dependency-info"); } public void compile(CompileScope scope, CompileStatusNotification callback, boolean clearingOutputDirsPossible) { myShouldClearOutputDirectory &= clearingOutputDirsPossible; if (containsFileIndexScopes(scope)) { scope = addAdditionalRoots(scope, ALL_EXCEPT_SOURCE_PROCESSING); } if (validateCompilerConfiguration(scope, false)) { startup(scope, false, true, callback, null, true); } else { callback.finished(true, 0, 0, DummyCompileContext.getInstance()); } } private static boolean containsFileIndexScopes(CompileScope scope) { if (scope instanceof CompositeScope) { for (CompileScope childScope : ((CompositeScope)scope).getScopes()) { if (containsFileIndexScopes(childScope)) { return true; } } } return scope instanceof FileIndexCompileScope; } private static class CompileStatus { final int CACHE_FORMAT_VERSION; final boolean COMPILATION_IN_PROGRESS; final long VFS_CREATION_STAMP; private CompileStatus(int cacheVersion, boolean isCompilationInProgress, long vfsStamp) { CACHE_FORMAT_VERSION = cacheVersion; COMPILATION_IN_PROGRESS = isCompilationInProgress; VFS_CREATION_STAMP = vfsStamp; } } private CompileStatus readStatus() { final boolean isInProgress = getLockFile().exists(); int version = -1; long vfsStamp = -1L; try { final File versionFile = new File(myCachesDirectoryPath, VERSION_FILE_NAME); DataInputStream in = new DataInputStream(new FileInputStream(versionFile)); try { version = in.readInt(); try { vfsStamp = in.readLong(); } catch (IOException ignored) { } } finally { in.close(); } } catch (FileNotFoundException e) { // ignore } catch (IOException e) { LOG.info(e); // may happen in case of IDEA crashed and the file is not written properly return null; } return new CompileStatus(version, isInProgress, vfsStamp); } private void writeStatus(CompileStatus status, CompileContext context) { final File statusFile = new File(myCachesDirectoryPath, VERSION_FILE_NAME); final File lockFile = getLockFile(); try { FileUtil.createIfDoesntExist(statusFile); DataOutputStream out = new DataOutputStream(new FileOutputStream(statusFile)); try { out.writeInt(status.CACHE_FORMAT_VERSION); out.writeLong(status.VFS_CREATION_STAMP); } finally { out.close(); } if (status.COMPILATION_IN_PROGRESS) { FileUtil.createIfDoesntExist(lockFile); } else { deleteFile(lockFile); } } catch (IOException e) { context.addMessage(CompilerMessageCategory.ERROR, CompilerBundle.message("compiler.error.exception", e.getMessage()), null, -1, -1); } } private File getLockFile() { return new File(CompilerPaths.getCompilerSystemDirectory(myProject), LOCK_FILE_NAME); } private void doRebuild(CompileStatusNotification callback, CompilerMessage message, final boolean checkCachesVersion, final CompileScope compileScope) { if (validateCompilerConfiguration(compileScope, !useOutOfProcessBuild())) { startup(compileScope, true, false, callback, message, checkCachesVersion); } else { callback.finished(true, 0, 0, DummyCompileContext.getInstance()); } } private CompileScope addAdditionalRoots(CompileScope originalScope, final CompilerFilter filter) { CompileScope scope = attachIntermediateOutputDirectories(originalScope, filter); final AdditionalCompileScopeProvider[] scopeProviders = Extensions.getExtensions(AdditionalCompileScopeProvider.EXTENSION_POINT_NAME); CompileScope baseScope = scope; for (AdditionalCompileScopeProvider scopeProvider : scopeProviders) { final CompileScope additionalScope = scopeProvider.getAdditionalScope(baseScope, filter, myProject); if (additionalScope != null) { scope = new CompositeScope(scope, additionalScope); } } return scope; } private CompileScope attachIntermediateOutputDirectories(CompileScope originalScope, CompilerFilter filter) { CompileScope scope = originalScope; final Set<Module> affected = new HashSet<Module>(Arrays.asList(originalScope.getAffectedModules())); for (Map.Entry<Pair<IntermediateOutputCompiler, Module>, Pair<VirtualFile, VirtualFile>> entry : myGenerationCompilerModuleToOutputDirMap.entrySet()) { final Module module = entry.getKey().getSecond(); if (affected.contains(module) && filter.acceptCompiler(entry.getKey().getFirst())) { final Pair<VirtualFile, VirtualFile> outputs = entry.getValue(); scope = new CompositeScope(scope, new FileSetCompileScope(Arrays.asList(outputs.getFirst(), outputs.getSecond()), new Module[]{module})); } } return scope; } public static void setCompilationStartedAutomatically(CompileScope scope) { //todo[nik] pass this option as a parameter to compile/make methods instead scope.putUserData(COMPILATION_STARTED_AUTOMATICALLY, Boolean.TRUE); } private static boolean isCompilationStartedAutomatically(CompileScope scope) { return Boolean.TRUE.equals(scope.getUserData(COMPILATION_STARTED_AUTOMATICALLY)); } private void attachAnnotationProcessorsOutputDirectories(CompileContextEx context) { final LocalFileSystem lfs = LocalFileSystem.getInstance(); final CompilerConfiguration config = CompilerConfiguration.getInstance(myProject); final Set<Module> affected = new HashSet<Module>(Arrays.asList(context.getCompileScope().getAffectedModules())); for (Module module : affected) { if (!config.getAnnotationProcessingConfiguration(module).isEnabled()) { continue; } final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); if (path == null) { continue; } final VirtualFile vFile = lfs.findFileByPath(path); if (vFile == null) { continue; } if (ModuleRootManager.getInstance(module).getFileIndex().isInSourceContent(vFile)) { // no need to add, is already marked as source continue; } context.addScope(new FileSetCompileScope(Collections.singletonList(vFile), new Module[]{module})); context.assignModule(vFile, module, false, null); } } @Nullable private RequestFuture compileInExternalProcess(final @NotNull CompileContextImpl compileContext, final boolean onlyCheckUpToDate) throws Exception { final CompileScope scope = compileContext.getCompileScope(); final Collection<String> paths = CompileScopeUtil.fetchFiles(compileContext); List<TargetTypeBuildScope> scopes = new ArrayList<TargetTypeBuildScope>(); final boolean forceBuild = !compileContext.isMake(); if (!compileContext.isRebuild() && !CompileScopeUtil.allProjectModulesAffected(compileContext)) { CompileScopeUtil.addScopesForModules(Arrays.asList(scope.getAffectedModules()), scopes, forceBuild); } else { scopes.addAll(CmdlineProtoUtil.createAllModulesScopes(forceBuild)); } if (paths.isEmpty()) { for (BuildTargetScopeProvider provider : BuildTargetScopeProvider.EP_NAME.getExtensions()) { scopes = CompileScopeUtil.mergeScopes(scopes, provider.getBuildTargetScopes(scope, myCompilerFilter, myProject, forceBuild)); } } // need to pass scope's user data to server final Map<String, String> builderParams; if (onlyCheckUpToDate) { builderParams = Collections.emptyMap(); } else { final Map<Key, Object> exported = scope.exportUserData(); if (!exported.isEmpty()) { builderParams = new HashMap<String, String>(); for (Map.Entry<Key, Object> entry : exported.entrySet()) { final String _key = entry.getKey().toString(); final String _value = entry.getValue().toString(); builderParams.put(_key, _value); } } else { builderParams = Collections.emptyMap(); } } final MessageBus messageBus = myProject.getMessageBus(); final MultiMap<String, Artifact> outputToArtifact = ArtifactCompilerUtil.containsArtifacts(scopes) ? ArtifactCompilerUtil.createOutputToArtifactMap(myProject) : null; final BuildManager buildManager = BuildManager.getInstance(); buildManager.cancelAutoMakeTasks(myProject); return buildManager.scheduleBuild(myProject, compileContext.isRebuild(), compileContext.isMake(), onlyCheckUpToDate, scopes, paths, builderParams, new DefaultMessageHandler(myProject) { @Override public void buildStarted(UUID sessionId) { } @Override public void sessionTerminated(final UUID sessionId) { if (compileContext.shouldUpdateProblemsView()) { final ProblemsView view = ProblemsViewImpl.SERVICE.getInstance(myProject); view.clearProgress(); view.clearOldMessages(compileContext.getCompileScope(), compileContext.getSessionId()); } } @Override public void handleFailure(UUID sessionId, CmdlineRemoteProto.Message.Failure failure) { compileContext.addMessage(CompilerMessageCategory.ERROR, failure.hasDescription()? failure.getDescription() : "", null, -1, -1); final String trace = failure.hasStacktrace()? failure.getStacktrace() : null; if (trace != null) { LOG.info(trace); } compileContext.putUserData(COMPILE_SERVER_BUILD_STATUS, ExitStatus.ERRORS); } @Override protected void handleCompileMessage(UUID sessionId, CmdlineRemoteProto.Message.BuilderMessage.CompileMessage message) { final CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind kind = message.getKind(); //System.out.println(compilerMessage.getText()); final String messageText = message.getText(); if (kind == CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.PROGRESS) { final ProgressIndicator indicator = compileContext.getProgressIndicator(); indicator.setText(messageText); if (message.hasDone()) { indicator.setFraction(message.getDone()); } } else { final CompilerMessageCategory category = kind == CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.ERROR ? CompilerMessageCategory.ERROR : kind == CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.WARNING ? CompilerMessageCategory.WARNING : CompilerMessageCategory.INFORMATION; String sourceFilePath = message.hasSourceFilePath() ? message.getSourceFilePath() : null; if (sourceFilePath != null) { sourceFilePath = FileUtil.toSystemIndependentName(sourceFilePath); } final long line = message.hasLine() ? message.getLine() : -1; final long column = message.hasColumn() ? message.getColumn() : -1; final String srcUrl = sourceFilePath != null ? VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, sourceFilePath) : null; compileContext.addMessage(category, messageText, srcUrl, (int)line, (int)column); } } @Override protected void handleBuildEvent(UUID sessionId, CmdlineRemoteProto.Message.BuilderMessage.BuildEvent event) { final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Type eventType = event.getEventType(); switch (eventType) { case FILES_GENERATED: final List<CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.GeneratedFile> generated = event.getGeneratedFilesList(); final CompilationStatusListener publisher = messageBus.syncPublisher(CompilerTopics.COMPILATION_STATUS); Set<String> writtenArtifactOutputPaths = outputToArtifact != null ? new THashSet<String>(FileUtil.PATH_HASHING_STRATEGY) : null; for (CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.GeneratedFile generatedFile : generated) { final String root = FileUtil.toSystemIndependentName(generatedFile.getOutputRoot()); final String relativePath = FileUtil.toSystemIndependentName(generatedFile.getRelativePath()); publisher.fileGenerated(root, relativePath); if (outputToArtifact != null) { Collection<Artifact> artifacts = outputToArtifact.get(root); if (!artifacts.isEmpty()) { for (Artifact artifact : artifacts) { ArtifactsCompiler.addChangedArtifact(compileContext, artifact); } writtenArtifactOutputPaths.add(FileUtil.toSystemDependentName(DeploymentUtil.appendToPath(root, relativePath))); } } } if (writtenArtifactOutputPaths != null && !writtenArtifactOutputPaths.isEmpty()) { ArtifactsCompiler.addWrittenPaths(compileContext, writtenArtifactOutputPaths); } break; case BUILD_COMPLETED: ExitStatus status = ExitStatus.SUCCESS; if (event.hasCompletionStatus()) { final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status completionStatus = event.getCompletionStatus(); switch (completionStatus) { case CANCELED: status = ExitStatus.CANCELLED; break; case ERRORS: status = ExitStatus.ERRORS; break; case SUCCESS: status = ExitStatus.SUCCESS; break; case UP_TO_DATE: status = ExitStatus.UP_TO_DATE; break; } } compileContext.putUserDataIfAbsent(COMPILE_SERVER_BUILD_STATUS, status); break; case CUSTOM_BUILDER_MESSAGE: if (event.hasCustomBuilderMessage()) { CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.CustomBuilderMessage message = event.getCustomBuilderMessage(); messageBus.syncPublisher(CustomBuilderMessageHandler.TOPIC).messageReceived(message.getBuilderId(), message.getMessageType(), message.getMessageText()); } break; } } }); } private static final Key<ExitStatus> COMPILE_SERVER_BUILD_STATUS = Key.create("COMPILE_SERVER_BUILD_STATUS"); private void startup(final CompileScope scope, final boolean isRebuild, final boolean forceCompile, final CompileStatusNotification callback, final CompilerMessage message, final boolean checkCachesVersion) { ApplicationManager.getApplication().assertIsDispatchThread(); final boolean useExtProcessBuild = useOutOfProcessBuild(); final String contentName = forceCompile ? CompilerBundle.message("compiler.content.name.compile") : CompilerBundle.message("compiler.content.name.make"); final CompilerTask compileTask = new CompilerTask(myProject, contentName, ApplicationManager.getApplication().isUnitTestMode(), true, true, isCompilationStartedAutomatically(scope)); StatusBar.Info.set("", myProject, "Compiler"); if (useExtProcessBuild) { // ensure the project model seen by build process is up-to-date myProject.save(); if (!ApplicationManager.getApplication().isUnitTestMode()) { ApplicationManager.getApplication().saveSettings(); } } PsiDocumentManager.getInstance(myProject).commitAllDocuments(); FileDocumentManager.getInstance().saveAllDocuments(); final DependencyCache dependencyCache = useExtProcessBuild ? null: createDependencyCache(); final CompileContextImpl compileContext = new CompileContextImpl(myProject, compileTask, scope, dependencyCache, !isRebuild && !forceCompile, isRebuild); if (!useExtProcessBuild) { for (Map.Entry<Pair<IntermediateOutputCompiler, Module>, Pair<VirtualFile, VirtualFile>> entry : myGenerationCompilerModuleToOutputDirMap.entrySet()) { final Pair<VirtualFile, VirtualFile> outputs = entry.getValue(); final Pair<IntermediateOutputCompiler, Module> key = entry.getKey(); final Module module = key.getSecond(); compileContext.assignModule(outputs.getFirst(), module, false, key.getFirst()); compileContext.assignModule(outputs.getSecond(), module, true, key.getFirst()); } attachAnnotationProcessorsOutputDirectories(compileContext); } final Runnable compileWork; if (useExtProcessBuild) { compileWork = new Runnable() { public void run() { final ProgressIndicator indicator = compileContext.getProgressIndicator(); if (indicator.isCanceled() || myProject.isDisposed()) { if (callback != null) { callback.finished(true, 0, 0, compileContext); } return; } try { LOG.info("COMPILATION STARTED (BUILD PROCESS)"); if (message != null) { compileContext.addMessage(message); } final boolean beforeTasksOk = executeCompileTasks(compileContext, true); final int errorCount = compileContext.getMessageCount(CompilerMessageCategory.ERROR); if (!beforeTasksOk || errorCount > 0) { COMPILE_SERVER_BUILD_STATUS.set(compileContext, errorCount > 0? ExitStatus.ERRORS : ExitStatus.CANCELLED); return; } final RequestFuture future = compileInExternalProcess(compileContext, false); if (future != null) { while (!future.waitFor(200L , TimeUnit.MILLISECONDS)) { if (indicator.isCanceled()) { future.cancel(false); } } if (!executeCompileTasks(compileContext, false)) { COMPILE_SERVER_BUILD_STATUS.set(compileContext, ExitStatus.CANCELLED); } if (compileContext.getMessageCount(CompilerMessageCategory.ERROR) > 0) { COMPILE_SERVER_BUILD_STATUS.set(compileContext, ExitStatus.ERRORS); } } } catch (Throwable e) { LOG.error(e); // todo } finally { CompilerCacheManager.getInstance(myProject).flushCaches(); final long duration = notifyCompilationCompleted(compileContext, callback, COMPILE_SERVER_BUILD_STATUS.get(compileContext), true); CompilerUtil.logDuration( "\tCOMPILATION FINISHED (BUILD PROCESS); Errors: " + compileContext.getMessageCount(CompilerMessageCategory.ERROR) + "; warnings: " + compileContext.getMessageCount(CompilerMessageCategory.WARNING), duration ); } } }; } else { compileWork = new Runnable() { public void run() { if (compileContext.getProgressIndicator().isCanceled()) { if (callback != null) { callback.finished(true, 0, 0, compileContext); } return; } try { if (myProject.isDisposed()) { return; } LOG.info("COMPILATION STARTED"); if (message != null) { compileContext.addMessage(message); } TranslatingCompilerFilesMonitor.getInstance().ensureInitializationCompleted(myProject, compileContext.getProgressIndicator()); doCompile(compileContext, isRebuild, forceCompile, callback, checkCachesVersion); } finally { FileUtil.delete(CompilerPaths.getRebuildMarkerFile(myProject)); } } }; } compileTask.start(compileWork, new Runnable() { public void run() { if (isRebuild) { final int rv = Messages.showOkCancelDialog( myProject, "You are about to rebuild the whole project.\nRun 'Make Project' instead?", "Confirm Project Rebuild", "Make", "Rebuild", Messages.getQuestionIcon() ); if (rv == 0 /*yes, please, do run make*/) { startup(scope, false, false, callback, null, checkCachesVersion); return; } } startup(scope, isRebuild, forceCompile, callback, message, checkCachesVersion); } }); } @Nullable @TestOnly public static ExitStatus getExternalBuildExitStatus(CompileContext context) { return context.getUserData(COMPILE_SERVER_BUILD_STATUS); } private void doCompile(final CompileContextImpl compileContext, final boolean isRebuild, final boolean forceCompile, final CompileStatusNotification callback, final boolean checkCachesVersion) { ExitStatus status = ExitStatus.ERRORS; boolean wereExceptions = false; final long vfsTimestamp = (ManagingFS.getInstance()).getCreationTimestamp(); try { if (checkCachesVersion) { checkCachesVersion(compileContext, vfsTimestamp); if (compileContext.isRebuildRequested()) { return; } } writeStatus(new CompileStatus(CompilerConfigurationImpl.DEPENDENCY_FORMAT_VERSION, true, vfsTimestamp), compileContext); if (compileContext.getMessageCount(CompilerMessageCategory.ERROR) > 0) { return; } myAllOutputDirectories = getAllOutputDirectories(compileContext); status = doCompile(compileContext, isRebuild, forceCompile, false); } catch (Throwable ex) { if (ApplicationManager.getApplication().isUnitTestMode()) { throw new RuntimeException(ex); } wereExceptions = true; final PluginId pluginId = IdeErrorsDialog.findPluginId(ex); final StringBuilder message = new StringBuilder(); message.append("Internal error"); if (pluginId != null) { message.append(" (Plugin: ").append(pluginId).append(")"); } message.append(": ").append(ex.getMessage()); compileContext.addMessage(CompilerMessageCategory.ERROR, message.toString(), null, -1, -1); if (pluginId != null) { throw new PluginException(ex, pluginId); } throw new RuntimeException(ex); } finally { dropDependencyCache(compileContext); CompilerCacheManager.getInstance(myProject).flushCaches(); if (compileContext.isRebuildRequested()) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { final CompilerMessageImpl msg = new CompilerMessageImpl(myProject, CompilerMessageCategory.INFORMATION, compileContext.getRebuildReason()); doRebuild(callback, msg, false, compileContext.getCompileScope()); } }, ModalityState.NON_MODAL); } else { if (!myProject.isDisposed()) { writeStatus(new CompileStatus(CompilerConfigurationImpl.DEPENDENCY_FORMAT_VERSION, wereExceptions, vfsTimestamp), compileContext); } final long duration = notifyCompilationCompleted(compileContext, callback, status, false); CompilerUtil.logDuration( "\tCOMPILATION FINISHED; Errors: " + compileContext.getMessageCount(CompilerMessageCategory.ERROR) + "; warnings: " + compileContext.getMessageCount(CompilerMessageCategory.WARNING), duration ); } } } /** @noinspection SSBasedInspection*/ private long notifyCompilationCompleted(final CompileContextImpl compileContext, final CompileStatusNotification callback, final ExitStatus _status, final boolean refreshOutputRoots) { final long duration = System.currentTimeMillis() - compileContext.getStartCompilationStamp(); if (refreshOutputRoots) { // refresh on output roots is required in order for the order enumerator to see all roots via VFS final Set<File> outputs = new HashSet<File>(); final Module[] affectedModules = compileContext.getCompileScope().getAffectedModules(); for (final String path : CompilerPathsEx.getOutputPaths(affectedModules)) { outputs.add(new File(path)); } final LocalFileSystem lfs = LocalFileSystem.getInstance(); if (!outputs.isEmpty()) { final ProgressIndicator indicator = compileContext.getProgressIndicator(); indicator.setText("Synchronizing output directories..."); lfs.refreshIoFiles(outputs, false, false, null); indicator.setText(""); } if (compileContext.isAnnotationProcessorsEnabled()) { final Set<VirtualFile> genSourceRoots = new HashSet<VirtualFile>(); final CompilerConfiguration config = CompilerConfiguration.getInstance(myProject); for (Module module : affectedModules) { if (config.getAnnotationProcessingConfiguration(module).isEnabled()) { final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); if (path != null) { final File genPath = new File(path); final VirtualFile vFile = lfs.findFileByIoFile(genPath); if (vFile != null && ModuleRootManager.getInstance(module).getFileIndex().isInSourceContent(vFile)) { genSourceRoots.add(vFile); } } } } if (!genSourceRoots.isEmpty()) { // refresh generates source roots asynchronously; needed for error highlighting update lfs.refreshFiles(genSourceRoots, true, true, null); } } } SwingUtilities.invokeLater(new Runnable() { public void run() { int errorCount = 0; int warningCount = 0; try { errorCount = compileContext.getMessageCount(CompilerMessageCategory.ERROR); warningCount = compileContext.getMessageCount(CompilerMessageCategory.WARNING); if (!myProject.isDisposed()) { final String statusMessage = createStatusMessage(_status, warningCount, errorCount, duration); final MessageType messageType = errorCount > 0 ? MessageType.ERROR : warningCount > 0 ? MessageType.WARNING : MessageType.INFO; if (duration > ONE_MINUTE_MS) { ToolWindowManager.getInstance(myProject).notifyByBalloon(ToolWindowId.MESSAGES_WINDOW, messageType, statusMessage); } CompilerManager.NOTIFICATION_GROUP.createNotification(statusMessage, messageType).notify(myProject); if (_status != ExitStatus.UP_TO_DATE && compileContext.getMessageCount(null) > 0) { compileContext.addMessage(CompilerMessageCategory.INFORMATION, statusMessage, null, -1, -1); } } } finally { if (callback != null) { callback.finished(_status == ExitStatus.CANCELLED, errorCount, warningCount, compileContext); } } } }); return duration; } private void checkCachesVersion(final CompileContextImpl compileContext, final long currentVFSTimestamp) { if (CompilerPaths.getRebuildMarkerFile(compileContext.getProject()).exists()) { compileContext.requestRebuildNextTime("Compiler caches are out of date, project rebuild is required"); return; } final CompileStatus compileStatus = readStatus(); if (compileStatus == null) { compileContext.requestRebuildNextTime(CompilerBundle.message("error.compiler.caches.corrupted")); } else if (compileStatus.CACHE_FORMAT_VERSION != -1 && compileStatus.CACHE_FORMAT_VERSION != CompilerConfigurationImpl.DEPENDENCY_FORMAT_VERSION) { compileContext.requestRebuildNextTime(CompilerBundle.message("error.caches.old.format")); } else if (compileStatus.COMPILATION_IN_PROGRESS) { compileContext.requestRebuildNextTime(CompilerBundle.message("error.previous.compilation.failed")); } else if (compileStatus.VFS_CREATION_STAMP >= 0L){ if (currentVFSTimestamp != compileStatus.VFS_CREATION_STAMP) { compileContext.requestRebuildNextTime(CompilerBundle.message("error.vfs.was.rebuilt")); } } } private static String createStatusMessage(final ExitStatus status, final int warningCount, final int errorCount, long duration) { String message; if (status == ExitStatus.CANCELLED) { message = CompilerBundle.message("status.compilation.aborted"); } else if (status == ExitStatus.UP_TO_DATE) { message = CompilerBundle.message("status.all.up.to.date"); } else { if (status == ExitStatus.SUCCESS) { message = warningCount > 0 ? CompilerBundle.message("status.compilation.completed.successfully.with.warnings", warningCount) : CompilerBundle.message("status.compilation.completed.successfully"); } else { message = CompilerBundle.message("status.compilation.completed.successfully.with.warnings.and.errors", errorCount, warningCount); } message = message + " in " + Utils.formatDuration(duration); } return message; } private ExitStatus doCompile(final CompileContextEx context, boolean isRebuild, final boolean forceCompile, final boolean onlyCheckStatus) { try { if (isRebuild) { deleteAll(context); } else if (forceCompile) { if (myShouldClearOutputDirectory) { clearAffectedOutputPathsIfPossible(context); } } if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { if (LOG.isDebugEnabled()) { logErrorMessages(context); } return ExitStatus.ERRORS; } if (!onlyCheckStatus) { if (!executeCompileTasks(context, true)) { if (LOG.isDebugEnabled()) { LOG.debug("Compilation cancelled"); } return ExitStatus.CANCELLED; } } if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { if (LOG.isDebugEnabled()) { logErrorMessages(context); } return ExitStatus.ERRORS; } boolean needRecalcOutputDirs = false; if (Registry.is(PROP_PERFORM_INITIAL_REFRESH) || !Boolean.valueOf(REFRESH_DONE_KEY.get(myProject, Boolean.FALSE))) { REFRESH_DONE_KEY.set(myProject, Boolean.TRUE); final long refreshStart = System.currentTimeMillis(); //need this to make sure the VFS is built final List<VirtualFile> outputsToRefresh = new ArrayList<VirtualFile>(); final VirtualFile[] all = context.getAllOutputDirectories(); final ProgressIndicator progressIndicator = context.getProgressIndicator(); //final int totalCount = all.length + myGenerationCompilerModuleToOutputDirMap.size() * 2; progressIndicator.pushState(); progressIndicator.setText("Inspecting output directories..."); try { for (VirtualFile output : all) { if (output.isValid()) { walkChildren(output, context); } else { needRecalcOutputDirs = true; final File file = new File(output.getPath()); if (!file.exists()) { final boolean created = file.mkdirs(); if (!created) { context.addMessage(CompilerMessageCategory.ERROR, "Failed to create output directory " + file.getPath(), null, 0, 0); return ExitStatus.ERRORS; } } output = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); if (output == null) { context.addMessage(CompilerMessageCategory.ERROR, "Failed to locate output directory " + file.getPath(), null, 0, 0); return ExitStatus.ERRORS; } } outputsToRefresh.add(output); } for (Pair<IntermediateOutputCompiler, Module> pair : myGenerationCompilerModuleToOutputDirMap.keySet()) { final Pair<VirtualFile, VirtualFile> generated = myGenerationCompilerModuleToOutputDirMap.get(pair); walkChildren(generated.getFirst(), context); outputsToRefresh.add(generated.getFirst()); walkChildren(generated.getSecond(), context); outputsToRefresh.add(generated.getSecond()); } RefreshQueue.getInstance().refresh(false, true, null, outputsToRefresh); if (progressIndicator.isCanceled()) { return ExitStatus.CANCELLED; } } finally { progressIndicator.popState(); } final long initialRefreshTime = System.currentTimeMillis() - refreshStart; CompilerUtil.logDuration("Initial VFS refresh", initialRefreshTime); } //DumbService.getInstance(myProject).waitForSmartMode(); final Semaphore semaphore = new Semaphore(); semaphore.down(); DumbService.getInstance(myProject).runWhenSmart(new Runnable() { public void run() { semaphore.up(); } }); while (!semaphore.waitFor(500)) { if (context.getProgressIndicator().isCanceled()) { return ExitStatus.CANCELLED; } } if (needRecalcOutputDirs) { context.recalculateOutputDirs(); } boolean didSomething = false; final CompilerManager compilerManager = CompilerManager.getInstance(myProject); GenericCompilerRunner runner = new GenericCompilerRunner(context, isRebuild, onlyCheckStatus, compilerManager.getCompilers(GenericCompiler.class, myCompilerFilter)); try { didSomething |= generateSources(compilerManager, context, forceCompile, onlyCheckStatus); didSomething |= invokeFileProcessingCompilers(compilerManager, context, SourceInstrumentingCompiler.class, FILE_PROCESSING_COMPILER_ADAPTER_FACTORY, forceCompile, true, onlyCheckStatus); didSomething |= invokeFileProcessingCompilers(compilerManager, context, SourceProcessingCompiler.class, FILE_PROCESSING_COMPILER_ADAPTER_FACTORY, forceCompile, true, onlyCheckStatus); final CompileScope intermediateSources = attachIntermediateOutputDirectories(new CompositeScope(CompileScope.EMPTY_ARRAY) { @NotNull public Module[] getAffectedModules() { return context.getCompileScope().getAffectedModules(); } }, SOURCE_PROCESSING_ONLY); context.addScope(intermediateSources); didSomething |= translate(context, compilerManager, forceCompile, isRebuild, onlyCheckStatus); didSomething |= invokeFileProcessingCompilers(compilerManager, context, ClassInstrumentingCompiler.class, FILE_PROCESSING_COMPILER_ADAPTER_FACTORY, isRebuild, false, onlyCheckStatus); didSomething |= runner.invokeCompilers(GenericCompiler.CompileOrderPlace.CLASS_INSTRUMENTING); // explicitly passing forceCompile = false because in scopes that is narrower than ProjectScope it is impossible // to understand whether the class to be processed is in scope or not. Otherwise compiler may process its items even if // there were changes in completely independent files. didSomething |= invokeFileProcessingCompilers(compilerManager, context, ClassPostProcessingCompiler.class, FILE_PROCESSING_COMPILER_ADAPTER_FACTORY, isRebuild, false, onlyCheckStatus); didSomething |= runner.invokeCompilers(GenericCompiler.CompileOrderPlace.CLASS_POST_PROCESSING); didSomething |= invokeFileProcessingCompilers(compilerManager, context, PackagingCompiler.class, FILE_PACKAGING_COMPILER_ADAPTER_FACTORY, isRebuild, false, onlyCheckStatus); didSomething |= runner.invokeCompilers(GenericCompiler.CompileOrderPlace.PACKAGING); didSomething |= invokeFileProcessingCompilers(compilerManager, context, Validator.class, FILE_PROCESSING_COMPILER_ADAPTER_FACTORY, forceCompile, true, onlyCheckStatus); didSomething |= runner.invokeCompilers(GenericCompiler.CompileOrderPlace.VALIDATING); } catch (ExitException e) { if (LOG.isDebugEnabled()) { LOG.debug(e); logErrorMessages(context); } return e.getExitStatus(); } finally { // drop in case it has not been dropped yet. dropDependencyCache(context); final VirtualFile[] allOutputDirs = context.getAllOutputDirectories(); if (didSomething && GENERATE_CLASSPATH_INDEX) { CompilerUtil.runInContext(context, "Generating classpath index...", new ThrowableRunnable<RuntimeException>(){ public void run() { int count = 0; for (VirtualFile file : allOutputDirs) { context.getProgressIndicator().setFraction((double)++count / allOutputDirs.length); createClasspathIndex(file); } } }); } } if (!onlyCheckStatus) { if (!executeCompileTasks(context, false)) { return ExitStatus.CANCELLED; } final int constantSearchesCount = ChangedConstantsDependencyProcessor.getConstantSearchesCount(context); LOG.debug("Constants searches: " + constantSearchesCount); } if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { if (LOG.isDebugEnabled()) { logErrorMessages(context); } return ExitStatus.ERRORS; } if (!didSomething) { return ExitStatus.UP_TO_DATE; } return ExitStatus.SUCCESS; } catch (ProcessCanceledException e) { return ExitStatus.CANCELLED; } } private void clearAffectedOutputPathsIfPossible(final CompileContextEx context) { final List<File> scopeOutputs = new ReadAction<List<File>>() { protected void run(final Result<List<File>> result) { final MultiMap<File, Module> outputToModulesMap = new MultiMap<File, Module>(); for (Module module : ModuleManager.getInstance(myProject).getModules()) { final CompilerModuleExtension compilerModuleExtension = CompilerModuleExtension.getInstance(module); if (compilerModuleExtension == null) { continue; } final String outputPathUrl = compilerModuleExtension.getCompilerOutputUrl(); if (outputPathUrl != null) { final String path = VirtualFileManager.extractPath(outputPathUrl); outputToModulesMap.putValue(new File(path), module); } final String outputPathForTestsUrl = compilerModuleExtension.getCompilerOutputUrlForTests(); if (outputPathForTestsUrl != null) { final String path = VirtualFileManager.extractPath(outputPathForTestsUrl); outputToModulesMap.putValue(new File(path), module); } } final Set<Module> affectedModules = new HashSet<Module>(Arrays.asList(context.getCompileScope().getAffectedModules())); List<File> scopeOutputs = new ArrayList<File>(affectedModules.size() * 2); for (File output : outputToModulesMap.keySet()) { if (affectedModules.containsAll(outputToModulesMap.get(output))) { scopeOutputs.add(output); } } final Set<Artifact> artifactsToBuild = ArtifactCompileScope.getArtifactsToBuild(myProject, context.getCompileScope(), true); for (Artifact artifact : artifactsToBuild) { final String outputFilePath = ((ArtifactImpl)artifact).getOutputDirectoryPathToCleanOnRebuild(); if (outputFilePath != null) { scopeOutputs.add(new File(FileUtil.toSystemDependentName(outputFilePath))); } } result.setResult(scopeOutputs); } }.execute().getResultObject(); if (scopeOutputs.size() > 0) { CompilerUtil.runInContext(context, CompilerBundle.message("progress.clearing.output"), new ThrowableRunnable<RuntimeException>() { public void run() { CompilerUtil.clearOutputDirectories(scopeOutputs); } }); } } private static void logErrorMessages(final CompileContext context) { final CompilerMessage[] errors = context.getMessages(CompilerMessageCategory.ERROR); if (errors.length > 0) { LOG.debug("Errors reported: "); for (CompilerMessage error : errors) { LOG.debug("\t" + error.getMessage()); } } } private static void walkChildren(VirtualFile from, final CompileContext context) { VfsUtilCore.visitChildrenRecursively(from, new VirtualFileVisitor() { @Override public boolean visitFile(@NotNull VirtualFile file) { if (file.isDirectory()) { context.getProgressIndicator().checkCanceled(); context.getProgressIndicator().setText2(file.getPresentableUrl()); } return true; } }); } private static void createClasspathIndex(final VirtualFile file) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(new File(VfsUtilCore.virtualToIoFile(file), "classpath.index"))); try { writeIndex(writer, file, file); } finally { writer.close(); } } catch (IOException e) { // Ignore. Failed to create optional classpath index } } private static void writeIndex(final BufferedWriter writer, final VirtualFile root, final VirtualFile file) throws IOException { VfsUtilCore.visitChildrenRecursively(file, new VirtualFileVisitor() { @Override public boolean visitFile(@NotNull VirtualFile file) { try { writer.write(VfsUtilCore.getRelativePath(file, root, '/')); writer.write('\n'); return true; } catch (IOException e) { throw new VisitorException(e); } } }, IOException.class); } private static void dropDependencyCache(final CompileContextEx context) { CompilerUtil.runInContext(context, CompilerBundle.message("progress.saving.caches"), new ThrowableRunnable<RuntimeException>(){ public void run() { context.getDependencyCache().resetState(); } }); } private boolean generateSources(final CompilerManager compilerManager, CompileContextEx context, final boolean forceCompile, final boolean onlyCheckStatus) throws ExitException { boolean didSomething = false; final SourceGeneratingCompiler[] sourceGenerators = compilerManager.getCompilers(SourceGeneratingCompiler.class, myCompilerFilter); for (final SourceGeneratingCompiler sourceGenerator : sourceGenerators) { if (context.getProgressIndicator().isCanceled()) { throw new ExitException(ExitStatus.CANCELLED); } final boolean generatedSomething = generateOutput(context, sourceGenerator, forceCompile, onlyCheckStatus); if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { throw new ExitException(ExitStatus.ERRORS); } didSomething |= generatedSomething; } return didSomething; } private boolean translate(final CompileContextEx context, final CompilerManager compilerManager, final boolean forceCompile, boolean isRebuild, final boolean onlyCheckStatus) throws ExitException { boolean didSomething = false; final TranslatingCompiler[] translators = compilerManager.getCompilers(TranslatingCompiler.class, myCompilerFilter); final List<Chunk<Module>> sortedChunks = Collections.unmodifiableList(ApplicationManager.getApplication().runReadAction(new Computable<List<Chunk<Module>>>() { public List<Chunk<Module>> compute() { final ModuleManager moduleManager = ModuleManager.getInstance(myProject); return ModuleCompilerUtil.getSortedModuleChunks(myProject, Arrays.asList(moduleManager.getModules())); } })); final DumbService dumbService = DumbService.getInstance(myProject); try { final Set<Module> processedModules = new HashSet<Module>(); VirtualFile[] snapshot = null; final Map<Chunk<Module>, Collection<VirtualFile>> chunkMap = new HashMap<Chunk<Module>, Collection<VirtualFile>>(); int total = 0; int processed = 0; for (final Chunk<Module> currentChunk : sortedChunks) { final TranslatorsOutputSink sink = new TranslatorsOutputSink(context, translators); final Set<FileType> generatedTypes = new HashSet<FileType>(); Collection<VirtualFile> chunkFiles = chunkMap.get(currentChunk); final Set<VirtualFile> filesToRecompile = new HashSet<VirtualFile>(); final Set<VirtualFile> allDependent = new HashSet<VirtualFile>(); try { int round = 0; boolean compiledSomethingForThisChunk = false; Collection<VirtualFile> dependentFiles = Collections.emptyList(); final Function<Pair<int[], Set<VirtualFile>>, Pair<int[], Set<VirtualFile>>> dependencyFilter = new DependentClassesCumulativeFilter(); do { for (int currentCompiler = 0, translatorsLength = translators.length; currentCompiler < translatorsLength; currentCompiler++) { sink.setCurrentCompilerIndex(currentCompiler); final TranslatingCompiler compiler = translators[currentCompiler]; if (context.getProgressIndicator().isCanceled()) { throw new ExitException(ExitStatus.CANCELLED); } dumbService.waitForSmartMode(); if (snapshot == null || ContainerUtil.intersects(generatedTypes, compilerManager.getRegisteredInputTypes(compiler))) { // rescan snapshot if previously generated files may influence the input of this compiler final Set<VirtualFile> prevSnapshot = round > 0 && snapshot != null? new HashSet<VirtualFile>(Arrays.asList(snapshot)) : Collections.<VirtualFile>emptySet(); snapshot = ApplicationManager.getApplication().runReadAction(new Computable<VirtualFile[]>() { public VirtualFile[] compute() { return context.getCompileScope().getFiles(null, true); } }); recalculateChunkToFilesMap(context, sortedChunks, snapshot, chunkMap); if (round == 0) { chunkFiles = chunkMap.get(currentChunk); } else { final Set<VirtualFile> newFiles = new HashSet<VirtualFile>(chunkMap.get(currentChunk)); newFiles.removeAll(prevSnapshot); newFiles.removeAll(chunkFiles); if (!newFiles.isEmpty()) { final ArrayList<VirtualFile> merged = new ArrayList<VirtualFile>(chunkFiles.size() + newFiles.size()); merged.addAll(chunkFiles); merged.addAll(newFiles); chunkFiles = merged; } } total = snapshot.length * translatorsLength; } final CompileContextEx _context; if (compiler instanceof IntermediateOutputCompiler) { // wrap compile context so that output goes into intermediate directories final IntermediateOutputCompiler _compiler = (IntermediateOutputCompiler)compiler; _context = new CompileContextExProxy(context) { public VirtualFile getModuleOutputDirectory(final Module module) { return getGenerationOutputDir(_compiler, module, false); } public VirtualFile getModuleOutputDirectoryForTests(final Module module) { return getGenerationOutputDir(_compiler, module, true); } }; } else { _context = context; } final boolean compiledSomething = compileSources(_context, currentChunk, compiler, chunkFiles, round == 0? forceCompile : true, isRebuild, onlyCheckStatus, sink); processed += chunkFiles.size(); _context.getProgressIndicator().setFraction(((double)processed) / total); if (compiledSomething) { generatedTypes.addAll(compilerManager.getRegisteredOutputTypes(compiler)); } didSomething |= compiledSomething; compiledSomethingForThisChunk |= didSomething; if (_context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { break; // break the loop over compilers } } final boolean hasUnprocessedTraverseRoots = context.getDependencyCache().hasUnprocessedTraverseRoots(); if (!isRebuild && (compiledSomethingForThisChunk || hasUnprocessedTraverseRoots)) { final Set<VirtualFile> compiledWithErrors = CacheUtils.getFilesCompiledWithErrors(context); filesToRecompile.removeAll(sink.getCompiledSources()); filesToRecompile.addAll(compiledWithErrors); dependentFiles = CacheUtils.findDependentFiles(context, compiledWithErrors, dependencyFilter); if (!processedModules.isEmpty()) { for (Iterator<VirtualFile> it = dependentFiles.iterator(); it.hasNext();) { final VirtualFile next = it.next(); final Module module = context.getModuleByFile(next); if (module != null && processedModules.contains(module)) { it.remove(); } } } if (ourDebugMode) { if (!dependentFiles.isEmpty()) { for (VirtualFile dependentFile : dependentFiles) { System.out.println("FOUND TO RECOMPILE: " + dependentFile.getPresentableUrl()); } } else { System.out.println("NO FILES TO RECOMPILE"); } } if (!dependentFiles.isEmpty()) { filesToRecompile.addAll(dependentFiles); allDependent.addAll(dependentFiles); if (context.getProgressIndicator().isCanceled() || context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { break; } final List<VirtualFile> filesInScope = getFilesInScope(context, currentChunk, dependentFiles); if (filesInScope.isEmpty()) { break; } context.getDependencyCache().clearTraverseRoots(); chunkFiles = filesInScope; total += chunkFiles.size() * translators.length; } didSomething |= (hasUnprocessedTraverseRoots != context.getDependencyCache().hasUnprocessedTraverseRoots()); } round++; } while (!dependentFiles.isEmpty() && context.getMessageCount(CompilerMessageCategory.ERROR) == 0); if (CompilerConfiguration.MAKE_ENABLED) { if (!context.getProgressIndicator().isCanceled()) { // when cancelled pretend nothing was compiled and next compile will compile everything from the scratch final ProgressIndicator indicator = context.getProgressIndicator(); final DependencyCache cache = context.getDependencyCache(); indicator.pushState(); indicator.setText(CompilerBundle.message("progress.updating.caches")); indicator.setText2(""); cache.update(); indicator.setText(CompilerBundle.message("progress.saving.caches")); cache.resetState(); processedModules.addAll(currentChunk.getNodes()); indicator.popState(); } } if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { throw new ExitException(ExitStatus.ERRORS); } } catch (CacheCorruptedException e) { LOG.info(e); context.requestRebuildNextTime(e.getMessage()); } finally { final int errorCount = context.getMessageCount(CompilerMessageCategory.ERROR); if (errorCount != 0) { filesToRecompile.addAll(allDependent); } if (filesToRecompile.size() > 0) { sink.add(null, Collections.<TranslatingCompiler.OutputItem>emptyList(), VfsUtilCore.toVirtualFileArray(filesToRecompile)); } if (errorCount == 0) { // perform update only if there were no errors, so it is guaranteed that the file was processd by all neccesary compilers sink.flushPostponedItems(); } } } } catch (ProcessCanceledException e) { ProgressManager.getInstance().executeNonCancelableSection(new Runnable() { public void run() { try { final Collection<VirtualFile> deps = CacheUtils.findDependentFiles(context, Collections.<VirtualFile>emptySet(), null); if (deps.size() > 0) { TranslatingCompilerFilesMonitor.getInstance().update(context, null, Collections.<TranslatingCompiler.OutputItem>emptyList(), VfsUtilCore.toVirtualFileArray(deps)); } } catch (IOException ignored) { LOG.info(ignored); } catch (CacheCorruptedException ignored) { LOG.info(ignored); } catch (ExitException e1) { LOG.info(e1); } } }); throw e; } finally { dropDependencyCache(context); if (didSomething) { TranslatingCompilerFilesMonitor.getInstance().updateOutputRootsLayout(myProject); } } return didSomething; } private static List<VirtualFile> getFilesInScope(final CompileContextEx context, final Chunk<Module> chunk, final Collection<VirtualFile> files) { final List<VirtualFile> filesInScope = new ArrayList<VirtualFile>(files.size()); ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { for (VirtualFile file : files) { if (context.getCompileScope().belongs(file.getUrl())) { final Module module = context.getModuleByFile(file); if (chunk.getNodes().contains(module)) { filesInScope.add(file); } } } } }); return filesInScope; } private static void recalculateChunkToFilesMap(CompileContextEx context, List<Chunk<Module>> allChunks, VirtualFile[] snapshot, Map<Chunk<Module>, Collection<VirtualFile>> chunkMap) { final Map<Module, List<VirtualFile>> moduleToFilesMap = CompilerUtil.buildModuleToFilesMap(context, snapshot); for (Chunk<Module> moduleChunk : allChunks) { List<VirtualFile> files = Collections.emptyList(); for (Module module : moduleChunk.getNodes()) { final List<VirtualFile> moduleFiles = moduleToFilesMap.get(module); if (moduleFiles != null) { files = ContainerUtil.concat(files, moduleFiles); } } chunkMap.put(moduleChunk, files); } } private interface FileProcessingCompilerAdapterFactory { FileProcessingCompilerAdapter create(CompileContext context, FileProcessingCompiler compiler); } private boolean invokeFileProcessingCompilers(final CompilerManager compilerManager, CompileContextEx context, Class<? extends FileProcessingCompiler> fileProcessingCompilerClass, FileProcessingCompilerAdapterFactory factory, boolean forceCompile, final boolean checkScope, final boolean onlyCheckStatus) throws ExitException { boolean didSomething = false; final FileProcessingCompiler[] compilers = compilerManager.getCompilers(fileProcessingCompilerClass, myCompilerFilter); if (compilers.length > 0) { try { CacheDeferredUpdater cacheUpdater = new CacheDeferredUpdater(); try { for (final FileProcessingCompiler compiler : compilers) { if (context.getProgressIndicator().isCanceled()) { throw new ExitException(ExitStatus.CANCELLED); } CompileContextEx _context = context; if (compiler instanceof IntermediateOutputCompiler) { final IntermediateOutputCompiler _compiler = (IntermediateOutputCompiler)compiler; _context = new CompileContextExProxy(context) { public VirtualFile getModuleOutputDirectory(final Module module) { return getGenerationOutputDir(_compiler, module, false); } public VirtualFile getModuleOutputDirectoryForTests(final Module module) { return getGenerationOutputDir(_compiler, module, true); } }; } final boolean processedSomething = processFiles(factory.create(_context, compiler), forceCompile, checkScope, onlyCheckStatus, cacheUpdater); if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { throw new ExitException(ExitStatus.ERRORS); } didSomething |= processedSomething; } } finally { cacheUpdater.doUpdate(); } } catch (IOException e) { LOG.info(e); context.requestRebuildNextTime(e.getMessage()); throw new ExitException(ExitStatus.ERRORS); } catch (ProcessCanceledException e) { throw e; } catch (ExitException e) { throw e; } catch (Exception e) { context.addMessage(CompilerMessageCategory.ERROR, CompilerBundle.message("compiler.error.exception", e.getMessage()), null, -1, -1); LOG.error(e); } } return didSomething; } private static Map<Module, Set<GeneratingCompiler.GenerationItem>> buildModuleToGenerationItemMap(GeneratingCompiler.GenerationItem[] items) { final Map<Module, Set<GeneratingCompiler.GenerationItem>> map = new HashMap<Module, Set<GeneratingCompiler.GenerationItem>>(); for (GeneratingCompiler.GenerationItem item : items) { Module module = item.getModule(); LOG.assertTrue(module != null); Set<GeneratingCompiler.GenerationItem> itemSet = map.get(module); if (itemSet == null) { itemSet = new HashSet<GeneratingCompiler.GenerationItem>(); map.put(module, itemSet); } itemSet.add(item); } return map; } private void deleteAll(final CompileContextEx context) { CompilerUtil.runInContext(context, CompilerBundle.message("progress.clearing.output"), new ThrowableRunnable<RuntimeException>() { public void run() { final boolean isTestMode = ApplicationManager.getApplication().isUnitTestMode(); final VirtualFile[] allSources = context.getProjectCompileScope().getFiles(null, true); if (myShouldClearOutputDirectory) { CompilerUtil.clearOutputDirectories(myAllOutputDirectories); } else { // refresh is still required try { for (final Compiler compiler : CompilerManager.getInstance(myProject).getCompilers(Compiler.class)) { try { if (compiler instanceof GeneratingCompiler) { final StateCache<ValidityState> cache = getGeneratingCompilerCache((GeneratingCompiler)compiler); final Iterator<String> urlIterator = cache.getUrlsIterator(); while (urlIterator.hasNext()) { context.getProgressIndicator().checkCanceled(); deleteFile(new File(VirtualFileManager.extractPath(urlIterator.next()))); } } else if (compiler instanceof TranslatingCompiler) { final ArrayList<Trinity<File, String, Boolean>> toDelete = new ArrayList<Trinity<File, String, Boolean>>(); ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { TranslatingCompilerFilesMonitor.getInstance().collectFiles( context, (TranslatingCompiler)compiler, Arrays.<VirtualFile>asList(allSources).iterator(), true /*pass true to make sure that every source in scope file is processed*/, false /*important! should pass false to enable collection of files to delete*/, new ArrayList<VirtualFile>(), toDelete ); } }); for (Trinity<File, String, Boolean> trinity : toDelete) { context.getProgressIndicator().checkCanceled(); final File file = trinity.getFirst(); deleteFile(file); if (isTestMode) { CompilerManagerImpl.addDeletedPath(file.getPath()); } } } } catch (IOException e) { LOG.info(e); } } pruneEmptyDirectories(context.getProgressIndicator(), myAllOutputDirectories); // to avoid too much files deleted events } finally { CompilerUtil.refreshIODirectories(myAllOutputDirectories); } } dropScopesCaches(); clearCompilerSystemDirectory(context); } }); } private void dropScopesCaches() { // hack to be sure the classpath will include the output directories ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { ((ProjectRootManagerEx)ProjectRootManager.getInstance(myProject)).clearScopesCachesForModules(); } }); } private static void pruneEmptyDirectories(ProgressIndicator progress, final Set<File> directories) { for (File directory : directories) { doPrune(progress, directory, directories); } } private static boolean doPrune(ProgressIndicator progress, final File directory, final Set<File> outPutDirectories) { progress.checkCanceled(); final File[] files = directory.listFiles(); boolean isEmpty = true; if (files != null) { for (File file : files) { if (!outPutDirectories.contains(file)) { if (doPrune(progress, file, outPutDirectories)) { deleteFile(file); } else { isEmpty = false; } } else { isEmpty = false; } } } else { isEmpty = false; } return isEmpty; } private Set<File> getAllOutputDirectories(CompileContext context) { final Set<File> outputDirs = new OrderedSet<File>(); final Module[] modules = ModuleManager.getInstance(myProject).getModules(); for (final String path : CompilerPathsEx.getOutputPaths(modules)) { outputDirs.add(new File(path)); } for (Pair<IntermediateOutputCompiler, Module> pair : myGenerationCompilerModuleToOutputDirMap.keySet()) { outputDirs.add(new File(CompilerPaths.getGenerationOutputPath(pair.getFirst(), pair.getSecond(), false))); outputDirs.add(new File(CompilerPaths.getGenerationOutputPath(pair.getFirst(), pair.getSecond(), true))); } final CompilerConfiguration config = CompilerConfiguration.getInstance(myProject); if (context.isAnnotationProcessorsEnabled()) { for (Module module : modules) { if (config.getAnnotationProcessingConfiguration(module).isEnabled()) { final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); if (path != null) { outputDirs.add(new File(path)); } } } } for (Artifact artifact : ArtifactManager.getInstance(myProject).getArtifacts()) { final String path = ((ArtifactImpl)artifact).getOutputDirectoryPathToCleanOnRebuild(); if (path != null) { outputDirs.add(new File(FileUtil.toSystemDependentName(path))); } } return outputDirs; } private void clearCompilerSystemDirectory(final CompileContextEx context) { CompilerCacheManager.getInstance(myProject).clearCaches(context); FileUtil.delete(CompilerPathsEx.getZipStoreDirectory(myProject)); dropDependencyCache(context); for (Pair<IntermediateOutputCompiler, Module> pair : myGenerationCompilerModuleToOutputDirMap.keySet()) { final File[] outputs = { new File(CompilerPaths.getGenerationOutputPath(pair.getFirst(), pair.getSecond(), false)), new File(CompilerPaths.getGenerationOutputPath(pair.getFirst(), pair.getSecond(), true)) }; for (File output : outputs) { final File[] files = output.listFiles(); if (files != null) { for (final File file : files) { final boolean deleteOk = deleteFile(file); if (!deleteOk) { context.addMessage(CompilerMessageCategory.ERROR, CompilerBundle.message("compiler.error.failed.to.delete", file.getPath()), null, -1, -1); } } } } } } /** * @param file a file to delete * @return true if and only if the file existed and was successfully deleted * Note: the behaviour is different from FileUtil.delete() which returns true if the file absent on the disk */ private static boolean deleteFile(final File file) { File[] files = file.listFiles(); if (files != null) { for (File file1 : files) { deleteFile(file1); } } for (int i = 0; i < 10; i++){ if (file.delete()) { return true; } if (!file.exists()) { return false; } try { Thread.sleep(50); } catch (InterruptedException ignored) { } } return false; } private VirtualFile getGenerationOutputDir(final IntermediateOutputCompiler compiler, final Module module, final boolean forTestSources) { final Pair<VirtualFile, VirtualFile> outputs = myGenerationCompilerModuleToOutputDirMap.get(new Pair<IntermediateOutputCompiler, Module>(compiler, module)); return forTestSources? outputs.getSecond() : outputs.getFirst(); } private boolean generateOutput(final CompileContextEx context, final GeneratingCompiler compiler, final boolean forceGenerate, final boolean onlyCheckStatus) throws ExitException { final GeneratingCompiler.GenerationItem[] allItems = compiler.getGenerationItems(context); final List<GeneratingCompiler.GenerationItem> toGenerate = new ArrayList<GeneratingCompiler.GenerationItem>(); final List<File> filesToRefresh = new ArrayList<File>(); final List<File> generatedFiles = new ArrayList<File>(); final List<Module> affectedModules = new ArrayList<Module>(); try { final StateCache<ValidityState> cache = getGeneratingCompilerCache(compiler); final Set<String> pathsToRemove = new HashSet<String>(cache.getUrls()); final Map<GeneratingCompiler.GenerationItem, String> itemToOutputPathMap = new HashMap<GeneratingCompiler.GenerationItem, String>(); final IOException[] ex = {null}; ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { for (final GeneratingCompiler.GenerationItem item : allItems) { final Module itemModule = item.getModule(); final String outputDirPath = CompilerPaths.getGenerationOutputPath(compiler, itemModule, item.isTestSource()); final String outputPath = outputDirPath + "/" + item.getPath(); itemToOutputPathMap.put(item, outputPath); try { final ValidityState savedState = cache.getState(outputPath); if (forceGenerate || savedState == null || !savedState.equalsTo(item.getValidityState())) { final String outputPathUrl = VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, outputPath); if (context.getCompileScope().belongs(outputPathUrl)) { toGenerate.add(item); } else { pathsToRemove.remove(outputPath); } } else { pathsToRemove.remove(outputPath); } } catch (IOException e) { ex[0] = e; } } } }); if (ex[0] != null) { throw ex[0]; } if (onlyCheckStatus) { if (toGenerate.isEmpty() && pathsToRemove.isEmpty()) { return false; } if (LOG.isDebugEnabled()) { if (!toGenerate.isEmpty()) { LOG.debug("Found items to generate, compiler " + compiler.getDescription()); } if (!pathsToRemove.isEmpty()) { LOG.debug("Found paths to remove, compiler " + compiler.getDescription()); } } throw new ExitException(ExitStatus.CANCELLED); } if (!pathsToRemove.isEmpty()) { CompilerUtil.runInContext(context, CompilerBundle.message("progress.synchronizing.output.directory"), new ThrowableRunnable<IOException>(){ public void run() throws IOException { for (final String path : pathsToRemove) { final File file = new File(path); final boolean deleted = deleteFile(file); if (deleted) { cache.remove(path); filesToRefresh.add(file); } } } }); } final Map<Module, Set<GeneratingCompiler.GenerationItem>> moduleToItemMap = buildModuleToGenerationItemMap(toGenerate.toArray(new GeneratingCompiler.GenerationItem[toGenerate.size()])); List<Module> modules = new ArrayList<Module>(moduleToItemMap.size()); for (final Module module : moduleToItemMap.keySet()) { modules.add(module); } ModuleCompilerUtil.sortModules(myProject, modules); for (final Module module : modules) { CompilerUtil.runInContext(context, "Generating output from "+compiler.getDescription(),new ThrowableRunnable<IOException>(){ public void run() throws IOException { final Set<GeneratingCompiler.GenerationItem> items = moduleToItemMap.get(module); if (items != null && !items.isEmpty()) { final GeneratingCompiler.GenerationItem[][] productionAndTestItems = splitGenerationItems(items); for (GeneratingCompiler.GenerationItem[] _items : productionAndTestItems) { if (_items.length == 0) continue; final VirtualFile outputDir = getGenerationOutputDir(compiler, module, _items[0].isTestSource()); final GeneratingCompiler.GenerationItem[] successfullyGenerated = compiler.generate(context, _items, outputDir); CompilerUtil.runInContext(context, CompilerBundle.message("progress.updating.caches"), new ThrowableRunnable<IOException>() { public void run() throws IOException { if (successfullyGenerated.length > 0) { affectedModules.add(module); } for (final GeneratingCompiler.GenerationItem item : successfullyGenerated) { final String fullOutputPath = itemToOutputPathMap.get(item); cache.update(fullOutputPath, item.getValidityState()); final File file = new File(fullOutputPath); filesToRefresh.add(file); generatedFiles.add(file); context.getProgressIndicator().setText2(file.getPath()); } } }); } } } }); } } catch (IOException e) { LOG.info(e); context.requestRebuildNextTime(e.getMessage()); throw new ExitException(ExitStatus.ERRORS); } finally { CompilerUtil.refreshIOFiles(filesToRefresh); if (!generatedFiles.isEmpty()) { DumbService.getInstance(myProject).waitForSmartMode(); List<VirtualFile> vFiles = ApplicationManager.getApplication().runReadAction(new Computable<List<VirtualFile>>() { public List<VirtualFile> compute() { final ArrayList<VirtualFile> vFiles = new ArrayList<VirtualFile>(generatedFiles.size()); for (File generatedFile : generatedFiles) { final VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(generatedFile); if (vFile != null) { vFiles.add(vFile); } } return vFiles; } }); if (forceGenerate) { context.addScope(new FileSetCompileScope(vFiles, affectedModules.toArray(new Module[affectedModules.size()]))); } context.markGenerated(vFiles); } } return !toGenerate.isEmpty() || !filesToRefresh.isEmpty(); } private static GeneratingCompiler.GenerationItem[][] splitGenerationItems(final Set<GeneratingCompiler.GenerationItem> items) { final List<GeneratingCompiler.GenerationItem> production = new ArrayList<GeneratingCompiler.GenerationItem>(); final List<GeneratingCompiler.GenerationItem> tests = new ArrayList<GeneratingCompiler.GenerationItem>(); for (GeneratingCompiler.GenerationItem item : items) { if (item.isTestSource()) { tests.add(item); } else { production.add(item); } } return new GeneratingCompiler.GenerationItem[][]{ production.toArray(new GeneratingCompiler.GenerationItem[production.size()]), tests.toArray(new GeneratingCompiler.GenerationItem[tests.size()]) }; } private boolean compileSources(final CompileContextEx context, final Chunk<Module> moduleChunk, final TranslatingCompiler compiler, final Collection<VirtualFile> srcSnapshot, final boolean forceCompile, final boolean isRebuild, final boolean onlyCheckStatus, TranslatingCompiler.OutputSink sink) throws ExitException { final Set<VirtualFile> toCompile = new HashSet<VirtualFile>(); final List<Trinity<File, String, Boolean>> toDelete = new ArrayList<Trinity<File, String, Boolean>>(); context.getProgressIndicator().pushState(); final boolean[] wereFilesDeleted = {false}; try { ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { TranslatingCompilerFilesMonitor.getInstance().collectFiles( context, compiler, srcSnapshot.iterator(), forceCompile, isRebuild, toCompile, toDelete ); } }); if (onlyCheckStatus) { if (toDelete.isEmpty() && toCompile.isEmpty()) { return false; } if (LOG.isDebugEnabled() || ourDebugMode) { if (!toDelete.isEmpty()) { final StringBuilder message = new StringBuilder(); message.append("Found items to delete, compiler ").append(compiler.getDescription()); for (Trinity<File, String, Boolean> trinity : toDelete) { message.append("\n").append(trinity.getFirst()); } LOG.debug(message.toString()); if (ourDebugMode) { System.out.println(message); } } if (!toCompile.isEmpty()) { final String message = "Found items to compile, compiler " + compiler.getDescription(); LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } } throw new ExitException(ExitStatus.CANCELLED); } if (!toDelete.isEmpty()) { try { wereFilesDeleted[0] = syncOutputDir(context, toDelete); } catch (CacheCorruptedException e) { LOG.info(e); context.requestRebuildNextTime(e.getMessage()); } } if ((wereFilesDeleted[0] || !toCompile.isEmpty()) && context.getMessageCount(CompilerMessageCategory.ERROR) == 0) { compiler.compile(context, moduleChunk, VfsUtilCore.toVirtualFileArray(toCompile), sink); } } finally { context.getProgressIndicator().popState(); } return !toCompile.isEmpty() || wereFilesDeleted[0]; } private static boolean syncOutputDir(final CompileContextEx context, final Collection<Trinity<File, String, Boolean>> toDelete) throws CacheCorruptedException { final DependencyCache dependencyCache = context.getDependencyCache(); final boolean isTestMode = ApplicationManager.getApplication().isUnitTestMode(); final List<File> filesToRefresh = new ArrayList<File>(); final boolean[] wereFilesDeleted = {false}; CompilerUtil.runInContext(context, CompilerBundle.message("progress.synchronizing.output.directory"), new ThrowableRunnable<CacheCorruptedException>(){ public void run() throws CacheCorruptedException { final long start = System.currentTimeMillis(); try { for (final Trinity<File, String, Boolean> trinity : toDelete) { final File outputPath = trinity.getFirst(); context.getProgressIndicator().checkCanceled(); context.getProgressIndicator().setText2(outputPath.getPath()); filesToRefresh.add(outputPath); if (isTestMode) { LOG.assertTrue(outputPath.exists()); } if (!deleteFile(outputPath)) { if (isTestMode) { if (outputPath.exists()) { LOG.error("Was not able to delete output file: " + outputPath.getPath()); } else { CompilerManagerImpl.addDeletedPath(outputPath.getPath()); } } continue; } wereFilesDeleted[0] = true; // update zip here //final String outputDir = myOutputFinder.lookupOutputPath(outputPath); //if (outputDir != null) { // try { // context.updateZippedOuput(outputDir, FileUtil.toSystemIndependentName(outputPath.getPath()).substring(outputDir.length() + 1)); // } // catch (IOException e) { // LOG.info(e); // } //} final String className = trinity.getSecond(); if (className != null) { final int id = dependencyCache.getSymbolTable().getId(className); dependencyCache.addTraverseRoot(id); final boolean sourcePresent = trinity.getThird().booleanValue(); if (!sourcePresent) { dependencyCache.markSourceRemoved(id); } } if (isTestMode) { CompilerManagerImpl.addDeletedPath(outputPath.getPath()); } } } finally { CompilerUtil.logDuration("Sync output directory", System.currentTimeMillis() - start); CompilerUtil.refreshIOFiles(filesToRefresh); } } }); return wereFilesDeleted[0]; } // [mike] performance optimization - this method is accessed > 15,000 times in Aurora private String getModuleOutputPath(final Module module, boolean inTestSourceContent) { final Map<Module, String> map = inTestSourceContent ? myModuleTestOutputPaths : myModuleOutputPaths; String path = map.get(module); if (path == null) { path = CompilerPaths.getModuleOutputPath(module, inTestSourceContent); map.put(module, path); } return path; } private boolean processFiles(final FileProcessingCompilerAdapter adapter, final boolean forceCompile, final boolean checkScope, final boolean onlyCheckStatus, final CacheDeferredUpdater cacheUpdater) throws ExitException, IOException { final CompileContextEx context = (CompileContextEx)adapter.getCompileContext(); final FileProcessingCompilerStateCache cache = getFileProcessingCompilerCache(adapter.getCompiler()); final FileProcessingCompiler.ProcessingItem[] items = adapter.getProcessingItems(); if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { return false; } if (LOG.isDebugEnabled() && items.length > 0) { LOG.debug("Start processing files by " + adapter.getCompiler().getDescription()); } final CompileScope scope = context.getCompileScope(); final List<FileProcessingCompiler.ProcessingItem> toProcess = new ArrayList<FileProcessingCompiler.ProcessingItem>(); final Set<String> allUrls = new HashSet<String>(); final IOException[] ex = {null}; DumbService.getInstance(myProject).waitForSmartMode(); ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { try { for (FileProcessingCompiler.ProcessingItem item : items) { final VirtualFile file = item.getFile(); final String url = file.getUrl(); allUrls.add(url); if (!forceCompile && cache.getTimestamp(url) == file.getTimeStamp()) { final ValidityState state = cache.getExtState(url); final ValidityState itemState = item.getValidityState(); if (state != null ? state.equalsTo(itemState) : itemState == null) { continue; } } if (LOG.isDebugEnabled()) { LOG.debug("Adding item to process: " + url + "; saved ts= " + cache.getTimestamp(url) + "; VFS ts=" + file.getTimeStamp()); } toProcess.add(item); } } catch (IOException e) { ex[0] = e; } } }); if (ex[0] != null) { throw ex[0]; } final Collection<String> urls = cache.getUrls(); final List<String> urlsToRemove = new ArrayList<String>(); if (!urls.isEmpty()) { CompilerUtil.runInContext(context, CompilerBundle.message("progress.processing.outdated.files"), new ThrowableRunnable<IOException>(){ public void run() throws IOException { ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { for (final String url : urls) { if (!allUrls.contains(url)) { if (!checkScope || scope.belongs(url)) { urlsToRemove.add(url); } } } } }); if (!onlyCheckStatus && !urlsToRemove.isEmpty()) { for (final String url : urlsToRemove) { adapter.processOutdatedItem(context, url, cache.getExtState(url)); cache.remove(url); } } } }); } if (onlyCheckStatus) { if (urlsToRemove.isEmpty() && toProcess.isEmpty()) { return false; } if (LOG.isDebugEnabled()) { if (!urlsToRemove.isEmpty()) { LOG.debug("Found urls to remove, compiler " + adapter.getCompiler().getDescription()); for (String url : urlsToRemove) { LOG.debug("\t" + url); } } if (!toProcess.isEmpty()) { LOG.debug("Found items to compile, compiler " + adapter.getCompiler().getDescription()); for (FileProcessingCompiler.ProcessingItem item : toProcess) { LOG.debug("\t" + item.getFile().getPresentableUrl()); } } } throw new ExitException(ExitStatus.CANCELLED); } if (toProcess.isEmpty()) { return false; } final FileProcessingCompiler.ProcessingItem[] processed = adapter.process(toProcess.toArray(new FileProcessingCompiler.ProcessingItem[toProcess.size()])); if (processed.length == 0) { return true; } CompilerUtil.runInContext(context, CompilerBundle.message("progress.updating.caches"), new ThrowableRunnable<IOException>() { public void run() { final List<VirtualFile> vFiles = new ArrayList<VirtualFile>(processed.length); for (FileProcessingCompiler.ProcessingItem aProcessed : processed) { final VirtualFile file = aProcessed.getFile(); vFiles.add(file); if (LOG.isDebugEnabled()) { LOG.debug("\tFile processed " + file.getPresentableUrl() + "; ts=" + file.getTimeStamp()); } //final String path = file.getPath(); //final String outputDir = myOutputFinder.lookupOutputPath(path); //if (outputDir != null) { // context.updateZippedOuput(outputDir, path.substring(outputDir.length() + 1)); //} } LocalFileSystem.getInstance().refreshFiles(vFiles); if (LOG.isDebugEnabled()) { LOG.debug("Files after VFS refresh:"); for (VirtualFile file : vFiles) { LOG.debug("\t" + file.getPresentableUrl() + "; ts=" + file.getTimeStamp()); } } for (FileProcessingCompiler.ProcessingItem item : processed) { cacheUpdater.addFileForUpdate(item, cache); } } }); return true; } private FileProcessingCompilerStateCache getFileProcessingCompilerCache(FileProcessingCompiler compiler) throws IOException { return CompilerCacheManager.getInstance(myProject).getFileProcessingCompilerCache(compiler); } private StateCache<ValidityState> getGeneratingCompilerCache(final GeneratingCompiler compiler) throws IOException { return CompilerCacheManager.getInstance(myProject).getGeneratingCompilerCache(compiler); } public void executeCompileTask(final CompileTask task, final CompileScope scope, final String contentName, final Runnable onTaskFinished) { final CompilerTask progressManagerTask = new CompilerTask(myProject, contentName, false, false, true, isCompilationStartedAutomatically(scope)); final CompileContextImpl compileContext = new CompileContextImpl(myProject, progressManagerTask, scope, null, false, false); FileDocumentManager.getInstance().saveAllDocuments(); progressManagerTask.start(new Runnable() { public void run() { try { task.execute(compileContext); } catch (ProcessCanceledException ex) { // suppressed } finally { if (onTaskFinished != null) { onTaskFinished.run(); } } } }, null); } private boolean executeCompileTasks(final CompileContext context, final boolean beforeTasks) { final CompilerManager manager = CompilerManager.getInstance(myProject); final ProgressIndicator progressIndicator = context.getProgressIndicator(); progressIndicator.pushState(); try { CompileTask[] tasks = beforeTasks ? manager.getBeforeTasks() : manager.getAfterTasks(); if (tasks.length > 0) { progressIndicator.setText(beforeTasks ? CompilerBundle.message("progress.executing.precompile.tasks") : CompilerBundle.message("progress.executing.postcompile.tasks")); for (CompileTask task : tasks) { if (!task.execute(context)) { return false; } } } } finally { progressIndicator.popState(); WindowManager.getInstance().getStatusBar(myProject).setInfo(""); if (progressIndicator instanceof CompilerTask) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { ((CompilerTask)progressIndicator).showCompilerContent(); } }); } } return true; } private boolean validateCompilerConfiguration(final CompileScope scope, boolean checkOutputAndSourceIntersection) { try { final Module[] scopeModules = scope.getAffectedModules()/*ModuleManager.getInstance(myProject).getModules()*/; final List<String> modulesWithoutOutputPathSpecified = new ArrayList<String>(); boolean isProjectCompilePathSpecified = true; final List<String> modulesWithoutJdkAssigned = new ArrayList<String>(); final Set<File> nonExistingOutputPaths = new HashSet<File>(); final CompilerConfiguration config = CompilerConfiguration.getInstance(myProject); final CompilerManager compilerManager = CompilerManager.getInstance(myProject); final boolean useOutOfProcessBuild = useOutOfProcessBuild(); for (final Module module : scopeModules) { if (!compilerManager.isValidationEnabled(module)) { continue; } final boolean hasSources = hasSources(module, false); final boolean hasTestSources = hasSources(module, true); if (!hasSources && !hasTestSources) { // If module contains no sources, shouldn't have to select JDK or output directory (SCR #19333) // todo still there may be problems with this approach if some generated files are attributed by this module continue; } final Sdk jdk = ModuleRootManager.getInstance(module).getSdk(); if (jdk == null) { modulesWithoutJdkAssigned.add(module.getName()); } final String outputPath = getModuleOutputPath(module, false); final String testsOutputPath = getModuleOutputPath(module, true); if (outputPath == null && testsOutputPath == null) { modulesWithoutOutputPathSpecified.add(module.getName()); } else { if (outputPath != null) { if (!useOutOfProcessBuild) { final File file = new File(outputPath.replace('/', File.separatorChar)); if (!file.exists()) { nonExistingOutputPaths.add(file); } } } else { if (hasSources) { modulesWithoutOutputPathSpecified.add(module.getName()); } } if (testsOutputPath != null) { if (!useOutOfProcessBuild) { final File f = new File(testsOutputPath.replace('/', File.separatorChar)); if (!f.exists()) { nonExistingOutputPaths.add(f); } } } else { if (hasTestSources) { modulesWithoutOutputPathSpecified.add(module.getName()); } } if (!useOutOfProcessBuild) { if (config.getAnnotationProcessingConfiguration(module).isEnabled()) { final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); if (path == null) { final CompilerProjectExtension extension = CompilerProjectExtension.getInstance(module.getProject()); if (extension == null || extension.getCompilerOutputUrl() == null) { isProjectCompilePathSpecified = false; } else { modulesWithoutOutputPathSpecified.add(module.getName()); } } else { final File file = new File(path); if (!file.exists()) { nonExistingOutputPaths.add(file); } } } } } } if (!modulesWithoutJdkAssigned.isEmpty()) { showNotSpecifiedError("error.jdk.not.specified", modulesWithoutJdkAssigned, ProjectBundle.message("modules.classpath.title")); return false; } if (!isProjectCompilePathSpecified) { final String message = CompilerBundle.message("error.project.output.not.specified"); if (ApplicationManager.getApplication().isUnitTestMode()) { LOG.error(message); } Messages.showMessageDialog(myProject, message, CommonBundle.getErrorTitle(), Messages.getErrorIcon()); ProjectSettingsService.getInstance(myProject).openProjectSettings(); return false; } if (!modulesWithoutOutputPathSpecified.isEmpty()) { showNotSpecifiedError("error.output.not.specified", modulesWithoutOutputPathSpecified, CommonContentEntriesEditor.NAME); return false; } if (!nonExistingOutputPaths.isEmpty()) { for (File file : nonExistingOutputPaths) { final boolean succeeded = file.mkdirs(); if (!succeeded) { if (file.exists()) { // for overlapping paths, this one might have been created as an intermediate path on a previous iteration continue; } Messages.showMessageDialog(myProject, CompilerBundle.message("error.failed.to.create.directory", file.getPath()), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); return false; } } final Boolean refreshSuccess = new WriteAction<Boolean>() { @Override protected void run(Result<Boolean> result) throws Throwable { LocalFileSystem.getInstance().refreshIoFiles(nonExistingOutputPaths); Boolean res = Boolean.TRUE; for (File file : nonExistingOutputPaths) { if (LocalFileSystem.getInstance().findFileByIoFile(file) == null) { res = Boolean.FALSE; break; } } result.setResult(res); } }.execute().getResultObject(); if (!refreshSuccess.booleanValue()) { return false; } dropScopesCaches(); } if (checkOutputAndSourceIntersection && myShouldClearOutputDirectory) { if (!validateOutputAndSourcePathsIntersection()) { return false; } // myShouldClearOutputDirectory may change in validateOutputAndSourcePathsIntersection() CompilerPathsEx.CLEAR_ALL_OUTPUTS_KEY.set(scope, myShouldClearOutputDirectory); } else { CompilerPathsEx.CLEAR_ALL_OUTPUTS_KEY.set(scope, false); } final List<Chunk<Module>> chunks = ModuleCompilerUtil.getSortedModuleChunks(myProject, Arrays.asList(scopeModules)); for (final Chunk<Module> chunk : chunks) { final Set<Module> chunkModules = chunk.getNodes(); if (chunkModules.size() <= 1) { continue; // no need to check one-module chunks } for (Module chunkModule : chunkModules) { if (config.getAnnotationProcessingConfiguration(chunkModule).isEnabled()) { showCyclesNotSupportedForAnnotationProcessors(chunkModules.toArray(new Module[chunkModules.size()])); return false; } } Sdk jdk = null; LanguageLevel languageLevel = null; for (final Module module : chunkModules) { final Sdk moduleJdk = ModuleRootManager.getInstance(module).getSdk(); if (jdk == null) { jdk = moduleJdk; } else { if (!jdk.equals(moduleJdk)) { showCyclicModulesHaveDifferentJdksError(chunkModules.toArray(new Module[chunkModules.size()])); return false; } } LanguageLevel moduleLanguageLevel = LanguageLevelUtil.getEffectiveLanguageLevel(module); if (languageLevel == null) { languageLevel = moduleLanguageLevel; } else { if (!languageLevel.equals(moduleLanguageLevel)) { showCyclicModulesHaveDifferentLanguageLevel(chunkModules.toArray(new Module[chunkModules.size()])); return false; } } } } if (!useOutOfProcessBuild) { final Compiler[] allCompilers = compilerManager.getCompilers(Compiler.class); for (Compiler compiler : allCompilers) { if (!compiler.validateConfiguration(scope)) { return false; } } } return true; } catch (Throwable e) { LOG.info(e); return false; } } private boolean useOutOfProcessBuild() { return CompilerWorkspaceConfiguration.getInstance(myProject).useOutOfProcessBuild(); } private void showCyclicModulesHaveDifferentLanguageLevel(Module[] modulesInChunk) { LOG.assertTrue(modulesInChunk.length > 0); String moduleNameToSelect = modulesInChunk[0].getName(); final String moduleNames = getModulesString(modulesInChunk); Messages.showMessageDialog(myProject, CompilerBundle.message("error.chunk.modules.must.have.same.language.level", moduleNames), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); showConfigurationDialog(moduleNameToSelect, null); } private void showCyclicModulesHaveDifferentJdksError(Module[] modulesInChunk) { LOG.assertTrue(modulesInChunk.length > 0); String moduleNameToSelect = modulesInChunk[0].getName(); final String moduleNames = getModulesString(modulesInChunk); Messages.showMessageDialog(myProject, CompilerBundle.message("error.chunk.modules.must.have.same.jdk", moduleNames), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); showConfigurationDialog(moduleNameToSelect, null); } private void showCyclesNotSupportedForAnnotationProcessors(Module[] modulesInChunk) { LOG.assertTrue(modulesInChunk.length > 0); String moduleNameToSelect = modulesInChunk[0].getName(); final String moduleNames = getModulesString(modulesInChunk); Messages.showMessageDialog(myProject, CompilerBundle.message("error.annotation.processing.not.supported.for.module.cycles", moduleNames), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); showConfigurationDialog(moduleNameToSelect, null); } private static String getModulesString(Module[] modulesInChunk) { final StringBuilder moduleNames = StringBuilderSpinAllocator.alloc(); try { for (Module module : modulesInChunk) { if (moduleNames.length() > 0) { moduleNames.append("\n"); } moduleNames.append("\"").append(module.getName()).append("\""); } return moduleNames.toString(); } finally { StringBuilderSpinAllocator.dispose(moduleNames); } } private static boolean hasSources(Module module, boolean checkTestSources) { final ContentEntry[] contentEntries = ModuleRootManager.getInstance(module).getContentEntries(); for (final ContentEntry contentEntry : contentEntries) { final SourceFolder[] sourceFolders = contentEntry.getSourceFolders(); for (final SourceFolder sourceFolder : sourceFolders) { if (sourceFolder.getFile() == null) { continue; // skip invalid source folders } if (checkTestSources) { if (sourceFolder.isTestSource()) { return true; } } else { if (!sourceFolder.isTestSource()) { return true; } } } } return false; } private void showNotSpecifiedError(@NonNls final String resourceId, List<String> modules, String editorNameToSelect) { String nameToSelect = null; final StringBuilder names = StringBuilderSpinAllocator.alloc(); final String message; try { final int maxModulesToShow = 10; for (String name : modules.size() > maxModulesToShow ? modules.subList(0, maxModulesToShow) : modules) { if (nameToSelect == null) { nameToSelect = name; } if (names.length() > 0) { names.append(",\n"); } names.append("\""); names.append(name); names.append("\""); } if (modules.size() > maxModulesToShow) { names.append(",\n..."); } message = CompilerBundle.message(resourceId, modules.size(), names.toString()); } finally { StringBuilderSpinAllocator.dispose(names); } if (ApplicationManager.getApplication().isUnitTestMode()) { LOG.error(message); } Messages.showMessageDialog(myProject, message, CommonBundle.getErrorTitle(), Messages.getErrorIcon()); showConfigurationDialog(nameToSelect, editorNameToSelect); } private boolean validateOutputAndSourcePathsIntersection() { final Module[] allModules = ModuleManager.getInstance(myProject).getModules(); List<VirtualFile> allOutputs = new ArrayList<VirtualFile>(); ContainerUtil.addAll(allOutputs, CompilerPathsEx.getOutputDirectories(allModules)); for (Artifact artifact : ArtifactManager.getInstance(myProject).getArtifacts()) { ContainerUtil.addIfNotNull(artifact.getOutputFile(), allOutputs); } final Set<VirtualFile> affectedOutputPaths = new HashSet<VirtualFile>(); CompilerUtil.computeIntersectingPaths(myProject, allOutputs, affectedOutputPaths); affectedOutputPaths.addAll(ArtifactCompilerUtil.getArtifactOutputsContainingSourceFiles(myProject)); if (!affectedOutputPaths.isEmpty()) { if (CompilerUtil.askUserToContinueWithNoClearing(myProject, affectedOutputPaths)) { myShouldClearOutputDirectory = false; return true; } else { return false; } } return true; } private void showConfigurationDialog(String moduleNameToSelect, String tabNameToSelect) { ProjectSettingsService.getInstance(myProject).showModuleConfigurationDialog(moduleNameToSelect, tabNameToSelect); } private static VirtualFile lookupVFile(final LocalFileSystem lfs, final String path) { final File file = new File(path); VirtualFile vFile = lfs.findFileByIoFile(file); if (vFile != null) { return vFile; } final boolean justCreated = file.mkdirs(); vFile = lfs.refreshAndFindFileByIoFile(file); if (vFile == null) { assert false: "Virtual file not found for " + file.getPath() + "; mkdirs() exit code is " + justCreated + "; file exists()? " + file.exists(); } return vFile; } private static class CacheDeferredUpdater { private final Map<VirtualFile, List<Pair<FileProcessingCompilerStateCache, FileProcessingCompiler.ProcessingItem>>> myData = new java.util.HashMap<VirtualFile, List<Pair<FileProcessingCompilerStateCache, FileProcessingCompiler.ProcessingItem>>>(); public void addFileForUpdate(final FileProcessingCompiler.ProcessingItem item, FileProcessingCompilerStateCache cache) { final VirtualFile file = item.getFile(); List<Pair<FileProcessingCompilerStateCache, FileProcessingCompiler.ProcessingItem>> list = myData.get(file); if (list == null) { list = new ArrayList<Pair<FileProcessingCompilerStateCache, FileProcessingCompiler.ProcessingItem>>(); myData.put(file, list); } list.add(new Pair<FileProcessingCompilerStateCache, FileProcessingCompiler.ProcessingItem>(cache, item)); } public void doUpdate() throws IOException{ final IOException[] ex = {null}; ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { try { for (Map.Entry<VirtualFile, List<Pair<FileProcessingCompilerStateCache, FileProcessingCompiler.ProcessingItem>>> entry : myData.entrySet()) { for (Pair<FileProcessingCompilerStateCache, FileProcessingCompiler.ProcessingItem> pair : entry.getValue()) { final FileProcessingCompiler.ProcessingItem item = pair.getSecond(); pair.getFirst().update(entry.getKey(), item.getValidityState()); } } } catch (IOException e) { ex[0] = e; } } }); if (ex[0] != null) { throw ex[0]; } } } private static class TranslatorsOutputSink implements TranslatingCompiler.OutputSink { final Map<String, Collection<TranslatingCompiler.OutputItem>> myPostponedItems = new HashMap<String, Collection<TranslatingCompiler.OutputItem>>(); private final CompileContextEx myContext; private final TranslatingCompiler[] myCompilers; private int myCurrentCompilerIdx; private final Set<VirtualFile> myCompiledSources = new HashSet<VirtualFile>(); //private LinkedBlockingQueue<Future> myFutures = new LinkedBlockingQueue<Future>(); private TranslatorsOutputSink(CompileContextEx context, TranslatingCompiler[] compilers) { myContext = context; myCompilers = compilers; } public void setCurrentCompilerIndex(int index) { myCurrentCompilerIdx = index; } public Set<VirtualFile> getCompiledSources() { return Collections.unmodifiableSet(myCompiledSources); } public void add(final String outputRoot, final Collection<TranslatingCompiler.OutputItem> items, final VirtualFile[] filesToRecompile) { for (TranslatingCompiler.OutputItem item : items) { final VirtualFile file = item.getSourceFile(); if (file != null) { myCompiledSources.add(file); } } final TranslatingCompiler compiler = myCompilers[myCurrentCompilerIdx]; if (compiler instanceof IntermediateOutputCompiler) { final LocalFileSystem lfs = LocalFileSystem.getInstance(); final List<VirtualFile> outputs = new ArrayList<VirtualFile>(); for (TranslatingCompiler.OutputItem item : items) { final VirtualFile vFile = lfs.findFileByPath(item.getOutputPath()); if (vFile != null) { outputs.add(vFile); } } myContext.markGenerated(outputs); } final int nextCompilerIdx = myCurrentCompilerIdx + 1; try { if (nextCompilerIdx < myCompilers.length ) { final Map<String, Collection<TranslatingCompiler.OutputItem>> updateNow = new java.util.HashMap<String, Collection<TranslatingCompiler.OutputItem>>(); // process postponed for (Map.Entry<String, Collection<TranslatingCompiler.OutputItem>> entry : myPostponedItems.entrySet()) { final String outputDir = entry.getKey(); final Collection<TranslatingCompiler.OutputItem> postponed = entry.getValue(); for (Iterator<TranslatingCompiler.OutputItem> it = postponed.iterator(); it.hasNext();) { TranslatingCompiler.OutputItem item = it.next(); boolean shouldPostpone = false; for (int idx = nextCompilerIdx; idx < myCompilers.length; idx++) { shouldPostpone = myCompilers[idx].isCompilableFile(item.getSourceFile(), myContext); if (shouldPostpone) { break; } } if (!shouldPostpone) { // the file is not compilable by the rest of compilers, so it is safe to update it now it.remove(); addItemToMap(updateNow, outputDir, item); } } } // process items from current compilation for (TranslatingCompiler.OutputItem item : items) { boolean shouldPostpone = false; for (int idx = nextCompilerIdx; idx < myCompilers.length; idx++) { shouldPostpone = myCompilers[idx].isCompilableFile(item.getSourceFile(), myContext); if (shouldPostpone) { break; } } if (shouldPostpone) { // the file is compilable by the next compiler in row, update should be postponed addItemToMap(myPostponedItems, outputRoot, item); } else { addItemToMap(updateNow, outputRoot, item); } } if (updateNow.size() == 1) { final Map.Entry<String, Collection<TranslatingCompiler.OutputItem>> entry = updateNow.entrySet().iterator().next(); final String outputDir = entry.getKey(); final Collection<TranslatingCompiler.OutputItem> itemsToUpdate = entry.getValue(); TranslatingCompilerFilesMonitor.getInstance().update(myContext, outputDir, itemsToUpdate, filesToRecompile); } else { for (Map.Entry<String, Collection<TranslatingCompiler.OutputItem>> entry : updateNow.entrySet()) { final String outputDir = entry.getKey(); final Collection<TranslatingCompiler.OutputItem> itemsToUpdate = entry.getValue(); TranslatingCompilerFilesMonitor.getInstance().update(myContext, outputDir, itemsToUpdate, VirtualFile.EMPTY_ARRAY); } if (filesToRecompile.length > 0) { TranslatingCompilerFilesMonitor.getInstance().update(myContext, null, Collections.<TranslatingCompiler.OutputItem>emptyList(), filesToRecompile); } } } else { TranslatingCompilerFilesMonitor.getInstance().update(myContext, outputRoot, items, filesToRecompile); } } catch (IOException e) { LOG.info(e); myContext.requestRebuildNextTime(e.getMessage()); } } private static void addItemToMap(Map<String, Collection<TranslatingCompiler.OutputItem>> map, String outputDir, TranslatingCompiler.OutputItem item) { Collection<TranslatingCompiler.OutputItem> collection = map.get(outputDir); if (collection == null) { collection = new ArrayList<TranslatingCompiler.OutputItem>(); map.put(outputDir, collection); } collection.add(item); } public void flushPostponedItems() { final TranslatingCompilerFilesMonitor filesMonitor = TranslatingCompilerFilesMonitor.getInstance(); try { for (Map.Entry<String, Collection<TranslatingCompiler.OutputItem>> entry : myPostponedItems.entrySet()) { final String outputDir = entry.getKey(); final Collection<TranslatingCompiler.OutputItem> items = entry.getValue(); filesMonitor.update(myContext, outputDir, items, VirtualFile.EMPTY_ARRAY); } } catch (IOException e) { LOG.info(e); myContext.requestRebuildNextTime(e.getMessage()); } } } private static class DependentClassesCumulativeFilter implements Function<Pair<int[], Set<VirtualFile>>, Pair<int[], Set<VirtualFile>>> { private final TIntHashSet myProcessedNames = new TIntHashSet(); private final Set<VirtualFile> myProcessedFiles = new HashSet<VirtualFile>(); public Pair<int[], Set<VirtualFile>> fun(Pair<int[], Set<VirtualFile>> deps) { final TIntHashSet currentDeps = new TIntHashSet(deps.getFirst()); currentDeps.removeAll(myProcessedNames.toArray()); myProcessedNames.addAll(deps.getFirst()); final Set<VirtualFile> depFiles = new HashSet<VirtualFile>(deps.getSecond()); depFiles.removeAll(myProcessedFiles); myProcessedFiles.addAll(deps.getSecond()); return new Pair<int[], Set<VirtualFile>>(currentDeps.toArray(), depFiles); } } }
java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java
/* * Copyright 2000-2012 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. */ /** * @author: Eugene Zhuravlev * Date: Jan 17, 2003 * Time: 1:42:26 PM */ package com.intellij.compiler.impl; import com.intellij.CommonBundle; import com.intellij.compiler.*; import com.intellij.compiler.make.CacheCorruptedException; import com.intellij.compiler.make.CacheUtils; import com.intellij.compiler.make.ChangedConstantsDependencyProcessor; import com.intellij.compiler.make.DependencyCache; import com.intellij.compiler.progress.CompilerTask; import com.intellij.compiler.server.BuildManager; import com.intellij.compiler.server.CustomBuilderMessageHandler; import com.intellij.compiler.server.DefaultMessageHandler; import com.intellij.diagnostic.IdeErrorsDialog; import com.intellij.diagnostic.PluginException; import com.intellij.openapi.application.*; import com.intellij.openapi.compiler.*; import com.intellij.openapi.compiler.Compiler; import com.intellij.openapi.compiler.ex.CompileContextEx; import com.intellij.openapi.compiler.ex.CompilerPathsEx; import com.intellij.openapi.compiler.generic.GenericCompiler; import com.intellij.openapi.deployment.DeploymentUtil; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.module.LanguageLevelUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.ex.ProjectRootManagerEx; import com.intellij.openapi.roots.ui.configuration.CommonContentEntriesEditor; import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.newvfs.ManagingFS; import com.intellij.openapi.vfs.newvfs.RefreshQueue; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.openapi.wm.WindowManager; import com.intellij.packaging.artifacts.Artifact; import com.intellij.packaging.artifacts.ArtifactManager; import com.intellij.packaging.impl.artifacts.ArtifactImpl; import com.intellij.packaging.impl.artifacts.ArtifactUtil; import com.intellij.packaging.impl.compiler.ArtifactCompileScope; import com.intellij.packaging.impl.compiler.ArtifactCompilerUtil; import com.intellij.packaging.impl.compiler.ArtifactsCompiler; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.PsiDocumentManager; import com.intellij.util.Chunk; import com.intellij.util.Function; import com.intellij.util.StringBuilderSpinAllocator; import com.intellij.util.ThrowableRunnable; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashMap; import com.intellij.util.containers.MultiMap; import com.intellij.util.containers.OrderedSet; import com.intellij.util.messages.MessageBus; import gnu.trove.THashSet; import gnu.trove.TIntHashSet; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import org.jetbrains.jps.api.CmdlineProtoUtil; import org.jetbrains.jps.api.CmdlineRemoteProto; import org.jetbrains.jps.api.RequestFuture; import org.jetbrains.jps.incremental.Utils; import javax.swing.*; import java.io.*; import java.util.*; import java.util.concurrent.TimeUnit; import static org.jetbrains.jps.api.CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.TargetTypeBuildScope; public class CompileDriver { private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.CompileDriver"); // to be used in tests only for debug output public static volatile boolean ourDebugMode = false; private final Project myProject; private final Map<Pair<IntermediateOutputCompiler, Module>, Pair<VirtualFile, VirtualFile>> myGenerationCompilerModuleToOutputDirMap; // [IntermediateOutputCompiler, Module] -> [ProductionSources, TestSources] private final String myCachesDirectoryPath; private boolean myShouldClearOutputDirectory; private final Map<Module, String> myModuleOutputPaths = new HashMap<Module, String>(); private final Map<Module, String> myModuleTestOutputPaths = new HashMap<Module, String>(); @NonNls private static final String VERSION_FILE_NAME = "version.dat"; @NonNls private static final String LOCK_FILE_NAME = "in_progress.dat"; private static final boolean GENERATE_CLASSPATH_INDEX = "true".equals(System.getProperty("generate.classpath.index")); private static final String PROP_PERFORM_INITIAL_REFRESH = "compiler.perform.outputs.refresh.on.start"; private static final Key<Boolean> REFRESH_DONE_KEY = Key.create("_compiler.initial.refresh.done_"); private static final Key<Boolean> COMPILATION_STARTED_AUTOMATICALLY = Key.create("compilation_started_automatically"); private static final FileProcessingCompilerAdapterFactory FILE_PROCESSING_COMPILER_ADAPTER_FACTORY = new FileProcessingCompilerAdapterFactory() { public FileProcessingCompilerAdapter create(CompileContext context, FileProcessingCompiler compiler) { return new FileProcessingCompilerAdapter(context, compiler); } }; private static final FileProcessingCompilerAdapterFactory FILE_PACKAGING_COMPILER_ADAPTER_FACTORY = new FileProcessingCompilerAdapterFactory() { public FileProcessingCompilerAdapter create(CompileContext context, FileProcessingCompiler compiler) { return new PackagingCompilerAdapter(context, (PackagingCompiler)compiler); } }; private CompilerFilter myCompilerFilter = CompilerFilter.ALL; private static final CompilerFilter SOURCE_PROCESSING_ONLY = new CompilerFilter() { public boolean acceptCompiler(Compiler compiler) { return compiler instanceof SourceProcessingCompiler; } }; private static final CompilerFilter ALL_EXCEPT_SOURCE_PROCESSING = new CompilerFilter() { public boolean acceptCompiler(Compiler compiler) { return !SOURCE_PROCESSING_ONLY.acceptCompiler(compiler); } }; private Set<File> myAllOutputDirectories; private static final long ONE_MINUTE_MS = 60L /*sec*/ * 1000L /*millisec*/; public CompileDriver(Project project) { myProject = project; myCachesDirectoryPath = CompilerPaths.getCacheStoreDirectory(myProject).getPath().replace('/', File.separatorChar); myShouldClearOutputDirectory = CompilerWorkspaceConfiguration.getInstance(myProject).CLEAR_OUTPUT_DIRECTORY; myGenerationCompilerModuleToOutputDirMap = new HashMap<Pair<IntermediateOutputCompiler, Module>, Pair<VirtualFile, VirtualFile>>(); if (!useOutOfProcessBuild()) { final LocalFileSystem lfs = LocalFileSystem.getInstance(); final IntermediateOutputCompiler[] generatingCompilers = CompilerManager.getInstance(myProject).getCompilers(IntermediateOutputCompiler.class, myCompilerFilter); final Module[] allModules = ModuleManager.getInstance(myProject).getModules(); final CompilerConfiguration config = CompilerConfiguration.getInstance(project); for (Module module : allModules) { for (IntermediateOutputCompiler compiler : generatingCompilers) { final VirtualFile productionOutput = lookupVFile(lfs, CompilerPaths.getGenerationOutputPath(compiler, module, false)); final VirtualFile testOutput = lookupVFile(lfs, CompilerPaths.getGenerationOutputPath(compiler, module, true)); final Pair<IntermediateOutputCompiler, Module> pair = new Pair<IntermediateOutputCompiler, Module>(compiler, module); final Pair<VirtualFile, VirtualFile> outputs = new Pair<VirtualFile, VirtualFile>(productionOutput, testOutput); myGenerationCompilerModuleToOutputDirMap.put(pair, outputs); } if (config.getAnnotationProcessingConfiguration(module).isEnabled()) { final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); if (path != null) { lookupVFile(lfs, path); // ensure the file is created and added to VFS } } } } } public void setCompilerFilter(CompilerFilter compilerFilter) { myCompilerFilter = compilerFilter == null? CompilerFilter.ALL : compilerFilter; } public void rebuild(CompileStatusNotification callback) { final CompileScope compileScope; ProjectCompileScope projectScope = new ProjectCompileScope(myProject); if (useOutOfProcessBuild()) { compileScope = projectScope; } else { CompileScope scopeWithArtifacts = ArtifactCompileScope.createScopeWithArtifacts(projectScope, ArtifactUtil.getArtifactWithOutputPaths(myProject), false); compileScope = addAdditionalRoots(scopeWithArtifacts, ALL_EXCEPT_SOURCE_PROCESSING); } doRebuild(callback, null, true, compileScope); } public void make(CompileScope scope, CompileStatusNotification callback) { if (!useOutOfProcessBuild()) { scope = addAdditionalRoots(scope, ALL_EXCEPT_SOURCE_PROCESSING); } if (validateCompilerConfiguration(scope, false)) { startup(scope, false, false, callback, null, true); } else { callback.finished(true, 0, 0, DummyCompileContext.getInstance()); } } public boolean isUpToDate(CompileScope scope) { if (LOG.isDebugEnabled()) { LOG.debug("isUpToDate operation started"); } if (!useOutOfProcessBuild()) { scope = addAdditionalRoots(scope, ALL_EXCEPT_SOURCE_PROCESSING); } final CompilerTask task = new CompilerTask(myProject, "Classes up-to-date check", true, false, false, isCompilationStartedAutomatically(scope)); final DependencyCache cache = useOutOfProcessBuild()? null : createDependencyCache(); final CompileContextImpl compileContext = new CompileContextImpl(myProject, task, scope, cache, true, false); if (!useOutOfProcessBuild()) { checkCachesVersion(compileContext, ManagingFS.getInstance().getCreationTimestamp()); if (compileContext.isRebuildRequested()) { if (LOG.isDebugEnabled()) { LOG.debug("Rebuild requested, up-to-date=false"); } return false; } for (Map.Entry<Pair<IntermediateOutputCompiler, Module>, Pair<VirtualFile, VirtualFile>> entry : myGenerationCompilerModuleToOutputDirMap.entrySet()) { final Pair<VirtualFile, VirtualFile> outputs = entry.getValue(); final Pair<IntermediateOutputCompiler, Module> key = entry.getKey(); final Module module = key.getSecond(); compileContext.assignModule(outputs.getFirst(), module, false, key.getFirst()); compileContext.assignModule(outputs.getSecond(), module, true, key.getFirst()); } } final Ref<ExitStatus> result = new Ref<ExitStatus>(); final Runnable compileWork; if (useOutOfProcessBuild()) { compileWork = new Runnable() { public void run() { final ProgressIndicator indicator = compileContext.getProgressIndicator(); if (indicator.isCanceled() || myProject.isDisposed()) { return; } try { final RequestFuture future = compileInExternalProcess(compileContext, true); if (future != null) { while (!future.waitFor(200L , TimeUnit.MILLISECONDS)) { if (indicator.isCanceled()) { future.cancel(false); } } } } catch (Throwable e) { LOG.error(e); } finally { result.set(COMPILE_SERVER_BUILD_STATUS.get(compileContext)); CompilerCacheManager.getInstance(myProject).flushCaches(); } } }; } else { compileWork = new Runnable() { public void run() { try { myAllOutputDirectories = getAllOutputDirectories(compileContext); // need this for updating zip archives experiment, uncomment if the feature is turned on //myOutputFinder = new OutputPathFinder(myAllOutputDirectories); result.set(doCompile(compileContext, false, false, true)); } finally { CompilerCacheManager.getInstance(myProject).flushCaches(); } } }; } task.start(compileWork, null); if (LOG.isDebugEnabled()) { LOG.debug("isUpToDate operation finished"); } return ExitStatus.UP_TO_DATE.equals(result.get()); } private DependencyCache createDependencyCache() { return new DependencyCache(myCachesDirectoryPath + File.separator + ".dependency-info"); } public void compile(CompileScope scope, CompileStatusNotification callback, boolean clearingOutputDirsPossible) { myShouldClearOutputDirectory &= clearingOutputDirsPossible; if (containsFileIndexScopes(scope)) { scope = addAdditionalRoots(scope, ALL_EXCEPT_SOURCE_PROCESSING); } if (validateCompilerConfiguration(scope, false)) { startup(scope, false, true, callback, null, true); } else { callback.finished(true, 0, 0, DummyCompileContext.getInstance()); } } private static boolean containsFileIndexScopes(CompileScope scope) { if (scope instanceof CompositeScope) { for (CompileScope childScope : ((CompositeScope)scope).getScopes()) { if (containsFileIndexScopes(childScope)) { return true; } } } return scope instanceof FileIndexCompileScope; } private static class CompileStatus { final int CACHE_FORMAT_VERSION; final boolean COMPILATION_IN_PROGRESS; final long VFS_CREATION_STAMP; private CompileStatus(int cacheVersion, boolean isCompilationInProgress, long vfsStamp) { CACHE_FORMAT_VERSION = cacheVersion; COMPILATION_IN_PROGRESS = isCompilationInProgress; VFS_CREATION_STAMP = vfsStamp; } } private CompileStatus readStatus() { final boolean isInProgress = getLockFile().exists(); int version = -1; long vfsStamp = -1L; try { final File versionFile = new File(myCachesDirectoryPath, VERSION_FILE_NAME); DataInputStream in = new DataInputStream(new FileInputStream(versionFile)); try { version = in.readInt(); try { vfsStamp = in.readLong(); } catch (IOException ignored) { } } finally { in.close(); } } catch (FileNotFoundException e) { // ignore } catch (IOException e) { LOG.info(e); // may happen in case of IDEA crashed and the file is not written properly return null; } return new CompileStatus(version, isInProgress, vfsStamp); } private void writeStatus(CompileStatus status, CompileContext context) { final File statusFile = new File(myCachesDirectoryPath, VERSION_FILE_NAME); final File lockFile = getLockFile(); try { FileUtil.createIfDoesntExist(statusFile); DataOutputStream out = new DataOutputStream(new FileOutputStream(statusFile)); try { out.writeInt(status.CACHE_FORMAT_VERSION); out.writeLong(status.VFS_CREATION_STAMP); } finally { out.close(); } if (status.COMPILATION_IN_PROGRESS) { FileUtil.createIfDoesntExist(lockFile); } else { deleteFile(lockFile); } } catch (IOException e) { context.addMessage(CompilerMessageCategory.ERROR, CompilerBundle.message("compiler.error.exception", e.getMessage()), null, -1, -1); } } private File getLockFile() { return new File(CompilerPaths.getCompilerSystemDirectory(myProject), LOCK_FILE_NAME); } private void doRebuild(CompileStatusNotification callback, CompilerMessage message, final boolean checkCachesVersion, final CompileScope compileScope) { if (validateCompilerConfiguration(compileScope, !useOutOfProcessBuild())) { startup(compileScope, true, false, callback, message, checkCachesVersion); } else { callback.finished(true, 0, 0, DummyCompileContext.getInstance()); } } private CompileScope addAdditionalRoots(CompileScope originalScope, final CompilerFilter filter) { CompileScope scope = attachIntermediateOutputDirectories(originalScope, filter); final AdditionalCompileScopeProvider[] scopeProviders = Extensions.getExtensions(AdditionalCompileScopeProvider.EXTENSION_POINT_NAME); CompileScope baseScope = scope; for (AdditionalCompileScopeProvider scopeProvider : scopeProviders) { final CompileScope additionalScope = scopeProvider.getAdditionalScope(baseScope, filter, myProject); if (additionalScope != null) { scope = new CompositeScope(scope, additionalScope); } } return scope; } private CompileScope attachIntermediateOutputDirectories(CompileScope originalScope, CompilerFilter filter) { CompileScope scope = originalScope; final Set<Module> affected = new HashSet<Module>(Arrays.asList(originalScope.getAffectedModules())); for (Map.Entry<Pair<IntermediateOutputCompiler, Module>, Pair<VirtualFile, VirtualFile>> entry : myGenerationCompilerModuleToOutputDirMap.entrySet()) { final Module module = entry.getKey().getSecond(); if (affected.contains(module) && filter.acceptCompiler(entry.getKey().getFirst())) { final Pair<VirtualFile, VirtualFile> outputs = entry.getValue(); scope = new CompositeScope(scope, new FileSetCompileScope(Arrays.asList(outputs.getFirst(), outputs.getSecond()), new Module[]{module})); } } return scope; } public static void setCompilationStartedAutomatically(CompileScope scope) { //todo[nik] pass this option as a parameter to compile/make methods instead scope.putUserData(COMPILATION_STARTED_AUTOMATICALLY, Boolean.TRUE); } private static boolean isCompilationStartedAutomatically(CompileScope scope) { return Boolean.TRUE.equals(scope.getUserData(COMPILATION_STARTED_AUTOMATICALLY)); } private void attachAnnotationProcessorsOutputDirectories(CompileContextEx context) { final LocalFileSystem lfs = LocalFileSystem.getInstance(); final CompilerConfiguration config = CompilerConfiguration.getInstance(myProject); final Set<Module> affected = new HashSet<Module>(Arrays.asList(context.getCompileScope().getAffectedModules())); for (Module module : affected) { if (!config.getAnnotationProcessingConfiguration(module).isEnabled()) { continue; } final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); if (path == null) { continue; } final VirtualFile vFile = lfs.findFileByPath(path); if (vFile == null) { continue; } if (ModuleRootManager.getInstance(module).getFileIndex().isInSourceContent(vFile)) { // no need to add, is already marked as source continue; } context.addScope(new FileSetCompileScope(Collections.singletonList(vFile), new Module[]{module})); context.assignModule(vFile, module, false, null); } } @Nullable private RequestFuture compileInExternalProcess(final @NotNull CompileContextImpl compileContext, final boolean onlyCheckUpToDate) throws Exception { final CompileScope scope = compileContext.getCompileScope(); final Collection<String> paths = CompileScopeUtil.fetchFiles(compileContext); List<TargetTypeBuildScope> scopes = new ArrayList<TargetTypeBuildScope>(); final boolean forceBuild = !compileContext.isMake(); if (!compileContext.isRebuild() && !CompileScopeUtil.allProjectModulesAffected(compileContext)) { CompileScopeUtil.addScopesForModules(Arrays.asList(scope.getAffectedModules()), scopes, forceBuild); } else { scopes.addAll(CmdlineProtoUtil.createAllModulesScopes(forceBuild)); } if (paths.isEmpty()) { for (BuildTargetScopeProvider provider : BuildTargetScopeProvider.EP_NAME.getExtensions()) { scopes = CompileScopeUtil.mergeScopes(scopes, provider.getBuildTargetScopes(scope, myCompilerFilter, myProject, forceBuild)); } } // need to pass scope's user data to server final Map<String, String> builderParams; if (onlyCheckUpToDate) { builderParams = Collections.emptyMap(); } else { final Map<Key, Object> exported = scope.exportUserData(); if (!exported.isEmpty()) { builderParams = new HashMap<String, String>(); for (Map.Entry<Key, Object> entry : exported.entrySet()) { final String _key = entry.getKey().toString(); final String _value = entry.getValue().toString(); builderParams.put(_key, _value); } } else { builderParams = Collections.emptyMap(); } } final MessageBus messageBus = myProject.getMessageBus(); final MultiMap<String, Artifact> outputToArtifact = ArtifactCompilerUtil.containsArtifacts(scopes) ? ArtifactCompilerUtil.createOutputToArtifactMap(myProject) : null; final BuildManager buildManager = BuildManager.getInstance(); buildManager.cancelAutoMakeTasks(myProject); return buildManager.scheduleBuild(myProject, compileContext.isRebuild(), compileContext.isMake(), onlyCheckUpToDate, scopes, paths, builderParams, new DefaultMessageHandler(myProject) { @Override public void buildStarted(UUID sessionId) { } @Override public void sessionTerminated(final UUID sessionId) { if (compileContext.shouldUpdateProblemsView()) { final ProblemsView view = ProblemsViewImpl.SERVICE.getInstance(myProject); view.clearProgress(); view.clearOldMessages(compileContext.getCompileScope(), compileContext.getSessionId()); } } @Override public void handleFailure(UUID sessionId, CmdlineRemoteProto.Message.Failure failure) { compileContext.addMessage(CompilerMessageCategory.ERROR, failure.hasDescription()? failure.getDescription() : "", null, -1, -1); final String trace = failure.hasStacktrace()? failure.getStacktrace() : null; if (trace != null) { LOG.info(trace); } compileContext.putUserData(COMPILE_SERVER_BUILD_STATUS, ExitStatus.ERRORS); } @Override protected void handleCompileMessage(UUID sessionId, CmdlineRemoteProto.Message.BuilderMessage.CompileMessage message) { final CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind kind = message.getKind(); //System.out.println(compilerMessage.getText()); final String messageText = message.getText(); if (kind == CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.PROGRESS) { final ProgressIndicator indicator = compileContext.getProgressIndicator(); indicator.setText(messageText); if (message.hasDone()) { indicator.setFraction(message.getDone()); } } else { final CompilerMessageCategory category = kind == CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.ERROR ? CompilerMessageCategory.ERROR : kind == CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.WARNING ? CompilerMessageCategory.WARNING : CompilerMessageCategory.INFORMATION; String sourceFilePath = message.hasSourceFilePath() ? message.getSourceFilePath() : null; if (sourceFilePath != null) { sourceFilePath = FileUtil.toSystemIndependentName(sourceFilePath); } final long line = message.hasLine() ? message.getLine() : -1; final long column = message.hasColumn() ? message.getColumn() : -1; final String srcUrl = sourceFilePath != null ? VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, sourceFilePath) : null; compileContext.addMessage(category, messageText, srcUrl, (int)line, (int)column); } } @Override protected void handleBuildEvent(UUID sessionId, CmdlineRemoteProto.Message.BuilderMessage.BuildEvent event) { final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Type eventType = event.getEventType(); switch (eventType) { case FILES_GENERATED: final List<CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.GeneratedFile> generated = event.getGeneratedFilesList(); final CompilationStatusListener publisher = messageBus.syncPublisher(CompilerTopics.COMPILATION_STATUS); Set<String> writtenArtifactOutputPaths = outputToArtifact != null ? new THashSet<String>(FileUtil.PATH_HASHING_STRATEGY) : null; for (CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.GeneratedFile generatedFile : generated) { final String root = FileUtil.toSystemIndependentName(generatedFile.getOutputRoot()); final String relativePath = FileUtil.toSystemIndependentName(generatedFile.getRelativePath()); publisher.fileGenerated(root, relativePath); if (outputToArtifact != null) { Collection<Artifact> artifacts = outputToArtifact.get(root); if (!artifacts.isEmpty()) { for (Artifact artifact : artifacts) { ArtifactsCompiler.addChangedArtifact(compileContext, artifact); } writtenArtifactOutputPaths.add(FileUtil.toSystemDependentName(DeploymentUtil.appendToPath(root, relativePath))); } } } if (writtenArtifactOutputPaths != null && !writtenArtifactOutputPaths.isEmpty()) { ArtifactsCompiler.addWrittenPaths(compileContext, writtenArtifactOutputPaths); } break; case BUILD_COMPLETED: ExitStatus status = ExitStatus.SUCCESS; if (event.hasCompletionStatus()) { final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status completionStatus = event.getCompletionStatus(); switch (completionStatus) { case CANCELED: status = ExitStatus.CANCELLED; break; case ERRORS: status = ExitStatus.ERRORS; break; case SUCCESS: status = ExitStatus.SUCCESS; break; case UP_TO_DATE: status = ExitStatus.UP_TO_DATE; break; } } compileContext.putUserDataIfAbsent(COMPILE_SERVER_BUILD_STATUS, status); break; case CUSTOM_BUILDER_MESSAGE: if (event.hasCustomBuilderMessage()) { CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.CustomBuilderMessage message = event.getCustomBuilderMessage(); messageBus.syncPublisher(CustomBuilderMessageHandler.TOPIC).messageReceived(message.getBuilderId(), message.getMessageType(), message.getMessageText()); } break; } } }); } private static final Key<ExitStatus> COMPILE_SERVER_BUILD_STATUS = Key.create("COMPILE_SERVER_BUILD_STATUS"); private void startup(final CompileScope scope, final boolean isRebuild, final boolean forceCompile, final CompileStatusNotification callback, final CompilerMessage message, final boolean checkCachesVersion) { ApplicationManager.getApplication().assertIsDispatchThread(); final boolean useExtProcessBuild = useOutOfProcessBuild(); final String contentName = forceCompile ? CompilerBundle.message("compiler.content.name.compile") : CompilerBundle.message("compiler.content.name.make"); final CompilerTask compileTask = new CompilerTask(myProject, contentName, ApplicationManager.getApplication().isUnitTestMode(), true, true, isCompilationStartedAutomatically(scope)); StatusBar.Info.set("", myProject, "Compiler"); if (useExtProcessBuild) { // ensure the project model seen by build process is up-to-date myProject.save(); if (!ApplicationManager.getApplication().isUnitTestMode()) { ApplicationManager.getApplication().saveSettings(); } } PsiDocumentManager.getInstance(myProject).commitAllDocuments(); FileDocumentManager.getInstance().saveAllDocuments(); final DependencyCache dependencyCache = useExtProcessBuild ? null: createDependencyCache(); final CompileContextImpl compileContext = new CompileContextImpl(myProject, compileTask, scope, dependencyCache, !isRebuild && !forceCompile, isRebuild); if (!useExtProcessBuild) { for (Map.Entry<Pair<IntermediateOutputCompiler, Module>, Pair<VirtualFile, VirtualFile>> entry : myGenerationCompilerModuleToOutputDirMap.entrySet()) { final Pair<VirtualFile, VirtualFile> outputs = entry.getValue(); final Pair<IntermediateOutputCompiler, Module> key = entry.getKey(); final Module module = key.getSecond(); compileContext.assignModule(outputs.getFirst(), module, false, key.getFirst()); compileContext.assignModule(outputs.getSecond(), module, true, key.getFirst()); } attachAnnotationProcessorsOutputDirectories(compileContext); } final Runnable compileWork; if (useExtProcessBuild) { compileWork = new Runnable() { public void run() { final ProgressIndicator indicator = compileContext.getProgressIndicator(); if (indicator.isCanceled() || myProject.isDisposed()) { if (callback != null) { callback.finished(true, 0, 0, compileContext); } return; } try { LOG.info("COMPILATION STARTED (BUILD PROCESS)"); if (message != null) { compileContext.addMessage(message); } final boolean beforeTasksOk = executeCompileTasks(compileContext, true); final int errorCount = compileContext.getMessageCount(CompilerMessageCategory.ERROR); if (!beforeTasksOk || errorCount > 0) { COMPILE_SERVER_BUILD_STATUS.set(compileContext, errorCount > 0? ExitStatus.ERRORS : ExitStatus.CANCELLED); return; } final RequestFuture future = compileInExternalProcess(compileContext, false); if (future != null) { while (!future.waitFor(200L , TimeUnit.MILLISECONDS)) { if (indicator.isCanceled()) { future.cancel(false); } } if (!executeCompileTasks(compileContext, false)) { COMPILE_SERVER_BUILD_STATUS.set(compileContext, ExitStatus.CANCELLED); } if (compileContext.getMessageCount(CompilerMessageCategory.ERROR) > 0) { COMPILE_SERVER_BUILD_STATUS.set(compileContext, ExitStatus.ERRORS); } } } catch (Throwable e) { LOG.error(e); // todo } finally { CompilerCacheManager.getInstance(myProject).flushCaches(); final long duration = notifyCompilationCompleted(compileContext, callback, COMPILE_SERVER_BUILD_STATUS.get(compileContext), true); CompilerUtil.logDuration( "\tCOMPILATION FINISHED (BUILD PROCESS); Errors: " + compileContext.getMessageCount(CompilerMessageCategory.ERROR) + "; warnings: " + compileContext.getMessageCount(CompilerMessageCategory.WARNING), duration ); } } }; } else { compileWork = new Runnable() { public void run() { if (compileContext.getProgressIndicator().isCanceled()) { if (callback != null) { callback.finished(true, 0, 0, compileContext); } return; } try { if (myProject.isDisposed()) { return; } LOG.info("COMPILATION STARTED"); if (message != null) { compileContext.addMessage(message); } TranslatingCompilerFilesMonitor.getInstance().ensureInitializationCompleted(myProject, compileContext.getProgressIndicator()); doCompile(compileContext, isRebuild, forceCompile, callback, checkCachesVersion); } finally { FileUtil.delete(CompilerPaths.getRebuildMarkerFile(myProject)); } } }; } compileTask.start(compileWork, new Runnable() { public void run() { if (isRebuild) { final int rv = Messages.showOkCancelDialog( myProject, "You are about to rebuild the whole project.\nRun 'Make Project' instead?", "Confirm Project Rebuild", "Make", "Rebuild", Messages.getQuestionIcon() ); if (rv == 0 /*yes, please, do run make*/) { startup(scope, false, false, callback, null, checkCachesVersion); return; } } startup(scope, isRebuild, forceCompile, callback, message, checkCachesVersion); } }); } @Nullable @TestOnly public static ExitStatus getExternalBuildExitStatus(CompileContext context) { return context.getUserData(COMPILE_SERVER_BUILD_STATUS); } private void doCompile(final CompileContextImpl compileContext, final boolean isRebuild, final boolean forceCompile, final CompileStatusNotification callback, final boolean checkCachesVersion) { ExitStatus status = ExitStatus.ERRORS; boolean wereExceptions = false; final long vfsTimestamp = (ManagingFS.getInstance()).getCreationTimestamp(); try { if (checkCachesVersion) { checkCachesVersion(compileContext, vfsTimestamp); if (compileContext.isRebuildRequested()) { return; } } writeStatus(new CompileStatus(CompilerConfigurationImpl.DEPENDENCY_FORMAT_VERSION, true, vfsTimestamp), compileContext); if (compileContext.getMessageCount(CompilerMessageCategory.ERROR) > 0) { return; } myAllOutputDirectories = getAllOutputDirectories(compileContext); status = doCompile(compileContext, isRebuild, forceCompile, false); } catch (Throwable ex) { if (ApplicationManager.getApplication().isUnitTestMode()) { throw new RuntimeException(ex); } wereExceptions = true; final PluginId pluginId = IdeErrorsDialog.findPluginId(ex); final StringBuilder message = new StringBuilder(); message.append("Internal error"); if (pluginId != null) { message.append(" (Plugin: ").append(pluginId).append(")"); } message.append(": ").append(ex.getMessage()); compileContext.addMessage(CompilerMessageCategory.ERROR, message.toString(), null, -1, -1); if (pluginId != null) { throw new PluginException(ex, pluginId); } throw new RuntimeException(ex); } finally { dropDependencyCache(compileContext); CompilerCacheManager.getInstance(myProject).flushCaches(); if (compileContext.isRebuildRequested()) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { final CompilerMessageImpl msg = new CompilerMessageImpl(myProject, CompilerMessageCategory.INFORMATION, compileContext.getRebuildReason()); doRebuild(callback, msg, false, compileContext.getCompileScope()); } }, ModalityState.NON_MODAL); } else { if (!myProject.isDisposed()) { writeStatus(new CompileStatus(CompilerConfigurationImpl.DEPENDENCY_FORMAT_VERSION, wereExceptions, vfsTimestamp), compileContext); } final long duration = notifyCompilationCompleted(compileContext, callback, status, false); CompilerUtil.logDuration( "\tCOMPILATION FINISHED; Errors: " + compileContext.getMessageCount(CompilerMessageCategory.ERROR) + "; warnings: " + compileContext.getMessageCount(CompilerMessageCategory.WARNING), duration ); } } } /** @noinspection SSBasedInspection*/ private long notifyCompilationCompleted(final CompileContextImpl compileContext, final CompileStatusNotification callback, final ExitStatus _status, final boolean refreshOutputRoots) { final long duration = System.currentTimeMillis() - compileContext.getStartCompilationStamp(); if (refreshOutputRoots) { // refresh on output roots is required in order for the order enumerator to see all roots via VFS final Set<File> outputs = new HashSet<File>(); for (final String path : CompilerPathsEx.getOutputPaths(ModuleManager.getInstance(myProject).getModules())) { outputs.add(new File(path)); } if (!outputs.isEmpty()) { final ProgressIndicator indicator = compileContext.getProgressIndicator(); indicator.setText("Synchronizing output directories..."); LocalFileSystem.getInstance().refreshIoFiles(outputs, false, false, null); indicator.setText(""); } } SwingUtilities.invokeLater(new Runnable() { public void run() { int errorCount = 0; int warningCount = 0; try { errorCount = compileContext.getMessageCount(CompilerMessageCategory.ERROR); warningCount = compileContext.getMessageCount(CompilerMessageCategory.WARNING); if (!myProject.isDisposed()) { final String statusMessage = createStatusMessage(_status, warningCount, errorCount, duration); final MessageType messageType = errorCount > 0 ? MessageType.ERROR : warningCount > 0 ? MessageType.WARNING : MessageType.INFO; if (duration > ONE_MINUTE_MS) { ToolWindowManager.getInstance(myProject).notifyByBalloon(ToolWindowId.MESSAGES_WINDOW, messageType, statusMessage); } CompilerManager.NOTIFICATION_GROUP.createNotification(statusMessage, messageType).notify(myProject); if (_status != ExitStatus.UP_TO_DATE && compileContext.getMessageCount(null) > 0) { compileContext.addMessage(CompilerMessageCategory.INFORMATION, statusMessage, null, -1, -1); } } } finally { if (callback != null) { callback.finished(_status == ExitStatus.CANCELLED, errorCount, warningCount, compileContext); } } } }); return duration; } private void checkCachesVersion(final CompileContextImpl compileContext, final long currentVFSTimestamp) { if (CompilerPaths.getRebuildMarkerFile(compileContext.getProject()).exists()) { compileContext.requestRebuildNextTime("Compiler caches are out of date, project rebuild is required"); return; } final CompileStatus compileStatus = readStatus(); if (compileStatus == null) { compileContext.requestRebuildNextTime(CompilerBundle.message("error.compiler.caches.corrupted")); } else if (compileStatus.CACHE_FORMAT_VERSION != -1 && compileStatus.CACHE_FORMAT_VERSION != CompilerConfigurationImpl.DEPENDENCY_FORMAT_VERSION) { compileContext.requestRebuildNextTime(CompilerBundle.message("error.caches.old.format")); } else if (compileStatus.COMPILATION_IN_PROGRESS) { compileContext.requestRebuildNextTime(CompilerBundle.message("error.previous.compilation.failed")); } else if (compileStatus.VFS_CREATION_STAMP >= 0L){ if (currentVFSTimestamp != compileStatus.VFS_CREATION_STAMP) { compileContext.requestRebuildNextTime(CompilerBundle.message("error.vfs.was.rebuilt")); } } } private static String createStatusMessage(final ExitStatus status, final int warningCount, final int errorCount, long duration) { String message; if (status == ExitStatus.CANCELLED) { message = CompilerBundle.message("status.compilation.aborted"); } else if (status == ExitStatus.UP_TO_DATE) { message = CompilerBundle.message("status.all.up.to.date"); } else { if (status == ExitStatus.SUCCESS) { message = warningCount > 0 ? CompilerBundle.message("status.compilation.completed.successfully.with.warnings", warningCount) : CompilerBundle.message("status.compilation.completed.successfully"); } else { message = CompilerBundle.message("status.compilation.completed.successfully.with.warnings.and.errors", errorCount, warningCount); } message = message + " in " + Utils.formatDuration(duration); } return message; } private ExitStatus doCompile(final CompileContextEx context, boolean isRebuild, final boolean forceCompile, final boolean onlyCheckStatus) { try { if (isRebuild) { deleteAll(context); } else if (forceCompile) { if (myShouldClearOutputDirectory) { clearAffectedOutputPathsIfPossible(context); } } if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { if (LOG.isDebugEnabled()) { logErrorMessages(context); } return ExitStatus.ERRORS; } if (!onlyCheckStatus) { if (!executeCompileTasks(context, true)) { if (LOG.isDebugEnabled()) { LOG.debug("Compilation cancelled"); } return ExitStatus.CANCELLED; } } if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { if (LOG.isDebugEnabled()) { logErrorMessages(context); } return ExitStatus.ERRORS; } boolean needRecalcOutputDirs = false; if (Registry.is(PROP_PERFORM_INITIAL_REFRESH) || !Boolean.valueOf(REFRESH_DONE_KEY.get(myProject, Boolean.FALSE))) { REFRESH_DONE_KEY.set(myProject, Boolean.TRUE); final long refreshStart = System.currentTimeMillis(); //need this to make sure the VFS is built final List<VirtualFile> outputsToRefresh = new ArrayList<VirtualFile>(); final VirtualFile[] all = context.getAllOutputDirectories(); final ProgressIndicator progressIndicator = context.getProgressIndicator(); //final int totalCount = all.length + myGenerationCompilerModuleToOutputDirMap.size() * 2; progressIndicator.pushState(); progressIndicator.setText("Inspecting output directories..."); try { for (VirtualFile output : all) { if (output.isValid()) { walkChildren(output, context); } else { needRecalcOutputDirs = true; final File file = new File(output.getPath()); if (!file.exists()) { final boolean created = file.mkdirs(); if (!created) { context.addMessage(CompilerMessageCategory.ERROR, "Failed to create output directory " + file.getPath(), null, 0, 0); return ExitStatus.ERRORS; } } output = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); if (output == null) { context.addMessage(CompilerMessageCategory.ERROR, "Failed to locate output directory " + file.getPath(), null, 0, 0); return ExitStatus.ERRORS; } } outputsToRefresh.add(output); } for (Pair<IntermediateOutputCompiler, Module> pair : myGenerationCompilerModuleToOutputDirMap.keySet()) { final Pair<VirtualFile, VirtualFile> generated = myGenerationCompilerModuleToOutputDirMap.get(pair); walkChildren(generated.getFirst(), context); outputsToRefresh.add(generated.getFirst()); walkChildren(generated.getSecond(), context); outputsToRefresh.add(generated.getSecond()); } RefreshQueue.getInstance().refresh(false, true, null, outputsToRefresh); if (progressIndicator.isCanceled()) { return ExitStatus.CANCELLED; } } finally { progressIndicator.popState(); } final long initialRefreshTime = System.currentTimeMillis() - refreshStart; CompilerUtil.logDuration("Initial VFS refresh", initialRefreshTime); } //DumbService.getInstance(myProject).waitForSmartMode(); final Semaphore semaphore = new Semaphore(); semaphore.down(); DumbService.getInstance(myProject).runWhenSmart(new Runnable() { public void run() { semaphore.up(); } }); while (!semaphore.waitFor(500)) { if (context.getProgressIndicator().isCanceled()) { return ExitStatus.CANCELLED; } } if (needRecalcOutputDirs) { context.recalculateOutputDirs(); } boolean didSomething = false; final CompilerManager compilerManager = CompilerManager.getInstance(myProject); GenericCompilerRunner runner = new GenericCompilerRunner(context, isRebuild, onlyCheckStatus, compilerManager.getCompilers(GenericCompiler.class, myCompilerFilter)); try { didSomething |= generateSources(compilerManager, context, forceCompile, onlyCheckStatus); didSomething |= invokeFileProcessingCompilers(compilerManager, context, SourceInstrumentingCompiler.class, FILE_PROCESSING_COMPILER_ADAPTER_FACTORY, forceCompile, true, onlyCheckStatus); didSomething |= invokeFileProcessingCompilers(compilerManager, context, SourceProcessingCompiler.class, FILE_PROCESSING_COMPILER_ADAPTER_FACTORY, forceCompile, true, onlyCheckStatus); final CompileScope intermediateSources = attachIntermediateOutputDirectories(new CompositeScope(CompileScope.EMPTY_ARRAY) { @NotNull public Module[] getAffectedModules() { return context.getCompileScope().getAffectedModules(); } }, SOURCE_PROCESSING_ONLY); context.addScope(intermediateSources); didSomething |= translate(context, compilerManager, forceCompile, isRebuild, onlyCheckStatus); didSomething |= invokeFileProcessingCompilers(compilerManager, context, ClassInstrumentingCompiler.class, FILE_PROCESSING_COMPILER_ADAPTER_FACTORY, isRebuild, false, onlyCheckStatus); didSomething |= runner.invokeCompilers(GenericCompiler.CompileOrderPlace.CLASS_INSTRUMENTING); // explicitly passing forceCompile = false because in scopes that is narrower than ProjectScope it is impossible // to understand whether the class to be processed is in scope or not. Otherwise compiler may process its items even if // there were changes in completely independent files. didSomething |= invokeFileProcessingCompilers(compilerManager, context, ClassPostProcessingCompiler.class, FILE_PROCESSING_COMPILER_ADAPTER_FACTORY, isRebuild, false, onlyCheckStatus); didSomething |= runner.invokeCompilers(GenericCompiler.CompileOrderPlace.CLASS_POST_PROCESSING); didSomething |= invokeFileProcessingCompilers(compilerManager, context, PackagingCompiler.class, FILE_PACKAGING_COMPILER_ADAPTER_FACTORY, isRebuild, false, onlyCheckStatus); didSomething |= runner.invokeCompilers(GenericCompiler.CompileOrderPlace.PACKAGING); didSomething |= invokeFileProcessingCompilers(compilerManager, context, Validator.class, FILE_PROCESSING_COMPILER_ADAPTER_FACTORY, forceCompile, true, onlyCheckStatus); didSomething |= runner.invokeCompilers(GenericCompiler.CompileOrderPlace.VALIDATING); } catch (ExitException e) { if (LOG.isDebugEnabled()) { LOG.debug(e); logErrorMessages(context); } return e.getExitStatus(); } finally { // drop in case it has not been dropped yet. dropDependencyCache(context); final VirtualFile[] allOutputDirs = context.getAllOutputDirectories(); if (didSomething && GENERATE_CLASSPATH_INDEX) { CompilerUtil.runInContext(context, "Generating classpath index...", new ThrowableRunnable<RuntimeException>(){ public void run() { int count = 0; for (VirtualFile file : allOutputDirs) { context.getProgressIndicator().setFraction((double)++count / allOutputDirs.length); createClasspathIndex(file); } } }); } } if (!onlyCheckStatus) { if (!executeCompileTasks(context, false)) { return ExitStatus.CANCELLED; } final int constantSearchesCount = ChangedConstantsDependencyProcessor.getConstantSearchesCount(context); LOG.debug("Constants searches: " + constantSearchesCount); } if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { if (LOG.isDebugEnabled()) { logErrorMessages(context); } return ExitStatus.ERRORS; } if (!didSomething) { return ExitStatus.UP_TO_DATE; } return ExitStatus.SUCCESS; } catch (ProcessCanceledException e) { return ExitStatus.CANCELLED; } } private void clearAffectedOutputPathsIfPossible(final CompileContextEx context) { final List<File> scopeOutputs = new ReadAction<List<File>>() { protected void run(final Result<List<File>> result) { final MultiMap<File, Module> outputToModulesMap = new MultiMap<File, Module>(); for (Module module : ModuleManager.getInstance(myProject).getModules()) { final CompilerModuleExtension compilerModuleExtension = CompilerModuleExtension.getInstance(module); if (compilerModuleExtension == null) { continue; } final String outputPathUrl = compilerModuleExtension.getCompilerOutputUrl(); if (outputPathUrl != null) { final String path = VirtualFileManager.extractPath(outputPathUrl); outputToModulesMap.putValue(new File(path), module); } final String outputPathForTestsUrl = compilerModuleExtension.getCompilerOutputUrlForTests(); if (outputPathForTestsUrl != null) { final String path = VirtualFileManager.extractPath(outputPathForTestsUrl); outputToModulesMap.putValue(new File(path), module); } } final Set<Module> affectedModules = new HashSet<Module>(Arrays.asList(context.getCompileScope().getAffectedModules())); List<File> scopeOutputs = new ArrayList<File>(affectedModules.size() * 2); for (File output : outputToModulesMap.keySet()) { if (affectedModules.containsAll(outputToModulesMap.get(output))) { scopeOutputs.add(output); } } final Set<Artifact> artifactsToBuild = ArtifactCompileScope.getArtifactsToBuild(myProject, context.getCompileScope(), true); for (Artifact artifact : artifactsToBuild) { final String outputFilePath = ((ArtifactImpl)artifact).getOutputDirectoryPathToCleanOnRebuild(); if (outputFilePath != null) { scopeOutputs.add(new File(FileUtil.toSystemDependentName(outputFilePath))); } } result.setResult(scopeOutputs); } }.execute().getResultObject(); if (scopeOutputs.size() > 0) { CompilerUtil.runInContext(context, CompilerBundle.message("progress.clearing.output"), new ThrowableRunnable<RuntimeException>() { public void run() { CompilerUtil.clearOutputDirectories(scopeOutputs); } }); } } private static void logErrorMessages(final CompileContext context) { final CompilerMessage[] errors = context.getMessages(CompilerMessageCategory.ERROR); if (errors.length > 0) { LOG.debug("Errors reported: "); for (CompilerMessage error : errors) { LOG.debug("\t" + error.getMessage()); } } } private static void walkChildren(VirtualFile from, final CompileContext context) { VfsUtilCore.visitChildrenRecursively(from, new VirtualFileVisitor() { @Override public boolean visitFile(@NotNull VirtualFile file) { if (file.isDirectory()) { context.getProgressIndicator().checkCanceled(); context.getProgressIndicator().setText2(file.getPresentableUrl()); } return true; } }); } private static void createClasspathIndex(final VirtualFile file) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(new File(VfsUtilCore.virtualToIoFile(file), "classpath.index"))); try { writeIndex(writer, file, file); } finally { writer.close(); } } catch (IOException e) { // Ignore. Failed to create optional classpath index } } private static void writeIndex(final BufferedWriter writer, final VirtualFile root, final VirtualFile file) throws IOException { VfsUtilCore.visitChildrenRecursively(file, new VirtualFileVisitor() { @Override public boolean visitFile(@NotNull VirtualFile file) { try { writer.write(VfsUtilCore.getRelativePath(file, root, '/')); writer.write('\n'); return true; } catch (IOException e) { throw new VisitorException(e); } } }, IOException.class); } private static void dropDependencyCache(final CompileContextEx context) { CompilerUtil.runInContext(context, CompilerBundle.message("progress.saving.caches"), new ThrowableRunnable<RuntimeException>(){ public void run() { context.getDependencyCache().resetState(); } }); } private boolean generateSources(final CompilerManager compilerManager, CompileContextEx context, final boolean forceCompile, final boolean onlyCheckStatus) throws ExitException { boolean didSomething = false; final SourceGeneratingCompiler[] sourceGenerators = compilerManager.getCompilers(SourceGeneratingCompiler.class, myCompilerFilter); for (final SourceGeneratingCompiler sourceGenerator : sourceGenerators) { if (context.getProgressIndicator().isCanceled()) { throw new ExitException(ExitStatus.CANCELLED); } final boolean generatedSomething = generateOutput(context, sourceGenerator, forceCompile, onlyCheckStatus); if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { throw new ExitException(ExitStatus.ERRORS); } didSomething |= generatedSomething; } return didSomething; } private boolean translate(final CompileContextEx context, final CompilerManager compilerManager, final boolean forceCompile, boolean isRebuild, final boolean onlyCheckStatus) throws ExitException { boolean didSomething = false; final TranslatingCompiler[] translators = compilerManager.getCompilers(TranslatingCompiler.class, myCompilerFilter); final List<Chunk<Module>> sortedChunks = Collections.unmodifiableList(ApplicationManager.getApplication().runReadAction(new Computable<List<Chunk<Module>>>() { public List<Chunk<Module>> compute() { final ModuleManager moduleManager = ModuleManager.getInstance(myProject); return ModuleCompilerUtil.getSortedModuleChunks(myProject, Arrays.asList(moduleManager.getModules())); } })); final DumbService dumbService = DumbService.getInstance(myProject); try { final Set<Module> processedModules = new HashSet<Module>(); VirtualFile[] snapshot = null; final Map<Chunk<Module>, Collection<VirtualFile>> chunkMap = new HashMap<Chunk<Module>, Collection<VirtualFile>>(); int total = 0; int processed = 0; for (final Chunk<Module> currentChunk : sortedChunks) { final TranslatorsOutputSink sink = new TranslatorsOutputSink(context, translators); final Set<FileType> generatedTypes = new HashSet<FileType>(); Collection<VirtualFile> chunkFiles = chunkMap.get(currentChunk); final Set<VirtualFile> filesToRecompile = new HashSet<VirtualFile>(); final Set<VirtualFile> allDependent = new HashSet<VirtualFile>(); try { int round = 0; boolean compiledSomethingForThisChunk = false; Collection<VirtualFile> dependentFiles = Collections.emptyList(); final Function<Pair<int[], Set<VirtualFile>>, Pair<int[], Set<VirtualFile>>> dependencyFilter = new DependentClassesCumulativeFilter(); do { for (int currentCompiler = 0, translatorsLength = translators.length; currentCompiler < translatorsLength; currentCompiler++) { sink.setCurrentCompilerIndex(currentCompiler); final TranslatingCompiler compiler = translators[currentCompiler]; if (context.getProgressIndicator().isCanceled()) { throw new ExitException(ExitStatus.CANCELLED); } dumbService.waitForSmartMode(); if (snapshot == null || ContainerUtil.intersects(generatedTypes, compilerManager.getRegisteredInputTypes(compiler))) { // rescan snapshot if previously generated files may influence the input of this compiler final Set<VirtualFile> prevSnapshot = round > 0 && snapshot != null? new HashSet<VirtualFile>(Arrays.asList(snapshot)) : Collections.<VirtualFile>emptySet(); snapshot = ApplicationManager.getApplication().runReadAction(new Computable<VirtualFile[]>() { public VirtualFile[] compute() { return context.getCompileScope().getFiles(null, true); } }); recalculateChunkToFilesMap(context, sortedChunks, snapshot, chunkMap); if (round == 0) { chunkFiles = chunkMap.get(currentChunk); } else { final Set<VirtualFile> newFiles = new HashSet<VirtualFile>(chunkMap.get(currentChunk)); newFiles.removeAll(prevSnapshot); newFiles.removeAll(chunkFiles); if (!newFiles.isEmpty()) { final ArrayList<VirtualFile> merged = new ArrayList<VirtualFile>(chunkFiles.size() + newFiles.size()); merged.addAll(chunkFiles); merged.addAll(newFiles); chunkFiles = merged; } } total = snapshot.length * translatorsLength; } final CompileContextEx _context; if (compiler instanceof IntermediateOutputCompiler) { // wrap compile context so that output goes into intermediate directories final IntermediateOutputCompiler _compiler = (IntermediateOutputCompiler)compiler; _context = new CompileContextExProxy(context) { public VirtualFile getModuleOutputDirectory(final Module module) { return getGenerationOutputDir(_compiler, module, false); } public VirtualFile getModuleOutputDirectoryForTests(final Module module) { return getGenerationOutputDir(_compiler, module, true); } }; } else { _context = context; } final boolean compiledSomething = compileSources(_context, currentChunk, compiler, chunkFiles, round == 0? forceCompile : true, isRebuild, onlyCheckStatus, sink); processed += chunkFiles.size(); _context.getProgressIndicator().setFraction(((double)processed) / total); if (compiledSomething) { generatedTypes.addAll(compilerManager.getRegisteredOutputTypes(compiler)); } didSomething |= compiledSomething; compiledSomethingForThisChunk |= didSomething; if (_context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { break; // break the loop over compilers } } final boolean hasUnprocessedTraverseRoots = context.getDependencyCache().hasUnprocessedTraverseRoots(); if (!isRebuild && (compiledSomethingForThisChunk || hasUnprocessedTraverseRoots)) { final Set<VirtualFile> compiledWithErrors = CacheUtils.getFilesCompiledWithErrors(context); filesToRecompile.removeAll(sink.getCompiledSources()); filesToRecompile.addAll(compiledWithErrors); dependentFiles = CacheUtils.findDependentFiles(context, compiledWithErrors, dependencyFilter); if (!processedModules.isEmpty()) { for (Iterator<VirtualFile> it = dependentFiles.iterator(); it.hasNext();) { final VirtualFile next = it.next(); final Module module = context.getModuleByFile(next); if (module != null && processedModules.contains(module)) { it.remove(); } } } if (ourDebugMode) { if (!dependentFiles.isEmpty()) { for (VirtualFile dependentFile : dependentFiles) { System.out.println("FOUND TO RECOMPILE: " + dependentFile.getPresentableUrl()); } } else { System.out.println("NO FILES TO RECOMPILE"); } } if (!dependentFiles.isEmpty()) { filesToRecompile.addAll(dependentFiles); allDependent.addAll(dependentFiles); if (context.getProgressIndicator().isCanceled() || context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { break; } final List<VirtualFile> filesInScope = getFilesInScope(context, currentChunk, dependentFiles); if (filesInScope.isEmpty()) { break; } context.getDependencyCache().clearTraverseRoots(); chunkFiles = filesInScope; total += chunkFiles.size() * translators.length; } didSomething |= (hasUnprocessedTraverseRoots != context.getDependencyCache().hasUnprocessedTraverseRoots()); } round++; } while (!dependentFiles.isEmpty() && context.getMessageCount(CompilerMessageCategory.ERROR) == 0); if (CompilerConfiguration.MAKE_ENABLED) { if (!context.getProgressIndicator().isCanceled()) { // when cancelled pretend nothing was compiled and next compile will compile everything from the scratch final ProgressIndicator indicator = context.getProgressIndicator(); final DependencyCache cache = context.getDependencyCache(); indicator.pushState(); indicator.setText(CompilerBundle.message("progress.updating.caches")); indicator.setText2(""); cache.update(); indicator.setText(CompilerBundle.message("progress.saving.caches")); cache.resetState(); processedModules.addAll(currentChunk.getNodes()); indicator.popState(); } } if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { throw new ExitException(ExitStatus.ERRORS); } } catch (CacheCorruptedException e) { LOG.info(e); context.requestRebuildNextTime(e.getMessage()); } finally { final int errorCount = context.getMessageCount(CompilerMessageCategory.ERROR); if (errorCount != 0) { filesToRecompile.addAll(allDependent); } if (filesToRecompile.size() > 0) { sink.add(null, Collections.<TranslatingCompiler.OutputItem>emptyList(), VfsUtilCore.toVirtualFileArray(filesToRecompile)); } if (errorCount == 0) { // perform update only if there were no errors, so it is guaranteed that the file was processd by all neccesary compilers sink.flushPostponedItems(); } } } } catch (ProcessCanceledException e) { ProgressManager.getInstance().executeNonCancelableSection(new Runnable() { public void run() { try { final Collection<VirtualFile> deps = CacheUtils.findDependentFiles(context, Collections.<VirtualFile>emptySet(), null); if (deps.size() > 0) { TranslatingCompilerFilesMonitor.getInstance().update(context, null, Collections.<TranslatingCompiler.OutputItem>emptyList(), VfsUtilCore.toVirtualFileArray(deps)); } } catch (IOException ignored) { LOG.info(ignored); } catch (CacheCorruptedException ignored) { LOG.info(ignored); } catch (ExitException e1) { LOG.info(e1); } } }); throw e; } finally { dropDependencyCache(context); if (didSomething) { TranslatingCompilerFilesMonitor.getInstance().updateOutputRootsLayout(myProject); } } return didSomething; } private static List<VirtualFile> getFilesInScope(final CompileContextEx context, final Chunk<Module> chunk, final Collection<VirtualFile> files) { final List<VirtualFile> filesInScope = new ArrayList<VirtualFile>(files.size()); ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { for (VirtualFile file : files) { if (context.getCompileScope().belongs(file.getUrl())) { final Module module = context.getModuleByFile(file); if (chunk.getNodes().contains(module)) { filesInScope.add(file); } } } } }); return filesInScope; } private static void recalculateChunkToFilesMap(CompileContextEx context, List<Chunk<Module>> allChunks, VirtualFile[] snapshot, Map<Chunk<Module>, Collection<VirtualFile>> chunkMap) { final Map<Module, List<VirtualFile>> moduleToFilesMap = CompilerUtil.buildModuleToFilesMap(context, snapshot); for (Chunk<Module> moduleChunk : allChunks) { List<VirtualFile> files = Collections.emptyList(); for (Module module : moduleChunk.getNodes()) { final List<VirtualFile> moduleFiles = moduleToFilesMap.get(module); if (moduleFiles != null) { files = ContainerUtil.concat(files, moduleFiles); } } chunkMap.put(moduleChunk, files); } } private interface FileProcessingCompilerAdapterFactory { FileProcessingCompilerAdapter create(CompileContext context, FileProcessingCompiler compiler); } private boolean invokeFileProcessingCompilers(final CompilerManager compilerManager, CompileContextEx context, Class<? extends FileProcessingCompiler> fileProcessingCompilerClass, FileProcessingCompilerAdapterFactory factory, boolean forceCompile, final boolean checkScope, final boolean onlyCheckStatus) throws ExitException { boolean didSomething = false; final FileProcessingCompiler[] compilers = compilerManager.getCompilers(fileProcessingCompilerClass, myCompilerFilter); if (compilers.length > 0) { try { CacheDeferredUpdater cacheUpdater = new CacheDeferredUpdater(); try { for (final FileProcessingCompiler compiler : compilers) { if (context.getProgressIndicator().isCanceled()) { throw new ExitException(ExitStatus.CANCELLED); } CompileContextEx _context = context; if (compiler instanceof IntermediateOutputCompiler) { final IntermediateOutputCompiler _compiler = (IntermediateOutputCompiler)compiler; _context = new CompileContextExProxy(context) { public VirtualFile getModuleOutputDirectory(final Module module) { return getGenerationOutputDir(_compiler, module, false); } public VirtualFile getModuleOutputDirectoryForTests(final Module module) { return getGenerationOutputDir(_compiler, module, true); } }; } final boolean processedSomething = processFiles(factory.create(_context, compiler), forceCompile, checkScope, onlyCheckStatus, cacheUpdater); if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { throw new ExitException(ExitStatus.ERRORS); } didSomething |= processedSomething; } } finally { cacheUpdater.doUpdate(); } } catch (IOException e) { LOG.info(e); context.requestRebuildNextTime(e.getMessage()); throw new ExitException(ExitStatus.ERRORS); } catch (ProcessCanceledException e) { throw e; } catch (ExitException e) { throw e; } catch (Exception e) { context.addMessage(CompilerMessageCategory.ERROR, CompilerBundle.message("compiler.error.exception", e.getMessage()), null, -1, -1); LOG.error(e); } } return didSomething; } private static Map<Module, Set<GeneratingCompiler.GenerationItem>> buildModuleToGenerationItemMap(GeneratingCompiler.GenerationItem[] items) { final Map<Module, Set<GeneratingCompiler.GenerationItem>> map = new HashMap<Module, Set<GeneratingCompiler.GenerationItem>>(); for (GeneratingCompiler.GenerationItem item : items) { Module module = item.getModule(); LOG.assertTrue(module != null); Set<GeneratingCompiler.GenerationItem> itemSet = map.get(module); if (itemSet == null) { itemSet = new HashSet<GeneratingCompiler.GenerationItem>(); map.put(module, itemSet); } itemSet.add(item); } return map; } private void deleteAll(final CompileContextEx context) { CompilerUtil.runInContext(context, CompilerBundle.message("progress.clearing.output"), new ThrowableRunnable<RuntimeException>() { public void run() { final boolean isTestMode = ApplicationManager.getApplication().isUnitTestMode(); final VirtualFile[] allSources = context.getProjectCompileScope().getFiles(null, true); if (myShouldClearOutputDirectory) { CompilerUtil.clearOutputDirectories(myAllOutputDirectories); } else { // refresh is still required try { for (final Compiler compiler : CompilerManager.getInstance(myProject).getCompilers(Compiler.class)) { try { if (compiler instanceof GeneratingCompiler) { final StateCache<ValidityState> cache = getGeneratingCompilerCache((GeneratingCompiler)compiler); final Iterator<String> urlIterator = cache.getUrlsIterator(); while (urlIterator.hasNext()) { context.getProgressIndicator().checkCanceled(); deleteFile(new File(VirtualFileManager.extractPath(urlIterator.next()))); } } else if (compiler instanceof TranslatingCompiler) { final ArrayList<Trinity<File, String, Boolean>> toDelete = new ArrayList<Trinity<File, String, Boolean>>(); ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { TranslatingCompilerFilesMonitor.getInstance().collectFiles( context, (TranslatingCompiler)compiler, Arrays.<VirtualFile>asList(allSources).iterator(), true /*pass true to make sure that every source in scope file is processed*/, false /*important! should pass false to enable collection of files to delete*/, new ArrayList<VirtualFile>(), toDelete ); } }); for (Trinity<File, String, Boolean> trinity : toDelete) { context.getProgressIndicator().checkCanceled(); final File file = trinity.getFirst(); deleteFile(file); if (isTestMode) { CompilerManagerImpl.addDeletedPath(file.getPath()); } } } } catch (IOException e) { LOG.info(e); } } pruneEmptyDirectories(context.getProgressIndicator(), myAllOutputDirectories); // to avoid too much files deleted events } finally { CompilerUtil.refreshIODirectories(myAllOutputDirectories); } } dropScopesCaches(); clearCompilerSystemDirectory(context); } }); } private void dropScopesCaches() { // hack to be sure the classpath will include the output directories ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { ((ProjectRootManagerEx)ProjectRootManager.getInstance(myProject)).clearScopesCachesForModules(); } }); } private static void pruneEmptyDirectories(ProgressIndicator progress, final Set<File> directories) { for (File directory : directories) { doPrune(progress, directory, directories); } } private static boolean doPrune(ProgressIndicator progress, final File directory, final Set<File> outPutDirectories) { progress.checkCanceled(); final File[] files = directory.listFiles(); boolean isEmpty = true; if (files != null) { for (File file : files) { if (!outPutDirectories.contains(file)) { if (doPrune(progress, file, outPutDirectories)) { deleteFile(file); } else { isEmpty = false; } } else { isEmpty = false; } } } else { isEmpty = false; } return isEmpty; } private Set<File> getAllOutputDirectories(CompileContext context) { final Set<File> outputDirs = new OrderedSet<File>(); final Module[] modules = ModuleManager.getInstance(myProject).getModules(); for (final String path : CompilerPathsEx.getOutputPaths(modules)) { outputDirs.add(new File(path)); } for (Pair<IntermediateOutputCompiler, Module> pair : myGenerationCompilerModuleToOutputDirMap.keySet()) { outputDirs.add(new File(CompilerPaths.getGenerationOutputPath(pair.getFirst(), pair.getSecond(), false))); outputDirs.add(new File(CompilerPaths.getGenerationOutputPath(pair.getFirst(), pair.getSecond(), true))); } final CompilerConfiguration config = CompilerConfiguration.getInstance(myProject); if (context.isAnnotationProcessorsEnabled()) { for (Module module : modules) { if (config.getAnnotationProcessingConfiguration(module).isEnabled()) { final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); if (path != null) { outputDirs.add(new File(path)); } } } } for (Artifact artifact : ArtifactManager.getInstance(myProject).getArtifacts()) { final String path = ((ArtifactImpl)artifact).getOutputDirectoryPathToCleanOnRebuild(); if (path != null) { outputDirs.add(new File(FileUtil.toSystemDependentName(path))); } } return outputDirs; } private void clearCompilerSystemDirectory(final CompileContextEx context) { CompilerCacheManager.getInstance(myProject).clearCaches(context); FileUtil.delete(CompilerPathsEx.getZipStoreDirectory(myProject)); dropDependencyCache(context); for (Pair<IntermediateOutputCompiler, Module> pair : myGenerationCompilerModuleToOutputDirMap.keySet()) { final File[] outputs = { new File(CompilerPaths.getGenerationOutputPath(pair.getFirst(), pair.getSecond(), false)), new File(CompilerPaths.getGenerationOutputPath(pair.getFirst(), pair.getSecond(), true)) }; for (File output : outputs) { final File[] files = output.listFiles(); if (files != null) { for (final File file : files) { final boolean deleteOk = deleteFile(file); if (!deleteOk) { context.addMessage(CompilerMessageCategory.ERROR, CompilerBundle.message("compiler.error.failed.to.delete", file.getPath()), null, -1, -1); } } } } } } /** * @param file a file to delete * @return true if and only if the file existed and was successfully deleted * Note: the behaviour is different from FileUtil.delete() which returns true if the file absent on the disk */ private static boolean deleteFile(final File file) { File[] files = file.listFiles(); if (files != null) { for (File file1 : files) { deleteFile(file1); } } for (int i = 0; i < 10; i++){ if (file.delete()) { return true; } if (!file.exists()) { return false; } try { Thread.sleep(50); } catch (InterruptedException ignored) { } } return false; } private VirtualFile getGenerationOutputDir(final IntermediateOutputCompiler compiler, final Module module, final boolean forTestSources) { final Pair<VirtualFile, VirtualFile> outputs = myGenerationCompilerModuleToOutputDirMap.get(new Pair<IntermediateOutputCompiler, Module>(compiler, module)); return forTestSources? outputs.getSecond() : outputs.getFirst(); } private boolean generateOutput(final CompileContextEx context, final GeneratingCompiler compiler, final boolean forceGenerate, final boolean onlyCheckStatus) throws ExitException { final GeneratingCompiler.GenerationItem[] allItems = compiler.getGenerationItems(context); final List<GeneratingCompiler.GenerationItem> toGenerate = new ArrayList<GeneratingCompiler.GenerationItem>(); final List<File> filesToRefresh = new ArrayList<File>(); final List<File> generatedFiles = new ArrayList<File>(); final List<Module> affectedModules = new ArrayList<Module>(); try { final StateCache<ValidityState> cache = getGeneratingCompilerCache(compiler); final Set<String> pathsToRemove = new HashSet<String>(cache.getUrls()); final Map<GeneratingCompiler.GenerationItem, String> itemToOutputPathMap = new HashMap<GeneratingCompiler.GenerationItem, String>(); final IOException[] ex = {null}; ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { for (final GeneratingCompiler.GenerationItem item : allItems) { final Module itemModule = item.getModule(); final String outputDirPath = CompilerPaths.getGenerationOutputPath(compiler, itemModule, item.isTestSource()); final String outputPath = outputDirPath + "/" + item.getPath(); itemToOutputPathMap.put(item, outputPath); try { final ValidityState savedState = cache.getState(outputPath); if (forceGenerate || savedState == null || !savedState.equalsTo(item.getValidityState())) { final String outputPathUrl = VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, outputPath); if (context.getCompileScope().belongs(outputPathUrl)) { toGenerate.add(item); } else { pathsToRemove.remove(outputPath); } } else { pathsToRemove.remove(outputPath); } } catch (IOException e) { ex[0] = e; } } } }); if (ex[0] != null) { throw ex[0]; } if (onlyCheckStatus) { if (toGenerate.isEmpty() && pathsToRemove.isEmpty()) { return false; } if (LOG.isDebugEnabled()) { if (!toGenerate.isEmpty()) { LOG.debug("Found items to generate, compiler " + compiler.getDescription()); } if (!pathsToRemove.isEmpty()) { LOG.debug("Found paths to remove, compiler " + compiler.getDescription()); } } throw new ExitException(ExitStatus.CANCELLED); } if (!pathsToRemove.isEmpty()) { CompilerUtil.runInContext(context, CompilerBundle.message("progress.synchronizing.output.directory"), new ThrowableRunnable<IOException>(){ public void run() throws IOException { for (final String path : pathsToRemove) { final File file = new File(path); final boolean deleted = deleteFile(file); if (deleted) { cache.remove(path); filesToRefresh.add(file); } } } }); } final Map<Module, Set<GeneratingCompiler.GenerationItem>> moduleToItemMap = buildModuleToGenerationItemMap(toGenerate.toArray(new GeneratingCompiler.GenerationItem[toGenerate.size()])); List<Module> modules = new ArrayList<Module>(moduleToItemMap.size()); for (final Module module : moduleToItemMap.keySet()) { modules.add(module); } ModuleCompilerUtil.sortModules(myProject, modules); for (final Module module : modules) { CompilerUtil.runInContext(context, "Generating output from "+compiler.getDescription(),new ThrowableRunnable<IOException>(){ public void run() throws IOException { final Set<GeneratingCompiler.GenerationItem> items = moduleToItemMap.get(module); if (items != null && !items.isEmpty()) { final GeneratingCompiler.GenerationItem[][] productionAndTestItems = splitGenerationItems(items); for (GeneratingCompiler.GenerationItem[] _items : productionAndTestItems) { if (_items.length == 0) continue; final VirtualFile outputDir = getGenerationOutputDir(compiler, module, _items[0].isTestSource()); final GeneratingCompiler.GenerationItem[] successfullyGenerated = compiler.generate(context, _items, outputDir); CompilerUtil.runInContext(context, CompilerBundle.message("progress.updating.caches"), new ThrowableRunnable<IOException>() { public void run() throws IOException { if (successfullyGenerated.length > 0) { affectedModules.add(module); } for (final GeneratingCompiler.GenerationItem item : successfullyGenerated) { final String fullOutputPath = itemToOutputPathMap.get(item); cache.update(fullOutputPath, item.getValidityState()); final File file = new File(fullOutputPath); filesToRefresh.add(file); generatedFiles.add(file); context.getProgressIndicator().setText2(file.getPath()); } } }); } } } }); } } catch (IOException e) { LOG.info(e); context.requestRebuildNextTime(e.getMessage()); throw new ExitException(ExitStatus.ERRORS); } finally { CompilerUtil.refreshIOFiles(filesToRefresh); if (!generatedFiles.isEmpty()) { DumbService.getInstance(myProject).waitForSmartMode(); List<VirtualFile> vFiles = ApplicationManager.getApplication().runReadAction(new Computable<List<VirtualFile>>() { public List<VirtualFile> compute() { final ArrayList<VirtualFile> vFiles = new ArrayList<VirtualFile>(generatedFiles.size()); for (File generatedFile : generatedFiles) { final VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(generatedFile); if (vFile != null) { vFiles.add(vFile); } } return vFiles; } }); if (forceGenerate) { context.addScope(new FileSetCompileScope(vFiles, affectedModules.toArray(new Module[affectedModules.size()]))); } context.markGenerated(vFiles); } } return !toGenerate.isEmpty() || !filesToRefresh.isEmpty(); } private static GeneratingCompiler.GenerationItem[][] splitGenerationItems(final Set<GeneratingCompiler.GenerationItem> items) { final List<GeneratingCompiler.GenerationItem> production = new ArrayList<GeneratingCompiler.GenerationItem>(); final List<GeneratingCompiler.GenerationItem> tests = new ArrayList<GeneratingCompiler.GenerationItem>(); for (GeneratingCompiler.GenerationItem item : items) { if (item.isTestSource()) { tests.add(item); } else { production.add(item); } } return new GeneratingCompiler.GenerationItem[][]{ production.toArray(new GeneratingCompiler.GenerationItem[production.size()]), tests.toArray(new GeneratingCompiler.GenerationItem[tests.size()]) }; } private boolean compileSources(final CompileContextEx context, final Chunk<Module> moduleChunk, final TranslatingCompiler compiler, final Collection<VirtualFile> srcSnapshot, final boolean forceCompile, final boolean isRebuild, final boolean onlyCheckStatus, TranslatingCompiler.OutputSink sink) throws ExitException { final Set<VirtualFile> toCompile = new HashSet<VirtualFile>(); final List<Trinity<File, String, Boolean>> toDelete = new ArrayList<Trinity<File, String, Boolean>>(); context.getProgressIndicator().pushState(); final boolean[] wereFilesDeleted = {false}; try { ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { TranslatingCompilerFilesMonitor.getInstance().collectFiles( context, compiler, srcSnapshot.iterator(), forceCompile, isRebuild, toCompile, toDelete ); } }); if (onlyCheckStatus) { if (toDelete.isEmpty() && toCompile.isEmpty()) { return false; } if (LOG.isDebugEnabled() || ourDebugMode) { if (!toDelete.isEmpty()) { final StringBuilder message = new StringBuilder(); message.append("Found items to delete, compiler ").append(compiler.getDescription()); for (Trinity<File, String, Boolean> trinity : toDelete) { message.append("\n").append(trinity.getFirst()); } LOG.debug(message.toString()); if (ourDebugMode) { System.out.println(message); } } if (!toCompile.isEmpty()) { final String message = "Found items to compile, compiler " + compiler.getDescription(); LOG.debug(message); if (ourDebugMode) { System.out.println(message); } } } throw new ExitException(ExitStatus.CANCELLED); } if (!toDelete.isEmpty()) { try { wereFilesDeleted[0] = syncOutputDir(context, toDelete); } catch (CacheCorruptedException e) { LOG.info(e); context.requestRebuildNextTime(e.getMessage()); } } if ((wereFilesDeleted[0] || !toCompile.isEmpty()) && context.getMessageCount(CompilerMessageCategory.ERROR) == 0) { compiler.compile(context, moduleChunk, VfsUtilCore.toVirtualFileArray(toCompile), sink); } } finally { context.getProgressIndicator().popState(); } return !toCompile.isEmpty() || wereFilesDeleted[0]; } private static boolean syncOutputDir(final CompileContextEx context, final Collection<Trinity<File, String, Boolean>> toDelete) throws CacheCorruptedException { final DependencyCache dependencyCache = context.getDependencyCache(); final boolean isTestMode = ApplicationManager.getApplication().isUnitTestMode(); final List<File> filesToRefresh = new ArrayList<File>(); final boolean[] wereFilesDeleted = {false}; CompilerUtil.runInContext(context, CompilerBundle.message("progress.synchronizing.output.directory"), new ThrowableRunnable<CacheCorruptedException>(){ public void run() throws CacheCorruptedException { final long start = System.currentTimeMillis(); try { for (final Trinity<File, String, Boolean> trinity : toDelete) { final File outputPath = trinity.getFirst(); context.getProgressIndicator().checkCanceled(); context.getProgressIndicator().setText2(outputPath.getPath()); filesToRefresh.add(outputPath); if (isTestMode) { LOG.assertTrue(outputPath.exists()); } if (!deleteFile(outputPath)) { if (isTestMode) { if (outputPath.exists()) { LOG.error("Was not able to delete output file: " + outputPath.getPath()); } else { CompilerManagerImpl.addDeletedPath(outputPath.getPath()); } } continue; } wereFilesDeleted[0] = true; // update zip here //final String outputDir = myOutputFinder.lookupOutputPath(outputPath); //if (outputDir != null) { // try { // context.updateZippedOuput(outputDir, FileUtil.toSystemIndependentName(outputPath.getPath()).substring(outputDir.length() + 1)); // } // catch (IOException e) { // LOG.info(e); // } //} final String className = trinity.getSecond(); if (className != null) { final int id = dependencyCache.getSymbolTable().getId(className); dependencyCache.addTraverseRoot(id); final boolean sourcePresent = trinity.getThird().booleanValue(); if (!sourcePresent) { dependencyCache.markSourceRemoved(id); } } if (isTestMode) { CompilerManagerImpl.addDeletedPath(outputPath.getPath()); } } } finally { CompilerUtil.logDuration("Sync output directory", System.currentTimeMillis() - start); CompilerUtil.refreshIOFiles(filesToRefresh); } } }); return wereFilesDeleted[0]; } // [mike] performance optimization - this method is accessed > 15,000 times in Aurora private String getModuleOutputPath(final Module module, boolean inTestSourceContent) { final Map<Module, String> map = inTestSourceContent ? myModuleTestOutputPaths : myModuleOutputPaths; String path = map.get(module); if (path == null) { path = CompilerPaths.getModuleOutputPath(module, inTestSourceContent); map.put(module, path); } return path; } private boolean processFiles(final FileProcessingCompilerAdapter adapter, final boolean forceCompile, final boolean checkScope, final boolean onlyCheckStatus, final CacheDeferredUpdater cacheUpdater) throws ExitException, IOException { final CompileContextEx context = (CompileContextEx)adapter.getCompileContext(); final FileProcessingCompilerStateCache cache = getFileProcessingCompilerCache(adapter.getCompiler()); final FileProcessingCompiler.ProcessingItem[] items = adapter.getProcessingItems(); if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { return false; } if (LOG.isDebugEnabled() && items.length > 0) { LOG.debug("Start processing files by " + adapter.getCompiler().getDescription()); } final CompileScope scope = context.getCompileScope(); final List<FileProcessingCompiler.ProcessingItem> toProcess = new ArrayList<FileProcessingCompiler.ProcessingItem>(); final Set<String> allUrls = new HashSet<String>(); final IOException[] ex = {null}; DumbService.getInstance(myProject).waitForSmartMode(); ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { try { for (FileProcessingCompiler.ProcessingItem item : items) { final VirtualFile file = item.getFile(); final String url = file.getUrl(); allUrls.add(url); if (!forceCompile && cache.getTimestamp(url) == file.getTimeStamp()) { final ValidityState state = cache.getExtState(url); final ValidityState itemState = item.getValidityState(); if (state != null ? state.equalsTo(itemState) : itemState == null) { continue; } } if (LOG.isDebugEnabled()) { LOG.debug("Adding item to process: " + url + "; saved ts= " + cache.getTimestamp(url) + "; VFS ts=" + file.getTimeStamp()); } toProcess.add(item); } } catch (IOException e) { ex[0] = e; } } }); if (ex[0] != null) { throw ex[0]; } final Collection<String> urls = cache.getUrls(); final List<String> urlsToRemove = new ArrayList<String>(); if (!urls.isEmpty()) { CompilerUtil.runInContext(context, CompilerBundle.message("progress.processing.outdated.files"), new ThrowableRunnable<IOException>(){ public void run() throws IOException { ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { for (final String url : urls) { if (!allUrls.contains(url)) { if (!checkScope || scope.belongs(url)) { urlsToRemove.add(url); } } } } }); if (!onlyCheckStatus && !urlsToRemove.isEmpty()) { for (final String url : urlsToRemove) { adapter.processOutdatedItem(context, url, cache.getExtState(url)); cache.remove(url); } } } }); } if (onlyCheckStatus) { if (urlsToRemove.isEmpty() && toProcess.isEmpty()) { return false; } if (LOG.isDebugEnabled()) { if (!urlsToRemove.isEmpty()) { LOG.debug("Found urls to remove, compiler " + adapter.getCompiler().getDescription()); for (String url : urlsToRemove) { LOG.debug("\t" + url); } } if (!toProcess.isEmpty()) { LOG.debug("Found items to compile, compiler " + adapter.getCompiler().getDescription()); for (FileProcessingCompiler.ProcessingItem item : toProcess) { LOG.debug("\t" + item.getFile().getPresentableUrl()); } } } throw new ExitException(ExitStatus.CANCELLED); } if (toProcess.isEmpty()) { return false; } final FileProcessingCompiler.ProcessingItem[] processed = adapter.process(toProcess.toArray(new FileProcessingCompiler.ProcessingItem[toProcess.size()])); if (processed.length == 0) { return true; } CompilerUtil.runInContext(context, CompilerBundle.message("progress.updating.caches"), new ThrowableRunnable<IOException>() { public void run() { final List<VirtualFile> vFiles = new ArrayList<VirtualFile>(processed.length); for (FileProcessingCompiler.ProcessingItem aProcessed : processed) { final VirtualFile file = aProcessed.getFile(); vFiles.add(file); if (LOG.isDebugEnabled()) { LOG.debug("\tFile processed " + file.getPresentableUrl() + "; ts=" + file.getTimeStamp()); } //final String path = file.getPath(); //final String outputDir = myOutputFinder.lookupOutputPath(path); //if (outputDir != null) { // context.updateZippedOuput(outputDir, path.substring(outputDir.length() + 1)); //} } LocalFileSystem.getInstance().refreshFiles(vFiles); if (LOG.isDebugEnabled()) { LOG.debug("Files after VFS refresh:"); for (VirtualFile file : vFiles) { LOG.debug("\t" + file.getPresentableUrl() + "; ts=" + file.getTimeStamp()); } } for (FileProcessingCompiler.ProcessingItem item : processed) { cacheUpdater.addFileForUpdate(item, cache); } } }); return true; } private FileProcessingCompilerStateCache getFileProcessingCompilerCache(FileProcessingCompiler compiler) throws IOException { return CompilerCacheManager.getInstance(myProject).getFileProcessingCompilerCache(compiler); } private StateCache<ValidityState> getGeneratingCompilerCache(final GeneratingCompiler compiler) throws IOException { return CompilerCacheManager.getInstance(myProject).getGeneratingCompilerCache(compiler); } public void executeCompileTask(final CompileTask task, final CompileScope scope, final String contentName, final Runnable onTaskFinished) { final CompilerTask progressManagerTask = new CompilerTask(myProject, contentName, false, false, true, isCompilationStartedAutomatically(scope)); final CompileContextImpl compileContext = new CompileContextImpl(myProject, progressManagerTask, scope, null, false, false); FileDocumentManager.getInstance().saveAllDocuments(); progressManagerTask.start(new Runnable() { public void run() { try { task.execute(compileContext); } catch (ProcessCanceledException ex) { // suppressed } finally { if (onTaskFinished != null) { onTaskFinished.run(); } } } }, null); } private boolean executeCompileTasks(final CompileContext context, final boolean beforeTasks) { final CompilerManager manager = CompilerManager.getInstance(myProject); final ProgressIndicator progressIndicator = context.getProgressIndicator(); progressIndicator.pushState(); try { CompileTask[] tasks = beforeTasks ? manager.getBeforeTasks() : manager.getAfterTasks(); if (tasks.length > 0) { progressIndicator.setText(beforeTasks ? CompilerBundle.message("progress.executing.precompile.tasks") : CompilerBundle.message("progress.executing.postcompile.tasks")); for (CompileTask task : tasks) { if (!task.execute(context)) { return false; } } } } finally { progressIndicator.popState(); WindowManager.getInstance().getStatusBar(myProject).setInfo(""); if (progressIndicator instanceof CompilerTask) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { ((CompilerTask)progressIndicator).showCompilerContent(); } }); } } return true; } private boolean validateCompilerConfiguration(final CompileScope scope, boolean checkOutputAndSourceIntersection) { try { final Module[] scopeModules = scope.getAffectedModules()/*ModuleManager.getInstance(myProject).getModules()*/; final List<String> modulesWithoutOutputPathSpecified = new ArrayList<String>(); boolean isProjectCompilePathSpecified = true; final List<String> modulesWithoutJdkAssigned = new ArrayList<String>(); final Set<File> nonExistingOutputPaths = new HashSet<File>(); final CompilerConfiguration config = CompilerConfiguration.getInstance(myProject); final CompilerManager compilerManager = CompilerManager.getInstance(myProject); final boolean useOutOfProcessBuild = useOutOfProcessBuild(); for (final Module module : scopeModules) { if (!compilerManager.isValidationEnabled(module)) { continue; } final boolean hasSources = hasSources(module, false); final boolean hasTestSources = hasSources(module, true); if (!hasSources && !hasTestSources) { // If module contains no sources, shouldn't have to select JDK or output directory (SCR #19333) // todo still there may be problems with this approach if some generated files are attributed by this module continue; } final Sdk jdk = ModuleRootManager.getInstance(module).getSdk(); if (jdk == null) { modulesWithoutJdkAssigned.add(module.getName()); } final String outputPath = getModuleOutputPath(module, false); final String testsOutputPath = getModuleOutputPath(module, true); if (outputPath == null && testsOutputPath == null) { modulesWithoutOutputPathSpecified.add(module.getName()); } else { if (outputPath != null) { if (!useOutOfProcessBuild) { final File file = new File(outputPath.replace('/', File.separatorChar)); if (!file.exists()) { nonExistingOutputPaths.add(file); } } } else { if (hasSources) { modulesWithoutOutputPathSpecified.add(module.getName()); } } if (testsOutputPath != null) { if (!useOutOfProcessBuild) { final File f = new File(testsOutputPath.replace('/', File.separatorChar)); if (!f.exists()) { nonExistingOutputPaths.add(f); } } } else { if (hasTestSources) { modulesWithoutOutputPathSpecified.add(module.getName()); } } if (!useOutOfProcessBuild) { if (config.getAnnotationProcessingConfiguration(module).isEnabled()) { final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); if (path == null) { final CompilerProjectExtension extension = CompilerProjectExtension.getInstance(module.getProject()); if (extension == null || extension.getCompilerOutputUrl() == null) { isProjectCompilePathSpecified = false; } else { modulesWithoutOutputPathSpecified.add(module.getName()); } } else { final File file = new File(path); if (!file.exists()) { nonExistingOutputPaths.add(file); } } } } } } if (!modulesWithoutJdkAssigned.isEmpty()) { showNotSpecifiedError("error.jdk.not.specified", modulesWithoutJdkAssigned, ProjectBundle.message("modules.classpath.title")); return false; } if (!isProjectCompilePathSpecified) { final String message = CompilerBundle.message("error.project.output.not.specified"); if (ApplicationManager.getApplication().isUnitTestMode()) { LOG.error(message); } Messages.showMessageDialog(myProject, message, CommonBundle.getErrorTitle(), Messages.getErrorIcon()); ProjectSettingsService.getInstance(myProject).openProjectSettings(); return false; } if (!modulesWithoutOutputPathSpecified.isEmpty()) { showNotSpecifiedError("error.output.not.specified", modulesWithoutOutputPathSpecified, CommonContentEntriesEditor.NAME); return false; } if (!nonExistingOutputPaths.isEmpty()) { for (File file : nonExistingOutputPaths) { final boolean succeeded = file.mkdirs(); if (!succeeded) { if (file.exists()) { // for overlapping paths, this one might have been created as an intermediate path on a previous iteration continue; } Messages.showMessageDialog(myProject, CompilerBundle.message("error.failed.to.create.directory", file.getPath()), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); return false; } } final Boolean refreshSuccess = new WriteAction<Boolean>() { @Override protected void run(Result<Boolean> result) throws Throwable { LocalFileSystem.getInstance().refreshIoFiles(nonExistingOutputPaths); Boolean res = Boolean.TRUE; for (File file : nonExistingOutputPaths) { if (LocalFileSystem.getInstance().findFileByIoFile(file) == null) { res = Boolean.FALSE; break; } } result.setResult(res); } }.execute().getResultObject(); if (!refreshSuccess.booleanValue()) { return false; } dropScopesCaches(); } if (checkOutputAndSourceIntersection && myShouldClearOutputDirectory) { if (!validateOutputAndSourcePathsIntersection()) { return false; } // myShouldClearOutputDirectory may change in validateOutputAndSourcePathsIntersection() CompilerPathsEx.CLEAR_ALL_OUTPUTS_KEY.set(scope, myShouldClearOutputDirectory); } else { CompilerPathsEx.CLEAR_ALL_OUTPUTS_KEY.set(scope, false); } final List<Chunk<Module>> chunks = ModuleCompilerUtil.getSortedModuleChunks(myProject, Arrays.asList(scopeModules)); for (final Chunk<Module> chunk : chunks) { final Set<Module> chunkModules = chunk.getNodes(); if (chunkModules.size() <= 1) { continue; // no need to check one-module chunks } for (Module chunkModule : chunkModules) { if (config.getAnnotationProcessingConfiguration(chunkModule).isEnabled()) { showCyclesNotSupportedForAnnotationProcessors(chunkModules.toArray(new Module[chunkModules.size()])); return false; } } Sdk jdk = null; LanguageLevel languageLevel = null; for (final Module module : chunkModules) { final Sdk moduleJdk = ModuleRootManager.getInstance(module).getSdk(); if (jdk == null) { jdk = moduleJdk; } else { if (!jdk.equals(moduleJdk)) { showCyclicModulesHaveDifferentJdksError(chunkModules.toArray(new Module[chunkModules.size()])); return false; } } LanguageLevel moduleLanguageLevel = LanguageLevelUtil.getEffectiveLanguageLevel(module); if (languageLevel == null) { languageLevel = moduleLanguageLevel; } else { if (!languageLevel.equals(moduleLanguageLevel)) { showCyclicModulesHaveDifferentLanguageLevel(chunkModules.toArray(new Module[chunkModules.size()])); return false; } } } } if (!useOutOfProcessBuild) { final Compiler[] allCompilers = compilerManager.getCompilers(Compiler.class); for (Compiler compiler : allCompilers) { if (!compiler.validateConfiguration(scope)) { return false; } } } return true; } catch (Throwable e) { LOG.info(e); return false; } } private boolean useOutOfProcessBuild() { return CompilerWorkspaceConfiguration.getInstance(myProject).useOutOfProcessBuild(); } private void showCyclicModulesHaveDifferentLanguageLevel(Module[] modulesInChunk) { LOG.assertTrue(modulesInChunk.length > 0); String moduleNameToSelect = modulesInChunk[0].getName(); final String moduleNames = getModulesString(modulesInChunk); Messages.showMessageDialog(myProject, CompilerBundle.message("error.chunk.modules.must.have.same.language.level", moduleNames), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); showConfigurationDialog(moduleNameToSelect, null); } private void showCyclicModulesHaveDifferentJdksError(Module[] modulesInChunk) { LOG.assertTrue(modulesInChunk.length > 0); String moduleNameToSelect = modulesInChunk[0].getName(); final String moduleNames = getModulesString(modulesInChunk); Messages.showMessageDialog(myProject, CompilerBundle.message("error.chunk.modules.must.have.same.jdk", moduleNames), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); showConfigurationDialog(moduleNameToSelect, null); } private void showCyclesNotSupportedForAnnotationProcessors(Module[] modulesInChunk) { LOG.assertTrue(modulesInChunk.length > 0); String moduleNameToSelect = modulesInChunk[0].getName(); final String moduleNames = getModulesString(modulesInChunk); Messages.showMessageDialog(myProject, CompilerBundle.message("error.annotation.processing.not.supported.for.module.cycles", moduleNames), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); showConfigurationDialog(moduleNameToSelect, null); } private static String getModulesString(Module[] modulesInChunk) { final StringBuilder moduleNames = StringBuilderSpinAllocator.alloc(); try { for (Module module : modulesInChunk) { if (moduleNames.length() > 0) { moduleNames.append("\n"); } moduleNames.append("\"").append(module.getName()).append("\""); } return moduleNames.toString(); } finally { StringBuilderSpinAllocator.dispose(moduleNames); } } private static boolean hasSources(Module module, boolean checkTestSources) { final ContentEntry[] contentEntries = ModuleRootManager.getInstance(module).getContentEntries(); for (final ContentEntry contentEntry : contentEntries) { final SourceFolder[] sourceFolders = contentEntry.getSourceFolders(); for (final SourceFolder sourceFolder : sourceFolders) { if (sourceFolder.getFile() == null) { continue; // skip invalid source folders } if (checkTestSources) { if (sourceFolder.isTestSource()) { return true; } } else { if (!sourceFolder.isTestSource()) { return true; } } } } return false; } private void showNotSpecifiedError(@NonNls final String resourceId, List<String> modules, String editorNameToSelect) { String nameToSelect = null; final StringBuilder names = StringBuilderSpinAllocator.alloc(); final String message; try { final int maxModulesToShow = 10; for (String name : modules.size() > maxModulesToShow ? modules.subList(0, maxModulesToShow) : modules) { if (nameToSelect == null) { nameToSelect = name; } if (names.length() > 0) { names.append(",\n"); } names.append("\""); names.append(name); names.append("\""); } if (modules.size() > maxModulesToShow) { names.append(",\n..."); } message = CompilerBundle.message(resourceId, modules.size(), names.toString()); } finally { StringBuilderSpinAllocator.dispose(names); } if (ApplicationManager.getApplication().isUnitTestMode()) { LOG.error(message); } Messages.showMessageDialog(myProject, message, CommonBundle.getErrorTitle(), Messages.getErrorIcon()); showConfigurationDialog(nameToSelect, editorNameToSelect); } private boolean validateOutputAndSourcePathsIntersection() { final Module[] allModules = ModuleManager.getInstance(myProject).getModules(); List<VirtualFile> allOutputs = new ArrayList<VirtualFile>(); ContainerUtil.addAll(allOutputs, CompilerPathsEx.getOutputDirectories(allModules)); for (Artifact artifact : ArtifactManager.getInstance(myProject).getArtifacts()) { ContainerUtil.addIfNotNull(artifact.getOutputFile(), allOutputs); } final Set<VirtualFile> affectedOutputPaths = new HashSet<VirtualFile>(); CompilerUtil.computeIntersectingPaths(myProject, allOutputs, affectedOutputPaths); affectedOutputPaths.addAll(ArtifactCompilerUtil.getArtifactOutputsContainingSourceFiles(myProject)); if (!affectedOutputPaths.isEmpty()) { if (CompilerUtil.askUserToContinueWithNoClearing(myProject, affectedOutputPaths)) { myShouldClearOutputDirectory = false; return true; } else { return false; } } return true; } private void showConfigurationDialog(String moduleNameToSelect, String tabNameToSelect) { ProjectSettingsService.getInstance(myProject).showModuleConfigurationDialog(moduleNameToSelect, tabNameToSelect); } private static VirtualFile lookupVFile(final LocalFileSystem lfs, final String path) { final File file = new File(path); VirtualFile vFile = lfs.findFileByIoFile(file); if (vFile != null) { return vFile; } final boolean justCreated = file.mkdirs(); vFile = lfs.refreshAndFindFileByIoFile(file); if (vFile == null) { assert false: "Virtual file not found for " + file.getPath() + "; mkdirs() exit code is " + justCreated + "; file exists()? " + file.exists(); } return vFile; } private static class CacheDeferredUpdater { private final Map<VirtualFile, List<Pair<FileProcessingCompilerStateCache, FileProcessingCompiler.ProcessingItem>>> myData = new java.util.HashMap<VirtualFile, List<Pair<FileProcessingCompilerStateCache, FileProcessingCompiler.ProcessingItem>>>(); public void addFileForUpdate(final FileProcessingCompiler.ProcessingItem item, FileProcessingCompilerStateCache cache) { final VirtualFile file = item.getFile(); List<Pair<FileProcessingCompilerStateCache, FileProcessingCompiler.ProcessingItem>> list = myData.get(file); if (list == null) { list = new ArrayList<Pair<FileProcessingCompilerStateCache, FileProcessingCompiler.ProcessingItem>>(); myData.put(file, list); } list.add(new Pair<FileProcessingCompilerStateCache, FileProcessingCompiler.ProcessingItem>(cache, item)); } public void doUpdate() throws IOException{ final IOException[] ex = {null}; ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { try { for (Map.Entry<VirtualFile, List<Pair<FileProcessingCompilerStateCache, FileProcessingCompiler.ProcessingItem>>> entry : myData.entrySet()) { for (Pair<FileProcessingCompilerStateCache, FileProcessingCompiler.ProcessingItem> pair : entry.getValue()) { final FileProcessingCompiler.ProcessingItem item = pair.getSecond(); pair.getFirst().update(entry.getKey(), item.getValidityState()); } } } catch (IOException e) { ex[0] = e; } } }); if (ex[0] != null) { throw ex[0]; } } } private static class TranslatorsOutputSink implements TranslatingCompiler.OutputSink { final Map<String, Collection<TranslatingCompiler.OutputItem>> myPostponedItems = new HashMap<String, Collection<TranslatingCompiler.OutputItem>>(); private final CompileContextEx myContext; private final TranslatingCompiler[] myCompilers; private int myCurrentCompilerIdx; private final Set<VirtualFile> myCompiledSources = new HashSet<VirtualFile>(); //private LinkedBlockingQueue<Future> myFutures = new LinkedBlockingQueue<Future>(); private TranslatorsOutputSink(CompileContextEx context, TranslatingCompiler[] compilers) { myContext = context; myCompilers = compilers; } public void setCurrentCompilerIndex(int index) { myCurrentCompilerIdx = index; } public Set<VirtualFile> getCompiledSources() { return Collections.unmodifiableSet(myCompiledSources); } public void add(final String outputRoot, final Collection<TranslatingCompiler.OutputItem> items, final VirtualFile[] filesToRecompile) { for (TranslatingCompiler.OutputItem item : items) { final VirtualFile file = item.getSourceFile(); if (file != null) { myCompiledSources.add(file); } } final TranslatingCompiler compiler = myCompilers[myCurrentCompilerIdx]; if (compiler instanceof IntermediateOutputCompiler) { final LocalFileSystem lfs = LocalFileSystem.getInstance(); final List<VirtualFile> outputs = new ArrayList<VirtualFile>(); for (TranslatingCompiler.OutputItem item : items) { final VirtualFile vFile = lfs.findFileByPath(item.getOutputPath()); if (vFile != null) { outputs.add(vFile); } } myContext.markGenerated(outputs); } final int nextCompilerIdx = myCurrentCompilerIdx + 1; try { if (nextCompilerIdx < myCompilers.length ) { final Map<String, Collection<TranslatingCompiler.OutputItem>> updateNow = new java.util.HashMap<String, Collection<TranslatingCompiler.OutputItem>>(); // process postponed for (Map.Entry<String, Collection<TranslatingCompiler.OutputItem>> entry : myPostponedItems.entrySet()) { final String outputDir = entry.getKey(); final Collection<TranslatingCompiler.OutputItem> postponed = entry.getValue(); for (Iterator<TranslatingCompiler.OutputItem> it = postponed.iterator(); it.hasNext();) { TranslatingCompiler.OutputItem item = it.next(); boolean shouldPostpone = false; for (int idx = nextCompilerIdx; idx < myCompilers.length; idx++) { shouldPostpone = myCompilers[idx].isCompilableFile(item.getSourceFile(), myContext); if (shouldPostpone) { break; } } if (!shouldPostpone) { // the file is not compilable by the rest of compilers, so it is safe to update it now it.remove(); addItemToMap(updateNow, outputDir, item); } } } // process items from current compilation for (TranslatingCompiler.OutputItem item : items) { boolean shouldPostpone = false; for (int idx = nextCompilerIdx; idx < myCompilers.length; idx++) { shouldPostpone = myCompilers[idx].isCompilableFile(item.getSourceFile(), myContext); if (shouldPostpone) { break; } } if (shouldPostpone) { // the file is compilable by the next compiler in row, update should be postponed addItemToMap(myPostponedItems, outputRoot, item); } else { addItemToMap(updateNow, outputRoot, item); } } if (updateNow.size() == 1) { final Map.Entry<String, Collection<TranslatingCompiler.OutputItem>> entry = updateNow.entrySet().iterator().next(); final String outputDir = entry.getKey(); final Collection<TranslatingCompiler.OutputItem> itemsToUpdate = entry.getValue(); TranslatingCompilerFilesMonitor.getInstance().update(myContext, outputDir, itemsToUpdate, filesToRecompile); } else { for (Map.Entry<String, Collection<TranslatingCompiler.OutputItem>> entry : updateNow.entrySet()) { final String outputDir = entry.getKey(); final Collection<TranslatingCompiler.OutputItem> itemsToUpdate = entry.getValue(); TranslatingCompilerFilesMonitor.getInstance().update(myContext, outputDir, itemsToUpdate, VirtualFile.EMPTY_ARRAY); } if (filesToRecompile.length > 0) { TranslatingCompilerFilesMonitor.getInstance().update(myContext, null, Collections.<TranslatingCompiler.OutputItem>emptyList(), filesToRecompile); } } } else { TranslatingCompilerFilesMonitor.getInstance().update(myContext, outputRoot, items, filesToRecompile); } } catch (IOException e) { LOG.info(e); myContext.requestRebuildNextTime(e.getMessage()); } } private static void addItemToMap(Map<String, Collection<TranslatingCompiler.OutputItem>> map, String outputDir, TranslatingCompiler.OutputItem item) { Collection<TranslatingCompiler.OutputItem> collection = map.get(outputDir); if (collection == null) { collection = new ArrayList<TranslatingCompiler.OutputItem>(); map.put(outputDir, collection); } collection.add(item); } public void flushPostponedItems() { final TranslatingCompilerFilesMonitor filesMonitor = TranslatingCompilerFilesMonitor.getInstance(); try { for (Map.Entry<String, Collection<TranslatingCompiler.OutputItem>> entry : myPostponedItems.entrySet()) { final String outputDir = entry.getKey(); final Collection<TranslatingCompiler.OutputItem> items = entry.getValue(); filesMonitor.update(myContext, outputDir, items, VirtualFile.EMPTY_ARRAY); } } catch (IOException e) { LOG.info(e); myContext.requestRebuildNextTime(e.getMessage()); } } } private static class DependentClassesCumulativeFilter implements Function<Pair<int[], Set<VirtualFile>>, Pair<int[], Set<VirtualFile>>> { private final TIntHashSet myProcessedNames = new TIntHashSet(); private final Set<VirtualFile> myProcessedFiles = new HashSet<VirtualFile>(); public Pair<int[], Set<VirtualFile>> fun(Pair<int[], Set<VirtualFile>> deps) { final TIntHashSet currentDeps = new TIntHashSet(deps.getFirst()); currentDeps.removeAll(myProcessedNames.toArray()); myProcessedNames.addAll(deps.getFirst()); final Set<VirtualFile> depFiles = new HashSet<VirtualFile>(deps.getSecond()); depFiles.removeAll(myProcessedFiles); myProcessedFiles.addAll(deps.getSecond()); return new Pair<int[], Set<VirtualFile>>(currentDeps.toArray(), depFiles); } } }
at the end of compilation additionally refresh output roots for generated sources, if they are located under module's source content. Need this to update errors highlighting in IDEA, if annotation processors generated something
java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java
at the end of compilation additionally refresh output roots for generated sources, if they are located under module's source content. Need this to update errors highlighting in IDEA, if annotation processors generated something
<ide><path>ava/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java <ide> if (refreshOutputRoots) { <ide> // refresh on output roots is required in order for the order enumerator to see all roots via VFS <ide> final Set<File> outputs = new HashSet<File>(); <del> for (final String path : CompilerPathsEx.getOutputPaths(ModuleManager.getInstance(myProject).getModules())) { <add> final Module[] affectedModules = compileContext.getCompileScope().getAffectedModules(); <add> for (final String path : CompilerPathsEx.getOutputPaths(affectedModules)) { <ide> outputs.add(new File(path)); <ide> } <add> final LocalFileSystem lfs = LocalFileSystem.getInstance(); <ide> if (!outputs.isEmpty()) { <ide> final ProgressIndicator indicator = compileContext.getProgressIndicator(); <ide> indicator.setText("Synchronizing output directories..."); <del> LocalFileSystem.getInstance().refreshIoFiles(outputs, false, false, null); <add> lfs.refreshIoFiles(outputs, false, false, null); <ide> indicator.setText(""); <add> } <add> if (compileContext.isAnnotationProcessorsEnabled()) { <add> final Set<VirtualFile> genSourceRoots = new HashSet<VirtualFile>(); <add> final CompilerConfiguration config = CompilerConfiguration.getInstance(myProject); <add> for (Module module : affectedModules) { <add> if (config.getAnnotationProcessingConfiguration(module).isEnabled()) { <add> final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); <add> if (path != null) { <add> final File genPath = new File(path); <add> final VirtualFile vFile = lfs.findFileByIoFile(genPath); <add> if (vFile != null && ModuleRootManager.getInstance(module).getFileIndex().isInSourceContent(vFile)) { <add> genSourceRoots.add(vFile); <add> } <add> } <add> } <add> } <add> if (!genSourceRoots.isEmpty()) { <add> // refresh generates source roots asynchronously; needed for error highlighting update <add> lfs.refreshFiles(genSourceRoots, true, true, null); <add> } <ide> } <ide> } <ide> SwingUtilities.invokeLater(new Runnable() {
Java
apache-2.0
688f8e14f60128b75dd58ebcc7e5cffc71a33fe2
0
hysGitHub/hysGitHub
package com.hys.demo.join; /** * join 主要用于 主线程 等待子线程结束 * * @author hys * */ public class JoinDemo { public static void main(String[] args) { final Thread h1 = new Thread(new Runnable() { @Override public void run() {//.. System.err.println(Thread.currentThread().getName()+"执行"); } }); final Thread h2 = new Thread(new Runnable() { @Override public void run() { try { h1.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.err.println(Thread.currentThread().getName()+"执行"); } }); final Thread h3 = new Thread(new Runnable() { @Override public void run() { try { h2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.err.println(Thread.currentThread().getName()+"执行"); } }); try { h3.start(); h2.start(); h1.start(); //主线程 等待 h3 执行完毕 h3.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.err.println(Thread.currentThread().getName()+"执行"); } }
ThreadDemo/src/com/hys/demo/join/JoinDemo.java
package com.hys.demo.join; /** * join 主要用于 主线程 等待子线程结束 * * @author hys * */ public class JoinDemo { public static void main(String[] args) { final Thread h1 = new Thread(new Runnable() { @Override public void run() { System.err.println(Thread.currentThread().getName()+"执行"); } }); final Thread h2 = new Thread(new Runnable() { @Override public void run() { try { h1.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.err.println(Thread.currentThread().getName()+"执行"); } }); final Thread h3 = new Thread(new Runnable() { @Override public void run() { try { h2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.err.println(Thread.currentThread().getName()+"执行"); } }); try { h3.start(); h2.start(); h1.start(); //主线程 等待 h3 执行完毕 h3.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.err.println(Thread.currentThread().getName()+"执行"); } }
joinDemo //..
ThreadDemo/src/com/hys/demo/join/JoinDemo.java
joinDemo //..
<ide><path>hreadDemo/src/com/hys/demo/join/JoinDemo.java <ide> final Thread h1 = new Thread(new Runnable() { <ide> <ide> @Override <del> public void run() { <add> public void run() {//.. <ide> <ide> System.err.println(Thread.currentThread().getName()+"执行"); <ide> }
Java
apache-2.0
6b8f1e0235eee69efd9f599f95fab64993668f39
0
qtproject/qtqa-gerrit,TonyChai24/test,atdt/gerrit,ashang/aaron-gerrit,Distrotech/gerrit,Overruler/gerrit,Distrotech/gerrit,1yvT0s/gerrit,Team-OctOS/host_gerrit,hdost/gerrit,bpollack/gerrit,dwhipstock/gerrit,1yvT0s/gerrit,joshuawilson/merrit,austinchic/Gerrit,netroby/gerrit,CandyShop/gerrit,renchaorevee/gerrit,TonyChai24/test,Distrotech/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,keerath/gerrit_newssh,gracefullife/gerrit,netroby/gerrit,Team-OctOS/host_gerrit,renchaorevee/gerrit,pkdevbox/gerrit,hdost/gerrit,Seinlin/gerrit,gcoders/gerrit,Overruler/gerrit,ashang/aaron-gerrit,qtproject/qtqa-gerrit,cjh1/gerrit,anminhsu/gerrit,dwhipstock/gerrit,hdost/gerrit,cjh1/gerrit,midnightradio/gerrit,duboisf/gerrit,Team-OctOS/host_gerrit,keerath/gerrit_newssh,basilgor/gerrit,gracefullife/gerrit,CandyShop/gerrit,makholm/gerrit-ceremony,gracefullife/gerrit,keerath/gerrit_newssh,anminhsu/gerrit,ashang/aaron-gerrit,WANdisco/gerrit,joshuawilson/merrit,bpollack/gerrit,TonyChai24/test,evanchueng/gerrit,CandyShop/gerrit,Overruler/gerrit,anminhsu/gerrit,Saulis/gerrit,basilgor/gerrit,jackminicloud/test,netroby/gerrit,rtyley/mini-git-server,thinkernel/gerrit,Saulis/gerrit,sudosurootdev/gerrit,austinchic/Gerrit,Saulis/gerrit,GerritCodeReview/gerrit,quyixia/gerrit,CandyShop/gerrit,qtproject/qtqa-gerrit,Seinlin/gerrit,pkdevbox/gerrit,pkdevbox/gerrit,bpollack/gerrit,gcoders/gerrit,Seinlin/gerrit,midnightradio/gerrit,Overruler/gerrit,WANdisco/gerrit,bootstraponline-archive/gerrit-mirror,atdt/gerrit,dwhipstock/gerrit,m1kah/gerrit-contributions,ckamm/gerrit,midnightradio/gerrit,thinkernel/gerrit,evanchueng/gerrit,gerrit-review/gerrit,bootstraponline-archive/gerrit-mirror,midnightradio/gerrit,MerritCR/merrit,GerritCodeReview/gerrit,evanchueng/gerrit,keerath/gerrit_newssh,Distrotech/gerrit,1yvT0s/gerrit,anminhsu/gerrit,ashang/aaron-gerrit,joshuawilson/merrit,thesamet/gerrit,TonyChai24/test,bpollack/gerrit,bootstraponline-archive/gerrit-mirror,anminhsu/gerrit,MerritCR/merrit,makholm/gerrit-ceremony,midnightradio/gerrit,GerritCodeReview/gerrit,renchaorevee/gerrit,Team-OctOS/host_gerrit,zommarin/gerrit,evanchueng/gerrit,qtproject/qtqa-gerrit,dwhipstock/gerrit,pkdevbox/gerrit,skurfuerst/gerrit,joshuawilson/merrit,thesamet/gerrit,netroby/gerrit,jackminicloud/test,sudosurootdev/gerrit,renchaorevee/gerrit,zommarin/gerrit,gerrit-review/gerrit,WANdisco/gerrit,Distrotech/gerrit,joshuawilson/merrit,catrope/gerrit,gcoders/gerrit,joshuawilson/merrit,GerritCodeReview/gerrit,austinchic/Gerrit,1yvT0s/gerrit,skurfuerst/gerrit,gracefullife/gerrit,supriyantomaftuh/gerrit,1yvT0s/gerrit,Seinlin/gerrit,midnightradio/gerrit,thesamet/gerrit,pkdevbox/gerrit,zommarin/gerrit,thinkernel/gerrit,rtyley/mini-git-server,Saulis/gerrit,gracefullife/gerrit,MerritCR/merrit,duboisf/gerrit,jackminicloud/test,qtproject/qtqa-gerrit,WANdisco/gerrit,hdost/gerrit,thesamet/gerrit,catrope/gerrit,ashang/aaron-gerrit,WANdisco/gerrit,jackminicloud/test,ckamm/gerrit,teamblueridge/gerrit,supriyantomaftuh/gerrit,cjh1/gerrit,bpollack/gerrit,renchaorevee/gerrit,atdt/gerrit,jackminicloud/test,MerritCR/merrit,zommarin/gerrit,Seinlin/gerrit,evanchueng/gerrit,hdost/gerrit,joshuawilson/merrit,quyixia/gerrit,quyixia/gerrit,gerrit-review/gerrit,Team-OctOS/host_gerrit,catrope/gerrit,gcoders/gerrit,teamblueridge/gerrit,jeblair/gerrit,makholm/gerrit-ceremony,thesamet/gerrit,Team-OctOS/host_gerrit,joshuawilson/merrit,Team-OctOS/host_gerrit,gcoders/gerrit,anminhsu/gerrit,quyixia/gerrit,WANdisco/gerrit,duboisf/gerrit,qtproject/qtqa-gerrit,supriyantomaftuh/gerrit,TonyChai24/test,gerrit-review/gerrit,pkdevbox/gerrit,TonyChai24/test,thesamet/gerrit,netroby/gerrit,jeblair/gerrit,ckamm/gerrit,GerritCodeReview/gerrit,keerath/gerrit_newssh,quyixia/gerrit,thesamet/gerrit,WANdisco/gerrit,renchaorevee/gerrit,gerrit-review/gerrit,MerritCR/merrit,pkdevbox/gerrit,ckamm/gerrit,renchaorevee/gerrit,sudosurootdev/gerrit,jeblair/gerrit,TonyChai24/test,quyixia/gerrit,gerrit-review/gerrit,Distrotech/gerrit,m1kah/gerrit-contributions,gcoders/gerrit,teamblueridge/gerrit,ckamm/gerrit,dwhipstock/gerrit,cjh1/gerrit,hdost/gerrit,m1kah/gerrit-contributions,jeblair/gerrit,hdost/gerrit,zommarin/gerrit,duboisf/gerrit,Seinlin/gerrit,gcoders/gerrit,thinkernel/gerrit,dwhipstock/gerrit,skurfuerst/gerrit,Overruler/gerrit,qtproject/qtqa-gerrit,basilgor/gerrit,supriyantomaftuh/gerrit,austinchic/Gerrit,supriyantomaftuh/gerrit,GerritCodeReview/gerrit,Seinlin/gerrit,teamblueridge/gerrit,jackminicloud/test,dwhipstock/gerrit,atdt/gerrit,thinkernel/gerrit,supriyantomaftuh/gerrit,teamblueridge/gerrit,thinkernel/gerrit,atdt/gerrit,catrope/gerrit,quyixia/gerrit,bootstraponline-archive/gerrit-mirror,bootstraponline-archive/gerrit-mirror,CandyShop/gerrit,netroby/gerrit,Saulis/gerrit,anminhsu/gerrit,MerritCR/merrit,bootstraponline-archive/gerrit-mirror,m1kah/gerrit-contributions,thinkernel/gerrit,jackminicloud/test,makholm/gerrit-ceremony,MerritCR/merrit,Distrotech/gerrit,basilgor/gerrit,gerrit-review/gerrit,bpollack/gerrit,netroby/gerrit,sudosurootdev/gerrit,supriyantomaftuh/gerrit,Saulis/gerrit,basilgor/gerrit,MerritCR/merrit,Overruler/gerrit,sudosurootdev/gerrit,skurfuerst/gerrit
// Copyright (C) 2008 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.client.admin; import com.google.gerrit.client.Gerrit; import com.google.gerrit.client.rpc.GerritCallback; import com.google.gerrit.client.ui.AccountGroupSuggestOracle; import com.google.gerrit.client.ui.FancyFlexTable; import com.google.gerrit.client.ui.SmallHeading; import com.google.gerrit.common.data.ApprovalType; import com.google.gerrit.common.data.GerritConfig; import com.google.gerrit.common.data.ProjectDetail; import com.google.gerrit.reviewdb.AccountGroup; import com.google.gerrit.reviewdb.ApprovalCategory; import com.google.gerrit.reviewdb.ApprovalCategoryValue; import com.google.gerrit.reviewdb.Project; import com.google.gerrit.reviewdb.RefRight; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.SuggestBox; import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter; import com.google.gwtexpui.globalkey.client.NpTextBox; import com.google.gwtexpui.safehtml.client.SafeHtml; import com.google.gwtexpui.safehtml.client.SafeHtmlBuilder; import com.google.gwtjsonrpc.client.VoidResult; import java.util.HashSet; import java.util.List; import java.util.Map; public class ProjectRightsPanel extends Composite { private Project.NameKey projectName; private RightsTable rights; private Button delRight; private Button addRight; private ListBox catBox; private ListBox rangeMinBox; private ListBox rangeMaxBox; private NpTextBox nameTxtBox; private SuggestBox nameTxt; private NpTextBox referenceTxt; public ProjectRightsPanel(final Project.NameKey toShow) { projectName = toShow; final FlowPanel body = new FlowPanel(); initRights(body); initWidget(body); } @Override protected void onLoad() { enableForm(false); super.onLoad(); Util.PROJECT_SVC.projectDetail(projectName, new GerritCallback<ProjectDetail>() { public void onSuccess(final ProjectDetail result) { enableForm(true); display(result); } }); } private void enableForm(final boolean on) { delRight.setEnabled(on); final boolean canAdd = on && catBox.getItemCount() > 0; addRight.setEnabled(canAdd); nameTxtBox.setEnabled(canAdd); referenceTxt.setEnabled(canAdd); catBox.setEnabled(canAdd); rangeMinBox.setEnabled(canAdd); rangeMaxBox.setEnabled(canAdd); } private void initRights(final Panel body) { final FlowPanel addPanel = new FlowPanel(); addPanel.setStyleName(Gerrit.RESOURCES.css().addSshKeyPanel()); final Grid addGrid = new Grid(5, 2); catBox = new ListBox(); rangeMinBox = new ListBox(); rangeMaxBox = new ListBox(); catBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(final ChangeEvent event) { updateCategorySelection(); } }); for (final ApprovalType at : Gerrit.getConfig().getApprovalTypes() .getApprovalTypes()) { final ApprovalCategory c = at.getCategory(); catBox.addItem(c.getName(), c.getId().get()); } for (final ApprovalType at : Gerrit.getConfig().getApprovalTypes() .getActionTypes()) { final ApprovalCategory c = at.getCategory(); if (Gerrit.getConfig().getWildProject().equals(projectName) && ApprovalCategory.OWN.equals(c.getId())) { // Giving out control of the WILD_PROJECT to other groups beyond // Administrators is dangerous. Having control over WILD_PROJECT // is about the same as having Administrator access as users are // able to affect grants in all projects on the system. // continue; } catBox.addItem(c.getName(), c.getId().get()); } addGrid.setText(0, 0, Util.C.columnApprovalCategory() + ":"); addGrid.setWidget(0, 1, catBox); nameTxtBox = new NpTextBox(); nameTxt = new SuggestBox(new AccountGroupSuggestOracle(), nameTxtBox); nameTxtBox.setVisibleLength(50); nameTxtBox.setText(Util.C.defaultAccountGroupName()); nameTxtBox.addStyleName(Gerrit.RESOURCES.css().inputFieldTypeHint()); nameTxtBox.addFocusHandler(new FocusHandler() { @Override public void onFocus(FocusEvent event) { if (Util.C.defaultAccountGroupName().equals(nameTxtBox.getText())) { nameTxtBox.setText(""); nameTxtBox.removeStyleName(Gerrit.RESOURCES.css() .inputFieldTypeHint()); } } }); nameTxtBox.addBlurHandler(new BlurHandler() { @Override public void onBlur(BlurEvent event) { if ("".equals(nameTxtBox.getText())) { nameTxtBox.setText(Util.C.defaultAccountGroupName()); nameTxtBox.addStyleName(Gerrit.RESOURCES.css().inputFieldTypeHint()); } } }); addGrid.setText(1, 0, Util.C.columnGroupName() + ":"); addGrid.setWidget(1, 1, nameTxt); referenceTxt = new NpTextBox(); referenceTxt.setVisibleLength(50); referenceTxt.setText(""); addGrid.setText(2, 0, Util.C.columnRefName() + ":"); addGrid.setWidget(2, 1, referenceTxt); addGrid.setText(3, 0, Util.C.columnRightRange() + ":"); addGrid.setWidget(3, 1, rangeMinBox); addGrid.setText(4, 0, ""); addGrid.setWidget(4, 1, rangeMaxBox); addRight = new Button(Util.C.buttonAddProjectRight()); addRight.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { doAddNewRight(); } }); addPanel.add(addGrid); addPanel.add(addRight); rights = new RightsTable(); delRight = new Button(Util.C.buttonDeleteGroupMembers()); delRight.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { rights.deleteChecked(); } }); body.add(new SmallHeading(Util.C.headingAccessRights())); body.add(rights); body.add(delRight); body.add(addPanel); if (catBox.getItemCount() > 0) { catBox.setSelectedIndex(0); updateCategorySelection(); } } void display(final ProjectDetail result) { rights.display(result.groups, result.rights); } private void doAddNewRight() { int idx = catBox.getSelectedIndex(); final ApprovalType at; ApprovalCategoryValue min, max; if (idx < 0) { return; } at = Gerrit.getConfig().getApprovalTypes().getApprovalType( new ApprovalCategory.Id(catBox.getValue(idx))); if (at == null) { return; } idx = rangeMinBox.getSelectedIndex(); if (idx < 0) { return; } min = at.getValue(Short.parseShort(rangeMinBox.getValue(idx))); if (min == null) { return; } idx = rangeMaxBox.getSelectedIndex(); if (idx < 0) { return; } max = at.getValue(Short.parseShort(rangeMaxBox.getValue(idx))); if (max == null) { return; } final String groupName = nameTxt.getText(); if ("".equals(groupName) || Util.C.defaultAccountGroupName().equals(groupName)) { return; } final String refPattern = referenceTxt.getText(); if (min.getValue() > max.getValue()) { // If the user selects it backwards in the web UI, help them out // by reversing the order to what we would expect. // final ApprovalCategoryValue newMin = max; final ApprovalCategoryValue newMax = min; min = newMin; max = newMax; } addRight.setEnabled(false); Util.PROJECT_SVC.addRight(projectName, at.getCategory().getId(), groupName, refPattern, min.getValue(), max.getValue(), new GerritCallback<ProjectDetail>() { public void onSuccess(final ProjectDetail result) { addRight.setEnabled(true); nameTxt.setText(""); referenceTxt.setText(""); display(result); } @Override public void onFailure(final Throwable caught) { addRight.setEnabled(true); super.onFailure(caught); } }); } private void updateCategorySelection() { final int idx = catBox.getSelectedIndex(); final ApprovalType at; if (idx >= 0) { at = Gerrit.getConfig().getApprovalTypes().getApprovalType( new ApprovalCategory.Id(catBox.getValue(idx))); } else { at = null; } if (at == null || at.getValues().isEmpty()) { rangeMinBox.setEnabled(false); rangeMaxBox.setEnabled(false); referenceTxt.setEnabled(false); addRight.setEnabled(false); return; } // TODO Support per-branch READ access. if (ApprovalCategory.READ.equals(at.getCategory().getId())) { referenceTxt.setText(""); referenceTxt.setEnabled(false); } else { referenceTxt.setEnabled(true); } int curIndex = 0, minIndex = -1, maxIndex = -1; rangeMinBox.clear(); rangeMaxBox.clear(); for (final ApprovalCategoryValue v : at.getValues()) { final String vStr = String.valueOf(v.getValue()); String nStr = vStr + ": " + v.getName(); if (v.getValue() > 0) { nStr = "+" + nStr; } rangeMinBox.addItem(nStr, vStr); rangeMaxBox.addItem(nStr, vStr); if (v.getValue() < 0) { minIndex = curIndex; } if (maxIndex < 0 && v.getValue() > 0) { maxIndex = curIndex; } curIndex++; } if (ApprovalCategory.READ.equals(at.getCategory().getId())) { // Special case; for READ the most logical range is just // +1 READ, so assume that as the default for both. minIndex = maxIndex; } rangeMinBox.setSelectedIndex(minIndex >= 0 ? minIndex : 0); rangeMaxBox.setSelectedIndex(maxIndex >= 0 ? maxIndex : curIndex - 1); addRight.setEnabled(true); } private class RightsTable extends FancyFlexTable<RefRight> { RightsTable() { table.setWidth(""); table.setText(0, 2, Util.C.columnApprovalCategory()); table.setText(0, 3, Util.C.columnGroupName()); table.setText(0, 4, Util.C.columnRefName()); table.setText(0, 5, Util.C.columnRightRange()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(0, 1, Gerrit.RESOURCES.css().iconHeader()); fmt.addStyleName(0, 2, Gerrit.RESOURCES.css().dataHeader()); fmt.addStyleName(0, 3, Gerrit.RESOURCES.css().dataHeader()); fmt.addStyleName(0, 4, Gerrit.RESOURCES.css().dataHeader()); fmt.addStyleName(0, 5, Gerrit.RESOURCES.css().dataHeader()); } void deleteChecked() { final HashSet<RefRight.Key> refRightIds = new HashSet<RefRight.Key>(); for (int row = 1; row < table.getRowCount(); row++) { RefRight r = getRowItem(row); if (r != null && table.getWidget(row, 1) instanceof CheckBox && ((CheckBox) table.getWidget(row, 1)).getValue()) { refRightIds.add(r.getKey()); } } GerritCallback<VoidResult> updateTable = new GerritCallback<VoidResult>() { @Override public void onSuccess(final VoidResult result) { for (int row = 1; row < table.getRowCount();) { RefRight r = getRowItem(row); if (r != null && refRightIds.contains(r.getKey())) { table.removeRow(row); } else { row++; } } } }; if (!refRightIds.isEmpty()) { Util.PROJECT_SVC.deleteRight(projectName, refRightIds, updateTable); } } void display(final Map<AccountGroup.Id, AccountGroup> groups, final List<RefRight> refRights) { while (1 < table.getRowCount()) table.removeRow(table.getRowCount() - 1); for (final RefRight r : refRights) { final int row = table.getRowCount(); table.insertRow(row); applyDataRowStyle(row); populate(row, groups, r); } } void populate(final int row, final Map<AccountGroup.Id, AccountGroup> groups, final RefRight r) { final GerritConfig config = Gerrit.getConfig(); final ApprovalType ar = config.getApprovalTypes().getApprovalType(r.getApprovalCategoryId()); final AccountGroup group = groups.get(r.getAccountGroupId()); table.setWidget(row, 1, new CheckBox()); if (ar != null) { table.setText(row, 2, ar.getCategory().getName()); } else { table.setText(row, 2, r.getApprovalCategoryId().get()); } if (group != null) { table.setText(row, 3, group.getName()); } else { table.setText(row, 3, Util.M.deletedGroup(r.getAccountGroupId().get())); } table.setText(row, 4, r.getRefPattern()); { final SafeHtmlBuilder m = new SafeHtmlBuilder(); final ApprovalCategoryValue min, max; min = ar != null ? ar.getValue(r.getMinValue()) : null; max = ar != null ? ar.getValue(r.getMaxValue()) : null; formatValue(m, r.getMinValue(), min); if (r.getMinValue() != r.getMaxValue()) { m.br(); formatValue(m, r.getMaxValue(), max); } SafeHtml.set(table, row, 5, m); } final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().iconCell()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 3, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 4, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 5, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 5, Gerrit.RESOURCES.css() .projectAdminApprovalCategoryRangeLine()); setRowItem(row, r); } private void formatValue(final SafeHtmlBuilder m, final short v, final ApprovalCategoryValue e) { m.openSpan(); m .setStyleName(Gerrit.RESOURCES.css() .projectAdminApprovalCategoryValue()); if (v == 0) { m.append(' '); } else if (v > 0) { m.append('+'); } m.append(v); m.closeSpan(); if (e != null) { m.append(": "); m.append(e.getName()); } } } }
gerrit-gwtui/src/main/java/com/google/gerrit/client/admin/ProjectRightsPanel.java
// Copyright (C) 2008 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.client.admin; import com.google.gerrit.client.Gerrit; import com.google.gerrit.client.rpc.GerritCallback; import com.google.gerrit.client.ui.AccountGroupSuggestOracle; import com.google.gerrit.client.ui.FancyFlexTable; import com.google.gerrit.client.ui.SmallHeading; import com.google.gerrit.common.data.ApprovalType; import com.google.gerrit.common.data.GerritConfig; import com.google.gerrit.common.data.ProjectDetail; import com.google.gerrit.reviewdb.AccountGroup; import com.google.gerrit.reviewdb.ApprovalCategory; import com.google.gerrit.reviewdb.ApprovalCategoryValue; import com.google.gerrit.reviewdb.Project; import com.google.gerrit.reviewdb.RefRight; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.SuggestBox; import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter; import com.google.gwtexpui.globalkey.client.NpTextBox; import com.google.gwtexpui.safehtml.client.SafeHtml; import com.google.gwtexpui.safehtml.client.SafeHtmlBuilder; import com.google.gwtjsonrpc.client.VoidResult; import java.util.HashSet; import java.util.List; import java.util.Map; public class ProjectRightsPanel extends Composite { private Project.NameKey projectName; private RightsTable rights; private Button delRight; private Button addRight; private ListBox catBox; private ListBox rangeMinBox; private ListBox rangeMaxBox; private NpTextBox nameTxtBox; private SuggestBox nameTxt; private NpTextBox referenceTxt; public ProjectRightsPanel(final Project.NameKey toShow) { projectName = toShow; final FlowPanel body = new FlowPanel(); initRights(body); initWidget(body); } @Override protected void onLoad() { enableForm(false); super.onLoad(); Util.PROJECT_SVC.projectDetail(projectName, new GerritCallback<ProjectDetail>() { public void onSuccess(final ProjectDetail result) { enableForm(true); display(result); } }); } private void enableForm(final boolean on) { delRight.setEnabled(on); final boolean canAdd = on && catBox.getItemCount() > 0; addRight.setEnabled(canAdd); nameTxtBox.setEnabled(canAdd); referenceTxt.setEnabled(canAdd); catBox.setEnabled(canAdd); rangeMinBox.setEnabled(canAdd); rangeMaxBox.setEnabled(canAdd); } private void initRights(final Panel body) { final FlowPanel addPanel = new FlowPanel(); addPanel.setStyleName(Gerrit.RESOURCES.css().addSshKeyPanel()); final Grid addGrid = new Grid(5, 2); catBox = new ListBox(); rangeMinBox = new ListBox(); rangeMaxBox = new ListBox(); catBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(final ChangeEvent event) { updateCategorySelection(); } }); for (final ApprovalType at : Gerrit.getConfig().getApprovalTypes() .getApprovalTypes()) { final ApprovalCategory c = at.getCategory(); catBox.addItem(c.getName(), c.getId().get()); } for (final ApprovalType at : Gerrit.getConfig().getApprovalTypes() .getActionTypes()) { final ApprovalCategory c = at.getCategory(); if (Gerrit.getConfig().getWildProject().equals(projectName) && ApprovalCategory.OWN.equals(c.getId())) { // Giving out control of the WILD_PROJECT to other groups beyond // Administrators is dangerous. Having control over WILD_PROJECT // is about the same as having Administrator access as users are // able to affect grants in all projects on the system. // continue; } catBox.addItem(c.getName(), c.getId().get()); } if (catBox.getItemCount() > 0) { catBox.setSelectedIndex(0); updateCategorySelection(); } addGrid.setText(0, 0, Util.C.columnApprovalCategory() + ":"); addGrid.setWidget(0, 1, catBox); nameTxtBox = new NpTextBox(); nameTxt = new SuggestBox(new AccountGroupSuggestOracle(), nameTxtBox); nameTxtBox.setVisibleLength(50); nameTxtBox.setText(Util.C.defaultAccountGroupName()); nameTxtBox.addStyleName(Gerrit.RESOURCES.css().inputFieldTypeHint()); nameTxtBox.addFocusHandler(new FocusHandler() { @Override public void onFocus(FocusEvent event) { if (Util.C.defaultAccountGroupName().equals(nameTxtBox.getText())) { nameTxtBox.setText(""); nameTxtBox.removeStyleName(Gerrit.RESOURCES.css() .inputFieldTypeHint()); } } }); nameTxtBox.addBlurHandler(new BlurHandler() { @Override public void onBlur(BlurEvent event) { if ("".equals(nameTxtBox.getText())) { nameTxtBox.setText(Util.C.defaultAccountGroupName()); nameTxtBox.addStyleName(Gerrit.RESOURCES.css().inputFieldTypeHint()); } } }); addGrid.setText(1, 0, Util.C.columnGroupName() + ":"); addGrid.setWidget(1, 1, nameTxt); referenceTxt = new NpTextBox(); referenceTxt.setVisibleLength(50); referenceTxt.setText(""); addGrid.setText(2, 0, Util.C.columnRefName() + ":"); addGrid.setWidget(2, 1, referenceTxt); addGrid.setText(3, 0, Util.C.columnRightRange() + ":"); addGrid.setWidget(3, 1, rangeMinBox); addGrid.setText(4, 0, ""); addGrid.setWidget(4, 1, rangeMaxBox); addRight = new Button(Util.C.buttonAddProjectRight()); addRight.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { doAddNewRight(); } }); addPanel.add(addGrid); addPanel.add(addRight); rights = new RightsTable(); delRight = new Button(Util.C.buttonDeleteGroupMembers()); delRight.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { rights.deleteChecked(); } }); body.add(new SmallHeading(Util.C.headingAccessRights())); body.add(rights); body.add(delRight); body.add(addPanel); } void display(final ProjectDetail result) { rights.display(result.groups, result.rights); } private void doAddNewRight() { int idx = catBox.getSelectedIndex(); final ApprovalType at; ApprovalCategoryValue min, max; if (idx < 0) { return; } at = Gerrit.getConfig().getApprovalTypes().getApprovalType( new ApprovalCategory.Id(catBox.getValue(idx))); if (at == null) { return; } idx = rangeMinBox.getSelectedIndex(); if (idx < 0) { return; } min = at.getValue(Short.parseShort(rangeMinBox.getValue(idx))); if (min == null) { return; } idx = rangeMaxBox.getSelectedIndex(); if (idx < 0) { return; } max = at.getValue(Short.parseShort(rangeMaxBox.getValue(idx))); if (max == null) { return; } final String groupName = nameTxt.getText(); if ("".equals(groupName) || Util.C.defaultAccountGroupName().equals(groupName)) { return; } final String refPattern = referenceTxt.getText(); if (min.getValue() > max.getValue()) { // If the user selects it backwards in the web UI, help them out // by reversing the order to what we would expect. // final ApprovalCategoryValue newMin = max; final ApprovalCategoryValue newMax = min; min = newMin; max = newMax; } addRight.setEnabled(false); Util.PROJECT_SVC.addRight(projectName, at.getCategory().getId(), groupName, refPattern, min.getValue(), max.getValue(), new GerritCallback<ProjectDetail>() { public void onSuccess(final ProjectDetail result) { addRight.setEnabled(true); nameTxt.setText(""); referenceTxt.setText(""); display(result); } @Override public void onFailure(final Throwable caught) { addRight.setEnabled(true); super.onFailure(caught); } }); } private void updateCategorySelection() { final int idx = catBox.getSelectedIndex(); final ApprovalType at; if (idx >= 0) { at = Gerrit.getConfig().getApprovalTypes().getApprovalType( new ApprovalCategory.Id(catBox.getValue(idx))); } else { at = null; } if (at == null || at.getValues().isEmpty()) { rangeMinBox.setEnabled(false); rangeMaxBox.setEnabled(false); referenceTxt.setEnabled(false); addRight.setEnabled(false); return; } // TODO Support per-branch READ access. if (ApprovalCategory.READ.equals(at.getCategory().getId())) { referenceTxt.setText(""); referenceTxt.setEnabled(false); } else { referenceTxt.setEnabled(true); } int curIndex = 0, minIndex = -1, maxIndex = -1; rangeMinBox.clear(); rangeMaxBox.clear(); for (final ApprovalCategoryValue v : at.getValues()) { final String vStr = String.valueOf(v.getValue()); String nStr = vStr + ": " + v.getName(); if (v.getValue() > 0) { nStr = "+" + nStr; } rangeMinBox.addItem(nStr, vStr); rangeMaxBox.addItem(nStr, vStr); if (v.getValue() < 0) { minIndex = curIndex; } if (maxIndex < 0 && v.getValue() > 0) { maxIndex = curIndex; } curIndex++; } if (ApprovalCategory.READ.equals(at.getCategory().getId())) { // Special case; for READ the most logical range is just // +1 READ, so assume that as the default for both. minIndex = maxIndex; } rangeMinBox.setSelectedIndex(minIndex >= 0 ? minIndex : 0); rangeMaxBox.setSelectedIndex(maxIndex >= 0 ? maxIndex : curIndex - 1); addRight.setEnabled(true); } private class RightsTable extends FancyFlexTable<RefRight> { RightsTable() { table.setWidth(""); table.setText(0, 2, Util.C.columnApprovalCategory()); table.setText(0, 3, Util.C.columnGroupName()); table.setText(0, 4, Util.C.columnRefName()); table.setText(0, 5, Util.C.columnRightRange()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(0, 1, Gerrit.RESOURCES.css().iconHeader()); fmt.addStyleName(0, 2, Gerrit.RESOURCES.css().dataHeader()); fmt.addStyleName(0, 3, Gerrit.RESOURCES.css().dataHeader()); fmt.addStyleName(0, 4, Gerrit.RESOURCES.css().dataHeader()); fmt.addStyleName(0, 5, Gerrit.RESOURCES.css().dataHeader()); } void deleteChecked() { final HashSet<RefRight.Key> refRightIds = new HashSet<RefRight.Key>(); for (int row = 1; row < table.getRowCount(); row++) { RefRight r = getRowItem(row); if (r != null && table.getWidget(row, 1) instanceof CheckBox && ((CheckBox) table.getWidget(row, 1)).getValue()) { refRightIds.add(r.getKey()); } } GerritCallback<VoidResult> updateTable = new GerritCallback<VoidResult>() { @Override public void onSuccess(final VoidResult result) { for (int row = 1; row < table.getRowCount();) { RefRight r = getRowItem(row); if (r != null && refRightIds.contains(r.getKey())) { table.removeRow(row); } else { row++; } } } }; if (!refRightIds.isEmpty()) { Util.PROJECT_SVC.deleteRight(projectName, refRightIds, updateTable); } } void display(final Map<AccountGroup.Id, AccountGroup> groups, final List<RefRight> refRights) { while (1 < table.getRowCount()) table.removeRow(table.getRowCount() - 1); for (final RefRight r : refRights) { final int row = table.getRowCount(); table.insertRow(row); applyDataRowStyle(row); populate(row, groups, r); } } void populate(final int row, final Map<AccountGroup.Id, AccountGroup> groups, final RefRight r) { final GerritConfig config = Gerrit.getConfig(); final ApprovalType ar = config.getApprovalTypes().getApprovalType(r.getApprovalCategoryId()); final AccountGroup group = groups.get(r.getAccountGroupId()); table.setWidget(row, 1, new CheckBox()); if (ar != null) { table.setText(row, 2, ar.getCategory().getName()); } else { table.setText(row, 2, r.getApprovalCategoryId().get()); } if (group != null) { table.setText(row, 3, group.getName()); } else { table.setText(row, 3, Util.M.deletedGroup(r.getAccountGroupId().get())); } table.setText(row, 4, r.getRefPattern()); { final SafeHtmlBuilder m = new SafeHtmlBuilder(); final ApprovalCategoryValue min, max; min = ar != null ? ar.getValue(r.getMinValue()) : null; max = ar != null ? ar.getValue(r.getMaxValue()) : null; formatValue(m, r.getMinValue(), min); if (r.getMinValue() != r.getMaxValue()) { m.br(); formatValue(m, r.getMaxValue(), max); } SafeHtml.set(table, row, 5, m); } final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().iconCell()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 3, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 4, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 5, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 5, Gerrit.RESOURCES.css() .projectAdminApprovalCategoryRangeLine()); setRowItem(row, r); } private void formatValue(final SafeHtmlBuilder m, final short v, final ApprovalCategoryValue e) { m.openSpan(); m .setStyleName(Gerrit.RESOURCES.css() .projectAdminApprovalCategoryValue()); if (v == 0) { m.append(' '); } else if (v > 0) { m.append('+'); } m.append(v); m.closeSpan(); if (e != null) { m.append(": "); m.append(e.getName()); } } } }
Fix crash while loading project Access tab We tried to reference a text box before it was created. Defer updating the UI until after the widgets have all been created. Change-Id: Ic475688ef6cfa9aef543d890ccee1fa5e898d086 Signed-off-by: Shawn O. Pearce <[email protected]> Reviewed-by: Nico Sallembien <[email protected]>
gerrit-gwtui/src/main/java/com/google/gerrit/client/admin/ProjectRightsPanel.java
Fix crash while loading project Access tab
<ide><path>errit-gwtui/src/main/java/com/google/gerrit/client/admin/ProjectRightsPanel.java <ide> } <ide> catBox.addItem(c.getName(), c.getId().get()); <ide> } <del> if (catBox.getItemCount() > 0) { <del> catBox.setSelectedIndex(0); <del> updateCategorySelection(); <del> } <ide> <ide> addGrid.setText(0, 0, Util.C.columnApprovalCategory() + ":"); <ide> addGrid.setWidget(0, 1, catBox); <ide> body.add(rights); <ide> body.add(delRight); <ide> body.add(addPanel); <add> <add> if (catBox.getItemCount() > 0) { <add> catBox.setSelectedIndex(0); <add> updateCategorySelection(); <add> } <ide> } <ide> <ide> void display(final ProjectDetail result) {
Java
apache-2.0
01b9d58fd164144714b220deffaa7d232594c6bc
0
emeidiem/SoftModelling
/* * Sketch Copyright (c) 2014 Manuel Jimenez Garcia * HEMesh (c) Frederik Vanhoutte * Toxiclibs library (c) 2009 Karsten Schmidt * ControlP5 (c) 2009 Andreas Schlegel * PeasyCam (c) Jonathan Feinberg */ package softmodelling; import processing.core.PApplet; import processing.core.PFont; import processing.core.PVector; import peasy.PeasyCam; import toxi.geom.Rect; import toxi.geom.Vec3D; import toxi.physics.VerletPhysics; import toxi.physics.behaviors.GravityBehavior; import toxi.physics.behaviors.ParticleBehavior; import toxi.physics.VerletParticle; import toxi.geom.mesh.Face; import toxi.geom.mesh.TriangleMesh; import toxi.geom.mesh.WETriangleMesh; import java.util.ArrayList; import java.util.Iterator; import controlP5.*; import shapes3d.utils.*; import shapes3d.*; import toxi.processing.*; import wblut.hemesh.HET_Export; import wblut.processing.WB_Render; public class SoftModelling extends PApplet { PFont f; PeasyCam cam; float gravityValue = 9.8f; int myColor = color(255, 0, 0); boolean displaySelectors = false; boolean displayVertexKey = false; boolean mouseClicked = false; public boolean displayMesh = true; boolean updatePhysics = false; boolean unlockParticle = false; PVector pickedPos = new PVector(); Vec3D pickedPos3D = new Vec3D(); int boxSize = 5; boolean addingRowsOrCols = false; int selectionMode = 0; float springlengthScale = 1; int subdivLevel = 1; boolean keepEdgesBool = true; boolean keepBoundBool = true; int subdivType = 0; boolean killspringsActive = true; // ---Extrude---// float extrDistance = 0; float extrChanfer = 0; boolean extrSelectNeighbour = false; boolean extrLockExtrudeParticles = false; // ---Lattice---// float latticeDepth = 0; float latticeWidth = 0; boolean lattSelOldFaces = false; boolean lattSelNewFaces = false; boolean lattLockExtrudeParticles = false; int exportIndex = 30; Gui gui; MeshClass mesh; WB_Render render; VerletPhysics physics; ToxiclibsSupport gfx; Surface surface; ArrayList boxesSelected = new ArrayList<BoxClass>(); public void setup() { // size(1900, 980, P3D); size(1900, 1080, P3D); smooth(); cursor(CROSS); cam = new PeasyCam(this, 600); cam.lookAt(0, 0, 0); gui = new Gui(this); mesh = new MeshClass(this); render = new WB_Render(this); physics = new VerletPhysics(); physics.addBehavior(new GravityBehavior(new Vec3D(0, 0, 9.8f))); surface = new Surface(this); println("github check"); println("....................LAUNCHED..................."); } public void draw() { background(0); if (gui.cp5.window(this).isMouseOver()) { cam.setActive(false); } else { cam.setActive(true); } if (mouseClicked) { pickBox(); mouseClicked = false; } renderPickedBox(); gui.run(); if (updatePhysics) { physics.update(); } surface.run(); mesh.run(); } void pickBox() { BoxClass picked = (BoxClass) Shape3D.pickShape(this, mouseX, mouseY); if (picked != null) { picked.isSelected = true; picked.fill(color(255, 0, 0)); pickedPos = picked.getPosVec(); pickedPos3D = new Vec3D(pickedPos.x, pickedPos.y, pickedPos.z); if (boxesSelected.contains(picked)) boxesSelected.add(picked); if (this.selectionMode == 0) surface.getParticleswithKey(surface.particles, picked.key).isSelected = true; if (this.selectionMode == 1) mesh.selectPickedEdges(picked); if (this.selectionMode == 2) mesh.selectPickedFaces(picked); } } void renderPickedBox() { strokeWeight(30); stroke(255, 0, 255, 100); point(pickedPos3D.x, pickedPos3D.y, pickedPos3D.z); } public void mouseClicked() { mouseClicked = true; if (mouseButton == RIGHT) { mesh.deselectAll(); } } public void controlEvent(ControlEvent theEvent) { if (theEvent.isFrom(gui.radB)) { print("got an event from " + theEvent.getName() + "\t"); for (int i = 0; i < theEvent.getGroup().getArrayValue().length; i++) { print((int) (theEvent.getGroup().getArrayValue()[i])); } println("subdivType = " + (int) theEvent.getValue()); subdivType = (int) theEvent.group().value(); } else { if (theEvent.controller().name().equals("Vertex")) selectionMode = 0; if (theEvent.controller().name().equals("Edge")) selectionMode = 1; if (theEvent.controller().name().equals("Face")) selectionMode = 2; } } void SP_LENGTH(int theValue) { if (frameCount > 0) { springlengthScale = theValue; surface.resizeSprings(); } } void GRAVITY(float gravitySlider) { if (frameCount > 0) { gravityValue = gravitySlider; physics.behaviors.clear(); physics.addBehavior(new GravityBehavior(new Vec3D(0, 0, gravityValue))); println("a slider event. setting GRAVITY to " + gravityValue); } } // -----------------------------------------------------------------------tut014 void REMOVE_ELEMENT(float theValue) { if (selectionMode == 0) surface.killSelectParticles(); if (selectionMode == 2) mesh.killSelectedFaces(); if (selectionMode == 1) mesh.killSelectedEdges(); } void KILL_SPRINGS(boolean theFlag) { killspringsActive = theFlag; } // -----------------------------------------------------------------------tut014// void LOCK_ELEMENT(float theValue) { if (selectionMode == 0) surface.lockSelectParticles(); if (selectionMode == 1) mesh.lockSelectedEdges(false); if (selectionMode == 2) mesh.lockSelectedFaces(false); } void UNLOCK_ELEMENT(float theValue) { // unlockParticle = true; if (selectionMode == 0) surface.unlockSelectParticles(); if (selectionMode == 1) mesh.lockSelectedEdges(true); if (selectionMode == 2) mesh.lockSelectedFaces(true); } void GROW() { mesh.growMeshSelection(); } void SHRINK() { mesh.shrinkMeshSelection(); } void SELECT_ALL() { if (selectionMode == 0) surface.selectAllParticles(); if (selectionMode == 1) mesh.selectAllEdges(); if (selectionMode == 2) mesh.selectAllFaces(); } void DESELECT(float theValue) { mesh.deselectAll(); } void SUBDIVIDE_LEVEL(int theValue) { subdivLevel = theValue; } void SUBDIVIDE_KEEPEDGES(boolean theValue) { keepEdgesBool = theValue; } void SUBDIVIDE_KEEPBOUND(boolean theValue) { keepBoundBool = theValue; } void SUBDIVIDE_RUN(float theValue) { mesh.subdivideMesh(); } void EXTRUSION_CHANFER(float theValue) { extrChanfer = theValue; } void EXTRUSION_DISTANCE(float theValue) { extrDistance = theValue; } void EXTRUDE_SELECTNEIGHBOUR(boolean theValue) { extrSelectNeighbour = theValue; } void EXTRUDE_LOCKPARTICLES(boolean theValue) { extrLockExtrudeParticles = theValue; } void EXTRUDE_RUN(float theValue) { mesh.extrudeFaces(); } // -----------------------------------------------------------------------tut013 void LATTICE_DEPTH(float theValue) { latticeDepth = theValue; } void LATTICE_WIDTH(float theValue) { latticeWidth = theValue; } void LATTICE_SELOLD(boolean theFlag) { lattSelOldFaces = theFlag; } void LATTICE_SELNEW(boolean theFlag) { lattSelNewFaces = theFlag; } void LATTICE_LOCKPARTICLES(boolean theFlag) { lattLockExtrudeParticles = theFlag; } void LATTICE_RUN() { mesh.lattice(); } void EXPORT_STL() { HET_Export.saveToSTL(mesh.mesh, dataPath("mesh" + exportIndex + ".stl"), 1.0); exportIndex++; } void EXPORT_OBJ() { HET_Export.saveToOBJ(mesh.mesh, dataPath("mesh" + exportIndex + ".obj")); exportIndex++; } void UPDATE_PHYSICS(boolean theFlag) { if (theFlag == true) { updatePhysics = true; } else { updatePhysics = false; } println("a toggle event."); } void RESET(float theValue) {} void DISPLAY_SELECTORS(boolean theFlag) { displaySelectors = theFlag; } void DISPLAY_KEY(boolean theFlag) { displayVertexKey = theFlag; } void DISPLAY_MESH(boolean theFlag) { displayMesh = theFlag; } public void mousePressed() {} public void mouseDragged() {} public void mouseReleased() { gui.prevMoveX += (gui.slider2d.arrayValue()[0] - (gui.size2dSlider / 2)) * 10; gui.prevMoveY += (gui.slider2d.arrayValue()[1] - (gui.size2dSlider / 2)) * 10; gui.prevMoveZ += (gui.sliderZ.arrayValue()[1] - (gui.sizeZSlider / 2)) * 10; gui.slider2d = gui.cp5.addSlider2D("PARTICLE-XY").setPosition(50, 160).setSize(gui.size2dSlider, gui.size2dSlider).setArrayValue(new float[]{gui.size2dSlider / 2, gui.size2dSlider / 2});// .disableCrosshair(); gui.sliderZ = gui.cp5.addSlider2D("PARTICLE-Z").setPosition(gui.offsetSliders + gui.size2dSlider, 160).setSize(gui.size2dSlider / 10, gui.size2dSlider) .setArrayValue(new float[]{gui.size2dSlider / 2, gui.size2dSlider / 2}).setLabel(""); } public void keyPressed() { // -----------------------------------------------------------------------tut014 if ((keyCode == DELETE) || (keyCode == BACKSPACE)) { if (selectionMode == 0) surface.killSelectParticles(); if (selectionMode == 1) mesh.killSelectedEdges(); if (selectionMode == 2) mesh.killSelectedFaces(); } if (key == 's' || key == 'S') { saveFrames(); } // -----------------------------------------------------------------------tut014// if (gui.cp5.controller("level23") != null) { println("removing multilist button level23."); gui.cp5.controller("level23").remove(); } } void saveFrames() { String PicName; PicName = ("Images/frame_" + frameCount + ".png"); saveFrame(PicName); } public static void main(String _args[]) { PApplet.main(new String[]{softmodelling.SoftModelling.class.getName()}); } }
SoftModelling_Tools/src/softmodelling/SoftModelling.java
/* * Sketch Copyright (c) 2014 Manuel Jimenez Garcia * HEMesh (c) Frederik Vanhoutte * Toxiclibs library (c) 2009 Karsten Schmidt * ControlP5 (c) 2009 Andreas Schlegel * PeasyCam (c) Jonathan Feinberg */ package softmodelling; import processing.core.PApplet; import processing.core.PFont; import processing.core.PVector; import peasy.PeasyCam; import toxi.geom.Rect; import toxi.geom.Vec3D; import toxi.physics.VerletPhysics; import toxi.physics.behaviors.GravityBehavior; import toxi.physics.behaviors.ParticleBehavior; import toxi.physics.VerletParticle; import toxi.geom.mesh.Face; import toxi.geom.mesh.TriangleMesh; import toxi.geom.mesh.WETriangleMesh; import java.util.ArrayList; import java.util.Iterator; import controlP5.*; import shapes3d.utils.*; import shapes3d.*; import toxi.processing.*; import wblut.hemesh.HET_Export; import wblut.processing.WB_Render; public class SoftModelling extends PApplet { PFont f; PeasyCam cam; float gravityValue = 9.8f; int myColor = color(255, 0, 0); boolean displaySelectors = false; boolean displayVertexKey = false; boolean mouseClicked = false; public boolean displayMesh = true; boolean updatePhysics = false; boolean unlockParticle = false; PVector pickedPos = new PVector(); Vec3D pickedPos3D = new Vec3D(); int boxSize = 5; boolean addingRowsOrCols = false; int selectionMode = 0; float springlengthScale = 1; int subdivLevel = 1; boolean keepEdgesBool = true; boolean keepBoundBool = true; int subdivType = 0; boolean killspringsActive = true; // ---Extrude---// float extrDistance = 0; float extrChanfer = 0; boolean extrSelectNeighbour = false; boolean extrLockExtrudeParticles = false; // ---Lattice---// float latticeDepth = 0; float latticeWidth = 0; boolean lattSelOldFaces = false; boolean lattSelNewFaces = false; boolean lattLockExtrudeParticles = false; int exportIndex = 30; Gui gui; MeshClass mesh; WB_Render render; VerletPhysics physics; ToxiclibsSupport gfx; Surface surface; ArrayList boxesSelected = new ArrayList<BoxClass>(); public void setup() { // size(1900, 980, P3D); size(1900, 1080, P3D); smooth(); cursor(CROSS); cam = new PeasyCam(this, 600); cam.lookAt(0, 0, 0); gui = new Gui(this); mesh = new MeshClass(this); render = new WB_Render(this); physics = new VerletPhysics(); physics.addBehavior(new GravityBehavior(new Vec3D(0, 0, 9.8f))); surface = new Surface(this); println("....................LAUNCHED..................."); } public void draw() { background(0); if (gui.cp5.window(this).isMouseOver()) { cam.setActive(false); } else { cam.setActive(true); } if (mouseClicked) { pickBox(); mouseClicked = false; } renderPickedBox(); gui.run(); if (updatePhysics) { physics.update(); } surface.run(); mesh.run(); } void pickBox() { BoxClass picked = (BoxClass) Shape3D.pickShape(this, mouseX, mouseY); if (picked != null) { picked.isSelected = true; picked.fill(color(255, 0, 0)); pickedPos = picked.getPosVec(); pickedPos3D = new Vec3D(pickedPos.x, pickedPos.y, pickedPos.z); if (boxesSelected.contains(picked)) boxesSelected.add(picked); if (this.selectionMode == 0) surface.getParticleswithKey(surface.particles, picked.key).isSelected = true; if (this.selectionMode == 1) mesh.selectPickedEdges(picked); if (this.selectionMode == 2) mesh.selectPickedFaces(picked); } } void renderPickedBox() { strokeWeight(30); stroke(255, 0, 255, 100); point(pickedPos3D.x, pickedPos3D.y, pickedPos3D.z); } public void mouseClicked() { mouseClicked = true; if (mouseButton == RIGHT) { mesh.deselectAll(); } } public void controlEvent(ControlEvent theEvent) { if (theEvent.isFrom(gui.radB)) { print("got an event from " + theEvent.getName() + "\t"); for (int i = 0; i < theEvent.getGroup().getArrayValue().length; i++) { print((int) (theEvent.getGroup().getArrayValue()[i])); } println("subdivType = " + (int) theEvent.getValue()); subdivType = (int) theEvent.group().value(); } else { if (theEvent.controller().name().equals("Vertex")) selectionMode = 0; if (theEvent.controller().name().equals("Edge")) selectionMode = 1; if (theEvent.controller().name().equals("Face")) selectionMode = 2; } } void SP_LENGTH(int theValue) { if (frameCount > 0) { springlengthScale = theValue; surface.resizeSprings(); } } void GRAVITY(float gravitySlider) { if (frameCount > 0) { gravityValue = gravitySlider; physics.behaviors.clear(); physics.addBehavior(new GravityBehavior(new Vec3D(0, 0, gravityValue))); println("a slider event. setting GRAVITY to " + gravityValue); } } // -----------------------------------------------------------------------tut014 void REMOVE_ELEMENT(float theValue) { if (selectionMode == 0) surface.killSelectParticles(); if (selectionMode == 2) mesh.killSelectedFaces(); if (selectionMode == 1) mesh.killSelectedEdges(); } void KILL_SPRINGS(boolean theFlag) { killspringsActive = theFlag; } // -----------------------------------------------------------------------tut014// void LOCK_ELEMENT(float theValue) { if (selectionMode == 0) surface.lockSelectParticles(); if (selectionMode == 1) mesh.lockSelectedEdges(false); if (selectionMode == 2) mesh.lockSelectedFaces(false); } void UNLOCK_ELEMENT(float theValue) { // unlockParticle = true; if (selectionMode == 0) surface.unlockSelectParticles(); if (selectionMode == 1) mesh.lockSelectedEdges(true); if (selectionMode == 2) mesh.lockSelectedFaces(true); } void GROW() { mesh.growMeshSelection(); } void SHRINK() { mesh.shrinkMeshSelection(); } void SELECT_ALL() { if (selectionMode == 0) surface.selectAllParticles(); if (selectionMode == 1) mesh.selectAllEdges(); if (selectionMode == 2) mesh.selectAllFaces(); } void DESELECT(float theValue) { mesh.deselectAll(); } void SUBDIVIDE_LEVEL(int theValue) { subdivLevel = theValue; } void SUBDIVIDE_KEEPEDGES(boolean theValue) { keepEdgesBool = theValue; } void SUBDIVIDE_KEEPBOUND(boolean theValue) { keepBoundBool = theValue; } void SUBDIVIDE_RUN(float theValue) { mesh.subdivideMesh(); } void EXTRUSION_CHANFER(float theValue) { extrChanfer = theValue; } void EXTRUSION_DISTANCE(float theValue) { extrDistance = theValue; } void EXTRUDE_SELECTNEIGHBOUR(boolean theValue) { extrSelectNeighbour = theValue; } void EXTRUDE_LOCKPARTICLES(boolean theValue) { extrLockExtrudeParticles = theValue; } void EXTRUDE_RUN(float theValue) { mesh.extrudeFaces(); } // -----------------------------------------------------------------------tut013 void LATTICE_DEPTH(float theValue) { latticeDepth = theValue; } void LATTICE_WIDTH(float theValue) { latticeWidth = theValue; } void LATTICE_SELOLD(boolean theFlag) { lattSelOldFaces = theFlag; } void LATTICE_SELNEW(boolean theFlag) { lattSelNewFaces = theFlag; } void LATTICE_LOCKPARTICLES(boolean theFlag) { lattLockExtrudeParticles = theFlag; } void LATTICE_RUN() { mesh.lattice(); } void EXPORT_STL() { HET_Export.saveToSTL(mesh.mesh, dataPath("mesh" + exportIndex + ".stl"), 1.0); exportIndex++; } void EXPORT_OBJ() { HET_Export.saveToOBJ(mesh.mesh, dataPath("mesh" + exportIndex + ".obj")); exportIndex++; } void UPDATE_PHYSICS(boolean theFlag) { if (theFlag == true) { updatePhysics = true; } else { updatePhysics = false; } println("a toggle event."); } void RESET(float theValue) {} void DISPLAY_SELECTORS(boolean theFlag) { displaySelectors = theFlag; } void DISPLAY_KEY(boolean theFlag) { displayVertexKey = theFlag; } void DISPLAY_MESH(boolean theFlag) { displayMesh = theFlag; } public void mousePressed() {} public void mouseDragged() {} public void mouseReleased() { gui.prevMoveX += (gui.slider2d.arrayValue()[0] - (gui.size2dSlider / 2)) * 10; gui.prevMoveY += (gui.slider2d.arrayValue()[1] - (gui.size2dSlider / 2)) * 10; gui.prevMoveZ += (gui.sliderZ.arrayValue()[1] - (gui.sizeZSlider / 2)) * 10; gui.slider2d = gui.cp5.addSlider2D("PARTICLE-XY").setPosition(50, 160).setSize(gui.size2dSlider, gui.size2dSlider).setArrayValue(new float[]{gui.size2dSlider / 2, gui.size2dSlider / 2});// .disableCrosshair(); gui.sliderZ = gui.cp5.addSlider2D("PARTICLE-Z").setPosition(gui.offsetSliders + gui.size2dSlider, 160).setSize(gui.size2dSlider / 10, gui.size2dSlider) .setArrayValue(new float[]{gui.size2dSlider / 2, gui.size2dSlider / 2}).setLabel(""); } public void keyPressed() { // -----------------------------------------------------------------------tut014 if ((keyCode == DELETE) || (keyCode == BACKSPACE)) { if (selectionMode == 0) surface.killSelectParticles(); if (selectionMode == 1) mesh.killSelectedEdges(); if (selectionMode == 2) mesh.killSelectedFaces(); } if (key == 's' || key == 'S') { saveFrames(); } // -----------------------------------------------------------------------tut014// if (gui.cp5.controller("level23") != null) { println("removing multilist button level23."); gui.cp5.controller("level23").remove(); } } void saveFrames() { String PicName; PicName = ("Images/frame_" + frameCount + ".png"); saveFrame(PicName); } public static void main(String _args[]) { PApplet.main(new String[]{softmodelling.SoftModelling.class.getName()}); } }
First change - simple check
SoftModelling_Tools/src/softmodelling/SoftModelling.java
First change - simple check
<ide><path>oftModelling_Tools/src/softmodelling/SoftModelling.java <ide> physics = new VerletPhysics(); <ide> physics.addBehavior(new GravityBehavior(new Vec3D(0, 0, 9.8f))); <ide> surface = new Surface(this); <del> <add> println("github check"); <ide> println("....................LAUNCHED..................."); <ide> } <ide> <ide> } <ide> surface.run(); <ide> mesh.run(); <add> <ide> } <ide> void pickBox() { <ide> BoxClass picked = (BoxClass) Shape3D.pickShape(this, mouseX, mouseY);
Java
apache-2.0
22e4eb635ff51a2848f71fc4eb725b7ace61a27c
0
ekoontz/Lily,ekoontz/Lily
package org.lilycms.indexer.model.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.zookeeper.*; import org.apache.zookeeper.data.Stat; import static org.apache.zookeeper.Watcher.Event.EventType.*; import org.lilycms.indexer.model.api.*; import org.lilycms.util.zookeeper.*; import static org.lilycms.indexer.model.api.IndexerModelEventType.*; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; // About how the indexer conf is stored in ZooKeeper // ------------------------------------------------- // I had to make the decision of whether to store all properties of an index in the // data of one node, or rather to add these properties as subnodes. // // The advantages of putting index properties in subnodes are: // - they allow to watch inidividual properties, so you know which one changed // - each property can be updated individually // - there is no impact of big properties, like the indexerconf XML, on other // ones // // The advantages of putting all index properties in the data of one znode are: // - the atomic create or update of an index is easy/possible. ZK does not have // transactions. Intermediate state while performing updates is not visible. // - watching is simpler: just watch one node, rather than having to register // watches on every child node and on the parent for children changes. // - in practice it is usually still easy to know what individual properties // changed, by comparing with previous state you hold yourself. // // So the clear winner was to put all properties in the data of one znode. // It is much easier: less work, reduced complexity, less chance for errors. // Also, the state of indexes does not change frequently, so that the data // of this znode is somewhat bigger is not really important. public class IndexerModelImpl implements WriteableIndexerModel { private ZooKeeperItf zk; /** * Cache of the indexes as they are stored in ZK. Updated based on ZK watcher events. People who update * this cache should synchronize on {@link #indexes_lock}. */ private Map<String, IndexDefinition> indexes = new ConcurrentHashMap<String, IndexDefinition>(16, 0.75f, 1); private final Object indexes_lock = new Object(); private Map<IndexerModelListener, Object> listeners = new IdentityHashMap<IndexerModelListener, Object>(); private Watcher watcher = new MyWatcher(); private Log log = LogFactory.getLog(getClass()); private static final String INDEX_COLLECTION_PATH = "/lily/indexer/index"; private static final String INDEX_COLLECTION_PATH_SLASH = INDEX_COLLECTION_PATH + "/"; public IndexerModelImpl(ZooKeeperItf zk) throws ZkPathCreationException, InterruptedException, KeeperException { this.zk = zk; ZkUtil.createPath(zk, INDEX_COLLECTION_PATH); synchronized(indexes_lock) { refreshIndexes(); } } public IndexDefinition newIndex(String name) { return new IndexDefinitionImpl(name); } public void addIndex(IndexDefinition index) throws IndexExistsException, IndexModelException { assertValid(index); final String indexPath = INDEX_COLLECTION_PATH + "/" + index.getName(); final byte[] data = IndexDefinitionConverter.INSTANCE.toJsonBytes(index); try { ZkUtil.retryOperationForever(new ZooKeeperOperation<String>() { public String execute() throws KeeperException, InterruptedException { return zk.create(indexPath, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } }); } catch (KeeperException.NodeExistsException e) { throw new IndexExistsException(index.getName()); } catch (Exception e) { throw new IndexModelException("Error creating index.", e); } } private void assertValid(IndexDefinition index) { if (index.getName() == null || index.getName().length() == 0) throw new IllegalArgumentException("IndexDefinition: name should not be null or zero-length"); if (index.getConfiguration() == null) throw new IllegalArgumentException("IndexDefinition: configuration should not be null."); if (index.getState() == null) throw new IllegalArgumentException("IndexDefinition: state should not be null."); if (index.getSolrShards() == null || index.getSolrShards().isEmpty()) throw new IllegalArgumentException("IndexDefinition: SOLR shards should not be null or empty."); for (String shard : index.getSolrShards()) { try { URI uri = new URI(shard); if (!uri.isAbsolute()) { throw new IllegalArgumentException("IndexDefinition: SOLR shard URI is not absolute: " + shard); } } catch (URISyntaxException e) { throw new IllegalArgumentException("IndexDefinition: invalid SOLR shard URI: " + shard); } } } public void updateIndex(final IndexDefinition index) throws InterruptedException, KeeperException, IndexNotFoundException, IndexConcurrentModificationException { assertValid(index); final byte[] newData = IndexDefinitionConverter.INSTANCE.toJsonBytes(index); try { ZkUtil.retryOperationForever(new ZooKeeperOperation<Stat>() { public Stat execute() throws KeeperException, InterruptedException { return zk.setData(INDEX_COLLECTION_PATH_SLASH + index.getName(), newData, index.getZkDataVersion()); } }); } catch (KeeperException.NoNodeException e) { throw new IndexNotFoundException(index.getName()); } catch (KeeperException.BadVersionException e) { throw new IndexConcurrentModificationException(index.getName()); } } public String lockIndex(String indexName) throws ZkLockException, IndexNotFoundException, InterruptedException, KeeperException { final String lockPath = INDEX_COLLECTION_PATH_SLASH + indexName + "/lock"; // // Create the lock path if necessary // Stat stat = ZkUtil.retryOperationForever(new ZooKeeperOperation<Stat>() { public Stat execute() throws KeeperException, InterruptedException { return zk.exists(lockPath, null); } }); if (stat == null) { // We do not make use of ZkUtil.createPath (= recursive path creation) on purpose, // because if the parent path does not exist, this means the index does not exist, // and we do not want to create an index path (with null data) like that. try { ZkUtil.retryOperationForever(new ZooKeeperOperation<String>() { public String execute() throws KeeperException, InterruptedException { return zk.create(lockPath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } }); } catch (KeeperException.NodeExistsException e) { // ok, someone created it since we checked } catch (KeeperException.NoNodeException e) { throw new IndexNotFoundException(indexName); } } // // Take the actual lock // return ZkLock.lock(zk, INDEX_COLLECTION_PATH_SLASH + indexName + "/lock"); } public void unlockIndex(String lock) throws ZkLockException { ZkLock.unlock(zk, lock); } public IndexDefinition getIndex(String name) throws IndexNotFoundException { IndexDefinition index = indexes.get(name); if (index == null) { throw new IndexNotFoundException(name); } return index; } public boolean hasIndex(String name) { return indexes.containsKey(name); } public IndexDefinition getMutableIndex(String name) throws InterruptedException, KeeperException, IndexNotFoundException { return loadIndex(name); } public Collection<IndexDefinition> getIndexes() { return new ArrayList<IndexDefinition>(indexes.values()); } public Collection<IndexDefinition> getIndexes(IndexerModelListener listener) { synchronized (indexes_lock) { registerListener(listener); return new ArrayList<IndexDefinition>(indexes.values()); } } public Collection<IndexDefinition> getIndexes(IndexState... states) { return null; } private List<IndexerModelEvent> refreshIndexes() throws InterruptedException, KeeperException { List<IndexerModelEvent> events = new ArrayList<IndexerModelEvent>(); List<String> indexNames = ZkUtil.retryOperationForever(new ZooKeeperOperation<List<String>>() { public List<String> execute() throws KeeperException, InterruptedException { return zk.getChildren(INDEX_COLLECTION_PATH, watcher); } }); Set<String> indexNameSet = new HashSet<String>(); indexNameSet.addAll(indexNames); // Remove indexes which no longer exist in ZK Iterator<String> currentIndexNamesIt = indexes.keySet().iterator(); while (currentIndexNamesIt.hasNext()) { String indexName = currentIndexNamesIt.next(); if (!indexNameSet.contains(indexName)) { currentIndexNamesIt.remove(); events.add(new IndexerModelEvent(INDEX_REMOVED, indexName)); } } // Add new indexes for (String indexName : indexNames) { if (!indexes.containsKey(indexName)) { events.add(refreshIndex(indexName)); } } return events; } /** * Adds or updates the given index to the internal cache. */ private IndexerModelEvent refreshIndex(final String indexName) throws InterruptedException, KeeperException { try { IndexDefinitionImpl index = loadIndex(indexName); index.makeImmutable(); final boolean isNew = !indexes.containsKey(indexName); indexes.put(indexName, index); return new IndexerModelEvent(isNew ? IndexerModelEventType.INDEX_ADDED : IndexerModelEventType.INDEX_UPDATED, indexName); } catch (IndexNotFoundException e) { indexes.remove(indexName); return new IndexerModelEvent(IndexerModelEventType.INDEX_REMOVED, indexName); } } private IndexDefinitionImpl loadIndex(String indexName) throws InterruptedException, KeeperException, IndexNotFoundException { final String childPath = INDEX_COLLECTION_PATH + "/" + indexName; final Stat stat = new Stat(); byte[] data; try { data = ZkUtil.retryOperationForever(new ZooKeeperOperation<byte[]>() { public byte[] execute() throws KeeperException, InterruptedException { return zk.getData(childPath, watcher, stat); } }); } catch (KeeperException.NoNodeException e) { throw new IndexNotFoundException(indexName); } IndexDefinitionImpl index = new IndexDefinitionImpl(indexName); index.setZkDataVersion(stat.getVersion()); IndexDefinitionConverter.INSTANCE.fromJsonBytes(data, index); return index; } private void notifyListeners(List<IndexerModelEvent> events) { for (IndexerModelEvent event : events) { for (IndexerModelListener listener : listeners.keySet()) { listener.process(event); } } } public void registerListener(IndexerModelListener listener) { this.listeners.put(listener, null); } public void unregisterListener(IndexerModelListener listener) { this.listeners.remove(listener); } private class MyWatcher implements Watcher { public void process(WatchedEvent event) { try { if (NodeChildrenChanged.equals(event.getType()) && event.getPath().equals(INDEX_COLLECTION_PATH)) { List<IndexerModelEvent> events; synchronized (indexes_lock) { events = refreshIndexes(); } notifyListeners(events); } else if (NodeDataChanged.equals(event.getType()) && event.getPath().startsWith(INDEX_COLLECTION_PATH_SLASH)) { IndexerModelEvent myEvent; synchronized (indexes_lock) { String indexName = event.getPath().substring(INDEX_COLLECTION_PATH_SLASH.length()); myEvent = refreshIndex(indexName); } notifyListeners(Collections.singletonList(myEvent)); } } catch (Throwable t) { log.error("Indexer Model: error handling event from ZooKeeper. Event: " + event, t); } } } }
indexer/model/src/main/java/org/lilycms/indexer/model/impl/IndexerModelImpl.java
package org.lilycms.indexer.model.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.zookeeper.*; import org.apache.zookeeper.data.Stat; import static org.apache.zookeeper.Watcher.Event.EventType.*; import org.lilycms.indexer.model.api.*; import org.lilycms.util.zookeeper.*; import static org.lilycms.indexer.model.api.IndexerModelEventType.*; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; public class IndexerModelImpl implements WriteableIndexerModel { private ZooKeeperItf zk; /** * Cache of the indexes as they are stored in ZK. Updated based on ZK watcher events. People who update * this cache should synchronize on {@link #indexes_lock}. */ private Map<String, IndexDefinition> indexes = new ConcurrentHashMap<String, IndexDefinition>(16, 0.75f, 1); private final Object indexes_lock = new Object(); private Map<IndexerModelListener, Object> listeners = new IdentityHashMap<IndexerModelListener, Object>(); private Watcher watcher = new MyWatcher(); private Log log = LogFactory.getLog(getClass()); private static final String INDEX_COLLECTION_PATH = "/lily/indexer/index"; private static final String INDEX_COLLECTION_PATH_SLASH = INDEX_COLLECTION_PATH + "/"; public IndexerModelImpl(ZooKeeperItf zk) throws ZkPathCreationException, InterruptedException, KeeperException { this.zk = zk; ZkUtil.createPath(zk, INDEX_COLLECTION_PATH); synchronized(indexes_lock) { refreshIndexes(); } } public IndexDefinition newIndex(String name) { return new IndexDefinitionImpl(name); } public void addIndex(IndexDefinition index) throws IndexExistsException, IndexModelException { assertValid(index); final String indexPath = INDEX_COLLECTION_PATH + "/" + index.getName(); final byte[] data = IndexDefinitionConverter.INSTANCE.toJsonBytes(index); try { ZkUtil.retryOperationForever(new ZooKeeperOperation<String>() { public String execute() throws KeeperException, InterruptedException { return zk.create(indexPath, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } }); } catch (KeeperException.NodeExistsException e) { throw new IndexExistsException(index.getName()); } catch (Exception e) { throw new IndexModelException("Error creating index.", e); } } private void assertValid(IndexDefinition index) { if (index.getName() == null || index.getName().length() == 0) throw new IllegalArgumentException("IndexDefinition: name should not be null or zero-length"); if (index.getConfiguration() == null) throw new IllegalArgumentException("IndexDefinition: configuration should not be null."); if (index.getState() == null) throw new IllegalArgumentException("IndexDefinition: state should not be null."); if (index.getSolrShards() == null || index.getSolrShards().isEmpty()) throw new IllegalArgumentException("IndexDefinition: SOLR shards should not be null or empty."); for (String shard : index.getSolrShards()) { try { URI uri = new URI(shard); if (!uri.isAbsolute()) { throw new IllegalArgumentException("IndexDefinition: SOLR shard URI is not absolute: " + shard); } } catch (URISyntaxException e) { throw new IllegalArgumentException("IndexDefinition: invalid SOLR shard URI: " + shard); } } } public void updateIndex(final IndexDefinition index) throws InterruptedException, KeeperException, IndexNotFoundException, IndexConcurrentModificationException { assertValid(index); final byte[] newData = IndexDefinitionConverter.INSTANCE.toJsonBytes(index); try { ZkUtil.retryOperationForever(new ZooKeeperOperation<Stat>() { public Stat execute() throws KeeperException, InterruptedException { return zk.setData(INDEX_COLLECTION_PATH_SLASH + index.getName(), newData, index.getZkDataVersion()); } }); } catch (KeeperException.NoNodeException e) { throw new IndexNotFoundException(index.getName()); } catch (KeeperException.BadVersionException e) { throw new IndexConcurrentModificationException(index.getName()); } } public String lockIndex(String indexName) throws ZkLockException, IndexNotFoundException, InterruptedException, KeeperException { final String lockPath = INDEX_COLLECTION_PATH_SLASH + indexName + "/lock"; // // Create the lock path if necessary // Stat stat = ZkUtil.retryOperationForever(new ZooKeeperOperation<Stat>() { public Stat execute() throws KeeperException, InterruptedException { return zk.exists(lockPath, null); } }); if (stat == null) { // We do not make use of ZkUtil.createPath (= recursive path creation) on purpose, // because if the parent path does not exist, this means the index does not exist, // and we do not want to create an index path (with null data) like that. try { ZkUtil.retryOperationForever(new ZooKeeperOperation<String>() { public String execute() throws KeeperException, InterruptedException { return zk.create(lockPath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } }); } catch (KeeperException.NodeExistsException e) { // ok, someone created it since we checked } catch (KeeperException.NoNodeException e) { throw new IndexNotFoundException(indexName); } } // // Take the actual lock // return ZkLock.lock(zk, INDEX_COLLECTION_PATH_SLASH + indexName + "/lock"); } public void unlockIndex(String lock) throws ZkLockException { ZkLock.unlock(zk, lock); } public IndexDefinition getIndex(String name) throws IndexNotFoundException { IndexDefinition index = indexes.get(name); if (index == null) { throw new IndexNotFoundException(name); } return index; } public boolean hasIndex(String name) { return indexes.containsKey(name); } public IndexDefinition getMutableIndex(String name) throws InterruptedException, KeeperException, IndexNotFoundException { return loadIndex(name); } public Collection<IndexDefinition> getIndexes() { return new ArrayList<IndexDefinition>(indexes.values()); } public Collection<IndexDefinition> getIndexes(IndexerModelListener listener) { synchronized (indexes_lock) { registerListener(listener); return new ArrayList<IndexDefinition>(indexes.values()); } } public Collection<IndexDefinition> getIndexes(IndexState... states) { return null; } private List<IndexerModelEvent> refreshIndexes() throws InterruptedException, KeeperException { List<IndexerModelEvent> events = new ArrayList<IndexerModelEvent>(); List<String> indexNames = ZkUtil.retryOperationForever(new ZooKeeperOperation<List<String>>() { public List<String> execute() throws KeeperException, InterruptedException { return zk.getChildren(INDEX_COLLECTION_PATH, watcher); } }); Set<String> indexNameSet = new HashSet<String>(); indexNameSet.addAll(indexNames); // Remove indexes which no longer exist in ZK Iterator<String> currentIndexNamesIt = indexes.keySet().iterator(); while (currentIndexNamesIt.hasNext()) { String indexName = currentIndexNamesIt.next(); if (!indexNameSet.contains(indexName)) { currentIndexNamesIt.remove(); events.add(new IndexerModelEvent(INDEX_REMOVED, indexName)); } } // Add new indexes for (String indexName : indexNames) { if (!indexes.containsKey(indexName)) { events.add(refreshIndex(indexName)); } } return events; } /** * Adds or updates the given index to the internal cache. */ private IndexerModelEvent refreshIndex(final String indexName) throws InterruptedException, KeeperException { try { IndexDefinitionImpl index = loadIndex(indexName); index.makeImmutable(); final boolean isNew = !indexes.containsKey(indexName); indexes.put(indexName, index); return new IndexerModelEvent(isNew ? IndexerModelEventType.INDEX_ADDED : IndexerModelEventType.INDEX_UPDATED, indexName); } catch (IndexNotFoundException e) { indexes.remove(indexName); return new IndexerModelEvent(IndexerModelEventType.INDEX_REMOVED, indexName); } } private IndexDefinitionImpl loadIndex(String indexName) throws InterruptedException, KeeperException, IndexNotFoundException { final String childPath = INDEX_COLLECTION_PATH + "/" + indexName; final Stat stat = new Stat(); byte[] data; try { data = ZkUtil.retryOperationForever(new ZooKeeperOperation<byte[]>() { public byte[] execute() throws KeeperException, InterruptedException { return zk.getData(childPath, watcher, stat); } }); } catch (KeeperException.NoNodeException e) { throw new IndexNotFoundException(indexName); } IndexDefinitionImpl index = new IndexDefinitionImpl(indexName); index.setZkDataVersion(stat.getVersion()); IndexDefinitionConverter.INSTANCE.fromJsonBytes(data, index); return index; } private void notifyListeners(List<IndexerModelEvent> events) { for (IndexerModelEvent event : events) { for (IndexerModelListener listener : listeners.keySet()) { listener.process(event); } } } public void registerListener(IndexerModelListener listener) { this.listeners.put(listener, null); } public void unregisterListener(IndexerModelListener listener) { this.listeners.remove(listener); } private class MyWatcher implements Watcher { public void process(WatchedEvent event) { try { if (NodeChildrenChanged.equals(event.getType()) && event.getPath().equals(INDEX_COLLECTION_PATH)) { List<IndexerModelEvent> events; synchronized (indexes_lock) { events = refreshIndexes(); } notifyListeners(events); } else if (NodeDataChanged.equals(event.getType()) && event.getPath().startsWith(INDEX_COLLECTION_PATH_SLASH)) { IndexerModelEvent myEvent; synchronized (indexes_lock) { String indexName = event.getPath().substring(INDEX_COLLECTION_PATH_SLASH.length()); myEvent = refreshIndex(indexName); } notifyListeners(Collections.singletonList(myEvent)); } } catch (Throwable t) { log.error("Indexer Model: error handling event from ZooKeeper. Event: " + event, t); } } } }
Add comment explaining reasoning for putting all properties of an index in the data of one znode rather than in subnodes. git-svn-id: b2e229788468211432b231ab01e4470aadc9ed86@4241 b80d95f8-e103-0410-bd55-e03a9dc29394
indexer/model/src/main/java/org/lilycms/indexer/model/impl/IndexerModelImpl.java
Add comment explaining reasoning for putting all properties of an index in the data of one znode rather than in subnodes.
<ide><path>ndexer/model/src/main/java/org/lilycms/indexer/model/impl/IndexerModelImpl.java <ide> import java.net.URISyntaxException; <ide> import java.util.*; <ide> import java.util.concurrent.ConcurrentHashMap; <add> <add>// About how the indexer conf is stored in ZooKeeper <add>// ------------------------------------------------- <add>// I had to make the decision of whether to store all properties of an index in the <add>// data of one node, or rather to add these properties as subnodes. <add>// <add>// The advantages of putting index properties in subnodes are: <add>// - they allow to watch inidividual properties, so you know which one changed <add>// - each property can be updated individually <add>// - there is no impact of big properties, like the indexerconf XML, on other <add>// ones <add>// <add>// The advantages of putting all index properties in the data of one znode are: <add>// - the atomic create or update of an index is easy/possible. ZK does not have <add>// transactions. Intermediate state while performing updates is not visible. <add>// - watching is simpler: just watch one node, rather than having to register <add>// watches on every child node and on the parent for children changes. <add>// - in practice it is usually still easy to know what individual properties <add>// changed, by comparing with previous state you hold yourself. <add>// <add>// So the clear winner was to put all properties in the data of one znode. <add>// It is much easier: less work, reduced complexity, less chance for errors. <add>// Also, the state of indexes does not change frequently, so that the data <add>// of this znode is somewhat bigger is not really important. <add> <ide> <ide> public class IndexerModelImpl implements WriteableIndexerModel { <ide> private ZooKeeperItf zk;
Java
mit
90d9dd696017fc9feefa28b4e90e79a27e535e96
0
mzmine/mzmine3,mzmine/mzmine3
/* * Copyright 2006-2012 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA */ package net.sf.mzmine.modules.peaklistmethods.io.csvexport; import java.io.File; import java.io.FileWriter; import net.sf.mzmine.data.ChromatographicPeak; import net.sf.mzmine.data.PeakIdentity; import net.sf.mzmine.data.PeakList; import net.sf.mzmine.data.PeakListRow; import net.sf.mzmine.data.PeakStatus; import net.sf.mzmine.data.RawDataFile; import net.sf.mzmine.parameters.ParameterSet; import net.sf.mzmine.taskcontrol.AbstractTask; import net.sf.mzmine.taskcontrol.TaskStatus; class CSVExportTask extends AbstractTask { private PeakList peakList; private int processedRows = 0, totalRows = 0; // parameter values private File fileName; private String fieldSeparator; private ExportRowCommonElement[] commonElements; private String[] identityElements; private ExportRowDataFileElement[] dataFileElements; CSVExportTask(ParameterSet parameters) { this.peakList = parameters.getParameter(CSVExportParameters.peakList) .getValue()[0]; fileName = parameters.getParameter(CSVExportParameters.filename) .getValue(); fieldSeparator = parameters.getParameter( CSVExportParameters.fieldSeparator).getValue(); commonElements = parameters.getParameter( CSVExportParameters.exportCommonItems).getValue(); identityElements = parameters.getParameter( CSVExportParameters.exportIdentityItems).getValue(); dataFileElements = parameters.getParameter( CSVExportParameters.exportDataFileItems).getValue(); } public double getFinishedPercentage() { if (totalRows == 0) { return 0; } return (double) processedRows / (double) totalRows; } public String getTaskDescription() { return "Exporting peak list " + peakList + " to " + fileName; } public void run() { setStatus(TaskStatus.PROCESSING); // Open file FileWriter writer; try { writer = new FileWriter(fileName); } catch (Exception e) { setStatus(TaskStatus.ERROR); errorMessage = "Could not open file " + fileName + " for writing."; return; } // Get number of rows totalRows = peakList.getNumberOfRows(); exportPeakList(peakList, writer); // Close file try { writer.close(); } catch (Exception e) { setStatus(TaskStatus.ERROR); errorMessage = "Could not close file " + fileName; return; } if (getStatus() == TaskStatus.PROCESSING) setStatus(TaskStatus.FINISHED); } private void exportPeakList(PeakList peakList, FileWriter writer) { RawDataFile rawDataFiles[] = peakList.getRawDataFiles(); // Buffer for writing StringBuffer line = new StringBuffer(); // Write column headers // Common elements int length = commonElements.length; String name; for (int i = 0; i < length; i++) { name = commonElements[i].toString(); name = name.replace("Export ", ""); line.append(name + fieldSeparator); } // Peak identity elements length = identityElements.length; for (int i = 0; i < length; i++) { name = identityElements[i]; line.append(name + fieldSeparator); } // Data file elements length = dataFileElements.length; for (int df = 0; df < peakList.getNumberOfRawDataFiles(); df++) { for (int i = 0; i < length; i++) { name = dataFileElements[i].toString(); name = name.replace("Export", rawDataFiles[df].getName()); line.append(name + fieldSeparator); } } line.append("\n"); try { writer.write(line.toString()); } catch (Exception e) { setStatus(TaskStatus.ERROR); errorMessage = "Could not write to file " + fileName; return; } // Write data rows for (PeakListRow peakListRow : peakList.getRows()) { // Cancel? if (isCanceled()) { return; } // Reset the buffer line.setLength(0); // Common elements length = commonElements.length; for (int i = 0; i < length; i++) { switch (commonElements[i]) { case ROW_ID: line.append(peakListRow.getID() + fieldSeparator); break; case ROW_MZ: line.append(peakListRow.getAverageMZ() + fieldSeparator); break; case ROW_RT: line.append((peakListRow.getAverageRT() / 60) + fieldSeparator); break; case ROW_COMMENT: String comment = peakListRow.getComment(); if (comment == null) { line.append(fieldSeparator); break; } // If the text contains fieldSeparator, we will add // parenthesis if (comment.contains(fieldSeparator)) { comment = "\"" + comment.replaceAll("\"", "'") + "\""; } line.append(comment + fieldSeparator); break; case ROW_PEAK_NUMBER: int numDetected = 0; for (ChromatographicPeak p : peakListRow.getPeaks()) { if (p.getPeakStatus() == PeakStatus.DETECTED) { numDetected++; } } line.append(numDetected + fieldSeparator); break; } } // Identity elements length = identityElements.length; PeakIdentity peakIdentity = peakListRow.getPreferredPeakIdentity(); if (peakIdentity != null) { for (int i = 0; i < length; i++) { String propertyValue = peakIdentity .getPropertyValue(identityElements[i]); if (propertyValue == null) { propertyValue = ""; } // If the text contains fieldSeparator, we will add // parenthesis if (propertyValue.contains(fieldSeparator)) { propertyValue = "\"" + propertyValue.replaceAll("\"", "'") + "\""; } line.append(propertyValue + fieldSeparator); } } else { for (int i = 0; i < length; i++) { line.append(fieldSeparator); } } // Data file elements length = dataFileElements.length; for (RawDataFile dataFile : rawDataFiles) { for (int i = 0; i < length; i++) { ChromatographicPeak peak = peakListRow.getPeak(dataFile); if (peak != null) { switch (dataFileElements[i]) { case PEAK_STATUS: line.append(peak.getPeakStatus() + fieldSeparator); break; case PEAK_MZ: line.append(peak.getMZ() + fieldSeparator); break; case PEAK_RT: line.append(peak.getRT() + fieldSeparator); break; case PEAK_HEIGHT: line.append(peak.getHeight() + fieldSeparator); break; case PEAK_AREA: line.append(peak.getArea() + fieldSeparator); break; } } else { line.append("N/A" + fieldSeparator); } } } line.append("\n"); try { writer.write(line.toString()); } catch (Exception e) { setStatus(TaskStatus.ERROR); errorMessage = "Could not write to file " + fileName; return; } processedRows++; } } public Object[] getCreatedObjects() { return null; } }
src/net/sf/mzmine/modules/peaklistmethods/io/csvexport/CSVExportTask.java
/* * Copyright 2006-2012 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA */ package net.sf.mzmine.modules.peaklistmethods.io.csvexport; import java.io.File; import java.io.FileWriter; import net.sf.mzmine.data.ChromatographicPeak; import net.sf.mzmine.data.PeakIdentity; import net.sf.mzmine.data.PeakList; import net.sf.mzmine.data.PeakListRow; import net.sf.mzmine.data.PeakStatus; import net.sf.mzmine.data.RawDataFile; import net.sf.mzmine.parameters.ParameterSet; import net.sf.mzmine.taskcontrol.AbstractTask; import net.sf.mzmine.taskcontrol.TaskStatus; class CSVExportTask extends AbstractTask { private PeakList peakList; private int processedRows = 0, totalRows = 0; // parameter values private File fileName; private String fieldSeparator; private ExportRowCommonElement[] commonElements; private String[] identityElements; private ExportRowDataFileElement[] dataFileElements; CSVExportTask(ParameterSet parameters) { this.peakList = parameters.getParameter(CSVExportParameters.peakList) .getValue()[0]; fileName = parameters.getParameter(CSVExportParameters.filename) .getValue(); fieldSeparator = parameters.getParameter( CSVExportParameters.fieldSeparator).getValue(); commonElements = parameters.getParameter( CSVExportParameters.exportCommonItems).getValue(); identityElements = parameters.getParameter( CSVExportParameters.exportIdentityItems).getValue(); dataFileElements = parameters.getParameter( CSVExportParameters.exportDataFileItems).getValue(); } public double getFinishedPercentage() { if (totalRows == 0) { return 0; } return (double) processedRows / (double) totalRows; } public String getTaskDescription() { return "Exporting peak list " + peakList + " to " + fileName; } public void run() { // Open file FileWriter writer; try { writer = new FileWriter(fileName); } catch (Exception e) { setStatus(TaskStatus.ERROR); errorMessage = "Could not open file " + fileName + " for writing."; return; } // Get number of rows totalRows = peakList.getNumberOfRows(); exportPeakList(peakList, writer); // Close file try { writer.close(); } catch (Exception e) { setStatus(TaskStatus.ERROR); errorMessage = "Could not close file " + fileName; return; } setStatus(TaskStatus.FINISHED); } private void exportPeakList(PeakList peakList, FileWriter writer) { RawDataFile rawDataFiles[] = peakList.getRawDataFiles(); // Buffer for writing StringBuffer line = new StringBuffer(); // Write column headers // Common elements int length = commonElements.length; String name; for (int i = 0; i < length; i++) { name = commonElements[i].toString(); name = name.replace("Export ", ""); line.append(name + fieldSeparator); } // Peak identity elements length = identityElements.length; for (int i = 0; i < length; i++) { name = identityElements[i]; line.append(name + fieldSeparator); } // Data file elements length = dataFileElements.length; for (int df = 0; df < peakList.getNumberOfRawDataFiles(); df++) { for (int i = 0; i < length; i++) { name = dataFileElements[i].toString(); name = name.replace("Export", rawDataFiles[df].getName()); line.append(name + fieldSeparator); } } line.append("\n"); try { writer.write(line.toString()); } catch (Exception e) { setStatus(TaskStatus.ERROR); errorMessage = "Could not write to file " + fileName; return; } // Write data rows for (PeakListRow peakListRow : peakList.getRows()) { // Cancel? if (isCanceled()) { return; } // Reset the buffer line.setLength(0); // Common elements length = commonElements.length; for (int i = 0; i < length; i++) { switch (commonElements[i]) { case ROW_ID: line.append(peakListRow.getID() + fieldSeparator); break; case ROW_MZ: line.append(peakListRow.getAverageMZ() + fieldSeparator); break; case ROW_RT: line.append((peakListRow.getAverageRT() / 60) + fieldSeparator); break; case ROW_COMMENT: String comment = peakListRow.getComment(); if (comment == null) { line.append(fieldSeparator); break; } // If the text contains fieldSeparator, we will add // parenthesis if (comment.contains(fieldSeparator)) { comment = "\"" + comment.replaceAll("\"", "'") + "\""; } line.append(comment + fieldSeparator); break; case ROW_PEAK_NUMBER: int numDetected = 0; for (ChromatographicPeak p : peakListRow.getPeaks()) { if (p.getPeakStatus() == PeakStatus.DETECTED) { numDetected++; } } line.append(numDetected + fieldSeparator); break; } } // Identity elements length = identityElements.length; PeakIdentity peakIdentity = peakListRow.getPreferredPeakIdentity(); if (peakIdentity != null) { for (int i = 0; i < length; i++) { String propertyValue = peakIdentity .getPropertyValue(identityElements[i]); if (propertyValue == null) { propertyValue = ""; } // If the text contains fieldSeparator, we will add // parenthesis if (propertyValue.contains(fieldSeparator)) { propertyValue = "\"" + propertyValue.replaceAll("\"", "'") + "\""; } line.append(propertyValue + fieldSeparator); } } else { for (int i = 0; i < length; i++) { line.append(fieldSeparator); } } // Data file elements length = dataFileElements.length; for (RawDataFile dataFile : rawDataFiles) { for (int i = 0; i < length; i++) { ChromatographicPeak peak = peakListRow.getPeak(dataFile); if (peak != null) { switch (dataFileElements[i]) { case PEAK_STATUS: line.append(peak.getPeakStatus() + fieldSeparator); break; case PEAK_MZ: line.append(peak.getMZ() + fieldSeparator); break; case PEAK_RT: line.append(peak.getRT() + fieldSeparator); break; case PEAK_HEIGHT: line.append(peak.getHeight() + fieldSeparator); break; case PEAK_AREA: line.append(peak.getArea() + fieldSeparator); break; } } else { line.append("N/A" + fieldSeparator); } } } line.append("\n"); try { writer.write(line.toString()); } catch (Exception e) { setStatus(TaskStatus.ERROR); errorMessage = "Could not write to file " + fileName; return; } processedRows++; } } public Object[] getCreatedObjects() { return null; } }
Fixed minor bugs in the CSV module regarding Task status
src/net/sf/mzmine/modules/peaklistmethods/io/csvexport/CSVExportTask.java
Fixed minor bugs in the CSV module regarding Task status
<ide><path>rc/net/sf/mzmine/modules/peaklistmethods/io/csvexport/CSVExportTask.java <ide> <ide> class CSVExportTask extends AbstractTask { <ide> <del> private PeakList peakList; <del> private int processedRows = 0, totalRows = 0; <del> <del> // parameter values <del> private File fileName; <del> private String fieldSeparator; <del> private ExportRowCommonElement[] commonElements; <del> private String[] identityElements; <del> private ExportRowDataFileElement[] dataFileElements; <del> <del> CSVExportTask(ParameterSet parameters) { <del> <del> this.peakList = parameters.getParameter(CSVExportParameters.peakList) <del> .getValue()[0]; <del> <del> fileName = parameters.getParameter(CSVExportParameters.filename) <del> .getValue(); <del> fieldSeparator = parameters.getParameter( <del> CSVExportParameters.fieldSeparator).getValue(); <del> <del> commonElements = parameters.getParameter( <del> CSVExportParameters.exportCommonItems).getValue(); <del> <del> identityElements = parameters.getParameter( <del> CSVExportParameters.exportIdentityItems).getValue(); <del> dataFileElements = parameters.getParameter( <del> CSVExportParameters.exportDataFileItems).getValue(); <del> <del> } <del> <del> public double getFinishedPercentage() { <del> if (totalRows == 0) { <del> return 0; <del> } <del> return (double) processedRows / (double) totalRows; <del> } <del> <del> public String getTaskDescription() { <del> return "Exporting peak list " + peakList + " to " + fileName; <del> } <del> <del> public void run() { <del> <del> // Open file <del> FileWriter writer; <del> try { <del> writer = new FileWriter(fileName); <del> } catch (Exception e) { <del> setStatus(TaskStatus.ERROR); <del> errorMessage = "Could not open file " + fileName + " for writing."; <del> return; <del> } <del> <del> // Get number of rows <del> totalRows = peakList.getNumberOfRows(); <del> <del> exportPeakList(peakList, writer); <del> <del> // Close file <del> try { <del> writer.close(); <del> } catch (Exception e) { <del> setStatus(TaskStatus.ERROR); <del> errorMessage = "Could not close file " + fileName; <del> return; <del> } <del> <del> setStatus(TaskStatus.FINISHED); <del> <del> } <del> <del> private void exportPeakList(PeakList peakList, FileWriter writer) { <del> <del> RawDataFile rawDataFiles[] = peakList.getRawDataFiles(); <del> <del> // Buffer for writing <del> StringBuffer line = new StringBuffer(); <del> <del> // Write column headers <del> // Common elements <del> int length = commonElements.length; <del> String name; <add> private PeakList peakList; <add> private int processedRows = 0, totalRows = 0; <add> <add> // parameter values <add> private File fileName; <add> private String fieldSeparator; <add> private ExportRowCommonElement[] commonElements; <add> private String[] identityElements; <add> private ExportRowDataFileElement[] dataFileElements; <add> <add> CSVExportTask(ParameterSet parameters) { <add> <add> this.peakList = parameters.getParameter(CSVExportParameters.peakList) <add> .getValue()[0]; <add> <add> fileName = parameters.getParameter(CSVExportParameters.filename) <add> .getValue(); <add> fieldSeparator = parameters.getParameter( <add> CSVExportParameters.fieldSeparator).getValue(); <add> <add> commonElements = parameters.getParameter( <add> CSVExportParameters.exportCommonItems).getValue(); <add> <add> identityElements = parameters.getParameter( <add> CSVExportParameters.exportIdentityItems).getValue(); <add> dataFileElements = parameters.getParameter( <add> CSVExportParameters.exportDataFileItems).getValue(); <add> <add> } <add> <add> public double getFinishedPercentage() { <add> if (totalRows == 0) { <add> return 0; <add> } <add> return (double) processedRows / (double) totalRows; <add> } <add> <add> public String getTaskDescription() { <add> return "Exporting peak list " + peakList + " to " + fileName; <add> } <add> <add> public void run() { <add> <add> setStatus(TaskStatus.PROCESSING); <add> <add> // Open file <add> FileWriter writer; <add> try { <add> writer = new FileWriter(fileName); <add> } catch (Exception e) { <add> setStatus(TaskStatus.ERROR); <add> errorMessage = "Could not open file " + fileName + " for writing."; <add> return; <add> } <add> <add> // Get number of rows <add> totalRows = peakList.getNumberOfRows(); <add> <add> exportPeakList(peakList, writer); <add> <add> // Close file <add> try { <add> writer.close(); <add> } catch (Exception e) { <add> setStatus(TaskStatus.ERROR); <add> errorMessage = "Could not close file " + fileName; <add> return; <add> } <add> <add> if (getStatus() == TaskStatus.PROCESSING) <add> setStatus(TaskStatus.FINISHED); <add> <add> } <add> <add> private void exportPeakList(PeakList peakList, FileWriter writer) { <add> <add> RawDataFile rawDataFiles[] = peakList.getRawDataFiles(); <add> <add> // Buffer for writing <add> StringBuffer line = new StringBuffer(); <add> <add> // Write column headers <add> // Common elements <add> int length = commonElements.length; <add> String name; <add> for (int i = 0; i < length; i++) { <add> name = commonElements[i].toString(); <add> name = name.replace("Export ", ""); <add> line.append(name + fieldSeparator); <add> } <add> <add> // Peak identity elements <add> length = identityElements.length; <add> for (int i = 0; i < length; i++) { <add> name = identityElements[i]; <add> line.append(name + fieldSeparator); <add> } <add> <add> // Data file elements <add> length = dataFileElements.length; <add> for (int df = 0; df < peakList.getNumberOfRawDataFiles(); df++) { <add> for (int i = 0; i < length; i++) { <add> name = dataFileElements[i].toString(); <add> name = name.replace("Export", rawDataFiles[df].getName()); <add> line.append(name + fieldSeparator); <add> } <add> } <add> <add> line.append("\n"); <add> <add> try { <add> writer.write(line.toString()); <add> } catch (Exception e) { <add> setStatus(TaskStatus.ERROR); <add> errorMessage = "Could not write to file " + fileName; <add> return; <add> } <add> <add> // Write data rows <add> for (PeakListRow peakListRow : peakList.getRows()) { <add> <add> // Cancel? <add> if (isCanceled()) { <add> return; <add> } <add> <add> // Reset the buffer <add> line.setLength(0); <add> <add> // Common elements <add> length = commonElements.length; <add> for (int i = 0; i < length; i++) { <add> switch (commonElements[i]) { <add> case ROW_ID: <add> line.append(peakListRow.getID() + fieldSeparator); <add> break; <add> case ROW_MZ: <add> line.append(peakListRow.getAverageMZ() + fieldSeparator); <add> break; <add> case ROW_RT: <add> line.append((peakListRow.getAverageRT() / 60) <add> + fieldSeparator); <add> break; <add> case ROW_COMMENT: <add> String comment = peakListRow.getComment(); <add> if (comment == null) { <add> line.append(fieldSeparator); <add> break; <add> } <add> // If the text contains fieldSeparator, we will add <add> // parenthesis <add> if (comment.contains(fieldSeparator)) { <add> comment = "\"" + comment.replaceAll("\"", "'") + "\""; <add> } <add> line.append(comment + fieldSeparator); <add> break; <add> case ROW_PEAK_NUMBER: <add> int numDetected = 0; <add> for (ChromatographicPeak p : peakListRow.getPeaks()) { <add> if (p.getPeakStatus() == PeakStatus.DETECTED) { <add> numDetected++; <add> } <add> } <add> line.append(numDetected + fieldSeparator); <add> break; <add> } <add> } <add> <add> // Identity elements <add> length = identityElements.length; <add> PeakIdentity peakIdentity = peakListRow.getPreferredPeakIdentity(); <add> if (peakIdentity != null) { <ide> for (int i = 0; i < length; i++) { <del> name = commonElements[i].toString(); <del> name = name.replace("Export ", ""); <del> line.append(name + fieldSeparator); <del> } <del> <del> // Peak identity elements <del> length = identityElements.length; <add> String propertyValue = peakIdentity <add> .getPropertyValue(identityElements[i]); <add> if (propertyValue == null) { <add> propertyValue = ""; <add> } <add> <add> // If the text contains fieldSeparator, we will add <add> // parenthesis <add> if (propertyValue.contains(fieldSeparator)) { <add> propertyValue = "\"" <add> + propertyValue.replaceAll("\"", "'") + "\""; <add> } <add> <add> line.append(propertyValue + fieldSeparator); <add> } <add> } else { <ide> for (int i = 0; i < length; i++) { <del> name = identityElements[i]; <del> line.append(name + fieldSeparator); <del> } <del> <del> // Data file elements <del> length = dataFileElements.length; <del> for (int df = 0; df < peakList.getNumberOfRawDataFiles(); df++) { <del> for (int i = 0; i < length; i++) { <del> name = dataFileElements[i].toString(); <del> name = name.replace("Export", rawDataFiles[df].getName()); <del> line.append(name + fieldSeparator); <add> line.append(fieldSeparator); <add> } <add> } <add> <add> // Data file elements <add> length = dataFileElements.length; <add> for (RawDataFile dataFile : rawDataFiles) { <add> for (int i = 0; i < length; i++) { <add> ChromatographicPeak peak = peakListRow.getPeak(dataFile); <add> if (peak != null) { <add> switch (dataFileElements[i]) { <add> case PEAK_STATUS: <add> line.append(peak.getPeakStatus() + fieldSeparator); <add> break; <add> case PEAK_MZ: <add> line.append(peak.getMZ() + fieldSeparator); <add> break; <add> case PEAK_RT: <add> line.append(peak.getRT() + fieldSeparator); <add> break; <add> case PEAK_HEIGHT: <add> line.append(peak.getHeight() + fieldSeparator); <add> break; <add> case PEAK_AREA: <add> line.append(peak.getArea() + fieldSeparator); <add> break; <ide> } <del> } <del> <del> line.append("\n"); <del> <del> try { <del> writer.write(line.toString()); <del> } catch (Exception e) { <del> setStatus(TaskStatus.ERROR); <del> errorMessage = "Could not write to file " + fileName; <del> return; <del> } <del> <del> // Write data rows <del> for (PeakListRow peakListRow : peakList.getRows()) { <del> <del> // Cancel? <del> if (isCanceled()) { <del> return; <del> } <del> <del> // Reset the buffer <del> line.setLength(0); <del> <del> // Common elements <del> length = commonElements.length; <del> for (int i = 0; i < length; i++) { <del> switch (commonElements[i]) { <del> case ROW_ID: <del> line.append(peakListRow.getID() + fieldSeparator); <del> break; <del> case ROW_MZ: <del> line.append(peakListRow.getAverageMZ() + fieldSeparator); <del> break; <del> case ROW_RT: <del> line.append((peakListRow.getAverageRT() / 60) <del> + fieldSeparator); <del> break; <del> case ROW_COMMENT: <del> String comment = peakListRow.getComment(); <del> if (comment == null) { <del> line.append(fieldSeparator); <del> break; <del> } <del> // If the text contains fieldSeparator, we will add <del> // parenthesis <del> if (comment.contains(fieldSeparator)) { <del> comment = "\"" + comment.replaceAll("\"", "'") + "\""; <del> } <del> line.append(comment + fieldSeparator); <del> break; <del> case ROW_PEAK_NUMBER: <del> int numDetected = 0; <del> for (ChromatographicPeak p : peakListRow.getPeaks()) { <del> if (p.getPeakStatus() == PeakStatus.DETECTED) { <del> numDetected++; <del> } <del> } <del> line.append(numDetected + fieldSeparator); <del> break; <del> } <del> } <del> <del> // Identity elements <del> length = identityElements.length; <del> PeakIdentity peakIdentity = peakListRow.getPreferredPeakIdentity(); <del> if (peakIdentity != null) { <del> for (int i = 0; i < length; i++) { <del> String propertyValue = peakIdentity <del> .getPropertyValue(identityElements[i]); <del> if (propertyValue == null) { <del> propertyValue = ""; <del> } <del> <del> // If the text contains fieldSeparator, we will add <del> // parenthesis <del> if (propertyValue.contains(fieldSeparator)) { <del> propertyValue = "\"" <del> + propertyValue.replaceAll("\"", "'") + "\""; <del> } <del> <del> line.append(propertyValue + fieldSeparator); <del> } <del> } else { <del> for (int i = 0; i < length; i++) { <del> line.append(fieldSeparator); <del> } <del> } <del> <del> // Data file elements <del> length = dataFileElements.length; <del> for (RawDataFile dataFile : rawDataFiles) { <del> for (int i = 0; i < length; i++) { <del> ChromatographicPeak peak = peakListRow.getPeak(dataFile); <del> if (peak != null) { <del> switch (dataFileElements[i]) { <del> case PEAK_STATUS: <del> line.append(peak.getPeakStatus() + fieldSeparator); <del> break; <del> case PEAK_MZ: <del> line.append(peak.getMZ() + fieldSeparator); <del> break; <del> case PEAK_RT: <del> line.append(peak.getRT() + fieldSeparator); <del> break; <del> case PEAK_HEIGHT: <del> line.append(peak.getHeight() + fieldSeparator); <del> break; <del> case PEAK_AREA: <del> line.append(peak.getArea() + fieldSeparator); <del> break; <del> } <del> } else { <del> line.append("N/A" + fieldSeparator); <del> } <del> } <del> } <del> <del> line.append("\n"); <del> <del> try { <del> writer.write(line.toString()); <del> } catch (Exception e) { <del> setStatus(TaskStatus.ERROR); <del> errorMessage = "Could not write to file " + fileName; <del> return; <del> } <del> <del> processedRows++; <del> } <del> } <del> <del> public Object[] getCreatedObjects() { <del> return null; <del> } <add> } else { <add> line.append("N/A" + fieldSeparator); <add> } <add> } <add> } <add> <add> line.append("\n"); <add> <add> try { <add> writer.write(line.toString()); <add> } catch (Exception e) { <add> setStatus(TaskStatus.ERROR); <add> errorMessage = "Could not write to file " + fileName; <add> return; <add> } <add> <add> processedRows++; <add> } <add> } <add> <add> public Object[] getCreatedObjects() { <add> return null; <add> } <ide> }
Java
lgpl-2.1
871d4d16b6f321bfdbcdbb9363f11d884b966489
0
xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.xpn.xwiki.doc; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.lang.ref.SoftReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ecs.filter.CharacterFilter; import org.apache.velocity.VelocityContext; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.dom.DOMDocument; import org.dom4j.dom.DOMElement; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.suigeneris.jrcs.diff.Diff; import org.suigeneris.jrcs.diff.DifferentiationFailedException; import org.suigeneris.jrcs.diff.Revision; import org.suigeneris.jrcs.diff.delta.Delta; import org.suigeneris.jrcs.rcs.Version; import org.suigeneris.jrcs.util.ToString; import org.xwiki.rendering.block.XDOM; import org.xwiki.rendering.parser.Parser; import org.xwiki.rendering.parser.SyntaxFactory; import org.xwiki.rendering.renderer.XHTMLRenderer; import org.xwiki.rendering.transformation.TransformationManager; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiConstant; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.DocumentSection; import com.xpn.xwiki.content.Link; import com.xpn.xwiki.content.parsers.DocumentParser; import com.xpn.xwiki.content.parsers.LinkParser; import com.xpn.xwiki.content.parsers.RenamePageReplaceLinkHandler; import com.xpn.xwiki.content.parsers.ReplacementResultCollection; import com.xpn.xwiki.criteria.impl.RevisionCriteria; import com.xpn.xwiki.doc.rcs.XWikiRCSNodeInfo; import com.xpn.xwiki.notify.XWikiNotificationRule; import com.xpn.xwiki.objects.BaseCollection; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseProperty; import com.xpn.xwiki.objects.ListProperty; import com.xpn.xwiki.objects.ObjectDiff; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.objects.classes.ListClass; import com.xpn.xwiki.objects.classes.PropertyClass; import com.xpn.xwiki.objects.classes.StaticListClass; import com.xpn.xwiki.plugin.query.XWikiCriteria; import com.xpn.xwiki.render.XWikiVelocityRenderer; import com.xpn.xwiki.store.XWikiAttachmentStoreInterface; import com.xpn.xwiki.store.XWikiStoreInterface; import com.xpn.xwiki.store.XWikiVersioningStoreInterface; import com.xpn.xwiki.util.Util; import com.xpn.xwiki.validation.XWikiValidationInterface; import com.xpn.xwiki.validation.XWikiValidationStatus; import com.xpn.xwiki.web.EditForm; import com.xpn.xwiki.web.ObjectAddForm; import com.xpn.xwiki.web.Utils; import com.xpn.xwiki.web.XWikiMessageTool; import com.xpn.xwiki.web.XWikiRequest; public class XWikiDocument { private static final Log log = LogFactory.getLog(XWikiDocument.class); /** * Regex Pattern to recognize if there's HTML code in a XWiki page. */ private static final Pattern HTML_TAG_PATTERN = Pattern.compile("</?(html|body|img|a|i|b|embed|script|form|input|textarea|object|" + "font|li|ul|ol|table|center|hr|br|p) ?([^>]*)>"); private String title; private String parent; private String space; private String name; private String content; private String meta; private String format; private String creator; private String author; private String contentAuthor; private String customClass; private Date contentUpdateDate; private Date updateDate; private Date creationDate; private Version version; private long id = 0; private boolean mostRecent = true; private boolean isNew = true; private String template; private String language; private String defaultLanguage; private int translation; private String database; private BaseObject tags; /** * Comment on the latest modification. */ private String comment; /** * Wiki syntax supported by this document. This is used to support different syntaxes inside the same wiki. For * example a page can use the Confluence 2.0 syntax while another one uses the XWiki 1.0 syntax. In practice our * first need is to support the new rendering component. To use the old rendering implementation specify a * "xwiki/1.0" syntaxId and use a "xwiki/2.0" syntaxId for using the new rendering component. */ private String syntaxId; /** * Is latest modification a minor edit */ private boolean isMinorEdit = false; /** * Used to make sure the MetaData String is regenerated. */ private boolean isContentDirty = true; /** * Used to make sure the MetaData String is regenerated */ private boolean isMetaDataDirty = true; public static final int HAS_ATTACHMENTS = 1; public static final int HAS_OBJECTS = 2; public static final int HAS_CLASS = 4; private int elements = HAS_OBJECTS | HAS_ATTACHMENTS; /** * Separator string between database name and space name. */ public static final String DB_SPACE_SEP = ":"; /** * Separator string between space name and page name. */ public static final String SPACE_NAME_SEP = "."; // Meta Data private BaseClass xWikiClass; private String xWikiClassXML; /** * Map holding document objects grouped by classname (className -> Vector of objects). The map is not synchronized, * and uses a TreeMap implementation to preserve className ordering (consistent sorted order for output to XML, * rendering in velocity, etc.) */ private Map<String, Vector<BaseObject>> xWikiObjects = new TreeMap<String, Vector<BaseObject>>(); private List<XWikiAttachment> attachmentList; // Caching private boolean fromCache = false; private ArrayList<BaseObject> objectsToRemove = new ArrayList<BaseObject>(); // Template by default assign to a view private String defaultTemplate; private String validationScript; private Object wikiNode; // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during the // request) private SoftReference<XWikiDocumentArchive> archive; private XWikiStoreInterface store; /** * This is a copy of this XWikiDocument before any modification was made to it. It is reset to the actual values * when the document is saved in the database. This copy is used for finding out differences made to this document * (useful for example to send the correct notifications to document change listeners). */ private XWikiDocument originalDocument; public XWikiStoreInterface getStore(XWikiContext context) { return context.getWiki().getStore(); } public XWikiAttachmentStoreInterface getAttachmentStore(XWikiContext context) { return context.getWiki().getAttachmentStore(); } public XWikiVersioningStoreInterface getVersioningStore(XWikiContext context) { return context.getWiki().getVersioningStore(); } public XWikiStoreInterface getStore() { return this.store; } public void setStore(XWikiStoreInterface store) { this.store = store; } public long getId() { if ((this.language == null) || this.language.trim().equals("")) { this.id = getFullName().hashCode(); } else { this.id = (getFullName() + ":" + this.language).hashCode(); } // if (log.isDebugEnabled()) // log.debug("ID: " + getFullName() + " " + language + ": " + id); return this.id; } public void setId(long id) { this.id = id; } /** * @return the name of the space of the document */ public String getSpace() { return this.space; } public void setSpace(String space) { this.space = space; } public String getVersion() { return getRCSVersion().toString(); } public void setVersion(String version) { if (version != null && !"".equals(version)) { this.version = new Version(version); } } public Version getRCSVersion() { if (this.version == null) { return new Version("1.1"); } return this.version; } public void setRCSVersion(Version version) { this.version = version; } public XWikiDocument() { this("Main", "WebHome"); } public XWikiDocument(String web, String name) { setSpace(web); int i1 = name.indexOf("."); if (i1 == -1) { setName(name); } else { setSpace(name.substring(0, i1)); setName(name.substring(i1 + 1)); } this.updateDate = new Date(); this.updateDate.setTime((this.updateDate.getTime() / 1000) * 1000); this.contentUpdateDate = new Date(); this.contentUpdateDate.setTime((this.contentUpdateDate.getTime() / 1000) * 1000); this.creationDate = new Date(); this.creationDate.setTime((this.creationDate.getTime() / 1000) * 1000); this.parent = ""; this.content = "\n"; this.format = ""; this.author = ""; this.language = ""; this.defaultLanguage = ""; this.attachmentList = new ArrayList<XWikiAttachment>(); this.customClass = ""; this.comment = ""; this.syntaxId = "xwiki/1.0"; // Note: As there's no notion of an Empty document we don't set the original document // field. Thus getOriginalDocument() may return null. } /** * @return the copy of this XWikiDocument instance before any modification was made to it. * @see #originalDocument */ public XWikiDocument getOriginalDocument() { return this.originalDocument; } /** * @param originalDocument the original document representing this document instance before any change was made to * it, prior to the last time it was saved * @see #originalDocument */ public void setOriginalDocument(XWikiDocument originalDocument) { this.originalDocument = originalDocument; } public XWikiDocument getParentDoc() { return new XWikiDocument(getSpace(), getParent()); } public String getParent() { return this.parent != null ? this.parent : ""; } public void setParent(String parent) { if (parent != null && !parent.equals(this.parent)) { setMetaDataDirty(true); } this.parent = parent; } public String getContent() { return this.content; } public void setContent(String content) { if (!content.equals(this.content)) { setContentDirty(true); setWikiNode(null); } this.content = content; } public String getRenderedContent(XWikiContext context) throws XWikiException { String renderedContent; // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem. Otherwise use the new one. if (getSyntaxId().equalsIgnoreCase("xwiki/1.0")) { renderedContent = context.getWiki().getRenderingEngine().renderDocument(this, context); } else { StringWriter writer = new StringWriter(); TransformationManager transformations = (TransformationManager) Utils.getComponent(TransformationManager.ROLE); XDOM dom; try { Parser parser = (Parser) Utils.getComponent(Parser.ROLE, getSyntaxId()); dom = parser.parse(new StringReader(this.content)); SyntaxFactory syntaxFactory = (SyntaxFactory) Utils.getComponent(SyntaxFactory.ROLE); transformations.performTransformations(dom, syntaxFactory.createSyntaxFromIdString(getSyntaxId())); } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN, "Failed to render content using new rendering system", e); } dom.traverse(new XHTMLRenderer(writer)); renderedContent = writer.toString(); } return renderedContent; } public String getRenderedContent(String text, XWikiContext context) { String result; HashMap<String, Object> backup = new HashMap<String, Object>(); try { backupContext(backup, context); setAsContextDoc(context); result = context.getWiki().getRenderingEngine().renderText(text, this, context); } finally { restoreContext(backup, context); } return result; } public String getEscapedContent(XWikiContext context) throws XWikiException { CharacterFilter filter = new CharacterFilter(); return filter.process(getTranslatedContent(context)); } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getFullName() { StringBuffer buf = new StringBuffer(); buf.append(getSpace()); buf.append("."); buf.append(getName()); return buf.toString(); } public void setFullName(String name) { setFullName(name, null); } public String getTitle() { return (this.title != null) ? this.title : ""; } /** * @param context the XWiki context used to get acces to the XWikiRenderingEngine object * @return the document title. If a title has not been provided, look for a section title in the document's content * and if not found return the page name. The returned title is also interpreted which means it's allowed to * use Velocity, Groovy, etc syntax within a title. */ public String getDisplayTitle(XWikiContext context) { // 1) Check if the user has provided a title String title = getTitle(); // 2) If not, then try to extract the title from the first document section title if (title.length() == 0) { title = extractTitle(); } // 3) Last if a title has been found renders it as it can contain macros, velocity code, // groovy, etc. if (title.length() > 0) { // This will not completely work for scriting code in title referencing variables // defined elsewhere. In that case it'll only work if those variables have been // parsed and put in the corresponding scripting context. This will not work for // breadcrumbs for example. title = context.getWiki().getRenderingEngine().interpretText(title, this, context); } else { // 4) No title has been found, return the page name as the title title = getName(); } return title; } /** * @return the first level 1 or level 1.1 title text in the document's content or "" if none are found * @todo this method has nothing to do in this class and should be moved elsewhere */ public String extractTitle() { try { String content = getContent(); int i1 = 0; int i2; while (true) { i2 = content.indexOf("\n", i1); String title = ""; if (i2 != -1) { title = content.substring(i1, i2).trim(); } else { title = content.substring(i1).trim(); } if ((!title.equals("")) && (title.matches("1(\\.1)?\\s+.+"))) { return title.substring(title.indexOf(" ")).trim(); } if (i2 == -1) { break; } i1 = i2 + 1; } } catch (Exception e) { } return ""; } public void setTitle(String title) { if (title != null && !title.equals(this.title)) { setContentDirty(true); } this.title = title; } public String getFormat() { return this.format != null ? this.format : ""; } public void setFormat(String format) { this.format = format; if (!format.equals(this.format)) { setMetaDataDirty(true); } } public String getAuthor() { return this.author != null ? this.author.trim() : ""; } public String getContentAuthor() { return this.contentAuthor != null ? this.contentAuthor.trim() : ""; } public void setAuthor(String author) { if (!getAuthor().equals(author)) { setMetaDataDirty(true); } this.author = author; } public void setContentAuthor(String contentAuthor) { if (!getContentAuthor().equals(contentAuthor)) { setMetaDataDirty(true); } this.contentAuthor = contentAuthor; } public String getCreator() { return this.creator != null ? this.creator.trim() : ""; } public void setCreator(String creator) { if (!getCreator().equals(creator)) { setMetaDataDirty(true); } this.creator = creator; } public Date getDate() { if (this.updateDate == null) { return new Date(); } else { return this.updateDate; } } public void setDate(Date date) { if ((date != null) && (!date.equals(this.updateDate))) { setMetaDataDirty(true); } // Make sure we drop milliseconds for consistency with the database if (date != null) { date.setTime((date.getTime() / 1000) * 1000); } this.updateDate = date; } public Date getCreationDate() { if (this.creationDate == null) { return new Date(); } else { return this.creationDate; } } public void setCreationDate(Date date) { if ((date != null) && (!date.equals(this.creationDate))) { setMetaDataDirty(true); } // Make sure we drop milliseconds for consistency with the database if (date != null) { date.setTime((date.getTime() / 1000) * 1000); } this.creationDate = date; } public Date getContentUpdateDate() { if (this.contentUpdateDate == null) { return new Date(); } else { return this.contentUpdateDate; } } public void setContentUpdateDate(Date date) { if ((date != null) && (!date.equals(this.contentUpdateDate))) { setMetaDataDirty(true); } // Make sure we drop milliseconds for consistency with the database if (date != null) { date.setTime((date.getTime() / 1000) * 1000); } this.contentUpdateDate = date; } public String getMeta() { return this.meta; } public void setMeta(String meta) { if (meta == null) { if (this.meta != null) { setMetaDataDirty(true); } } else if (!meta.equals(this.meta)) { setMetaDataDirty(true); } this.meta = meta; } public void appendMeta(String meta) { StringBuffer buf = new StringBuffer(this.meta); buf.append(meta); buf.append("\n"); this.meta = buf.toString(); setMetaDataDirty(true); } public boolean isContentDirty() { return this.isContentDirty; } public void incrementVersion() { if (this.version == null) { this.version = new Version("1.1"); } else { if (isMinorEdit()) { this.version = this.version.next(); } else { this.version = this.version.getBranchPoint().next().newBranch(1); } } } public void setContentDirty(boolean contentDirty) { this.isContentDirty = contentDirty; } public boolean isMetaDataDirty() { return this.isMetaDataDirty; } public void setMetaDataDirty(boolean metaDataDirty) { this.isMetaDataDirty = metaDataDirty; } public String getAttachmentURL(String filename, XWikiContext context) { return getAttachmentURL(filename, "download", context); } public String getAttachmentURL(String filename, String action, XWikiContext context) { URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getExternalAttachmentURL(String filename, String action, XWikiContext context) { URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(), context); return url.toString(); } public String getAttachmentURL(String filename, String action, String querystring, XWikiContext context) { URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, querystring, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getAttachmentRevisionURL(String filename, String revision, XWikiContext context) { URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getAttachmentRevisionURL(String filename, String revision, String querystring, XWikiContext context) { URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, querystring, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getURL(String action, String params, boolean redirect, XWikiContext context) { URL url = context.getURLFactory().createURL(getSpace(), getName(), action, params, null, getDatabase(), context); if (redirect) { if (url == null) { return null; } else { return url.toString(); } } else { return context.getURLFactory().getURL(url, context); } } public String getURL(String action, boolean redirect, XWikiContext context) { return getURL(action, null, redirect, context); } public String getURL(String action, XWikiContext context) { return getURL(action, false, context); } public String getURL(String action, String querystring, XWikiContext context) { URL url = context.getURLFactory().createURL(getSpace(), getName(), action, querystring, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getExternalURL(String action, XWikiContext context) { URL url = context.getURLFactory() .createExternalURL(getSpace(), getName(), action, null, null, getDatabase(), context); return url.toString(); } public String getExternalURL(String action, String querystring, XWikiContext context) { URL url = context.getURLFactory().createExternalURL(getSpace(), getName(), action, querystring, null, getDatabase(), context); return url.toString(); } public String getParentURL(XWikiContext context) throws XWikiException { XWikiDocument doc = new XWikiDocument(); doc.setFullName(getParent(), context); URL url = context.getURLFactory() .createURL(doc.getSpace(), doc.getName(), "view", null, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public XWikiDocumentArchive getDocumentArchive(XWikiContext context) throws XWikiException { loadArchive(context); return getDocumentArchive(); } /** * return a wrapped version of an XWikiDocument. Prefer this function instead of new Document(XWikiDocument, * XWikiContext) */ public com.xpn.xwiki.api.Document newDocument(String customClassName, XWikiContext context) { if (!((customClassName == null) || (customClassName.equals("")))) { try { Class< ? >[] classes = new Class[] {XWikiDocument.class, XWikiContext.class}; Object[] args = new Object[] {this, context}; return (com.xpn.xwiki.api.Document) Class.forName(customClassName).getConstructor(classes).newInstance( args); } catch (InstantiationException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | // File Templates. } catch (IllegalAccessException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | // File Templates. } catch (ClassNotFoundException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | // File Templates. } catch (NoSuchMethodException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | // File Templates. } catch (InvocationTargetException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | // File Templates. } } return new com.xpn.xwiki.api.Document(this, context); } public com.xpn.xwiki.api.Document newDocument(XWikiContext context) { String customClass = getCustomClass(); return newDocument(customClass, context); } public void loadArchive(XWikiContext context) throws XWikiException { if (this.archive == null || this.archive.get() == null) { XWikiDocumentArchive arch = getVersioningStore(context).getXWikiDocumentArchive(this, context); // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during // the request) this.archive = new SoftReference<XWikiDocumentArchive>(arch); } } public XWikiDocumentArchive getDocumentArchive() { // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during the // request) if (this.archive == null) { return null; } else { return this.archive.get(); } } public void setDocumentArchive(XWikiDocumentArchive arch) { // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during the // request) if (arch != null) { this.archive = new SoftReference<XWikiDocumentArchive>(arch); } } public void setDocumentArchive(String sarch) throws XWikiException { XWikiDocumentArchive xda = new XWikiDocumentArchive(getId()); xda.setArchive(sarch); setDocumentArchive(xda); } public Version[] getRevisions(XWikiContext context) throws XWikiException { return getVersioningStore(context).getXWikiDocVersions(this, context); } public String[] getRecentRevisions(int nb, XWikiContext context) throws XWikiException { try { Version[] revisions = getVersioningStore(context).getXWikiDocVersions(this, context); int length = nb; // 0 means all revisions if (nb == 0) { length = revisions.length; } if (revisions.length < length) { length = revisions.length; } String[] recentrevs = new String[length]; for (int i = 1; i <= length; i++) { recentrevs[i - 1] = revisions[revisions.length - i].toString(); } return recentrevs; } catch (Exception e) { return new String[0]; } } /** * Get document versions matching criterias like author, minimum creation date, etc. * * @param criteria criteria used to match versions * @return a list of matching versions */ public List<String> getRevisions(RevisionCriteria criteria, XWikiContext context) throws XWikiException { List<String> results = new ArrayList<String>(); Version[] revisions = getRevisions(context); XWikiRCSNodeInfo nextNodeinfo = null; XWikiRCSNodeInfo nodeinfo = null; for (int i = 0; i < revisions.length; i++) { nodeinfo = nextNodeinfo; nextNodeinfo = getRevisionInfo(revisions[i].toString(), context); if (nodeinfo == null) { continue; } // Minor/Major version matching if (criteria.getIncludeMinorVersions() || !nextNodeinfo.isMinorEdit()) { // Author matching if (criteria.getAuthor().equals("") || criteria.getAuthor().equals(nodeinfo.getAuthor())) { // Date range matching if (nodeinfo.getDate().after(criteria.getMinDate()) && nodeinfo.getDate().before(criteria.getMaxDate())) { results.add(nodeinfo.getVersion().toString()); } } } } nodeinfo = nextNodeinfo; if (nodeinfo != null) { if (criteria.getAuthor().equals("") || criteria.getAuthor().equals(nodeinfo.getAuthor())) { // Date range matching if (nodeinfo.getDate().after(criteria.getMinDate()) && nodeinfo.getDate().before(criteria.getMaxDate())) { results.add(nodeinfo.getVersion().toString()); } } } return criteria.getRange().subList(results); } public XWikiRCSNodeInfo getRevisionInfo(String version, XWikiContext context) throws XWikiException { return getDocumentArchive(context).getNode(new Version(version)); } /** * @return Is this version the most recent one. False if and only if there are newer versions of this document in * the database. */ public boolean isMostRecent() { return this.mostRecent; } /** * must not be used unless in store system. * * @param mostRecent - mark document as most recent. */ public void setMostRecent(boolean mostRecent) { this.mostRecent = mostRecent; } public BaseClass getxWikiClass() { if (this.xWikiClass == null) { this.xWikiClass = new BaseClass(); this.xWikiClass.setName(getFullName()); } return this.xWikiClass; } public void setxWikiClass(BaseClass xWikiClass) { this.xWikiClass = xWikiClass; } public Map<String, Vector<BaseObject>> getxWikiObjects() { return this.xWikiObjects; } public void setxWikiObjects(Map<String, Vector<BaseObject>> xWikiObjects) { this.xWikiObjects = xWikiObjects; } public BaseObject getxWikiObject() { return getObject(getFullName()); } public List<BaseClass> getxWikiClasses(XWikiContext context) { List<BaseClass> list = new ArrayList<BaseClass>(); // xWikiObjects is a TreeMap, with elements sorted by className for (String classname : getxWikiObjects().keySet()) { BaseClass bclass = null; Vector<BaseObject> objects = getObjects(classname); for (BaseObject obj : objects) { if (obj != null) { bclass = obj.getxWikiClass(context); if (bclass != null) { break; } } } if (bclass != null) { list.add(bclass); } } return list; } public int createNewObject(String classname, XWikiContext context) throws XWikiException { BaseObject object = BaseClass.newCustomClassInstance(classname, context); object.setName(getFullName()); object.setClassName(classname); Vector<BaseObject> objects = getObjects(classname); if (objects == null) { objects = new Vector<BaseObject>(); setObjects(classname, objects); } objects.add(object); int nb = objects.size() - 1; object.setNumber(nb); setContentDirty(true); return nb; } public int getObjectNumbers(String classname) { try { return getxWikiObjects().get(classname).size(); } catch (Exception e) { return 0; } } public Vector<BaseObject> getObjects(String classname) { if (classname == null) { return new Vector<BaseObject>(); } if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } return getxWikiObjects().get(classname); } public void setObjects(String classname, Vector<BaseObject> objects) { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } getxWikiObjects().put(classname, objects); } public BaseObject getObject(String classname) { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } Vector<BaseObject> objects = getxWikiObjects().get(classname); if (objects == null) { return null; } for (int i = 0; i < objects.size(); i++) { BaseObject obj = objects.get(i); if (obj != null) { return obj; } } return null; } public BaseObject getObject(String classname, int nb) { try { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } return getxWikiObjects().get(classname).get(nb); } catch (Exception e) { return null; } } public BaseObject getObject(String classname, String key, String value) { return getObject(classname, key, value, false); } public BaseObject getObject(String classname, String key, String value, boolean failover) { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } try { if (value == null) { if (failover) { return getObject(classname); } else { return null; } } Vector<BaseObject> objects = getxWikiObjects().get(classname); if ((objects == null) || (objects.size() == 0)) { return null; } for (int i = 0; i < objects.size(); i++) { BaseObject obj = objects.get(i); if (obj != null) { if (value.equals(obj.getStringValue(key))) { return obj; } } } if (failover) { return getObject(classname); } else { return null; } } catch (Exception e) { if (failover) { return getObject(classname); } e.printStackTrace(); return null; } } public void addObject(String classname, BaseObject object) { Vector<BaseObject> vobj = getObjects(classname); if (vobj == null) { setObject(classname, 0, object); } else { setObject(classname, vobj.size(), object); } setContentDirty(true); } public void setObject(String classname, int nb, BaseObject object) { Vector<BaseObject> objects = getObjects(classname); if (objects == null) { objects = new Vector<BaseObject>(); setObjects(classname, objects); } if (nb >= objects.size()) { objects.setSize(nb + 1); } objects.set(nb, object); object.setNumber(nb); setContentDirty(true); } /** * @return true if the document is a new one (ie it has never been saved) or false otherwise */ public boolean isNew() { return this.isNew; } public void setNew(boolean aNew) { this.isNew = aNew; } public void mergexWikiClass(XWikiDocument templatedoc) { BaseClass bclass = getxWikiClass(); BaseClass tbclass = templatedoc.getxWikiClass(); if (tbclass != null) { if (bclass == null) { setxWikiClass((BaseClass) tbclass.clone()); } else { getxWikiClass().merge((BaseClass) tbclass.clone()); } } setContentDirty(true); } public void mergexWikiObjects(XWikiDocument templatedoc) { // TODO: look for each object if it already exist and add it if it doesn't for (String name : templatedoc.getxWikiObjects().keySet()) { Vector<BaseObject> myObjects = getxWikiObjects().get(name); if (myObjects == null) { myObjects = new Vector<BaseObject>(); } for (BaseObject otherObject : templatedoc.getxWikiObjects().get(name)) { if (otherObject != null) { BaseObject myObject = (BaseObject) otherObject.clone(); myObjects.add(myObject); myObject.setNumber(myObjects.size() - 1); } } getxWikiObjects().put(name, myObjects); } setContentDirty(true); } public void clonexWikiObjects(XWikiDocument templatedoc) { for (String name : templatedoc.getxWikiObjects().keySet()) { Vector<BaseObject> tobjects = templatedoc.getObjects(name); Vector<BaseObject> objects = new Vector<BaseObject>(); objects.setSize(tobjects.size()); for (int i = 0; i < tobjects.size(); i++) { BaseObject otherObject = tobjects.get(i); if (otherObject != null) { BaseObject myObject = (BaseObject) otherObject.clone(); objects.set(i, myObject); } } getxWikiObjects().put(name, objects); } } public String getTemplate() { return StringUtils.defaultString(this.template); } public void setTemplate(String template) { this.template = template; setMetaDataDirty(true); } public String displayPrettyName(String fieldname, XWikiContext context) { return displayPrettyName(fieldname, false, true, context); } public String displayPrettyName(String fieldname, boolean showMandatory, XWikiContext context) { return displayPrettyName(fieldname, false, true, context); } public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } return displayPrettyName(fieldname, showMandatory, before, object, context); } catch (Exception e) { return ""; } } public String displayPrettyName(String fieldname, BaseObject obj, XWikiContext context) { return displayPrettyName(fieldname, false, true, obj, context); } public String displayPrettyName(String fieldname, boolean showMandatory, BaseObject obj, XWikiContext context) { return displayPrettyName(fieldname, showMandatory, true, obj, context); } public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, BaseObject obj, XWikiContext context) { try { PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname); String dprettyName = ""; if ((showMandatory) && (pclass.getValidationRegExp() != null) && (!pclass.getValidationRegExp().equals(""))) { dprettyName = context.getWiki().addMandatory(context); } if (before) { return dprettyName + pclass.getPrettyName(); } else { return pclass.getPrettyName() + dprettyName; } } catch (Exception e) { return ""; } } public String displayTooltip(String fieldname, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } return displayTooltip(fieldname, object, context); } catch (Exception e) { return ""; } } public String displayTooltip(String fieldname, BaseObject obj, XWikiContext context) { try { PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname); String tooltip = pclass.getTooltip(context); if ((tooltip != null) && (!tooltip.trim().equals(""))) { String img = "<img src=\"" + context.getWiki().getSkinFile("info.gif", context) + "\" class=\"tooltip_image\" align=\"middle\" />"; return context.getWiki().addTooltip(img, tooltip, context); } else { return ""; } } catch (Exception e) { return ""; } } public String display(String fieldname, String type, BaseObject obj, XWikiContext context) { return display(fieldname, type, "", obj, context); } public String display(String fieldname, String type, String pref, BaseObject obj, XWikiContext context) { HashMap<String, Object> backup = new HashMap<String, Object>(); try { backupContext(backup, context); setAsContextDoc(context); type = type.toLowerCase(); StringBuffer result = new StringBuffer(); PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname); String prefix = pref + obj.getxWikiClass(context).getName() + "_" + obj.getNumber() + "_"; if (pclass.isCustomDisplayed(context)) { pclass.displayCustom(result, fieldname, prefix, type, obj, context); } else if (type.equals("view")) { pclass.displayView(result, fieldname, prefix, obj, context); } else if (type.equals("rendered")) { String fcontent = pclass.displayView(fieldname, prefix, obj, context); result.append(getRenderedContent(fcontent, context)); } else if (type.equals("edit")) { context.addDisplayedField(fieldname); result.append("{pre}"); pclass.displayEdit(result, fieldname, prefix, obj, context); result.append("{/pre}"); } else if (type.equals("hidden")) { result.append("{pre}"); pclass.displayHidden(result, fieldname, prefix, obj, context); result.append("{/pre}"); } else if (type.equals("search")) { result.append("{pre}"); prefix = obj.getxWikiClass(context).getName() + "_"; pclass.displaySearch(result, fieldname, prefix, (XWikiCriteria) context.get("query"), context); result.append("{/pre}"); } else { pclass.displayView(result, fieldname, prefix, obj, context); } return result.toString(); } catch (Exception ex) { // TODO: It would better to check if the field exists rather than catching an exception // raised by a NPE as this is currently the case here... log.warn("Failed to display field [" + fieldname + "] in [" + type + "] mode for Object [" + (obj == null ? "NULL" : obj.getName()) + "]"); return ""; } finally { restoreContext(backup, context); } } public String display(String fieldname, BaseObject obj, XWikiContext context) { String type = null; try { type = (String) context.get("display"); } catch (Exception e) { } if (type == null) { type = "view"; } return display(fieldname, type, obj, context); } public String display(String fieldname, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } return display(fieldname, object, context); } catch (Exception e) { return ""; } } public String display(String fieldname, String mode, XWikiContext context) { return display(fieldname, mode, "", context); } public String display(String fieldname, String mode, String prefix, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } if (object == null) { return ""; } else { return display(fieldname, mode, prefix, object, context); } } catch (Exception e) { return ""; } } public String displayForm(String className, String header, String format, XWikiContext context) { return displayForm(className, header, format, true, context); } public String displayForm(String className, String header, String format, boolean linebreak, XWikiContext context) { Vector<BaseObject> objects = getObjects(className); if (format.endsWith("\\n")) { linebreak = true; } BaseObject firstobject = null; Iterator<BaseObject> foit = objects.iterator(); while ((firstobject == null) && foit.hasNext()) { firstobject = foit.next(); } if (firstobject == null) { return ""; } BaseClass bclass = firstobject.getxWikiClass(context); Collection fields = bclass.getFieldList(); if (fields.size() == 0) { return ""; } StringBuffer result = new StringBuffer(); VelocityContext vcontext = new VelocityContext(); for (Iterator it = fields.iterator(); it.hasNext();) { PropertyClass pclass = (PropertyClass) it.next(); vcontext.put(pclass.getName(), pclass.getPrettyName()); } result.append(XWikiVelocityRenderer.evaluate(header, context.getDoc().getFullName(), vcontext, context)); if (linebreak) { result.append("\n"); } // display each line for (int i = 0; i < objects.size(); i++) { vcontext.put("id", new Integer(i + 1)); BaseObject object = objects.get(i); if (object != null) { for (Iterator it = bclass.getPropertyList().iterator(); it.hasNext();) { String name = (String) it.next(); vcontext.put(name, display(name, object, context)); } result .append(XWikiVelocityRenderer.evaluate(format, context.getDoc().getFullName(), vcontext, context)); if (linebreak) { result.append("\n"); } } } return result.toString(); } public String displayForm(String className, XWikiContext context) { Vector<BaseObject> objects = getObjects(className); if (objects == null) { return ""; } BaseObject firstobject = null; Iterator<BaseObject> foit = objects.iterator(); while ((firstobject == null) && foit.hasNext()) { firstobject = foit.next(); } if (firstobject == null) { return ""; } BaseClass bclass = firstobject.getxWikiClass(context); Collection fields = bclass.getFieldList(); if (fields.size() == 0) { return ""; } StringBuffer result = new StringBuffer(); result.append("{table}\n"); boolean first = true; for (Iterator it = fields.iterator(); it.hasNext();) { if (first == true) { first = false; } else { result.append("|"); } PropertyClass pclass = (PropertyClass) it.next(); result.append(pclass.getPrettyName()); } result.append("\n"); for (int i = 0; i < objects.size(); i++) { BaseObject object = objects.get(i); if (object != null) { first = true; for (Iterator it = bclass.getPropertyList().iterator(); it.hasNext();) { if (first == true) { first = false; } else { result.append("|"); } String data = display((String) it.next(), object, context); data = data.trim(); data = data.replaceAll("\n", " "); if (data.length() == 0) { result.append("&nbsp;"); } else { result.append(data); } } result.append("\n"); } } result.append("{table}\n"); return result.toString(); } public boolean isFromCache() { return this.fromCache; } public void setFromCache(boolean fromCache) { this.fromCache = fromCache; } public void readDocMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException { String defaultLanguage = eform.getDefaultLanguage(); if (defaultLanguage != null) { setDefaultLanguage(defaultLanguage); } String defaultTemplate = eform.getDefaultTemplate(); if (defaultTemplate != null) { setDefaultTemplate(defaultTemplate); } String creator = eform.getCreator(); if ((creator != null) && (!creator.equals(getCreator()))) { if ((getCreator().equals(context.getUser())) || (context.getWiki().getRightService().hasAdminRights(context))) { setCreator(creator); } } String parent = eform.getParent(); if (parent != null) { setParent(parent); } // Read the comment from the form String comment = eform.getComment(); if (comment != null) { setComment(comment); } // Read the minor edit checkbox from the form setMinorEdit(eform.isMinorEdit()); String tags = eform.getTags(); if (tags != null) { setTags(tags, context); } // Set the Syntax id if defined String syntaxId = eform.getSyntaxId(); if (syntaxId != null) { setSyntaxId(syntaxId); } } /** * add tags to the document. */ public void setTags(String tags, XWikiContext context) throws XWikiException { loadTags(context); StaticListClass tagProp = (StaticListClass) this.tags.getxWikiClass(context).getField(XWikiConstant.TAG_CLASS_PROP_TAGS); tagProp.fromString(tags); this.tags.safeput(XWikiConstant.TAG_CLASS_PROP_TAGS, tagProp.fromString(tags)); setMetaDataDirty(true); } public String getTags(XWikiContext context) { ListProperty prop = (ListProperty) getTagProperty(context); if (prop != null) { return prop.getTextValue(); } return null; } public List getTagsList(XWikiContext context) { List tagList = null; BaseProperty prop = getTagProperty(context); if (prop != null) { tagList = (List) prop.getValue(); } return tagList; } private BaseProperty getTagProperty(XWikiContext context) { loadTags(context); return ((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS)); } private void loadTags(XWikiContext context) { if (this.tags == null) { this.tags = getObject(XWikiConstant.TAG_CLASS, true, context); } } public List getTagsPossibleValues(XWikiContext context) { loadTags(context); String possibleValues = ((StaticListClass) this.tags.getxWikiClass(context).getField(XWikiConstant.TAG_CLASS_PROP_TAGS)) .getValues(); return ListClass.getListFromString(possibleValues); // ((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS)).toString(); } public void readTranslationMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException { String content = eform.getContent(); if (content != null) { // Cleanup in case we use HTMLAREA // content = context.getUtil().substitute("s/<br class=\\\"htmlarea\\\"\\/>/\\r\\n/g", // content); content = context.getUtil().substitute("s/<br class=\"htmlarea\" \\/>/\r\n/g", content); setContent(content); } String title = eform.getTitle(); if (title != null) { setTitle(title); } } public void readObjectsFromForm(EditForm eform, XWikiContext context) throws XWikiException { for (String name : getxWikiObjects().keySet()) { Vector<BaseObject> oldObjects = getObjects(name); Vector<BaseObject> newObjects = new Vector<BaseObject>(); newObjects.setSize(oldObjects.size()); for (int i = 0; i < oldObjects.size(); i++) { BaseObject oldobject = oldObjects.get(i); if (oldobject != null) { BaseClass baseclass = oldobject.getxWikiClass(context); BaseObject newobject = (BaseObject) baseclass.fromMap(eform.getObject(baseclass.getName() + "_" + i), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setName(getFullName()); newObjects.set(newobject.getNumber(), newobject); } } getxWikiObjects().put(name, newObjects); } setContentDirty(true); } public void readFromForm(EditForm eform, XWikiContext context) throws XWikiException { readDocMetaFromForm(eform, context); readTranslationMetaFromForm(eform, context); readObjectsFromForm(eform, context); } public void readFromTemplate(EditForm eform, XWikiContext context) throws XWikiException { String template = eform.getTemplate(); readFromTemplate(template, context); } public void readFromTemplate(String template, XWikiContext context) throws XWikiException { if ((template != null) && (!template.equals(""))) { String content = getContent(); if ((!content.equals("\n")) && (!content.equals("")) && !isNew()) { Object[] args = {getFullName()}; throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY, "Cannot add a template to document {0} because it already has content", null, args); } else { if (template.indexOf('.') == -1) { template = getSpace() + "." + template; } XWiki xwiki = context.getWiki(); XWikiDocument templatedoc = xwiki.getDocument(template, context); if (templatedoc.isNew()) { Object[] args = {template, getFullName()}; throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_APP_TEMPLATE_DOES_NOT_EXIST, "Template document {0} does not exist when adding to document {1}", null, args); } else { setTemplate(template); setContent(templatedoc.getContent()); if ((getParent() == null) || (getParent().equals(""))) { String tparent = templatedoc.getParent(); if (tparent != null) { setParent(tparent); } } if (isNew()) { // We might have received the object from the cache // and the template objects might have been copied already // we need to remove them setxWikiObjects(new TreeMap<String, Vector<BaseObject>>()); } // Merge the external objects // Currently the choice is not to merge the base class and object because it is // not // the prefered way of using external classes and objects. mergexWikiObjects(templatedoc); } } } setContentDirty(true); } public void notify(XWikiNotificationRule rule, XWikiDocument newdoc, XWikiDocument olddoc, int event, XWikiContext context) { // Do nothing for the moment.. // A usefull thing here would be to look at any instances of a Notification Object // with email addresses and send an email to warn that the document has been modified.. } /** * Use the document passsed as parameter as the new identity for the current document. * * @param document the document containing the new identity * @throws XWikiException in case of error */ private void clone(XWikiDocument document) throws XWikiException { setDatabase(document.getDatabase()); setRCSVersion(document.getRCSVersion()); setDocumentArchive(document.getDocumentArchive()); setAuthor(document.getAuthor()); setContentAuthor(document.getContentAuthor()); setContent(document.getContent()); setContentDirty(document.isContentDirty()); setCreationDate(document.getCreationDate()); setDate(document.getDate()); setCustomClass(document.getCustomClass()); setContentUpdateDate(document.getContentUpdateDate()); setTitle(document.getTitle()); setFormat(document.getFormat()); setFromCache(document.isFromCache()); setElements(document.getElements()); setId(document.getId()); setMeta(document.getMeta()); setMetaDataDirty(document.isMetaDataDirty()); setMostRecent(document.isMostRecent()); setName(document.getName()); setNew(document.isNew()); setStore(document.getStore()); setTemplate(document.getTemplate()); setSpace(document.getSpace()); setParent(document.getParent()); setCreator(document.getCreator()); setDefaultLanguage(document.getDefaultLanguage()); setDefaultTemplate(document.getDefaultTemplate()); setValidationScript(document.getValidationScript()); setLanguage(document.getLanguage()); setTranslation(document.getTranslation()); setxWikiClass((BaseClass) document.getxWikiClass().clone()); setxWikiClassXML(document.getxWikiClassXML()); setComment(document.getComment()); setMinorEdit(document.isMinorEdit()); setSyntaxId(document.getSyntaxId()); setSyntaxId(document.getSyntaxId()); clonexWikiObjects(document); copyAttachments(document); this.elements = document.elements; this.originalDocument = document.originalDocument; } @Override public Object clone() { XWikiDocument doc = null; try { doc = getClass().newInstance(); doc.setDatabase(getDatabase()); doc.setRCSVersion(getRCSVersion()); doc.setDocumentArchive(getDocumentArchive()); doc.setAuthor(getAuthor()); doc.setContentAuthor(getContentAuthor()); doc.setContent(getContent()); doc.setContentDirty(isContentDirty()); doc.setCreationDate(getCreationDate()); doc.setDate(getDate()); doc.setCustomClass(getCustomClass()); doc.setContentUpdateDate(getContentUpdateDate()); doc.setTitle(getTitle()); doc.setFormat(getFormat()); doc.setFromCache(isFromCache()); doc.setElements(getElements()); doc.setId(getId()); doc.setMeta(getMeta()); doc.setMetaDataDirty(isMetaDataDirty()); doc.setMostRecent(isMostRecent()); doc.setName(getName()); doc.setNew(isNew()); doc.setStore(getStore()); doc.setTemplate(getTemplate()); doc.setSpace(getSpace()); doc.setParent(getParent()); doc.setCreator(getCreator()); doc.setDefaultLanguage(getDefaultLanguage()); doc.setDefaultTemplate(getDefaultTemplate()); doc.setValidationScript(getValidationScript()); doc.setLanguage(getLanguage()); doc.setTranslation(getTranslation()); doc.setxWikiClass((BaseClass) getxWikiClass().clone()); doc.setxWikiClassXML(getxWikiClassXML()); doc.setComment(getComment()); doc.setMinorEdit(isMinorEdit()); doc.setSyntaxId(getSyntaxId()); doc.clonexWikiObjects(this); doc.copyAttachments(this); doc.elements = this.elements; doc.originalDocument = this.originalDocument; } catch (Exception e) { // This should not happen log.error("Exception while doc.clone", e); } return doc; } public void copyAttachments(XWikiDocument xWikiSourceDocument) { getAttachmentList().clear(); Iterator<XWikiAttachment> attit = xWikiSourceDocument.getAttachmentList().iterator(); while (attit.hasNext()) { XWikiAttachment attachment = attit.next(); XWikiAttachment newattachment = (XWikiAttachment) attachment.clone(); newattachment.setDoc(this); if (newattachment.getAttachment_content() != null) { newattachment.getAttachment_content().setContentDirty(true); } getAttachmentList().add(newattachment); } setContentDirty(true); } public void loadAttachments(XWikiContext context) throws XWikiException { for (XWikiAttachment attachment : getAttachmentList()) { attachment.loadContent(context); attachment.loadArchive(context); } } @Override public boolean equals(Object object) { XWikiDocument doc = (XWikiDocument) object; if (!getName().equals(doc.getName())) { return false; } if (!getSpace().equals(doc.getSpace())) { return false; } if (!getAuthor().equals(doc.getAuthor())) { return false; } if (!getContentAuthor().equals(doc.getContentAuthor())) { return false; } if (!getParent().equals(doc.getParent())) { return false; } if (!getCreator().equals(doc.getCreator())) { return false; } if (!getDefaultLanguage().equals(doc.getDefaultLanguage())) { return false; } if (!getLanguage().equals(doc.getLanguage())) { return false; } if (getTranslation() != doc.getTranslation()) { return false; } if (getDate().getTime() != doc.getDate().getTime()) { return false; } if (getContentUpdateDate().getTime() != doc.getContentUpdateDate().getTime()) { return false; } if (getCreationDate().getTime() != doc.getCreationDate().getTime()) { return false; } if (!getFormat().equals(doc.getFormat())) { return false; } if (!getTitle().equals(doc.getTitle())) { return false; } if (!getContent().equals(doc.getContent())) { return false; } if (!getVersion().equals(doc.getVersion())) { return false; } if (!getTemplate().equals(doc.getTemplate())) { return false; } if (!getDefaultTemplate().equals(doc.getDefaultTemplate())) { return false; } if (!getValidationScript().equals(doc.getValidationScript())) { return false; } if (!getComment().equals(doc.getComment())) { return false; } if (isMinorEdit() != doc.isMinorEdit()) { return false; } if (!getSyntaxId().equals(doc.getSyntaxId())) { return false; } if (!getxWikiClass().equals(doc.getxWikiClass())) { return false; } Set<String> myObjectClassnames = getxWikiObjects().keySet(); Set<String> otherObjectClassnames = doc.getxWikiObjects().keySet(); if (!myObjectClassnames.equals(otherObjectClassnames)) { return false; } for (String name : myObjectClassnames) { Vector<BaseObject> myObjects = getObjects(name); Vector<BaseObject> otherObjects = doc.getObjects(name); if (myObjects.size() != otherObjects.size()) { return false; } for (int i = 0; i < myObjects.size(); i++) { if ((myObjects.get(i) == null) && (otherObjects.get(i) != null)) { return false; } if (!myObjects.get(i).equals(otherObjects.get(i))) { return false; } } } // We consider that 2 documents are still equal even when they have different original // documents (see getOriginalDocument() for more details as to what is an original // document). return true; } public String toXML(Document doc, XWikiContext context) { OutputFormat outputFormat = new OutputFormat("", true); if ((context == null) || (context.getWiki() == null)) { outputFormat.setEncoding("UTF-8"); } else { outputFormat.setEncoding(context.getWiki().getEncoding()); } StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, outputFormat); try { writer.write(doc); return out.toString(); } catch (IOException e) { e.printStackTrace(); return ""; } } public String getXMLContent(XWikiContext context) throws XWikiException { XWikiDocument tdoc = getTranslatedDocument(context); Document doc = tdoc.toXMLDocument(true, true, false, false, context); return toXML(doc, context); } public String toXML(XWikiContext context) throws XWikiException { Document doc = toXMLDocument(context); return toXML(doc, context); } public String toFullXML(XWikiContext context) throws XWikiException { return toXML(true, false, true, true, context); } public void addToZip(ZipOutputStream zos, boolean withVersions, XWikiContext context) throws IOException { try { String zipname = getSpace() + "/" + getName(); String language = getLanguage(); if ((language != null) && (!language.equals(""))) { zipname += "." + language; } ZipEntry zipentry = new ZipEntry(zipname); zos.putNextEntry(zipentry); zos.write(toXML(true, false, true, withVersions, context).getBytes()); zos.closeEntry(); } catch (Exception e) { e.printStackTrace(); } } public void addToZip(ZipOutputStream zos, XWikiContext context) throws IOException { addToZip(zos, true, context); } public String toXML(boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent, boolean bWithVersions, XWikiContext context) throws XWikiException { Document doc = toXMLDocument(bWithObjects, bWithRendering, bWithAttachmentContent, bWithVersions, context); return toXML(doc, context); } public Document toXMLDocument(XWikiContext context) throws XWikiException { return toXMLDocument(true, false, false, false, context); } public Document toXMLDocument(boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent, boolean bWithVersions, XWikiContext context) throws XWikiException { Document doc = new DOMDocument(); Element docel = new DOMElement("xwikidoc"); doc.setRootElement(docel); Element el = new DOMElement("web"); el.addText(getSpace()); docel.add(el); el = new DOMElement("name"); el.addText(getName()); docel.add(el); el = new DOMElement("language"); el.addText(getLanguage()); docel.add(el); el = new DOMElement("defaultLanguage"); el.addText(getDefaultLanguage()); docel.add(el); el = new DOMElement("translation"); el.addText("" + getTranslation()); docel.add(el); el = new DOMElement("parent"); el.addText(getParent()); docel.add(el); el = new DOMElement("creator"); el.addText(getCreator()); docel.add(el); el = new DOMElement("author"); el.addText(getAuthor()); docel.add(el); el = new DOMElement("customClass"); el.addText(getCustomClass()); docel.add(el); el = new DOMElement("contentAuthor"); el.addText(getContentAuthor()); docel.add(el); long d = getCreationDate().getTime(); el = new DOMElement("creationDate"); el.addText("" + d); docel.add(el); d = getDate().getTime(); el = new DOMElement("date"); el.addText("" + d); docel.add(el); d = getContentUpdateDate().getTime(); el = new DOMElement("contentUpdateDate"); el.addText("" + d); docel.add(el); el = new DOMElement("version"); el.addText(getVersion()); docel.add(el); el = new DOMElement("title"); el.addText(getTitle()); docel.add(el); el = new DOMElement("template"); el.addText(getTemplate()); docel.add(el); el = new DOMElement("defaultTemplate"); el.addText(getDefaultTemplate()); docel.add(el); el = new DOMElement("validationScript"); el.addText(getValidationScript()); docel.add(el); el = new DOMElement("comment"); el.addText(getComment()); docel.add(el); el = new DOMElement("minorEdit"); el.addText(String.valueOf(isMinorEdit())); docel.add(el); el = new DOMElement("syntaxId"); el.addText(getSyntaxId()); docel.add(el); for (XWikiAttachment attach : getAttachmentList()) { docel.add(attach.toXML(bWithAttachmentContent, bWithVersions, context)); } if (bWithObjects) { // Add Class BaseClass bclass = getxWikiClass(); if (bclass.getFieldList().size() > 0) { // If the class has fields, add class definition and field information to XML docel.add(bclass.toXML(null)); } // Add Objects (THEIR ORDER IS MOLDED IN STONE!) for (Vector<BaseObject> objects : getxWikiObjects().values()) { for (BaseObject obj : objects) { if (obj != null) { BaseClass objclass = null; if (obj.getName().equals(obj.getClassName())) { objclass = bclass; } else { objclass = obj.getxWikiClass(context); } docel.add(obj.toXML(objclass)); } } } } // Add Content el = new DOMElement("content"); // Filter filter = new CharacterFilter(); // String newcontent = filter.process(getContent()); // String newcontent = encodedXMLStringAsUTF8(getContent()); String newcontent = this.content; el.addText(newcontent); docel.add(el); if (bWithRendering) { el = new DOMElement("renderedcontent"); try { el.addText(getRenderedContent(context)); } catch (XWikiException e) { el.addText("Exception with rendering content: " + e.getFullMessage()); } docel.add(el); } if (bWithVersions) { el = new DOMElement("versions"); try { el.addText(getDocumentArchive(context).getArchive(context)); docel.add(el); } catch (XWikiException e) { log.error("Document [" + this.getFullName() + "] has malformed history"); } } return doc; } protected String encodedXMLStringAsUTF8(String xmlString) { if (xmlString == null) { return ""; } int length = xmlString.length(); char character; StringBuffer result = new StringBuffer(); for (int i = 0; i < length; i++) { character = xmlString.charAt(i); switch (character) { case '&': result.append("&amp;"); break; case '"': result.append("&quot;"); break; case '<': result.append("&lt;"); break; case '>': result.append("&gt;"); break; case '\n': result.append("\n"); break; case '\r': result.append("\r"); break; case '\t': result.append("\t"); break; default: if (character < 0x20) { } else if (character > 0x7F) { result.append("&#x"); result.append(Integer.toHexString(character).toUpperCase()); result.append(";"); } else { result.append(character); } break; } } return result.toString(); } protected String getElement(Element docel, String name) { Element el = docel.element(name); if (el == null) { return ""; } else { return el.getText(); } } public void fromXML(String xml) throws XWikiException { fromXML(xml, false); } public void fromXML(InputStream is) throws XWikiException { fromXML(is, false); } public void fromXML(String xml, boolean withArchive) throws XWikiException { SAXReader reader = new SAXReader(); Document domdoc; try { StringReader in = new StringReader(xml); domdoc = reader.read(in); } catch (DocumentException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null); } fromXML(domdoc, withArchive); } public void fromXML(InputStream in, boolean withArchive) throws XWikiException { SAXReader reader = new SAXReader(); Document domdoc; try { domdoc = reader.read(in); } catch (DocumentException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null); } fromXML(domdoc, withArchive); } public void fromXML(Document domdoc, boolean withArchive) throws XWikiException { Element docel = domdoc.getRootElement(); setName(getElement(docel, "name")); setSpace(getElement(docel, "web")); setParent(getElement(docel, "parent")); setCreator(getElement(docel, "creator")); setAuthor(getElement(docel, "author")); setCustomClass(getElement(docel, "customClass")); setContentAuthor(getElement(docel, "contentAuthor")); if (docel.element("version") != null) { setVersion(getElement(docel, "version")); } setContent(getElement(docel, "content")); setLanguage(getElement(docel, "language")); setDefaultLanguage(getElement(docel, "defaultLanguage")); setTitle(getElement(docel, "title")); setDefaultTemplate(getElement(docel, "defaultTemplate")); setValidationScript(getElement(docel, "validationScript")); setComment(getElement(docel, "comment")); String minorEdit = getElement(docel, "minorEdit"); setMinorEdit(Boolean.valueOf(minorEdit).booleanValue()); String strans = getElement(docel, "translation"); if ((strans == null) || strans.equals("")) { setTranslation(0); } else { setTranslation(Integer.parseInt(strans)); } String archive = getElement(docel, "versions"); if (withArchive && archive != null && archive.length() > 0) { setDocumentArchive(archive); } String sdate = getElement(docel, "date"); if (!sdate.equals("")) { Date date = new Date(Long.parseLong(sdate)); setDate(date); } String scdate = getElement(docel, "creationDate"); if (!scdate.equals("")) { Date cdate = new Date(Long.parseLong(scdate)); setCreationDate(cdate); } String syntaxId = getElement(docel, "syntaxId"); if ((syntaxId == null) || (syntaxId.length() == 0)) { setSyntaxId("xwiki/1.0"); } else { setSyntaxId(syntaxId); } List atels = docel.elements("attachment"); for (int i = 0; i < atels.size(); i++) { Element atel = (Element) atels.get(i); XWikiAttachment attach = new XWikiAttachment(); attach.setDoc(this); attach.fromXML(atel); getAttachmentList().add(attach); } Element cel = docel.element("class"); BaseClass bclass = new BaseClass(); if (cel != null) { bclass.fromXML(cel); setxWikiClass(bclass); } List objels = docel.elements("object"); for (int i = 0; i < objels.size(); i++) { Element objel = (Element) objels.get(i); BaseObject bobject = new BaseObject(); bobject.fromXML(objel); addObject(bobject.getClassName(), bobject); } // We have been reading from XML so the document does not need a new version when saved setMetaDataDirty(false); setContentDirty(false); // Note: We don't set the original document as that is not stored in the XML, and it doesn't make much sense to // have an original document for a de-serialized object. } /** * Check if provided xml document is a wiki document. * * @param domdoc the xml document. * @return true if provided xml document is a wiki document. */ public static boolean containsXMLWikiDocument(Document domdoc) { return domdoc.getRootElement().getName().equals("xwikidoc"); } public void setAttachmentList(List<XWikiAttachment> list) { this.attachmentList = list; } public List<XWikiAttachment> getAttachmentList() { return this.attachmentList; } public void saveAllAttachments(XWikiContext context) throws XWikiException { for (int i = 0; i < this.attachmentList.size(); i++) { saveAttachmentContent(this.attachmentList.get(i), context); } } public void saveAllAttachments(boolean updateParent, boolean transaction, XWikiContext context) throws XWikiException { for (int i = 0; i < this.attachmentList.size(); i++) { saveAttachmentContent(this.attachmentList.get(i), updateParent, transaction, context); } } public void saveAttachmentsContent(List<XWikiAttachment> attachments, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } context.getWiki().getAttachmentStore().saveAttachmentsContent(attachments, this, true, context, true); } catch (java.lang.OutOfMemoryError e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception"); } finally { if (database != null) { context.setDatabase(database); } } } public void saveAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException { saveAttachmentContent(attachment, true, true, context); } protected void saveAttachmentContent(XWikiAttachment attachment, boolean bParentUpdate, boolean bTransaction, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } // We need to make sure there is a version upgrade setMetaDataDirty(true); context.getWiki().getAttachmentStore().saveAttachmentContent(attachment, bParentUpdate, context, bTransaction); } catch (java.lang.OutOfMemoryError e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception"); } finally { if (database != null) { context.setDatabase(database); } } } public void loadAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } context.getWiki().getAttachmentStore().loadAttachmentContent(attachment, context, true); } finally { if (database != null) { context.setDatabase(database); } } } public void deleteAttachment(XWikiAttachment attachment, XWikiContext context) throws XWikiException { deleteAttachment(attachment, true, context); } public void deleteAttachment(XWikiAttachment attachment, boolean toRecycleBin, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } try { // We need to make sure there is a version upgrade setMetaDataDirty(true); if (toRecycleBin && context.getWiki().hasAttachmentRecycleBin(context)) { context.getWiki().getAttachmentRecycleBinStore().saveToRecycleBin(attachment, context.getUser(), new Date(), context, true); } context.getWiki().getAttachmentStore().deleteXWikiAttachment(attachment, context, true); } catch (java.lang.OutOfMemoryError e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception"); } } finally { if (database != null) { context.setDatabase(database); } } } public List getBacklinks(XWikiContext context) throws XWikiException { return getStore(context).loadBacklinks(getFullName(), context, true); } public List getLinks(XWikiContext context) throws XWikiException { return getStore(context).loadLinks(getId(), context, true); } public void renameProperties(String className, Map fieldsToRename) { Vector<BaseObject> objects = getObjects(className); if (objects == null) { return; } for (BaseObject bobject : objects) { if (bobject == null) { continue; } for (Iterator renameit = fieldsToRename.keySet().iterator(); renameit.hasNext();) { String origname = (String) renameit.next(); String newname = (String) fieldsToRename.get(origname); BaseProperty origprop = (BaseProperty) bobject.safeget(origname); if (origprop != null) { BaseProperty prop = (BaseProperty) origprop.clone(); bobject.removeField(origname); prop.setName(newname); bobject.addField(newname, prop); } } } setContentDirty(true); } public void addObjectsToRemove(BaseObject object) { getObjectsToRemove().add(object); setContentDirty(true); } public ArrayList<BaseObject> getObjectsToRemove() { return this.objectsToRemove; } public void setObjectsToRemove(ArrayList<BaseObject> objectsToRemove) { this.objectsToRemove = objectsToRemove; setContentDirty(true); } public List<String> getIncludedPages(XWikiContext context) { try { String pattern = "#include(Topic|InContext|Form|Macros|parseGroovyFromPage)\\([\"'](.*?)[\"']\\)"; List<String> list = context.getUtil().getUniqueMatches(getContent(), pattern, 2); for (int i = 0; i < list.size(); i++) { try { String name = list.get(i); if (name.indexOf(".") == -1) { list.set(i, getSpace() + "." + name); } } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } return list; } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } public List<String> getIncludedMacros(XWikiContext context) { return context.getWiki().getIncludedMacros(getSpace(), getContent(), context); } public List<String> getLinkedPages(XWikiContext context) { try { String pattern = "\\[(.*?)\\]"; List<String> newlist = new ArrayList<String>(); List<String> list = context.getUtil().getUniqueMatches(getContent(), pattern, 1); for (String name : list) { try { int i1 = name.indexOf(">"); if (i1 != -1) { name = name.substring(i1 + 1); } i1 = name.indexOf("&gt;"); if (i1 != -1) { name = name.substring(i1 + 4); } i1 = name.indexOf("#"); if (i1 != -1) { name = name.substring(0, i1); } i1 = name.indexOf("?"); if (i1 != -1) { name = name.substring(0, i1); } // Let's get rid of anything that's not a real link if (name.trim().equals("") || (name.indexOf("$") != -1) || (name.indexOf("://") != -1) || (name.indexOf("\"") != -1) || (name.indexOf("\'") != -1) || (name.indexOf("..") != -1) || (name.indexOf(":") != -1) || (name.indexOf("=") != -1)) { continue; } // generate the link String newname = StringUtils.replace(Util.noaccents(name), " ", ""); // If it is a local link let's add the space if (newname.indexOf(".") == -1) { newname = getSpace() + "." + name; } if (context.getWiki().exists(newname, context)) { name = newname; } else { // If it is a local link let's add the space if (name.indexOf(".") == -1) { name = getSpace() + "." + name; } } // Let's finally ignore the autolinks if (!name.equals(getFullName())) { newlist.add(name); } } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } return newlist; } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } public String displayRendered(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) throws XWikiException { String result = pclass.displayView(pclass.getName(), prefix, object, context); return getRenderedContent(result, context); } public String displayView(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) { return (pclass == null) ? "" : pclass.displayView(pclass.getName(), prefix, object, context); } public String displayEdit(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) { return (pclass == null) ? "" : pclass.displayEdit(pclass.getName(), prefix, object, context); } public String displayHidden(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) { return (pclass == null) ? "" : pclass.displayHidden(pclass.getName(), prefix, object, context); } public String displaySearch(PropertyClass pclass, String prefix, XWikiCriteria criteria, XWikiContext context) { return (pclass == null) ? "" : pclass.displaySearch(pclass.getName(), prefix, criteria, context); } public XWikiAttachment getAttachment(String filename) { for (XWikiAttachment attach : getAttachmentList()) { if (attach.getFilename().equals(filename)) { return attach; } } for (XWikiAttachment attach : getAttachmentList()) { if (attach.getFilename().startsWith(filename + ".")) { return attach; } } return null; } public BaseObject getFirstObject(String fieldname) { // Keeping this function with context null for compatibilit reasons // It should not be used, since it would miss properties which are only defined in the class // and not present in the object because the object was not updated return getFirstObject(fieldname, null); } public BaseObject getFirstObject(String fieldname, XWikiContext context) { Collection<Vector<BaseObject>> objectscoll = getxWikiObjects().values(); if (objectscoll == null) { return null; } for (Vector<BaseObject> objects : objectscoll) { for (BaseObject obj : objects) { if (obj != null) { BaseClass bclass = obj.getxWikiClass(context); if (bclass != null) { Set set = bclass.getPropertyList(); if ((set != null) && set.contains(fieldname)) { return obj; } } Set set = obj.getPropertyList(); if ((set != null) && set.contains(fieldname)) { return obj; } } } } return null; } public void setProperty(String className, String fieldName, BaseProperty value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.safeput(fieldName, value); setContentDirty(true); } public int getIntValue(String className, String fieldName) { BaseObject obj = getObject(className, 0); if (obj == null) { return 0; } return obj.getIntValue(fieldName); } public long getLongValue(String className, String fieldName) { BaseObject obj = getObject(className, 0); if (obj == null) { return 0; } return obj.getLongValue(fieldName); } public String getStringValue(String className, String fieldName) { BaseObject obj = getObject(className); if (obj == null) { return ""; } String result = obj.getStringValue(fieldName); if (result.equals(" ")) { return ""; } else { return result; } } public int getIntValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return 0; } else { return object.getIntValue(fieldName); } } public long getLongValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return 0; } else { return object.getLongValue(fieldName); } } public String getStringValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return ""; } String result = object.getStringValue(fieldName); if (result.equals(" ")) { return ""; } else { return result; } } public void setStringValue(String className, String fieldName, String value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setStringValue(fieldName, value); setContentDirty(true); } public List getListValue(String className, String fieldName) { BaseObject obj = getObject(className); if (obj == null) { return new ArrayList(); } return obj.getListValue(fieldName); } public List getListValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return new ArrayList(); } return object.getListValue(fieldName); } public void setStringListValue(String className, String fieldName, List value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setStringListValue(fieldName, value); setContentDirty(true); } public void setDBStringListValue(String className, String fieldName, List value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setDBStringListValue(fieldName, value); setContentDirty(true); } public void setLargeStringValue(String className, String fieldName, String value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setLargeStringValue(fieldName, value); setContentDirty(true); } public void setIntValue(String className, String fieldName, int value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setIntValue(fieldName, value); setContentDirty(true); } public String getDatabase() { return this.database; } public void setDatabase(String database) { this.database = database; } public void setFullName(String fullname, XWikiContext context) { if (fullname == null) { return; } int i0 = fullname.lastIndexOf(":"); int i1 = fullname.lastIndexOf("."); if (i0 != -1) { setDatabase(fullname.substring(0, i0)); setSpace(fullname.substring(i0 + 1, i1)); setName(fullname.substring(i1 + 1)); } else { if (i1 == -1) { try { setSpace(context.getDoc().getSpace()); } catch (Exception e) { setSpace("XWiki"); } setName(fullname); } else { setSpace(fullname.substring(0, i1)); setName(fullname.substring(i1 + 1)); } } if (getName().equals("")) { setName("WebHome"); } setContentDirty(true); } public String getLanguage() { if (this.language == null) { return ""; } else { return this.language.trim(); } } public void setLanguage(String language) { this.language = language; } public String getDefaultLanguage() { if (this.defaultLanguage == null) { return ""; } else { return this.defaultLanguage.trim(); } } public void setDefaultLanguage(String defaultLanguage) { this.defaultLanguage = defaultLanguage; setMetaDataDirty(true); } public int getTranslation() { return this.translation; } public void setTranslation(int translation) { this.translation = translation; setMetaDataDirty(true); } public String getTranslatedContent(XWikiContext context) throws XWikiException { String language = context.getWiki().getLanguagePreference(context); return getTranslatedContent(language, context); } public String getTranslatedContent(String language, XWikiContext context) throws XWikiException { XWikiDocument tdoc = getTranslatedDocument(language, context); String rev = (String) context.get("rev"); if ((rev == null) || (rev.length() == 0)) { return tdoc.getContent(); } XWikiDocument cdoc = context.getWiki().getDocument(tdoc, rev, context); return cdoc.getContent(); } public XWikiDocument getTranslatedDocument(XWikiContext context) throws XWikiException { String language = context.getWiki().getLanguagePreference(context); return getTranslatedDocument(language, context); } public XWikiDocument getTranslatedDocument(String language, XWikiContext context) throws XWikiException { XWikiDocument tdoc = this; if (!((language == null) || (language.equals("")) || language.equals(this.defaultLanguage))) { tdoc = new XWikiDocument(getSpace(), getName()); tdoc.setLanguage(language); String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } tdoc = getStore(context).loadXWikiDoc(tdoc, context); if (tdoc.isNew()) { tdoc = this; } } catch (Exception e) { tdoc = this; } finally { context.setDatabase(database); } } return tdoc; } public String getRealLanguage(XWikiContext context) throws XWikiException { String lang = getLanguage(); if ((lang.equals("") || lang.equals("default"))) { return getDefaultLanguage(); } else { return lang; } } public String getRealLanguage() { String lang = getLanguage(); if ((lang.equals("") || lang.equals("default"))) { return getDefaultLanguage(); } else { return lang; } } public List<String> getTranslationList(XWikiContext context) throws XWikiException { return getStore().getTranslationList(this, context); } public List<Delta> getXMLDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException, DifferentiationFailedException { return getDeltas(Diff.diff(ToString.stringToArray(fromDoc.toXML(context)), ToString.stringToArray(toDoc .toXML(context)))); } public List<Delta> getContentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException, DifferentiationFailedException { return getDeltas(Diff.diff(ToString.stringToArray(fromDoc.getContent()), ToString.stringToArray(toDoc .getContent()))); } public List<Delta> getContentDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getContentDiff(fromDoc, toDoc, context); } public List<Delta> getContentDiff(String fromRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getContentDiff(revdoc, this, context); } public List<Delta> getLastChanges(XWikiContext context) throws XWikiException, DifferentiationFailedException { Version version = getRCSVersion(); try { String prev = getDocumentArchive(context).getPrevVersion(version).toString(); XWikiDocument prevDoc = context.getWiki().getDocument(this, prev, context); return getDeltas(Diff.diff(ToString.stringToArray(prevDoc.getContent()), ToString .stringToArray(getContent()))); } catch (Exception ex) { log.debug("Exception getting differences from previous version: " + ex.getMessage()); } return new ArrayList<Delta>(); } public List<Delta> getRenderedContentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException, DifferentiationFailedException { String originalContent, newContent; originalContent = context.getWiki().getRenderingEngine().renderText(fromDoc.getContent(), fromDoc, context); newContent = context.getWiki().getRenderingEngine().renderText(toDoc.getContent(), toDoc, context); return getDeltas(Diff.diff(ToString.stringToArray(originalContent), ToString.stringToArray(newContent))); } public List<Delta> getRenderedContentDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getRenderedContentDiff(fromDoc, toDoc, context); } public List<Delta> getRenderedContentDiff(String fromRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getRenderedContentDiff(revdoc, this, context); } protected List<Delta> getDeltas(Revision rev) { List<Delta> list = new ArrayList<Delta>(); for (int i = 0; i < rev.size(); i++) { list.add(rev.getDelta(i)); } return list; } public List<MetaDataDiff> getMetaDataDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getMetaDataDiff(fromDoc, toDoc, context); } public List<MetaDataDiff> getMetaDataDiff(String fromRev, XWikiContext context) throws XWikiException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getMetaDataDiff(revdoc, this, context); } public List<MetaDataDiff> getMetaDataDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { List<MetaDataDiff> list = new ArrayList<MetaDataDiff>(); if ((fromDoc == null) || (toDoc == null)) { return list; } if (!fromDoc.getParent().equals(toDoc.getParent())) { list.add(new MetaDataDiff("parent", fromDoc.getParent(), toDoc.getParent())); } if (!fromDoc.getAuthor().equals(toDoc.getAuthor())) { list.add(new MetaDataDiff("author", fromDoc.getAuthor(), toDoc.getAuthor())); } if (!fromDoc.getSpace().equals(toDoc.getSpace())) { list.add(new MetaDataDiff("web", fromDoc.getSpace(), toDoc.getSpace())); } if (!fromDoc.getName().equals(toDoc.getName())) { list.add(new MetaDataDiff("name", fromDoc.getName(), toDoc.getName())); } if (!fromDoc.getLanguage().equals(toDoc.getLanguage())) { list.add(new MetaDataDiff("language", fromDoc.getLanguage(), toDoc.getLanguage())); } if (!fromDoc.getDefaultLanguage().equals(toDoc.getDefaultLanguage())) { list.add(new MetaDataDiff("defaultLanguage", fromDoc.getDefaultLanguage(), toDoc.getDefaultLanguage())); } return list; } public List<List<ObjectDiff>> getObjectDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getObjectDiff(fromDoc, toDoc, context); } public List<List<ObjectDiff>> getObjectDiff(String fromRev, XWikiContext context) throws XWikiException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getObjectDiff(revdoc, this, context); } /** * Return the object differences between two document versions. There is no hard requirement on the order of the two * versions, but the results are semantically correct only if the two versions are given in the right order. * * @param fromDoc The old ('before') version of the document. * @param toDoc The new ('after') version of the document. * @param context The {@link com.xpn.xwiki.XWikiContext context}. * @return The object differences. The returned list's elements are other lists, one for each changed object. The * inner lists contain {@link ObjectDiff} elements, one object for each changed property of the object. * Additionally, if the object was added or removed, then the first entry in the list will be an * "object-added" or "object-removed" marker. * @throws XWikiException If there's an error computing the differences. */ public List<List<ObjectDiff>> getObjectDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { ArrayList<List<ObjectDiff>> difflist = new ArrayList<List<ObjectDiff>>(); // Since objects could have been deleted or added, we iterate on both the old and the new // object collections. // First, iterate over the old objects. for (Vector<BaseObject> objects : fromDoc.getxWikiObjects().values()) { for (BaseObject originalObj : objects) { // This happens when objects are deleted, and the document is still in the cache // storage. if (originalObj != null) { BaseObject newObj = toDoc.getObject(originalObj.getClassName(), originalObj.getNumber()); List<ObjectDiff> dlist; if (newObj == null) { // The object was deleted. dlist = new BaseObject().getDiff(originalObj, context); ObjectDiff deleteMarker = new ObjectDiff(originalObj.getClassName(), originalObj.getNumber(), "object-removed", "", "", ""); dlist.add(0, deleteMarker); } else { // The object exists in both versions, but might have been changed. dlist = newObj.getDiff(originalObj, context); } if (dlist.size() > 0) { difflist.add(dlist); } } } } // Second, iterate over the objects which are only in the new version. for (Vector<BaseObject> objects : toDoc.getxWikiObjects().values()) { for (BaseObject newObj : objects) { // This happens when objects are deleted, and the document is still in the cache // storage. if (newObj != null) { BaseObject originalObj = fromDoc.getObject(newObj.getClassName(), newObj.getNumber()); if (originalObj == null) { // Only consider added objects, the other case was treated above. originalObj = new BaseObject(); originalObj.setClassName(newObj.getClassName()); originalObj.setNumber(newObj.getNumber()); List<ObjectDiff> dlist = newObj.getDiff(originalObj, context); ObjectDiff addMarker = new ObjectDiff(newObj.getClassName(), newObj.getNumber(), "object-added", "", "", ""); dlist.add(0, addMarker); if (dlist.size() > 0) { difflist.add(dlist); } } } } } return difflist; } public List<List<ObjectDiff>> getClassDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { ArrayList<List<ObjectDiff>> difflist = new ArrayList<List<ObjectDiff>>(); BaseClass oldClass = fromDoc.getxWikiClass(); BaseClass newClass = toDoc.getxWikiClass(); if ((newClass == null) && (oldClass == null)) { return difflist; } List<ObjectDiff> dlist = newClass.getDiff(oldClass, context); if (dlist.size() > 0) { difflist.add(dlist); } return difflist; } /** * @param fromDoc * @param toDoc * @param context * @return * @throws XWikiException */ public List<AttachmentDiff> getAttachmentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { List<AttachmentDiff> difflist = new ArrayList<AttachmentDiff>(); for (XWikiAttachment origAttach : fromDoc.getAttachmentList()) { String fileName = origAttach.getFilename(); XWikiAttachment newAttach = toDoc.getAttachment(fileName); if (newAttach == null) { difflist.add(new AttachmentDiff(fileName, origAttach.getVersion(), null)); } else { if (!origAttach.getVersion().equals(newAttach.getVersion())) { difflist.add(new AttachmentDiff(fileName, origAttach.getVersion(), newAttach.getVersion())); } } } for (XWikiAttachment newAttach : toDoc.getAttachmentList()) { String fileName = newAttach.getFilename(); XWikiAttachment origAttach = fromDoc.getAttachment(fileName); if (origAttach == null) { difflist.add(new AttachmentDiff(fileName, null, newAttach.getVersion())); } } return difflist; } /** * Rename the current document and all the backlinks leading to it. See * {@link #rename(String, java.util.List, com.xpn.xwiki.XWikiContext)} for more details. * * @param newDocumentName the new document name. If the space is not specified then defaults to the current space. * @param context the ubiquitous XWiki Context * @throws XWikiException in case of an error */ public void rename(String newDocumentName, XWikiContext context) throws XWikiException { rename(newDocumentName, getBacklinks(context), context); } /** * Rename the current document and all the links pointing to it in the list of passed backlink documents. The * renaming algorithm takes into account the fact that there are several ways to write a link to a given page and * all those forms need to be renamed. For example the following links all point to the same page: * <ul> * <li>[Page]</li> * <li>[Page?param=1]</li> * <li>[currentwiki:Page]</li> * <li>[CurrentSpace.Page]</li> * </ul> * <p> * Note: links without a space are renamed with the space added. * </p> * * @param newDocumentName the new document name. If the space is not specified then defaults to the current space. * @param backlinkDocumentNames the list of documents to parse and for which links will be modified to point to the * new renamed document. * @param context the ubiquitous XWiki Context * @throws XWikiException in case of an error */ public void rename(String newDocumentName, List<String> backlinkDocumentNames, XWikiContext context) throws XWikiException { // TODO: Do all this in a single DB transaction as otherwise the state will be unknown if // something fails in the middle... if (isNew()) { return; } // This link handler recognizes that 2 links are the same when they point to the same // document (regardless of query string, target or alias). It keeps the query string, // target and alias from the link being replaced. RenamePageReplaceLinkHandler linkHandler = new RenamePageReplaceLinkHandler(); // Transform string representation of old and new links so that they can be manipulated. Link oldLink = new LinkParser().parse(getFullName()); Link newLink = new LinkParser().parse(newDocumentName); // Verify if the user is trying to rename to the same name... In that case, simply exits // for efficiency. if (linkHandler.compare(newLink, oldLink)) { return; } // Step 1: Copy the document under a new name context.getWiki().copyDocument(getFullName(), newDocumentName, false, context); // Step 2: For each backlink to rename, parse the backlink document and replace the links // with the new name. // Note: we ignore invalid links here. Invalid links should be shown to the user so // that they fix them but the rename feature ignores them. DocumentParser documentParser = new DocumentParser(); for (String backlinkDocumentName : backlinkDocumentNames) { XWikiDocument backlinkDocument = context.getWiki().getDocument(backlinkDocumentName, context); // Note: Here we cannot do a simple search/replace as there are several ways to point // to the same document. For example [Page], [Page?param=1], [currentwiki:Page], // [CurrentSpace.Page] all point to the same document. Thus we have to parse the links // to recognize them and do the replace. ReplacementResultCollection result = documentParser.parseLinksAndReplace(backlinkDocument.getContent(), oldLink, newLink, linkHandler, getSpace()); backlinkDocument.setContent((String) result.getModifiedContent()); context.getWiki().saveDocument(backlinkDocument, context.getMessageTool().get("core.comment.renameLink", Arrays.asList(new String[] {newDocumentName})), true, context); } // Step 3: Delete the old document context.getWiki().deleteDocument(this, context); // Step 4: The current document needs to point to the renamed document as otherwise it's // pointing to an invalid XWikiDocument object as it's been deleted... clone(context.getWiki().getDocument(newDocumentName, context)); } public XWikiDocument copyDocument(String newDocumentName, XWikiContext context) throws XWikiException { String oldname = getFullName(); loadAttachments(context); loadArchive(context); /* * if (oldname.equals(docname)) return this; */ XWikiDocument newdoc = (XWikiDocument) clone(); newdoc.setFullName(newDocumentName, context); newdoc.setContentDirty(true); newdoc.getxWikiClass().setName(newDocumentName); Vector<BaseObject> objects = newdoc.getObjects(oldname); if (objects != null) { for (BaseObject object : objects) { object.setName(newDocumentName); } } XWikiDocumentArchive archive = newdoc.getDocumentArchive(); if (archive != null) { newdoc.setDocumentArchive(archive.clone(newdoc.getId(), context)); } return newdoc; } public XWikiLock getLock(XWikiContext context) throws XWikiException { XWikiLock theLock = getStore(context).loadLock(getId(), context, true); if (theLock != null) { int timeout = context.getWiki().getXWikiPreferenceAsInt("lock_Timeout", 30 * 60, context); if (theLock.getDate().getTime() + timeout * 1000 < new Date().getTime()) { getStore(context).deleteLock(theLock, context, true); theLock = null; } } return theLock; } public void setLock(String userName, XWikiContext context) throws XWikiException { XWikiLock lock = new XWikiLock(getId(), userName); getStore(context).saveLock(lock, context, true); } public void removeLock(XWikiContext context) throws XWikiException { XWikiLock lock = getStore(context).loadLock(getId(), context, true); if (lock != null) { getStore(context).deleteLock(lock, context, true); } } public void insertText(String text, String marker, XWikiContext context) throws XWikiException { setContent(StringUtils.replaceOnce(getContent(), marker, text + marker)); context.getWiki().saveDocument(this, context); } public Object getWikiNode() { return this.wikiNode; } public void setWikiNode(Object wikiNode) { this.wikiNode = wikiNode; } public String getxWikiClassXML() { return this.xWikiClassXML; } public void setxWikiClassXML(String xWikiClassXML) { this.xWikiClassXML = xWikiClassXML; } public int getElements() { return this.elements; } public void setElements(int elements) { this.elements = elements; } public void setElement(int element, boolean toggle) { if (toggle) { this.elements = this.elements | element; } else { this.elements = this.elements & (~element); } } public boolean hasElement(int element) { return ((this.elements & element) == element); } public String getDefaultEditURL(XWikiContext context) throws XWikiException { com.xpn.xwiki.XWiki xwiki = context.getWiki(); if (getContent().indexOf("includeForm(") != -1) { return getEditURL("inline", "", context); } else { String editor = xwiki.getEditorPreference(context); return getEditURL("edit", editor, context); } } public String getEditURL(String action, String mode, XWikiContext context) throws XWikiException { com.xpn.xwiki.XWiki xwiki = context.getWiki(); String language = ""; XWikiDocument tdoc = (XWikiDocument) context.get("tdoc"); String realLang = tdoc.getRealLanguage(context); if ((xwiki.isMultiLingual(context) == true) && (!realLang.equals(""))) { language = realLang; } return getEditURL(action, mode, language, context); } public String getEditURL(String action, String mode, String language, XWikiContext context) { StringBuffer editparams = new StringBuffer(); if (!mode.equals("")) { editparams.append("xpage="); editparams.append(mode); } if (!language.equals("")) { if (!mode.equals("")) { editparams.append("&"); } editparams.append("language="); editparams.append(language); } return getURL(action, editparams.toString(), context); } public String getDefaultTemplate() { if (this.defaultTemplate == null) { return ""; } else { return this.defaultTemplate; } } public void setDefaultTemplate(String defaultTemplate) { this.defaultTemplate = defaultTemplate; setMetaDataDirty(true); } public Vector<BaseObject> getComments() { return getComments(true); } /** * @return the Syntax id representing the syntax used for the current document. For example "xwiki/1.0" represents * the first version XWiki syntax while "xwiki/2.0" represents version 2.0 of the XWiki Syntax. */ public String getSyntaxId() { String result; if ((this.syntaxId == null) || (this.syntaxId.length() == 0)) { result = "xwiki/1.0"; } else { result = this.syntaxId; } return result; } /** * @param syntaxId the new syntax id to set (eg "xwiki/1.0", "xwiki/2.0", etc) * @see #getSyntaxId() */ public void setSyntaxId(String syntaxId) { this.syntaxId = syntaxId; } public Vector<BaseObject> getComments(boolean asc) { if (asc) { return getObjects("XWiki.XWikiComments"); } else { Vector<BaseObject> list = getObjects("XWiki.XWikiComments"); if (list == null) { return list; } Vector<BaseObject> newlist = new Vector<BaseObject>(); for (int i = list.size() - 1; i >= 0; i--) { newlist.add(list.get(i)); } return newlist; } } public boolean isCurrentUserCreator(XWikiContext context) { return isCreator(context.getUser()); } public boolean isCreator(String username) { if (username.equals("XWiki.XWikiGuest")) { return false; } return username.equals(getCreator()); } public boolean isCurrentUserPage(XWikiContext context) { String username = context.getUser(); if (username.equals("XWiki.XWikiGuest")) { return false; } return context.getUser().equals(getFullName()); } public boolean isCurrentLocalUserPage(XWikiContext context) { String username = context.getLocalUser(); if (username.equals("XWiki.XWikiGuest")) { return false; } return context.getUser().equals(getFullName()); } public void resetArchive(XWikiContext context) throws XWikiException { boolean hasVersioning = context.getWiki().hasVersioning(getFullName(), context); if (hasVersioning) { getVersioningStore(context).resetRCSArchive(this, true, context); } } // This functions adds an object from an new object creation form public BaseObject addObjectFromRequest(XWikiContext context) throws XWikiException { // Read info in object ObjectAddForm form = new ObjectAddForm(); form.setRequest((HttpServletRequest) context.getRequest()); form.readRequest(); String className = form.getClassName(); int nb = createNewObject(className, context); BaseObject oldobject = getObject(className, nb); BaseClass baseclass = oldobject.getxWikiClass(context); BaseObject newobject = (BaseObject) baseclass.fromMap(form.getObject(className), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setName(getFullName()); setObject(className, nb, newobject); return newobject; } // This functions adds an object from an new object creation form public BaseObject addObjectFromRequest(String className, XWikiContext context) throws XWikiException { return addObjectFromRequest(className, "", 0, context); } // This functions adds an object from an new object creation form public BaseObject addObjectFromRequest(String className, String prefix, XWikiContext context) throws XWikiException { return addObjectFromRequest(className, prefix, 0, context); } // This functions adds multiple objects from an new objects creation form public List<BaseObject> addObjectsFromRequest(String className, XWikiContext context) throws XWikiException { return addObjectsFromRequest(className, "", context); } // This functions adds multiple objects from an new objects creation form public List<BaseObject> addObjectsFromRequest(String className, String pref, XWikiContext context) throws XWikiException { Map map = context.getRequest().getParameterMap(); List<Integer> objectsNumberDone = new ArrayList<Integer>(); List<BaseObject> objects = new ArrayList<BaseObject>(); Iterator it = map.keySet().iterator(); String start = pref + className + "_"; while (it.hasNext()) { String name = (String) it.next(); if (name.startsWith(start)) { int pos = name.indexOf("_", start.length() + 1); String prefix = name.substring(0, pos); int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue(); if (!objectsNumberDone.contains(new Integer(num))) { objectsNumberDone.add(new Integer(num)); objects.add(addObjectFromRequest(className, pref, num, context)); } } } return objects; } // This functions adds object from an new object creation form public BaseObject addObjectFromRequest(String className, int num, XWikiContext context) throws XWikiException { return addObjectFromRequest(className, "", num, context); } // This functions adds object from an new object creation form public BaseObject addObjectFromRequest(String className, String prefix, int num, XWikiContext context) throws XWikiException { int nb = createNewObject(className, context); BaseObject oldobject = getObject(className, nb); BaseClass baseclass = oldobject.getxWikiClass(context); BaseObject newobject = (BaseObject) baseclass.fromMap(Util.getObject(context.getRequest(), prefix + className + "_" + num), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setName(getFullName()); setObject(className, nb, newobject); return newobject; } // This functions adds an object from an new object creation form public BaseObject updateObjectFromRequest(String className, XWikiContext context) throws XWikiException { return updateObjectFromRequest(className, "", context); } // This functions adds an object from an new object creation form public BaseObject updateObjectFromRequest(String className, String prefix, XWikiContext context) throws XWikiException { return updateObjectFromRequest(className, prefix, 0, context); } // This functions adds an object from an new object creation form public BaseObject updateObjectFromRequest(String className, String prefix, int num, XWikiContext context) throws XWikiException { int nb; BaseObject oldobject = getObject(className, num); if (oldobject == null) { nb = createNewObject(className, context); oldobject = getObject(className, nb); } else { nb = oldobject.getNumber(); } BaseClass baseclass = oldobject.getxWikiClass(context); BaseObject newobject = (BaseObject) baseclass.fromMap(Util.getObject(context.getRequest(), prefix + className + "_" + nb), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setName(getFullName()); setObject(className, nb, newobject); return newobject; } // This functions adds an object from an new object creation form public List updateObjectsFromRequest(String className, XWikiContext context) throws XWikiException { return updateObjectsFromRequest(className, "", context); } // This functions adds multiple objects from an new objects creation form public List<BaseObject> updateObjectsFromRequest(String className, String pref, XWikiContext context) throws XWikiException { Map map = context.getRequest().getParameterMap(); List<Integer> objectsNumberDone = new ArrayList<Integer>(); List<BaseObject> objects = new ArrayList<BaseObject>(); Iterator it = map.keySet().iterator(); String start = pref + className + "_"; while (it.hasNext()) { String name = (String) it.next(); if (name.startsWith(start)) { int pos = name.indexOf("_", start.length() + 1); String prefix = name.substring(0, pos); int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue(); if (!objectsNumberDone.contains(new Integer(num))) { objectsNumberDone.add(new Integer(num)); objects.add(updateObjectFromRequest(className, pref, num, context)); } } } return objects; } public boolean isAdvancedContent() { String[] matches = {"<%", "#set", "#include", "#if", "public class", "/* Advanced content */", "## Advanced content", "/* Programmatic content */", "## Programmatic content"}; String content2 = this.content.toLowerCase(); for (int i = 0; i < matches.length; i++) { if (content2.indexOf(matches[i].toLowerCase()) != -1) { return true; } } if (HTML_TAG_PATTERN.matcher(content2).find()) { return true; } return false; } public boolean isProgrammaticContent() { String[] matches = {"<%", "\\$xwiki.xWiki", "$context.context", "$doc.document", "$xwiki.getXWiki()", "$context.getContext()", "$doc.getDocument()", "WithProgrammingRights(", "/* Programmatic content */", "## Programmatic content", "$xwiki.search(", "$xwiki.createUser", "$xwiki.createNewWiki", "$xwiki.addToAllGroup", "$xwiki.sendMessage", "$xwiki.copyDocument", "$xwiki.copyWikiWeb", "$xwiki.parseGroovyFromString", "$doc.toXML()", "$doc.toXMLDocument()",}; String content2 = this.content.toLowerCase(); for (int i = 0; i < matches.length; i++) { if (content2.indexOf(matches[i].toLowerCase()) != -1) { return true; } } return false; } public boolean removeObject(BaseObject bobj) { Vector<BaseObject> objects = getObjects(bobj.getClassName()); if (objects == null) { return false; } if (objects.elementAt(bobj.getNumber()) == null) { return false; } objects.set(bobj.getNumber(), null); addObjectsToRemove(bobj); return true; } /** * Remove all the objects of a given type (XClass) from the document. * * @param className The class name of the objects to be removed. */ public boolean removeObjects(String className) { Vector<BaseObject> objects = getObjects(className); if (objects == null) { return false; } Iterator<BaseObject> it = objects.iterator(); while (it.hasNext()) { BaseObject bobj = it.next(); if (bobj != null) { objects.set(bobj.getNumber(), null); addObjectsToRemove(bobj); } } return true; } // This method to split section according to title . public List<DocumentSection> getSplitSectionsAccordingToTitle() throws XWikiException { // Pattern to match the title. Matches only level 1 and level 2 headings. Pattern headingPattern = Pattern.compile("^[ \\t]*+(1(\\.1){0,1}+)[ \\t]++(.++)$", Pattern.MULTILINE); Matcher matcher = headingPattern.matcher(getContent()); List<DocumentSection> splitSections = new ArrayList<DocumentSection>(); int sectionNumber = 0; // find title to split while (matcher.find()) { ++sectionNumber; String sectionLevel = matcher.group(1); String sectionTitle = matcher.group(3); int sectionIndex = matcher.start(); // Initialize a documentSection object. DocumentSection docSection = new DocumentSection(sectionNumber, sectionIndex, sectionLevel, sectionTitle); // Add the document section to list. splitSections.add(docSection); } return splitSections; } // This function to return a Document section with parameter is sectionNumber public DocumentSection getDocumentSection(int sectionNumber) throws XWikiException { // return a document section according to section number return getSplitSectionsAccordingToTitle().get(sectionNumber - 1); } // This method to return the content of a section public String getContentOfSection(int sectionNumber) throws XWikiException { List<DocumentSection> splitSections = getSplitSectionsAccordingToTitle(); int indexEnd = 0; // get current section DocumentSection section = splitSections.get(sectionNumber - 1); int indexStart = section.getSectionIndex(); String sectionLevel = section.getSectionLevel(); // Determine where this section ends, which is at the start of the next section of the // same or a higher level. for (int i = sectionNumber; i < splitSections.size(); i++) { DocumentSection nextSection = splitSections.get(i); String nextLevel = nextSection.getSectionLevel(); if (sectionLevel.equals(nextLevel) || sectionLevel.length() > nextLevel.length()) { indexEnd = nextSection.getSectionIndex(); break; } } String sectionContent = null; if (indexStart < 0) { indexStart = 0; } if (indexEnd == 0) { sectionContent = getContent().substring(indexStart); } else { sectionContent = getContent().substring(indexStart, indexEnd); } return sectionContent; } // This function to update a section content in document public String updateDocumentSection(int sectionNumber, String newSectionContent) throws XWikiException { StringBuffer newContent = new StringBuffer(); // get document section that will be edited DocumentSection docSection = getDocumentSection(sectionNumber); int numberOfSections = getSplitSectionsAccordingToTitle().size(); int indexSection = docSection.getSectionIndex(); if (numberOfSections == 1) { // there is only a sections in document String contentBegin = getContent().substring(0, indexSection); newContent = newContent.append(contentBegin).append(newSectionContent); return newContent.toString(); } else if (sectionNumber == numberOfSections) { // edit lastest section that doesn't contain subtitle String contentBegin = getContent().substring(0, indexSection); newContent = newContent.append(contentBegin).append(newSectionContent); return newContent.toString(); } else { String sectionLevel = docSection.getSectionLevel(); int nextSectionIndex = 0; // get index of next section for (int i = sectionNumber; i < numberOfSections; i++) { DocumentSection nextSection = getDocumentSection(i + 1); // get next section String nextSectionLevel = nextSection.getSectionLevel(); if (sectionLevel.equals(nextSectionLevel)) { nextSectionIndex = nextSection.getSectionIndex(); break; } else if (sectionLevel.length() > nextSectionLevel.length()) { nextSectionIndex = nextSection.getSectionIndex(); break; } } if (nextSectionIndex == 0) {// edit the last section newContent = newContent.append(getContent().substring(0, indexSection)).append(newSectionContent); return newContent.toString(); } else { String contentAfter = getContent().substring(nextSectionIndex); String contentBegin = getContent().substring(0, indexSection); newContent = newContent.append(contentBegin).append(newSectionContent).append(contentAfter); } return newContent.toString(); } } /** * Computes a document hash, taking into account all document data: content, objects, attachments, metadata... TODO: * cache the hash value, update only on modification. */ public String getVersionHashCode(XWikiContext context) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { log.error("Cannot create MD5 object", ex); return this.hashCode() + ""; } try { String valueBeforeMD5 = toXML(true, false, true, false, context); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b)); } return sb.toString(); } catch (Exception ex) { log.error("Exception while computing document hash", ex); } return this.hashCode() + ""; } public static String getInternalPropertyName(String propname, XWikiContext context) { XWikiMessageTool msg = context.getMessageTool(); String cpropname = StringUtils.capitalize(propname); return (msg == null) ? cpropname : msg.get(cpropname); } public String getInternalProperty(String propname) { String methodName = "get" + StringUtils.capitalize(propname); try { Method method = getClass().getDeclaredMethod(methodName, (Class[]) null); return (String) method.invoke(this, (Object[]) null); } catch (Exception e) { return null; } } public String getCustomClass() { if (this.customClass == null) { return ""; } return this.customClass; } public void setCustomClass(String customClass) { this.customClass = customClass; setMetaDataDirty(true); } public void setValidationScript(String validationScript) { this.validationScript = validationScript; setMetaDataDirty(true); } public String getValidationScript() { if (this.validationScript == null) { return ""; } else { return this.validationScript; } } public String getComment() { if (this.comment == null) { return ""; } return this.comment; } public void setComment(String comment) { this.comment = comment; } public boolean isMinorEdit() { return this.isMinorEdit; } public void setMinorEdit(boolean isMinor) { this.isMinorEdit = isMinor; } // methods for easy table update. It is need only for hibernate. // when hibernate update old database without minorEdit field, hibernate will create field with // null in despite of notnull in hbm. // (http://opensource.atlassian.com/projects/hibernate/browse/HB-1151) // so minorEdit will be null for old documents. But hibernate can't convert null to boolean. // so we need convert Boolean to boolean protected Boolean getMinorEdit1() { return Boolean.valueOf(this.isMinorEdit); } protected void setMinorEdit1(Boolean isMinor) { this.isMinorEdit = (isMinor != null && isMinor.booleanValue()); } public BaseObject newObject(String classname, XWikiContext context) throws XWikiException { int nb = createNewObject(classname, context); return getObject(classname, nb); } public BaseObject getObject(String classname, boolean create, XWikiContext context) { try { BaseObject obj = getObject(classname); if ((obj == null) && create) { return newObject(classname, context); } if (obj == null) { return null; } else { return obj; } } catch (Exception e) { return null; } } public boolean validate(XWikiContext context) throws XWikiException { return validate(null, context); } public boolean validate(String[] classNames, XWikiContext context) throws XWikiException { boolean isValid = true; if ((classNames == null) || (classNames.length == 0)) { for (String classname : getxWikiObjects().keySet()) { BaseClass bclass = context.getWiki().getClass(classname, context); Vector<BaseObject> objects = getObjects(classname); for (BaseObject obj : objects) { if (obj != null) { isValid &= bclass.validateObject(obj, context); } } } } else { for (int i = 0; i < classNames.length; i++) { Vector<BaseObject> objects = getObjects(classNames[i]); if (objects != null) { for (BaseObject obj : objects) { if (obj != null) { BaseClass bclass = obj.getxWikiClass(context); isValid &= bclass.validateObject(obj, context); } } } } } String validationScript = ""; XWikiRequest req = context.getRequest(); if (req != null) { validationScript = req.get("xvalidation"); } if ((validationScript == null) || (validationScript.trim().equals(""))) { validationScript = getValidationScript(); } if ((validationScript != null) && (!validationScript.trim().equals(""))) { isValid &= executeValidationScript(context, validationScript); } return isValid; } private boolean executeValidationScript(XWikiContext context, String validationScript) throws XWikiException { try { XWikiValidationInterface validObject = (XWikiValidationInterface) context.getWiki().parseGroovyFromPage(validationScript, context); return validObject.validateDocument(this, context); } catch (Throwable e) { XWikiValidationStatus.addExceptionToContext(getFullName(), "", e, context); return false; } } public static void backupContext(HashMap<String, Object> backup, XWikiContext context) { backup.put("doc", context.getDoc()); VelocityContext vcontext = (VelocityContext) context.get("vcontext"); if (vcontext != null) { backup.put("vdoc", vcontext.get("doc")); backup.put("vcdoc", vcontext.get("cdoc")); backup.put("vtdoc", vcontext.get("tdoc")); } Map gcontext = (Map) context.get("gcontext"); if (gcontext != null) { backup.put("gdoc", gcontext.get("doc")); backup.put("gcdoc", gcontext.get("cdoc")); backup.put("gtdoc", gcontext.get("tdoc")); } } public static void restoreContext(HashMap<String, Object> backup, XWikiContext context) { context.setDoc((XWikiDocument) backup.get("doc")); VelocityContext vcontext = (VelocityContext) context.get("vcontext"); Map gcontext = (Map) context.get("gcontext"); if (vcontext != null) { if (backup.get("vdoc") != null) { vcontext.put("doc", backup.get("vdoc")); } if (backup.get("vcdoc") != null) { vcontext.put("cdoc", backup.get("vcdoc")); } if (backup.get("vtdoc") != null) { vcontext.put("tdoc", backup.get("vtdoc")); } } if (gcontext != null) { if (backup.get("gdoc") != null) { gcontext.put("doc", backup.get("gdoc")); } if (backup.get("gcdoc") != null) { gcontext.put("cdoc", backup.get("gcdoc")); } if (backup.get("gtdoc") != null) { gcontext.put("tdoc", backup.get("gtdoc")); } } } public void setAsContextDoc(XWikiContext context) { try { context.setDoc(this); com.xpn.xwiki.api.Document apidoc = this.newDocument(context); com.xpn.xwiki.api.Document tdoc = apidoc.getTranslatedDocument(); VelocityContext vcontext = (VelocityContext) context.get("vcontext"); Map gcontext = (Map) context.get("gcontext"); if (vcontext != null) { vcontext.put("doc", apidoc); vcontext.put("tdoc", tdoc); } if (gcontext != null) { gcontext.put("doc", apidoc); gcontext.put("tdoc", tdoc); } } catch (XWikiException ex) { log.warn("Unhandled exception setting context", ex); } } public String getPreviousVersion() { return getDocumentArchive().getPrevVersion(this.version).toString(); } @Override public String toString() { return getFullName(); } }
xwiki-core/src/main/java/com/xpn/xwiki/doc/XWikiDocument.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.xpn.xwiki.doc; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.lang.ref.SoftReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ecs.filter.CharacterFilter; import org.apache.velocity.VelocityContext; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.dom.DOMDocument; import org.dom4j.dom.DOMElement; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.suigeneris.jrcs.diff.Diff; import org.suigeneris.jrcs.diff.DifferentiationFailedException; import org.suigeneris.jrcs.diff.Revision; import org.suigeneris.jrcs.diff.delta.Delta; import org.suigeneris.jrcs.rcs.Version; import org.suigeneris.jrcs.util.ToString; import org.xwiki.rendering.block.XDOM; import org.xwiki.rendering.parser.Parser; import org.xwiki.rendering.parser.SyntaxFactory; import org.xwiki.rendering.renderer.XHTMLRenderer; import org.xwiki.rendering.transformation.TransformationManager; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiConstant; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.DocumentSection; import com.xpn.xwiki.content.Link; import com.xpn.xwiki.content.parsers.DocumentParser; import com.xpn.xwiki.content.parsers.LinkParser; import com.xpn.xwiki.content.parsers.RenamePageReplaceLinkHandler; import com.xpn.xwiki.content.parsers.ReplacementResultCollection; import com.xpn.xwiki.criteria.impl.RevisionCriteria; import com.xpn.xwiki.doc.rcs.XWikiRCSNodeInfo; import com.xpn.xwiki.notify.XWikiNotificationRule; import com.xpn.xwiki.objects.BaseCollection; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseProperty; import com.xpn.xwiki.objects.ListProperty; import com.xpn.xwiki.objects.ObjectDiff; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.objects.classes.ListClass; import com.xpn.xwiki.objects.classes.PropertyClass; import com.xpn.xwiki.objects.classes.StaticListClass; import com.xpn.xwiki.plugin.query.XWikiCriteria; import com.xpn.xwiki.render.XWikiVelocityRenderer; import com.xpn.xwiki.store.XWikiAttachmentStoreInterface; import com.xpn.xwiki.store.XWikiStoreInterface; import com.xpn.xwiki.store.XWikiVersioningStoreInterface; import com.xpn.xwiki.util.Util; import com.xpn.xwiki.validation.XWikiValidationInterface; import com.xpn.xwiki.validation.XWikiValidationStatus; import com.xpn.xwiki.web.EditForm; import com.xpn.xwiki.web.ObjectAddForm; import com.xpn.xwiki.web.Utils; import com.xpn.xwiki.web.XWikiMessageTool; import com.xpn.xwiki.web.XWikiRequest; public class XWikiDocument { private static final Log log = LogFactory.getLog(XWikiDocument.class); /** * Regex Pattern to recognize if there's HTML code in a XWiki page. */ private static final Pattern HTML_TAG_PATTERN = Pattern.compile("</?(html|body|img|a|i|b|embed|script|form|input|textarea|object|" + "font|li|ul|ol|table|center|hr|br|p) ?([^>]*)>"); private String title; private String parent; private String web; private String name; private String content; private String meta; private String format; private String creator; private String author; private String contentAuthor; private String customClass; private Date contentUpdateDate; private Date updateDate; private Date creationDate; private Version version; private long id = 0; private boolean mostRecent = true; private boolean isNew = true; private String template; private String language; private String defaultLanguage; private int translation; private String database; private BaseObject tags; /** * Comment on the latest modification. */ private String comment; /** * Wiki syntax supported by this document. This is used to support different syntaxes inside the same wiki. For * example a page can use the Confluence 2.0 syntax while another one uses the XWiki 1.0 syntax. In practice our * first need is to support the new rendering component. To use the old rendering implementation specify a * "xwiki/1.0" syntaxId and use a "xwiki/2.0" syntaxId for using the new rendering component. */ private String syntaxId; /** * Is latest modification a minor edit */ private boolean isMinorEdit = false; /** * Used to make sure the MetaData String is regenerated. */ private boolean isContentDirty = true; /** * Used to make sure the MetaData String is regenerated */ private boolean isMetaDataDirty = true; public static final int HAS_ATTACHMENTS = 1; public static final int HAS_OBJECTS = 2; public static final int HAS_CLASS = 4; private int elements = HAS_OBJECTS | HAS_ATTACHMENTS; /** * Separator string between database name and space name. */ public static final String DB_SPACE_SEP = ":"; /** * Separator string between space name and page name. */ public static final String SPACE_NAME_SEP = "."; // Meta Data private BaseClass xWikiClass; private String xWikiClassXML; /** * Map holding document objects grouped by classname (className -> Vector of objects). The map is not synchronized, * and uses a TreeMap implementation to preserve className ordering (consistent sorted order for output to XML, * rendering in velocity, etc.) */ private Map<String, Vector<BaseObject>> xWikiObjects = new TreeMap<String, Vector<BaseObject>>(); private List<XWikiAttachment> attachmentList; // Caching private boolean fromCache = false; private ArrayList<BaseObject> objectsToRemove = new ArrayList<BaseObject>(); // Template by default assign to a view private String defaultTemplate; private String validationScript; private Object wikiNode; // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during the // request) private SoftReference<XWikiDocumentArchive> archive; private XWikiStoreInterface store; /** * This is a copy of this XWikiDocument before any modification was made to it. It is reset to the actual values * when the document is saved in the database. This copy is used for finding out differences made to this document * (useful for example to send the correct notifications to document change listeners). */ private XWikiDocument originalDocument; public XWikiStoreInterface getStore(XWikiContext context) { return context.getWiki().getStore(); } public XWikiAttachmentStoreInterface getAttachmentStore(XWikiContext context) { return context.getWiki().getAttachmentStore(); } public XWikiVersioningStoreInterface getVersioningStore(XWikiContext context) { return context.getWiki().getVersioningStore(); } public XWikiStoreInterface getStore() { return this.store; } public void setStore(XWikiStoreInterface store) { this.store = store; } public long getId() { if ((this.language == null) || this.language.trim().equals("")) { this.id = getFullName().hashCode(); } else { this.id = (getFullName() + ":" + this.language).hashCode(); } // if (log.isDebugEnabled()) // log.debug("ID: " + getFullName() + " " + language + ": " + id); return this.id; } public void setId(long id) { this.id = id; } /** * @return the name of the space of the document */ public String getSpace() { return this.web; } public void setSpace(String space) { this.web = space; } public String getVersion() { return getRCSVersion().toString(); } public void setVersion(String version) { if (version != null && !"".equals(version)) { this.version = new Version(version); } } public Version getRCSVersion() { if (this.version == null) { return new Version("1.1"); } return this.version; } public void setRCSVersion(Version version) { this.version = version; } public XWikiDocument() { this("Main", "WebHome"); } public XWikiDocument(String web, String name) { setSpace(web); int i1 = name.indexOf("."); if (i1 == -1) { setName(name); } else { setSpace(name.substring(0, i1)); setName(name.substring(i1 + 1)); } this.updateDate = new Date(); this.updateDate.setTime((this.updateDate.getTime() / 1000) * 1000); this.contentUpdateDate = new Date(); this.contentUpdateDate.setTime((this.contentUpdateDate.getTime() / 1000) * 1000); this.creationDate = new Date(); this.creationDate.setTime((this.creationDate.getTime() / 1000) * 1000); this.parent = ""; this.content = "\n"; this.format = ""; this.author = ""; this.language = ""; this.defaultLanguage = ""; this.attachmentList = new ArrayList<XWikiAttachment>(); this.customClass = ""; this.comment = ""; this.syntaxId = "xwiki/1.0"; // Note: As there's no notion of an Empty document we don't set the original document // field. Thus getOriginalDocument() may return null. } /** * @return the copy of this XWikiDocument instance before any modification was made to it. * @see #originalDocument */ public XWikiDocument getOriginalDocument() { return this.originalDocument; } /** * @param originalDocument the original document representing this document instance before any change was made to * it, prior to the last time it was saved * @see #originalDocument */ public void setOriginalDocument(XWikiDocument originalDocument) { this.originalDocument = originalDocument; } public XWikiDocument getParentDoc() { return new XWikiDocument(getSpace(), getParent()); } public String getParent() { return this.parent != null ? this.parent : ""; } public void setParent(String parent) { if (parent != null && !parent.equals(this.parent)) { setMetaDataDirty(true); } this.parent = parent; } public String getContent() { return this.content; } public void setContent(String content) { if (!content.equals(this.content)) { setContentDirty(true); setWikiNode(null); } this.content = content; } public String getRenderedContent(XWikiContext context) throws XWikiException { String renderedContent; // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem. Otherwise use the new one. if (getSyntaxId().equalsIgnoreCase("xwiki/1.0")) { renderedContent = context.getWiki().getRenderingEngine().renderDocument(this, context); } else { StringWriter writer = new StringWriter(); TransformationManager transformations = (TransformationManager) Utils.getComponent(TransformationManager.ROLE); XDOM dom; try { Parser parser = (Parser) Utils.getComponent(Parser.ROLE, getSyntaxId()); dom = parser.parse(new StringReader(this.content)); SyntaxFactory syntaxFactory = (SyntaxFactory) Utils.getComponent(SyntaxFactory.ROLE); transformations.performTransformations(dom, syntaxFactory.createSyntaxFromIdString(getSyntaxId())); } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN, "Failed to render content using new rendering system", e); } dom.traverse(new XHTMLRenderer(writer)); renderedContent = writer.toString(); } return renderedContent; } public String getRenderedContent(String text, XWikiContext context) { String result; HashMap<String, Object> backup = new HashMap<String, Object>(); try { backupContext(backup, context); setAsContextDoc(context); result = context.getWiki().getRenderingEngine().renderText(text, this, context); } finally { restoreContext(backup, context); } return result; } public String getEscapedContent(XWikiContext context) throws XWikiException { CharacterFilter filter = new CharacterFilter(); return filter.process(getTranslatedContent(context)); } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getFullName() { StringBuffer buf = new StringBuffer(); buf.append(getSpace()); buf.append("."); buf.append(getName()); return buf.toString(); } public void setFullName(String name) { setFullName(name, null); } public String getTitle() { return (this.title != null) ? this.title : ""; } /** * @param context the XWiki context used to get acces to the XWikiRenderingEngine object * @return the document title. If a title has not been provided, look for a section title in the document's content * and if not found return the page name. The returned title is also interpreted which means it's allowed to * use Velocity, Groovy, etc syntax within a title. */ public String getDisplayTitle(XWikiContext context) { // 1) Check if the user has provided a title String title = getTitle(); // 2) If not, then try to extract the title from the first document section title if (title.length() == 0) { title = extractTitle(); } // 3) Last if a title has been found renders it as it can contain macros, velocity code, // groovy, etc. if (title.length() > 0) { // This will not completely work for scriting code in title referencing variables // defined elsewhere. In that case it'll only work if those variables have been // parsed and put in the corresponding scripting context. This will not work for // breadcrumbs for example. title = context.getWiki().getRenderingEngine().interpretText(title, this, context); } else { // 4) No title has been found, return the page name as the title title = getName(); } return title; } /** * @return the first level 1 or level 1.1 title text in the document's content or "" if none are found * @todo this method has nothing to do in this class and should be moved elsewhere */ public String extractTitle() { try { String content = getContent(); int i1 = 0; int i2; while (true) { i2 = content.indexOf("\n", i1); String title = ""; if (i2 != -1) { title = content.substring(i1, i2).trim(); } else { title = content.substring(i1).trim(); } if ((!title.equals("")) && (title.matches("1(\\.1)?\\s+.+"))) { return title.substring(title.indexOf(" ")).trim(); } if (i2 == -1) { break; } i1 = i2 + 1; } } catch (Exception e) { } return ""; } public void setTitle(String title) { if (title != null && !title.equals(this.title)) { setContentDirty(true); } this.title = title; } public String getFormat() { return this.format != null ? this.format : ""; } public void setFormat(String format) { this.format = format; if (!format.equals(this.format)) { setMetaDataDirty(true); } } public String getAuthor() { return this.author != null ? this.author.trim() : ""; } public String getContentAuthor() { return this.contentAuthor != null ? this.contentAuthor.trim() : ""; } public void setAuthor(String author) { if (!getAuthor().equals(author)) { setMetaDataDirty(true); } this.author = author; } public void setContentAuthor(String contentAuthor) { if (!getContentAuthor().equals(contentAuthor)) { setMetaDataDirty(true); } this.contentAuthor = contentAuthor; } public String getCreator() { return this.creator != null ? this.creator.trim() : ""; } public void setCreator(String creator) { if (!getCreator().equals(creator)) { setMetaDataDirty(true); } this.creator = creator; } public Date getDate() { if (this.updateDate == null) { return new Date(); } else { return this.updateDate; } } public void setDate(Date date) { if ((date != null) && (!date.equals(this.updateDate))) { setMetaDataDirty(true); } // Make sure we drop milliseconds for consistency with the database if (date != null) { date.setTime((date.getTime() / 1000) * 1000); } this.updateDate = date; } public Date getCreationDate() { if (this.creationDate == null) { return new Date(); } else { return this.creationDate; } } public void setCreationDate(Date date) { if ((date != null) && (!date.equals(this.creationDate))) { setMetaDataDirty(true); } // Make sure we drop milliseconds for consistency with the database if (date != null) { date.setTime((date.getTime() / 1000) * 1000); } this.creationDate = date; } public Date getContentUpdateDate() { if (this.contentUpdateDate == null) { return new Date(); } else { return this.contentUpdateDate; } } public void setContentUpdateDate(Date date) { if ((date != null) && (!date.equals(this.contentUpdateDate))) { setMetaDataDirty(true); } // Make sure we drop milliseconds for consistency with the database if (date != null) { date.setTime((date.getTime() / 1000) * 1000); } this.contentUpdateDate = date; } public String getMeta() { return this.meta; } public void setMeta(String meta) { if (meta == null) { if (this.meta != null) { setMetaDataDirty(true); } } else if (!meta.equals(this.meta)) { setMetaDataDirty(true); } this.meta = meta; } public void appendMeta(String meta) { StringBuffer buf = new StringBuffer(this.meta); buf.append(meta); buf.append("\n"); this.meta = buf.toString(); setMetaDataDirty(true); } public boolean isContentDirty() { return this.isContentDirty; } public void incrementVersion() { if (this.version == null) { this.version = new Version("1.1"); } else { if (isMinorEdit()) { this.version = this.version.next(); } else { this.version = this.version.getBranchPoint().next().newBranch(1); } } } public void setContentDirty(boolean contentDirty) { this.isContentDirty = contentDirty; } public boolean isMetaDataDirty() { return this.isMetaDataDirty; } public void setMetaDataDirty(boolean metaDataDirty) { this.isMetaDataDirty = metaDataDirty; } public String getAttachmentURL(String filename, XWikiContext context) { return getAttachmentURL(filename, "download", context); } public String getAttachmentURL(String filename, String action, XWikiContext context) { URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getExternalAttachmentURL(String filename, String action, XWikiContext context) { URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(), context); return url.toString(); } public String getAttachmentURL(String filename, String action, String querystring, XWikiContext context) { URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, querystring, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getAttachmentRevisionURL(String filename, String revision, XWikiContext context) { URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getAttachmentRevisionURL(String filename, String revision, String querystring, XWikiContext context) { URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, querystring, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getURL(String action, String params, boolean redirect, XWikiContext context) { URL url = context.getURLFactory().createURL(getSpace(), getName(), action, params, null, getDatabase(), context); if (redirect) { if (url == null) { return null; } else { return url.toString(); } } else { return context.getURLFactory().getURL(url, context); } } public String getURL(String action, boolean redirect, XWikiContext context) { return getURL(action, null, redirect, context); } public String getURL(String action, XWikiContext context) { return getURL(action, false, context); } public String getURL(String action, String querystring, XWikiContext context) { URL url = context.getURLFactory().createURL(getSpace(), getName(), action, querystring, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getExternalURL(String action, XWikiContext context) { URL url = context.getURLFactory() .createExternalURL(getSpace(), getName(), action, null, null, getDatabase(), context); return url.toString(); } public String getExternalURL(String action, String querystring, XWikiContext context) { URL url = context.getURLFactory().createExternalURL(getSpace(), getName(), action, querystring, null, getDatabase(), context); return url.toString(); } public String getParentURL(XWikiContext context) throws XWikiException { XWikiDocument doc = new XWikiDocument(); doc.setFullName(getParent(), context); URL url = context.getURLFactory() .createURL(doc.getSpace(), doc.getName(), "view", null, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public XWikiDocumentArchive getDocumentArchive(XWikiContext context) throws XWikiException { loadArchive(context); return getDocumentArchive(); } /** * return a wrapped version of an XWikiDocument. Prefer this function instead of new Document(XWikiDocument, * XWikiContext) */ public com.xpn.xwiki.api.Document newDocument(String customClassName, XWikiContext context) { if (!((customClassName == null) || (customClassName.equals("")))) { try { Class< ? >[] classes = new Class[] {XWikiDocument.class, XWikiContext.class}; Object[] args = new Object[] {this, context}; return (com.xpn.xwiki.api.Document) Class.forName(customClassName).getConstructor(classes).newInstance( args); } catch (InstantiationException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | // File Templates. } catch (IllegalAccessException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | // File Templates. } catch (ClassNotFoundException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | // File Templates. } catch (NoSuchMethodException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | // File Templates. } catch (InvocationTargetException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | // File Templates. } } return new com.xpn.xwiki.api.Document(this, context); } public com.xpn.xwiki.api.Document newDocument(XWikiContext context) { String customClass = getCustomClass(); return newDocument(customClass, context); } public void loadArchive(XWikiContext context) throws XWikiException { if (this.archive == null || this.archive.get() == null) { XWikiDocumentArchive arch = getVersioningStore(context).getXWikiDocumentArchive(this, context); // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during // the request) this.archive = new SoftReference<XWikiDocumentArchive>(arch); } } public XWikiDocumentArchive getDocumentArchive() { // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during the // request) if (this.archive == null) { return null; } else { return this.archive.get(); } } public void setDocumentArchive(XWikiDocumentArchive arch) { // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during the // request) if (arch != null) { this.archive = new SoftReference<XWikiDocumentArchive>(arch); } } public void setDocumentArchive(String sarch) throws XWikiException { XWikiDocumentArchive xda = new XWikiDocumentArchive(getId()); xda.setArchive(sarch); setDocumentArchive(xda); } public Version[] getRevisions(XWikiContext context) throws XWikiException { return getVersioningStore(context).getXWikiDocVersions(this, context); } public String[] getRecentRevisions(int nb, XWikiContext context) throws XWikiException { try { Version[] revisions = getVersioningStore(context).getXWikiDocVersions(this, context); int length = nb; // 0 means all revisions if (nb == 0) { length = revisions.length; } if (revisions.length < length) { length = revisions.length; } String[] recentrevs = new String[length]; for (int i = 1; i <= length; i++) { recentrevs[i - 1] = revisions[revisions.length - i].toString(); } return recentrevs; } catch (Exception e) { return new String[0]; } } /** * Get document versions matching criterias like author, minimum creation date, etc. * * @param criteria criteria used to match versions * @return a list of matching versions */ public List<String> getRevisions(RevisionCriteria criteria, XWikiContext context) throws XWikiException { List<String> results = new ArrayList<String>(); Version[] revisions = getRevisions(context); XWikiRCSNodeInfo nextNodeinfo = null; XWikiRCSNodeInfo nodeinfo = null; for (int i = 0; i < revisions.length; i++) { nodeinfo = nextNodeinfo; nextNodeinfo = getRevisionInfo(revisions[i].toString(), context); if (nodeinfo == null) { continue; } // Minor/Major version matching if (criteria.getIncludeMinorVersions() || !nextNodeinfo.isMinorEdit()) { // Author matching if (criteria.getAuthor().equals("") || criteria.getAuthor().equals(nodeinfo.getAuthor())) { // Date range matching if (nodeinfo.getDate().after(criteria.getMinDate()) && nodeinfo.getDate().before(criteria.getMaxDate())) { results.add(nodeinfo.getVersion().toString()); } } } } nodeinfo = nextNodeinfo; if (nodeinfo != null) { if (criteria.getAuthor().equals("") || criteria.getAuthor().equals(nodeinfo.getAuthor())) { // Date range matching if (nodeinfo.getDate().after(criteria.getMinDate()) && nodeinfo.getDate().before(criteria.getMaxDate())) { results.add(nodeinfo.getVersion().toString()); } } } return criteria.getRange().subList(results); } public XWikiRCSNodeInfo getRevisionInfo(String version, XWikiContext context) throws XWikiException { return getDocumentArchive(context).getNode(new Version(version)); } /** * @return Is this version the most recent one. False if and only if there are newer versions of this document in * the database. */ public boolean isMostRecent() { return this.mostRecent; } /** * must not be used unless in store system. * * @param mostRecent - mark document as most recent. */ public void setMostRecent(boolean mostRecent) { this.mostRecent = mostRecent; } public BaseClass getxWikiClass() { if (this.xWikiClass == null) { this.xWikiClass = new BaseClass(); this.xWikiClass.setName(getFullName()); } return this.xWikiClass; } public void setxWikiClass(BaseClass xWikiClass) { this.xWikiClass = xWikiClass; } public Map<String, Vector<BaseObject>> getxWikiObjects() { return this.xWikiObjects; } public void setxWikiObjects(Map<String, Vector<BaseObject>> xWikiObjects) { this.xWikiObjects = xWikiObjects; } public BaseObject getxWikiObject() { return getObject(getFullName()); } public List<BaseClass> getxWikiClasses(XWikiContext context) { List<BaseClass> list = new ArrayList<BaseClass>(); // xWikiObjects is a TreeMap, with elements sorted by className for (String classname : getxWikiObjects().keySet()) { BaseClass bclass = null; Vector<BaseObject> objects = getObjects(classname); for (BaseObject obj : objects) { if (obj != null) { bclass = obj.getxWikiClass(context); if (bclass != null) { break; } } } if (bclass != null) { list.add(bclass); } } return list; } public int createNewObject(String classname, XWikiContext context) throws XWikiException { BaseObject object = BaseClass.newCustomClassInstance(classname, context); object.setName(getFullName()); object.setClassName(classname); Vector<BaseObject> objects = getObjects(classname); if (objects == null) { objects = new Vector<BaseObject>(); setObjects(classname, objects); } objects.add(object); int nb = objects.size() - 1; object.setNumber(nb); setContentDirty(true); return nb; } public int getObjectNumbers(String classname) { try { return getxWikiObjects().get(classname).size(); } catch (Exception e) { return 0; } } public Vector<BaseObject> getObjects(String classname) { if (classname == null) { return new Vector<BaseObject>(); } if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } return getxWikiObjects().get(classname); } public void setObjects(String classname, Vector<BaseObject> objects) { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } getxWikiObjects().put(classname, objects); } public BaseObject getObject(String classname) { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } Vector<BaseObject> objects = getxWikiObjects().get(classname); if (objects == null) { return null; } for (int i = 0; i < objects.size(); i++) { BaseObject obj = objects.get(i); if (obj != null) { return obj; } } return null; } public BaseObject getObject(String classname, int nb) { try { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } return getxWikiObjects().get(classname).get(nb); } catch (Exception e) { return null; } } public BaseObject getObject(String classname, String key, String value) { return getObject(classname, key, value, false); } public BaseObject getObject(String classname, String key, String value, boolean failover) { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } try { if (value == null) { if (failover) { return getObject(classname); } else { return null; } } Vector<BaseObject> objects = getxWikiObjects().get(classname); if ((objects == null) || (objects.size() == 0)) { return null; } for (int i = 0; i < objects.size(); i++) { BaseObject obj = objects.get(i); if (obj != null) { if (value.equals(obj.getStringValue(key))) { return obj; } } } if (failover) { return getObject(classname); } else { return null; } } catch (Exception e) { if (failover) { return getObject(classname); } e.printStackTrace(); return null; } } public void addObject(String classname, BaseObject object) { Vector<BaseObject> vobj = getObjects(classname); if (vobj == null) { setObject(classname, 0, object); } else { setObject(classname, vobj.size(), object); } setContentDirty(true); } public void setObject(String classname, int nb, BaseObject object) { Vector<BaseObject> objects = getObjects(classname); if (objects == null) { objects = new Vector<BaseObject>(); setObjects(classname, objects); } if (nb >= objects.size()) { objects.setSize(nb + 1); } objects.set(nb, object); object.setNumber(nb); setContentDirty(true); } /** * @return true if the document is a new one (ie it has never been saved) or false otherwise */ public boolean isNew() { return this.isNew; } public void setNew(boolean aNew) { this.isNew = aNew; } public void mergexWikiClass(XWikiDocument templatedoc) { BaseClass bclass = getxWikiClass(); BaseClass tbclass = templatedoc.getxWikiClass(); if (tbclass != null) { if (bclass == null) { setxWikiClass((BaseClass) tbclass.clone()); } else { getxWikiClass().merge((BaseClass) tbclass.clone()); } } setContentDirty(true); } public void mergexWikiObjects(XWikiDocument templatedoc) { // TODO: look for each object if it already exist and add it if it doesn't for (String name : templatedoc.getxWikiObjects().keySet()) { Vector<BaseObject> myObjects = getxWikiObjects().get(name); if (myObjects == null) { myObjects = new Vector<BaseObject>(); } for (BaseObject otherObject : templatedoc.getxWikiObjects().get(name)) { if (otherObject != null) { BaseObject myObject = (BaseObject) otherObject.clone(); myObjects.add(myObject); myObject.setNumber(myObjects.size() - 1); } } getxWikiObjects().put(name, myObjects); } setContentDirty(true); } public void clonexWikiObjects(XWikiDocument templatedoc) { for (String name : templatedoc.getxWikiObjects().keySet()) { Vector<BaseObject> tobjects = templatedoc.getObjects(name); Vector<BaseObject> objects = new Vector<BaseObject>(); objects.setSize(tobjects.size()); for (int i = 0; i < tobjects.size(); i++) { BaseObject otherObject = tobjects.get(i); if (otherObject != null) { BaseObject myObject = (BaseObject) otherObject.clone(); objects.set(i, myObject); } } getxWikiObjects().put(name, objects); } } public String getTemplate() { return StringUtils.defaultString(this.template); } public void setTemplate(String template) { this.template = template; setMetaDataDirty(true); } public String displayPrettyName(String fieldname, XWikiContext context) { return displayPrettyName(fieldname, false, true, context); } public String displayPrettyName(String fieldname, boolean showMandatory, XWikiContext context) { return displayPrettyName(fieldname, false, true, context); } public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } return displayPrettyName(fieldname, showMandatory, before, object, context); } catch (Exception e) { return ""; } } public String displayPrettyName(String fieldname, BaseObject obj, XWikiContext context) { return displayPrettyName(fieldname, false, true, obj, context); } public String displayPrettyName(String fieldname, boolean showMandatory, BaseObject obj, XWikiContext context) { return displayPrettyName(fieldname, showMandatory, true, obj, context); } public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, BaseObject obj, XWikiContext context) { try { PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname); String dprettyName = ""; if ((showMandatory) && (pclass.getValidationRegExp() != null) && (!pclass.getValidationRegExp().equals(""))) { dprettyName = context.getWiki().addMandatory(context); } if (before) { return dprettyName + pclass.getPrettyName(); } else { return pclass.getPrettyName() + dprettyName; } } catch (Exception e) { return ""; } } public String displayTooltip(String fieldname, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } return displayTooltip(fieldname, object, context); } catch (Exception e) { return ""; } } public String displayTooltip(String fieldname, BaseObject obj, XWikiContext context) { try { PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname); String tooltip = pclass.getTooltip(context); if ((tooltip != null) && (!tooltip.trim().equals(""))) { String img = "<img src=\"" + context.getWiki().getSkinFile("info.gif", context) + "\" class=\"tooltip_image\" align=\"middle\" />"; return context.getWiki().addTooltip(img, tooltip, context); } else { return ""; } } catch (Exception e) { return ""; } } public String display(String fieldname, String type, BaseObject obj, XWikiContext context) { return display(fieldname, type, "", obj, context); } public String display(String fieldname, String type, String pref, BaseObject obj, XWikiContext context) { HashMap<String, Object> backup = new HashMap<String, Object>(); try { backupContext(backup, context); setAsContextDoc(context); type = type.toLowerCase(); StringBuffer result = new StringBuffer(); PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname); String prefix = pref + obj.getxWikiClass(context).getName() + "_" + obj.getNumber() + "_"; if (pclass.isCustomDisplayed(context)) { pclass.displayCustom(result, fieldname, prefix, type, obj, context); } else if (type.equals("view")) { pclass.displayView(result, fieldname, prefix, obj, context); } else if (type.equals("rendered")) { String fcontent = pclass.displayView(fieldname, prefix, obj, context); result.append(getRenderedContent(fcontent, context)); } else if (type.equals("edit")) { context.addDisplayedField(fieldname); result.append("{pre}"); pclass.displayEdit(result, fieldname, prefix, obj, context); result.append("{/pre}"); } else if (type.equals("hidden")) { result.append("{pre}"); pclass.displayHidden(result, fieldname, prefix, obj, context); result.append("{/pre}"); } else if (type.equals("search")) { result.append("{pre}"); prefix = obj.getxWikiClass(context).getName() + "_"; pclass.displaySearch(result, fieldname, prefix, (XWikiCriteria) context.get("query"), context); result.append("{/pre}"); } else { pclass.displayView(result, fieldname, prefix, obj, context); } return result.toString(); } catch (Exception ex) { // TODO: It would better to check if the field exists rather than catching an exception // raised by a NPE as this is currently the case here... log.warn("Failed to display field [" + fieldname + "] in [" + type + "] mode for Object [" + (obj == null ? "NULL" : obj.getName()) + "]"); return ""; } finally { restoreContext(backup, context); } } public String display(String fieldname, BaseObject obj, XWikiContext context) { String type = null; try { type = (String) context.get("display"); } catch (Exception e) { } if (type == null) { type = "view"; } return display(fieldname, type, obj, context); } public String display(String fieldname, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } return display(fieldname, object, context); } catch (Exception e) { return ""; } } public String display(String fieldname, String mode, XWikiContext context) { return display(fieldname, mode, "", context); } public String display(String fieldname, String mode, String prefix, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } if (object == null) { return ""; } else { return display(fieldname, mode, prefix, object, context); } } catch (Exception e) { return ""; } } public String displayForm(String className, String header, String format, XWikiContext context) { return displayForm(className, header, format, true, context); } public String displayForm(String className, String header, String format, boolean linebreak, XWikiContext context) { Vector<BaseObject> objects = getObjects(className); if (format.endsWith("\\n")) { linebreak = true; } BaseObject firstobject = null; Iterator<BaseObject> foit = objects.iterator(); while ((firstobject == null) && foit.hasNext()) { firstobject = foit.next(); } if (firstobject == null) { return ""; } BaseClass bclass = firstobject.getxWikiClass(context); Collection fields = bclass.getFieldList(); if (fields.size() == 0) { return ""; } StringBuffer result = new StringBuffer(); VelocityContext vcontext = new VelocityContext(); for (Iterator it = fields.iterator(); it.hasNext();) { PropertyClass pclass = (PropertyClass) it.next(); vcontext.put(pclass.getName(), pclass.getPrettyName()); } result.append(XWikiVelocityRenderer.evaluate(header, context.getDoc().getFullName(), vcontext, context)); if (linebreak) { result.append("\n"); } // display each line for (int i = 0; i < objects.size(); i++) { vcontext.put("id", new Integer(i + 1)); BaseObject object = objects.get(i); if (object != null) { for (Iterator it = bclass.getPropertyList().iterator(); it.hasNext();) { String name = (String) it.next(); vcontext.put(name, display(name, object, context)); } result .append(XWikiVelocityRenderer.evaluate(format, context.getDoc().getFullName(), vcontext, context)); if (linebreak) { result.append("\n"); } } } return result.toString(); } public String displayForm(String className, XWikiContext context) { Vector<BaseObject> objects = getObjects(className); if (objects == null) { return ""; } BaseObject firstobject = null; Iterator<BaseObject> foit = objects.iterator(); while ((firstobject == null) && foit.hasNext()) { firstobject = foit.next(); } if (firstobject == null) { return ""; } BaseClass bclass = firstobject.getxWikiClass(context); Collection fields = bclass.getFieldList(); if (fields.size() == 0) { return ""; } StringBuffer result = new StringBuffer(); result.append("{table}\n"); boolean first = true; for (Iterator it = fields.iterator(); it.hasNext();) { if (first == true) { first = false; } else { result.append("|"); } PropertyClass pclass = (PropertyClass) it.next(); result.append(pclass.getPrettyName()); } result.append("\n"); for (int i = 0; i < objects.size(); i++) { BaseObject object = objects.get(i); if (object != null) { first = true; for (Iterator it = bclass.getPropertyList().iterator(); it.hasNext();) { if (first == true) { first = false; } else { result.append("|"); } String data = display((String) it.next(), object, context); data = data.trim(); data = data.replaceAll("\n", " "); if (data.length() == 0) { result.append("&nbsp;"); } else { result.append(data); } } result.append("\n"); } } result.append("{table}\n"); return result.toString(); } public boolean isFromCache() { return this.fromCache; } public void setFromCache(boolean fromCache) { this.fromCache = fromCache; } public void readDocMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException { String defaultLanguage = eform.getDefaultLanguage(); if (defaultLanguage != null) { setDefaultLanguage(defaultLanguage); } String defaultTemplate = eform.getDefaultTemplate(); if (defaultTemplate != null) { setDefaultTemplate(defaultTemplate); } String creator = eform.getCreator(); if ((creator != null) && (!creator.equals(getCreator()))) { if ((getCreator().equals(context.getUser())) || (context.getWiki().getRightService().hasAdminRights(context))) { setCreator(creator); } } String parent = eform.getParent(); if (parent != null) { setParent(parent); } // Read the comment from the form String comment = eform.getComment(); if (comment != null) { setComment(comment); } // Read the minor edit checkbox from the form setMinorEdit(eform.isMinorEdit()); String tags = eform.getTags(); if (tags != null) { setTags(tags, context); } // Set the Syntax id if defined String syntaxId = eform.getSyntaxId(); if (syntaxId != null) { setSyntaxId(syntaxId); } } /** * add tags to the document. */ public void setTags(String tags, XWikiContext context) throws XWikiException { loadTags(context); StaticListClass tagProp = (StaticListClass) this.tags.getxWikiClass(context).getField(XWikiConstant.TAG_CLASS_PROP_TAGS); tagProp.fromString(tags); this.tags.safeput(XWikiConstant.TAG_CLASS_PROP_TAGS, tagProp.fromString(tags)); setMetaDataDirty(true); } public String getTags(XWikiContext context) { ListProperty prop = (ListProperty) getTagProperty(context); if (prop != null) { return prop.getTextValue(); } return null; } public List getTagsList(XWikiContext context) { List tagList = null; BaseProperty prop = getTagProperty(context); if (prop != null) { tagList = (List) prop.getValue(); } return tagList; } private BaseProperty getTagProperty(XWikiContext context) { loadTags(context); return ((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS)); } private void loadTags(XWikiContext context) { if (this.tags == null) { this.tags = getObject(XWikiConstant.TAG_CLASS, true, context); } } public List getTagsPossibleValues(XWikiContext context) { loadTags(context); String possibleValues = ((StaticListClass) this.tags.getxWikiClass(context).getField(XWikiConstant.TAG_CLASS_PROP_TAGS)) .getValues(); return ListClass.getListFromString(possibleValues); // ((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS)).toString(); } public void readTranslationMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException { String content = eform.getContent(); if (content != null) { // Cleanup in case we use HTMLAREA // content = context.getUtil().substitute("s/<br class=\\\"htmlarea\\\"\\/>/\\r\\n/g", // content); content = context.getUtil().substitute("s/<br class=\"htmlarea\" \\/>/\r\n/g", content); setContent(content); } String title = eform.getTitle(); if (title != null) { setTitle(title); } } public void readObjectsFromForm(EditForm eform, XWikiContext context) throws XWikiException { for (String name : getxWikiObjects().keySet()) { Vector<BaseObject> oldObjects = getObjects(name); Vector<BaseObject> newObjects = new Vector<BaseObject>(); newObjects.setSize(oldObjects.size()); for (int i = 0; i < oldObjects.size(); i++) { BaseObject oldobject = oldObjects.get(i); if (oldobject != null) { BaseClass baseclass = oldobject.getxWikiClass(context); BaseObject newobject = (BaseObject) baseclass.fromMap(eform.getObject(baseclass.getName() + "_" + i), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setName(getFullName()); newObjects.set(newobject.getNumber(), newobject); } } getxWikiObjects().put(name, newObjects); } setContentDirty(true); } public void readFromForm(EditForm eform, XWikiContext context) throws XWikiException { readDocMetaFromForm(eform, context); readTranslationMetaFromForm(eform, context); readObjectsFromForm(eform, context); } public void readFromTemplate(EditForm eform, XWikiContext context) throws XWikiException { String template = eform.getTemplate(); readFromTemplate(template, context); } public void readFromTemplate(String template, XWikiContext context) throws XWikiException { if ((template != null) && (!template.equals(""))) { String content = getContent(); if ((!content.equals("\n")) && (!content.equals("")) && !isNew()) { Object[] args = {getFullName()}; throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY, "Cannot add a template to document {0} because it already has content", null, args); } else { if (template.indexOf('.') == -1) { template = getSpace() + "." + template; } XWiki xwiki = context.getWiki(); XWikiDocument templatedoc = xwiki.getDocument(template, context); if (templatedoc.isNew()) { Object[] args = {template, getFullName()}; throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_APP_TEMPLATE_DOES_NOT_EXIST, "Template document {0} does not exist when adding to document {1}", null, args); } else { setTemplate(template); setContent(templatedoc.getContent()); if ((getParent() == null) || (getParent().equals(""))) { String tparent = templatedoc.getParent(); if (tparent != null) { setParent(tparent); } } if (isNew()) { // We might have received the object from the cache // and the template objects might have been copied already // we need to remove them setxWikiObjects(new TreeMap<String, Vector<BaseObject>>()); } // Merge the external objects // Currently the choice is not to merge the base class and object because it is // not // the prefered way of using external classes and objects. mergexWikiObjects(templatedoc); } } } setContentDirty(true); } public void notify(XWikiNotificationRule rule, XWikiDocument newdoc, XWikiDocument olddoc, int event, XWikiContext context) { // Do nothing for the moment.. // A usefull thing here would be to look at any instances of a Notification Object // with email addresses and send an email to warn that the document has been modified.. } /** * Use the document passsed as parameter as the new identity for the current document. * * @param document the document containing the new identity * @throws XWikiException in case of error */ private void clone(XWikiDocument document) throws XWikiException { setDatabase(document.getDatabase()); setRCSVersion(document.getRCSVersion()); setDocumentArchive(document.getDocumentArchive()); setAuthor(document.getAuthor()); setContentAuthor(document.getContentAuthor()); setContent(document.getContent()); setContentDirty(document.isContentDirty()); setCreationDate(document.getCreationDate()); setDate(document.getDate()); setCustomClass(document.getCustomClass()); setContentUpdateDate(document.getContentUpdateDate()); setTitle(document.getTitle()); setFormat(document.getFormat()); setFromCache(document.isFromCache()); setElements(document.getElements()); setId(document.getId()); setMeta(document.getMeta()); setMetaDataDirty(document.isMetaDataDirty()); setMostRecent(document.isMostRecent()); setName(document.getName()); setNew(document.isNew()); setStore(document.getStore()); setTemplate(document.getTemplate()); setSpace(document.getSpace()); setParent(document.getParent()); setCreator(document.getCreator()); setDefaultLanguage(document.getDefaultLanguage()); setDefaultTemplate(document.getDefaultTemplate()); setValidationScript(document.getValidationScript()); setLanguage(document.getLanguage()); setTranslation(document.getTranslation()); setxWikiClass((BaseClass) document.getxWikiClass().clone()); setxWikiClassXML(document.getxWikiClassXML()); setComment(document.getComment()); setMinorEdit(document.isMinorEdit()); setSyntaxId(document.getSyntaxId()); setSyntaxId(document.getSyntaxId()); clonexWikiObjects(document); copyAttachments(document); this.elements = document.elements; this.originalDocument = document.originalDocument; } @Override public Object clone() { XWikiDocument doc = null; try { doc = getClass().newInstance(); doc.setDatabase(getDatabase()); doc.setRCSVersion(getRCSVersion()); doc.setDocumentArchive(getDocumentArchive()); doc.setAuthor(getAuthor()); doc.setContentAuthor(getContentAuthor()); doc.setContent(getContent()); doc.setContentDirty(isContentDirty()); doc.setCreationDate(getCreationDate()); doc.setDate(getDate()); doc.setCustomClass(getCustomClass()); doc.setContentUpdateDate(getContentUpdateDate()); doc.setTitle(getTitle()); doc.setFormat(getFormat()); doc.setFromCache(isFromCache()); doc.setElements(getElements()); doc.setId(getId()); doc.setMeta(getMeta()); doc.setMetaDataDirty(isMetaDataDirty()); doc.setMostRecent(isMostRecent()); doc.setName(getName()); doc.setNew(isNew()); doc.setStore(getStore()); doc.setTemplate(getTemplate()); doc.setSpace(getSpace()); doc.setParent(getParent()); doc.setCreator(getCreator()); doc.setDefaultLanguage(getDefaultLanguage()); doc.setDefaultTemplate(getDefaultTemplate()); doc.setValidationScript(getValidationScript()); doc.setLanguage(getLanguage()); doc.setTranslation(getTranslation()); doc.setxWikiClass((BaseClass) getxWikiClass().clone()); doc.setxWikiClassXML(getxWikiClassXML()); doc.setComment(getComment()); doc.setMinorEdit(isMinorEdit()); doc.setSyntaxId(getSyntaxId()); doc.clonexWikiObjects(this); doc.copyAttachments(this); doc.elements = this.elements; doc.originalDocument = this.originalDocument; } catch (Exception e) { // This should not happen log.error("Exception while doc.clone", e); } return doc; } public void copyAttachments(XWikiDocument xWikiSourceDocument) { getAttachmentList().clear(); Iterator<XWikiAttachment> attit = xWikiSourceDocument.getAttachmentList().iterator(); while (attit.hasNext()) { XWikiAttachment attachment = attit.next(); XWikiAttachment newattachment = (XWikiAttachment) attachment.clone(); newattachment.setDoc(this); if (newattachment.getAttachment_content() != null) { newattachment.getAttachment_content().setContentDirty(true); } getAttachmentList().add(newattachment); } setContentDirty(true); } public void loadAttachments(XWikiContext context) throws XWikiException { for (XWikiAttachment attachment : getAttachmentList()) { attachment.loadContent(context); attachment.loadArchive(context); } } @Override public boolean equals(Object object) { XWikiDocument doc = (XWikiDocument) object; if (!getName().equals(doc.getName())) { return false; } if (!getSpace().equals(doc.getSpace())) { return false; } if (!getAuthor().equals(doc.getAuthor())) { return false; } if (!getContentAuthor().equals(doc.getContentAuthor())) { return false; } if (!getParent().equals(doc.getParent())) { return false; } if (!getCreator().equals(doc.getCreator())) { return false; } if (!getDefaultLanguage().equals(doc.getDefaultLanguage())) { return false; } if (!getLanguage().equals(doc.getLanguage())) { return false; } if (getTranslation() != doc.getTranslation()) { return false; } if (getDate().getTime() != doc.getDate().getTime()) { return false; } if (getContentUpdateDate().getTime() != doc.getContentUpdateDate().getTime()) { return false; } if (getCreationDate().getTime() != doc.getCreationDate().getTime()) { return false; } if (!getFormat().equals(doc.getFormat())) { return false; } if (!getTitle().equals(doc.getTitle())) { return false; } if (!getContent().equals(doc.getContent())) { return false; } if (!getVersion().equals(doc.getVersion())) { return false; } if (!getTemplate().equals(doc.getTemplate())) { return false; } if (!getDefaultTemplate().equals(doc.getDefaultTemplate())) { return false; } if (!getValidationScript().equals(doc.getValidationScript())) { return false; } if (!getComment().equals(doc.getComment())) { return false; } if (isMinorEdit() != doc.isMinorEdit()) { return false; } if (!getSyntaxId().equals(doc.getSyntaxId())) { return false; } if (!getxWikiClass().equals(doc.getxWikiClass())) { return false; } Set<String> myObjectClassnames = getxWikiObjects().keySet(); Set<String> otherObjectClassnames = doc.getxWikiObjects().keySet(); if (!myObjectClassnames.equals(otherObjectClassnames)) { return false; } for (String name : myObjectClassnames) { Vector<BaseObject> myObjects = getObjects(name); Vector<BaseObject> otherObjects = doc.getObjects(name); if (myObjects.size() != otherObjects.size()) { return false; } for (int i = 0; i < myObjects.size(); i++) { if ((myObjects.get(i) == null) && (otherObjects.get(i) != null)) { return false; } if (!myObjects.get(i).equals(otherObjects.get(i))) { return false; } } } // We consider that 2 documents are still equal even when they have different original // documents (see getOriginalDocument() for more details as to what is an original // document). return true; } public String toXML(Document doc, XWikiContext context) { OutputFormat outputFormat = new OutputFormat("", true); if ((context == null) || (context.getWiki() == null)) { outputFormat.setEncoding("UTF-8"); } else { outputFormat.setEncoding(context.getWiki().getEncoding()); } StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, outputFormat); try { writer.write(doc); return out.toString(); } catch (IOException e) { e.printStackTrace(); return ""; } } public String getXMLContent(XWikiContext context) throws XWikiException { XWikiDocument tdoc = getTranslatedDocument(context); Document doc = tdoc.toXMLDocument(true, true, false, false, context); return toXML(doc, context); } public String toXML(XWikiContext context) throws XWikiException { Document doc = toXMLDocument(context); return toXML(doc, context); } public String toFullXML(XWikiContext context) throws XWikiException { return toXML(true, false, true, true, context); } public void addToZip(ZipOutputStream zos, boolean withVersions, XWikiContext context) throws IOException { try { String zipname = getSpace() + "/" + getName(); String language = getLanguage(); if ((language != null) && (!language.equals(""))) { zipname += "." + language; } ZipEntry zipentry = new ZipEntry(zipname); zos.putNextEntry(zipentry); zos.write(toXML(true, false, true, withVersions, context).getBytes()); zos.closeEntry(); } catch (Exception e) { e.printStackTrace(); } } public void addToZip(ZipOutputStream zos, XWikiContext context) throws IOException { addToZip(zos, true, context); } public String toXML(boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent, boolean bWithVersions, XWikiContext context) throws XWikiException { Document doc = toXMLDocument(bWithObjects, bWithRendering, bWithAttachmentContent, bWithVersions, context); return toXML(doc, context); } public Document toXMLDocument(XWikiContext context) throws XWikiException { return toXMLDocument(true, false, false, false, context); } public Document toXMLDocument(boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent, boolean bWithVersions, XWikiContext context) throws XWikiException { Document doc = new DOMDocument(); Element docel = new DOMElement("xwikidoc"); doc.setRootElement(docel); Element el = new DOMElement("web"); el.addText(getSpace()); docel.add(el); el = new DOMElement("name"); el.addText(getName()); docel.add(el); el = new DOMElement("language"); el.addText(getLanguage()); docel.add(el); el = new DOMElement("defaultLanguage"); el.addText(getDefaultLanguage()); docel.add(el); el = new DOMElement("translation"); el.addText("" + getTranslation()); docel.add(el); el = new DOMElement("parent"); el.addText(getParent()); docel.add(el); el = new DOMElement("creator"); el.addText(getCreator()); docel.add(el); el = new DOMElement("author"); el.addText(getAuthor()); docel.add(el); el = new DOMElement("customClass"); el.addText(getCustomClass()); docel.add(el); el = new DOMElement("contentAuthor"); el.addText(getContentAuthor()); docel.add(el); long d = getCreationDate().getTime(); el = new DOMElement("creationDate"); el.addText("" + d); docel.add(el); d = getDate().getTime(); el = new DOMElement("date"); el.addText("" + d); docel.add(el); d = getContentUpdateDate().getTime(); el = new DOMElement("contentUpdateDate"); el.addText("" + d); docel.add(el); el = new DOMElement("version"); el.addText(getVersion()); docel.add(el); el = new DOMElement("title"); el.addText(getTitle()); docel.add(el); el = new DOMElement("template"); el.addText(getTemplate()); docel.add(el); el = new DOMElement("defaultTemplate"); el.addText(getDefaultTemplate()); docel.add(el); el = new DOMElement("validationScript"); el.addText(getValidationScript()); docel.add(el); el = new DOMElement("comment"); el.addText(getComment()); docel.add(el); el = new DOMElement("minorEdit"); el.addText(String.valueOf(isMinorEdit())); docel.add(el); el = new DOMElement("syntaxId"); el.addText(getSyntaxId()); docel.add(el); for (XWikiAttachment attach : getAttachmentList()) { docel.add(attach.toXML(bWithAttachmentContent, bWithVersions, context)); } if (bWithObjects) { // Add Class BaseClass bclass = getxWikiClass(); if (bclass.getFieldList().size() > 0) { // If the class has fields, add class definition and field information to XML docel.add(bclass.toXML(null)); } // Add Objects (THEIR ORDER IS MOLDED IN STONE!) for (Vector<BaseObject> objects : getxWikiObjects().values()) { for (BaseObject obj : objects) { if (obj != null) { BaseClass objclass = null; if (obj.getName().equals(obj.getClassName())) { objclass = bclass; } else { objclass = obj.getxWikiClass(context); } docel.add(obj.toXML(objclass)); } } } } // Add Content el = new DOMElement("content"); // Filter filter = new CharacterFilter(); // String newcontent = filter.process(getContent()); // String newcontent = encodedXMLStringAsUTF8(getContent()); String newcontent = this.content; el.addText(newcontent); docel.add(el); if (bWithRendering) { el = new DOMElement("renderedcontent"); try { el.addText(getRenderedContent(context)); } catch (XWikiException e) { el.addText("Exception with rendering content: " + e.getFullMessage()); } docel.add(el); } if (bWithVersions) { el = new DOMElement("versions"); try { el.addText(getDocumentArchive(context).getArchive(context)); docel.add(el); } catch (XWikiException e) { log.error("Document [" + this.getFullName() + "] has malformed history"); } } return doc; } protected String encodedXMLStringAsUTF8(String xmlString) { if (xmlString == null) { return ""; } int length = xmlString.length(); char character; StringBuffer result = new StringBuffer(); for (int i = 0; i < length; i++) { character = xmlString.charAt(i); switch (character) { case '&': result.append("&amp;"); break; case '"': result.append("&quot;"); break; case '<': result.append("&lt;"); break; case '>': result.append("&gt;"); break; case '\n': result.append("\n"); break; case '\r': result.append("\r"); break; case '\t': result.append("\t"); break; default: if (character < 0x20) { } else if (character > 0x7F) { result.append("&#x"); result.append(Integer.toHexString(character).toUpperCase()); result.append(";"); } else { result.append(character); } break; } } return result.toString(); } protected String getElement(Element docel, String name) { Element el = docel.element(name); if (el == null) { return ""; } else { return el.getText(); } } public void fromXML(String xml) throws XWikiException { fromXML(xml, false); } public void fromXML(InputStream is) throws XWikiException { fromXML(is, false); } public void fromXML(String xml, boolean withArchive) throws XWikiException { SAXReader reader = new SAXReader(); Document domdoc; try { StringReader in = new StringReader(xml); domdoc = reader.read(in); } catch (DocumentException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null); } fromXML(domdoc, withArchive); } public void fromXML(InputStream in, boolean withArchive) throws XWikiException { SAXReader reader = new SAXReader(); Document domdoc; try { domdoc = reader.read(in); } catch (DocumentException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null); } fromXML(domdoc, withArchive); } public void fromXML(Document domdoc, boolean withArchive) throws XWikiException { Element docel = domdoc.getRootElement(); setName(getElement(docel, "name")); setSpace(getElement(docel, "web")); setParent(getElement(docel, "parent")); setCreator(getElement(docel, "creator")); setAuthor(getElement(docel, "author")); setCustomClass(getElement(docel, "customClass")); setContentAuthor(getElement(docel, "contentAuthor")); if (docel.element("version") != null) { setVersion(getElement(docel, "version")); } setContent(getElement(docel, "content")); setLanguage(getElement(docel, "language")); setDefaultLanguage(getElement(docel, "defaultLanguage")); setTitle(getElement(docel, "title")); setDefaultTemplate(getElement(docel, "defaultTemplate")); setValidationScript(getElement(docel, "validationScript")); setComment(getElement(docel, "comment")); String minorEdit = getElement(docel, "minorEdit"); setMinorEdit(Boolean.valueOf(minorEdit).booleanValue()); String strans = getElement(docel, "translation"); if ((strans == null) || strans.equals("")) { setTranslation(0); } else { setTranslation(Integer.parseInt(strans)); } String archive = getElement(docel, "versions"); if (withArchive && archive != null && archive.length() > 0) { setDocumentArchive(archive); } String sdate = getElement(docel, "date"); if (!sdate.equals("")) { Date date = new Date(Long.parseLong(sdate)); setDate(date); } String scdate = getElement(docel, "creationDate"); if (!scdate.equals("")) { Date cdate = new Date(Long.parseLong(scdate)); setCreationDate(cdate); } String syntaxId = getElement(docel, "syntaxId"); if ((syntaxId == null) || (syntaxId.length() == 0)) { setSyntaxId("xwiki/1.0"); } else { setSyntaxId(syntaxId); } List atels = docel.elements("attachment"); for (int i = 0; i < atels.size(); i++) { Element atel = (Element) atels.get(i); XWikiAttachment attach = new XWikiAttachment(); attach.setDoc(this); attach.fromXML(atel); getAttachmentList().add(attach); } Element cel = docel.element("class"); BaseClass bclass = new BaseClass(); if (cel != null) { bclass.fromXML(cel); setxWikiClass(bclass); } List objels = docel.elements("object"); for (int i = 0; i < objels.size(); i++) { Element objel = (Element) objels.get(i); BaseObject bobject = new BaseObject(); bobject.fromXML(objel); addObject(bobject.getClassName(), bobject); } // We have been reading from XML so the document does not need a new version when saved setMetaDataDirty(false); setContentDirty(false); // Note: We don't set the original document as that is not stored in the XML, and it doesn't make much sense to // have an original document for a de-serialized object. } /** * Check if provided xml document is a wiki document. * * @param domdoc the xml document. * @return true if provided xml document is a wiki document. */ public static boolean containsXMLWikiDocument(Document domdoc) { return domdoc.getRootElement().getName().equals("xwikidoc"); } public void setAttachmentList(List<XWikiAttachment> list) { this.attachmentList = list; } public List<XWikiAttachment> getAttachmentList() { return this.attachmentList; } public void saveAllAttachments(XWikiContext context) throws XWikiException { for (int i = 0; i < this.attachmentList.size(); i++) { saveAttachmentContent(this.attachmentList.get(i), context); } } public void saveAllAttachments(boolean updateParent, boolean transaction, XWikiContext context) throws XWikiException { for (int i = 0; i < this.attachmentList.size(); i++) { saveAttachmentContent(this.attachmentList.get(i), updateParent, transaction, context); } } public void saveAttachmentsContent(List<XWikiAttachment> attachments, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } context.getWiki().getAttachmentStore().saveAttachmentsContent(attachments, this, true, context, true); } catch (java.lang.OutOfMemoryError e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception"); } finally { if (database != null) { context.setDatabase(database); } } } public void saveAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException { saveAttachmentContent(attachment, true, true, context); } protected void saveAttachmentContent(XWikiAttachment attachment, boolean bParentUpdate, boolean bTransaction, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } // We need to make sure there is a version upgrade setMetaDataDirty(true); context.getWiki().getAttachmentStore().saveAttachmentContent(attachment, bParentUpdate, context, bTransaction); } catch (java.lang.OutOfMemoryError e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception"); } finally { if (database != null) { context.setDatabase(database); } } } public void loadAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } context.getWiki().getAttachmentStore().loadAttachmentContent(attachment, context, true); } finally { if (database != null) { context.setDatabase(database); } } } public void deleteAttachment(XWikiAttachment attachment, XWikiContext context) throws XWikiException { deleteAttachment(attachment, true, context); } public void deleteAttachment(XWikiAttachment attachment, boolean toRecycleBin, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } try { // We need to make sure there is a version upgrade setMetaDataDirty(true); if (toRecycleBin && context.getWiki().hasAttachmentRecycleBin(context)) { context.getWiki().getAttachmentRecycleBinStore().saveToRecycleBin(attachment, context.getUser(), new Date(), context, true); } context.getWiki().getAttachmentStore().deleteXWikiAttachment(attachment, context, true); } catch (java.lang.OutOfMemoryError e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception"); } } finally { if (database != null) { context.setDatabase(database); } } } public List getBacklinks(XWikiContext context) throws XWikiException { return getStore(context).loadBacklinks(getFullName(), context, true); } public List getLinks(XWikiContext context) throws XWikiException { return getStore(context).loadLinks(getId(), context, true); } public void renameProperties(String className, Map fieldsToRename) { Vector<BaseObject> objects = getObjects(className); if (objects == null) { return; } for (BaseObject bobject : objects) { if (bobject == null) { continue; } for (Iterator renameit = fieldsToRename.keySet().iterator(); renameit.hasNext();) { String origname = (String) renameit.next(); String newname = (String) fieldsToRename.get(origname); BaseProperty origprop = (BaseProperty) bobject.safeget(origname); if (origprop != null) { BaseProperty prop = (BaseProperty) origprop.clone(); bobject.removeField(origname); prop.setName(newname); bobject.addField(newname, prop); } } } setContentDirty(true); } public void addObjectsToRemove(BaseObject object) { getObjectsToRemove().add(object); setContentDirty(true); } public ArrayList<BaseObject> getObjectsToRemove() { return this.objectsToRemove; } public void setObjectsToRemove(ArrayList<BaseObject> objectsToRemove) { this.objectsToRemove = objectsToRemove; setContentDirty(true); } public List<String> getIncludedPages(XWikiContext context) { try { String pattern = "#include(Topic|InContext|Form|Macros|parseGroovyFromPage)\\([\"'](.*?)[\"']\\)"; List<String> list = context.getUtil().getUniqueMatches(getContent(), pattern, 2); for (int i = 0; i < list.size(); i++) { try { String name = list.get(i); if (name.indexOf(".") == -1) { list.set(i, getSpace() + "." + name); } } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } return list; } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } public List<String> getIncludedMacros(XWikiContext context) { return context.getWiki().getIncludedMacros(getSpace(), getContent(), context); } public List<String> getLinkedPages(XWikiContext context) { try { String pattern = "\\[(.*?)\\]"; List<String> newlist = new ArrayList<String>(); List<String> list = context.getUtil().getUniqueMatches(getContent(), pattern, 1); for (String name : list) { try { int i1 = name.indexOf(">"); if (i1 != -1) { name = name.substring(i1 + 1); } i1 = name.indexOf("&gt;"); if (i1 != -1) { name = name.substring(i1 + 4); } i1 = name.indexOf("#"); if (i1 != -1) { name = name.substring(0, i1); } i1 = name.indexOf("?"); if (i1 != -1) { name = name.substring(0, i1); } // Let's get rid of anything that's not a real link if (name.trim().equals("") || (name.indexOf("$") != -1) || (name.indexOf("://") != -1) || (name.indexOf("\"") != -1) || (name.indexOf("\'") != -1) || (name.indexOf("..") != -1) || (name.indexOf(":") != -1) || (name.indexOf("=") != -1)) { continue; } // generate the link String newname = StringUtils.replace(Util.noaccents(name), " ", ""); // If it is a local link let's add the space if (newname.indexOf(".") == -1) { newname = getSpace() + "." + name; } if (context.getWiki().exists(newname, context)) { name = newname; } else { // If it is a local link let's add the space if (name.indexOf(".") == -1) { name = getSpace() + "." + name; } } // Let's finally ignore the autolinks if (!name.equals(getFullName())) { newlist.add(name); } } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } return newlist; } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } public String displayRendered(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) throws XWikiException { String result = pclass.displayView(pclass.getName(), prefix, object, context); return getRenderedContent(result, context); } public String displayView(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) { return (pclass == null) ? "" : pclass.displayView(pclass.getName(), prefix, object, context); } public String displayEdit(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) { return (pclass == null) ? "" : pclass.displayEdit(pclass.getName(), prefix, object, context); } public String displayHidden(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) { return (pclass == null) ? "" : pclass.displayHidden(pclass.getName(), prefix, object, context); } public String displaySearch(PropertyClass pclass, String prefix, XWikiCriteria criteria, XWikiContext context) { return (pclass == null) ? "" : pclass.displaySearch(pclass.getName(), prefix, criteria, context); } public XWikiAttachment getAttachment(String filename) { for (XWikiAttachment attach : getAttachmentList()) { if (attach.getFilename().equals(filename)) { return attach; } } for (XWikiAttachment attach : getAttachmentList()) { if (attach.getFilename().startsWith(filename + ".")) { return attach; } } return null; } public BaseObject getFirstObject(String fieldname) { // Keeping this function with context null for compatibilit reasons // It should not be used, since it would miss properties which are only defined in the class // and not present in the object because the object was not updated return getFirstObject(fieldname, null); } public BaseObject getFirstObject(String fieldname, XWikiContext context) { Collection<Vector<BaseObject>> objectscoll = getxWikiObjects().values(); if (objectscoll == null) { return null; } for (Vector<BaseObject> objects : objectscoll) { for (BaseObject obj : objects) { if (obj != null) { BaseClass bclass = obj.getxWikiClass(context); if (bclass != null) { Set set = bclass.getPropertyList(); if ((set != null) && set.contains(fieldname)) { return obj; } } Set set = obj.getPropertyList(); if ((set != null) && set.contains(fieldname)) { return obj; } } } } return null; } public void setProperty(String className, String fieldName, BaseProperty value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.safeput(fieldName, value); setContentDirty(true); } public int getIntValue(String className, String fieldName) { BaseObject obj = getObject(className, 0); if (obj == null) { return 0; } return obj.getIntValue(fieldName); } public long getLongValue(String className, String fieldName) { BaseObject obj = getObject(className, 0); if (obj == null) { return 0; } return obj.getLongValue(fieldName); } public String getStringValue(String className, String fieldName) { BaseObject obj = getObject(className); if (obj == null) { return ""; } String result = obj.getStringValue(fieldName); if (result.equals(" ")) { return ""; } else { return result; } } public int getIntValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return 0; } else { return object.getIntValue(fieldName); } } public long getLongValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return 0; } else { return object.getLongValue(fieldName); } } public String getStringValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return ""; } String result = object.getStringValue(fieldName); if (result.equals(" ")) { return ""; } else { return result; } } public void setStringValue(String className, String fieldName, String value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setStringValue(fieldName, value); setContentDirty(true); } public List getListValue(String className, String fieldName) { BaseObject obj = getObject(className); if (obj == null) { return new ArrayList(); } return obj.getListValue(fieldName); } public List getListValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return new ArrayList(); } return object.getListValue(fieldName); } public void setStringListValue(String className, String fieldName, List value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setStringListValue(fieldName, value); setContentDirty(true); } public void setDBStringListValue(String className, String fieldName, List value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setDBStringListValue(fieldName, value); setContentDirty(true); } public void setLargeStringValue(String className, String fieldName, String value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setLargeStringValue(fieldName, value); setContentDirty(true); } public void setIntValue(String className, String fieldName, int value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setIntValue(fieldName, value); setContentDirty(true); } public String getDatabase() { return this.database; } public void setDatabase(String database) { this.database = database; } public void setFullName(String fullname, XWikiContext context) { if (fullname == null) { return; } int i0 = fullname.lastIndexOf(":"); int i1 = fullname.lastIndexOf("."); if (i0 != -1) { setDatabase(fullname.substring(0, i0)); setSpace(fullname.substring(i0 + 1, i1)); setName(fullname.substring(i1 + 1)); } else { if (i1 == -1) { try { setSpace(context.getDoc().getSpace()); } catch (Exception e) { setSpace("XWiki"); } setName(fullname); } else { setSpace(fullname.substring(0, i1)); setName(fullname.substring(i1 + 1)); } } if (getName().equals("")) { setName("WebHome"); } setContentDirty(true); } public String getLanguage() { if (this.language == null) { return ""; } else { return this.language.trim(); } } public void setLanguage(String language) { this.language = language; } public String getDefaultLanguage() { if (this.defaultLanguage == null) { return ""; } else { return this.defaultLanguage.trim(); } } public void setDefaultLanguage(String defaultLanguage) { this.defaultLanguage = defaultLanguage; setMetaDataDirty(true); } public int getTranslation() { return this.translation; } public void setTranslation(int translation) { this.translation = translation; setMetaDataDirty(true); } public String getTranslatedContent(XWikiContext context) throws XWikiException { String language = context.getWiki().getLanguagePreference(context); return getTranslatedContent(language, context); } public String getTranslatedContent(String language, XWikiContext context) throws XWikiException { XWikiDocument tdoc = getTranslatedDocument(language, context); String rev = (String) context.get("rev"); if ((rev == null) || (rev.length() == 0)) { return tdoc.getContent(); } XWikiDocument cdoc = context.getWiki().getDocument(tdoc, rev, context); return cdoc.getContent(); } public XWikiDocument getTranslatedDocument(XWikiContext context) throws XWikiException { String language = context.getWiki().getLanguagePreference(context); return getTranslatedDocument(language, context); } public XWikiDocument getTranslatedDocument(String language, XWikiContext context) throws XWikiException { XWikiDocument tdoc = this; if (!((language == null) || (language.equals("")) || language.equals(this.defaultLanguage))) { tdoc = new XWikiDocument(getSpace(), getName()); tdoc.setLanguage(language); String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } tdoc = getStore(context).loadXWikiDoc(tdoc, context); if (tdoc.isNew()) { tdoc = this; } } catch (Exception e) { tdoc = this; } finally { context.setDatabase(database); } } return tdoc; } public String getRealLanguage(XWikiContext context) throws XWikiException { String lang = getLanguage(); if ((lang.equals("") || lang.equals("default"))) { return getDefaultLanguage(); } else { return lang; } } public String getRealLanguage() { String lang = getLanguage(); if ((lang.equals("") || lang.equals("default"))) { return getDefaultLanguage(); } else { return lang; } } public List<String> getTranslationList(XWikiContext context) throws XWikiException { return getStore().getTranslationList(this, context); } public List<Delta> getXMLDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException, DifferentiationFailedException { return getDeltas(Diff.diff(ToString.stringToArray(fromDoc.toXML(context)), ToString.stringToArray(toDoc .toXML(context)))); } public List<Delta> getContentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException, DifferentiationFailedException { return getDeltas(Diff.diff(ToString.stringToArray(fromDoc.getContent()), ToString.stringToArray(toDoc .getContent()))); } public List<Delta> getContentDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getContentDiff(fromDoc, toDoc, context); } public List<Delta> getContentDiff(String fromRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getContentDiff(revdoc, this, context); } public List<Delta> getLastChanges(XWikiContext context) throws XWikiException, DifferentiationFailedException { Version version = getRCSVersion(); try { String prev = getDocumentArchive(context).getPrevVersion(version).toString(); XWikiDocument prevDoc = context.getWiki().getDocument(this, prev, context); return getDeltas(Diff.diff(ToString.stringToArray(prevDoc.getContent()), ToString .stringToArray(getContent()))); } catch (Exception ex) { log.debug("Exception getting differences from previous version: " + ex.getMessage()); } return new ArrayList<Delta>(); } public List<Delta> getRenderedContentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException, DifferentiationFailedException { String originalContent, newContent; originalContent = context.getWiki().getRenderingEngine().renderText(fromDoc.getContent(), fromDoc, context); newContent = context.getWiki().getRenderingEngine().renderText(toDoc.getContent(), toDoc, context); return getDeltas(Diff.diff(ToString.stringToArray(originalContent), ToString.stringToArray(newContent))); } public List<Delta> getRenderedContentDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getRenderedContentDiff(fromDoc, toDoc, context); } public List<Delta> getRenderedContentDiff(String fromRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getRenderedContentDiff(revdoc, this, context); } protected List<Delta> getDeltas(Revision rev) { List<Delta> list = new ArrayList<Delta>(); for (int i = 0; i < rev.size(); i++) { list.add(rev.getDelta(i)); } return list; } public List<MetaDataDiff> getMetaDataDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getMetaDataDiff(fromDoc, toDoc, context); } public List<MetaDataDiff> getMetaDataDiff(String fromRev, XWikiContext context) throws XWikiException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getMetaDataDiff(revdoc, this, context); } public List<MetaDataDiff> getMetaDataDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { List<MetaDataDiff> list = new ArrayList<MetaDataDiff>(); if ((fromDoc == null) || (toDoc == null)) { return list; } if (!fromDoc.getParent().equals(toDoc.getParent())) { list.add(new MetaDataDiff("parent", fromDoc.getParent(), toDoc.getParent())); } if (!fromDoc.getAuthor().equals(toDoc.getAuthor())) { list.add(new MetaDataDiff("author", fromDoc.getAuthor(), toDoc.getAuthor())); } if (!fromDoc.getSpace().equals(toDoc.getSpace())) { list.add(new MetaDataDiff("web", fromDoc.getSpace(), toDoc.getSpace())); } if (!fromDoc.getName().equals(toDoc.getName())) { list.add(new MetaDataDiff("name", fromDoc.getName(), toDoc.getName())); } if (!fromDoc.getLanguage().equals(toDoc.getLanguage())) { list.add(new MetaDataDiff("language", fromDoc.getLanguage(), toDoc.getLanguage())); } if (!fromDoc.getDefaultLanguage().equals(toDoc.getDefaultLanguage())) { list.add(new MetaDataDiff("defaultLanguage", fromDoc.getDefaultLanguage(), toDoc.getDefaultLanguage())); } return list; } public List<List<ObjectDiff>> getObjectDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getObjectDiff(fromDoc, toDoc, context); } public List<List<ObjectDiff>> getObjectDiff(String fromRev, XWikiContext context) throws XWikiException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getObjectDiff(revdoc, this, context); } /** * Return the object differences between two document versions. There is no hard requirement on the order of the two * versions, but the results are semantically correct only if the two versions are given in the right order. * * @param fromDoc The old ('before') version of the document. * @param toDoc The new ('after') version of the document. * @param context The {@link com.xpn.xwiki.XWikiContext context}. * @return The object differences. The returned list's elements are other lists, one for each changed object. The * inner lists contain {@link ObjectDiff} elements, one object for each changed property of the object. * Additionally, if the object was added or removed, then the first entry in the list will be an * "object-added" or "object-removed" marker. * @throws XWikiException If there's an error computing the differences. */ public List<List<ObjectDiff>> getObjectDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { ArrayList<List<ObjectDiff>> difflist = new ArrayList<List<ObjectDiff>>(); // Since objects could have been deleted or added, we iterate on both the old and the new // object collections. // First, iterate over the old objects. for (Vector<BaseObject> objects : fromDoc.getxWikiObjects().values()) { for (BaseObject originalObj : objects) { // This happens when objects are deleted, and the document is still in the cache // storage. if (originalObj != null) { BaseObject newObj = toDoc.getObject(originalObj.getClassName(), originalObj.getNumber()); List<ObjectDiff> dlist; if (newObj == null) { // The object was deleted. dlist = new BaseObject().getDiff(originalObj, context); ObjectDiff deleteMarker = new ObjectDiff(originalObj.getClassName(), originalObj.getNumber(), "object-removed", "", "", ""); dlist.add(0, deleteMarker); } else { // The object exists in both versions, but might have been changed. dlist = newObj.getDiff(originalObj, context); } if (dlist.size() > 0) { difflist.add(dlist); } } } } // Second, iterate over the objects which are only in the new version. for (Vector<BaseObject> objects : toDoc.getxWikiObjects().values()) { for (BaseObject newObj : objects) { // This happens when objects are deleted, and the document is still in the cache // storage. if (newObj != null) { BaseObject originalObj = fromDoc.getObject(newObj.getClassName(), newObj.getNumber()); if (originalObj == null) { // Only consider added objects, the other case was treated above. originalObj = new BaseObject(); originalObj.setClassName(newObj.getClassName()); originalObj.setNumber(newObj.getNumber()); List<ObjectDiff> dlist = newObj.getDiff(originalObj, context); ObjectDiff addMarker = new ObjectDiff(newObj.getClassName(), newObj.getNumber(), "object-added", "", "", ""); dlist.add(0, addMarker); if (dlist.size() > 0) { difflist.add(dlist); } } } } } return difflist; } public List<List<ObjectDiff>> getClassDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { ArrayList<List<ObjectDiff>> difflist = new ArrayList<List<ObjectDiff>>(); BaseClass oldClass = fromDoc.getxWikiClass(); BaseClass newClass = toDoc.getxWikiClass(); if ((newClass == null) && (oldClass == null)) { return difflist; } List<ObjectDiff> dlist = newClass.getDiff(oldClass, context); if (dlist.size() > 0) { difflist.add(dlist); } return difflist; } /** * @param fromDoc * @param toDoc * @param context * @return * @throws XWikiException */ public List<AttachmentDiff> getAttachmentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { List<AttachmentDiff> difflist = new ArrayList<AttachmentDiff>(); for (XWikiAttachment origAttach : fromDoc.getAttachmentList()) { String fileName = origAttach.getFilename(); XWikiAttachment newAttach = toDoc.getAttachment(fileName); if (newAttach == null) { difflist.add(new AttachmentDiff(fileName, origAttach.getVersion(), null)); } else { if (!origAttach.getVersion().equals(newAttach.getVersion())) { difflist.add(new AttachmentDiff(fileName, origAttach.getVersion(), newAttach.getVersion())); } } } for (XWikiAttachment newAttach : toDoc.getAttachmentList()) { String fileName = newAttach.getFilename(); XWikiAttachment origAttach = fromDoc.getAttachment(fileName); if (origAttach == null) { difflist.add(new AttachmentDiff(fileName, null, newAttach.getVersion())); } } return difflist; } /** * Rename the current document and all the backlinks leading to it. See * {@link #rename(String, java.util.List, com.xpn.xwiki.XWikiContext)} for more details. * * @param newDocumentName the new document name. If the space is not specified then defaults to the current space. * @param context the ubiquitous XWiki Context * @throws XWikiException in case of an error */ public void rename(String newDocumentName, XWikiContext context) throws XWikiException { rename(newDocumentName, getBacklinks(context), context); } /** * Rename the current document and all the links pointing to it in the list of passed backlink documents. The * renaming algorithm takes into account the fact that there are several ways to write a link to a given page and * all those forms need to be renamed. For example the following links all point to the same page: * <ul> * <li>[Page]</li> * <li>[Page?param=1]</li> * <li>[currentwiki:Page]</li> * <li>[CurrentSpace.Page]</li> * </ul> * <p> * Note: links without a space are renamed with the space added. * </p> * * @param newDocumentName the new document name. If the space is not specified then defaults to the current space. * @param backlinkDocumentNames the list of documents to parse and for which links will be modified to point to the * new renamed document. * @param context the ubiquitous XWiki Context * @throws XWikiException in case of an error */ public void rename(String newDocumentName, List<String> backlinkDocumentNames, XWikiContext context) throws XWikiException { // TODO: Do all this in a single DB transaction as otherwise the state will be unknown if // something fails in the middle... if (isNew()) { return; } // This link handler recognizes that 2 links are the same when they point to the same // document (regardless of query string, target or alias). It keeps the query string, // target and alias from the link being replaced. RenamePageReplaceLinkHandler linkHandler = new RenamePageReplaceLinkHandler(); // Transform string representation of old and new links so that they can be manipulated. Link oldLink = new LinkParser().parse(getFullName()); Link newLink = new LinkParser().parse(newDocumentName); // Verify if the user is trying to rename to the same name... In that case, simply exits // for efficiency. if (linkHandler.compare(newLink, oldLink)) { return; } // Step 1: Copy the document under a new name context.getWiki().copyDocument(getFullName(), newDocumentName, false, context); // Step 2: For each backlink to rename, parse the backlink document and replace the links // with the new name. // Note: we ignore invalid links here. Invalid links should be shown to the user so // that they fix them but the rename feature ignores them. DocumentParser documentParser = new DocumentParser(); for (String backlinkDocumentName : backlinkDocumentNames) { XWikiDocument backlinkDocument = context.getWiki().getDocument(backlinkDocumentName, context); // Note: Here we cannot do a simple search/replace as there are several ways to point // to the same document. For example [Page], [Page?param=1], [currentwiki:Page], // [CurrentSpace.Page] all point to the same document. Thus we have to parse the links // to recognize them and do the replace. ReplacementResultCollection result = documentParser.parseLinksAndReplace(backlinkDocument.getContent(), oldLink, newLink, linkHandler, getSpace()); backlinkDocument.setContent((String) result.getModifiedContent()); context.getWiki().saveDocument(backlinkDocument, context.getMessageTool().get("core.comment.renameLink", Arrays.asList(new String[] {newDocumentName})), true, context); } // Step 3: Delete the old document context.getWiki().deleteDocument(this, context); // Step 4: The current document needs to point to the renamed document as otherwise it's // pointing to an invalid XWikiDocument object as it's been deleted... clone(context.getWiki().getDocument(newDocumentName, context)); } public XWikiDocument copyDocument(String newDocumentName, XWikiContext context) throws XWikiException { String oldname = getFullName(); loadAttachments(context); loadArchive(context); /* * if (oldname.equals(docname)) return this; */ XWikiDocument newdoc = (XWikiDocument) clone(); newdoc.setFullName(newDocumentName, context); newdoc.setContentDirty(true); newdoc.getxWikiClass().setName(newDocumentName); Vector<BaseObject> objects = newdoc.getObjects(oldname); if (objects != null) { for (BaseObject object : objects) { object.setName(newDocumentName); } } XWikiDocumentArchive archive = newdoc.getDocumentArchive(); if (archive != null) { newdoc.setDocumentArchive(archive.clone(newdoc.getId(), context)); } return newdoc; } public XWikiLock getLock(XWikiContext context) throws XWikiException { XWikiLock theLock = getStore(context).loadLock(getId(), context, true); if (theLock != null) { int timeout = context.getWiki().getXWikiPreferenceAsInt("lock_Timeout", 30 * 60, context); if (theLock.getDate().getTime() + timeout * 1000 < new Date().getTime()) { getStore(context).deleteLock(theLock, context, true); theLock = null; } } return theLock; } public void setLock(String userName, XWikiContext context) throws XWikiException { XWikiLock lock = new XWikiLock(getId(), userName); getStore(context).saveLock(lock, context, true); } public void removeLock(XWikiContext context) throws XWikiException { XWikiLock lock = getStore(context).loadLock(getId(), context, true); if (lock != null) { getStore(context).deleteLock(lock, context, true); } } public void insertText(String text, String marker, XWikiContext context) throws XWikiException { setContent(StringUtils.replaceOnce(getContent(), marker, text + marker)); context.getWiki().saveDocument(this, context); } public Object getWikiNode() { return this.wikiNode; } public void setWikiNode(Object wikiNode) { this.wikiNode = wikiNode; } public String getxWikiClassXML() { return this.xWikiClassXML; } public void setxWikiClassXML(String xWikiClassXML) { this.xWikiClassXML = xWikiClassXML; } public int getElements() { return this.elements; } public void setElements(int elements) { this.elements = elements; } public void setElement(int element, boolean toggle) { if (toggle) { this.elements = this.elements | element; } else { this.elements = this.elements & (~element); } } public boolean hasElement(int element) { return ((this.elements & element) == element); } public String getDefaultEditURL(XWikiContext context) throws XWikiException { com.xpn.xwiki.XWiki xwiki = context.getWiki(); if (getContent().indexOf("includeForm(") != -1) { return getEditURL("inline", "", context); } else { String editor = xwiki.getEditorPreference(context); return getEditURL("edit", editor, context); } } public String getEditURL(String action, String mode, XWikiContext context) throws XWikiException { com.xpn.xwiki.XWiki xwiki = context.getWiki(); String language = ""; XWikiDocument tdoc = (XWikiDocument) context.get("tdoc"); String realLang = tdoc.getRealLanguage(context); if ((xwiki.isMultiLingual(context) == true) && (!realLang.equals(""))) { language = realLang; } return getEditURL(action, mode, language, context); } public String getEditURL(String action, String mode, String language, XWikiContext context) { StringBuffer editparams = new StringBuffer(); if (!mode.equals("")) { editparams.append("xpage="); editparams.append(mode); } if (!language.equals("")) { if (!mode.equals("")) { editparams.append("&"); } editparams.append("language="); editparams.append(language); } return getURL(action, editparams.toString(), context); } public String getDefaultTemplate() { if (this.defaultTemplate == null) { return ""; } else { return this.defaultTemplate; } } public void setDefaultTemplate(String defaultTemplate) { this.defaultTemplate = defaultTemplate; setMetaDataDirty(true); } public Vector<BaseObject> getComments() { return getComments(true); } /** * @return the Syntax id representing the syntax used for the current document. For example "xwiki/1.0" represents * the first version XWiki syntax while "xwiki/2.0" represents version 2.0 of the XWiki Syntax. */ public String getSyntaxId() { String result; if ((this.syntaxId == null) || (this.syntaxId.length() == 0)) { result = "xwiki/1.0"; } else { result = this.syntaxId; } return result; } /** * @param syntaxId the new syntax id to set (eg "xwiki/1.0", "xwiki/2.0", etc) * @see #getSyntaxId() */ public void setSyntaxId(String syntaxId) { this.syntaxId = syntaxId; } public Vector<BaseObject> getComments(boolean asc) { if (asc) { return getObjects("XWiki.XWikiComments"); } else { Vector<BaseObject> list = getObjects("XWiki.XWikiComments"); if (list == null) { return list; } Vector<BaseObject> newlist = new Vector<BaseObject>(); for (int i = list.size() - 1; i >= 0; i--) { newlist.add(list.get(i)); } return newlist; } } public boolean isCurrentUserCreator(XWikiContext context) { return isCreator(context.getUser()); } public boolean isCreator(String username) { if (username.equals("XWiki.XWikiGuest")) { return false; } return username.equals(getCreator()); } public boolean isCurrentUserPage(XWikiContext context) { String username = context.getUser(); if (username.equals("XWiki.XWikiGuest")) { return false; } return context.getUser().equals(getFullName()); } public boolean isCurrentLocalUserPage(XWikiContext context) { String username = context.getLocalUser(); if (username.equals("XWiki.XWikiGuest")) { return false; } return context.getUser().equals(getFullName()); } public void resetArchive(XWikiContext context) throws XWikiException { boolean hasVersioning = context.getWiki().hasVersioning(getFullName(), context); if (hasVersioning) { getVersioningStore(context).resetRCSArchive(this, true, context); } } // This functions adds an object from an new object creation form public BaseObject addObjectFromRequest(XWikiContext context) throws XWikiException { // Read info in object ObjectAddForm form = new ObjectAddForm(); form.setRequest((HttpServletRequest) context.getRequest()); form.readRequest(); String className = form.getClassName(); int nb = createNewObject(className, context); BaseObject oldobject = getObject(className, nb); BaseClass baseclass = oldobject.getxWikiClass(context); BaseObject newobject = (BaseObject) baseclass.fromMap(form.getObject(className), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setName(getFullName()); setObject(className, nb, newobject); return newobject; } // This functions adds an object from an new object creation form public BaseObject addObjectFromRequest(String className, XWikiContext context) throws XWikiException { return addObjectFromRequest(className, "", 0, context); } // This functions adds an object from an new object creation form public BaseObject addObjectFromRequest(String className, String prefix, XWikiContext context) throws XWikiException { return addObjectFromRequest(className, prefix, 0, context); } // This functions adds multiple objects from an new objects creation form public List<BaseObject> addObjectsFromRequest(String className, XWikiContext context) throws XWikiException { return addObjectsFromRequest(className, "", context); } // This functions adds multiple objects from an new objects creation form public List<BaseObject> addObjectsFromRequest(String className, String pref, XWikiContext context) throws XWikiException { Map map = context.getRequest().getParameterMap(); List<Integer> objectsNumberDone = new ArrayList<Integer>(); List<BaseObject> objects = new ArrayList<BaseObject>(); Iterator it = map.keySet().iterator(); String start = pref + className + "_"; while (it.hasNext()) { String name = (String) it.next(); if (name.startsWith(start)) { int pos = name.indexOf("_", start.length() + 1); String prefix = name.substring(0, pos); int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue(); if (!objectsNumberDone.contains(new Integer(num))) { objectsNumberDone.add(new Integer(num)); objects.add(addObjectFromRequest(className, pref, num, context)); } } } return objects; } // This functions adds object from an new object creation form public BaseObject addObjectFromRequest(String className, int num, XWikiContext context) throws XWikiException { return addObjectFromRequest(className, "", num, context); } // This functions adds object from an new object creation form public BaseObject addObjectFromRequest(String className, String prefix, int num, XWikiContext context) throws XWikiException { int nb = createNewObject(className, context); BaseObject oldobject = getObject(className, nb); BaseClass baseclass = oldobject.getxWikiClass(context); BaseObject newobject = (BaseObject) baseclass.fromMap(Util.getObject(context.getRequest(), prefix + className + "_" + num), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setName(getFullName()); setObject(className, nb, newobject); return newobject; } // This functions adds an object from an new object creation form public BaseObject updateObjectFromRequest(String className, XWikiContext context) throws XWikiException { return updateObjectFromRequest(className, "", context); } // This functions adds an object from an new object creation form public BaseObject updateObjectFromRequest(String className, String prefix, XWikiContext context) throws XWikiException { return updateObjectFromRequest(className, prefix, 0, context); } // This functions adds an object from an new object creation form public BaseObject updateObjectFromRequest(String className, String prefix, int num, XWikiContext context) throws XWikiException { int nb; BaseObject oldobject = getObject(className, num); if (oldobject == null) { nb = createNewObject(className, context); oldobject = getObject(className, nb); } else { nb = oldobject.getNumber(); } BaseClass baseclass = oldobject.getxWikiClass(context); BaseObject newobject = (BaseObject) baseclass.fromMap(Util.getObject(context.getRequest(), prefix + className + "_" + nb), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setName(getFullName()); setObject(className, nb, newobject); return newobject; } // This functions adds an object from an new object creation form public List updateObjectsFromRequest(String className, XWikiContext context) throws XWikiException { return updateObjectsFromRequest(className, "", context); } // This functions adds multiple objects from an new objects creation form public List<BaseObject> updateObjectsFromRequest(String className, String pref, XWikiContext context) throws XWikiException { Map map = context.getRequest().getParameterMap(); List<Integer> objectsNumberDone = new ArrayList<Integer>(); List<BaseObject> objects = new ArrayList<BaseObject>(); Iterator it = map.keySet().iterator(); String start = pref + className + "_"; while (it.hasNext()) { String name = (String) it.next(); if (name.startsWith(start)) { int pos = name.indexOf("_", start.length() + 1); String prefix = name.substring(0, pos); int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue(); if (!objectsNumberDone.contains(new Integer(num))) { objectsNumberDone.add(new Integer(num)); objects.add(updateObjectFromRequest(className, pref, num, context)); } } } return objects; } public boolean isAdvancedContent() { String[] matches = {"<%", "#set", "#include", "#if", "public class", "/* Advanced content */", "## Advanced content", "/* Programmatic content */", "## Programmatic content"}; String content2 = this.content.toLowerCase(); for (int i = 0; i < matches.length; i++) { if (content2.indexOf(matches[i].toLowerCase()) != -1) { return true; } } if (HTML_TAG_PATTERN.matcher(content2).find()) { return true; } return false; } public boolean isProgrammaticContent() { String[] matches = {"<%", "\\$xwiki.xWiki", "$context.context", "$doc.document", "$xwiki.getXWiki()", "$context.getContext()", "$doc.getDocument()", "WithProgrammingRights(", "/* Programmatic content */", "## Programmatic content", "$xwiki.search(", "$xwiki.createUser", "$xwiki.createNewWiki", "$xwiki.addToAllGroup", "$xwiki.sendMessage", "$xwiki.copyDocument", "$xwiki.copyWikiWeb", "$xwiki.parseGroovyFromString", "$doc.toXML()", "$doc.toXMLDocument()",}; String content2 = this.content.toLowerCase(); for (int i = 0; i < matches.length; i++) { if (content2.indexOf(matches[i].toLowerCase()) != -1) { return true; } } return false; } public boolean removeObject(BaseObject bobj) { Vector<BaseObject> objects = getObjects(bobj.getClassName()); if (objects == null) { return false; } if (objects.elementAt(bobj.getNumber()) == null) { return false; } objects.set(bobj.getNumber(), null); addObjectsToRemove(bobj); return true; } /** * Remove all the objects of a given type (XClass) from the document. * * @param className The class name of the objects to be removed. */ public boolean removeObjects(String className) { Vector<BaseObject> objects = getObjects(className); if (objects == null) { return false; } Iterator<BaseObject> it = objects.iterator(); while (it.hasNext()) { BaseObject bobj = it.next(); if (bobj != null) { objects.set(bobj.getNumber(), null); addObjectsToRemove(bobj); } } return true; } // This method to split section according to title . public List<DocumentSection> getSplitSectionsAccordingToTitle() throws XWikiException { // Pattern to match the title. Matches only level 1 and level 2 headings. Pattern headingPattern = Pattern.compile("^[ \\t]*+(1(\\.1){0,1}+)[ \\t]++(.++)$", Pattern.MULTILINE); Matcher matcher = headingPattern.matcher(getContent()); List<DocumentSection> splitSections = new ArrayList<DocumentSection>(); int sectionNumber = 0; // find title to split while (matcher.find()) { ++sectionNumber; String sectionLevel = matcher.group(1); String sectionTitle = matcher.group(3); int sectionIndex = matcher.start(); // Initialize a documentSection object. DocumentSection docSection = new DocumentSection(sectionNumber, sectionIndex, sectionLevel, sectionTitle); // Add the document section to list. splitSections.add(docSection); } return splitSections; } // This function to return a Document section with parameter is sectionNumber public DocumentSection getDocumentSection(int sectionNumber) throws XWikiException { // return a document section according to section number return getSplitSectionsAccordingToTitle().get(sectionNumber - 1); } // This method to return the content of a section public String getContentOfSection(int sectionNumber) throws XWikiException { List<DocumentSection> splitSections = getSplitSectionsAccordingToTitle(); int indexEnd = 0; // get current section DocumentSection section = splitSections.get(sectionNumber - 1); int indexStart = section.getSectionIndex(); String sectionLevel = section.getSectionLevel(); // Determine where this section ends, which is at the start of the next section of the // same or a higher level. for (int i = sectionNumber; i < splitSections.size(); i++) { DocumentSection nextSection = splitSections.get(i); String nextLevel = nextSection.getSectionLevel(); if (sectionLevel.equals(nextLevel) || sectionLevel.length() > nextLevel.length()) { indexEnd = nextSection.getSectionIndex(); break; } } String sectionContent = null; if (indexStart < 0) { indexStart = 0; } if (indexEnd == 0) { sectionContent = getContent().substring(indexStart); } else { sectionContent = getContent().substring(indexStart, indexEnd); } return sectionContent; } // This function to update a section content in document public String updateDocumentSection(int sectionNumber, String newSectionContent) throws XWikiException { StringBuffer newContent = new StringBuffer(); // get document section that will be edited DocumentSection docSection = getDocumentSection(sectionNumber); int numberOfSections = getSplitSectionsAccordingToTitle().size(); int indexSection = docSection.getSectionIndex(); if (numberOfSections == 1) { // there is only a sections in document String contentBegin = getContent().substring(0, indexSection); newContent = newContent.append(contentBegin).append(newSectionContent); return newContent.toString(); } else if (sectionNumber == numberOfSections) { // edit lastest section that doesn't contain subtitle String contentBegin = getContent().substring(0, indexSection); newContent = newContent.append(contentBegin).append(newSectionContent); return newContent.toString(); } else { String sectionLevel = docSection.getSectionLevel(); int nextSectionIndex = 0; // get index of next section for (int i = sectionNumber; i < numberOfSections; i++) { DocumentSection nextSection = getDocumentSection(i + 1); // get next section String nextSectionLevel = nextSection.getSectionLevel(); if (sectionLevel.equals(nextSectionLevel)) { nextSectionIndex = nextSection.getSectionIndex(); break; } else if (sectionLevel.length() > nextSectionLevel.length()) { nextSectionIndex = nextSection.getSectionIndex(); break; } } if (nextSectionIndex == 0) {// edit the last section newContent = newContent.append(getContent().substring(0, indexSection)).append(newSectionContent); return newContent.toString(); } else { String contentAfter = getContent().substring(nextSectionIndex); String contentBegin = getContent().substring(0, indexSection); newContent = newContent.append(contentBegin).append(newSectionContent).append(contentAfter); } return newContent.toString(); } } /** * Computes a document hash, taking into account all document data: content, objects, attachments, metadata... TODO: * cache the hash value, update only on modification. */ public String getVersionHashCode(XWikiContext context) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { log.error("Cannot create MD5 object", ex); return this.hashCode() + ""; } try { String valueBeforeMD5 = toXML(true, false, true, false, context); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b)); } return sb.toString(); } catch (Exception ex) { log.error("Exception while computing document hash", ex); } return this.hashCode() + ""; } public static String getInternalPropertyName(String propname, XWikiContext context) { XWikiMessageTool msg = context.getMessageTool(); String cpropname = StringUtils.capitalize(propname); return (msg == null) ? cpropname : msg.get(cpropname); } public String getInternalProperty(String propname) { String methodName = "get" + StringUtils.capitalize(propname); try { Method method = getClass().getDeclaredMethod(methodName, (Class[]) null); return (String) method.invoke(this, (Object[]) null); } catch (Exception e) { return null; } } public String getCustomClass() { if (this.customClass == null) { return ""; } return this.customClass; } public void setCustomClass(String customClass) { this.customClass = customClass; setMetaDataDirty(true); } public void setValidationScript(String validationScript) { this.validationScript = validationScript; setMetaDataDirty(true); } public String getValidationScript() { if (this.validationScript == null) { return ""; } else { return this.validationScript; } } public String getComment() { if (this.comment == null) { return ""; } return this.comment; } public void setComment(String comment) { this.comment = comment; } public boolean isMinorEdit() { return this.isMinorEdit; } public void setMinorEdit(boolean isMinor) { this.isMinorEdit = isMinor; } // methods for easy table update. It is need only for hibernate. // when hibernate update old database without minorEdit field, hibernate will create field with // null in despite of notnull in hbm. // (http://opensource.atlassian.com/projects/hibernate/browse/HB-1151) // so minorEdit will be null for old documents. But hibernate can't convert null to boolean. // so we need convert Boolean to boolean protected Boolean getMinorEdit1() { return Boolean.valueOf(this.isMinorEdit); } protected void setMinorEdit1(Boolean isMinor) { this.isMinorEdit = (isMinor != null && isMinor.booleanValue()); } public BaseObject newObject(String classname, XWikiContext context) throws XWikiException { int nb = createNewObject(classname, context); return getObject(classname, nb); } public BaseObject getObject(String classname, boolean create, XWikiContext context) { try { BaseObject obj = getObject(classname); if ((obj == null) && create) { return newObject(classname, context); } if (obj == null) { return null; } else { return obj; } } catch (Exception e) { return null; } } public boolean validate(XWikiContext context) throws XWikiException { return validate(null, context); } public boolean validate(String[] classNames, XWikiContext context) throws XWikiException { boolean isValid = true; if ((classNames == null) || (classNames.length == 0)) { for (String classname : getxWikiObjects().keySet()) { BaseClass bclass = context.getWiki().getClass(classname, context); Vector<BaseObject> objects = getObjects(classname); for (BaseObject obj : objects) { if (obj != null) { isValid &= bclass.validateObject(obj, context); } } } } else { for (int i = 0; i < classNames.length; i++) { Vector<BaseObject> objects = getObjects(classNames[i]); if (objects != null) { for (BaseObject obj : objects) { if (obj != null) { BaseClass bclass = obj.getxWikiClass(context); isValid &= bclass.validateObject(obj, context); } } } } } String validationScript = ""; XWikiRequest req = context.getRequest(); if (req != null) { validationScript = req.get("xvalidation"); } if ((validationScript == null) || (validationScript.trim().equals(""))) { validationScript = getValidationScript(); } if ((validationScript != null) && (!validationScript.trim().equals(""))) { isValid &= executeValidationScript(context, validationScript); } return isValid; } private boolean executeValidationScript(XWikiContext context, String validationScript) throws XWikiException { try { XWikiValidationInterface validObject = (XWikiValidationInterface) context.getWiki().parseGroovyFromPage(validationScript, context); return validObject.validateDocument(this, context); } catch (Throwable e) { XWikiValidationStatus.addExceptionToContext(getFullName(), "", e, context); return false; } } public static void backupContext(HashMap<String, Object> backup, XWikiContext context) { backup.put("doc", context.getDoc()); VelocityContext vcontext = (VelocityContext) context.get("vcontext"); if (vcontext != null) { backup.put("vdoc", vcontext.get("doc")); backup.put("vcdoc", vcontext.get("cdoc")); backup.put("vtdoc", vcontext.get("tdoc")); } Map gcontext = (Map) context.get("gcontext"); if (gcontext != null) { backup.put("gdoc", gcontext.get("doc")); backup.put("gcdoc", gcontext.get("cdoc")); backup.put("gtdoc", gcontext.get("tdoc")); } } public static void restoreContext(HashMap<String, Object> backup, XWikiContext context) { context.setDoc((XWikiDocument) backup.get("doc")); VelocityContext vcontext = (VelocityContext) context.get("vcontext"); Map gcontext = (Map) context.get("gcontext"); if (vcontext != null) { if (backup.get("vdoc") != null) { vcontext.put("doc", backup.get("vdoc")); } if (backup.get("vcdoc") != null) { vcontext.put("cdoc", backup.get("vcdoc")); } if (backup.get("vtdoc") != null) { vcontext.put("tdoc", backup.get("vtdoc")); } } if (gcontext != null) { if (backup.get("gdoc") != null) { gcontext.put("doc", backup.get("gdoc")); } if (backup.get("gcdoc") != null) { gcontext.put("cdoc", backup.get("gcdoc")); } if (backup.get("gtdoc") != null) { gcontext.put("tdoc", backup.get("gtdoc")); } } } public void setAsContextDoc(XWikiContext context) { try { context.setDoc(this); com.xpn.xwiki.api.Document apidoc = this.newDocument(context); com.xpn.xwiki.api.Document tdoc = apidoc.getTranslatedDocument(); VelocityContext vcontext = (VelocityContext) context.get("vcontext"); Map gcontext = (Map) context.get("gcontext"); if (vcontext != null) { vcontext.put("doc", apidoc); vcontext.put("tdoc", tdoc); } if (gcontext != null) { gcontext.put("doc", apidoc); gcontext.put("tdoc", tdoc); } } catch (XWikiException ex) { log.warn("Unhandled exception setting context", ex); } } public String getPreviousVersion() { return getDocumentArchive().getPrevVersion(this.version).toString(); } @Override public String toString() { return getFullName(); } }
XWIKI-2457: Rename the internal field XWikiDocument.web to XWikiDocument.space Done. git-svn-id: cfa2b40e478804c47c05d0f328c574ec5aa2b82e@10273 f329d543-caf0-0310-9063-dda96c69346f
xwiki-core/src/main/java/com/xpn/xwiki/doc/XWikiDocument.java
XWIKI-2457: Rename the internal field XWikiDocument.web to XWikiDocument.space Done.
<ide><path>wiki-core/src/main/java/com/xpn/xwiki/doc/XWikiDocument.java <ide> <ide> private String parent; <ide> <del> private String web; <add> private String space; <ide> <ide> private String name; <ide> <ide> */ <ide> public String getSpace() <ide> { <del> return this.web; <add> return this.space; <ide> } <ide> <ide> public void setSpace(String space) <ide> { <del> this.web = space; <add> this.space = space; <ide> } <ide> <ide> public String getVersion()
Java
mit
9e5532a7ea2f73d164e8b0dd1a79ee2912f8b9f5
0
aroelke/deck-editor-java
package editor.database.characteristics; import org.apache.commons.codec.binary.Base32; /** * This enum represents a rarity a Magic: The Gathering card can have. Rarities * are basically Strings, so they implement {@link CharSequence}. All of the * implemented methods operate on a Rarity's String representation from * {@link #toString()}. * * @author Alec Roelke */ public enum Rarity implements CharSequence { /** * Rarity for basic lands. */ BASIC_LAND("Basic Land"), /** * Common rarity. */ COMMON("Common"), /** * Uncommon rarity. */ UNCOMMON("Uncommon"), /** * Rare rarity. */ RARE("Rare"), /** * Mythic rare rarity. */ MYTHIC_RARE("Mythic Rare"), /** * "Special" rarity, such as timeshifted. */ SPECIAL("Special"); /** * Create a rarity from a shorthand character. * * @param rarity Character to create a Rarity from * @return a Rarity representing the specified shorthand character * @throws IllegalArgumentException if a Rarity cannot be created from the specified character */ public static Rarity parseRarity(char rarity) { return switch (Character.toLowerCase(rarity)) { case 'c' -> COMMON; case 'u' -> UNCOMMON; case 'r' -> RARE; case 'm' -> MYTHIC_RARE; case 's' -> SPECIAL; case 'b' -> BASIC_LAND; default -> throw new IllegalArgumentException("Illegal rarity shorthand"); }; } /** * Create a Rarity from the specified String. * * @param rarity String to create a Rarity from * @return a Rarity representing the specified String * @throws IllegalArgumentException if a Rarity cannot be created from the String */ public static Rarity parseRarity(String rarity) { if (rarity.contains("mythic")) return MYTHIC_RARE; else if (rarity.contains("rare")) return RARE; else if (rarity.contains("uncommon")) return UNCOMMON; else if (rarity.contains("common")) return COMMON; else if (rarity.contains("basic")) return BASIC_LAND; else { System.err.println("warning: Could not determine rarity of \"" + rarity + '"'); return SPECIAL; } } /** * String representation of this Rarity. */ private final String rarity; /** * Create a new Rarity. * * @param rarity String representation of the new Rarity. */ Rarity(final String rarity) { this.rarity = rarity; } @Override public char charAt(int index) { return rarity.charAt(index); } @Override public int length() { return rarity.length(); } /** * Get the shorthand character for this Rarity. * * @return A shorthand character representing this Rarity. */ public char shorthand() { return switch (this) { case COMMON -> 'C'; case UNCOMMON -> 'U'; case RARE -> 'R'; case MYTHIC_RARE -> 'M'; case SPECIAL -> 'S'; case BASIC_LAND -> 'B'; }; } @Override public CharSequence subSequence(int start, int end) { return rarity.subSequence(start, end); } @Override public String toString() { return rarity; } }
src/editor/database/characteristics/Rarity.java
package editor.database.characteristics; /** * This enum represents a rarity a Magic: The Gathering card can have. Rarities * are basically Strings, so they implement {@link CharSequence}. All of the * implemented methods operate on a Rarity's String representation from * {@link #toString()}. * * @author Alec Roelke */ public enum Rarity implements CharSequence { /** * Rarity for basic lands. */ BASIC_LAND("Basic Land"), /** * Common rarity. */ COMMON("Common"), /** * Uncommon rarity. */ UNCOMMON("Uncommon"), /** * Rare rarity. */ RARE("Rare"), /** * Mythic rare rarity. */ MYTHIC_RARE("Mythic Rare"), /** * "Special" rarity, such as timeshifted. */ SPECIAL("Special"); /** * Create a rarity from a shorthand character. * * @param rarity Character to create a Rarity from * @return a Rarity representing the specified shorthand character * @throws IllegalArgumentException if a Rarity cannot be created from the specified character */ public static Rarity parseRarity(char rarity) { switch (Character.toLowerCase(rarity)) { case 'c': return COMMON; case 'u': return UNCOMMON; case 'r': return RARE; case 'm': return MYTHIC_RARE; case 's': return SPECIAL; case 'b': return BASIC_LAND; default: throw new IllegalArgumentException("Illegal rarity shorthand"); } } /** * Create a Rarity from the specified String. * * @param rarity String to create a Rarity from * @return a Rarity representing the specified String * @throws IllegalArgumentException if a Rarity cannot be created from the String */ public static Rarity parseRarity(String rarity) { if (rarity.contains("mythic")) return MYTHIC_RARE; else if (rarity.contains("rare")) return RARE; else if (rarity.contains("uncommon")) return UNCOMMON; else if (rarity.contains("common")) return COMMON; else if (rarity.contains("basic")) return BASIC_LAND; else { System.err.println("warning: Could not determine rarity of \"" + rarity + '"'); return SPECIAL; } } /** * String representation of this Rarity. */ private final String rarity; /** * Create a new Rarity. * * @param rarity String representation of the new Rarity. */ Rarity(final String rarity) { this.rarity = rarity; } @Override public char charAt(int index) { return rarity.charAt(index); } @Override public int length() { return rarity.length(); } /** * Get the shorthand character for this Rarity. * * @return A shorthand character representing this Rarity. */ public char shorthand() { switch (this) { case COMMON: return 'C'; case UNCOMMON: return 'U'; case RARE: return 'R'; case MYTHIC_RARE: return 'M'; case SPECIAL: return 'S'; case BASIC_LAND: return 'B'; default: return '\0'; } } @Override public CharSequence subSequence(int start, int end) { return rarity.subSequence(start, end); } @Override public String toString() { return rarity; } }
Use switch expression for return value
src/editor/database/characteristics/Rarity.java
Use switch expression for return value
<ide><path>rc/editor/database/characteristics/Rarity.java <ide> package editor.database.characteristics; <add> <add>import org.apache.commons.codec.binary.Base32; <ide> <ide> /** <ide> * This enum represents a rarity a Magic: The Gathering card can have. Rarities <ide> */ <ide> public static Rarity parseRarity(char rarity) <ide> { <del> switch (Character.toLowerCase(rarity)) <del> { <del> case 'c': <del> return COMMON; <del> case 'u': <del> return UNCOMMON; <del> case 'r': <del> return RARE; <del> case 'm': <del> return MYTHIC_RARE; <del> case 's': <del> return SPECIAL; <del> case 'b': <del> return BASIC_LAND; <del> default: <del> throw new IllegalArgumentException("Illegal rarity shorthand"); <del> } <add> return switch (Character.toLowerCase(rarity)) { <add> case 'c' -> COMMON; <add> case 'u' -> UNCOMMON; <add> case 'r' -> RARE; <add> case 'm' -> MYTHIC_RARE; <add> case 's' -> SPECIAL; <add> case 'b' -> BASIC_LAND; <add> default -> throw new IllegalArgumentException("Illegal rarity shorthand"); <add> }; <ide> } <ide> <ide> /** <ide> */ <ide> public char shorthand() <ide> { <del> switch (this) <del> { <del> case COMMON: <del> return 'C'; <del> case UNCOMMON: <del> return 'U'; <del> case RARE: <del> return 'R'; <del> case MYTHIC_RARE: <del> return 'M'; <del> case SPECIAL: <del> return 'S'; <del> case BASIC_LAND: <del> return 'B'; <del> default: <del> return '\0'; <del> } <add> return switch (this) { <add> case COMMON -> 'C'; <add> case UNCOMMON -> 'U'; <add> case RARE -> 'R'; <add> case MYTHIC_RARE -> 'M'; <add> case SPECIAL -> 'S'; <add> case BASIC_LAND -> 'B'; <add> }; <ide> } <ide> <ide> @Override
Java
apache-2.0
9a7717c9819e58f7ef2d2f96c5ef48d6a3695765
0
laborautonomo/jitsi,procandi/jitsi,level7systems/jitsi,jibaro/jitsi,pplatek/jitsi,martin7890/jitsi,procandi/jitsi,tuijldert/jitsi,martin7890/jitsi,HelioGuilherme66/jitsi,marclaporte/jitsi,bebo/jitsi,Metaswitch/jitsi,bhatvv/jitsi,cobratbq/jitsi,tuijldert/jitsi,gpolitis/jitsi,jitsi/jitsi,ringdna/jitsi,tuijldert/jitsi,jitsi/jitsi,bebo/jitsi,laborautonomo/jitsi,bhatvv/jitsi,Metaswitch/jitsi,gpolitis/jitsi,ringdna/jitsi,mckayclarey/jitsi,marclaporte/jitsi,laborautonomo/jitsi,mckayclarey/jitsi,procandi/jitsi,ibauersachs/jitsi,pplatek/jitsi,jibaro/jitsi,damencho/jitsi,jitsi/jitsi,laborautonomo/jitsi,iant-gmbh/jitsi,jibaro/jitsi,mckayclarey/jitsi,dkcreinoso/jitsi,mckayclarey/jitsi,level7systems/jitsi,bebo/jitsi,ibauersachs/jitsi,459below/jitsi,459below/jitsi,level7systems/jitsi,dkcreinoso/jitsi,Metaswitch/jitsi,459below/jitsi,bhatvv/jitsi,marclaporte/jitsi,ibauersachs/jitsi,level7systems/jitsi,ringdna/jitsi,procandi/jitsi,iant-gmbh/jitsi,ringdna/jitsi,dkcreinoso/jitsi,dkcreinoso/jitsi,marclaporte/jitsi,gpolitis/jitsi,bhatvv/jitsi,level7systems/jitsi,martin7890/jitsi,pplatek/jitsi,cobratbq/jitsi,dkcreinoso/jitsi,bebo/jitsi,iant-gmbh/jitsi,iant-gmbh/jitsi,iant-gmbh/jitsi,martin7890/jitsi,mckayclarey/jitsi,damencho/jitsi,Metaswitch/jitsi,jibaro/jitsi,HelioGuilherme66/jitsi,bebo/jitsi,HelioGuilherme66/jitsi,pplatek/jitsi,laborautonomo/jitsi,gpolitis/jitsi,gpolitis/jitsi,cobratbq/jitsi,ringdna/jitsi,marclaporte/jitsi,tuijldert/jitsi,damencho/jitsi,procandi/jitsi,jitsi/jitsi,damencho/jitsi,pplatek/jitsi,bhatvv/jitsi,ibauersachs/jitsi,jitsi/jitsi,HelioGuilherme66/jitsi,459below/jitsi,cobratbq/jitsi,459below/jitsi,martin7890/jitsi,HelioGuilherme66/jitsi,cobratbq/jitsi,damencho/jitsi,tuijldert/jitsi,jibaro/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.plugin.pluginmanager; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import net.java.sip.communicator.service.gui.*; import org.osgi.framework.*; /** * The panel containing all buttons for the <tt>PluginManagerConfigForm</tt>. * * @author Yana Stamcheva */ public class ManageButtonsPanel extends JPanel implements ActionListener { private JButton desactivateButton = new JButton( Resources.getString("desactivate")); private JButton activateButton = new JButton( Resources.getString("activate")); private JButton uninstallButton = new JButton( Resources.getString("uninstall")); private JButton updateButton = new JButton( Resources.getString("update")); private JButton newButton = new JButton(Resources.getString("new")); private JCheckBox showSysBundlesCheckBox = new JCheckBox( Resources.getString("showSystemBundles")); private JPanel buttonsPanel = new JPanel(new GridLayout(0, 1, 8, 8)); private JTable pluginTable; public ManageButtonsPanel(JTable pluginTable) { this.pluginTable = pluginTable; this.setLayout(new BorderLayout()); this.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); //Obtains previously saved value for the showSystemBundles check box. String showSystemBundlesProp = PluginManagerActivator .getConfigurationService().getString( "net.java.sip.communicator.plugin.pluginManager.showSystemBundles"); if(showSystemBundlesProp != null) { boolean isShowSystemBundles = new Boolean(showSystemBundlesProp).booleanValue(); this.showSysBundlesCheckBox.setSelected(isShowSystemBundles); ((PluginTableModel)pluginTable.getModel()) .setShowSystemBundles(isShowSystemBundles); } this.showSysBundlesCheckBox .addChangeListener(new ShowSystemBundlesChangeListener()); this.buttonsPanel.add(newButton); this.buttonsPanel.add(activateButton); this.buttonsPanel.add(desactivateButton); this.buttonsPanel.add(uninstallButton); this.buttonsPanel.add(updateButton); this.buttonsPanel.add(showSysBundlesCheckBox); this.add(buttonsPanel, BorderLayout.NORTH); this.newButton.addActionListener(this); this.activateButton.addActionListener(this); this.desactivateButton.addActionListener(this); this.uninstallButton.addActionListener(this); this.updateButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { JButton sourceButton = (JButton) e.getSource(); if(sourceButton.equals(newButton)) { NewBundleDialog dialog = new NewBundleDialog(); dialog.pack(); dialog.setLocation( Toolkit.getDefaultToolkit().getScreenSize().width/2 - dialog.getWidth()/2, Toolkit.getDefaultToolkit().getScreenSize().height/2 - dialog.getHeight()/2 ); dialog.setVisible(true); } else if(sourceButton.equals(activateButton)) { int[] selectedRows = pluginTable.getSelectedRows(); for (int i = 0; i < selectedRows.length; i++) { try { ((Bundle)pluginTable.getModel() .getValueAt(selectedRows[i], 0)).start(); } catch (BundleException ex) { PluginManagerActivator.getUIService().getPopupDialog() .showMessagePopupDialog(ex.getMessage(), "Error", PopupDialog.ERROR_MESSAGE); } } } else if(sourceButton.equals(desactivateButton)) { int[] selectedRows = pluginTable.getSelectedRows(); for (int i = 0; i < selectedRows.length; i++) { try { ((Bundle)pluginTable.getModel() .getValueAt(selectedRows[i], 0)).stop(); } catch (BundleException ex) { PluginManagerActivator.getUIService().getPopupDialog() .showMessagePopupDialog(ex.getMessage(), "Error", PopupDialog.ERROR_MESSAGE); } } } else if(sourceButton.equals(uninstallButton)) { int[] selectedRows = pluginTable.getSelectedRows(); for (int i = selectedRows.length - 1; i >= 0; i--) { try { ((Bundle)pluginTable.getModel() .getValueAt(selectedRows[i], 0)).uninstall(); } catch (BundleException ex) { PluginManagerActivator.getUIService().getPopupDialog() .showMessagePopupDialog(ex.getMessage(), "Error", PopupDialog.ERROR_MESSAGE); } } } else if(sourceButton.equals(updateButton)) { int[] selectedRows = pluginTable.getSelectedRows(); for (int i = 0; i < selectedRows.length; i++) { try { ((Bundle)pluginTable.getModel() .getValueAt(selectedRows[i], 0)).update(); } catch (BundleException ex) { PluginManagerActivator.getUIService().getPopupDialog() .showMessagePopupDialog(ex.getMessage(), "Error", PopupDialog.ERROR_MESSAGE); } } } } /** * Enable or disable the activate button. * * @param enable TRUE - to enable the activate button, FALSE - to disable it */ public void enableActivateButton(boolean enable) { this.activateButton.setEnabled(enable); } /** * Enable or disable the desactivate button. * * @param enable TRUE - to enable the desactivate button, FALSE - to * disable it */ public void enableDesactivateButton(boolean enable) { this.desactivateButton.setEnabled(enable); } /** * Enable or disable the uninstall button. * * @param enable TRUE - to enable the uninstall button, FALSE - to * disable it */ public void enableUninstallButton(boolean enable) { this.uninstallButton.setEnabled(enable); } /** * Adds all system bundles to the bundles list when the check box is * selected and removes them when user deselect it. */ private class ShowSystemBundlesChangeListener implements ChangeListener { private boolean currentValue = false; public ShowSystemBundlesChangeListener() { currentValue = showSysBundlesCheckBox.isSelected(); } public void stateChanged(ChangeEvent e) { if (currentValue == showSysBundlesCheckBox.isSelected()) { return; } currentValue = showSysBundlesCheckBox.isSelected(); //Save the current value of the showSystemBundles check box. PluginManagerActivator.getConfigurationService().setProperty( "net.java.sip.communicator.plugin.pluginManager.showSystemBundles", new Boolean(showSysBundlesCheckBox.isSelected())); PluginTableModel tableModel = (PluginTableModel)pluginTable.getModel(); tableModel.setShowSystemBundles(showSysBundlesCheckBox.isSelected()); tableModel.update(); } } /** * Returns the current value of the "showSystemBundles" check box. * @return TRUE if the the "showSystemBundles" check box is selected, * FALSE - otherwise. */ public boolean isShowSystemBundles() { return showSysBundlesCheckBox.isSelected(); } }
src/net/java/sip/communicator/plugin/pluginmanager/ManageButtonsPanel.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.plugin.pluginmanager; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import net.java.sip.communicator.service.gui.*; import org.osgi.framework.*; /** * The panel containing all buttons for the <tt>PluginManagerConfigForm</tt>. * * @author Yana Stamcheva */ public class ManageButtonsPanel extends JPanel implements ActionListener { private JButton desactivateButton = new JButton( Resources.getString("desactivate")); private JButton activateButton = new JButton( Resources.getString("activate")); private JButton uninstallButton = new JButton( Resources.getString("uninstall")); private JButton updateButton = new JButton( Resources.getString("update")); private JButton newButton = new JButton(Resources.getString("new")); private JCheckBox showSysBundlesCheckBox = new JCheckBox( Resources.getString("showSystemBundles")); private JPanel buttonsPanel = new JPanel(new GridLayout(0, 1, 8, 8)); private JTable pluginTable; public ManageButtonsPanel(JTable pluginTable) { this.pluginTable = pluginTable; this.setLayout(new BorderLayout()); this.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); //Obtains previously saved value for the showSystemBundles check box. String showSystemBundlesProp = PluginManagerActivator .getConfigurationService().getString( "net.java.sip.communicator.plugin.pluginManager.showSystemBundles"); if(showSystemBundlesProp != null) { boolean isShowSystemBundles = new Boolean(showSystemBundlesProp).booleanValue(); this.showSysBundlesCheckBox.setSelected(isShowSystemBundles); ((PluginTableModel)pluginTable.getModel()) .setShowSystemBundles(isShowSystemBundles); } this.showSysBundlesCheckBox .addChangeListener(new ShowSystemBundlesChangeListener()); this.buttonsPanel.add(newButton); this.buttonsPanel.add(activateButton); this.buttonsPanel.add(desactivateButton); this.buttonsPanel.add(uninstallButton); this.buttonsPanel.add(updateButton); this.buttonsPanel.add(showSysBundlesCheckBox); this.add(buttonsPanel, BorderLayout.NORTH); this.newButton.addActionListener(this); this.activateButton.addActionListener(this); this.desactivateButton.addActionListener(this); this.uninstallButton.addActionListener(this); this.updateButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { JButton sourceButton = (JButton) e.getSource(); if(sourceButton.equals(newButton)) { NewBundleDialog dialog = new NewBundleDialog(); dialog.pack(); dialog.setLocation( Toolkit.getDefaultToolkit().getScreenSize().width/2 - dialog.getWidth()/2, Toolkit.getDefaultToolkit().getScreenSize().height/2 - dialog.getHeight()/2 ); dialog.setVisible(true); } else if(sourceButton.equals(activateButton)) { int[] selectedRows = pluginTable.getSelectedRows(); for (int i = 0; i < selectedRows.length; i++) { try { ((Bundle)pluginTable.getModel() .getValueAt(selectedRows[i], 0)).start(); } catch (BundleException ex) { PluginManagerActivator.getUIService().getPopupDialog() .showMessagePopupDialog(ex.getMessage(), "Error", PopupDialog.ERROR_MESSAGE); } } } else if(sourceButton.equals(desactivateButton)) { int[] selectedRows = pluginTable.getSelectedRows(); for (int i = 0; i < selectedRows.length; i++) { try { ((Bundle)pluginTable.getModel() .getValueAt(selectedRows[i], 0)).stop(); } catch (BundleException ex) { PluginManagerActivator.getUIService().getPopupDialog() .showMessagePopupDialog(ex.getMessage(), "Error", PopupDialog.ERROR_MESSAGE); } } } else if(sourceButton.equals(uninstallButton)) { int[] selectedRows = pluginTable.getSelectedRows(); for (int i = selectedRows.length - 1; i >= 0; i--) { try { ((Bundle)pluginTable.getModel() .getValueAt(selectedRows[i], 0)).uninstall(); } catch (BundleException ex) { PluginManagerActivator.getUIService().getPopupDialog() .showMessagePopupDialog(ex.getMessage(), "Error", PopupDialog.ERROR_MESSAGE); } } } else if(sourceButton.equals(updateButton)) { int[] selectedRows = pluginTable.getSelectedRows(); for (int i = 0; i < selectedRows.length; i++) { try { ((Bundle)pluginTable.getModel() .getValueAt(selectedRows[i], 0)).update(); } catch (BundleException ex) { PluginManagerActivator.getUIService().getPopupDialog() .showMessagePopupDialog(ex.getMessage(), "Error", PopupDialog.ERROR_MESSAGE); } } } } /** * Enable or disable the activate button. * * @param enable TRUE - to enable the activate button, FALSE - to disable it */ public void enableActivateButton(boolean enable) { this.activateButton.setEnabled(enable); } /** * Enable or disable the desactivate button. * * @param enable TRUE - to enable the desactivate button, FALSE - to * disable it */ public void enableDesactivateButton(boolean enable) { this.desactivateButton.setEnabled(enable); } /** * Enable or disable the uninstall button. * * @param enable TRUE - to enable the uninstall button, FALSE - to * disable it */ public void enableUninstallButton(boolean enable) { this.uninstallButton.setEnabled(enable); } /** * Adds all system bundles to the bundles list when the check box is * selected and removes them when user deselect it. */ private class ShowSystemBundlesChangeListener implements ChangeListener { public void stateChanged(ChangeEvent e) { //Save the current value of the showSystemBundles check box. PluginManagerActivator.getConfigurationService().setProperty( "net.java.sip.communicator.plugin.pluginManager.showSystemBundles", new Boolean(showSysBundlesCheckBox.isSelected())); PluginTableModel tableModel = (PluginTableModel)pluginTable.getModel(); tableModel.setShowSystemBundles(showSysBundlesCheckBox.isSelected()); tableModel.update(); } } /** * Returns the current value of the "showSystemBundles" check box. * @return TRUE if the the "showSystemBundles" check box is selected, * FALSE - otherwise. */ public boolean isShowSystemBundles() { return showSysBundlesCheckBox.isSelected(); } }
bugfix: when moving mouse over checkbox, selected items gets lost
src/net/java/sip/communicator/plugin/pluginmanager/ManageButtonsPanel.java
bugfix: when moving mouse over checkbox, selected items gets lost
<ide><path>rc/net/java/sip/communicator/plugin/pluginmanager/ManageButtonsPanel.java <ide> */ <ide> private class ShowSystemBundlesChangeListener implements ChangeListener <ide> { <add> private boolean currentValue = false; <add> <add> public ShowSystemBundlesChangeListener() <add> { <add> currentValue = showSysBundlesCheckBox.isSelected(); <add> } <add> <ide> public void stateChanged(ChangeEvent e) <ide> { <add> if (currentValue == showSysBundlesCheckBox.isSelected()) <add> { <add> return; <add> } <add> currentValue = showSysBundlesCheckBox.isSelected(); <ide> //Save the current value of the showSystemBundles check box. <ide> PluginManagerActivator.getConfigurationService().setProperty( <ide> "net.java.sip.communicator.plugin.pluginManager.showSystemBundles",
Java
mit
508316a4184ce82b260495e756cded54057e901b
0
civitaspo/embulk-input-hdfs,civitaspo/embulk-input-hdfs
package org.embulk.input.hdfs; import com.google.common.base.Function; import com.google.common.collect.Lists; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathNotFoundException; import org.embulk.config.Config; import org.embulk.config.ConfigDefault; import org.embulk.config.ConfigDiff; import org.embulk.config.ConfigInject; import org.embulk.config.ConfigSource; import org.embulk.config.Task; import org.embulk.config.TaskReport; import org.embulk.config.TaskSource; import org.embulk.spi.BufferAllocator; import org.embulk.spi.Exec; import org.embulk.spi.FileInputPlugin; import org.embulk.spi.TransactionalFileInput; import org.embulk.spi.util.InputStreamTransactionalFileInput; import org.jruby.embed.ScriptingContainer; import org.slf4j.Logger; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; public class HdfsFileInputPlugin implements FileInputPlugin { private static final Logger logger = Exec.getLogger(HdfsFileInputPlugin.class); public interface PluginTask extends Task { @Config("config_files") @ConfigDefault("[]") public List<String> getConfigFiles(); @Config("config") @ConfigDefault("{}") public Map<String, String> getConfig(); @Config("path") public String getPath(); @Config("rewind_seconds") @ConfigDefault("0") public int getRewindSeconds(); @Config("partition") @ConfigDefault("true") public boolean getPartition(); @Config("num_partitions") // this parameter is the approximate value. @ConfigDefault("-1") // Default: Runtime.getRuntime().availableProcessors() public long getApproximateNumPartitions(); public List<HdfsPartialFile> getFiles(); public void setFiles(List<HdfsPartialFile> hdfsFiles); @ConfigInject public BufferAllocator getBufferAllocator(); } @Override public ConfigDiff transaction(ConfigSource config, FileInputPlugin.Control control) { PluginTask task = config.loadConfig(PluginTask.class); // listing Files String pathString = strftime(task.getPath(), task.getRewindSeconds()); try { List<String> originalFileList = buildFileList(getFs(task), pathString); if (originalFileList.isEmpty()) { throw new PathNotFoundException(pathString); } logger.debug("embulk-input-hdfs: Loading target files: {}", originalFileList); task.setFiles(allocateHdfsFilesToTasks(task, getFs(task), originalFileList)); } catch (IOException e) { logger.error(e.getMessage()); throw new RuntimeException(e); } // log the detail of partial files. for (HdfsPartialFile partialFile : task.getFiles()) { logger.debug("embulk-input-hdfs: target file: {}, start: {}, end: {}", partialFile.getPath(), partialFile.getStart(), partialFile.getEnd()); } // number of processors is same with number of targets int taskCount = task.getFiles().size(); logger.info("embulk-input-hdfs: task size: {}", taskCount); return resume(task.dump(), taskCount, control); } @Override public ConfigDiff resume(TaskSource taskSource, int taskCount, FileInputPlugin.Control control) { control.run(taskSource, taskCount); ConfigDiff configDiff = Exec.newConfigDiff(); // usually, yo use last_path //if (task.getFiles().isEmpty()) { // if (task.getLastPath().isPresent()) { // configDiff.set("last_path", task.getLastPath().get()); // } //} else { // List<String> files = new ArrayList<String>(task.getFiles()); // Collections.sort(files); // configDiff.set("last_path", files.get(files.size() - 1)); //} return configDiff; } @Override public void cleanup(TaskSource taskSource, int taskCount, List<TaskReport> successTaskReports) { } @Override public TransactionalFileInput open(TaskSource taskSource, int taskIndex) { final PluginTask task = taskSource.loadTask(PluginTask.class); InputStream input; try { input = openInputStream(task, task.getFiles().get(taskIndex)); } catch (IOException e) { logger.error(e.getMessage()); throw new RuntimeException(e); } return new InputStreamTransactionalFileInput(task.getBufferAllocator(), input) { @Override public void abort() { } @Override public TaskReport commit() { return Exec.newTaskReport(); } }; } private static HdfsPartialFileInputStream openInputStream(PluginTask task, HdfsPartialFile partialFile) throws IOException { FileSystem fs = getFs(task); InputStream original = fs.open(new Path(partialFile.getPath())); return new HdfsPartialFileInputStream(original, partialFile.getStart(), partialFile.getEnd()); } private static FileSystem getFs(final PluginTask task) throws IOException { Configuration configuration = new Configuration(); for (String configFile : task.getConfigFiles()) { File file = new File(configFile); configuration.addResource(file.toURI().toURL()); } for (Map.Entry<String, String> entry: task.getConfig().entrySet()) { configuration.set(entry.getKey(), entry.getValue()); } // For debug Iterator<Map.Entry<String, String>> entryIterator = configuration.iterator(); while (entryIterator.hasNext()) { Map.Entry<String, String> entry = entryIterator.next(); logger.trace("{}: {}", entry.getKey(), entry.getValue()); } logger.debug("Resource Files: {}", configuration); return FileSystem.get(configuration); } private String strftime(final String raw, final int rewind_seconds) { ScriptingContainer jruby = new ScriptingContainer(); Object resolved = jruby.runScriptlet( String.format("(Time.now - %s).strftime('%s')", String.valueOf(rewind_seconds), raw)); return resolved.toString(); } private List<String> buildFileList(final FileSystem fs, final String pathString) throws IOException { List<String> fileList = new ArrayList<>(); Path rootPath = new Path(pathString); final FileStatus[] entries = fs.globStatus(rootPath); // `globStatus` does not throw PathNotFoundException. // return null instead. // see: https://github.com/apache/hadoop/blob/branch-2.7.0/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/Globber.java#L286 if (entries == null) { return fileList; } for (FileStatus entry : entries) { if (entry.isDirectory()) { fileList.addAll(lsr(fs, entry)); } else { fileList.add(entry.getPath().toString()); } } return fileList; } private List<String> lsr(final FileSystem fs, FileStatus status) throws IOException { List<String> fileList = new ArrayList<>(); if (status.isDirectory()) { for (FileStatus entry : fs.listStatus(status.getPath())) { fileList.addAll(lsr(fs, entry)); } } else { fileList.add(status.getPath().toString()); } return fileList; } private List<HdfsPartialFile> allocateHdfsFilesToTasks(final PluginTask task, final FileSystem fs, final List<String> fileList) throws IOException { List<Path> pathList = Lists.transform(fileList, new Function<String, Path>() { @Nullable @Override public Path apply(@Nullable String input) { return new Path(input); } }); long totalFileLength = 0; for (Path path : pathList) { totalFileLength += fs.getFileStatus(path).getLen(); } // TODO: optimum allocation of resources long approximateNumPartitions = (task.getApproximateNumPartitions() <= 0) ? Runtime.getRuntime().availableProcessors() : task.getApproximateNumPartitions(); long partitionSizeByOneTask = totalFileLength / approximateNumPartitions; List<HdfsPartialFile> hdfsPartialFiles = new ArrayList<>(); for (Path path : pathList) { long fileLength = fs.getFileStatus(path).getLen(); // declare `fileLength` here because this is used below. if (fileLength <= 0) { logger.info("embulk-input-hdfs: Skip the 0 byte target file: {}", path); continue; } long numPartitions; if (path.toString().endsWith(".gz") || path.toString().endsWith(".bz2") || path.toString().endsWith(".lzo")) { numPartitions = 1; } else if (!task.getPartition()) { numPartitions = 1; } else { numPartitions = ((fileLength - 1) / partitionSizeByOneTask) + 1; } HdfsFilePartitioner partitioner = new HdfsFilePartitioner(fs, path, numPartitions); hdfsPartialFiles.addAll(partitioner.getHdfsPartialFiles()); } return hdfsPartialFiles; } }
src/main/java/org/embulk/input/hdfs/HdfsFileInputPlugin.java
package org.embulk.input.hdfs; import com.google.common.base.Function; import com.google.common.collect.Lists; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathNotFoundException; import org.embulk.config.Config; import org.embulk.config.ConfigDefault; import org.embulk.config.ConfigDiff; import org.embulk.config.ConfigInject; import org.embulk.config.ConfigSource; import org.embulk.config.Task; import org.embulk.config.TaskReport; import org.embulk.config.TaskSource; import org.embulk.spi.BufferAllocator; import org.embulk.spi.Exec; import org.embulk.spi.FileInputPlugin; import org.embulk.spi.TransactionalFileInput; import org.embulk.spi.util.InputStreamTransactionalFileInput; import org.jruby.embed.ScriptingContainer; import org.slf4j.Logger; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; public class HdfsFileInputPlugin implements FileInputPlugin { private static final Logger logger = Exec.getLogger(HdfsFileInputPlugin.class); public interface PluginTask extends Task { @Config("config_files") @ConfigDefault("[]") public List<String> getConfigFiles(); @Config("config") @ConfigDefault("{}") public Map<String, String> getConfig(); @Config("path") public String getPath(); @Config("rewind_seconds") @ConfigDefault("0") public int getRewindSeconds(); @Config("partition") @ConfigDefault("true") public boolean getPartition(); @Config("num_partitions") // this parameter is the approximate value. @ConfigDefault("-1") // Default: Runtime.getRuntime().availableProcessors() public long getApproximateNumPartitions(); public List<HdfsPartialFile> getFiles(); public void setFiles(List<HdfsPartialFile> hdfsFiles); @ConfigInject public BufferAllocator getBufferAllocator(); } @Override public ConfigDiff transaction(ConfigSource config, FileInputPlugin.Control control) { PluginTask task = config.loadConfig(PluginTask.class); // listing Files String pathString = strftime(task.getPath(), task.getRewindSeconds()); try { List<String> originalFileList = buildFileList(getFs(task), pathString); if (originalFileList.isEmpty()) { throw new PathNotFoundException(pathString); } logger.debug("embulk-input-hdfs: Loading target files: {}", originalFileList); task.setFiles(allocateHdfsFilesToTasks(task, getFs(task), originalFileList)); } catch (IOException e) { logger.error(e.getMessage()); throw new RuntimeException(e); } // log the detail of partial files. for (HdfsPartialFile partialFile : task.getFiles()) { logger.debug("embulk-input-hdfs: target file: {}, start: {}, end: {}", partialFile.getPath(), partialFile.getStart(), partialFile.getEnd()); } // number of processors is same with number of targets int taskCount = task.getFiles().size(); logger.info("embulk-input-hdfs: task size: {}", taskCount); return resume(task.dump(), taskCount, control); } @Override public ConfigDiff resume(TaskSource taskSource, int taskCount, FileInputPlugin.Control control) { control.run(taskSource, taskCount); ConfigDiff configDiff = Exec.newConfigDiff(); // usually, yo use last_path //if (task.getFiles().isEmpty()) { // if (task.getLastPath().isPresent()) { // configDiff.set("last_path", task.getLastPath().get()); // } //} else { // List<String> files = new ArrayList<String>(task.getFiles()); // Collections.sort(files); // configDiff.set("last_path", files.get(files.size() - 1)); //} return configDiff; } @Override public void cleanup(TaskSource taskSource, int taskCount, List<TaskReport> successTaskReports) { } @Override public TransactionalFileInput open(TaskSource taskSource, int taskIndex) { final PluginTask task = taskSource.loadTask(PluginTask.class); InputStream input; try { input = openInputStream(task, task.getFiles().get(taskIndex)); } catch (IOException e) { logger.error(e.getMessage()); throw new RuntimeException(e); } return new InputStreamTransactionalFileInput(task.getBufferAllocator(), input) { @Override public void abort() { } @Override public TaskReport commit() { return Exec.newTaskReport(); } }; } private static HdfsPartialFileInputStream openInputStream(PluginTask task, HdfsPartialFile partialFile) throws IOException { FileSystem fs = getFs(task); InputStream original = fs.open(new Path(partialFile.getPath())); return new HdfsPartialFileInputStream(original, partialFile.getStart(), partialFile.getEnd()); } private static FileSystem getFs(final PluginTask task) throws IOException { Configuration configuration = new Configuration(); for (String configFile : task.getConfigFiles()) { File file = new File(configFile); configuration.addResource(file.toURI().toURL()); } for (Map.Entry<String, String> entry: task.getConfig().entrySet()) { configuration.set(entry.getKey(), entry.getValue()); } // For debug Iterator<Map.Entry<String, String>> entryIterator = configuration.iterator(); while (entryIterator.hasNext()) { Map.Entry<String, String> entry = entryIterator.next(); logger.debug("{}: {}", entry.getKey(), entry.getValue()); } logger.debug("Resource Files: {}", configuration); return FileSystem.get(configuration); } private String strftime(final String raw, final int rewind_seconds) { ScriptingContainer jruby = new ScriptingContainer(); Object resolved = jruby.runScriptlet( String.format("(Time.now - %s).strftime('%s')", String.valueOf(rewind_seconds), raw)); return resolved.toString(); } private List<String> buildFileList(final FileSystem fs, final String pathString) throws IOException { List<String> fileList = new ArrayList<>(); Path rootPath = new Path(pathString); final FileStatus[] entries = fs.globStatus(rootPath); // `globStatus` does not throw PathNotFoundException. // return null instead. // see: https://github.com/apache/hadoop/blob/branch-2.7.0/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/Globber.java#L286 if (entries == null) { return fileList; } for (FileStatus entry : entries) { if (entry.isDirectory()) { fileList.addAll(lsr(fs, entry)); } else { fileList.add(entry.getPath().toString()); } } return fileList; } private List<String> lsr(final FileSystem fs, FileStatus status) throws IOException { List<String> fileList = new ArrayList<>(); if (status.isDirectory()) { for (FileStatus entry : fs.listStatus(status.getPath())) { fileList.addAll(lsr(fs, entry)); } } else { fileList.add(status.getPath().toString()); } return fileList; } private List<HdfsPartialFile> allocateHdfsFilesToTasks(final PluginTask task, final FileSystem fs, final List<String> fileList) throws IOException { List<Path> pathList = Lists.transform(fileList, new Function<String, Path>() { @Nullable @Override public Path apply(@Nullable String input) { return new Path(input); } }); long totalFileLength = 0; for (Path path : pathList) { totalFileLength += fs.getFileStatus(path).getLen(); } // TODO: optimum allocation of resources long approximateNumPartitions = (task.getApproximateNumPartitions() <= 0) ? Runtime.getRuntime().availableProcessors() : task.getApproximateNumPartitions(); long partitionSizeByOneTask = totalFileLength / approximateNumPartitions; List<HdfsPartialFile> hdfsPartialFiles = new ArrayList<>(); for (Path path : pathList) { long fileLength = fs.getFileStatus(path).getLen(); // declare `fileLength` here because this is used below. if (fileLength <= 0) { logger.info("embulk-input-hdfs: Skip the 0 byte target file: {}", path); continue; } long numPartitions; if (path.toString().endsWith(".gz") || path.toString().endsWith(".bz2") || path.toString().endsWith(".lzo")) { numPartitions = 1; } else if (!task.getPartition()) { numPartitions = 1; } else { numPartitions = ((fileLength - 1) / partitionSizeByOneTask) + 1; } HdfsFilePartitioner partitioner = new HdfsFilePartitioner(fs, path, numPartitions); hdfsPartialFiles.addAll(partitioner.getHdfsPartialFiles()); } return hdfsPartialFiles; } }
Change log level: hadoop configuration
src/main/java/org/embulk/input/hdfs/HdfsFileInputPlugin.java
Change log level: hadoop configuration
<ide><path>rc/main/java/org/embulk/input/hdfs/HdfsFileInputPlugin.java <ide> Iterator<Map.Entry<String, String>> entryIterator = configuration.iterator(); <ide> while (entryIterator.hasNext()) { <ide> Map.Entry<String, String> entry = entryIterator.next(); <del> logger.debug("{}: {}", entry.getKey(), entry.getValue()); <add> logger.trace("{}: {}", entry.getKey(), entry.getValue()); <ide> } <ide> logger.debug("Resource Files: {}", configuration); <ide>
Java
mit
db93d4360f2f93c18d0c49562114f1030281eddc
0
znGames/skyroad-magnets
package com.zngames.skymag; import com.badlogic.gdx.math.Circle; import com.badlogic.gdx.math.MathUtils; @SuppressWarnings("serial") public class Hole extends Circle { boolean bridged; float bridgeStartX; float bridgeStartY; float bridgeEndX; float bridgeEndY; double angle; double cosAngle; double sinAngle; public Hole(float x, float y, float radius){ super(x,y,radius); bridged = false; } public Hole(float x, float y, float radius, boolean bridged){ super(x,y,radius); this.bridged = bridged; if(bridged){ if(x-radius < World.getLeftBorderXCoordinate()){ float leftLimit = (float) Math.min(Math.acos((World.getLeftBorderXCoordinate()-x)*1.0/radius), MathUtils.PI*3.0/4); angle = MathUtils.random(-leftLimit, leftLimit); } else if(x+radius > World.getRightBorderXCoordinate()){ float rightLimit = (float) Math.max(Math.acos((World.getRightBorderXCoordinate()-x)*1.0/radius), MathUtils.PI*1.0/4); angle = MathUtils.random(rightLimit, -rightLimit); } else{ angle = MathUtils.random((float) (MathUtils.PI*1.0/4), (float) (MathUtils.PI*3.0/4)); } cosAngle = Math.cos(angle); sinAngle = Math.sin(angle); bridgeStartX = (float) (x + radius*cosAngle); bridgeStartY = (float) (y + radius*sinAngle); bridgeEndX = (float) (x - radius*cosAngle); bridgeEndY = (float) (y - radius*sinAngle); } } public boolean isBridged(){ return bridged; } }
skyroad-magnets/src/com/zngames/skymag/Hole.java
package com.zngames.skymag; import com.badlogic.gdx.math.Circle; import com.badlogic.gdx.math.MathUtils; @SuppressWarnings("serial") public class Hole extends Circle { boolean bridged; float bridgeStartX; float bridgeStartY; float bridgeEndX; float bridgeEndY; double angle; double cosAngle; double sinAngle; public Hole(float x, float y, float radius){ super(x,y,radius); bridged = false; } public Hole(float x, float y, float radius, boolean bridged){ super(x,y,radius); this.bridged = bridged; if(bridged){ if(x-radius < World.getLeftBorderXCoordinate()){ angle = MathUtils.random((float) (MathUtils.PI*1.0/4), (float) Math.min(Math.acos((World.getLeftBorderXCoordinate()-x)*1.0/radius), MathUtils.PI*3.0/4)); } else if(x+radius > World.getRightBorderXCoordinate()){ angle = MathUtils.random((float) Math.max(Math.acos((World.getRightBorderXCoordinate()-x)*1.0/radius), MathUtils.PI*1.0/4), (float) (MathUtils.PI*3.0/4)); } else{ angle = MathUtils.random((float) (MathUtils.PI*1.0/4), (float) (MathUtils.PI*3.0/4)); } cosAngle = Math.cos(angle); sinAngle = Math.sin(angle); bridgeStartX = (float) (x + radius*cosAngle); bridgeStartY = (float) (y + radius*sinAngle); bridgeEndX = (float) (x - radius*cosAngle); bridgeEndY = (float) (y - radius*sinAngle); } } public boolean isBridged(){ return bridged; } }
* Fixed the bridge generation for cropped circles
skyroad-magnets/src/com/zngames/skymag/Hole.java
* Fixed the bridge generation for cropped circles
<ide><path>kyroad-magnets/src/com/zngames/skymag/Hole.java <ide> this.bridged = bridged; <ide> if(bridged){ <ide> if(x-radius < World.getLeftBorderXCoordinate()){ <del> angle = MathUtils.random((float) (MathUtils.PI*1.0/4), (float) Math.min(Math.acos((World.getLeftBorderXCoordinate()-x)*1.0/radius), MathUtils.PI*3.0/4)); <add> float leftLimit = (float) Math.min(Math.acos((World.getLeftBorderXCoordinate()-x)*1.0/radius), MathUtils.PI*3.0/4); <add> angle = MathUtils.random(-leftLimit, leftLimit); <ide> } else if(x+radius > World.getRightBorderXCoordinate()){ <del> angle = MathUtils.random((float) Math.max(Math.acos((World.getRightBorderXCoordinate()-x)*1.0/radius), MathUtils.PI*1.0/4), (float) (MathUtils.PI*3.0/4)); <add> float rightLimit = (float) Math.max(Math.acos((World.getRightBorderXCoordinate()-x)*1.0/radius), MathUtils.PI*1.0/4); <add> angle = MathUtils.random(rightLimit, -rightLimit); <ide> } else{ <ide> angle = MathUtils.random((float) (MathUtils.PI*1.0/4), (float) (MathUtils.PI*3.0/4)); <ide> }
Java
apache-2.0
efa85bd29038afbf25ae285cc5ead90e41815f7a
0
rwl/requestfactory-addon
package org.springframework.roo.support.util; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.namespace.NamespaceContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * Utilities related to DOM and XML usage. * * @author Stefan Schmidt * @author Ben Alex * @since 1.0 * */ public abstract class XmlUtils { private static final Map<String, XPathExpression> compiledExpressionCache = new HashMap<String, XPathExpression>(); public static final void writeXml(OutputStream outputEntry, Document document) { writeXml(createIndentingTransformer(), outputEntry, document); } public static final void writeMalformedXml(OutputStream outputEntry, NodeList nodes) { writeMalformedXml(createIndentingTransformer(), outputEntry, nodes); } // /** // * Obtains an element, throwing an {@link IllegalArgumentException} if not // * found. // * // * <p> // * Internally delegates to // * {@link DomUtils#getChildElementByTagName(Element, String)}. // * // * @param ele // * the DOM element to analyze (required) // * @param childEleName // * the child element name to look for (required) // * @return the Element instance (never null) // */ // public static Element getRequiredChildElementByTagName(Element ele, // String childEleName) { // Element e = DomUtils.getChildElementByTagName(ele, childEleName); // Assert.notNull("Unable to obtain element '" + childEleName // + "' from element '" + ele + "'"); // return e; // } // /** // * Checks in under a given root element whether it can find a child // element // * with the exact same name and attribute. // * // * @param root // * the parent DOM element // * @param target // * the child DOM element name to look for // * @return the element if discovered, otherwise null // */ // public static Element findElementIfExists(Element root, Element target) { // Assert.notNull(root, "Root element not supplied"); // Assert.notNull(target, "Target element not supplied"); // Element match = null; // // NodeList list = root.getChildNodes(); // for (int i = 0; i < list.getLength(); i++) { // // Node existingNode = list.item(i); // // if (!existingNode.getNodeName().equals(target.getNodeName())) // continue; // // NamedNodeMap existingAttributes = existingNode.getAttributes(); // // // we have a match based on element name only (no target attributes // // existing) // if (existingAttributes == null && target.getAttributes() == null) // return (Element) existingNode; // // if (existingAttributes == null) // continue; // // for (int j = 0; j < existingAttributes.getLength(); j++) { // // Node targetAttribute = target.getAttributes().getNamedItem( // existingAttributes.item(j).getNodeName()); // // // check if the target node has an attribute with the same name // // as one of the existing node attributes // if (targetAttribute == null) // return null; // // // check if the target node has an attribute with the same value // // as one of the existing node attribute values // Attr existingAttribute = (Attr) existingAttributes.item(j); // existingAttribute.getValue(); // if (!targetAttribute.getNodeValue().equals( // existingAttribute.getValue())) // match = null; // else // // the currently checked attribute matches // match = (Element) existingNode; // } // } // return match; // } // /** // * Checks in under a given root element whether it can find a child // element // * which contains the text supplied. Returns Element if exists. // * // * @param root // * the parent DOM element // * @param contents // * text contents of the child element to look for // * @return Element if discovered, otherwise null // */ // public static Element findMatchingTextNode(Element root, String contents) // { // Assert.notNull(root, "Root element not supplied"); // Assert.hasText(contents, "Text contents not supplied"); // // NodeList list = root.getChildNodes(); // for (int i = 0; i < list.getLength(); i++) { // if (list.item(i) instanceof Element) { // if (((Element) list.item(i)).getFirstChild().getTextContent() // .equals(contents)) // return (Element) list.item(i); // } // } // return null; // } public static final void writeXml(Transformer transformer, OutputStream outputEntry, Document document) { Assert.notNull(transformer, "Transformer required"); Assert.notNull(outputEntry, "Output entry required"); Assert.notNull(document, "Document required"); try { transformer.transform(new DOMSource(document), new StreamResult(new OutputStreamWriter(outputEntry, "ISO-8859-1"/* "UTF-8" */))); } catch (Exception ex) { throw new IllegalStateException(ex); } } public static final void writeMalformedXml(Transformer transformer, OutputStream outputEntry, NodeList nodes) { Assert.notNull(transformer, "Transformer required"); Assert.notNull(outputEntry, "Output entry required"); Assert.notNull(nodes, "NodeList required"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); try { for (int i = 0; i < nodes.getLength(); i++) { transformer.transform(new DOMSource(nodes.item(i)), new StreamResult(new OutputStreamWriter(outputEntry, "ISO-8859-1"))); } } catch (Exception ex) { throw new IllegalStateException(ex); } } /** * Checks in under a given root element whether it can find a child element * which matches the XPath expression supplied. Returns {@link Element} if * exists. * * @param xPathExpression * the xPathExpression (required) * @param root * the parent DOM element (required) * * @return the Element if discovered (null if not found) */ public static Element findFirstElement(String xPathExpression, Element root) { if (xPathExpression == null || root == null || xPathExpression.length() == 0) { throw new IllegalArgumentException("Xpath expression and root element required"); } XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); xpath.setNamespaceContext(getNamespaceContext()); Element rootElement = null; try { XPathExpression expr = compiledExpressionCache.get(xPathExpression); if (expr == null) { expr = xpath.compile(xPathExpression); compiledExpressionCache.put(xPathExpression, expr); } rootElement = (Element) expr.evaluate(root, XPathConstants.NODE); } catch (XPathExpressionException e) { throw new IllegalArgumentException("Unable evaluate xpath expression", e); } return rootElement; } /** * Checks in under a given root element whether it can find a child element * which matches the name supplied. Returns {@link Element} if exists. * * @param name * the Element name (required) * @param root * the parent DOM element (required) * * @return the Element if discovered */ public static Element findFirstElementByName(String name, Element root) { Assert.hasText(name, "Element name required"); Assert.notNull(root, "Root element required"); return (Element) root.getElementsByTagName(name).item(0); } /** * Checks in under a given root element whether it can find a child element * which matches the XPath expression supplied. The {@link Element} must * exist. Returns {@link Element} if exists. * * @param xPathExpression * the xPathExpression (required) * @param root * the parent DOM element (required) * * @return the Element if discovered (never null; an exception is thrown if * cannot be found) */ public static Element findRequiredElement(String xPathExpression, Element root) { Assert.hasText(xPathExpression, "XPath expression required"); Assert.notNull(root, "Root element required"); Element element = findFirstElement(xPathExpression, root); Assert.notNull(element, "Unable to obtain required element '" + xPathExpression + "' from element '" + root + "'"); return element; } /** * Checks in under a given root element whether it can find a child elements * which match the XPath expression supplied. Returns a {@link List} of * {@link Element} if they exist. * * @param xPathExpression * the xPathExpression * @param root * the parent DOM element * * @return a {@link List} of type {@link Element} if discovered, otherwise * null */ public static List<Element> findElements(String xPathExpression, Element root) { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); xpath.setNamespaceContext(getNamespaceContext()); List<Element> elements = new ArrayList<Element>(); NodeList nodes = null; try { XPathExpression expr = xpath.compile(xPathExpression); nodes = (NodeList) expr.evaluate(root, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new IllegalArgumentException("Unable evaluate xpath expression", e); } for (int i = 0; i < nodes.getLength(); i++) { elements.add((Element) nodes.item(i)); } return elements; } /** * @return a transformer that indents entries by 4 characters (never null) */ public static final Transformer createIndentingTransformer() { Transformer xformer; try { xformer = TransformerFactory.newInstance().newTransformer(); } catch (Exception ex) { throw new IllegalStateException(ex); } xformer.setOutputProperty(OutputKeys.INDENT, "yes"); xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); return xformer; } /** * @return a new document builder (never null) */ public static final DocumentBuilder getDocumentBuilder() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { return factory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { throw new IllegalStateException(ex); } } private static NamespaceContext getNamespaceContext() { return new NamespaceContext() { public String getNamespaceURI(String prefix) { String uri; if (prefix.equals("ns1")) { uri = "http://www.springframework.org/schema/aop"; } else if (prefix.equals("tx")) { uri = "http://www.springframework.org/schema/tx"; } else if (prefix.equals("context")) { uri = "http://www.springframework.org/schema/context"; } else if (prefix.equals("beans")) { uri = "http://www.springframework.org/schema/beans"; } else if (prefix.equals("webflow")) { uri = "http://www.springframework.org/schema/webflow-config"; } else if (prefix.equals("p")) { uri = "http://www.springframework.org/schema/p"; } else if (prefix.equals("security")) { uri = "http://www.springframework.org/schema/security"; } else if (prefix.equals("amq")) { uri = "http://activemq.apache.org/schema/core"; } else if (prefix.equals("jms")) { uri = "http://www.springframework.org/schema/jms"; } else { uri = null; } return uri; } public Iterator getPrefixes(String val) { return null; } public String getPrefix(String uri) { return null; } }; } }
support/src/main/java/org/springframework/roo/support/util/XmlUtils.java
package org.springframework.roo.support.util; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * Utilities related to DOM and XML usage. * * @author Ben Alex * @author Stefan Schmidt * @since 1.0 * */ public abstract class XmlUtils { private static final XPath xpath = XPathFactory.newInstance().newXPath(); private static final Map<String,XPathExpression> compiledExpressionCache = new HashMap<String, XPathExpression>(); public static final void writeXml(OutputStream outputEntry, Document document) { writeXml(createIndentingTransformer(), outputEntry, document); } public static final void writeMalformedXml(OutputStream outputEntry, NodeList nodes) { writeMalformedXml(createIndentingTransformer(), outputEntry, nodes); } // /** // * Obtains an element, throwing an {@link IllegalArgumentException} if not // * found. // * // * <p> // * Internally delegates to // * {@link DomUtils#getChildElementByTagName(Element, String)}. // * // * @param ele // * the DOM element to analyze (required) // * @param childEleName // * the child element name to look for (required) // * @return the Element instance (never null) // */ // public static Element getRequiredChildElementByTagName(Element ele, String childEleName) { // Element e = DomUtils.getChildElementByTagName(ele, childEleName); // Assert.notNull("Unable to obtain element '" + childEleName // + "' from element '" + ele + "'"); // return e; // } // /** // * Checks in under a given root element whether it can find a child element // * with the exact same name and attribute. // * // * @param root // * the parent DOM element // * @param target // * the child DOM element name to look for // * @return the element if discovered, otherwise null // */ // public static Element findElementIfExists(Element root, Element target) { // Assert.notNull(root, "Root element not supplied"); // Assert.notNull(target, "Target element not supplied"); // Element match = null; // // NodeList list = root.getChildNodes(); // for (int i = 0; i < list.getLength(); i++) { // // Node existingNode = list.item(i); // // if (!existingNode.getNodeName().equals(target.getNodeName())) // continue; // // NamedNodeMap existingAttributes = existingNode.getAttributes(); // // // we have a match based on element name only (no target attributes // // existing) // if (existingAttributes == null && target.getAttributes() == null) // return (Element) existingNode; // // if (existingAttributes == null) // continue; // // for (int j = 0; j < existingAttributes.getLength(); j++) { // // Node targetAttribute = target.getAttributes().getNamedItem( // existingAttributes.item(j).getNodeName()); // // // check if the target node has an attribute with the same name // // as one of the existing node attributes // if (targetAttribute == null) // return null; // // // check if the target node has an attribute with the same value // // as one of the existing node attribute values // Attr existingAttribute = (Attr) existingAttributes.item(j); // existingAttribute.getValue(); // if (!targetAttribute.getNodeValue().equals( // existingAttribute.getValue())) // match = null; // else // // the currently checked attribute matches // match = (Element) existingNode; // } // } // return match; // } // /** // * Checks in under a given root element whether it can find a child element // * which contains the text supplied. Returns Element if exists. // * // * @param root // * the parent DOM element // * @param contents // * text contents of the child element to look for // * @return Element if discovered, otherwise null // */ // public static Element findMatchingTextNode(Element root, String contents) { // Assert.notNull(root, "Root element not supplied"); // Assert.hasText(contents, "Text contents not supplied"); // // NodeList list = root.getChildNodes(); // for (int i = 0; i < list.getLength(); i++) { // if (list.item(i) instanceof Element) { // if (((Element) list.item(i)).getFirstChild().getTextContent() // .equals(contents)) // return (Element) list.item(i); // } // } // return null; // } public static final void writeXml(Transformer transformer, OutputStream outputEntry, Document document) { Assert.notNull(transformer, "Transformer required"); Assert.notNull(outputEntry, "Output entry required"); Assert.notNull(document, "Document required"); try { transformer.transform(new DOMSource(document), new StreamResult(new OutputStreamWriter(outputEntry, "ISO-8859-1"/* "UTF-8" */))); } catch (Exception ex) { throw new IllegalStateException(ex); } } public static final void writeMalformedXml(Transformer transformer, OutputStream outputEntry, NodeList nodes) { Assert.notNull(transformer, "Transformer required"); Assert.notNull(outputEntry, "Output entry required"); Assert.notNull(nodes, "NodeList required"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); try { for (int i = 0; i < nodes.getLength(); i++) { transformer.transform(new DOMSource(nodes.item(i)), new StreamResult(new OutputStreamWriter(outputEntry, "ISO-8859-1"))); } } catch (Exception ex) { throw new IllegalStateException(ex); } } /** * Checks in under a given root element whether it can find a child element * which matches the XPath expression supplied. Returns {@link Element} if exists. * * @param xPathExpression the xPathExpression (required) * @param root the parent DOM element (required) * * @return the Element if discovered (null if not found) */ public static Element findFirstElement(String xPathExpression, Element root) { if (xPathExpression == null || root == null || xPathExpression.length() == 0) { throw new IllegalArgumentException("Xpath expression and root element required"); } Element rootElement = null; try { XPathExpression expr = compiledExpressionCache.get(xPathExpression); if (expr == null) { expr = xpath.compile(xPathExpression); compiledExpressionCache.put(xPathExpression, expr); } rootElement = (Element) expr.evaluate(root, XPathConstants.NODE); } catch (XPathExpressionException e) { throw new IllegalArgumentException("Unable evaluate xpath expression", e); } return rootElement; } /** * Checks in under a given root element whether it can find a child element * which matches the name supplied. Returns {@link Element} if exists. * * @param name the Element name (required) * @param root the parent DOM element (required) * * @return the Element if discovered */ public static Element findFirstElementByName(String name, Element root) { Assert.hasText(name, "Element name required"); Assert.notNull(root, "Root element required"); return (Element)root.getElementsByTagName(name).item(0); } /** * Checks in under a given root element whether it can find a child element * which matches the XPath expression supplied. The {@link Element} must exist. * Returns {@link Element} if exists. * * @param xPathExpression the xPathExpression (required) * @param root the parent DOM element (required) * * @return the Element if discovered (never null; an exception is thrown if cannot be found) */ public static Element findRequiredElement(String xPathExpression, Element root) { Assert.hasText(xPathExpression, "XPath expression required"); Assert.notNull(root, "Root element required"); Element element = findFirstElement(xPathExpression, root); Assert.notNull(element, "Unable to obtain required element '" + xPathExpression + "' from element '" + root + "'"); return element; } /** * Checks in under a given root element whether it can find a child elements * which match the XPath expression supplied. Returns a {@link List} of {@link Element} * if they exist. * * @param xPathExpression the xPathExpression * @param root the parent DOM element * * @return a {@link List} of type {@link Element} if discovered, otherwise null */ public static List<Element> findElements(String xPathExpression, Element root) { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); List<Element> elements = new ArrayList<Element>(); NodeList nodes = null; try { XPathExpression expr = xpath.compile(xPathExpression); nodes = (NodeList) expr.evaluate(root, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new IllegalArgumentException("Unable evaluate xpath expression", e); } for (int i = 0; i < nodes.getLength(); i++) { elements.add((Element) nodes.item(i)); } return elements; } /** * @return a transformer that indents entries by 4 characters (never null) */ public static final Transformer createIndentingTransformer() { Transformer xformer; try { xformer = TransformerFactory.newInstance().newTransformer(); } catch (Exception ex) { throw new IllegalStateException(ex); } xformer.setOutputProperty(OutputKeys.INDENT, "yes"); xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); return xformer; } /** * @return a new document builder (never null) */ public static final DocumentBuilder getDocumentBuilder() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { return factory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { throw new IllegalStateException(ex); } } }
ROO-106: Unable to create project from petclinic sample script due to XPath exception
support/src/main/java/org/springframework/roo/support/util/XmlUtils.java
ROO-106: Unable to create project from petclinic sample script due to XPath exception
<ide><path>upport/src/main/java/org/springframework/roo/support/util/XmlUtils.java <ide> import java.io.OutputStreamWriter; <ide> import java.util.ArrayList; <ide> import java.util.HashMap; <add>import java.util.Iterator; <ide> import java.util.List; <ide> import java.util.Map; <ide> <add>import javax.xml.namespace.NamespaceContext; <ide> import javax.xml.parsers.DocumentBuilder; <ide> import javax.xml.parsers.DocumentBuilderFactory; <ide> import javax.xml.parsers.ParserConfigurationException; <ide> /** <ide> * Utilities related to DOM and XML usage. <ide> * <add> * @author Stefan Schmidt <ide> * @author Ben Alex <del> * @author Stefan Schmidt <ide> * @since 1.0 <ide> * <ide> */ <ide> public abstract class XmlUtils { <ide> <del> private static final XPath xpath = XPathFactory.newInstance().newXPath(); <del> private static final Map<String,XPathExpression> compiledExpressionCache = new HashMap<String, XPathExpression>(); <del> <add> private static final Map<String, XPathExpression> compiledExpressionCache = new HashMap<String, XPathExpression>(); <add> <ide> public static final void writeXml(OutputStream outputEntry, Document document) { <ide> writeXml(createIndentingTransformer(), outputEntry, document); <ide> } <ide> writeMalformedXml(createIndentingTransformer(), outputEntry, nodes); <ide> } <ide> <del>// /** <del>// * Obtains an element, throwing an {@link IllegalArgumentException} if not <del>// * found. <del>// * <del>// * <p> <del>// * Internally delegates to <del>// * {@link DomUtils#getChildElementByTagName(Element, String)}. <del>// * <del>// * @param ele <del>// * the DOM element to analyze (required) <del>// * @param childEleName <del>// * the child element name to look for (required) <del>// * @return the Element instance (never null) <del>// */ <del>// public static Element getRequiredChildElementByTagName(Element ele, String childEleName) { <del>// Element e = DomUtils.getChildElementByTagName(ele, childEleName); <del>// Assert.notNull("Unable to obtain element '" + childEleName <del>// + "' from element '" + ele + "'"); <del>// return e; <del>// } <del> <del>// /** <del>// * Checks in under a given root element whether it can find a child element <del>// * with the exact same name and attribute. <del>// * <del>// * @param root <del>// * the parent DOM element <del>// * @param target <del>// * the child DOM element name to look for <del>// * @return the element if discovered, otherwise null <del>// */ <del>// public static Element findElementIfExists(Element root, Element target) { <del>// Assert.notNull(root, "Root element not supplied"); <del>// Assert.notNull(target, "Target element not supplied"); <del>// Element match = null; <del>// <del>// NodeList list = root.getChildNodes(); <del>// for (int i = 0; i < list.getLength(); i++) { <del>// <del>// Node existingNode = list.item(i); <del>// <del>// if (!existingNode.getNodeName().equals(target.getNodeName())) <del>// continue; <del>// <del>// NamedNodeMap existingAttributes = existingNode.getAttributes(); <del>// <del>// // we have a match based on element name only (no target attributes <del>// // existing) <del>// if (existingAttributes == null && target.getAttributes() == null) <del>// return (Element) existingNode; <del>// <del>// if (existingAttributes == null) <del>// continue; <del>// <del>// for (int j = 0; j < existingAttributes.getLength(); j++) { <del>// <del>// Node targetAttribute = target.getAttributes().getNamedItem( <del>// existingAttributes.item(j).getNodeName()); <del>// <del>// // check if the target node has an attribute with the same name <del>// // as one of the existing node attributes <del>// if (targetAttribute == null) <del>// return null; <del>// <del>// // check if the target node has an attribute with the same value <del>// // as one of the existing node attribute values <del>// Attr existingAttribute = (Attr) existingAttributes.item(j); <del>// existingAttribute.getValue(); <del>// if (!targetAttribute.getNodeValue().equals( <del>// existingAttribute.getValue())) <del>// match = null; <del>// else <del>// // the currently checked attribute matches <del>// match = (Element) existingNode; <del>// } <del>// } <del>// return match; <del>// } <del> <del>// /** <del>// * Checks in under a given root element whether it can find a child element <del>// * which contains the text supplied. Returns Element if exists. <del>// * <del>// * @param root <del>// * the parent DOM element <del>// * @param contents <del>// * text contents of the child element to look for <del>// * @return Element if discovered, otherwise null <del>// */ <del>// public static Element findMatchingTextNode(Element root, String contents) { <del>// Assert.notNull(root, "Root element not supplied"); <del>// Assert.hasText(contents, "Text contents not supplied"); <del>// <del>// NodeList list = root.getChildNodes(); <del>// for (int i = 0; i < list.getLength(); i++) { <del>// if (list.item(i) instanceof Element) { <del>// if (((Element) list.item(i)).getFirstChild().getTextContent() <del>// .equals(contents)) <del>// return (Element) list.item(i); <del>// } <del>// } <del>// return null; <del>// } <del> <add> // /** <add> // * Obtains an element, throwing an {@link IllegalArgumentException} if not <add> // * found. <add> // * <add> // * <p> <add> // * Internally delegates to <add> // * {@link DomUtils#getChildElementByTagName(Element, String)}. <add> // * <add> // * @param ele <add> // * the DOM element to analyze (required) <add> // * @param childEleName <add> // * the child element name to look for (required) <add> // * @return the Element instance (never null) <add> // */ <add> // public static Element getRequiredChildElementByTagName(Element ele, <add> // String childEleName) { <add> // Element e = DomUtils.getChildElementByTagName(ele, childEleName); <add> // Assert.notNull("Unable to obtain element '" + childEleName <add> // + "' from element '" + ele + "'"); <add> // return e; <add> // } <add> <add> // /** <add> // * Checks in under a given root element whether it can find a child <add> // element <add> // * with the exact same name and attribute. <add> // * <add> // * @param root <add> // * the parent DOM element <add> // * @param target <add> // * the child DOM element name to look for <add> // * @return the element if discovered, otherwise null <add> // */ <add> // public static Element findElementIfExists(Element root, Element target) { <add> // Assert.notNull(root, "Root element not supplied"); <add> // Assert.notNull(target, "Target element not supplied"); <add> // Element match = null; <add> // <add> // NodeList list = root.getChildNodes(); <add> // for (int i = 0; i < list.getLength(); i++) { <add> // <add> // Node existingNode = list.item(i); <add> // <add> // if (!existingNode.getNodeName().equals(target.getNodeName())) <add> // continue; <add> // <add> // NamedNodeMap existingAttributes = existingNode.getAttributes(); <add> // <add> // // we have a match based on element name only (no target attributes <add> // // existing) <add> // if (existingAttributes == null && target.getAttributes() == null) <add> // return (Element) existingNode; <add> // <add> // if (existingAttributes == null) <add> // continue; <add> // <add> // for (int j = 0; j < existingAttributes.getLength(); j++) { <add> // <add> // Node targetAttribute = target.getAttributes().getNamedItem( <add> // existingAttributes.item(j).getNodeName()); <add> // <add> // // check if the target node has an attribute with the same name <add> // // as one of the existing node attributes <add> // if (targetAttribute == null) <add> // return null; <add> // <add> // // check if the target node has an attribute with the same value <add> // // as one of the existing node attribute values <add> // Attr existingAttribute = (Attr) existingAttributes.item(j); <add> // existingAttribute.getValue(); <add> // if (!targetAttribute.getNodeValue().equals( <add> // existingAttribute.getValue())) <add> // match = null; <add> // else <add> // // the currently checked attribute matches <add> // match = (Element) existingNode; <add> // } <add> // } <add> // return match; <add> // } <add> <add> // /** <add> // * Checks in under a given root element whether it can find a child <add> // element <add> // * which contains the text supplied. Returns Element if exists. <add> // * <add> // * @param root <add> // * the parent DOM element <add> // * @param contents <add> // * text contents of the child element to look for <add> // * @return Element if discovered, otherwise null <add> // */ <add> // public static Element findMatchingTextNode(Element root, String contents) <add> // { <add> // Assert.notNull(root, "Root element not supplied"); <add> // Assert.hasText(contents, "Text contents not supplied"); <add> // <add> // NodeList list = root.getChildNodes(); <add> // for (int i = 0; i < list.getLength(); i++) { <add> // if (list.item(i) instanceof Element) { <add> // if (((Element) list.item(i)).getFirstChild().getTextContent() <add> // .equals(contents)) <add> // return (Element) list.item(i); <add> // } <add> // } <add> // return null; <add> // } <add> <ide> public static final void writeXml(Transformer transformer, OutputStream outputEntry, Document document) { <ide> Assert.notNull(transformer, "Transformer required"); <ide> Assert.notNull(outputEntry, "Output entry required"); <ide> <ide> /** <ide> * Checks in under a given root element whether it can find a child element <del> * which matches the XPath expression supplied. Returns {@link Element} if exists. <del> * <del> * @param xPathExpression the xPathExpression (required) <del> * @param root the parent DOM element (required) <add> * which matches the XPath expression supplied. Returns {@link Element} if <add> * exists. <add> * <add> * @param xPathExpression <add> * the xPathExpression (required) <add> * @param root <add> * the parent DOM element (required) <ide> * <ide> * @return the Element if discovered (null if not found) <ide> */ <ide> if (xPathExpression == null || root == null || xPathExpression.length() == 0) { <ide> throw new IllegalArgumentException("Xpath expression and root element required"); <ide> } <add> <add> XPathFactory factory = XPathFactory.newInstance(); <add> XPath xpath = factory.newXPath(); <add> xpath.setNamespaceContext(getNamespaceContext()); <ide> <ide> Element rootElement = null; <ide> try { <del> <add> <ide> XPathExpression expr = compiledExpressionCache.get(xPathExpression); <ide> if (expr == null) { <ide> expr = xpath.compile(xPathExpression); <ide> } <ide> return rootElement; <ide> } <del> <add> <ide> /** <ide> * Checks in under a given root element whether it can find a child element <ide> * which matches the name supplied. Returns {@link Element} if exists. <ide> * <del> * @param name the Element name (required) <del> * @param root the parent DOM element (required) <add> * @param name <add> * the Element name (required) <add> * @param root <add> * the parent DOM element (required) <ide> * <ide> * @return the Element if discovered <ide> */ <ide> public static Element findFirstElementByName(String name, Element root) { <ide> Assert.hasText(name, "Element name required"); <ide> Assert.notNull(root, "Root element required"); <del> return (Element)root.getElementsByTagName(name).item(0); <del> } <del> <add> return (Element) root.getElementsByTagName(name).item(0); <add> } <add> <ide> /** <ide> * Checks in under a given root element whether it can find a child element <del> * which matches the XPath expression supplied. The {@link Element} must exist. <del> * Returns {@link Element} if exists. <del> * <del> * @param xPathExpression the xPathExpression (required) <del> * @param root the parent DOM element (required) <del> * <del> * @return the Element if discovered (never null; an exception is thrown if cannot be found) <add> * which matches the XPath expression supplied. The {@link Element} must <add> * exist. Returns {@link Element} if exists. <add> * <add> * @param xPathExpression <add> * the xPathExpression (required) <add> * @param root <add> * the parent DOM element (required) <add> * <add> * @return the Element if discovered (never null; an exception is thrown if <add> * cannot be found) <ide> */ <ide> public static Element findRequiredElement(String xPathExpression, Element root) { <ide> Assert.hasText(xPathExpression, "XPath expression required"); <ide> <ide> /** <ide> * Checks in under a given root element whether it can find a child elements <del> * which match the XPath expression supplied. Returns a {@link List} of {@link Element} <del> * if they exist. <del> * <del> * @param xPathExpression the xPathExpression <del> * @param root the parent DOM element <del> * <del> * @return a {@link List} of type {@link Element} if discovered, otherwise null <add> * which match the XPath expression supplied. Returns a {@link List} of <add> * {@link Element} if they exist. <add> * <add> * @param xPathExpression <add> * the xPathExpression <add> * @param root <add> * the parent DOM element <add> * <add> * @return a {@link List} of type {@link Element} if discovered, otherwise <add> * null <ide> */ <ide> public static List<Element> findElements(String xPathExpression, Element root) { <ide> XPathFactory factory = XPathFactory.newInstance(); <ide> XPath xpath = factory.newXPath(); <add> xpath.setNamespaceContext(getNamespaceContext()); <ide> List<Element> elements = new ArrayList<Element>(); <ide> <ide> NodeList nodes = null; <ide> } <ide> <ide> xformer.setOutputProperty(OutputKeys.INDENT, "yes"); <del> xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); <add> xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); <ide> return xformer; <ide> } <ide> <ide> } <ide> } <ide> <add> private static NamespaceContext getNamespaceContext() { <add> return new NamespaceContext() { <add> public String getNamespaceURI(String prefix) { <add> String uri; <add> <add> if (prefix.equals("ns1")) { <add> uri = "http://www.springframework.org/schema/aop"; <add> } else if (prefix.equals("tx")) { <add> uri = "http://www.springframework.org/schema/tx"; <add> } else if (prefix.equals("context")) { <add> uri = "http://www.springframework.org/schema/context"; <add> } else if (prefix.equals("beans")) { <add> uri = "http://www.springframework.org/schema/beans"; <add> } else if (prefix.equals("webflow")) { <add> uri = "http://www.springframework.org/schema/webflow-config"; <add> } else if (prefix.equals("p")) { <add> uri = "http://www.springframework.org/schema/p"; <add> } else if (prefix.equals("security")) { <add> uri = "http://www.springframework.org/schema/security"; <add> } else if (prefix.equals("amq")) { <add> uri = "http://activemq.apache.org/schema/core"; <add> } else if (prefix.equals("jms")) { <add> uri = "http://www.springframework.org/schema/jms"; <add> } else { <add> uri = null; <add> } <add> return uri; <add> } <add> <add> public Iterator getPrefixes(String val) { <add> return null; <add> } <add> <add> public String getPrefix(String uri) { <add> return null; <add> } <add> }; <add> } <ide> }
Java
isc
c0a9654b6a48d16bfa749725f0d5844af7481c38
0
TealCube/strife
/** * The MIT License Copyright (c) 2015 Teal Cube Games * * 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 info.faceland.strife.listeners; import info.faceland.strife.StrifePlugin; import info.faceland.strife.attributes.StrifeAttribute; import info.faceland.strife.data.Champion; import org.bukkit.Material; import org.bukkit.SkullType; import org.bukkit.Sound; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.entity.Skeleton; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import java.util.Random; public class CombatListener implements Listener { private static final String[] DOGE_MEMES = {"<aqua>wow", "<green>wow", "<light purple>wow", "<aqua>much pain", "<green>much pain", "<light purple>much pain", "<aqua>many disrespects", "<green>many disrespects", "<light purple>many disrespects", "<red>no u", "<red>2damage4me"}; private final StrifePlugin plugin; private final Random random; public CombatListener(StrifePlugin plugin) { this.plugin = plugin; random = new Random(System.currentTimeMillis()); } @EventHandler(priority = EventPriority.MONITOR) public void onEntityBurnEvent(EntityDamageEvent event) { if (!(event.getEntity() instanceof LivingEntity)) { return; } if (event.getCause() == EntityDamageEvent.DamageCause.ENTITY_ATTACK) { return; } if (event.getCause() == EntityDamageEvent.DamageCause.FIRE_TICK) { double hpdmg = ((LivingEntity) event.getEntity()).getHealth() / 25; event.setDamage(EntityDamageEvent.DamageModifier.ARMOR, 0); event.setDamage(1 + hpdmg); return; } if (event.getCause() == EntityDamageEvent.DamageCause.FIRE) { double hpdmg = ((LivingEntity) event.getEntity()).getHealth() / 25; event.setDamage(EntityDamageEvent.DamageModifier.ARMOR, 0); event.setDamage(1 + hpdmg); return; } if (event.getCause() == EntityDamageEvent.DamageCause.LAVA) { double hpdmg = ((LivingEntity) event.getEntity()).getHealth() / 20; event.setDamage(EntityDamageEvent.DamageModifier.ARMOR, 0); event.setDamage(1 + hpdmg); } } @EventHandler(priority = EventPriority.HIGHEST) public void onProjectileLaunch(ProjectileLaunchEvent event) { if (event.getEntity().getShooter() instanceof Entity) { event.getEntity().setVelocity(event.getEntity().getVelocity().add(((Entity) event.getEntity() .getShooter()).getVelocity())); } } @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDeath(EntityDeathEvent event) { if (event.getEntity() == null || event.getEntity().getKiller() == null) { return; } double chance = plugin.getChampionManager().getChampion(event.getEntity().getKiller().getUniqueId()) .getCacheAttribute(StrifeAttribute.HEAD_DROP, StrifeAttribute.HEAD_DROP.getBaseValue()); if (chance == 0) { return; } if (random.nextDouble() < chance) { LivingEntity e = event.getEntity(); if (e.getType() == EntityType.SKELETON) { if (((Skeleton) e).getSkeletonType() == Skeleton.SkeletonType.NORMAL) { ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short) 0); e.getWorld().dropItemNaturally(e.getLocation(), skull); } } else if ((e.getType() == EntityType.ZOMBIE)) { ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short) 2); e.getWorld().dropItemNaturally(e.getLocation(), skull); } else if ((e.getType() == EntityType.CREEPER)) { ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short) 4); e.getWorld().dropItemNaturally(e.getLocation(), skull); } else if ((e.getType() == EntityType.PLAYER)) { ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short) SkullType.PLAYER.ordinal()); SkullMeta skullMeta = (SkullMeta) skull.getItemMeta(); skullMeta.setOwner(event.getEntity().getName()); skull.setItemMeta(skullMeta); e.getWorld().dropItemNaturally(e.getLocation(), skull); } } } @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { // check if the event is cancelled // if it is, we do nothing if (event.isCancelled()) { return; } Entity damagingEntity = event.getDamager(); Entity damagedEntity = event.getEntity(); // check if the damaged entity is a living entity // if it isn't, we do nothing if (!(damagedEntity instanceof LivingEntity)) { return; } // check if the entity is an NPC // if it is, we do nothing if (damagedEntity.hasMetadata("NPC")) { return; } // find the living entities and if this is melee LivingEntity damagedLivingEntity = (LivingEntity) damagedEntity; LivingEntity damagingLivingEntity; boolean melee = true; if (damagingEntity instanceof LivingEntity) { damagingLivingEntity = (LivingEntity) damagingEntity; } else if (damagingEntity instanceof Projectile && ((Projectile) damagingEntity).getShooter() instanceof LivingEntity) { damagingLivingEntity = (LivingEntity) ((Projectile) damagingEntity).getShooter(); melee = false; } else { // there are no living entities, back out of this shit // we ain't doin' nothin' return; } // save the old base damage in case we need it double oldBaseDamage = event.getDamage(EntityDamageEvent.DamageModifier.BASE); // cancel out all damage from the old event for (EntityDamageEvent.DamageModifier modifier : EntityDamageEvent.DamageModifier.values()) { if (event.isApplicable(modifier)) { event.setDamage(modifier, 0D); } } // pass information to a new calculator double newBaseDamage = handleDamageCalculations(damagedLivingEntity, damagingLivingEntity, damagingEntity, oldBaseDamage, melee, event.getCause()); // set the base damage of the event event.setDamage(EntityDamageEvent.DamageModifier.BASE, newBaseDamage); } private double handleDamageCalculations(LivingEntity damagedLivingEntity, LivingEntity damagingLivingEntity, Entity damagingEntity, double oldBaseDamage, boolean melee, EntityDamageEvent.DamageCause cause) { double retDamage = 0D; // four branches: PvP, PvE, EvP, EvE if (damagedLivingEntity instanceof Player && damagingLivingEntity instanceof Player) { // PvP branch retDamage = handlePlayerVersusPlayerCalculation((Player) damagedLivingEntity, (Player) damagingLivingEntity, damagingEntity, melee); } else if (!(damagedLivingEntity instanceof Player) && damagingLivingEntity instanceof Player) { // PvE branch retDamage = handlePlayerVersusEnvironmentCalculation(damagedLivingEntity, (Player) damagingLivingEntity, damagingEntity, melee); } else if (damagedLivingEntity instanceof Player) { // EvP branch retDamage = handleEnvironmentVersusPlayerCalculation((Player) damagedLivingEntity, damagingLivingEntity, damagingEntity, melee); } else { // EvE branch retDamage = handleEnvironmentVersusEnvironmentCalculation(damagedLivingEntity, damagingLivingEntity, damagingEntity, oldBaseDamage, cause); } return retDamage; } private double handleEnvironmentVersusEnvironmentCalculation(LivingEntity damagedLivingEntity, LivingEntity damagingLivingEntity, Entity damagingEntity, double oldBaseDamage, EntityDamageEvent.DamageCause cause) { double damage; if (damagingLivingEntity.hasMetadata("DAMAGE")) { damage = getDamageFromMeta(damagingLivingEntity, damagedLivingEntity, cause); } else { damage = oldBaseDamage; } return damage; } private double handleEnvironmentVersusPlayerCalculation(Player damagedPlayer, LivingEntity damagingLivingEntity, Entity damagingEntity, boolean melee) { return 0; } private double handlePlayerVersusEnvironmentCalculation(LivingEntity damagedLivingEntity, Player damagingPlayer, Entity damagingEntity, boolean melee) { return 0; } private double handlePlayerVersusPlayerCalculation(Player damagedPlayer, Player damagingPlayer, Entity damagingEntity, boolean melee) { double retDamage; // get the champions Champion damagedChampion = plugin.getChampionManager().getChampion(damagedPlayer.getUniqueId()); Champion damagingChampion = plugin.getChampionManager().getChampion(damagingPlayer.getUniqueId()); // ensure that they have the correct caches damagedChampion.getWeaponAttributeValues(); damagedChampion.recombineCache(); damagingChampion.getWeaponAttributeValues(); damagingChampion.recombineCache(); // get the PvP damage multiplier double pvpMult = plugin.getSettings().getDouble("config.pvp-multiplier", 0.5); // get the evasion chance of the damaged champion and check if evaded double evadeChance = damagedChampion.getCacheAttribute(StrifeAttribute.EVASION); if (evadeChance > 0) { // get the accuracy of the damaging champion and check if still hits double accuracy = damagingChampion.getCacheAttribute(StrifeAttribute.ACCURACY); double normalizedEvadeChance = Math.max(evadeChance * (1 - accuracy), 0); double evasionCalc = 1 - (100 / (100 + (Math.pow(normalizedEvadeChance * 100, 1.1)))); if (random.nextDouble() < evasionCalc) { if (damagingEntity instanceof Projectile) { damagingEntity.remove(); } damagedPlayer.getWorld().playSound(damagedPlayer.getEyeLocation(), Sound.GHAST_FIREBALL, 0.5f, 2f); return 0D; } } // calculating attack speed and velocity double attackSpeedMult = 1D; double velocityMult = 1D; if (melee) { double attackSpeed = StrifeAttribute.ATTACK_SPEED.getBaseValue() * (1 / (1 + damagingChampion .getCacheAttribute(StrifeAttribute.ATTACK_SPEED))); long timeLeft = plugin.getAttackSpeedTask().getTimeLeft(damagingPlayer.getUniqueId()); long timeToSet = Math.round(Math.max(4.0 * attackSpeed, 0D)); if (timeLeft > 0) { attackSpeedMult = Math.max(1.0 - 1.0 * (timeLeft / timeToSet), 0.0); } plugin.getAttackSpeedTask().setTimeLeft(damagingPlayer.getUniqueId(), timeToSet); retDamage = damagingChampion.getCacheAttribute(StrifeAttribute.MELEE_DAMAGE) * attackSpeedMult; } else { velocityMult = Math.min(damagingEntity.getVelocity().lengthSquared() / 9D, 1); retDamage = damagingChampion.getCacheAttribute(StrifeAttribute.RANGED_DAMAGE) * velocityMult; } // check if damaged player is blocking if (damagedPlayer.isBlocking()) { if (random.nextDouble() < damagedChampion.getCacheAttribute(StrifeAttribute.ABSORB_CHANCE)) { if (damagingEntity instanceof Projectile) { damagingEntity.remove(); } damagedPlayer.setHealth(Math.min(damagedPlayer.getHealth() + (damagedPlayer.getMaxHealth() / 25), damagedPlayer.getMaxHealth())); damagedPlayer.getWorld().playSound(damagingPlayer.getEyeLocation(), Sound.BLAZE_HIT, 1f, 2f); return 0D; } if (melee) { if (random.nextDouble() < damagedChampion.getCacheAttribute(StrifeAttribute.PARRY)) { damagingPlayer.damage(retDamage * 0.2 * pvpMult); damagedPlayer.getWorld().playSound(damagedPlayer.getEyeLocation(), Sound.ANVIL_LAND, 1f, 2f); return 0D; } } else { if (random.nextDouble() < 2 * damagedChampion.getCacheAttribute(StrifeAttribute.PARRY)) { if (damagingEntity instanceof Projectile) { damagingEntity.remove(); } damagingPlayer.damage(retDamage * 0.2 * pvpMult); damagedPlayer.getWorld().playSound(damagedPlayer.getEyeLocation(), Sound.ANVIL_LAND, 1f, 2f); return 0D; } } retDamage *= 1 - (damagedChampion.getCacheAttribute(StrifeAttribute.BLOCK)); } // critical damage time! double critBonus = retDamage * getCritBonus(damagingChampion.getCacheAttribute(StrifeAttribute.CRITICAL_RATE), damagingChampion.getCacheAttribute(StrifeAttribute.CRITICAL_DAMAGE), damagingPlayer); // overbonus time! double overBonus = 0D; if (melee) { if (attackSpeedMult > 0.94) { overBonus = damagingChampion.getCacheAttribute(StrifeAttribute.OVERCHARGE) * retDamage; } } else { if (velocityMult > 0.94) { overBonus = damagingChampion.getCacheAttribute(StrifeAttribute.OVERCHARGE) * retDamage; } } // adding critBonus and overBonus to damage retDamage += critBonus; retDamage += overBonus; // elements calculations double trueDamage = 0D; double fireDamage = damagingChampion.getCacheAttribute(StrifeAttribute.FIRE_DAMAGE); double lightningDamage = damagingChampion.getCacheAttribute(StrifeAttribute.LIGHTNING_DAMAGE); double iceDamage = damagingChampion.getCacheAttribute(StrifeAttribute.ICE_DAMAGE); if (fireDamage > 0D) { double igniteCalc = damagingChampion.getCacheAttribute(StrifeAttribute.IGNITE_CHANCE) * (0.25 + attackSpeedMult * 0.75) * (1 - damagedChampion.getCacheAttribute(StrifeAttribute.RESISTANCE)); if (random.nextDouble() < igniteCalc) { trueDamage += fireDamage * 0.10D; damagedPlayer.setFireTicks(Math.max(10 + (int) Math.round(fireDamage * 20), damagedPlayer.getFireTicks())); damagedPlayer.playSound(damagedPlayer.getEyeLocation(), Sound.FIRE_IGNITE, 1f, 1f); } } if (lightningDamage > 0D) { double shockCalc = damagingChampion.getCacheAttribute(StrifeAttribute.SHOCK_CHANCE) * (0.25 + attackSpeedMult * 0.75) * (1 - damagedChampion.getCacheAttribute(StrifeAttribute.RESISTANCE)); if (random.nextDouble() < shockCalc) { trueDamage += lightningDamage * 0.75D; damagedPlayer.getWorld().playSound(damagedPlayer.getEyeLocation(), Sound.AMBIENCE_THUNDER, 1f, 1.5f); } } if (iceDamage > 0D) { double freezeCalc = damagingChampion.getCacheAttribute(StrifeAttribute.FREEZE_CHANCE) * (0.25 + attackSpeedMult * 0.75) * (1 - damagedChampion.getCacheAttribute(StrifeAttribute.RESISTANCE)); if (random.nextDouble() < freezeCalc) { retDamage += iceDamage + iceDamage * (damagedPlayer.getMaxHealth() / 300); damagedPlayer.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 5 + (int) iceDamage * 3, 1)); damagedPlayer.getWorld().playSound(damagedPlayer.getEyeLocation(), Sound.GLASS, 1f, 1f); } } // potion effects mults double potionMult = 1D; if (damagedPlayer.hasPotionEffect(PotionEffectType.WITHER)) { potionMult += 0.1D; } if (damagedPlayer.hasPotionEffect(PotionEffectType.DAMAGE_RESISTANCE)) { potionMult -= 0.1D; } if (melee) { if (damagingPlayer.hasPotionEffect(PotionEffectType.INCREASE_DAMAGE)) { potionMult += 0.1D; } if (damagingPlayer.hasPotionEffect(PotionEffectType.WEAKNESS)) { potionMult -= 0.1D; } } else { double snareChance = damagingChampion.getCacheAttribute(StrifeAttribute.SNARE_CHANCE); if (snareChance > 0) { if (random.nextDouble() < snareChance) { damagedPlayer.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 30, 5)); damagedPlayer.getWorld().playSound(damagedPlayer.getEyeLocation(), Sound.FIRE_IGNITE, 1f, 1f); } } } // combine! retDamage *= potionMult; retDamage *= getArmorMult(damagedChampion.getCacheAttribute(StrifeAttribute.ARMOR), damagingChampion .getCacheAttribute(StrifeAttribute.ARMOR_PENETRATION)); retDamage += trueDamage; retDamage *= pvpMult; // life steal double lifeSteal = damagingChampion.getCacheAttribute(StrifeAttribute.LIFE_STEAL); if (lifeSteal > 0) { double lifeStolen = retDamage * lifeSteal; lifeStolen *= Math.min(damagedPlayer.getFoodLevel() / 7.0D, 1.0D); if (damagingPlayer.hasPotionEffect(PotionEffectType.POISON)) { lifeStolen *= 0.34; } if (damagingPlayer.getHealth() > 0) { damagingPlayer.setHealth(Math.min(damagingPlayer.getHealth() + lifeStolen, damagingPlayer.getMaxHealth())); } } return retDamage; } private double getDamageFromMeta(LivingEntity a, LivingEntity b, EntityDamageEvent.DamageCause d) { double damage = a.getMetadata("DAMAGE").get(0).asDouble(); if (d == EntityDamageEvent.DamageCause.ENTITY_EXPLOSION) { damage = damage * Math.max(0.3, 2.5 / (a.getLocation().distanceSquared(b.getLocation()) + 1)); } return damage; } private double getArmorMult(double armor, double apen) { if (armor > 0) { if (apen < 1) { return 100 / (100 + (Math.pow(((armor * (1 - apen)) * 100), 1.2))); } else { return 1 + ((apen - 1) / 5); } } else { return 1 + (apen / 5); } } private double getCritBonus(double rate, double damage, Player a) { if (random.nextDouble() < rate) { a.getWorld().playSound(a.getEyeLocation(), Sound.FALL_BIG, 2f, 0.8f); return damage - 1.0; } return 1.0; } }
src/main/java/info/faceland/strife/listeners/CombatListener.java
/** * The MIT License Copyright (c) 2015 Teal Cube Games * * 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 info.faceland.strife.listeners; import info.faceland.strife.StrifePlugin; import info.faceland.strife.attributes.StrifeAttribute; import info.faceland.strife.data.Champion; import org.bukkit.Material; import org.bukkit.SkullType; import org.bukkit.Sound; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.entity.Skeleton; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import java.util.Random; public class CombatListener implements Listener { private static final String[] DOGE_MEMES = {"<aqua>wow", "<green>wow", "<light purple>wow", "<aqua>much pain", "<green>much pain", "<light purple>much pain", "<aqua>many disrespects", "<green>many disrespects", "<light purple>many disrespects", "<red>no u", "<red>2damage4me"}; private final StrifePlugin plugin; private final Random random; public CombatListener(StrifePlugin plugin) { this.plugin = plugin; random = new Random(System.currentTimeMillis()); } @EventHandler(priority = EventPriority.MONITOR) public void onEntityBurnEvent(EntityDamageEvent event) { if (!(event.getEntity() instanceof LivingEntity)) { return; } if (event.getCause() == EntityDamageEvent.DamageCause.ENTITY_ATTACK) { return; } if (event.getCause() == EntityDamageEvent.DamageCause.FIRE_TICK) { double hpdmg = ((LivingEntity) event.getEntity()).getHealth() / 25; event.setDamage(EntityDamageEvent.DamageModifier.ARMOR, 0); event.setDamage(1 + hpdmg); return; } if (event.getCause() == EntityDamageEvent.DamageCause.FIRE) { double hpdmg = ((LivingEntity) event.getEntity()).getHealth() / 25; event.setDamage(EntityDamageEvent.DamageModifier.ARMOR, 0); event.setDamage(1 + hpdmg); return; } if (event.getCause() == EntityDamageEvent.DamageCause.LAVA) { double hpdmg = ((LivingEntity) event.getEntity()).getHealth() / 20; event.setDamage(EntityDamageEvent.DamageModifier.ARMOR, 0); event.setDamage(1 + hpdmg); } } @EventHandler(priority = EventPriority.HIGHEST) public void onProjectileLaunch(ProjectileLaunchEvent event) { if (event.getEntity().getShooter() instanceof Entity) { event.getEntity().setVelocity(event.getEntity().getVelocity().add(((Entity) event.getEntity() .getShooter()).getVelocity())); } } @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDeath(EntityDeathEvent event) { if (event.getEntity() == null || event.getEntity().getKiller() == null) { return; } double chance = plugin.getChampionManager().getChampion(event.getEntity().getKiller().getUniqueId()) .getCacheAttribute(StrifeAttribute.HEAD_DROP, StrifeAttribute.HEAD_DROP.getBaseValue()); if (chance == 0) { return; } if (random.nextDouble() < chance) { LivingEntity e = event.getEntity(); if (e.getType() == EntityType.SKELETON) { if (((Skeleton) e).getSkeletonType() == Skeleton.SkeletonType.NORMAL) { ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short) 0); e.getWorld().dropItemNaturally(e.getLocation(), skull); } } else if ((e.getType() == EntityType.ZOMBIE)) { ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short) 2); e.getWorld().dropItemNaturally(e.getLocation(), skull); } else if ((e.getType() == EntityType.CREEPER)) { ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short) 4); e.getWorld().dropItemNaturally(e.getLocation(), skull); } else if ((e.getType() == EntityType.PLAYER)) { ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short) SkullType.PLAYER.ordinal()); SkullMeta skullMeta = (SkullMeta) skull.getItemMeta(); skullMeta.setOwner(event.getEntity().getName()); skull.setItemMeta(skullMeta); e.getWorld().dropItemNaturally(e.getLocation(), skull); } } } @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { // check if the event is cancelled // if it is, we do nothing if (event.isCancelled()) { return; } Entity damagingEntity = event.getDamager(); Entity damagedEntity = event.getEntity(); // check if the damaged entity is a living entity // if it isn't, we do nothing if (!(damagedEntity instanceof LivingEntity)) { return; } // check if the entity is an NPC // if it is, we do nothing if (damagedEntity.hasMetadata("NPC")) { return; } // find the living entities and if this is melee LivingEntity damagedLivingEntity = (LivingEntity) damagedEntity; LivingEntity damagingLivingEntity; boolean melee = true; if (damagingEntity instanceof LivingEntity) { damagingLivingEntity = (LivingEntity) damagingEntity; } else if (damagingEntity instanceof Projectile && ((Projectile) damagingEntity).getShooter() instanceof LivingEntity) { damagingLivingEntity = (LivingEntity) ((Projectile) damagingEntity).getShooter(); melee = false; } else { // there are no living entities, back out of this shit // we ain't doin' nothin' return; } // save the old base damage in case we need it double oldBaseDamage = event.getDamage(EntityDamageEvent.DamageModifier.BASE); // cancel out all damage from the old event for (EntityDamageEvent.DamageModifier modifier : EntityDamageEvent.DamageModifier.values()) { if (event.isApplicable(modifier)) { event.setDamage(modifier, 0D); } } // pass information to a new calculator double newBaseDamage = handleDamageCalculations(damagedLivingEntity, damagingLivingEntity, damagingEntity, oldBaseDamage, melee); // set the base damage of the event event.setDamage(EntityDamageEvent.DamageModifier.BASE, newBaseDamage); } private double handleDamageCalculations(LivingEntity damagedLivingEntity, LivingEntity damagingLivingEntity, Entity damagingEntity, double oldBaseDamage, boolean melee) { double retDamage = 0D; // four branches: PvP, PvE, EvP, EvE if (damagedLivingEntity instanceof Player && damagingLivingEntity instanceof Player) { // PvP branch retDamage = handlePlayerVersusPlayerCalculation((Player) damagedLivingEntity, (Player) damagingLivingEntity, damagingEntity, melee); } else if (!(damagedLivingEntity instanceof Player) && damagingLivingEntity instanceof Player) { // PvE branch retDamage = handlePlayerVersusEnvironmentCalculation(damagedLivingEntity, (Player) damagingLivingEntity, damagingEntity, melee); } else if (damagedLivingEntity instanceof Player) { // EvP branch retDamage = handleEnvironmentVersusPlayerCalculation((Player) damagedLivingEntity, damagingLivingEntity, damagingEntity, melee); } else { // EvE branch retDamage = handleEnvironmentVersusEnvironmentCalculation(damagedLivingEntity, damagingLivingEntity, damagingEntity, melee); } return retDamage; } private double handleEnvironmentVersusEnvironmentCalculation(LivingEntity damagedLivingEntity, LivingEntity damagingLivingEntity, Entity damagingEntity, boolean melee) { return 0; } private double handleEnvironmentVersusPlayerCalculation(Player damagedPlayer, LivingEntity damagingLivingEntity, Entity damagingEntity, boolean melee) { return 0; } private double handlePlayerVersusEnvironmentCalculation(LivingEntity damagedLivingEntity, Player damagingPlayer, Entity damagingEntity, boolean melee) { return 0; } private double handlePlayerVersusPlayerCalculation(Player damagedPlayer, Player damagingPlayer, Entity damagingEntity, boolean melee) { double retDamage; // get the champions Champion damagedChampion = plugin.getChampionManager().getChampion(damagedPlayer.getUniqueId()); Champion damagingChampion = plugin.getChampionManager().getChampion(damagingPlayer.getUniqueId()); // ensure that they have the correct caches damagedChampion.getWeaponAttributeValues(); damagedChampion.recombineCache(); damagingChampion.getWeaponAttributeValues(); damagingChampion.recombineCache(); // get the PvP damage multiplier double pvpMult = plugin.getSettings().getDouble("config.pvp-multiplier", 0.5); // get the evasion chance of the damaged champion and check if evaded double evadeChance = damagedChampion.getCacheAttribute(StrifeAttribute.EVASION); if (evadeChance > 0) { // get the accuracy of the damaging champion and check if still hits double accuracy = damagingChampion.getCacheAttribute(StrifeAttribute.ACCURACY); double normalizedEvadeChance = Math.max(evadeChance * (1 - accuracy), 0); double evasionCalc = 1 - (100 / (100 + (Math.pow(normalizedEvadeChance * 100, 1.1)))); if (random.nextDouble() < evasionCalc) { if (damagingEntity instanceof Projectile) { damagingEntity.remove(); } damagedPlayer.getWorld().playSound(damagedPlayer.getEyeLocation(), Sound.GHAST_FIREBALL, 0.5f, 2f); return 0D; } } // calculating attack speed and velocity double attackSpeedMult = 1D; double velocityMult = 1D; if (melee) { double attackSpeed = StrifeAttribute.ATTACK_SPEED.getBaseValue() * (1 / (1 + damagingChampion .getCacheAttribute(StrifeAttribute.ATTACK_SPEED))); long timeLeft = plugin.getAttackSpeedTask().getTimeLeft(damagingPlayer.getUniqueId()); long timeToSet = Math.round(Math.max(4.0 * attackSpeed, 0D)); if (timeLeft > 0) { attackSpeedMult = Math.max(1.0 - 1.0 * (timeLeft / timeToSet), 0.0); } plugin.getAttackSpeedTask().setTimeLeft(damagingPlayer.getUniqueId(), timeToSet); retDamage = damagingChampion.getCacheAttribute(StrifeAttribute.MELEE_DAMAGE) * attackSpeedMult; } else { velocityMult = Math.min(damagingEntity.getVelocity().lengthSquared() / 9D, 1); retDamage = damagingChampion.getCacheAttribute(StrifeAttribute.RANGED_DAMAGE) * velocityMult; } // check if damaged player is blocking if (damagedPlayer.isBlocking()) { if (random.nextDouble() < damagedChampion.getCacheAttribute(StrifeAttribute.ABSORB_CHANCE)) { if (damagingEntity instanceof Projectile) { damagingEntity.remove(); } damagedPlayer.setHealth(Math.min(damagedPlayer.getHealth() + (damagedPlayer.getMaxHealth() / 25), damagedPlayer.getMaxHealth())); damagedPlayer.getWorld().playSound(damagingPlayer.getEyeLocation(), Sound.BLAZE_HIT, 1f, 2f); return 0D; } if (melee) { if (random.nextDouble() < damagedChampion.getCacheAttribute(StrifeAttribute.PARRY)) { damagingPlayer.damage(retDamage * 0.2 * pvpMult); damagedPlayer.getWorld().playSound(damagedPlayer.getEyeLocation(), Sound.ANVIL_LAND, 1f, 2f); return 0D; } } else { if (random.nextDouble() < 2 * damagedChampion.getCacheAttribute(StrifeAttribute.PARRY)) { if (damagingEntity instanceof Projectile) { damagingEntity.remove(); } damagingPlayer.damage(retDamage * 0.2 * pvpMult); damagedPlayer.getWorld().playSound(damagedPlayer.getEyeLocation(), Sound.ANVIL_LAND, 1f, 2f); return 0D; } } retDamage *= 1 - (damagedChampion.getCacheAttribute(StrifeAttribute.BLOCK)); } // critical damage time! double critBonus = retDamage * getCritBonus(damagingChampion.getCacheAttribute(StrifeAttribute.CRITICAL_RATE), damagingChampion.getCacheAttribute(StrifeAttribute.CRITICAL_DAMAGE), damagingPlayer); // overbonus time! double overBonus = 0D; if (melee) { if (attackSpeedMult > 0.94) { overBonus = damagingChampion.getCacheAttribute(StrifeAttribute.OVERCHARGE) * retDamage; } } else { if (velocityMult > 0.94) { overBonus = damagingChampion.getCacheAttribute(StrifeAttribute.OVERCHARGE) * retDamage; } } // adding critBonus and overBonus to damage retDamage += critBonus; retDamage += overBonus; // elements calculations double trueDamage = 0D; double fireDamage = damagingChampion.getCacheAttribute(StrifeAttribute.FIRE_DAMAGE); double lightningDamage = damagingChampion.getCacheAttribute(StrifeAttribute.LIGHTNING_DAMAGE); double iceDamage = damagingChampion.getCacheAttribute(StrifeAttribute.ICE_DAMAGE); if (fireDamage > 0D) { double igniteCalc = damagingChampion.getCacheAttribute(StrifeAttribute.IGNITE_CHANCE) * (0.25 + attackSpeedMult * 0.75) * (1 - damagedChampion.getCacheAttribute(StrifeAttribute.RESISTANCE)); if (random.nextDouble() < igniteCalc) { trueDamage += fireDamage * 0.10D; damagedPlayer.setFireTicks(Math.max(10 + (int) Math.round(fireDamage * 20), damagedPlayer.getFireTicks())); damagedPlayer.playSound(damagedPlayer.getEyeLocation(), Sound.FIRE_IGNITE, 1f, 1f); } } if (lightningDamage > 0D) { double shockCalc = damagingChampion.getCacheAttribute(StrifeAttribute.SHOCK_CHANCE) * (0.25 + attackSpeedMult * 0.75) * (1 - damagedChampion.getCacheAttribute(StrifeAttribute.RESISTANCE)); if (random.nextDouble() < shockCalc) { trueDamage += lightningDamage * 0.75D; damagedPlayer.getWorld().playSound(damagedPlayer.getEyeLocation(), Sound.AMBIENCE_THUNDER, 1f, 1.5f); } } if (iceDamage > 0D) { double freezeCalc = damagingChampion.getCacheAttribute(StrifeAttribute.FREEZE_CHANCE) * (0.25 + attackSpeedMult * 0.75) * (1 - damagedChampion.getCacheAttribute(StrifeAttribute.RESISTANCE)); if (random.nextDouble() < freezeCalc) { retDamage += iceDamage + iceDamage * (damagedPlayer.getMaxHealth() / 300); damagedPlayer.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 5 + (int) iceDamage * 3, 1)); damagedPlayer.getWorld().playSound(damagedPlayer.getEyeLocation(), Sound.GLASS, 1f, 1f); } } // potion effects mults double potionMult = 1D; if (damagedPlayer.hasPotionEffect(PotionEffectType.WITHER)) { potionMult += 0.1D; } if (damagedPlayer.hasPotionEffect(PotionEffectType.DAMAGE_RESISTANCE)) { potionMult -= 0.1D; } if (melee) { if (damagingPlayer.hasPotionEffect(PotionEffectType.INCREASE_DAMAGE)) { potionMult += 0.1D; } if (damagingPlayer.hasPotionEffect(PotionEffectType.WEAKNESS)) { potionMult -= 0.1D; } } else { double snareChance = damagingChampion.getCacheAttribute(StrifeAttribute.SNARE_CHANCE); if (snareChance > 0) { if (random.nextDouble() < snareChance) { damagedPlayer.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 30, 5)); damagedPlayer.getWorld().playSound(damagedPlayer.getEyeLocation(), Sound.FIRE_IGNITE, 1f, 1f); } } } // combine! retDamage *= potionMult; retDamage *= getArmorMult(damagedChampion.getCacheAttribute(StrifeAttribute.ARMOR), damagingChampion .getCacheAttribute(StrifeAttribute.ARMOR_PENETRATION)); retDamage += trueDamage; retDamage *= pvpMult; // life steal double lifeSteal = damagingChampion.getCacheAttribute(StrifeAttribute.LIFE_STEAL); if (lifeSteal > 0) { double lifeStolen = retDamage * lifeSteal; lifeStolen *= Math.min(damagedPlayer.getFoodLevel() / 7.0D, 1.0D); if (damagingPlayer.hasPotionEffect(PotionEffectType.POISON)) { lifeStolen *= 0.34; } if (damagingPlayer.getHealth() > 0) { damagingPlayer.setHealth(Math.min(damagingPlayer.getHealth() + lifeStolen, damagingPlayer.getMaxHealth())); } } return retDamage; } private double getDamageFromMeta(LivingEntity a, LivingEntity b, EntityDamageEvent.DamageCause d) { double damage = a.getMetadata("DAMAGE").get(0).asDouble(); if (d == EntityDamageEvent.DamageCause.ENTITY_EXPLOSION) { damage = damage * Math.max(0.3, 2.5 / (a.getLocation().distanceSquared(b.getLocation()) + 1)); } return damage; } private double getArmorMult(double armor, double apen) { if (armor > 0) { if (apen < 1) { return 100 / (100 + (Math.pow(((armor * (1 - apen)) * 100), 1.2))); } else { return 1 + ((apen - 1) / 5); } } else { return 1 + (apen / 5); } } private double getCritBonus(double rate, double damage, Player a) { if (random.nextDouble() < rate) { a.getWorld().playSound(a.getEyeLocation(), Sound.FALL_BIG, 2f, 0.8f); return damage - 1.0; } return 1.0; } }
adding EvE damage
src/main/java/info/faceland/strife/listeners/CombatListener.java
adding EvE damage
<ide><path>rc/main/java/info/faceland/strife/listeners/CombatListener.java <ide> <ide> // pass information to a new calculator <ide> double newBaseDamage = handleDamageCalculations(damagedLivingEntity, damagingLivingEntity, damagingEntity, <del> oldBaseDamage, melee); <add> oldBaseDamage, melee, event.getCause()); <ide> <ide> // set the base damage of the event <ide> event.setDamage(EntityDamageEvent.DamageModifier.BASE, newBaseDamage); <ide> LivingEntity damagingLivingEntity, <ide> Entity damagingEntity, <ide> double oldBaseDamage, <del> boolean melee) { <add> boolean melee, <add> EntityDamageEvent.DamageCause cause) { <ide> double retDamage = 0D; <ide> // four branches: PvP, PvE, EvP, EvE <ide> if (damagedLivingEntity instanceof Player && damagingLivingEntity instanceof Player) { <ide> } else { <ide> // EvE branch <ide> retDamage = handleEnvironmentVersusEnvironmentCalculation(damagedLivingEntity, damagingLivingEntity, <del> damagingEntity, melee); <add> damagingEntity, oldBaseDamage, cause); <ide> } <ide> return retDamage; <ide> } <ide> private double handleEnvironmentVersusEnvironmentCalculation(LivingEntity damagedLivingEntity, <ide> LivingEntity damagingLivingEntity, <ide> Entity damagingEntity, <del> boolean melee) { <del> return 0; <add> double oldBaseDamage, <add> EntityDamageEvent.DamageCause cause) { <add> double damage; <add> if (damagingLivingEntity.hasMetadata("DAMAGE")) { <add> damage = getDamageFromMeta(damagingLivingEntity, damagedLivingEntity, cause); <add> } else { <add> damage = oldBaseDamage; <add> } <add> return damage; <ide> } <ide> <ide> private double handleEnvironmentVersusPlayerCalculation(Player damagedPlayer,
Java
apache-2.0
383a7c5f93af1869d7c1fc58b12f4106546ec1cf
0
lgrill-pentaho/pentaho-kettle,stepanovdg/pentaho-kettle,brosander/pentaho-kettle,aminmkhan/pentaho-kettle,pedrofvteixeira/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,tmcsantos/pentaho-kettle,marcoslarsen/pentaho-kettle,flbrino/pentaho-kettle,kurtwalker/pentaho-kettle,matthewtckr/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,denisprotopopov/pentaho-kettle,mbatchelor/pentaho-kettle,mkambol/pentaho-kettle,flbrino/pentaho-kettle,wseyler/pentaho-kettle,pedrofvteixeira/pentaho-kettle,marcoslarsen/pentaho-kettle,tmcsantos/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,HiromuHota/pentaho-kettle,nicoben/pentaho-kettle,ddiroma/pentaho-kettle,nicoben/pentaho-kettle,ccaspanello/pentaho-kettle,pminutillo/pentaho-kettle,marcoslarsen/pentaho-kettle,wseyler/pentaho-kettle,denisprotopopov/pentaho-kettle,rmansoor/pentaho-kettle,graimundo/pentaho-kettle,denisprotopopov/pentaho-kettle,DFieldFL/pentaho-kettle,pentaho/pentaho-kettle,zlcnju/kettle,bmorrise/pentaho-kettle,pminutillo/pentaho-kettle,lgrill-pentaho/pentaho-kettle,ccaspanello/pentaho-kettle,pavel-sakun/pentaho-kettle,emartin-pentaho/pentaho-kettle,matthewtckr/pentaho-kettle,dkincade/pentaho-kettle,nicoben/pentaho-kettle,graimundo/pentaho-kettle,hudak/pentaho-kettle,brosander/pentaho-kettle,mkambol/pentaho-kettle,HiromuHota/pentaho-kettle,hudak/pentaho-kettle,stepanovdg/pentaho-kettle,HiromuHota/pentaho-kettle,pavel-sakun/pentaho-kettle,e-cuellar/pentaho-kettle,cjsonger/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,zlcnju/kettle,hudak/pentaho-kettle,ccaspanello/pentaho-kettle,pentaho/pentaho-kettle,kurtwalker/pentaho-kettle,alina-ipatina/pentaho-kettle,alina-ipatina/pentaho-kettle,e-cuellar/pentaho-kettle,bmorrise/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,alina-ipatina/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,nicoben/pentaho-kettle,lgrill-pentaho/pentaho-kettle,pentaho/pentaho-kettle,stepanovdg/pentaho-kettle,hudak/pentaho-kettle,skofra0/pentaho-kettle,kurtwalker/pentaho-kettle,tkafalas/pentaho-kettle,pminutillo/pentaho-kettle,rmansoor/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,SergeyTravin/pentaho-kettle,DFieldFL/pentaho-kettle,SergeyTravin/pentaho-kettle,pedrofvteixeira/pentaho-kettle,wseyler/pentaho-kettle,aminmkhan/pentaho-kettle,emartin-pentaho/pentaho-kettle,e-cuellar/pentaho-kettle,mkambol/pentaho-kettle,roboguy/pentaho-kettle,pavel-sakun/pentaho-kettle,tkafalas/pentaho-kettle,mbatchelor/pentaho-kettle,aminmkhan/pentaho-kettle,ViswesvarSekar/pentaho-kettle,e-cuellar/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,Advent51/pentaho-kettle,pminutillo/pentaho-kettle,roboguy/pentaho-kettle,pavel-sakun/pentaho-kettle,dkincade/pentaho-kettle,matthewtckr/pentaho-kettle,graimundo/pentaho-kettle,SergeyTravin/pentaho-kettle,rmansoor/pentaho-kettle,ccaspanello/pentaho-kettle,bmorrise/pentaho-kettle,ViswesvarSekar/pentaho-kettle,cjsonger/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,marcoslarsen/pentaho-kettle,emartin-pentaho/pentaho-kettle,SergeyTravin/pentaho-kettle,ViswesvarSekar/pentaho-kettle,graimundo/pentaho-kettle,ddiroma/pentaho-kettle,brosander/pentaho-kettle,pedrofvteixeira/pentaho-kettle,emartin-pentaho/pentaho-kettle,cjsonger/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,ViswesvarSekar/pentaho-kettle,cjsonger/pentaho-kettle,matthewtckr/pentaho-kettle,mbatchelor/pentaho-kettle,zlcnju/kettle,brosander/pentaho-kettle,DFieldFL/pentaho-kettle,tmcsantos/pentaho-kettle,tkafalas/pentaho-kettle,alina-ipatina/pentaho-kettle,zlcnju/kettle,tmcsantos/pentaho-kettle,wseyler/pentaho-kettle,pentaho/pentaho-kettle,denisprotopopov/pentaho-kettle,flbrino/pentaho-kettle,Advent51/pentaho-kettle,HiromuHota/pentaho-kettle,Advent51/pentaho-kettle,stepanovdg/pentaho-kettle,mdamour1976/pentaho-kettle,ddiroma/pentaho-kettle,dkincade/pentaho-kettle,skofra0/pentaho-kettle,DFieldFL/pentaho-kettle,mdamour1976/pentaho-kettle,lgrill-pentaho/pentaho-kettle,rmansoor/pentaho-kettle,mdamour1976/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,flbrino/pentaho-kettle,dkincade/pentaho-kettle,tkafalas/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,mdamour1976/pentaho-kettle,bmorrise/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,roboguy/pentaho-kettle,roboguy/pentaho-kettle,Advent51/pentaho-kettle,mbatchelor/pentaho-kettle,skofra0/pentaho-kettle,kurtwalker/pentaho-kettle,skofra0/pentaho-kettle,aminmkhan/pentaho-kettle,ddiroma/pentaho-kettle,mkambol/pentaho-kettle
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2016 by Pentaho : 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.job.entries.sql; import java.util.Arrays; import java.util.List; import java.util.Map; import org.pentaho.di.job.entry.loadSave.JobEntryLoadSaveTestSupport; public class JobEntrySQLTest extends JobEntryLoadSaveTestSupport<JobEntrySQL> { @Override protected Class<JobEntrySQL> getJobEntryClass() { return JobEntrySQL.class; } @Override protected List<String> listCommonAttributes() { return Arrays.asList( "sql", "useVariableSubstitution", "sqlfromfile", "sqlfilename", "sendOneStatement", "database" ); } @Override protected Map<String, String> createGettersMap() { return toMap( "sql", "getSQL", "useVariableSubstitution", "getUseVariableSubstitution", "sqlfromfile", "getSQLFromFile", "sqlfilename", "getSQLFilename", "sendOneStatement", "isSendOneStatement", "database", "getDatabase" ); } @Override protected Map<String, String> createSettersMap() { return toMap( "sql", "setSQL", "useVariableSubstitution", "setUseVariableSubstitution", "sqlfromfile", "setSQLFromFile", "sqlfilename", "setSQLFilename", "sendOneStatement", "setSendOneStatement", "database", "setDatabase" ); } }
engine/test-src/org/pentaho/di/job/entries/sql/JobEntrySQLTest.java
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2014 by Pentaho : 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.job.entries.sql; import static java.util.Arrays.asList; import java.util.List; import java.util.Map; import org.pentaho.di.job.entry.loadSave.JobEntryLoadSaveTestSupport; public class JobEntrySQLTest extends JobEntryLoadSaveTestSupport<JobEntrySQL> { @Override protected Class<JobEntrySQL> getJobEntryClass() { return JobEntrySQL.class; } @Override protected List<String> listCommonAttributes() { return asList( "sql", "useVariableSubstitution", "sqlfromfile", "sqlfilename", "sendOneStatement" ); } @Override protected Map<String, String> createGettersMap() { return toMap( "sql", "getSQL", "useVariableSubstitution", "getUseVariableSubstitution", "sqlfromfile", "getSQLFromFile", "sqlfilename", "getSQLFilename", "sendOneStatement", "isSendOneStatement" ); } @Override protected Map<String, String> createSettersMap() { return toMap( "sql", "setSQL", "useVariableSubstitution", "setUseVariableSubstitution", "sqlfromfile", "setSQLFromFile", "sqlfilename", "setSQLFilename", "sendOneStatement", "setSendOneStatement" ); } }
[TEST] LoadSave for SQL job entry Added database check
engine/test-src/org/pentaho/di/job/entries/sql/JobEntrySQLTest.java
[TEST] LoadSave for SQL job entry
<ide><path>ngine/test-src/org/pentaho/di/job/entries/sql/JobEntrySQLTest.java <ide> * <ide> * Pentaho Data Integration <ide> * <del> * Copyright (C) 2002-2014 by Pentaho : http://www.pentaho.com <add> * Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com <ide> * <ide> ******************************************************************************* <ide> * <ide> * limitations under the License. <ide> * <ide> ******************************************************************************/ <add> <ide> package org.pentaho.di.job.entries.sql; <ide> <del>import static java.util.Arrays.asList; <del> <add>import java.util.Arrays; <ide> import java.util.List; <ide> import java.util.Map; <ide> <ide> <ide> @Override <ide> protected List<String> listCommonAttributes() { <del> return asList( <add> return Arrays.asList( <ide> "sql", <ide> "useVariableSubstitution", <ide> "sqlfromfile", <ide> "sqlfilename", <del> "sendOneStatement" ); <add> "sendOneStatement", <add> "database" ); <ide> } <ide> <ide> @Override <ide> "useVariableSubstitution", "getUseVariableSubstitution", <ide> "sqlfromfile", "getSQLFromFile", <ide> "sqlfilename", "getSQLFilename", <del> "sendOneStatement", "isSendOneStatement" ); <add> "sendOneStatement", "isSendOneStatement", <add> "database", "getDatabase" ); <ide> } <ide> <ide> @Override <ide> "useVariableSubstitution", "setUseVariableSubstitution", <ide> "sqlfromfile", "setSQLFromFile", <ide> "sqlfilename", "setSQLFilename", <del> "sendOneStatement", "setSendOneStatement" ); <add> "sendOneStatement", "setSendOneStatement", <add> "database", "setDatabase" ); <ide> } <ide> <ide> }
Java
apache-2.0
6a3b2ac913e4882b7086c9039f1bf99356a8b4c7
0
filipebezerra/standardlib,stablekernel/standardlib,rosshambrick/standardlib
package com.stablekernel.standardlib; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.os.Build; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewPropertyAnimatorListenerAdapter; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; public class FloatLabelLayout extends LinearLayout { private static final long ANIMATION_DURATION = 150; private static final float DEFAULT_LABEL_PADDING_LEFT = 3f; private static final float DEFAULT_LABEL_PADDING_TOP = 4f; private static final float DEFAULT_LABEL_PADDING_RIGHT = 3f; private static final float DEFAULT_LABEL_PADDING_BOTTOM = 4f; private EditText mEditText; private TextView mLabel; private CharSequence mHint; private Interpolator mInterpolator; public FloatLabelLayout(Context context) { this(context, null); } public FloatLabelLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public FloatLabelLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setOrientation(VERTICAL); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FloatLabelLayout); int leftPadding = a.getDimensionPixelSize( R.styleable.FloatLabelLayout_floatLabelPaddingLeft, dipsToPix(DEFAULT_LABEL_PADDING_LEFT)); int topPadding = a.getDimensionPixelSize( R.styleable.FloatLabelLayout_floatLabelPaddingTop, dipsToPix(DEFAULT_LABEL_PADDING_TOP)); int rightPadding = a.getDimensionPixelSize( R.styleable.FloatLabelLayout_floatLabelPaddingRight, dipsToPix(DEFAULT_LABEL_PADDING_RIGHT)); int bottomPadding = a.getDimensionPixelSize( R.styleable.FloatLabelLayout_floatLabelPaddingBottom, dipsToPix(DEFAULT_LABEL_PADDING_BOTTOM)); mHint = a.getText(R.styleable.FloatLabelLayout_floatLabelHint); mLabel = new TextView(context); mLabel.setPadding(leftPadding, topPadding, rightPadding, bottomPadding); mLabel.setVisibility(INVISIBLE); mLabel.setText(mHint); ViewCompat.setPivotX(mLabel, 0f); ViewCompat.setPivotY(mLabel, 0f); mLabel.setTextAppearance(context, a.getResourceId(R.styleable.FloatLabelLayout_floatLabelTextAppearance, android.R.style.TextAppearance_Small)); a.recycle(); addView(mLabel, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); if (!isInEditMode()) { mInterpolator = AnimationUtils.loadInterpolator(context, Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? android.R.interpolator.fast_out_slow_in : android.R.anim.decelerate_interpolator); } } @Override public final void addView(View child, int index, ViewGroup.LayoutParams params) { if (child instanceof EditText) { setEditText((EditText) child); } // Carry on adding the View... super.addView(child, index, params); } private void setEditText(EditText editText) { // If we already have an EditText, throw an exception if (mEditText != null) { throw new IllegalArgumentException("We already have an EditText, can only have one"); } mEditText = editText; int padding = (int) DisplayUtils.dpFromPixels(getContext(), 4); mEditText.setPadding(mEditText.getPaddingLeft(),padding,mEditText.getPaddingRight(),mEditText.getPaddingBottom()); // Update the label visibility with no animation updateLabelVisibility(false); // Add a TextWatcher so that we know when the text input has changed mEditText.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { updateLabelVisibility(false); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }); // Add focus listener to the EditText so that we can notify the label that it is activated. // Allows the use of a ColorStateList for the text color on the label mEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean focused) { updateLabelVisibility(true); } }); // If we do not have a valid hint, try and retrieve it from the EditText if (TextUtils.isEmpty(mHint)) { setHint(mEditText.getHint()); } } @Override public void setEnabled(boolean enabled) { mEditText.setEnabled(enabled); super.setEnabled(enabled); } private void updateLabelVisibility(boolean animate) { boolean hasText = !TextUtils.isEmpty(mEditText.getText()); boolean isFocused = mEditText.isFocused(); mLabel.setActivated(isFocused); if (hasText || isFocused) { // We should be showing the label so do so if it isn't already if (mLabel.getVisibility() != VISIBLE) { showLabel(animate); } } else { // We should not be showing the label so hide it if (mLabel.getVisibility() == VISIBLE) { hideLabel(animate); } } } /** * @return the {@link android.widget.EditText} text input */ public EditText getEditText() { return mEditText; } /** * @return the {@link android.widget.TextView} label */ public TextView getLabel() { return mLabel; } /** * Set the hint to be displayed in the floating label */ public void setHint(CharSequence hint) { mHint = hint; mLabel.setText(hint); } /** * Show the label */ private void showLabel(boolean animate) { if (animate) { mLabel.setVisibility(View.VISIBLE); ViewCompat.setTranslationY(mLabel, mLabel.getHeight()); float scale = mEditText.getTextSize() / mLabel.getTextSize(); ViewCompat.setScaleX(mLabel, scale); ViewCompat.setScaleY(mLabel, scale); ViewCompat.animate(mLabel) .translationY(0f) .scaleY(1f) .scaleX(1f) .setDuration(ANIMATION_DURATION) .setListener(null) .setInterpolator(mInterpolator).start(); } else { mLabel.setVisibility(VISIBLE); } mEditText.setHint(null); } /** * Hide the label */ private void hideLabel(boolean animate) { if (animate) { float scale = mEditText.getTextSize() / mLabel.getTextSize(); ViewCompat.setScaleX(mLabel, 1f); ViewCompat.setScaleY(mLabel, 1f); ViewCompat.setTranslationY(mLabel, 0f); ViewCompat.animate(mLabel) .translationY(mLabel.getHeight()) .setDuration(ANIMATION_DURATION) .scaleX(scale) .scaleY(scale) .setListener(new ViewPropertyAnimatorListenerAdapter() { @Override public void onAnimationEnd(View view) { mLabel.setVisibility(INVISIBLE); mEditText.setHint(mHint); } }) .setInterpolator(mInterpolator).start(); } else { mLabel.setVisibility(INVISIBLE); mEditText.setHint(mHint); } } /** * Helper method to convert dips to pixels. */ private int dipsToPix(float dps) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dps, getResources().getDisplayMetrics()); } }
src/main/java/com/stablekernel/standardlib/FloatLabelLayout.java
package com.stablekernel.standardlib; import android.content.Context; import android.content.res.TypedArray; import android.os.Build; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewPropertyAnimatorListenerAdapter; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; public class FloatLabelLayout extends LinearLayout { private static final long ANIMATION_DURATION = 150; private static final float DEFAULT_LABEL_PADDING_LEFT = 3f; private static final float DEFAULT_LABEL_PADDING_TOP = 4f; private static final float DEFAULT_LABEL_PADDING_RIGHT = 3f; private static final float DEFAULT_LABEL_PADDING_BOTTOM = 4f; private EditText mEditText; private TextView mLabel; private CharSequence mHint; private Interpolator mInterpolator; public FloatLabelLayout(Context context) { this(context, null); } public FloatLabelLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public FloatLabelLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setOrientation(VERTICAL); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FloatLabelLayout); int leftPadding = a.getDimensionPixelSize( R.styleable.FloatLabelLayout_floatLabelPaddingLeft, dipsToPix(DEFAULT_LABEL_PADDING_LEFT)); int topPadding = a.getDimensionPixelSize( R.styleable.FloatLabelLayout_floatLabelPaddingTop, dipsToPix(DEFAULT_LABEL_PADDING_TOP)); int rightPadding = a.getDimensionPixelSize( R.styleable.FloatLabelLayout_floatLabelPaddingRight, dipsToPix(DEFAULT_LABEL_PADDING_RIGHT)); int bottomPadding = a.getDimensionPixelSize( R.styleable.FloatLabelLayout_floatLabelPaddingBottom, dipsToPix(DEFAULT_LABEL_PADDING_BOTTOM)); mHint = a.getText(R.styleable.FloatLabelLayout_floatLabelHint); mLabel = new TextView(context); mLabel.setPadding(leftPadding, topPadding, rightPadding, bottomPadding); mLabel.setVisibility(INVISIBLE); mLabel.setText(mHint); ViewCompat.setPivotX(mLabel, 0f); ViewCompat.setPivotY(mLabel, 0f); mLabel.setTextAppearance(context, a.getResourceId(R.styleable.FloatLabelLayout_floatLabelTextAppearance, android.R.style.TextAppearance_Small)); a.recycle(); addView(mLabel, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); if (!isInEditMode()) { mInterpolator = AnimationUtils.loadInterpolator(context, Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? android.R.interpolator.fast_out_slow_in : android.R.anim.decelerate_interpolator); } } @Override public final void addView(View child, int index, ViewGroup.LayoutParams params) { if (child instanceof EditText) { setEditText((EditText) child); } // Carry on adding the View... super.addView(child, index, params); } private void setEditText(EditText editText) { // If we already have an EditText, throw an exception if (mEditText != null) { throw new IllegalArgumentException("We already have an EditText, can only have one"); } mEditText = editText; // Update the label visibility with no animation updateLabelVisibility(false); // Add a TextWatcher so that we know when the text input has changed mEditText.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { updateLabelVisibility(false); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }); // Add focus listener to the EditText so that we can notify the label that it is activated. // Allows the use of a ColorStateList for the text color on the label mEditText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean focused) { updateLabelVisibility(true); } }); // If we do not have a valid hint, try and retrieve it from the EditText if (TextUtils.isEmpty(mHint)) { setHint(mEditText.getHint()); } } @Override public void setEnabled(boolean enabled) { mEditText.setEnabled(enabled); super.setEnabled(enabled); } private void updateLabelVisibility(boolean animate) { boolean hasText = !TextUtils.isEmpty(mEditText.getText()); boolean isFocused = mEditText.isFocused(); mLabel.setActivated(isFocused); if (hasText || isFocused) { // We should be showing the label so do so if it isn't already if (mLabel.getVisibility() != VISIBLE) { showLabel(animate); } } else { // We should not be showing the label so hide it if (mLabel.getVisibility() == VISIBLE) { hideLabel(animate); } } } /** * @return the {@link android.widget.EditText} text input */ public EditText getEditText() { return mEditText; } /** * @return the {@link android.widget.TextView} label */ public TextView getLabel() { return mLabel; } /** * Set the hint to be displayed in the floating label */ public void setHint(CharSequence hint) { mHint = hint; mLabel.setText(hint); } /** * Show the label */ private void showLabel(boolean animate) { if (animate) { mLabel.setVisibility(View.VISIBLE); ViewCompat.setTranslationY(mLabel, mLabel.getHeight()); float scale = mEditText.getTextSize() / mLabel.getTextSize(); ViewCompat.setScaleX(mLabel, scale); ViewCompat.setScaleY(mLabel, scale); ViewCompat.animate(mLabel) .translationY(0f) .scaleY(1f) .scaleX(1f) .setDuration(ANIMATION_DURATION) .setListener(null) .setInterpolator(mInterpolator).start(); } else { mLabel.setVisibility(VISIBLE); } mEditText.setHint(null); } /** * Hide the label */ private void hideLabel(boolean animate) { if (animate) { float scale = mEditText.getTextSize() / mLabel.getTextSize(); ViewCompat.setScaleX(mLabel, 1f); ViewCompat.setScaleY(mLabel, 1f); ViewCompat.setTranslationY(mLabel, 0f); ViewCompat.animate(mLabel) .translationY(mLabel.getHeight()) .setDuration(ANIMATION_DURATION) .scaleX(scale) .scaleY(scale) .setListener(new ViewPropertyAnimatorListenerAdapter() { @Override public void onAnimationEnd(View view) { mLabel.setVisibility(INVISIBLE); mEditText.setHint(mHint); } }) .setInterpolator(mInterpolator).start(); } else { mLabel.setVisibility(INVISIBLE); mEditText.setHint(mHint); } } /** * Helper method to convert dips to pixels. */ private int dipsToPix(float dps) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dps, getResources().getDisplayMetrics()); } }
Changed padding on EditText
src/main/java/com/stablekernel/standardlib/FloatLabelLayout.java
Changed padding on EditText
<ide><path>rc/main/java/com/stablekernel/standardlib/FloatLabelLayout.java <ide> <ide> import android.content.Context; <ide> import android.content.res.TypedArray; <add>import android.graphics.Color; <ide> import android.os.Build; <ide> import android.support.v4.view.ViewCompat; <ide> import android.support.v4.view.ViewPropertyAnimatorListenerAdapter; <ide> throw new IllegalArgumentException("We already have an EditText, can only have one"); <ide> } <ide> mEditText = editText; <add> int padding = (int) DisplayUtils.dpFromPixels(getContext(), 4); <add> mEditText.setPadding(mEditText.getPaddingLeft(),padding,mEditText.getPaddingRight(),mEditText.getPaddingBottom()); <ide> <ide> // Update the label visibility with no animation <ide> updateLabelVisibility(false);
JavaScript
mit
b47008945800cd2b8be8d020f6a9641069fba049
0
halis/halis
(function( _, halisConfig ) { var ns; (function() { var globalNS, conflict; globalNS = halisConfig.namespace || 'halis'; if (window[globalNS]) { conflict = window[globalNS]; } ns = window[globalNS] = {}; if (!window.h) window.h = ns; ns.noConflict = function() { if (conflict) { window[globalNS] = conflict; } return this; }; delete window.halisConfig; }()); ns.typeNames = { Boolean: 'Boolean', Number: 'Number', String: 'String', Date: 'Date', RegExp: 'RegExp', Array: 'Array', Object: 'Object', Element: 'Element', Function: 'Function', }; ns.types = _.keys(ns.typeNames); String.prototype.isEmptyOrWhiteSpace = String.prototype.isEmptyOrWhiteSpace || function() { return this.trim() === ''; }; String.prototype.format = String.prototype.format || function() { var args, regex, esc, lb, rb, lbReplace, rbReplace, argReplace, ctr, that, delimiter; that = this; if (that.isEmptyOrWhiteSpace()) return that; args = _.toArray(arguments); if (!args || !args.length) return that; esc = '\\'; lb = '{'; rb = '}'; that = that.toString(); delimiter = '##%%'; regex = new RegExp(esc + lb + esc + lb, 'g'); lbReplace = delimiter + 'leftbracketreplace' + delimiter; that = that.replace(regex, lbReplace); regex = new RegExp(esc + rb + esc + rb, 'g'); rbReplace = delimiter + 'rightbracketreplace' + delimiter; that = that.replace(regex, rbReplace); ctr = 0; _.each(args, function( arg ) { if (!_.isString(arg)) arg = arg.toString(); argReplace = delimiter + ctr.toString() + delimiter; regex = new RegExp(esc + lb + ctr.toString() + esc + rb, 'g'); that = that.replace(regex, argReplace); ctr++; }.bind(that)); ctr = 0; _.each(args, function( arg ) { argReplace = delimiter + ctr.toString() + delimiter; regex = new RegExp(argReplace, 'g'); that = that.replace(regex, arg); ctr++; }.bind(that)); regex = new RegExp(lbReplace, 'g'); that = that.replace(regex, lb); regex = new RegExp(rbReplace, 'g'); that = that.replace(regex, rb); return that; }; Array.prototype.contains = Array.prototype.contains || function( val ) { return this.indexOf(val) !== -1; }; Date.prototype.toShortDateString = Date.prototype.toShortDateString || function() { return [this.getMonth() + 1, this.getDate(), this.getFullYear() ].join('/'); }; Date.prototype.toShortTimeString = Date.prototype.toShortTimeString || function() { var hours = this.getHours(); return [hours - 12, this.getMinutes() ].join(':') + ' ' + (hours < 12 ? 'AM' : 'PM'); }; Date.prototype.toShortDateTimeString = Date.prototype.toShortDateTimeString || function() { return this.toShortDateString() + ' ' + this.toShortTimeString(); } Date.prototype.toSortString = Date.prototype.toSortString || function() { var month, date, hours, minutes, seconds, ms; month = this.getMonth(); date = this.getDate(); hours = this.getHours(); minutes = this.getMinutes(); seconds = this.getSeconds(); ms = this.getMilliseconds(); function pad( num ) { if (num > 9) return num.toString(); else return '0' + num; } function padMS( num ) { if (num > 99) return num.toString(); else if (num > 9) return '0' + num; else return '00' + num; } return [this.getFullYear(), pad(month), pad(date), pad(hours), pad(minutes), pad(seconds), padMS(ms) ].join(':'); }; _.each(ns.types, function( type ) { var fn, fnName; fn = 'is{0}'.format(type); fnName = '{0}OrThrow'.format(fn); ns[fnName] = function( obj ) { if (!_[fn](obj)) throw 'value is not of type {0}'.format(type); }; }); ns.isArrayAndNotEmptyOrThrow = function( obj ) { ns.isArrayOrThrow(obj); if (_.isEmpty(obj)) throw 'value is empty'; }; ns.isObjectAndNotEmptyOrThrow = function( obj ) { ns.isObjectOrThrow(obj); if (_.isEmpty(obj)) throw 'value is empty'; }; ns.isStringNotEmptyOrThrow = function( obj ) { ns.isStringOrThrow(obj); if (obj.isEmptyOrWhiteSpace()) throw 'value is empty'; }; function HtmlCollection( arr ) { var that = this, h = {}; ns.isArrayOrThrow(arr); that.elements = arr; that.pop = function() { return that.elements.pop(); }; that.push = function( val ) { that.elements.push(val); return that.elements; }; return that; } function query( q, fnName ) { ns.isStringOrThrow(q); return new HtmlCollection(_.toArray(document[fnName](q))); } ns.$ = { id: function( id ) { var el; ns.isStringOrThrow(id); el = d.getElementById(id); return new HtmlCollection(el ? [el] : []); }, klass: function( className ) { return query(className, 'getElementsByClassName'); }, tag: function( tagName ) { return query(tagName, 'getElementsByTagName'); }, name: function( name ) { return query(name, 'getElementsByName'); }, query: function( qry ) { return query(qry, 'querySelectorAll'); }, }; HtmlCollection.prototype.html = function( html ) { ns.isStringOrThrow(html); _.each(this.elements, function( el ) { el.innerHTML = html; }); }; HtmlCollection.prototype.append = function( html ) { ns.isStringOrThrow(html); _.each(this.elements, function( el ) { el.innerHTML += html; }); }; HtmlCollection.prototype.empty = function() { _.each(this.elements, function( el ) { el.innerHTML = ''; }); }; HtmlCollection.prototype.text = function( text ) { ns.isStringOrThrow(text); _.each(this.elements, function( el ) { el.innerText = text; }); }; HtmlCollection.prototype.attr = function( attr, val ) { var result; ns.isStringOrThrow(attr); if (val !== undefined) { _.each(this.elements, function( el ) { el.setAttribute(attr, val); }); return; } result = []; _.each(this.elements, function( el ) { result.push(el.getAttribute(attr)); }); return result; }; HtmlCollection.prototype.on = function( eventName, fn ) { var result; ns.isStringOrThrow(eventName); ns.isFunctionOrThrow(fn); _.each(this.elements, function( el ) { el.addEventListener(eventName, fn, false); if (!el.handlers) el.handlers = new HtmlHandlers(el); el.handlers.add(eventName, fn); }); }; HtmlCollection.prototype.off = function( eventName ) { var handlers; ns.isStringOrThrow(eventName); _.each(this.elements, function( el ) { handlers = el.handlers.get()[eventName]; _.each(handlers, function( handler ) { el.removeEventListener(eventName, handler); }); if (!el.handlers) el.handlers = new HtmlHandlers(el); el.handlers.remove(eventName); }); }; HtmlCollection.prototype.trigger = function( eventName ) { ns.isStringOrThrow(eventName); _.each(this.elements, function( el ) { if (el[eventName] && _.isFunction(el[eventName])) el[eventName](); }); }; function HtmlHandlers( el ) { var that = this; that.el = el; that.handlers = {}; that.get = function() { return that.handlers; }; that.add = function( eventName, handler ) { if (that.handlers[eventName]) that.handlers[eventName].push(handler); else that.handlers[eventName] = [handler]; }; that.remove = function( eventName ) { delete that.handlers[eventName]; }; return that; } ns.cancelEvent = function( e ) { e.preventDefault(); e.stopImmediatePropagation(); return false; }; }(_, window.halisConfig));
halis.js
(function( _, halisConfig ) { var ns; (function() { var globalNS, conflict; globalNS = halisConfig.namespace || 'halis'; if (window[globalNS]) { conflict = window[globalNS]; } ns = window[globalNS] = {}; if (!window.h) window.h = ns; ns.noConflict = function() { if (conflict) { window[globalNS] = conflict; } return this; }; delete window.halisConfig; }()); ns.typeNames = { Boolean: 'Boolean', Number: 'Number', String: 'String', Date: 'Date', RegExp: 'RegExp', Array: 'Array', Object: 'Object', Element: 'Element', Function: 'Function', }; ns.types = _.keys(ns.typeNames); String.prototype.isEmptyOrWhiteSpace = String.prototype.isEmptyOrWhiteSpace || function() { return this.trim() === ''; }; String.prototype.format = String.prototype.format || function() { var args, regex, esc, lb, rb, lbReplace, rbReplace, argReplace, ctr, that, delimiter; that = this; if (that.isEmptyOrWhiteSpace()) return that; args = _.toArray(arguments); if (!args || !args.length) return that; esc = '\\'; lb = '{'; rb = '}'; that = that.toString(); delimiter = '##%%'; regex = new RegExp(esc + lb + esc + lb, 'g'); lbReplace = delimiter + 'leftbracketreplace' + delimiter; that = that.replace(regex, lbReplace); regex = new RegExp(esc + rb + esc + rb, 'g'); rbReplace = delimiter + 'rightbracketreplace' + delimiter; that = that.replace(regex, rbReplace); ctr = 0; _.each(args, function( arg ) { if (!_.isString(arg)) arg = arg.toString(); argReplace = delimiter + ctr.toString() + delimiter; regex = new RegExp(esc + lb + ctr.toString() + esc + rb, 'g'); that = that.replace(regex, argReplace); ctr++; }.bind(that)); ctr = 0; _.each(args, function( arg ) { argReplace = delimiter + ctr.toString() + delimiter; regex = new RegExp(argReplace, 'g'); that = that.replace(regex, arg); ctr++; }.bind(that)); regex = new RegExp(lbReplace, 'g'); that = that.replace(regex, lb); regex = new RegExp(rbReplace, 'g'); that = that.replace(regex, rb); return that; }; Array.prototype.contains = Array.prototype.contains || function( val ) { return this.indexOf(val) !== -1; }; Date.prototype.toShortDateString = Date.prototype.toShortDateString || function() { return [this.getMonth() + 1, this.getDate(), this.getFullYear() ].join('/'); }; Date.prototype.toShortTimeString = Date.prototype.toShortTimeString || function() { var hours = this.getHours(); return [hours - 12, this.getMinutes() ].join(':') + ' ' + (hours < 12 ? 'AM' : 'PM'); }; Date.prototype.toShortDateTimeString = Date.prototype.toShortDateTimeString || function() { return this.toShortDateString() + ' ' + this.toShortTimeString(); } Date.prototype.toSortString = Date.prototype.toSortString || function() { var month, date, hours, minutes, seconds, ms; month = this.getMonth(); date = this.getDate(); hours = this.getHours(); minutes = this.getMinutes(); seconds = this.getSeconds(); ms = this.getMilliseconds(); function pad( num ) { if (num > 9) return num.toString(); else return '0' + num; } function padMS( num ) { if (num > 99) return num.toString(); else if (num > 9) return '0' + num; else return '00' + num; } return [this.getFullYear(), pad(month), pad(date), pad(hours), pad(minutes), pad(seconds), padMS(ms) ].join(':'); }; _.each(ns.types, function( type ) { var fn, fnName; fn = 'is{0}'.format(type); fnName = '{0}OrThrow'.format(fn); ns[fnName] = function( obj ) { if (!_[fn](obj)) throw 'value is not of type {0}'.format(type); }; }); ns.isArrayAndNotEmptyOrThrow = function( obj ) { ns.isArrayOrThrow(obj); if (_.isEmpty(obj)) throw 'value is empty'; }; ns.isObjectAndNotEmptyOrThrow = function( obj ) { ns.isObjectOrThrow(obj); if (_.isEmpty(obj)) throw 'value is empty'; }; ns.isStringNotEmptyOrThrow = function( obj ) { ns.isStringOrThrow(obj); if (obj.isEmptyOrWhiteSpace()) throw 'value is empty'; }; function HtmlCollection( arr ) { var that = this, h = {}; ns.isArrayOrThrow(arr); that.elements = arr; that.pop = function() { return that.elements.pop(); }; that.push = function( val ) { that.elements.push(val); return that.elements; }; return that; } function query( q, fnName ) { ns.isStringOrThrow(q); return new HtmlCollection(_.toArray(document[fnName](q))); } ns.$ = { id: function( id ) { var el; ns.isStringOrThrow(id); el = d.getElementById(id); return new HtmlCollection(el ? [el] : []); }, klass: function( className ) { return query(className, 'getElementsByClassName'); }, tag: function( tagName ) { return query(tagName, 'getElementsByTagName'); }, name: function( name ) { return query(name, 'getElementsByName'); }, query: function( qry ) { return query(qry, 'querySelectorAll'); }, }; HtmlCollection.prototype.html = function( html ) { ns.isStringOrThrow(html); _.each(this.elements, function( el ) { el.innerHTML = html; }); }; HtmlCollection.prototype.append = function( html ) { ns.isStringOrThrow(html); _.each(this.elements, function( el ) { el.innerHTML += html; }); }; HtmlCollection.prototype.empty = function() { _.each(this.elements, function( el ) { el.innerHTML = ''; }); }; HtmlCollection.prototype.text = function( text ) { ns.isStringOrThrow(text); _.each(this.elements, function( el ) { el.innerText = text; }); }; HtmlCollection.prototype.attr = function( attr, val ) { var result; ns.isStringOrThrow(attr); if (val !== undefined) { _.each(this.elements, function( el ) { el.setAttribute(attr, val); }); return; } result = []; _.each(this.elements, function( el ) { result.push(el.getAttribute(attr)); }); return result; }; HtmlCollection.prototype.on = function( eventName, fn ) { var result; ns.isStringOrThrow(eventName); ns.isFunctionOrThrow(fn); _.each(this.elements, function( el ) { el.addEventListener(eventName, fn, false); if (!el.handlers) el.handlers = new HtmlHandlers(el); el.handlers.add(eventName, fn); }); }; HtmlCollection.prototype.off = function( eventName ) { var handlers; ns.isStringOrThrow(eventName); _.each(this.elements, function( el ) { handlers = el.handlers.get()[eventName]; _.each(handlers, function( handler ) { el.removeEventListener(eventName, handler); }); if (!el.handlers) el.handlers = new HtmlHandlers(el); el.handlers.remove(eventName); }); }; HtmlCollection.prototype.trigger = function( eventName ) { ns.isStringOrThrow(eventName); _.each(this.elements, function( el ) { if (el[eventName] && _.isFunction(el[eventName])) el[eventName](); }); }; function HtmlHandlers( el ) { var that = this; that.el = el; that.handlers = {}; that.get = function() { return that.handlers; }; that.add = function( eventName, handler ) { if (that.handlers[eventName]) that.handlers[eventName].push(handler); else that.handlers[eventName] = [handler]; }; that.remove = function( eventName ) { delete that.handlers[eventName]; }; return that; } ns.cancelEvent = function( e ) { e.preventDefault(); e.stopImmediatePropagation(); return false; }; }(_, window.halisConfig));
looked fine in sublime but spacing issues on gh
halis.js
looked fine in sublime but spacing issues on gh
<ide><path>alis.js <ide> <ide> (function( _, halisConfig ) { <del> var ns; <add> var ns; <ide> <ide> (function() { <ide> var globalNS, conflict; <ide> delete window.halisConfig; <ide> }()); <ide> <del> ns.typeNames = { <del> Boolean: 'Boolean', <del> Number: 'Number', <del> String: 'String', <del> Date: 'Date', <del> RegExp: 'RegExp', <del> Array: 'Array', <del> Object: 'Object', <del> Element: 'Element', <del> Function: 'Function', <del> }; <del> ns.types = _.keys(ns.typeNames); <add> ns.typeNames = { <add> Boolean: 'Boolean', <add> Number: 'Number', <add> String: 'String', <add> Date: 'Date', <add> RegExp: 'RegExp', <add> Array: 'Array', <add> Object: 'Object', <add> Element: 'Element', <add> Function: 'Function', <add> }; <add> ns.types = _.keys(ns.typeNames); <ide> <ide> String.prototype.isEmptyOrWhiteSpace = String.prototype.isEmptyOrWhiteSpace || function() { <ide> return this.trim() === ''; <ide> ].join(':'); <ide> }; <ide> <del> _.each(ns.types, function( type ) { <add> _.each(ns.types, function( type ) { <ide> var fn, fnName; <ide> <ide> fn = 'is{0}'.format(type); <ide> ns[fnName] = function( obj ) { <ide> if (!_[fn](obj)) throw 'value is not of type {0}'.format(type); <ide> }; <del> }); <add> }); <ide> <ide> ns.isArrayAndNotEmptyOrThrow = function( obj ) { <ide> ns.isArrayOrThrow(obj);
Java
mit
2cfdf67933cd419823a88d1d92ad91d80097bf1c
0
TheCBProject/EnderStorage
package codechicken.enderstorage.item; import codechicken.enderstorage.api.Frequency; import codechicken.enderstorage.handler.ConfigurationHandler; import codechicken.enderstorage.manager.EnderStorageManager; import codechicken.enderstorage.storage.EnderItemStorage; import codechicken.enderstorage.tile.TileEnderChest; import codechicken.enderstorage.util.LogHelper; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import java.util.List; public class ItemEnderPouch extends Item { public ItemEnderPouch() { setMaxStackSize(1); setCreativeTab(CreativeTabs.TRANSPORTATION); setUnlocalizedName("enderpouch"); } @Override public void addInformation(ItemStack stack, EntityPlayer player, List<String> list, boolean extended) { Frequency freq = Frequency.fromItemStack(stack); if (freq.owner != null) { list.add(freq.owner); } list.add(String.format("%s/%s/%s", freq.getLocalizedLeft(), freq.getLocalizedMiddle(), freq.getLocalizedRight())); //if (stack.hasTagCompound() && !stack.getTagCompound().getString("owner").equals("global")) { // list.add(stack.getTagCompound().getString("owner")); //} } @Override public EnumActionResult onItemUseFirst(ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, EnumHand hand) { if (world.isRemote) { return EnumActionResult.PASS; } TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileEnderChest && player.isSneaking()) { TileEnderChest chest = (TileEnderChest) tile; if (!stack.hasTagCompound()) { stack.setTagCompound(new NBTTagCompound()); } NBTTagCompound frequencyTag = new NBTTagCompound(); Frequency frequency = chest.frequency.copy(); if (ConfigurationHandler.anarchyMode && !frequency.owner.equals(player.getDisplayNameString())) { frequency.setOwner(null); } frequency.writeNBT(frequencyTag); stack.getTagCompound().setTag("Frequency", frequencyTag); //if (!ConfigurationHandler.anarchyMode || chest.owner.equals(player.getDisplayNameString())) { // stack.getTagCompound().setString("owner", chest.owner); //} else { // stack.getTagCompound().setString("owner", "global"); //} return EnumActionResult.SUCCESS; } return EnumActionResult.PASS; } @Override public ActionResult<ItemStack> onItemRightClick(ItemStack stack, World world, EntityPlayer player, EnumHand hand) { if (world.isRemote || player.isSneaking()) { return new ActionResult<ItemStack>(EnumActionResult.PASS, stack); } Frequency frequency = Frequency.fromItemStack(stack); LogHelper.info(frequency.toString()); ((EnderItemStorage) EnderStorageManager.instance(world.isRemote).getStorage(frequency, "item")).openSMPGui(player, stack.getUnlocalizedName() + ".name"); return new ActionResult<ItemStack>(EnumActionResult.SUCCESS, stack); } @Deprecated public String getOwner(ItemStack stack) { return EnderStorageManager.getOwner(stack); } /*@Override public int getRenderPasses(int metadata){ return 4; } @Override public IIcon getIcon(ItemStack stack, int renderPass){ return spriteSheet.getSprite(getIconIndex(stack, renderPass)); } public int getIconIndex(ItemStack stack, int renderPass) { if (renderPass == 0) { int i = 0; if (((EnderItemStorage) EnderStorageManager.instance(true).getStorage(getOwner(stack), Frequency.fromItemStack(stack), "item")).openCount() > 0) { i |= 1; } if (!getOwner(stack).equals("global")) { i |= 2; } return i; } return renderPass * 16 + EnderStorageManager.getColourFromFreq(stack.getItemDamage() & 0xFFF, renderPass - 1); } public boolean requiresMultipleRenderPasses() { return true; } @Override public void registerIcons(IIconRegister register){ spriteSheet = SpriteSheetManager.getSheet(new ResourceLocation("enderstorage", "textures/enderpouch.png")); spriteSheet.requestIndicies(0, 1, 2, 3); for(int i = 16; i < 64; i++) spriteSheet.requestIndicies(i); spriteSheet.registerIcons(register); }*/ }
src/main/java/codechicken/enderstorage/item/ItemEnderPouch.java
package codechicken.enderstorage.item; import codechicken.enderstorage.api.Frequency; import codechicken.enderstorage.handler.ConfigurationHandler; import codechicken.enderstorage.manager.EnderStorageManager; import codechicken.enderstorage.storage.EnderItemStorage; import codechicken.enderstorage.tile.TileEnderChest; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import java.util.List; public class ItemEnderPouch extends Item { public ItemEnderPouch() { setMaxStackSize(1); setCreativeTab(CreativeTabs.TRANSPORTATION); setUnlocalizedName("enderpouch"); } @Override public void addInformation(ItemStack stack, EntityPlayer player, List<String> list, boolean extended) { Frequency freq = Frequency.fromItemStack(stack); if (freq.owner != null) { list.add(freq.owner); } list.add(String.format("%s/%s/%s", freq.getLocalizedLeft(), freq.getLocalizedMiddle(), freq.getLocalizedRight())); //if (stack.hasTagCompound() && !stack.getTagCompound().getString("owner").equals("global")) { // list.add(stack.getTagCompound().getString("owner")); //} } @Override public EnumActionResult onItemUseFirst(ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, EnumHand hand) { if (world.isRemote) { return EnumActionResult.PASS; } TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileEnderChest && player.isSneaking()) { TileEnderChest chest = (TileEnderChest) tile; if (!stack.hasTagCompound()) { stack.setTagCompound(new NBTTagCompound()); } NBTTagCompound frequencyTag = new NBTTagCompound(); Frequency frequency = chest.frequency.copy(); if (ConfigurationHandler.anarchyMode && !frequency.owner.equals(player.getDisplayNameString())) { frequency.setOwner(null); } frequency.writeNBT(frequencyTag); stack.getTagCompound().setTag("Frequency", frequencyTag); //if (!ConfigurationHandler.anarchyMode || chest.owner.equals(player.getDisplayNameString())) { // stack.getTagCompound().setString("owner", chest.owner); //} else { // stack.getTagCompound().setString("owner", "global"); //} return EnumActionResult.SUCCESS; } return EnumActionResult.PASS; } @Override public ActionResult<ItemStack> onItemRightClick(ItemStack stack, World world, EntityPlayer player, EnumHand hand) { if (world.isRemote || player.isSneaking()) { return new ActionResult<ItemStack>(EnumActionResult.PASS, stack); } ((EnderItemStorage) EnderStorageManager.instance(world.isRemote).getStorage(Frequency.fromItemStack(stack), "item")).openSMPGui(player, stack.getUnlocalizedName() + ".name"); return new ActionResult<ItemStack>(EnumActionResult.SUCCESS, stack); } @Deprecated public String getOwner(ItemStack stack) { return EnderStorageManager.getOwner(stack); } /*@Override public int getRenderPasses(int metadata){ return 4; } @Override public IIcon getIcon(ItemStack stack, int renderPass){ return spriteSheet.getSprite(getIconIndex(stack, renderPass)); } public int getIconIndex(ItemStack stack, int renderPass) { if (renderPass == 0) { int i = 0; if (((EnderItemStorage) EnderStorageManager.instance(true).getStorage(getOwner(stack), Frequency.fromItemStack(stack), "item")).openCount() > 0) { i |= 1; } if (!getOwner(stack).equals("global")) { i |= 2; } return i; } return renderPass * 16 + EnderStorageManager.getColourFromFreq(stack.getItemDamage() & 0xFFF, renderPass - 1); } public boolean requiresMultipleRenderPasses() { return true; } @Override public void registerIcons(IIconRegister register){ spriteSheet = SpriteSheetManager.getSheet(new ResourceLocation("enderstorage", "textures/enderpouch.png")); spriteSheet.requestIndicies(0, 1, 2, 3); for(int i = 16; i < 64; i++) spriteSheet.requestIndicies(i); spriteSheet.registerIcons(register); }*/ }
Some debug log for Ender pouches
src/main/java/codechicken/enderstorage/item/ItemEnderPouch.java
Some debug log for Ender pouches
<ide><path>rc/main/java/codechicken/enderstorage/item/ItemEnderPouch.java <ide> import codechicken.enderstorage.manager.EnderStorageManager; <ide> import codechicken.enderstorage.storage.EnderItemStorage; <ide> import codechicken.enderstorage.tile.TileEnderChest; <add>import codechicken.enderstorage.util.LogHelper; <ide> import net.minecraft.creativetab.CreativeTabs; <ide> import net.minecraft.entity.player.EntityPlayer; <ide> import net.minecraft.item.Item; <ide> if (world.isRemote || player.isSneaking()) { <ide> return new ActionResult<ItemStack>(EnumActionResult.PASS, stack); <ide> } <del> ((EnderItemStorage) EnderStorageManager.instance(world.isRemote).getStorage(Frequency.fromItemStack(stack), "item")).openSMPGui(player, stack.getUnlocalizedName() + ".name"); <add> Frequency frequency = Frequency.fromItemStack(stack); <add> LogHelper.info(frequency.toString()); <add> ((EnderItemStorage) EnderStorageManager.instance(world.isRemote).getStorage(frequency, "item")).openSMPGui(player, stack.getUnlocalizedName() + ".name"); <ide> return new ActionResult<ItemStack>(EnumActionResult.SUCCESS, stack); <ide> } <ide>
Java
mit
cf39f86b93082d654f19ae0caa4c2122ca83e3b0
0
msaranu/TwitterApp
package com.codepath.apps.twitterapp.activities; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.codepath.apps.twitterapp.R; import com.codepath.apps.twitterapp.adapters.TweetsArrayAdapter; import com.codepath.apps.twitterapp.applications.TwitterApplication; import com.codepath.apps.twitterapp.clients.TwitterClient; import com.codepath.apps.twitterapp.decorators.EndlessRecyclerViewScrollListener; import com.codepath.apps.twitterapp.decorators.ItemClickSupport; import com.codepath.apps.twitterapp.fragments.ComposeTweetDialogFragment; import com.codepath.apps.twitterapp.fragments.TweetDetailDialogFragment; import com.codepath.apps.twitterapp.models.Tweet; import com.codepath.apps.twitterapp.models.User; import com.codepath.apps.twitterapp.network.NetworkUtil; import com.codepath.apps.twitterapp.services.TweetOfflineService; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import cz.msebera.android.httpclient.Header; import static com.codepath.apps.twitterapp.properties.properties.OFFLINE_PROFILE_URL; import static com.codepath.apps.twitterapp.properties.properties.OFFLINE_SCREEN_NAME; import static com.codepath.apps.twitterapp.properties.properties.OFFLINE__NAME; public class TimelineActivity extends AppCompatActivity implements TweetDetailDialogFragment.ComposeTweetDialogListener { private TwitterClient client; public TimelineActivity() { } ArrayList<Tweet> tweets; TweetsArrayAdapter adapter; @BindView(R.id.rvTweets) RecyclerView rvTweets; public static final int FIRST_PAGE = 0; private EndlessRecyclerViewScrollListener scrollListener; private SwipeRefreshLayout swipeContainer; TweetOfflineService tweetofflineservice; @BindView(R.id.fabComposeTweet) FloatingActionButton fabComposeTweet; Tweet composeTweet; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_timeline); ButterKnife.bind(this); Toolbar tbTwitter = (Toolbar) findViewById(R.id.tbTwitter); setSupportActionBar(tbTwitter); client = TwitterApplication.getRestClient(); bindDataToAdapter(this); bindChromeIntenttoAdapter(); setFloatingAction(); setRecyleViewLayout(); setSwipeRefreshLayout(); } private void bindChromeIntenttoAdapter() { // Get intent, action and MIME type Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); if (Intent.ACTION_SEND.equals(action) && type != null) { if ("text/plain".equals(type)) { // Make sure to check whether returned data will be null. String titleOfPage = intent.getStringExtra(Intent.EXTRA_SUBJECT); String urlOfPage = intent.getStringExtra(Intent.EXTRA_TEXT); Uri imageUriOfPage = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); String intentSring = "Title: " + titleOfPage + "\r\n" + "URL: " + urlOfPage ; if (intent != null) { Tweet t = new Tweet(); t.setText(intentSring); Bundle bundle = new Bundle(); bundle.putParcelable("TWEET_OBJ", t); onComposeTweet(bundle); } } } } private void setFloatingAction() { fabComposeTweet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bundle bundle = new Bundle(); bundle.putParcelable("TWEET_OBJ", new Tweet()); onComposeTweet(bundle); } }); } private void setSwipeRefreshLayout() { swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer); // Setup refresh listener which triggers new data loading swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { getTweets(0); } }); // Configure the refreshing colors swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); } private void populateTimeline(int page) { long id = 0; boolean scroll = false; //set it later if (page != 0) { id = tweets.get(tweets.size() - 1).getId() - 1; scroll = true; } client.getHomeTimeline(new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { Log.d("DEBUG", response.toString()); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); // register type adapters here, specify field naming policy, etc. Gson gson = gsonBuilder.create(); // Tweet[] tarray = gson.fromJson(response.toString(),Tweet[].class); List<Tweet> tweetList = gson.fromJson(response.toString(), new TypeToken<List<Tweet>>() { }.getType()); if (tweetList == null || tweetList.isEmpty() || tweetList.size() == 0) { Toast.makeText(TimelineActivity.this, "NO TWEETS", Toast.LENGTH_LONG).show(); } else { tweetofflineservice.deleteTweetsoffline(); tweetofflineservice.saveTweetsOffline(tweetList); tweets.addAll(tweetList); adapter.notifyDataSetChanged(); swipeContainer.setRefreshing(false); } } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { Log.d("DEBUG", errorResponse.toString()); if (errorResponse.toString().contains("Too Many Requests") || errorResponse.toString().contains("Rate limit exceeded")) { Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS THIS SESSION", Toast.LENGTH_LONG).show(); } else Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS ??", Toast.LENGTH_LONG).show(); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { Log.d("DEBUG", errorResponse.toString()); if (errorResponse.toString().contains("Too Many Requests")) { Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS THIS SESSION", Toast.LENGTH_LONG).show(); } else Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS ??", Toast.LENGTH_LONG).show(); } }, id, scroll); } private void setRecyleViewLayout() { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); rvTweets.setLayoutManager(linearLayoutManager); scrollListener = new EndlessRecyclerViewScrollListener(linearLayoutManager) { @Override public void onLoadMore(int page, int totalItemsCount, RecyclerView view) { getTweets(page); } }; // Adds the scroll listener to RecyclerView rvTweets.addOnScrollListener(scrollListener); getTweets(FIRST_PAGE); ItemClickSupport.addTo(rvTweets).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() { @Override public void onItemClicked(RecyclerView recyclerView, int position, View v) { Bundle bundle = new Bundle(); bundle.putParcelable("TWEET_OBJ", tweets.get(position)); onReplyTweet(bundle); } }); } private void bindDataToAdapter(TimelineActivity timelineActivity) { // fragFilterSettings = new FilterSettings(); // Create adapter passing in the sample user data tweets = new ArrayList<>(); adapter = new TweetsArrayAdapter(this, tweets); // Attach the adapter to the recyclerview to populate items rvTweets.setAdapter(adapter); } public void getTweets(int page) { { if (page == FIRST_PAGE) { tweets.clear(); scrollListener.resetState(); } callTwitterAPI(page); } } private void callTwitterAPI(int page) { //to test offline DB capture without bringing down internet connection everytime boolean offline = true; if (!offline && NetworkUtil.isInternetAvailable(getApplicationContext()) && NetworkUtil.isOnline()) { populateTimeline(page); } else { tweets.addAll(TweetOfflineService.retrieveTweetsOffline()); Handler handler = new Handler(); final Runnable r = new Runnable() { public void run() { adapter.notifyDataSetChanged(); } }; handler.post(r); Toast.makeText(TimelineActivity.this, "Retreiving Tweets Offline", Toast.LENGTH_LONG).show(); // swipeContainer.setRefreshing(false); return; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_twitter, menu); // MenuItem searchItem = menu.findItem(R.id.action_compose); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); return super.onOptionsItemSelected(item); } public void onComposeTweet(Bundle bundle) { FragmentManager fm = getSupportFragmentManager(); ComposeTweetDialogFragment fdf = ComposeTweetDialogFragment.newInstance(); fdf.setArguments(bundle); fdf.setStyle(DialogFragment.STYLE_NORMAL, R.style.AppDialogTheme); fdf.show(fm, "FRAGMENT_MODAL_COMPOSE"); } public void onReplyTweet(Bundle bundle) { FragmentManager fm = getSupportFragmentManager(); TweetDetailDialogFragment fdf = TweetDetailDialogFragment.newInstance(); fdf.setArguments(bundle); fdf.setStyle(DialogFragment.STYLE_NORMAL, R.style.AppDialogTheme); fdf.show(fm, "FRAGMENT_MODAL_COMPOSE"); } @Override public void onFinishComposeTweetDialog(String tweetText, Tweet tweet) { composeTweet = constructOfflineTweetUser(); composeTweet.setText(tweetText); client.postStatusUpdate(new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { Log.d("DEBUG", response.toString()); if (composeTweet.getId() <= 0) { tweets.add(0, composeTweet); adapter.notifyDataSetChanged(); rvTweets.scrollToPosition(0); swipeContainer.setRefreshing(false); } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { Log.d("DEBUG", response.toString()); if (composeTweet.getId() <= 0) { tweets.add(0, composeTweet); adapter.notifyDataSetChanged(); rvTweets.scrollToPosition(0); } } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { Log.d("DEBUG", errorResponse.toString()); if (errorResponse.toString().contains("Too Many Requests") || errorResponse.toString().contains("Rate limit exceeded")) { Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS THIS SESSION", Toast.LENGTH_LONG).show(); } else Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS 2 ??", Toast.LENGTH_LONG).show(); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { Log.d("DEBUG", errorResponse.toString()); if (errorResponse.toString().contains("Too Many Requests")) { Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS THIS SESSION", Toast.LENGTH_LONG).show(); } else Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS 3??", Toast.LENGTH_LONG).show(); } }, tweetText, tweet.getId()); } public Tweet constructOfflineTweetUser() { Tweet tweetOffline = new Tweet(); tweetOffline.setRetweetCount(0l); tweetOffline.setFavoriteCount(0l); User u = new User(); u.setScreenName(OFFLINE_SCREEN_NAME); u.setName(OFFLINE__NAME); u.setProfileImageUrl(OFFLINE_PROFILE_URL); u.setVerified(false); tweetOffline.setUser(u); return tweetOffline; } }
app/src/main/java/com/codepath/apps/twitterapp/activities/TimelineActivity.java
package com.codepath.apps.twitterapp.activities; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.codepath.apps.twitterapp.R; import com.codepath.apps.twitterapp.adapters.TweetsArrayAdapter; import com.codepath.apps.twitterapp.applications.TwitterApplication; import com.codepath.apps.twitterapp.clients.TwitterClient; import com.codepath.apps.twitterapp.decorators.EndlessRecyclerViewScrollListener; import com.codepath.apps.twitterapp.decorators.ItemClickSupport; import com.codepath.apps.twitterapp.fragments.ComposeTweetDialogFragment; import com.codepath.apps.twitterapp.fragments.TweetDetailDialogFragment; import com.codepath.apps.twitterapp.models.Tweet; import com.codepath.apps.twitterapp.models.User; import com.codepath.apps.twitterapp.network.NetworkUtil; import com.codepath.apps.twitterapp.services.TweetOfflineService; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import cz.msebera.android.httpclient.Header; import static com.codepath.apps.twitterapp.properties.properties.OFFLINE_PROFILE_URL; import static com.codepath.apps.twitterapp.properties.properties.OFFLINE_SCREEN_NAME; import static com.codepath.apps.twitterapp.properties.properties.OFFLINE__NAME; public class TimelineActivity extends AppCompatActivity implements TweetDetailDialogFragment.ComposeTweetDialogListener { private TwitterClient client; public TimelineActivity() { } ArrayList<Tweet> tweets; TweetsArrayAdapter adapter; @BindView(R.id.rvTweets) RecyclerView rvTweets; public static final int FIRST_PAGE = 0; private EndlessRecyclerViewScrollListener scrollListener; private SwipeRefreshLayout swipeContainer; TweetOfflineService tweetofflineservice; @BindView(R.id.fabComposeTweet) FloatingActionButton fabComposeTweet; Tweet composeTweet; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_timeline); ButterKnife.bind(this); Toolbar tbTwitter = (Toolbar) findViewById(R.id.tbTwitter); setSupportActionBar(tbTwitter); client = TwitterApplication.getRestClient(); bindDataToAdapter(this); bindChromeIntenttoAdapter(); setFloatingAction(); setRecyleViewLayout(); setSwipeRefreshLayout(); } private void bindChromeIntenttoAdapter() { // Get intent, action and MIME type Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); if (Intent.ACTION_SEND.equals(action) && type != null) { if ("text/plain".equals(type)) { // Make sure to check whether returned data will be null. String titleOfPage = intent.getStringExtra(Intent.EXTRA_SUBJECT); String urlOfPage = intent.getStringExtra(Intent.EXTRA_TEXT); Uri imageUriOfPage = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); String intentSring = "Title: " + titleOfPage + "\r\n" + "URL: " + urlOfPage ; if (intent != null) { Tweet t = new Tweet(); t.setText(intentSring); Bundle bundle = new Bundle(); bundle.putParcelable("TWEET_OBJ", t); onComposeTweet(bundle); } } } } private void setFloatingAction() { fabComposeTweet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bundle bundle = new Bundle(); bundle.putParcelable("TWEET_OBJ", new Tweet()); onComposeTweet(bundle); } }); } private void setSwipeRefreshLayout() { swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer); // Setup refresh listener which triggers new data loading swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { getTweets(0); } }); // Configure the refreshing colors swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); } private void populateTimeline(int page) { long id = 0; boolean scroll = false; //set it later if (page != 0) { id = tweets.get(tweets.size() - 1).getId() - 1; scroll = true; } client.getHomeTimeline(new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { Log.d("DEBUG", response.toString()); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); // register type adapters here, specify field naming policy, etc. Gson gson = gsonBuilder.create(); // Tweet[] tarray = gson.fromJson(response.toString(),Tweet[].class); List<Tweet> tweetList = gson.fromJson(response.toString(), new TypeToken<List<Tweet>>() { }.getType()); if (tweetList == null || tweetList.isEmpty() || tweetList.size() == 0) { Toast.makeText(TimelineActivity.this, "NO TWEETS", Toast.LENGTH_LONG).show(); } else { tweetofflineservice.deleteTweetsoffline(); tweetofflineservice.saveTweetsOffline(tweetList); tweets.addAll(tweetList); adapter.notifyDataSetChanged(); swipeContainer.setRefreshing(false); } } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { Log.d("DEBUG", errorResponse.toString()); if (errorResponse.toString().contains("Too Many Requests") || errorResponse.toString().contains("Rate limit exceeded")) { Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS THIS SESSION", Toast.LENGTH_LONG).show(); } else Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS ??", Toast.LENGTH_LONG).show(); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { Log.d("DEBUG", errorResponse.toString()); if (errorResponse.toString().contains("Too Many Requests")) { Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS THIS SESSION", Toast.LENGTH_LONG).show(); } else Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS ??", Toast.LENGTH_LONG).show(); } }, id, scroll); } private void setRecyleViewLayout() { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); rvTweets.setLayoutManager(linearLayoutManager); scrollListener = new EndlessRecyclerViewScrollListener(linearLayoutManager) { @Override public void onLoadMore(int page, int totalItemsCount, RecyclerView view) { getTweets(page); } }; // Adds the scroll listener to RecyclerView rvTweets.addOnScrollListener(scrollListener); getTweets(FIRST_PAGE); ItemClickSupport.addTo(rvTweets).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() { @Override public void onItemClicked(RecyclerView recyclerView, int position, View v) { Bundle bundle = new Bundle(); bundle.putParcelable("TWEET_OBJ", tweets.get(position)); onReplyTweet(bundle); } }); } private void bindDataToAdapter(TimelineActivity timelineActivity) { // fragFilterSettings = new FilterSettings(); // Create adapter passing in the sample user data tweets = new ArrayList<>(); adapter = new TweetsArrayAdapter(this, tweets); // Attach the adapter to the recyclerview to populate items rvTweets.setAdapter(adapter); } public void getTweets(int page) { { if (page == FIRST_PAGE) { tweets.clear(); scrollListener.resetState(); } callTwitterAPI(page); } } private void callTwitterAPI(int page) { boolean offline = false; if (!offline && NetworkUtil.isInternetAvailable(getApplicationContext()) && NetworkUtil.isOnline()) { populateTimeline(page); } else { tweets.addAll(TweetOfflineService.retrieveTweetsOffline()); Handler handler = new Handler(); final Runnable r = new Runnable() { public void run() { adapter.notifyDataSetChanged(); } }; handler.post(r); Toast.makeText(TimelineActivity.this, "Retreiving Tweets Offline from: ", Toast.LENGTH_LONG).show(); // swipeContainer.setRefreshing(false); return; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_twitter, menu); // MenuItem searchItem = menu.findItem(R.id.action_compose); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == 10) { Bundle bundle = new Bundle(); onComposeTweet(bundle); return true; } return super.onOptionsItemSelected(item); } public void onComposeTweet(Bundle bundle) { FragmentManager fm = getSupportFragmentManager(); ComposeTweetDialogFragment fdf = ComposeTweetDialogFragment.newInstance(); fdf.setArguments(bundle); fdf.setStyle(DialogFragment.STYLE_NORMAL, R.style.AppDialogTheme); fdf.show(fm, "FRAGMENT_MODAL_COMPOSE"); } public void onReplyTweet(Bundle bundle) { FragmentManager fm = getSupportFragmentManager(); TweetDetailDialogFragment fdf = TweetDetailDialogFragment.newInstance(); fdf.setArguments(bundle); fdf.setStyle(DialogFragment.STYLE_NORMAL, R.style.AppDialogTheme); fdf.show(fm, "FRAGMENT_MODAL_COMPOSE"); } @Override public void onFinishComposeTweetDialog(String tweetText, Tweet tweet) { composeTweet = constructOfflineTweetUser(); composeTweet.setText(tweetText); client.postStatusUpdate(new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { Log.d("DEBUG", response.toString()); if (composeTweet.getId() <= 0) { tweets.add(0, composeTweet); adapter.notifyDataSetChanged(); rvTweets.scrollToPosition(0); swipeContainer.setRefreshing(false); } } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { Log.d("DEBUG", response.toString()); if (composeTweet.getId() <= 0) { tweets.add(0, composeTweet); adapter.notifyDataSetChanged(); rvTweets.scrollToPosition(0); } } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { Log.d("DEBUG", errorResponse.toString()); if (errorResponse.toString().contains("Too Many Requests") || errorResponse.toString().contains("Rate limit exceeded")) { Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS THIS SESSION", Toast.LENGTH_LONG).show(); } else Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS 2 ??", Toast.LENGTH_LONG).show(); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { Log.d("DEBUG", errorResponse.toString()); if (errorResponse.toString().contains("Too Many Requests")) { Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS THIS SESSION", Toast.LENGTH_LONG).show(); } else Toast.makeText(TimelineActivity.this, "TOO MANY REQUESTS 3??", Toast.LENGTH_LONG).show(); } }, tweetText, tweet.getId()); } public Tweet constructOfflineTweetUser() { Tweet tweetOffline = new Tweet(); tweetOffline.setRetweetCount(0l); tweetOffline.setFavoriteCount(0l); User u = new User(); u.setScreenName(OFFLINE_SCREEN_NAME); u.setName(OFFLINE__NAME); u.setProfileImageUrl(OFFLINE_PROFILE_URL); u.setVerified(false); tweetOffline.setUser(u); return tweetOffline; } }
Update offline tweets
app/src/main/java/com/codepath/apps/twitterapp/activities/TimelineActivity.java
Update offline tweets
<ide><path>pp/src/main/java/com/codepath/apps/twitterapp/activities/TimelineActivity.java <ide> <ide> private void callTwitterAPI(int page) { <ide> <del> boolean offline = false; <add> //to test offline DB capture without bringing down internet connection everytime <add> boolean offline = true; <add> <ide> if (!offline && NetworkUtil.isInternetAvailable(getApplicationContext()) && NetworkUtil.isOnline()) { <ide> populateTimeline(page); <ide> } else { <ide> }; <ide> <ide> handler.post(r); <del> Toast.makeText(TimelineActivity.this, "Retreiving Tweets Offline from: ", <add> Toast.makeText(TimelineActivity.this, "Retreiving Tweets Offline", <ide> Toast.LENGTH_LONG).show(); <ide> // swipeContainer.setRefreshing(false); <ide> <ide> @Override <ide> public boolean onOptionsItemSelected(MenuItem item) { <ide> int id = item.getItemId(); <del> if (id == 10) { <del> Bundle bundle = new Bundle(); <del> onComposeTweet(bundle); <del> return true; <del> } <ide> return super.onOptionsItemSelected(item); <ide> } <ide>
Java
lgpl-2.1
e5c53db899efd1e05dad72c63e3853415f55ec5c
0
opax/exist,wshager/exist,ambs/exist,windauer/exist,windauer/exist,jessealama/exist,zwobit/exist,eXist-db/exist,dizzzz/exist,RemiKoutcherawy/exist,wolfgangmm/exist,kohsah/exist,joewiz/exist,dizzzz/exist,lcahlander/exist,eXist-db/exist,wolfgangmm/exist,eXist-db/exist,zwobit/exist,ljo/exist,zwobit/exist,lcahlander/exist,patczar/exist,MjAbuz/exist,shabanovd/exist,windauer/exist,ljo/exist,jessealama/exist,shabanovd/exist,joewiz/exist,ambs/exist,kohsah/exist,opax/exist,patczar/exist,lcahlander/exist,RemiKoutcherawy/exist,dizzzz/exist,wshager/exist,adamretter/exist,hungerburg/exist,RemiKoutcherawy/exist,wshager/exist,hungerburg/exist,adamretter/exist,shabanovd/exist,jensopetersen/exist,jensopetersen/exist,ambs/exist,adamretter/exist,olvidalo/exist,wshager/exist,RemiKoutcherawy/exist,patczar/exist,RemiKoutcherawy/exist,joewiz/exist,ljo/exist,dizzzz/exist,joewiz/exist,jessealama/exist,jessealama/exist,ambs/exist,olvidalo/exist,zwobit/exist,kohsah/exist,shabanovd/exist,hungerburg/exist,wolfgangmm/exist,eXist-db/exist,lcahlander/exist,eXist-db/exist,patczar/exist,jessealama/exist,MjAbuz/exist,wolfgangmm/exist,ljo/exist,olvidalo/exist,wolfgangmm/exist,eXist-db/exist,wolfgangmm/exist,olvidalo/exist,MjAbuz/exist,olvidalo/exist,jensopetersen/exist,joewiz/exist,RemiKoutcherawy/exist,kohsah/exist,hungerburg/exist,shabanovd/exist,dizzzz/exist,dizzzz/exist,patczar/exist,MjAbuz/exist,adamretter/exist,opax/exist,ljo/exist,ljo/exist,ambs/exist,adamretter/exist,MjAbuz/exist,shabanovd/exist,lcahlander/exist,adamretter/exist,ambs/exist,windauer/exist,jensopetersen/exist,opax/exist,windauer/exist,zwobit/exist,patczar/exist,jensopetersen/exist,kohsah/exist,zwobit/exist,lcahlander/exist,wshager/exist,jensopetersen/exist,opax/exist,jessealama/exist,joewiz/exist,MjAbuz/exist,windauer/exist,wshager/exist,kohsah/exist,hungerburg/exist
/* * eXist Open Source Native XML Database * Copyright (C) 2001-03 Wolfgang M. Meier * [email protected] * http://exist.sourceforge.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.xquery; import java.io.IOException; import java.io.Reader; import java.net.MalformedURLException; import java.text.Collator; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.TreeMap; import org.apache.log4j.Logger; import org.exist.EXistException; import org.exist.collections.Collection; import org.exist.dom.BinaryDocument; import org.exist.dom.DocumentImpl; import org.exist.dom.DocumentSet; import org.exist.dom.NodeProxy; import org.exist.dom.QName; import org.exist.memtree.MemTreeBuilder; import org.exist.security.Permission; import org.exist.security.PermissionDeniedException; import org.exist.security.User; import org.exist.source.DBSource; import org.exist.source.Source; import org.exist.source.SourceFactory; import org.exist.storage.DBBroker; import org.exist.storage.lock.Lock; import org.exist.util.Collations; import org.exist.util.Configuration; import org.exist.util.LockException; import org.exist.xquery.parser.XQueryLexer; import org.exist.xquery.parser.XQueryParser; import org.exist.xquery.parser.XQueryTreeParser; import org.exist.xquery.value.Item; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceIterator; import org.exist.xquery.value.Type; import antlr.RecognitionException; import antlr.TokenStreamException; import antlr.collections.AST; /** * The current XQuery execution context. Contains the static as well * as the dynamic XQuery context components. * * @author Wolfgang Meier ([email protected]) */ public class XQueryContext { private static final String JAVA_URI_START = "java:"; private static final String XMLDB_URI_START = "xmldb:exist://"; public final static String XML_NS = "http://www.w3.org/XML/1998/namespace"; public final static String SCHEMA_NS = "http://www.w3.org/2001/XMLSchema"; public final static String SCHEMA_DATATYPES_NS = "http://www.w3.org/2001/XMLSchema-datatypes"; public final static String SCHEMA_INSTANCE_NS = "http://www.w3.org/2001/XMLSchema-instance"; public final static String XPATH_DATATYPES_NS = "http://www.w3.org/2003/05/xpath-datatypes"; public final static String XQUERY_LOCAL_NS = "http://www.w3.org/2003/08/xquery-local-functions"; public final static String EXIST_NS = "http://exist.sourceforge.net/NS/exist"; private final static Logger LOG = Logger.getLogger(XQueryContext.class); private static final String TEMP_STORE_ERROR = "Error occurred while storing temporary data"; private static final HashMap moduleClasses = new HashMap(); // Static namespace/prefix mappings protected HashMap namespaces; // Local in-scope namespace/prefix mappings in the current context protected HashMap inScopeNamespaces = new HashMap(); // Static prefix/namespace mappings protected HashMap prefixes; // Local prefix/namespace mappings in the current context protected HashMap inScopePrefixes = new HashMap(); // Local namespace stack protected Stack namespaceStack = new Stack(); // Known user defined functions in the local module protected TreeMap declaredFunctions = new TreeMap(); // Globally declared variables protected TreeMap globalVariables = new TreeMap(); // The last element in the linked list of local in-scope variables protected LocalVariable lastVar = null; protected Stack contextStack = new Stack(); // The current size of the variable stack protected int variableStackSize = 0; // Unresolved references to user defined functions protected Stack forwardReferences = new Stack(); // List of pragmas declared for this query protected List pragmas = null; /** * the watchdog object assigned to this query * * @uml.property name="watchdog" * @uml.associationEnd multiplicity="(1 1)" */ protected XQueryWatchDog watchdog; /** * Loaded modules. */ protected HashMap modules = new HashMap(); /** * The set of statically known documents specified as * an array of paths to documents and collections. */ protected String[] staticDocumentPaths = null; /** * The actual set of statically known documents. This * will be generated on demand from staticDocumentPaths. */ protected DocumentSet staticDocuments = null; /** * The main database broker object providing access * to storage and indexes. Every XQuery has its own * DBBroker object. */ protected DBBroker broker; protected String baseURI = ""; protected boolean baseURISetInProlog = false; protected String moduleLoadPath = "."; protected String defaultFunctionNamespace = Function.BUILTIN_FUNCTION_NS; /** * The default collation URI */ private String defaultCollation = Collations.CODEPOINT; /** * Default Collator. Will be null for the default unicode codepoint collation. */ private Collator defaultCollator = null; /** * Set to true to enable XPath 1.0 * backwards compatibility. */ private boolean backwardsCompatible = true; /** * Should whitespace inside node constructors be stripped? */ private boolean stripWhitespace = true; /** * The position of the currently processed item in the context * sequence. This field has to be set on demand, for example, * before calling the fn:position() function. */ private int contextPosition = 0; /** * The builder used for creating in-memory document * fragments */ private MemTreeBuilder builder = null; /** * Stack for temporary document fragments */ private Stack fragmentStack = new Stack(); /** * The root of the expression tree */ private Expression rootExpression; /** * Flag to indicate that the query should put an exclusive * lock on all documents involved. * * TODO: No longer needed? */ private boolean exclusive = false; /** * Should all documents loaded by the query be locked? * If set to true, it is the responsibility of the calling client * code to unlock documents after the query has completed. */ private boolean lockDocumentsOnLoad = false; /** * Documents locked during the query. */ private DocumentSet lockedDocuments = null; /** * The profiler instance used by this context. */ private Profiler profiler = new Profiler(); //For holding XQuery Context variables from setXQueryContextVar() and getXQueryContextVar() HashMap XQueryContextVars = new HashMap(); //set an XQuery Context variable; called by context:set-var() public void setXQueryContextVar(String name, Object XQvar) { XQueryContextVars.put(name, XQvar); } //get an XQuery Context variable; called by context:get-var() public Object getXQueryContextVar(String name) { return(XQueryContextVars.get(name)); } //set the serializer to use for output; called by context:set-serializer() public void setXQuerySerializer(String name, boolean indent, boolean omitxmldeclaration) throws XPathException { Pragma pragma; //Has a exist:serialize pragma already been set? for(int i = 0; i < pragmas.size(); i++) { pragma = (Pragma)pragmas.get(i); if((pragma.getQName().equals("exist:serialize")) /*&& (pragma.getContents().indexOf("method") != -1)*/ ) { //yes, so modify the content from the existing pragma String content = pragma.getContents(); if(content.indexOf("method=") != -1) { content = content.replaceFirst("method=[^/ ]*", "method=" + name); } else { content += " method=" + name; } if(content.indexOf("indent=") != -1) { content = content.replaceFirst("indent=[^/ ]*", "indent=" + (indent ? "yes":"no")); } else { content += " indent" + (indent ? "yes":"no"); } if(content.indexOf("omit-xml-declaration") != -1) { content = content.replaceFirst("omit-xml-declaration=[^/ ]*", "omit-xml-declaration=" + (omitxmldeclaration ? "yes":"no")); } else { content += " omit-xml-declaration" + (omitxmldeclaration ? "yes":"no"); } //Delete the existing serialize pragma pragmas.remove(i); //Add the new serialize pragma addPragma("exist:serialize", content); return; //done } } //no, so set a pragma for serialization addPragma("exist:serialize", "method=" + name + " indent=" + (indent ? "yes":"no") + " omit-xml-declaration=" + (omitxmldeclaration ? "yes":"no")); } protected XQueryContext() { builder = new MemTreeBuilder(this); builder.startDocument(); } public XQueryContext(DBBroker broker) { this(); this.broker = broker; loadDefaults(broker.getConfiguration()); } /** * @return true if profiling is enabled for this context. */ public boolean isProfilingEnabled() { return profiler.isEnabled(); } public boolean isProfilingEnabled(int verbosity) { return profiler.isEnabled() && profiler.verbosity() >= verbosity; } /** * Returns the {@link Profiler} instance of this context * if profiling is enabled. * * @return the profiler instance. */ public Profiler getProfiler() { return profiler; } /** * Called from the XQuery compiler to set the root expression * for this context. * * @param expr */ public void setRootExpression(Expression expr) { this.rootExpression = expr; } /** * Returns the root expression of the XQuery associated with * this context. * * @return */ public Expression getRootExpression() { return rootExpression; } /** * Declare a user-defined prefix/namespace mapping. * * eXist internally keeps a table containing all prefix/namespace * mappings it found in documents, which have been previously * stored into the database. These default mappings need not to be * declared explicitely. * * @param prefix * @param uri */ public void declareNamespace(String prefix, String uri) throws XPathException { if (prefix == null) prefix = ""; if(uri == null) uri = ""; if (prefix.equals("xml") || prefix.equals("xmlns")) throw new XPathException("err:XQST0070: Namespace predefined prefix '" + prefix + "' can not be bound"); if (uri.equals(XML_NS)) throw new XPathException("err:XQST0070: Namespace URI '" + uri + "' must be bound to the 'xml' prefix"); final String prevURI = (String)namespaces.get(prefix); //This prefix was not bound if(prevURI == null ) { //Bind it if (uri.length() > 0) { namespaces.put(prefix, uri); prefixes.put(uri, prefix); return; } //Nothing to bind else { //TODO : check the specs : unbinding an NS which is not already bound may be disallowed. LOG.warn("Unbinding unbound prefix '" + prefix + "'"); } } else //This prefix was bound { //Unbind it if (uri.length() == 0) { // if an empty namespace is specified, // remove any existing mapping for this namespace //TODO : improve, since XML_NS can't be unbound prefixes.remove(uri); namespaces.remove(prefix); return; } //Forbids rebinding the *same* prefix in a *different* namespace in this *same* context if (!uri.equals(prevURI)) throw new XPathException("err:XQST0033: Namespace prefix '" + prefix + "' is already bound to a different uri '" + prevURI + "'"); } } public void declareNamespaces(Map namespaceMap) { Map.Entry entry; String prefix, uri; for(Iterator i = namespaceMap.entrySet().iterator(); i.hasNext(); ) { entry = (Map.Entry)i.next(); prefix = (String)entry.getKey(); uri = (String) entry.getValue(); if(prefix == null) prefix = ""; if(uri == null) uri = ""; namespaces.put(prefix, uri); prefixes.put(uri, prefix); } } /** * Declare an in-scope namespace. This is called during query execution. * * @param prefix * @param uri */ public void declareInScopeNamespace(String prefix, String uri) { if (prefix == null || uri == null) throw new IllegalArgumentException("null argument passed to declareNamespace"); if (inScopeNamespaces == null) inScopeNamespaces = new HashMap(); inScopeNamespaces.put(prefix, uri); } /** * Returns the current default function namespace. * * @return */ public String getDefaultFunctionNamespace() { return defaultFunctionNamespace; } /** * Set the default function namespace. By default, this * points to the namespace for XPath built-in functions. * * @param uri */ public void setDefaultFunctionNamespace(String uri) { defaultFunctionNamespace = uri; } /** * Set the default collation to be used by all operators and functions on strings. * Throws an exception if the collation is unknown or cannot be instantiated. * * @param uri * @throws XPathException */ public void setDefaultCollation(String uri) throws XPathException { if(uri.equals(Collations.CODEPOINT) || uri.equals(Collations.CODEPOINT_SHORT)) { defaultCollation = Collations.CODEPOINT; defaultCollator = null; } defaultCollator = Collations.getCollationFromURI(this, uri); defaultCollation = uri; } public String getDefaultCollation() { return defaultCollation; } public Collator getCollator(String uri) throws XPathException { if(uri == null) return defaultCollator; return Collations.getCollationFromURI(this, uri); } public Collator getDefaultCollator() { return defaultCollator; } /** * Return the namespace URI mapped to the registered prefix * or null if the prefix is not registered. * * @param prefix * @return */ public String getURIForPrefix(String prefix) { String ns = (String) namespaces.get(prefix); if (ns == null) // try in-scope namespace declarations return inScopeNamespaces == null ? null : (String) inScopeNamespaces.get(prefix); else return ns; } /** * Return the prefix mapped to the registered URI or * null if the URI is not registered. * * @param uri * @return */ public String getPrefixForURI(String uri) { String prefix = (String) prefixes.get(uri); if (prefix == null) return inScopePrefixes == null ? null : (String) inScopeNamespaces.get(uri); else return prefix; } /** * Removes the namespace URI from the prefix/namespace * mappings table. * * @param uri */ public void removeNamespace(String uri) { prefixes.remove(uri); for (Iterator i = namespaces.values().iterator(); i.hasNext();) { if (((String) i.next()).equals(uri)) { i.remove(); return; } } inScopePrefixes.remove(uri); if (inScopeNamespaces != null) { for (Iterator i = inScopeNamespaces.values().iterator(); i.hasNext();) { if (((String) i.next()).equals(uri)) { i.remove(); return; } } } } /** * Clear all user-defined prefix/namespace mappings. */ public void clearNamespaces() { namespaces.clear(); prefixes.clear(); if (inScopeNamespaces != null) { inScopeNamespaces.clear(); inScopePrefixes.clear(); } loadDefaults(broker.getConfiguration()); } /** * Set the set of statically known documents for the current * execution context. These documents will be processed if * no explicit document set has been set for the current expression * with fn:doc() or fn:collection(). * * @param docs */ public void setStaticallyKnownDocuments(String[] docs) { staticDocumentPaths = docs; } public void setStaticallyKnownDocuments(DocumentSet set) { staticDocuments = set; } /** * Get the set of statically known documents. * * @return */ public DocumentSet getStaticallyKnownDocuments() throws XPathException { if(staticDocuments != null) // the document set has already been built, return it return staticDocuments; staticDocuments = new DocumentSet(); if(staticDocumentPaths == null) // no path defined: return all documents in the db broker.getAllDocuments(staticDocuments); else { DocumentImpl doc; Collection collection; for(int i = 0; i < staticDocumentPaths.length; i++) { try { doc = broker.openDocument(staticDocumentPaths[i], Lock.READ_LOCK); if(doc != null) { if(doc.getPermissions().validate(broker.getUser(), Permission.READ)) { staticDocuments.add(doc); } doc.getUpdateLock().release(Lock.READ_LOCK); } else { collection = broker.getCollection(staticDocumentPaths[i]); if(collection != null) { LOG.debug("reading collection " + staticDocumentPaths[i]); collection.allDocs(broker, staticDocuments, true, true); } } } catch(PermissionDeniedException e) { LOG.warn("Permission denied to read resource " + staticDocumentPaths[i] + ". Skipping it."); } } } return staticDocuments; } /** * Should loaded documents be locked? * * @see #setLockDocumentsOnLoad(boolean) * * @return */ public boolean lockDocumentsOnLoad() { return lockDocumentsOnLoad; } /** * If lock is true, all documents loaded during query execution * will be locked. This way, we avoid that query results become * invalid before the entire result has been processed by the client * code. All attempts to modify nodes which are part of the result * set will be blocked. * * However, it is the client's responsibility to proper unlock * all documents once processing is completed. * * @param lock */ public void setLockDocumentsOnLoad(boolean lock) { lockDocumentsOnLoad = lock; if(lock) lockedDocuments = new DocumentSet(); } /** * Returns the set of documents that have been loaded and * locked during query execution. * * @see #setLockDocumentsOnLoad(boolean) * * @return */ public DocumentSet getLockedDocuments() { return lockedDocuments; } /** * Release all locks on documents that have been locked * during query execution. * *@see #setLockDocumentsOnLoad(boolean) */ public void releaseLockedDocuments() { if(lockedDocuments != null) lockedDocuments.unlock(false); lockDocumentsOnLoad = false; lockedDocuments = null; } /** * Release all locks on documents not being referenced by the sequence. * This is called after query execution has completed. Only locks on those * documents contained in the final result set will be preserved. All other * locks are released as they are no longer needed. * * @param seq * @return */ public DocumentSet releaseUnusedDocuments(Sequence seq) { if(lockedDocuments == null) return null; // determine the set of documents referenced by nodes in the sequence DocumentSet usedDocs = new DocumentSet(); for(SequenceIterator i = seq.iterate(); i.hasNext(); ) { Item next = i.nextItem(); if(Type.subTypeOf(next.getType(), Type.NODE)) { NodeValue node = (NodeValue) next; if(node.getImplementationType() == NodeValue.PERSISTENT_NODE) { DocumentImpl doc = ((NodeProxy)node).getDocument(); if(!usedDocs.contains(doc.getDocId())) usedDocs.add(doc, false); } } } DocumentSet remaining = new DocumentSet(); for(Iterator i = lockedDocuments.iterator(); i.hasNext(); ) { DocumentImpl next = (DocumentImpl) i.next(); if(usedDocs.contains(next.getDocId())) { remaining.add(next); } else { // LOG.debug("Releasing lock on " + next.getName()); next.getUpdateLock().release(Lock.READ_LOCK); } } // LOG.debug("Locks remaining: " + remaining.getLength()); lockDocumentsOnLoad = false; lockedDocuments = null; return remaining; } /** * Prepare this XQueryContext to be reused. This should be * called when adding an XQuery to the cache. */ public void reset() { builder = new MemTreeBuilder(this); builder.startDocument(); staticDocumentPaths = null; staticDocuments = null; lastVar = null; fragmentStack = new Stack(); watchdog.reset(); profiler.reset(); for(Iterator i = modules.values().iterator(); i.hasNext(); ) { Module module = (Module)i.next(); module.reset(); } } /** * Returns true if whitespace between constructed element nodes * should be stripped by default. * * @return */ public boolean stripWhitespace() { return stripWhitespace; } public void setStripWhitespace(boolean strip) { this.stripWhitespace = strip; } /** * Return an iterator over all built-in modules currently * registered. * * @return */ public Iterator getModules() { return modules.values().iterator(); } /** * Get the built-in module registered for the given namespace * URI. * * @param namespaceURI * @return */ public Module getModule(String namespaceURI) { return (Module) modules.get(namespaceURI); } /** * For compiled expressions: check if the source of any * module imported by the current query has changed since * compilation. * * @return */ public boolean checkModulesValid() { for(Iterator i = modules.values().iterator(); i.hasNext(); ) { Module module = (Module)i.next(); if(!module.isInternalModule()) { if(!((ExternalModule)module).moduleIsValid()) { LOG.debug("Module with URI " + module.getNamespaceURI() + " has changed and needs to be reloaded"); return false; } } } return true; } /** * Load a built-in module from the given class name and assign it to the * namespace URI. The specified class should be a subclass of * {@link Module}. The method will try to instantiate the class. If the * class is not found or an exception is thrown, the method will silently * fail. The namespace URI has to be equal to the namespace URI declared * by the module class. Otherwise, the module is not loaded. * * @param namespaceURI * @param moduleClass */ public Module loadBuiltInModule(String namespaceURI, String moduleClass) { Module module = getModule(namespaceURI); if (module != null) { // LOG.debug("module " + namespaceURI + " is already present"); return module; } try { Class mClass = (Class) moduleClasses.get(moduleClass); if (mClass == null) { mClass = Class.forName(moduleClass); if (!(Module.class.isAssignableFrom(mClass))) { LOG.warn( "failed to load module. " + moduleClass + " is not an instance of org.exist.xquery.Module."); return null; } moduleClasses.put(moduleClass, mClass); } module = (Module) mClass.newInstance(); if (!module.getNamespaceURI().equals(namespaceURI)) { LOG.warn("the module declares a different namespace URI. Skipping..."); return null; } if (getPrefixForURI(module.getNamespaceURI()) == null && module.getDefaultPrefix().length() > 0) declareNamespace(module.getDefaultPrefix(), module.getNamespaceURI()); modules.put(module.getNamespaceURI(), module); //LOG.debug("module " + module.getNamespaceURI() + " loaded successfully."); } catch (ClassNotFoundException e) { //LOG.warn("module class " + moduleClass + " not found. Skipping..."); } catch (InstantiationException e) { LOG.warn("error while instantiating module class " + moduleClass, e); } catch (IllegalAccessException e) { LOG.warn("error while instantiating module class " + moduleClass, e); } catch (XPathException e) { LOG.warn("error while instantiating module class " + moduleClass, e); } return module; } /** * Declare a user-defined function. All user-defined functions are kept * in a single hash map. * * @param function * @throws XPathException */ public void declareFunction(UserDefinedFunction function) throws XPathException { declaredFunctions.put(function.getSignature().getFunctionId(), function); } /** * Resolve a user-defined function. * * @param name * @return * @throws XPathException */ public UserDefinedFunction resolveFunction(QName name, int argCount) throws XPathException { FunctionId id = new FunctionId(name, argCount); UserDefinedFunction func = (UserDefinedFunction) declaredFunctions.get(id); return func; } public Iterator getSignaturesForFunction(QName name) { ArrayList signatures = new ArrayList(2); for (Iterator i = declaredFunctions.values().iterator(); i.hasNext(); ) { UserDefinedFunction func = (UserDefinedFunction) i.next(); if (func.getName().equals(name)) signatures.add(func.getSignature()); } return signatures.iterator(); } public Iterator localFunctions() { return declaredFunctions.values().iterator(); } /** * Declare a local variable. This is called by variable binding expressions like * "let" and "for". * * @param var * @return * @throws XPathException */ public LocalVariable declareVariableBinding(LocalVariable var) throws XPathException { if(lastVar == null) lastVar = var; else { lastVar.addAfter(var); lastVar = var; } var.setStackPosition(variableStackSize); return var; } /** * Declare a global variable as by "declare variable". * * @param qname * @param value * @return * @throws XPathException */ public Variable declareGlobalVariable(Variable var) throws XPathException { globalVariables.put(var.getQName(), var); var.setStackPosition(variableStackSize); return var; } /** * Declare a user-defined variable. * * The value argument is converted into an XPath value * (@see XPathUtil#javaObjectToXPath(Object)). * * @param qname the qualified name of the new variable. Any namespaces should * have been declared before. * @param value a Java object, representing the fixed value of the variable * @return the created Variable object * @throws XPathException if the value cannot be converted into a known XPath value * or the variable QName references an unknown namespace-prefix. */ public Variable declareVariable(String qname, Object value) throws XPathException { QName qn = QName.parse(this, qname, null); Variable var; Module module = getModule(qn.getNamespaceURI()); if(module != null) { var = module.declareVariable(qn, value); return var; } Sequence val = XPathUtil.javaObjectToXPath(value, this); var = (Variable)globalVariables.get(qn); if(var == null) { var = new Variable(qn); globalVariables.put(qn, var); } //TODO : should we allow global variable *re*declaration ? var.setValue(val); return var; } /** * Try to resolve a variable. * * @param qname the qualified name of the variable as string * @return the declared Variable object * @throws XPathException if the variable is unknown */ public Variable resolveVariable(String name) throws XPathException { QName qn = QName.parse(this, name, null); return resolveVariable(qn); } /** * Try to resolve a variable. * * @param qname the qualified name of the variable * @return the declared Variable object * @throws XPathException if the variable is unknown */ public Variable resolveVariable(QName qname) throws XPathException { Variable var; // check if the variable is declared local var = resolveLocalVariable(qname); // check if the variable is declared in a module if (var == null){ Module module = getModule(qname.getNamespaceURI()); if(module != null) { var = module.resolveVariable(qname); } } // check if the variable is declared global if (var == null) var = (Variable) globalVariables.get(qname); if (var == null) throw new XPathException("variable $" + qname + " is not bound"); return var; } private Variable resolveLocalVariable(QName qname) throws XPathException { LocalVariable end = contextStack.isEmpty() ? null : (LocalVariable) contextStack.peek(); for(LocalVariable var = lastVar; var != null; var = var.before) { if (var == end) return null; if(qname.equals(var.getQName())) return var; } return null; } public boolean isVarDeclared(QName qname) { Module module = getModule(qname.getNamespaceURI()); if(module != null) { if (module.isVarDeclared(qname)) return true; } return globalVariables.get(qname) != null; } /** * Turn on/off XPath 1.0 backwards compatibility. * * If turned on, comparison expressions will behave like * in XPath 1.0, i.e. if any one of the operands is a number, * the other operand will be cast to a double. * * @param backwardsCompatible */ public void setBackwardsCompatibility(boolean backwardsCompatible) { this.backwardsCompatible = backwardsCompatible; } /** * XPath 1.0 backwards compatibility turned on? * * In XPath 1.0 compatible mode, additional conversions * will be applied to values if a numeric value is expected. * * @return */ public boolean isBackwardsCompatible() { return this.backwardsCompatible; } /** * Get the DBBroker instance used for the current query. * * The DBBroker is the main database access object, providing * access to all internal database functions. * * @return */ public DBBroker getBroker() { return broker; } public void setBroker(DBBroker broker) { this.broker = broker; } /** * Get the user which executes the current query. * * @return */ public User getUser() { return broker.getUser(); } /** * Get the document builder currently used for creating * temporary document fragments. A new document builder * will be created on demand. * * @return */ public MemTreeBuilder getDocumentBuilder() { if (builder == null) { builder = new MemTreeBuilder(this); builder.startDocument(); } return builder; } /* Methods delegated to the watchdog */ public void proceed() throws TerminatedException { proceed(null); } public void proceed(Expression expr) throws TerminatedException { watchdog.proceed(expr); } public void proceed(Expression expr, MemTreeBuilder builder) throws TerminatedException { watchdog.proceed(expr, builder); } public void recover() { watchdog.reset(); builder = null; } public XQueryWatchDog getWatchDog() { return watchdog; } protected void setWatchDog(XQueryWatchDog watchdog) { this.watchdog = watchdog; } /** * Push any document fragment created within the current * execution context on the stack. */ public void pushDocumentContext() { fragmentStack.push(builder); builder = null; } public void popDocumentContext() { if (!fragmentStack.isEmpty()) { builder = (MemTreeBuilder) fragmentStack.pop(); } } /** * Set the base URI for the evaluation context. * * This is the URI returned by the fn:base-uri() * function. * * @param uri */ public void setBaseURI(String uri) { setBaseURI(uri, false); } /** * Set the base URI for the evaluation context. * * A base URI specified via the base-uri directive in the * XQuery prolog overwrites any other setting. * * @param uri * @param setInProlog */ public void setBaseURI(String uri, boolean setInProlog) { if (baseURISetInProlog) return; if (uri == null) baseURI = ""; baseURI = uri; baseURISetInProlog = setInProlog; } /** * Set the path to a base directory where modules should * be loaded from. Relative module paths will be resolved against * this directory. The property is usually set by the XQueryServlet or * XQueryGenerator, but can also be specified manually. * * @param path */ public void setModuleLoadPath(String path) { this.moduleLoadPath = path; } public String getModuleLoadPath() { return moduleLoadPath; } /** * Get the base URI of the evaluation context. * * This is the URI returned by the fn:base-uri() function. * * @return */ public String getBaseURI() { return baseURI; } /** * Set the current context position, i.e. the position * of the currently processed item in the context sequence. * This value is required by some expressions, e.g. fn:position(). * * @param pos */ public void setContextPosition(int pos) { contextPosition = pos; } /** * Get the current context position, i.e. the position of * the currently processed item in the context sequence. * * @return */ public int getContextPosition() { return contextPosition; } /** * Push all in-scope namespace declarations onto the stack. */ public void pushInScopeNamespaces() { HashMap m = (HashMap) inScopeNamespaces.clone(); namespaceStack.push(inScopeNamespaces); inScopeNamespaces = m; } public void popInScopeNamespaces() { inScopeNamespaces = (HashMap) namespaceStack.pop(); } public void pushNamespaceContext() { HashMap m = (HashMap) namespaces.clone(); HashMap p = (HashMap) prefixes.clone(); namespaceStack.push(namespaces); namespaceStack.push(prefixes); namespaces = m; prefixes = p; } public void popNamespaceContext() { prefixes = (HashMap) namespaceStack.pop(); namespaces = (HashMap) namespaceStack.pop(); } /** * Returns the last variable on the local variable stack. * The current variable context can be restored by passing * the return value to {@link #popLocalVariables(LocalVariable)}. * * @return */ public LocalVariable markLocalVariables(boolean newContext) { if (newContext) contextStack.push(lastVar); variableStackSize++; return lastVar; } /** * Restore the local variable stack to the position marked * by variable var. * * @param var */ public void popLocalVariables(LocalVariable var) { if(var != null) { var.after = null; if (!contextStack.isEmpty() && var == contextStack.peek()) { contextStack.pop(); } } lastVar = var; variableStackSize--; } /** * Returns the current size of the stack. This is used to determine * where a variable has been declared. * * @return */ public int getCurrentStackSize() { return variableStackSize; } /** * Import a module and make it available in this context. The prefix and * location parameters are optional. If prefix is null, the default prefix specified * by the module is used. If location is null, the module will be read from the * namespace URI. * * @param namespaceURI * @param prefix * @param location * @throws XPathException */ public void importModule(String namespaceURI, String prefix, String location) throws XPathException { Module module = getModule(namespaceURI); if(module != null) { LOG.debug("Module " + namespaceURI + " already present."); } else { if(location == null) location = namespaceURI; // is it a Java module? if(location.startsWith(JAVA_URI_START)) { location = location.substring(JAVA_URI_START.length()); module = loadBuiltInModule(namespaceURI, location); } else { Source source; // Is the module source stored in the database? if (location.startsWith(XMLDB_URI_START) || moduleLoadPath.startsWith(XMLDB_URI_START)) { if (location.indexOf(':') < 0) location = moduleLoadPath + '/' + location; String path = location.substring(XMLDB_URI_START.length()); DocumentImpl sourceDoc = null; try { sourceDoc = broker.openDocument(path, Lock.READ_LOCK); if (sourceDoc == null) throw new XPathException("source for module " + location + " not found in database"); if (sourceDoc.getResourceType() != DocumentImpl.BINARY_FILE || !sourceDoc.getMimeType().equals("application/xquery")) throw new XPathException("source for module " + location + " is not an XQuery or " + "declares a wrong mime-type"); source = new DBSource(broker, (BinaryDocument) sourceDoc, true); module = compileModule(namespaceURI, location, module, source); } catch (PermissionDeniedException e) { throw new XPathException("permission denied to read module source from " + location); } finally { if(sourceDoc != null) sourceDoc.getUpdateLock().release(Lock.READ_LOCK); } // No. Load from file or URL } else { try { source = SourceFactory.getSource(moduleLoadPath, location, true); } catch (MalformedURLException e) { throw new XPathException("source location for module " + namespaceURI + " should be a valid URL: " + e.getMessage()); } catch (IOException e) { throw new XPathException("source for module " + namespaceURI + " not found: " + e.getMessage()); } module = compileModule(namespaceURI, location, module, source); } } } if(prefix == null) prefix = module.getDefaultPrefix(); declareNamespace(prefix, namespaceURI); } /** * @param namespaceURI * @param location * @param module * @param source * @return * @throws XPathException */ private Module compileModule(String namespaceURI, String location, Module module, Source source) throws XPathException { LOG.debug("Loading module from " + location); Reader reader; try { reader = source.getReader(); } catch (IOException e) { throw new XPathException("IO exception while loading module " + namespaceURI, e); } XQueryContext modContext = new ModuleContext(this); XQueryLexer lexer = new XQueryLexer(modContext, reader); XQueryParser parser = new XQueryParser(lexer); XQueryTreeParser astParser = new XQueryTreeParser(modContext); try { parser.xpath(); if (parser.foundErrors()) { LOG.debug(parser.getErrorMessage()); throw new XPathException( "error found while loading module from " + location + ": " + parser.getErrorMessage()); } AST ast = parser.getAST(); PathExpr path = new PathExpr(modContext); astParser.xpath(ast, path); if (astParser.foundErrors()) { throw new XPathException( "error found while loading module from " + location + ": " + astParser.getErrorMessage(), astParser.getLastException()); } path.analyze(null, 0); ExternalModule modExternal = astParser.getModule(); if(modExternal == null) throw new XPathException("source at " + location + " is not a valid module"); if(!modExternal.getNamespaceURI().equals(namespaceURI)) throw new XPathException("namespace URI declared by module (" + modExternal.getNamespaceURI() + ") does not match namespace URI in import statement, which was: " + namespaceURI); modules.put(modExternal.getNamespaceURI(), modExternal); modExternal.setSource(source); modExternal.setContext(modContext); module = modExternal; } catch (RecognitionException e) { throw new XPathException( "error found while loading module from " + location + ": " + e.getMessage(), e.getLine(), e.getColumn()); } catch (TokenStreamException e) { throw new XPathException( "error found while loading module from " + location + ": " + e.getMessage(), e); } catch (XPathException e) { e.prependMessage("Error while loading module " + location + ": "); throw e; } catch (Exception e) { throw new XPathException("Internal error while loading module: " + location, e); } declareModuleVars(module); return module; } private void declareModuleVars(Module module) { String moduleNS = module.getNamespaceURI(); for (Iterator i = globalVariables.values().iterator(); i.hasNext(); ) { Variable var = (Variable) i.next(); if (moduleNS.equals(var.getQName().getNamespaceURI())) { module.declareVariable(var); i.remove(); } } } /** * Add a forward reference to an undeclared function. Forward * references will be resolved later. * * @param call */ public void addForwardReference(FunctionCall call) { forwardReferences.push(call); } /** * Resolve all forward references to previously undeclared functions. * * @throws XPathException */ public void resolveForwardReferences() throws XPathException { while(!forwardReferences.empty()) { FunctionCall call = (FunctionCall)forwardReferences.pop(); UserDefinedFunction func = resolveFunction(call.getQName(), call.getArgumentCount()); if(func == null) throw new XPathException(call.getASTNode(), "Call to undeclared function: " + call.getQName().toString()); call.resolveForwardReference(func); } } /** * Called by XUpdate to tell the query engine that it is running in * exclusive mode, i.e. no other query is executed at the same time. * * @param exclusive */ public void setExclusiveMode(boolean exclusive) { this.exclusive = exclusive; } public boolean inExclusiveMode() { return exclusive; } public void addPragma(String qnameString, String contents) throws XPathException { QName qn; try { qn = QName.parse(this, qnameString, defaultFunctionNamespace); } catch (XPathException e) { // unknown pragma: just ignore it LOG.debug("Ignoring unknown pragma: " + qnameString); return; } Pragma pragma = new Pragma(qn, contents); if(pragmas == null) pragmas = new ArrayList(); // check if this overwrites an already existing pragma boolean added = false; Pragma old; for (int i = 0; i < pragmas.size(); i++) { old = (Pragma) pragmas.get(i); if (old.equals(pragma)) { pragmas.add(i, pragma); added = true; break; } } // add the pragma to the list if it does not yet exist if (!added) pragmas.add(pragma); // check predefined pragmas if (Pragma.PROFILE_QNAME.compareTo(qn) == 0) { // configure profiling profiler.configure(pragma); } else if(Pragma.TIMEOUT_QNAME.compareTo(qn) == 0) watchdog.setTimeoutFromPragma(pragma); else if(Pragma.OUTPUT_SIZE_QNAME.compareTo(qn) == 0) watchdog.setMaxNodesFromPragma(pragma); } public Pragma getPragma(QName qname) { if(pragmas != null) { Pragma pragma; for(int i = 0; i < pragmas.size(); i++) { pragma = (Pragma)pragmas.get(i); if(qname.compareTo(pragma.getQName()) == 0) return pragma; } } return null; } /** * Store the supplied data to a temporary document fragment. * * @param data * @return * @throws XPathException */ public DocumentImpl storeTemporaryDoc(org.exist.memtree.DocumentImpl doc) throws XPathException { try { DocumentImpl targetDoc = broker.storeTemporaryDoc(doc); watchdog.addTemporaryFragment(targetDoc.getFileName()); LOG.debug("Stored: " + targetDoc.getDocId() + ": " + targetDoc.getName() + ": " + targetDoc.printTreeLevelOrder()); return targetDoc; } catch (EXistException e) { throw new XPathException(TEMP_STORE_ERROR, e); } catch (PermissionDeniedException e) { throw new XPathException(TEMP_STORE_ERROR, e); } catch (LockException e) { throw new XPathException(TEMP_STORE_ERROR, e); } } /** * Load the default prefix/namespace mappings table and set up * internal functions. */ protected void loadDefaults(Configuration config) { this.watchdog = new XQueryWatchDog(this); namespaces = new HashMap(); prefixes = new HashMap(); /* SymbolTable syms = broker.getSymbols(); String[] pfx = syms.defaultPrefixList(); namespaces = new HashMap(pfx.length); prefixes = new HashMap(pfx.length); String sym; for (int i = 0; i < pfx.length; i++) { sym = syms.getDefaultNamespace(pfx[i]); namespaces.put(pfx[i], sym); prefixes.put(sym, pfx[i]); } */ try { // default namespaces namespaces.put("xml", XML_NS); prefixes.put(XML_NS, "xml"); declareNamespace("xs", SCHEMA_NS); declareNamespace("xdt", XPATH_DATATYPES_NS); declareNamespace("local", XQUERY_LOCAL_NS); declareNamespace("fn", Function.BUILTIN_FUNCTION_NS); //*not* as standard NS declareNamespace("exist", EXIST_NS); } catch (XPathException e) { //TODO : ignored because it should never happen } // load built-in modules // these modules are loaded dynamically. It is not an error if the // specified module class cannot be found in the classpath. loadBuiltInModule( Function.BUILTIN_FUNCTION_NS, "org.exist.xquery.functions.ModuleImpl"); String modules[][] = (String[][]) config.getProperty("xquery.modules"); if ( modules != null ) { for (int i = 0; i < modules.length; i++) { // LOG.debug("Loading module " + modules[i][0]); loadBuiltInModule(modules[i][0], modules[i][1]); } } } }
src/org/exist/xquery/XQueryContext.java
/* * eXist Open Source Native XML Database * Copyright (C) 2001-03 Wolfgang M. Meier * [email protected] * http://exist.sourceforge.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.xquery; import java.io.IOException; import java.io.Reader; import java.net.MalformedURLException; import java.text.Collator; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.TreeMap; import org.apache.log4j.Logger; import org.exist.EXistException; import org.exist.collections.Collection; import org.exist.dom.BinaryDocument; import org.exist.dom.DocumentImpl; import org.exist.dom.DocumentSet; import org.exist.dom.NodeProxy; import org.exist.dom.QName; import org.exist.memtree.MemTreeBuilder; import org.exist.security.Permission; import org.exist.security.PermissionDeniedException; import org.exist.security.User; import org.exist.source.DBSource; import org.exist.source.Source; import org.exist.source.SourceFactory; import org.exist.storage.DBBroker; import org.exist.storage.lock.Lock; import org.exist.util.Collations; import org.exist.util.Configuration; import org.exist.util.LockException; import org.exist.xquery.parser.XQueryLexer; import org.exist.xquery.parser.XQueryParser; import org.exist.xquery.parser.XQueryTreeParser; import org.exist.xquery.value.Item; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceIterator; import org.exist.xquery.value.Type; import antlr.RecognitionException; import antlr.TokenStreamException; import antlr.collections.AST; /** * The current XQuery execution context. Contains the static as well * as the dynamic XQuery context components. * * @author Wolfgang Meier ([email protected]) */ public class XQueryContext { private static final String JAVA_URI_START = "java:"; private static final String XMLDB_URI_START = "xmldb:exist://"; public final static String XML_NS = "http://www.w3.org/XML/1998/namespace"; public final static String SCHEMA_NS = "http://www.w3.org/2001/XMLSchema"; public final static String SCHEMA_DATATYPES_NS = "http://www.w3.org/2001/XMLSchema-datatypes"; public final static String SCHEMA_INSTANCE_NS = "http://www.w3.org/2001/XMLSchema-instance"; public final static String XPATH_DATATYPES_NS = "http://www.w3.org/2003/05/xpath-datatypes"; public final static String XQUERY_LOCAL_NS = "http://www.w3.org/2003/08/xquery-local-functions"; public final static String EXIST_NS = "http://exist.sourceforge.net/NS/exist"; private final static Logger LOG = Logger.getLogger(XQueryContext.class); private static final String TEMP_STORE_ERROR = "Error occurred while storing temporary data"; private static final HashMap moduleClasses = new HashMap(); // Static namespace/prefix mappings protected HashMap namespaces; // Local in-scope namespace/prefix mappings in the current context protected HashMap inScopeNamespaces = new HashMap(); // Static prefix/namespace mappings protected HashMap prefixes; // Local prefix/namespace mappings in the current context protected HashMap inScopePrefixes = new HashMap(); // Local namespace stack protected Stack namespaceStack = new Stack(); // Known user defined functions in the local module protected TreeMap declaredFunctions = new TreeMap(); // Globally declared variables protected TreeMap globalVariables = new TreeMap(); // The last element in the linked list of local in-scope variables protected LocalVariable lastVar = null; protected Stack contextStack = new Stack(); // The current size of the variable stack protected int variableStackSize = 0; // Unresolved references to user defined functions protected Stack forwardReferences = new Stack(); // List of pragmas declared for this query protected List pragmas = null; /** * the watchdog object assigned to this query * * @uml.property name="watchdog" * @uml.associationEnd multiplicity="(1 1)" */ protected XQueryWatchDog watchdog; /** * Loaded modules. */ protected HashMap modules = new HashMap(); /** * The set of statically known documents specified as * an array of paths to documents and collections. */ protected String[] staticDocumentPaths = null; /** * The actual set of statically known documents. This * will be generated on demand from staticDocumentPaths. */ protected DocumentSet staticDocuments = null; /** * The main database broker object providing access * to storage and indexes. Every XQuery has its own * DBBroker object. */ protected DBBroker broker; protected String baseURI = ""; protected boolean baseURISetInProlog = false; protected String moduleLoadPath = "."; protected String defaultFunctionNamespace = Function.BUILTIN_FUNCTION_NS; /** * The default collation URI */ private String defaultCollation = Collations.CODEPOINT; /** * Default Collator. Will be null for the default unicode codepoint collation. */ private Collator defaultCollator = null; /** * Set to true to enable XPath 1.0 * backwards compatibility. */ private boolean backwardsCompatible = true; /** * Should whitespace inside node constructors be stripped? */ private boolean stripWhitespace = true; /** * The position of the currently processed item in the context * sequence. This field has to be set on demand, for example, * before calling the fn:position() function. */ private int contextPosition = 0; /** * The builder used for creating in-memory document * fragments */ private MemTreeBuilder builder = null; /** * Stack for temporary document fragments */ private Stack fragmentStack = new Stack(); /** * The root of the expression tree */ private Expression rootExpression; /** * Flag to indicate that the query should put an exclusive * lock on all documents involved. * * TODO: No longer needed? */ private boolean exclusive = false; /** * Should all documents loaded by the query be locked? * If set to true, it is the responsibility of the calling client * code to unlock documents after the query has completed. */ private boolean lockDocumentsOnLoad = false; /** * Documents locked during the query. */ private DocumentSet lockedDocuments = null; /** * The profiler instance used by this context. */ private Profiler profiler = new Profiler(); //For holding XQuery Context variables from setXQueryContextVar() and getXQueryContextVar() HashMap XQueryContextVars = new HashMap(); //set an XQuery Context variable; called by context:set-var() public void setXQueryContextVar(String name, Object XQvar) { XQueryContextVars.put(name, XQvar); } //get an XQuery Context variable; called by context:get-var() public Object getXQueryContextVar(String name) { return(XQueryContextVars.get(name)); } //set the serializer to use for output; called by context:set-serializer() public void setXQuerySerializer(String name, boolean indent, boolean omitxmldeclaration) throws XPathException { Pragma pragma; //Has a exist:serialize pragma already been set? for(int i = 0; i < pragmas.size(); i++) { pragma = (Pragma)pragmas.get(i); if((pragma.getQName().equals("exist:serialize")) /*&& (pragma.getContents().indexOf("method") != -1)*/ ) { //yes, so modify the content from the existing pragma String content = pragma.getContents(); if(content.indexOf("method=") != -1) { content = content.replaceFirst("method=[^/ ]*", "method=" + name); } else { content += " method=" + name; } if(content.indexOf("indent=") != -1) { content = content.replaceFirst("indent=[^/ ]*", "indent=" + (indent ? "yes":"no")); } else { content += " indent" + (indent ? "yes":"no"); } if(content.indexOf("omit-xml-declaration") != -1) { content = content.replaceFirst("omit-xml-declaration=[^/ ]*", "omit-xml-declaration=" + (omitxmldeclaration ? "yes":"no")); } else { content += " omit-xml-declaration" + (omitxmldeclaration ? "yes":"no"); } //Delete the existing serialize pragma pragmas.remove(i); //Add the new serialize pragma addPragma("exist:serialize", content); return; //done } } //no, so set a pragma for serialization addPragma("exist:serialize", "method=" + name + " indent=" + (indent ? "yes":"no") + " omit-xml-declaration=" + (omitxmldeclaration ? "yes":"no")); } protected XQueryContext() { builder = new MemTreeBuilder(this); builder.startDocument(); } public XQueryContext(DBBroker broker) { this(); this.broker = broker; loadDefaults(broker.getConfiguration()); } /** * @return true if profiling is enabled for this context. */ public boolean isProfilingEnabled() { return profiler.isEnabled(); } public boolean isProfilingEnabled(int verbosity) { return profiler.isEnabled() && profiler.verbosity() >= verbosity; } /** * Returns the {@link Profiler} instance of this context * if profiling is enabled. * * @return the profiler instance. */ public Profiler getProfiler() { return profiler; } /** * Called from the XQuery compiler to set the root expression * for this context. * * @param expr */ public void setRootExpression(Expression expr) { this.rootExpression = expr; } /** * Returns the root expression of the XQuery associated with * this context. * * @return */ public Expression getRootExpression() { return rootExpression; } /** * Declare a user-defined prefix/namespace mapping. * * eXist internally keeps a table containing all prefix/namespace * mappings it found in documents, which have been previously * stored into the database. These default mappings need not to be * declared explicitely. * * @param prefix * @param uri */ public void declareNamespace(String prefix, String uri) throws XPathException { if (prefix == null) prefix = ""; if(uri == null) uri = ""; if (prefix.equals("xml") || prefix.equals("xmlns")) throw new XPathException("err:XQST0070: Namespace predefined prefix '" + prefix + "' can not be bound"); if (uri.equals(XML_NS)) throw new XPathException("err:XQST0070: Namespace URI '" + uri + "' must be bound to the 'xml' prefix"); final String prevURI = (String)namespaces.get(prefix); //This prefix was not bound if(prevURI == null ) { //Bind it if (uri.length() > 0) { namespaces.put(prefix, uri); prefixes.put(uri, prefix); return; } //Nothing to bind else { //TODO : check the specs : unbinding an NS which is not already bound may be disallowed. LOG.warn("Unbinding unbound prefix '" + prefix + "'"); } } else //This prefix was bound { //Unbind it if (uri.length() == 0) { // if an empty namespace is specified, // remove any existing mapping for this namespace //TODO : improve, since XML_NS can't be unbound prefixes.remove(uri); namespaces.remove(prefix); return; } //Forbids rebinding the *same* prefix in a *different* namespace in this *same* context if (!uri.equals(prevURI)) throw new XPathException("err:XQST0033: Namespace prefix '" + prefix + "' is already bound to a different uri '" + prevURI + "'"); } } public void declareNamespaces(Map namespaceMap) { Map.Entry entry; String prefix, uri; for(Iterator i = namespaceMap.entrySet().iterator(); i.hasNext(); ) { entry = (Map.Entry)i.next(); prefix = (String)entry.getKey(); uri = (String) entry.getValue(); if(prefix == null) prefix = ""; if(uri == null) uri = ""; namespaces.put(prefix, uri); prefixes.put(uri, prefix); } } /** * Declare an in-scope namespace. This is called during query execution. * * @param prefix * @param uri */ public void declareInScopeNamespace(String prefix, String uri) { if (prefix == null || uri == null) throw new IllegalArgumentException("null argument passed to declareNamespace"); if (inScopeNamespaces == null) inScopeNamespaces = new HashMap(); inScopeNamespaces.put(prefix, uri); } /** * Returns the current default function namespace. * * @return */ public String getDefaultFunctionNamespace() { return defaultFunctionNamespace; } /** * Set the default function namespace. By default, this * points to the namespace for XPath built-in functions. * * @param uri */ public void setDefaultFunctionNamespace(String uri) { defaultFunctionNamespace = uri; } /** * Set the default collation to be used by all operators and functions on strings. * Throws an exception if the collation is unknown or cannot be instantiated. * * @param uri * @throws XPathException */ public void setDefaultCollation(String uri) throws XPathException { if(uri.equals(Collations.CODEPOINT) || uri.equals(Collations.CODEPOINT_SHORT)) { defaultCollation = Collations.CODEPOINT; defaultCollator = null; } defaultCollator = Collations.getCollationFromURI(this, uri); defaultCollation = uri; } public String getDefaultCollation() { return defaultCollation; } public Collator getCollator(String uri) throws XPathException { if(uri == null) return defaultCollator; return Collations.getCollationFromURI(this, uri); } public Collator getDefaultCollator() { return defaultCollator; } /** * Return the namespace URI mapped to the registered prefix * or null if the prefix is not registered. * * @param prefix * @return */ public String getURIForPrefix(String prefix) { String ns = (String) namespaces.get(prefix); if (ns == null) // try in-scope namespace declarations return inScopeNamespaces == null ? null : (String) inScopeNamespaces.get(prefix); else return ns; } /** * Return the prefix mapped to the registered URI or * null if the URI is not registered. * * @param uri * @return */ public String getPrefixForURI(String uri) { String prefix = (String) prefixes.get(uri); if (prefix == null) return inScopePrefixes == null ? null : (String) inScopeNamespaces.get(uri); else return prefix; } /** * Removes the namespace URI from the prefix/namespace * mappings table. * * @param uri */ public void removeNamespace(String uri) { prefixes.remove(uri); for (Iterator i = namespaces.values().iterator(); i.hasNext();) { if (((String) i.next()).equals(uri)) { i.remove(); return; } } inScopePrefixes.remove(uri); if (inScopeNamespaces != null) { for (Iterator i = inScopeNamespaces.values().iterator(); i.hasNext();) { if (((String) i.next()).equals(uri)) { i.remove(); return; } } } } /** * Clear all user-defined prefix/namespace mappings. */ public void clearNamespaces() { namespaces.clear(); prefixes.clear(); if (inScopeNamespaces != null) { inScopeNamespaces.clear(); inScopePrefixes.clear(); } loadDefaults(broker.getConfiguration()); } /** * Set the set of statically known documents for the current * execution context. These documents will be processed if * no explicit document set has been set for the current expression * with fn:doc() or fn:collection(). * * @param docs */ public void setStaticallyKnownDocuments(String[] docs) { staticDocumentPaths = docs; } public void setStaticallyKnownDocuments(DocumentSet set) { staticDocuments = set; } /** * Get the set of statically known documents. * * @return */ public DocumentSet getStaticallyKnownDocuments() throws XPathException { if(staticDocuments != null) // the document set has already been built, return it return staticDocuments; staticDocuments = new DocumentSet(); if(staticDocumentPaths == null) // no path defined: return all documents in the db broker.getAllDocuments(staticDocuments); else { DocumentImpl doc; Collection collection; for(int i = 0; i < staticDocumentPaths.length; i++) { try { doc = broker.openDocument(staticDocumentPaths[i], Lock.READ_LOCK); if(doc != null) { if(doc.getPermissions().validate(broker.getUser(), Permission.READ)) { staticDocuments.add(doc); } doc.getUpdateLock().release(Lock.READ_LOCK); } else { collection = broker.getCollection(staticDocumentPaths[i]); if(collection != null) { LOG.debug("reading collection " + staticDocumentPaths[i]); collection.allDocs(broker, staticDocuments, true, true); } } } catch(PermissionDeniedException e) { LOG.warn("Permission denied to read resource " + staticDocumentPaths[i] + ". Skipping it."); } } } return staticDocuments; } /** * Should loaded documents be locked? * * @see #setLockDocumentsOnLoad(boolean) * * @return */ public boolean lockDocumentsOnLoad() { return lockDocumentsOnLoad; } /** * If lock is true, all documents loaded during query execution * will be locked. This way, we avoid that query results become * invalid before the entire result has been processed by the client * code. All attempts to modify nodes which are part of the result * set will be blocked. * * However, it is the client's responsibility to proper unlock * all documents once processing is completed. * * @param lock */ public void setLockDocumentsOnLoad(boolean lock) { lockDocumentsOnLoad = lock; if(lock) lockedDocuments = new DocumentSet(); } /** * Returns the set of documents that have been loaded and * locked during query execution. * * @see #setLockDocumentsOnLoad(boolean) * * @return */ public DocumentSet getLockedDocuments() { return lockedDocuments; } /** * Release all locks on documents that have been locked * during query execution. * *@see #setLockDocumentsOnLoad(boolean) */ public void releaseLockedDocuments() { if(lockedDocuments != null) lockedDocuments.unlock(false); lockDocumentsOnLoad = false; lockedDocuments = null; } /** * Release all locks on documents not being referenced by the sequence. * This is called after query execution has completed. Only locks on those * documents contained in the final result set will be preserved. All other * locks are released as they are no longer needed. * * @param seq * @return */ public DocumentSet releaseUnusedDocuments(Sequence seq) { if(lockedDocuments == null) return null; // determine the set of documents referenced by nodes in the sequence DocumentSet usedDocs = new DocumentSet(); for(SequenceIterator i = seq.iterate(); i.hasNext(); ) { Item next = i.nextItem(); if(Type.subTypeOf(next.getType(), Type.NODE)) { NodeValue node = (NodeValue) next; if(node.getImplementationType() == NodeValue.PERSISTENT_NODE) { DocumentImpl doc = ((NodeProxy)node).getDocument(); if(!usedDocs.contains(doc.getDocId())) usedDocs.add(doc, false); } } } DocumentSet remaining = new DocumentSet(); for(Iterator i = lockedDocuments.iterator(); i.hasNext(); ) { DocumentImpl next = (DocumentImpl) i.next(); if(usedDocs.contains(next.getDocId())) { remaining.add(next); } else { // LOG.debug("Releasing lock on " + next.getName()); next.getUpdateLock().release(Lock.READ_LOCK); } } // LOG.debug("Locks remaining: " + remaining.getLength()); lockDocumentsOnLoad = false; lockedDocuments = null; return remaining; } /** * Prepare this XQueryContext to be reused. This should be * called when adding an XQuery to the cache. */ public void reset() { builder = new MemTreeBuilder(this); builder.startDocument(); staticDocumentPaths = null; staticDocuments = null; lastVar = null; fragmentStack = new Stack(); watchdog.reset(); profiler.reset(); for(Iterator i = modules.values().iterator(); i.hasNext(); ) { Module module = (Module)i.next(); module.reset(); } } /** * Returns true if whitespace between constructed element nodes * should be stripped by default. * * @return */ public boolean stripWhitespace() { return stripWhitespace; } public void setStripWhitespace(boolean strip) { this.stripWhitespace = strip; } /** * Return an iterator over all built-in modules currently * registered. * * @return */ public Iterator getModules() { return modules.values().iterator(); } /** * Get the built-in module registered for the given namespace * URI. * * @param namespaceURI * @return */ public Module getModule(String namespaceURI) { return (Module) modules.get(namespaceURI); } /** * For compiled expressions: check if the source of any * module imported by the current query has changed since * compilation. * * @return */ public boolean checkModulesValid() { for(Iterator i = modules.values().iterator(); i.hasNext(); ) { Module module = (Module)i.next(); if(!module.isInternalModule()) { if(!((ExternalModule)module).moduleIsValid()) { LOG.debug("Module with URI " + module.getNamespaceURI() + " has changed and needs to be reloaded"); return false; } } } return true; } /** * Load a built-in module from the given class name and assign it to the * namespace URI. The specified class should be a subclass of * {@link Module}. The method will try to instantiate the class. If the * class is not found or an exception is thrown, the method will silently * fail. The namespace URI has to be equal to the namespace URI declared * by the module class. Otherwise, the module is not loaded. * * @param namespaceURI * @param moduleClass */ public Module loadBuiltInModule(String namespaceURI, String moduleClass) { Module module = getModule(namespaceURI); if (module != null) { // LOG.debug("module " + namespaceURI + " is already present"); return module; } try { Class mClass = (Class) moduleClasses.get(moduleClass); if (mClass == null) { mClass = Class.forName(moduleClass); if (!(Module.class.isAssignableFrom(mClass))) { LOG.warn( "failed to load module. " + moduleClass + " is not an instance of org.exist.xquery.Module."); return null; } moduleClasses.put(moduleClass, mClass); } module = (Module) mClass.newInstance(); if (!module.getNamespaceURI().equals(namespaceURI)) { LOG.warn("the module declares a different namespace URI. Skipping..."); return null; } if (getPrefixForURI(module.getNamespaceURI()) == null && module.getDefaultPrefix().length() > 0) declareNamespace(module.getDefaultPrefix(), module.getNamespaceURI()); modules.put(module.getNamespaceURI(), module); //LOG.debug("module " + module.getNamespaceURI() + " loaded successfully."); } catch (ClassNotFoundException e) { //LOG.warn("module class " + moduleClass + " not found. Skipping..."); } catch (InstantiationException e) { LOG.warn("error while instantiating module class " + moduleClass, e); } catch (IllegalAccessException e) { LOG.warn("error while instantiating module class " + moduleClass, e); } catch (XPathException e) { LOG.warn("error while instantiating module class " + moduleClass, e); } return module; } /** * Declare a user-defined function. All user-defined functions are kept * in a single hash map. * * @param function * @throws XPathException */ public void declareFunction(UserDefinedFunction function) throws XPathException { declaredFunctions.put(function.getSignature().getFunctionId(), function); } /** * Resolve a user-defined function. * * @param name * @return * @throws XPathException */ public UserDefinedFunction resolveFunction(QName name, int argCount) throws XPathException { FunctionId id = new FunctionId(name, argCount); UserDefinedFunction func = (UserDefinedFunction) declaredFunctions.get(id); return func; } public Iterator getSignaturesForFunction(QName name) { ArrayList signatures = new ArrayList(2); for (Iterator i = declaredFunctions.values().iterator(); i.hasNext(); ) { UserDefinedFunction func = (UserDefinedFunction) i.next(); if (func.getName().equals(name)) signatures.add(func.getSignature()); } return signatures.iterator(); } public Iterator localFunctions() { return declaredFunctions.values().iterator(); } /** * Declare a local variable. This is called by variable binding expressions like * "let" and "for". * * @param var * @return * @throws XPathException */ public LocalVariable declareVariableBinding(LocalVariable var) throws XPathException { if(lastVar == null) lastVar = var; else { lastVar.addAfter(var); lastVar = var; } var.setStackPosition(variableStackSize); return var; } /** * Declare a global variable as by "declare variable". * * @param qname * @param value * @return * @throws XPathException */ public Variable declareGlobalVariable(Variable var) throws XPathException { globalVariables.put(var.getQName(), var); var.setStackPosition(variableStackSize); return var; } /** * Declare a user-defined variable. * * The value argument is converted into an XPath value * (@see XPathUtil#javaObjectToXPath(Object)). * * @param qname the qualified name of the new variable. Any namespaces should * have been declared before. * @param value a Java object, representing the fixed value of the variable * @return the created Variable object * @throws XPathException if the value cannot be converted into a known XPath value * or the variable QName references an unknown namespace-prefix. */ public Variable declareVariable(String qname, Object value) throws XPathException { QName qn = QName.parse(this, qname, null); Variable var; Module module = getModule(qn.getNamespaceURI()); if(module != null) { var = module.declareVariable(qn, value); return var; } Sequence val = XPathUtil.javaObjectToXPath(value, this); var = (Variable)globalVariables.get(qn); if(var == null) { var = new Variable(qn); globalVariables.put(qn, var); } //TODO : should we allow global variable *re*declaration ? var.setValue(val); return var; } /** * Try to resolve a variable. * * @param qname the qualified name of the variable as string * @return the declared Variable object * @throws XPathException if the variable is unknown */ public Variable resolveVariable(String name) throws XPathException { QName qn = QName.parse(this, name, null); return resolveVariable(qn); } /** * Try to resolve a variable. * * @param qname the qualified name of the variable * @return the declared Variable object * @throws XPathException if the variable is unknown */ public Variable resolveVariable(QName qname) throws XPathException { Variable var; // check if the variable is declared local var = resolveLocalVariable(qname); // check if the variable is declared in a module if (var == null){ Module module = getModule(qname.getNamespaceURI()); if(module != null) { var = module.resolveVariable(qname); } } // check if the variable is declared global if (var == null) var = (Variable) globalVariables.get(qname); if (var == null) throw new XPathException("variable $" + qname + " is not bound"); return var; } private Variable resolveLocalVariable(QName qname) throws XPathException { LocalVariable end = contextStack.isEmpty() ? null : (LocalVariable) contextStack.peek(); for(LocalVariable var = lastVar; var != null; var = var.before) { if (var == end) return null; if(qname.equals(var.getQName())) return var; } return null; } public boolean isVarDeclared(QName qname) { Module module = getModule(qname.getNamespaceURI()); if(module != null) { if (module.isVarDeclared(qname)) return true; } return globalVariables.get(qname) != null; } /** * Turn on/off XPath 1.0 backwards compatibility. * * If turned on, comparison expressions will behave like * in XPath 1.0, i.e. if any one of the operands is a number, * the other operand will be cast to a double. * * @param backwardsCompatible */ public void setBackwardsCompatibility(boolean backwardsCompatible) { this.backwardsCompatible = backwardsCompatible; } /** * XPath 1.0 backwards compatibility turned on? * * In XPath 1.0 compatible mode, additional conversions * will be applied to values if a numeric value is expected. * * @return */ public boolean isBackwardsCompatible() { return this.backwardsCompatible; } /** * Get the DBBroker instance used for the current query. * * The DBBroker is the main database access object, providing * access to all internal database functions. * * @return */ public DBBroker getBroker() { return broker; } public void setBroker(DBBroker broker) { this.broker = broker; } /** * Get the user which executes the current query. * * @return */ public User getUser() { return broker.getUser(); } /** * Get the document builder currently used for creating * temporary document fragments. A new document builder * will be created on demand. * * @return */ public MemTreeBuilder getDocumentBuilder() { if (builder == null) { builder = new MemTreeBuilder(this); builder.startDocument(); } return builder; } /* Methods delegated to the watchdog */ public void proceed() throws TerminatedException { proceed(null); } public void proceed(Expression expr) throws TerminatedException { watchdog.proceed(expr); } public void proceed(Expression expr, MemTreeBuilder builder) throws TerminatedException { watchdog.proceed(expr, builder); } public void recover() { watchdog.reset(); builder = null; } public XQueryWatchDog getWatchDog() { return watchdog; } protected void setWatchDog(XQueryWatchDog watchdog) { this.watchdog = watchdog; } /** * Push any document fragment created within the current * execution context on the stack. */ public void pushDocumentContext() { fragmentStack.push(builder); builder = null; } public void popDocumentContext() { if (!fragmentStack.isEmpty()) { builder = (MemTreeBuilder) fragmentStack.pop(); } } /** * Set the base URI for the evaluation context. * * This is the URI returned by the fn:base-uri() * function. * * @param uri */ public void setBaseURI(String uri) { setBaseURI(uri, false); } /** * Set the base URI for the evaluation context. * * A base URI specified via the base-uri directive in the * XQuery prolog overwrites any other setting. * * @param uri * @param setInProlog */ public void setBaseURI(String uri, boolean setInProlog) { if (baseURISetInProlog) return; if (uri == null) baseURI = ""; baseURI = uri; baseURISetInProlog = setInProlog; } /** * Set the path to a base directory where modules should * be loaded from. Relative module paths will be resolved against * this directory. The property is usually set by the XQueryServlet or * XQueryGenerator, but can also be specified manually. * * @param path */ public void setModuleLoadPath(String path) { this.moduleLoadPath = path; } public String getModuleLoadPath() { return moduleLoadPath; } /** * Get the base URI of the evaluation context. * * This is the URI returned by the fn:base-uri() function. * * @return */ public String getBaseURI() { return baseURI; } /** * Set the current context position, i.e. the position * of the currently processed item in the context sequence. * This value is required by some expressions, e.g. fn:position(). * * @param pos */ public void setContextPosition(int pos) { contextPosition = pos; } /** * Get the current context position, i.e. the position of * the currently processed item in the context sequence. * * @return */ public int getContextPosition() { return contextPosition; } /** * Push all in-scope namespace declarations onto the stack. */ public void pushInScopeNamespaces() { HashMap m = (HashMap) inScopeNamespaces.clone(); namespaceStack.push(inScopeNamespaces); inScopeNamespaces = m; } public void popInScopeNamespaces() { inScopeNamespaces = (HashMap) namespaceStack.pop(); } public void pushNamespaceContext() { HashMap m = (HashMap) namespaces.clone(); HashMap p = (HashMap) prefixes.clone(); namespaceStack.push(namespaces); namespaceStack.push(prefixes); namespaces = m; prefixes = p; } public void popNamespaceContext() { prefixes = (HashMap) namespaceStack.pop(); namespaces = (HashMap) namespaceStack.pop(); } /** * Returns the last variable on the local variable stack. * The current variable context can be restored by passing * the return value to {@link #popLocalVariables(LocalVariable)}. * * @return */ public LocalVariable markLocalVariables(boolean newContext) { if (newContext) contextStack.push(lastVar); variableStackSize++; return lastVar; } /** * Restore the local variable stack to the position marked * by variable var. * * @param var */ public void popLocalVariables(LocalVariable var) { if(var != null) { var.after = null; if (!contextStack.isEmpty() && var == contextStack.peek()) { contextStack.pop(); } } lastVar = var; variableStackSize--; } /** * Returns the current size of the stack. This is used to determine * where a variable has been declared. * * @return */ public int getCurrentStackSize() { return variableStackSize; } /** * Import a module and make it available in this context. The prefix and * location parameters are optional. If prefix is null, the default prefix specified * by the module is used. If location is null, the module will be read from the * namespace URI. * * @param namespaceURI * @param prefix * @param location * @throws XPathException */ public void importModule(String namespaceURI, String prefix, String location) throws XPathException { Module module = getModule(namespaceURI); if(module != null) { LOG.debug("Module " + namespaceURI + " already present."); } else { if(location == null) location = namespaceURI; // is it a Java module? if(location.startsWith(JAVA_URI_START)) { location = location.substring(JAVA_URI_START.length()); module = loadBuiltInModule(namespaceURI, location); } else { Source source; // Is the module source stored in the database? if (location.startsWith(XMLDB_URI_START) || moduleLoadPath.startsWith(XMLDB_URI_START)) { if (location.indexOf(':') < 0) location = moduleLoadPath + '/' + location; String path = location.substring(XMLDB_URI_START.length()); DocumentImpl sourceDoc = null; try { sourceDoc = broker.openDocument(path, Lock.READ_LOCK); if (sourceDoc == null) throw new XPathException("source for module " + location + " not found in database"); if (sourceDoc.getResourceType() != DocumentImpl.BINARY_FILE || !sourceDoc.getMimeType().equals("application/xquery")) throw new XPathException("source for module " + location + " is not an XQuery or " + "declares a wrong mime-type"); source = new DBSource(broker, (BinaryDocument) sourceDoc, true); module = compileModule(namespaceURI, location, module, source); } catch (PermissionDeniedException e) { throw new XPathException("permission denied to read module source from " + location); } finally { if(sourceDoc != null) sourceDoc.getUpdateLock().release(Lock.READ_LOCK); } // No. Load from file or URL } else { try { source = SourceFactory.getSource(moduleLoadPath, location, true); } catch (MalformedURLException e) { throw new XPathException("source location for module " + namespaceURI + " should be a valid URL: " + e.getMessage()); } catch (IOException e) { throw new XPathException("source for module " + namespaceURI + " not found: " + e.getMessage()); } module = compileModule(namespaceURI, location, module, source); } } } if(prefix == null) prefix = module.getDefaultPrefix(); declareNamespace(prefix, namespaceURI); } /** * @param namespaceURI * @param location * @param module * @param source * @return * @throws XPathException */ private Module compileModule(String namespaceURI, String location, Module module, Source source) throws XPathException { LOG.debug("Loading module from " + location); Reader reader; try { reader = source.getReader(); } catch (IOException e) { throw new XPathException("IO exception while loading module " + namespaceURI, e); } XQueryContext modContext = new ModuleContext(this); XQueryLexer lexer = new XQueryLexer(modContext, reader); XQueryParser parser = new XQueryParser(lexer); XQueryTreeParser astParser = new XQueryTreeParser(modContext); try { parser.xpath(); if (parser.foundErrors()) { LOG.debug(parser.getErrorMessage()); throw new XPathException( "error found while loading module from " + location + ": " + parser.getErrorMessage()); } AST ast = parser.getAST(); PathExpr path = new PathExpr(modContext); astParser.xpath(ast, path); if (astParser.foundErrors()) { throw new XPathException( "error found while loading module from " + location + ": " + astParser.getErrorMessage(), astParser.getLastException()); } path.analyze(null, 0); ExternalModule modExternal = astParser.getModule(); if(modExternal == null) throw new XPathException("source at " + location + " is not a valid module"); if(!modExternal.getNamespaceURI().equals(namespaceURI)) throw new XPathException("namespace URI declared by module (" + modExternal.getNamespaceURI() + ") does not match namespace URI in import statement, which was: " + namespaceURI); modules.put(modExternal.getNamespaceURI(), modExternal); modExternal.setSource(source); modExternal.setContext(modContext); module = modExternal; } catch (RecognitionException e) { throw new XPathException( "error found while loading module from " + location + ": " + e.getMessage(), e.getLine(), e.getColumn()); } catch (TokenStreamException e) { throw new XPathException( "error found while loading module from " + location + ": " + e.getMessage(), e); } catch (XPathException e) { e.prependMessage("Error while loading module " + location + ": "); throw e; } catch (Exception e) { throw new XPathException("Internal error while loading module: " + location, e); } declareModuleVars(module); return module; } private void declareModuleVars(Module module) { String moduleNS = module.getNamespaceURI(); for (Iterator i = globalVariables.values().iterator(); i.hasNext(); ) { Variable var = (Variable) i.next(); if (moduleNS.equals(var.getQName().getNamespaceURI())) { module.declareVariable(var); i.remove(); } } } /** * Add a forward reference to an undeclared function. Forward * references will be resolved later. * * @param call */ public void addForwardReference(FunctionCall call) { forwardReferences.push(call); } /** * Resolve all forward references to previously undeclared functions. * * @throws XPathException */ public void resolveForwardReferences() throws XPathException { while(!forwardReferences.empty()) { FunctionCall call = (FunctionCall)forwardReferences.pop(); UserDefinedFunction func = resolveFunction(call.getQName(), call.getArgumentCount()); if(func == null) throw new XPathException(call.getASTNode(), "Call to undeclared function: " + call.getQName().toString()); call.resolveForwardReference(func); } } /** * Called by XUpdate to tell the query engine that it is running in * exclusive mode, i.e. no other query is executed at the same time. * * @param exclusive */ public void setExclusiveMode(boolean exclusive) { this.exclusive = exclusive; } public boolean inExclusiveMode() { return exclusive; } public void addPragma(String qnameString, String contents) throws XPathException { QName qn; try { qn = QName.parse(this, qnameString, defaultFunctionNamespace); } catch (XPathException e) { // unknown pragma: just ignore it LOG.debug("Ignoring unknown pragma: " + qnameString); return; } Pragma pragma = new Pragma(qn, contents); if(pragmas == null) pragmas = new ArrayList(); pragmas.add(pragma); // check predefined pragmas if (Pragma.PROFILE_QNAME.compareTo(qn) == 0) { // configure profiling profiler.configure(pragma); } else if(Pragma.TIMEOUT_QNAME.compareTo(qn) == 0) watchdog.setTimeoutFromPragma(pragma); else if(Pragma.OUTPUT_SIZE_QNAME.compareTo(qn) == 0) watchdog.setMaxNodesFromPragma(pragma); } public Pragma getPragma(QName qname) { if(pragmas != null) { Pragma pragma; for(int i = 0; i < pragmas.size(); i++) { pragma = (Pragma)pragmas.get(i); if(qname.compareTo(pragma.getQName()) == 0) return pragma; } } return null; } /** * Store the supplied data to a temporary document fragment. * * @param data * @return * @throws XPathException */ public DocumentImpl storeTemporaryDoc(org.exist.memtree.DocumentImpl doc) throws XPathException { try { DocumentImpl targetDoc = broker.storeTemporaryDoc(doc); watchdog.addTemporaryFragment(targetDoc.getFileName()); LOG.debug("Stored: " + targetDoc.getDocId() + ": " + targetDoc.getName() + ": " + targetDoc.printTreeLevelOrder()); return targetDoc; } catch (EXistException e) { throw new XPathException(TEMP_STORE_ERROR, e); } catch (PermissionDeniedException e) { throw new XPathException(TEMP_STORE_ERROR, e); } catch (LockException e) { throw new XPathException(TEMP_STORE_ERROR, e); } } /** * Load the default prefix/namespace mappings table and set up * internal functions. */ protected void loadDefaults(Configuration config) { this.watchdog = new XQueryWatchDog(this); namespaces = new HashMap(); prefixes = new HashMap(); /* SymbolTable syms = broker.getSymbols(); String[] pfx = syms.defaultPrefixList(); namespaces = new HashMap(pfx.length); prefixes = new HashMap(pfx.length); String sym; for (int i = 0; i < pfx.length; i++) { sym = syms.getDefaultNamespace(pfx[i]); namespaces.put(pfx[i], sym); prefixes.put(sym, pfx[i]); } */ try { // default namespaces namespaces.put("xml", XML_NS); prefixes.put(XML_NS, "xml"); declareNamespace("xs", SCHEMA_NS); declareNamespace("xdt", XPATH_DATATYPES_NS); declareNamespace("local", XQUERY_LOCAL_NS); declareNamespace("fn", Function.BUILTIN_FUNCTION_NS); //*not* as standard NS declareNamespace("exist", EXIST_NS); } catch (XPathException e) { //TODO : ignored because it should never happen } // load built-in modules // these modules are loaded dynamically. It is not an error if the // specified module class cannot be found in the classpath. loadBuiltInModule( Function.BUILTIN_FUNCTION_NS, "org.exist.xquery.functions.ModuleImpl"); String modules[][] = (String[][]) config.getProperty("xquery.modules"); if ( modules != null ) { for (int i = 0; i < modules.length; i++) { // LOG.debug("Loading module " + modules[i][0]); loadBuiltInModule(modules[i][0], modules[i][1]); } } } }
Allow options to be overwritten at evaluation time. svn path=/trunk/eXist-1.0/; revision=2016
src/org/exist/xquery/XQueryContext.java
Allow options to be overwritten at evaluation time.
<ide><path>rc/org/exist/xquery/XQueryContext.java <ide> Pragma pragma = new Pragma(qn, contents); <ide> if(pragmas == null) <ide> pragmas = new ArrayList(); <del> pragmas.add(pragma); <add> <add> // check if this overwrites an already existing pragma <add> boolean added = false; <add> Pragma old; <add> for (int i = 0; i < pragmas.size(); i++) { <add> old = (Pragma) pragmas.get(i); <add> if (old.equals(pragma)) { <add> pragmas.add(i, pragma); <add> added = true; <add> break; <add> } <add> } <add> // add the pragma to the list if it does not yet exist <add> if (!added) <add> pragmas.add(pragma); <ide> <ide> // check predefined pragmas <ide> if (Pragma.PROFILE_QNAME.compareTo(qn) == 0) {
Java
apache-2.0
03e6113c9ea555bf93b9ce064a2c0d1cd8073cc5
0
icirellik/tika,smadha/tika,icirellik/tika,smadha/tika,zamattiac/tika,zamattiac/tika,zamattiac/tika,zamattiac/tika,icirellik/tika,smadha/tika,smadha/tika,smadha/tika,icirellik/tika,icirellik/tika,zamattiac/tika,icirellik/tika,icirellik/tika,smadha/tika,zamattiac/tika,smadha/tika,zamattiac/tika,smadha/tika,icirellik/tika,zamattiac/tika
/* * 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.tika.parser.microsoft.ooxml; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import org.apache.poi.POIXMLDocument; import org.apache.poi.POIXMLTextExtractor; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.openxml4j.opc.TargetMode; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.Ole10Native; import org.apache.poi.poifs.filesystem.Ole10NativeException; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.tika.exception.TikaException; import org.apache.tika.extractor.EmbeddedDocumentExtractor; import org.apache.tika.extractor.ParsingEmbeddedDocumentExtractor; import org.apache.tika.io.TikaInputStream; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.microsoft.OfficeParser.POIFSDocumentType; import org.apache.tika.sax.EmbeddedContentHandler; import org.apache.tika.sax.XHTMLContentHandler; import org.apache.xmlbeans.XmlException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; /** * Base class for all Tika OOXML extractors. * * Tika extractors decorate POI extractors so that the parsed content of * documents is returned as a sequence of XHTML SAX events. Subclasses must * implement the buildXHTML method {@link #buildXHTML(XHTMLContentHandler)} that * populates the {@link XHTMLContentHandler} object received as parameter. */ public abstract class AbstractOOXMLExtractor implements OOXMLExtractor { static final String RELATION_AUDIO = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/audio"; static final String RELATION_IMAGE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"; static final String RELATION_OLE_OBJECT = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject"; static final String RELATION_PACKAGE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/package"; private static final String TYPE_OLE_OBJECT = "application/vnd.openxmlformats-officedocument.oleObject"; protected POIXMLTextExtractor extractor; private final EmbeddedDocumentExtractor embeddedExtractor; private final String type; public AbstractOOXMLExtractor(ParseContext context, POIXMLTextExtractor extractor, String type) { this.extractor = extractor; this.type = type; EmbeddedDocumentExtractor ex = context.get(EmbeddedDocumentExtractor.class); if (ex==null) { embeddedExtractor = new ParsingEmbeddedDocumentExtractor(context); } else { embeddedExtractor = ex; } } /** * @see org.apache.tika.parser.microsoft.ooxml.OOXMLExtractor#getDocument() */ public POIXMLDocument getDocument() { return extractor.getDocument(); } /** * @see org.apache.tika.parser.microsoft.ooxml.OOXMLExtractor#getMetadataExtractor() */ public MetadataExtractor getMetadataExtractor() { return new MetadataExtractor(extractor, type); } /** * @see org.apache.tika.parser.microsoft.ooxml.OOXMLExtractor#getXHTML(org.xml.sax.ContentHandler, * org.apache.tika.metadata.Metadata) */ public void getXHTML( ContentHandler handler, Metadata metadata, ParseContext context) throws SAXException, XmlException, IOException, TikaException { XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startDocument(); buildXHTML(xhtml); // Now do any embedded parts handleEmbeddedParts(handler); xhtml.endDocument(); } private void handleEmbeddedParts(ContentHandler handler) throws TikaException, IOException, SAXException { try { for (PackagePart source : getMainDocumentParts()) { for (PackageRelationship rel : source.getRelationships()) { if (rel.getTargetMode() == TargetMode.INTERNAL) { PackagePart target = source.getRelatedPart(rel); String type = rel.getRelationshipType(); if (RELATION_OLE_OBJECT.equals(type) && TYPE_OLE_OBJECT.equals(target.getContentType())) { handleEmbeddedOLE(target, handler); } else if (RELATION_AUDIO.equals(type) || RELATION_IMAGE.equals(type) || RELATION_PACKAGE.equals(type) || RELATION_OLE_OBJECT.equals(type)) { handleEmbeddedFile(target, handler); } } } } } catch (InvalidFormatException e) { throw new TikaException("Broken OOXML file", e); } } /** * Handles an embedded OLE object in the document */ private void handleEmbeddedOLE(PackagePart part, ContentHandler handler) throws IOException, SAXException { POIFSFileSystem fs = new POIFSFileSystem(part.getInputStream()); try { Metadata metadata = new Metadata(); TikaInputStream stream = null; DirectoryNode root = fs.getRoot(); POIFSDocumentType type = POIFSDocumentType.detectType(root); if (root.hasEntry("CONTENTS") && root.hasEntry("\u0001Ole") && root.hasEntry("\u0001CompObj") && root.hasEntry("\u0003ObjInfo")) { // TIKA-704: OLE 2.0 embedded non-Office document? stream = TikaInputStream.get( fs.createDocumentInputStream("CONTENTS")); if (embeddedExtractor.shouldParseEmbedded(metadata)) { embeddedExtractor.parseEmbedded( stream, new EmbeddedContentHandler(handler), metadata, false); } } else if (POIFSDocumentType.OLE10_NATIVE == type) { // TIKA-704: OLE 1.0 embedded document Ole10Native ole = Ole10Native.createFromEmbeddedOleObject(fs); metadata.set(Metadata.RESOURCE_NAME_KEY, ole.getLabel()); byte[] data = ole.getDataBuffer(); if (data != null) { stream = TikaInputStream.get(data); } if (stream != null && embeddedExtractor.shouldParseEmbedded(metadata)) { embeddedExtractor.parseEmbedded( stream, new EmbeddedContentHandler(handler), metadata, false); } } else { handleEmbeddedFile(part, handler); } } catch (FileNotFoundException e) { // There was no CONTENTS entry, so skip this part } catch (Ole10NativeException e) { // Could not process an OLE 1.0 entry, so skip this part } } /** * Handles an embedded file in the document */ protected void handleEmbeddedFile(PackagePart part, ContentHandler handler) throws SAXException, IOException { Metadata metadata = new Metadata(); // Get the name String name = part.getPartName().getName(); metadata.set( Metadata.RESOURCE_NAME_KEY, name.substring(name.lastIndexOf('/') + 1)); // Get the content type metadata.set( Metadata.CONTENT_TYPE, part.getContentType()); // Call the recursing handler if (embeddedExtractor.shouldParseEmbedded(metadata)) { embeddedExtractor.parseEmbedded( TikaInputStream.get(part.getInputStream()), new EmbeddedContentHandler(handler), metadata, false); } } /** * Populates the {@link XHTMLContentHandler} object received as parameter. */ protected abstract void buildXHTML(XHTMLContentHandler xhtml) throws SAXException, XmlException, IOException; /** * Return a list of the main parts of the document, used * when searching for embedded resources. * This should be all the parts of the document that end * up with things embedded into them. */ protected abstract List<PackagePart> getMainDocumentParts() throws TikaException; }
tika-parsers/src/main/java/org/apache/tika/parser/microsoft/ooxml/AbstractOOXMLExtractor.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.tika.parser.microsoft.ooxml; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import org.apache.poi.POIXMLDocument; import org.apache.poi.POIXMLTextExtractor; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.openxml4j.opc.PackagingURIHelper; import org.apache.poi.openxml4j.opc.TargetMode; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.Ole10Native; import org.apache.poi.poifs.filesystem.Ole10NativeException; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.tika.exception.TikaException; import org.apache.tika.extractor.EmbeddedDocumentExtractor; import org.apache.tika.extractor.ParsingEmbeddedDocumentExtractor; import org.apache.tika.io.TikaInputStream; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.microsoft.OfficeParser.POIFSDocumentType; import org.apache.tika.sax.EmbeddedContentHandler; import org.apache.tika.sax.XHTMLContentHandler; import org.apache.xmlbeans.XmlException; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; /** * Base class for all Tika OOXML extractors. * * Tika extractors decorate POI extractors so that the parsed content of * documents is returned as a sequence of XHTML SAX events. Subclasses must * implement the buildXHTML method {@link #buildXHTML(XHTMLContentHandler)} that * populates the {@link XHTMLContentHandler} object received as parameter. */ public abstract class AbstractOOXMLExtractor implements OOXMLExtractor { static final String RELATION_AUDIO = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/audio"; static final String RELATION_IMAGE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"; static final String RELATION_OLE_OBJECT = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject"; static final String RELATION_PACKAGE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/package"; private static final String TYPE_OLE_OBJECT = "application/vnd.openxmlformats-officedocument.oleObject"; protected POIXMLTextExtractor extractor; private final EmbeddedDocumentExtractor embeddedExtractor; private final String type; public AbstractOOXMLExtractor(ParseContext context, POIXMLTextExtractor extractor, String type) { this.extractor = extractor; this.type = type; EmbeddedDocumentExtractor ex = context.get(EmbeddedDocumentExtractor.class); if (ex==null) { embeddedExtractor = new ParsingEmbeddedDocumentExtractor(context); } else { embeddedExtractor = ex; } } /** * @see org.apache.tika.parser.microsoft.ooxml.OOXMLExtractor#getDocument() */ public POIXMLDocument getDocument() { return extractor.getDocument(); } /** * @see org.apache.tika.parser.microsoft.ooxml.OOXMLExtractor#getMetadataExtractor() */ public MetadataExtractor getMetadataExtractor() { return new MetadataExtractor(extractor, type); } /** * @see org.apache.tika.parser.microsoft.ooxml.OOXMLExtractor#getXHTML(org.xml.sax.ContentHandler, * org.apache.tika.metadata.Metadata) */ public void getXHTML( ContentHandler handler, Metadata metadata, ParseContext context) throws SAXException, XmlException, IOException, TikaException { XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startDocument(); buildXHTML(xhtml); // Now do any embedded parts handleEmbeddedParts(handler); xhtml.endDocument(); } private void handleEmbeddedParts(ContentHandler handler) throws TikaException, IOException, SAXException { try { for (PackagePart source : getMainDocumentParts()) { for (PackageRelationship rel : source.getRelationships()) { if (rel.getTargetMode() == TargetMode.INTERNAL) { // TODO Simply this when on POI 3.8 beta 5 URI uri = rel.getTargetURI(); if(uri.getFragment() != null) { // TODO Workaround for TIKA-705 needed until 3.8 beta 5 try { String u = uri.toString(); uri = new URI(u.substring(0, u.indexOf('#'))); } catch(URISyntaxException e) { throw new TikaException("Broken OOXML file", e); } } PackagePart target = rel.getPackage().getPart( PackagingURIHelper.createPartName(uri)); // TODO Simpler version in POI 3.8 beta 5 // PackagePart target = source.getRelatedPart(rel); String type = rel.getRelationshipType(); if (RELATION_OLE_OBJECT.equals(type) && TYPE_OLE_OBJECT.equals(target.getContentType())) { handleEmbeddedOLE(target, handler); } else if (RELATION_AUDIO.equals(type) || RELATION_IMAGE.equals(type) || RELATION_PACKAGE.equals(type) || RELATION_OLE_OBJECT.equals(type)) { handleEmbeddedFile(target, handler); } } } } } catch (InvalidFormatException e) { throw new TikaException("Broken OOXML file", e); } } /** * Handles an embedded OLE object in the document */ private void handleEmbeddedOLE(PackagePart part, ContentHandler handler) throws IOException, SAXException { POIFSFileSystem fs = new POIFSFileSystem(part.getInputStream()); try { Metadata metadata = new Metadata(); TikaInputStream stream = null; DirectoryNode root = fs.getRoot(); POIFSDocumentType type = POIFSDocumentType.detectType(root); if (root.hasEntry("CONTENTS") && root.hasEntry("\u0001Ole") && root.hasEntry("\u0001CompObj") && root.hasEntry("\u0003ObjInfo")) { // TIKA-704: OLE 2.0 embedded non-Office document? stream = TikaInputStream.get( fs.createDocumentInputStream("CONTENTS")); if (embeddedExtractor.shouldParseEmbedded(metadata)) { embeddedExtractor.parseEmbedded( stream, new EmbeddedContentHandler(handler), metadata, false); } } else if (POIFSDocumentType.OLE10_NATIVE == type) { // TIKA-704: OLE 1.0 embedded document Ole10Native ole = Ole10Native.createFromEmbeddedOleObject(fs); metadata.set(Metadata.RESOURCE_NAME_KEY, ole.getLabel()); byte[] data = ole.getDataBuffer(); if (data != null) { stream = TikaInputStream.get(data); } if (stream != null && embeddedExtractor.shouldParseEmbedded(metadata)) { embeddedExtractor.parseEmbedded( stream, new EmbeddedContentHandler(handler), metadata, false); } } else { handleEmbeddedFile(part, handler); } } catch (FileNotFoundException e) { // There was no CONTENTS entry, so skip this part } catch (Ole10NativeException e) { // Could not process an OLE 1.0 entry, so skip this part } } /** * Handles an embedded file in the document */ protected void handleEmbeddedFile(PackagePart part, ContentHandler handler) throws SAXException, IOException { Metadata metadata = new Metadata(); // Get the name String name = part.getPartName().getName(); metadata.set( Metadata.RESOURCE_NAME_KEY, name.substring(name.lastIndexOf('/') + 1)); // Get the content type metadata.set( Metadata.CONTENT_TYPE, part.getContentType()); // Call the recursing handler if (embeddedExtractor.shouldParseEmbedded(metadata)) { embeddedExtractor.parseEmbedded( TikaInputStream.get(part.getInputStream()), new EmbeddedContentHandler(handler), metadata, false); } } /** * Populates the {@link XHTMLContentHandler} object received as parameter. */ protected abstract void buildXHTML(XHTMLContentHandler xhtml) throws SAXException, XmlException, IOException; /** * Return a list of the main parts of the document, used * when searching for embedded resources. * This should be all the parts of the document that end * up with things embedded into them. */ protected abstract List<PackagePart> getMainDocumentParts() throws TikaException; }
TIKA-705 / TIKA-757 - Simplify the OOXML related parts code, following POI upgrade git-svn-id: de575e320ab8ef6bd6941acfb783cdb8d8307cc1@1221115 13f79535-47bb-0310-9956-ffa450edef68
tika-parsers/src/main/java/org/apache/tika/parser/microsoft/ooxml/AbstractOOXMLExtractor.java
TIKA-705 / TIKA-757 - Simplify the OOXML related parts code, following POI upgrade
<ide><path>ika-parsers/src/main/java/org/apache/tika/parser/microsoft/ooxml/AbstractOOXMLExtractor.java <ide> <ide> import java.io.FileNotFoundException; <ide> import java.io.IOException; <del>import java.net.URI; <del>import java.net.URISyntaxException; <ide> import java.util.List; <ide> <ide> import org.apache.poi.POIXMLDocument; <ide> import org.apache.poi.openxml4j.exceptions.InvalidFormatException; <ide> import org.apache.poi.openxml4j.opc.PackagePart; <ide> import org.apache.poi.openxml4j.opc.PackageRelationship; <del>import org.apache.poi.openxml4j.opc.PackagingURIHelper; <ide> import org.apache.poi.openxml4j.opc.TargetMode; <ide> import org.apache.poi.poifs.filesystem.DirectoryNode; <ide> import org.apache.poi.poifs.filesystem.Ole10Native; <ide> for (PackagePart source : getMainDocumentParts()) { <ide> for (PackageRelationship rel : source.getRelationships()) { <ide> if (rel.getTargetMode() == TargetMode.INTERNAL) { <del> // TODO Simply this when on POI 3.8 beta 5 <del> URI uri = rel.getTargetURI(); <del> if(uri.getFragment() != null) { <del> // TODO Workaround for TIKA-705 needed until 3.8 beta 5 <del> try { <del> String u = uri.toString(); <del> uri = new URI(u.substring(0, u.indexOf('#'))); <del> } catch(URISyntaxException e) { <del> throw new TikaException("Broken OOXML file", e); <del> } <del> } <del> PackagePart target = rel.getPackage().getPart( <del> PackagingURIHelper.createPartName(uri)); <del> // TODO Simpler version in POI 3.8 beta 5 <del> // PackagePart target = source.getRelatedPart(rel); <add> PackagePart target = source.getRelatedPart(rel); <ide> <ide> String type = rel.getRelationshipType(); <ide> if (RELATION_OLE_OBJECT.equals(type)
Java
apache-2.0
27368362b3b3ebb3749ce411053e8c99b8510329
0
twogee/ant-ivy,jaikiran/ant-ivy,jaikiran/ant-ivy,twogee/ant-ivy,twogee/ant-ivy,apache/ant-ivy,apache/ant-ivy,apache/ant-ivy,jaikiran/ant-ivy,jaikiran/ant-ivy,apache/ant-ivy,twogee/ant-ivy
/* * 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.ivy.osgi.repo; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.apache.ivy.plugins.repository.Resource; import org.apache.ivy.plugins.repository.url.URLRepository; import org.apache.ivy.plugins.repository.url.URLResource; public class RelativeURLRepository extends URLRepository { private final URL baseUrl; public RelativeURLRepository() { super(); baseUrl = null; } public RelativeURLRepository(URL baseUrl) { super(); this.baseUrl = baseUrl; } private Map/* <String, Resource> */resourcesCache = new HashMap/* <String, Resource> */(); public Resource getResource(String source) throws IOException { source = encode(source); Resource res = (Resource) resourcesCache.get(source); if (res == null) { URI uri; try { uri = new URI(source); } catch (URISyntaxException e) { // very wierd URL, let's assume it is absolute uri = null; } if (uri == null || uri.isAbsolute()) { res = new URLResource(new URL(source)); } else { res = new URLResource(new URL(baseUrl + source)); } resourcesCache.put(source, res); } return res; } private static String encode(String source) { // TODO: add some more URL encodings here return source.trim().replaceAll(" ", "%20"); } }
src/java/org/apache/ivy/osgi/repo/RelativeURLRepository.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.ivy.osgi.repo; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.apache.ivy.plugins.repository.Resource; import org.apache.ivy.plugins.repository.url.URLRepository; import org.apache.ivy.plugins.repository.url.URLResource; public class RelativeURLRepository extends URLRepository { private final URL baseUrl; public RelativeURLRepository() { super(); baseUrl = null; } public RelativeURLRepository(URL baseUrl) { super(); this.baseUrl = baseUrl; } private Map/* <String, Resource> */resourcesCache = new HashMap/* <String, Resource> */(); public Resource getResource(String source) throws IOException { source = encode(source); Resource res = (Resource) resourcesCache.get(source); if (res == null) { if (baseUrl == null) { res = new URLResource(new URL(source)); } else { res = new URLResource(new URL(baseUrl + source)); } resourcesCache.put(source, res); } return res; } private static String encode(String source) { // TODO: add some more URL encodings here return source.trim().replaceAll(" ", "%20"); } }
handle url which are absolute git-svn-id: bddd0b838a5b7898c5897d85c562f956f46262e5@1051063 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/ivy/osgi/repo/RelativeURLRepository.java
handle url which are absolute
<ide><path>rc/java/org/apache/ivy/osgi/repo/RelativeURLRepository.java <ide> package org.apache.ivy.osgi.repo; <ide> <ide> import java.io.IOException; <add>import java.net.URI; <add>import java.net.URISyntaxException; <ide> import java.net.URL; <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> source = encode(source); <ide> Resource res = (Resource) resourcesCache.get(source); <ide> if (res == null) { <del> if (baseUrl == null) { <add> URI uri; <add> try { <add> uri = new URI(source); <add> } catch (URISyntaxException e) { <add> // very wierd URL, let's assume it is absolute <add> uri = null; <add> } <add> if (uri == null || uri.isAbsolute()) { <ide> res = new URLResource(new URL(source)); <ide> } else { <ide> res = new URLResource(new URL(baseUrl + source));
Java
apache-2.0
05161d39b6f947c197864aa7e89f0f6723d718d3
0
voyagersearch/Xponents,voyagersearch/Xponents,OpenSextant/Xponents,voyagersearch/Xponents,OpenSextant/Xponents,OpenSextant/Xponents,voyagersearch/Xponents,voyagersearch/Xponents
/** * * Copyright 2009-2013 The MITRE Corporation. * * 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. * * ************************************************************************** * NOTICE This software was produced for the U. S. Government under Contract No. * W15P7T-12-C-F600, and is subject to the Rights in Noncommercial Computer * Software and Noncommercial Computer Software Documentation Clause * 252.227-7014 (JUN 1995) * * (c) 2012 The MITRE Corporation. All Rights Reserved. * ************************************************************************** */ package org.opensextant.extractors.xtemporal; import java.util.Date; import org.opensextant.extraction.TextMatch; /** * * @author ubaldino */ public class DateMatch extends TextMatch { /** * Just the coordinate text normalized */ public Date datenorm = null; /** * */ public String datenorm_text = null; /** * */ public DateMatch() { // populate attrs as needed; type = "datetime"; producer = "XTemp"; } /** * A simplistic way to capture resolution of the date/time reference. */ public enum TimeResolution { NONE(-1, "U"), YEAR(1, "Y"), MONTH(2, "M"), WEEK(3, "W"), DAY(4, "D"), HOUR(5, "H"), MINUTE(6, "m"), SECOND(7, "s"); public int level = -1; public String code = null; TimeResolution(int l, String c) { level = l; code = c; } }; // Enum representing YEAR, MON, WEEK, DAY, HR, MIN // public TimeResolution resolution = TimeResolution.NONE; /** Flag caller can use to classify if a date match is distant */ public boolean isDistantPast = false; /** Flag caller can use to classify if date is future relative to a given date, by default TODAY*/ public boolean isFuture = false; }
Extraction/src/main/java/org/opensextant/extractors/xtemporal/DateMatch.java
/** * * Copyright 2009-2013 The MITRE Corporation. * * 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. * * ************************************************************************** * NOTICE This software was produced for the U. S. Government under Contract No. * W15P7T-12-C-F600, and is subject to the Rights in Noncommercial Computer * Software and Noncommercial Computer Software Documentation Clause * 252.227-7014 (JUN 1995) * * (c) 2012 The MITRE Corporation. All Rights Reserved. * ************************************************************************** */ package org.opensextant.extractors.xtemporal; import java.util.Date; import org.opensextant.extraction.TextMatch; /** * * @author ubaldino */ public class DateMatch extends TextMatch { /** * Just the coordinate text normalized */ public Date datenorm = null; /** * */ public String datenorm_text = null; /** * */ public DateMatch() { // populate attrs as needed; type = "datetime"; producer = "XTemp"; } /** * A simplistic way to capture resolution of the date/time reference. */ public enum TimeResolution { NONE(-1, "U"), YEAR(1, "Y"), MONTH(2, "M"), WEEK(3, "W"), DAY(4, "D"), HOUR(5, "H"), MINUTE(6, "m"), SECOND(7, "s"); public int level = -1; public String code = null; TimeResolution(int l, String c) { level = l; code = c; } }; // Enum representing YEAR, MON, WEEK, DAY, HR, MIN // public TimeResolution resolution = TimeResolution.NONE; /* public String toString() { return text + " @(" + start + ":" + end + ") matched by " + this.pattern_id; } */ }
added notion of past and future to dates; these are post-processed based on the contex set in the xtractor; or could be set by caller
Extraction/src/main/java/org/opensextant/extractors/xtemporal/DateMatch.java
added notion of past and future to dates; these are post-processed based on the contex set in the xtractor; or could be set by caller
<ide><path>xtraction/src/main/java/org/opensextant/extractors/xtemporal/DateMatch.java <ide> code = c; <ide> } <ide> }; <add> <ide> // Enum representing YEAR, MON, WEEK, DAY, HR, MIN <ide> // <ide> public TimeResolution resolution = TimeResolution.NONE; <ide> <del> /* public String toString() { <del> return text + " @(" + start + ":" + end + ") matched by " + this.pattern_id; <del> } */ <add> /** Flag caller can use to classify if a date match is distant */ <add> public boolean isDistantPast = false; <add> /** Flag caller can use to classify if date is future relative to a given date, by default TODAY*/ <add> public boolean isFuture = false; <add> <ide> }
Java
apache-2.0
9a6a2aff93ce47dcdf02e6c1328dac543eeead68
0
inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service
/* * Copyright 2012 Shared Learning Collaborative, LLC * * 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.slc.sli.dashboard.manager.impl; import java.io.File; import java.io.FileReader; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.slc.sli.dashboard.entity.Config; import org.slc.sli.dashboard.entity.ConfigMap; import org.slc.sli.dashboard.entity.EdOrgKey; import org.slc.sli.dashboard.entity.GenericEntity; import org.slc.sli.dashboard.manager.ApiClientManager; import org.slc.sli.dashboard.manager.ConfigManager; import org.slc.sli.dashboard.util.CacheableConfig; import org.slc.sli.dashboard.util.Constants; import org.slc.sli.dashboard.util.DashboardException; import org.slc.sli.dashboard.util.JsonConverter; /** * * ConfigManager allows other classes, such as controllers, to access and * persist view configurations. * Given a user, it will obtain view configuration at each level of the user's * hierarchy, and merge them into one set for the user. * * @author dwu */ public class ConfigManagerImpl extends ApiClientManager implements ConfigManager { private Logger logger = LoggerFactory.getLogger(getClass()); private String driverConfigLocation; private String userConfigLocation; public ConfigManagerImpl() { } /** * this method should be called by Spring Framework * set location of config file to be read. If the directory does not exist, * create it. * * @param configLocation * reading from properties file panel.config.driver.dir */ public void setDriverConfigLocation(String configLocation) { URL url = Config.class.getClassLoader().getResource(configLocation); if (url == null) { File f = new File(Config.class.getClassLoader().getResource("") + "/" + configLocation); f.mkdir(); this.driverConfigLocation = f.getAbsolutePath(); } else { this.driverConfigLocation = url.getPath(); } } /** * this method should be called by Spring Framework * set location of config file to be read. If the directory does not exist, * create it. * * @param configLocation * reading from properties file panel.config.custom.dir */ public void setUserConfigLocation(String configLocation) { if (!configLocation.startsWith("/")) { URL url = Config.class.getClassLoader().getResource(configLocation); if (url == null) { File f = new File(Config.class.getClassLoader().getResource("") .getPath() + configLocation); f.mkdir(); configLocation = f.getAbsolutePath(); } else { configLocation = url.getPath(); } } this.userConfigLocation = configLocation; } /** * return the absolute file path of domain specific config file * * @param path * can be district ID name or state ID name * @param componentId * profile name * @return the absolute file path of domain specific config file */ public String getComponentConfigLocation(String path, String componentId) { return userConfigLocation + "/" + path + "/" + componentId + ".json"; } /** * return the absolute file path of default config file * * @param path * can be district ID name or state ID name * @param componentId * profile name * @return the absolute file path of default config file */ public String getDriverConfigLocation(String componentId) { return this.driverConfigLocation + "/" + componentId + ".json"; } /** * Find the lowest organization hierarchy config file. If the lowest * organization hierarchy * config file does not exist, it returns default (Driver) config file. * If the Driver config file does not exist, it is in a critical situation. * It will throw an * exception. * * @param apiCustomConfig * custom configuration uploaded by admininistrator. * @param customPath * abslute directory path where a config file exist. * @param componentId * name of the profile * @return proper Config to be used for the dashboard */ private Config getConfigByPath(Config customConfig, String componentId) { Config driverConfig = null; try { String driverId = componentId; // if custom config exist, read the config file if (customConfig != null) { driverId = customConfig.getParentId(); } // read Driver (default) config. File f = new File(getDriverConfigLocation(driverId)); driverConfig = loadConfig(f); if (customConfig != null) { return driverConfig.overWrite(customConfig); } return driverConfig; } catch (Throwable t) { logger.error("Unable to read config for " + componentId, t); throw new DashboardException("Unable to read config for " + componentId); } } private Config loadConfig(File f) throws Exception { if (f.exists()) { FileReader fr = new FileReader(f); try { return JsonConverter.fromJson(fr, Config.class); } finally { IOUtils.closeQuietly(fr); } } return null; } @Override @CacheableConfig public Config getComponentConfig(String token, EdOrgKey edOrgKey, String componentId) { Config customComponentConfig = null; GenericEntity edOrg = null; GenericEntity parentEdOrg = null; EdOrgKey parentEdOrgKey = null; String id = edOrgKey.getSliId(); List<EdOrgKey> edOrgKeys = new ArrayList<EdOrgKey>(); edOrgKeys.add(edOrgKey); //keep reading EdOrg until it hits the top. do { edOrg = getApiClient().getEducationalOrganization(token, id); if(edOrg != null) { parentEdOrg = getApiClient().getParentEducationalOrganization(token, edOrg); if(parentEdOrg != null) { id = parentEdOrg.getId(); parentEdOrgKey = new EdOrgKey(id); edOrgKeys.add(parentEdOrgKey); } } else { //if edOrg is null, it means no parent edOrg either. parentEdOrg = null; } }while(parentEdOrg != null); for(EdOrgKey key:edOrgKeys) { ConfigMap configMap = getCustomConfig(token, key); // if api has config if (configMap != null && !configMap.isEmpty()) { Config edOrgComponentConfig = configMap.getComponentConfig(componentId); if(edOrgComponentConfig != null) { if(customComponentConfig == null) { customComponentConfig = edOrgComponentConfig; } else { //edOrgComponentConfig overwrites customComponentConfig customComponentConfig = edOrgComponentConfig.overWrite(customComponentConfig); } } } } return getConfigByPath(customComponentConfig, componentId); } @Override @Cacheable(value = Constants.CACHE_USER_WIDGET_CONFIG) public Collection<Config> getWidgetConfigs(String token, EdOrgKey edOrgKey) { Map<String, String> attrs = new HashMap<String, String>(); attrs.put("type", Config.Type.WIDGET.toString()); return getConfigsByAttribute(token, edOrgKey, attrs); } @Override public Collection<Config> getConfigsByAttribute(String token, EdOrgKey edOrgKey, Map<String, String> attrs) { // id to config map Map<String, Config> configs = new HashMap<String, Config>(); Config config; // list files in driver dir File driverConfigDir = new File(this.driverConfigLocation); File[] driverConfigFiles = driverConfigDir.listFiles(); if (driverConfigFiles == null) { logger.error("Unable to read config directory"); throw new DashboardException("Unable to read config directory!!!!"); } for (File f : driverConfigFiles) { try { config = loadConfig(f); } catch (Exception e) { logger.error("Unable to read config " + f.getName() + ". Skipping file", e); continue; } // check the config params. if they all match, add to the config map. boolean matchAll = true; for (String attrName : attrs.keySet()) { String methodName = ""; try { // use reflection to call the right config object method methodName = "get" + Character.toUpperCase(attrName.charAt(0)) + attrName.substring(1); Method method = config.getClass().getDeclaredMethod (methodName, new Class[] {}); Object ret = method.invoke(config, new Object[] {}); // compare the result to the desired result if (!(ret.toString().equals(attrs.get(attrName)))) { matchAll = false; break; } } catch (Exception e) { matchAll = false; logger.error("Error calling config method: " + methodName); } } // add to config map if (matchAll) { configs.put(config.getId(), config); } } // get custom configs for (String id : configs.keySet()) { configs.put(id, getComponentConfig(token, edOrgKey, id)); } return configs.values(); } /** * Get the user's educational organization's custom configuration. * * @param token * The user's authentication token. * @return The education organization's custom configuration */ @Override public ConfigMap getCustomConfig(String token, EdOrgKey edOrgKey) { try { return getApiClient().getEdOrgCustomData(token, edOrgKey.getSliId()); } catch (Throwable t) { // it's a valid scenario when there is no district specific config. Default will be used in this case. return null; } } /** * Put or save the user's educational organization's custom configuration. * * @param token * The user's authentication token. * @param customConfigJson * The education organization's custom configuration JSON. */ @Override @CacheEvict(value = Constants.CACHE_USER_PANEL_CONFIG, allEntries = true) public void putCustomConfig(String token, EdOrgKey edOrgKey, ConfigMap configMap) { getApiClient().putEdOrgCustomData(token, edOrgKey.getSliId(), configMap); } /** * Save one custom configuration for an ed-org * */ @Override @CacheEvict(value = Constants.CACHE_USER_PANEL_CONFIG, allEntries = true) public void putCustomConfig(String token, EdOrgKey edOrgKey, Config config) { // get current custom config map from api ConfigMap configMap = getCustomConfig(token, edOrgKey); if (configMap == null) { configMap = new ConfigMap(); configMap.setConfig(new HashMap<String, Config>()); } // update with new config ConfigMap newConfigMap = configMap.cloneWithNewConfig(config); // write new config map getApiClient().putEdOrgCustomData(token, edOrgKey.getSliId(), newConfigMap); } }
sli/dashboard/src/main/java/org/slc/sli/dashboard/manager/impl/ConfigManagerImpl.java
/* * Copyright 2012 Shared Learning Collaborative, LLC * * 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.slc.sli.dashboard.manager.impl; import java.io.File; import java.io.FileReader; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.slc.sli.dashboard.entity.Config; import org.slc.sli.dashboard.entity.ConfigMap; import org.slc.sli.dashboard.entity.EdOrgKey; import org.slc.sli.dashboard.entity.GenericEntity; import org.slc.sli.dashboard.manager.ApiClientManager; import org.slc.sli.dashboard.manager.ConfigManager; import org.slc.sli.dashboard.util.CacheableConfig; import org.slc.sli.dashboard.util.Constants; import org.slc.sli.dashboard.util.DashboardException; import org.slc.sli.dashboard.util.JsonConverter; /** * * ConfigManager allows other classes, such as controllers, to access and * persist view configurations. * Given a user, it will obtain view configuration at each level of the user's * hierarchy, and merge them into one set for the user. * * @author dwu */ public class ConfigManagerImpl extends ApiClientManager implements ConfigManager { private Logger logger = LoggerFactory.getLogger(getClass()); private String driverConfigLocation; private String userConfigLocation; public ConfigManagerImpl() { } /** * this method should be called by Spring Framework * set location of config file to be read. If the directory does not exist, * create it. * * @param configLocation * reading from properties file panel.config.driver.dir */ public void setDriverConfigLocation(String configLocation) { URL url = Config.class.getClassLoader().getResource(configLocation); if (url == null) { File f = new File(Config.class.getClassLoader().getResource("") + "/" + configLocation); f.mkdir(); this.driverConfigLocation = f.getAbsolutePath(); } else { this.driverConfigLocation = url.getPath(); } } /** * this method should be called by Spring Framework * set location of config file to be read. If the directory does not exist, * create it. * * @param configLocation * reading from properties file panel.config.custom.dir */ public void setUserConfigLocation(String configLocation) { if (!configLocation.startsWith("/")) { URL url = Config.class.getClassLoader().getResource(configLocation); if (url == null) { File f = new File(Config.class.getClassLoader().getResource("") .getPath() + configLocation); f.mkdir(); configLocation = f.getAbsolutePath(); } else { configLocation = url.getPath(); } } this.userConfigLocation = configLocation; } /** * return the absolute file path of domain specific config file * * @param path * can be district ID name or state ID name * @param componentId * profile name * @return the absolute file path of domain specific config file */ public String getComponentConfigLocation(String path, String componentId) { return userConfigLocation + "/" + path + "/" + componentId + ".json"; } /** * return the absolute file path of default config file * * @param path * can be district ID name or state ID name * @param componentId * profile name * @return the absolute file path of default config file */ public String getDriverConfigLocation(String componentId) { return this.driverConfigLocation + "/" + componentId + ".json"; } /** * Find the lowest organization hierarchy config file. If the lowest * organization hierarchy * config file does not exist, it returns default (Driver) config file. * If the Driver config file does not exist, it is in a critical situation. * It will throw an * exception. * * @param apiCustomConfig * custom configuration uploaded by admininistrator. * @param customPath * abslute directory path where a config file exist. * @param componentId * name of the profile * @return proper Config to be used for the dashboard */ private Config getConfigByPath(Config customConfig, String componentId) { Config driverConfig = null; try { String driverId = componentId; // if custom config exist, read the config file if (customConfig != null) { driverId = customConfig.getParentId(); } // read Driver (default) config. File f = new File(getDriverConfigLocation(driverId)); driverConfig = loadConfig(f); if (customConfig != null) { return driverConfig.overWrite(customConfig); } return driverConfig; } catch (Throwable t) { logger.error("Unable to read config for " + componentId, t); throw new DashboardException("Unable to read config for " + componentId); } } private Config loadConfig(File f) throws Exception { if (f.exists()) { FileReader fr = new FileReader(f); try { return JsonConverter.fromJson(fr, Config.class); } finally { IOUtils.closeQuietly(fr); } } return null; } @Override @CacheableConfig public Config getComponentConfig(String token, EdOrgKey edOrgKey, String componentId) { Config customComponentConfig = null; GenericEntity edOrg = null; GenericEntity parentEdOrg = null; EdOrgKey parentEdOrgKey = null; String id = edOrgKey.getSliId(); List<EdOrgKey> edOrgKeys = new ArrayList<EdOrgKey>(); edOrgKeys.add(edOrgKey); //keep reading EdOrg until it hits the top. do { edOrg = getApiClient().getEducationalOrganization(token, id); if(edOrg != null) { parentEdOrg = getApiClient().getParentEducationalOrganization(token, edOrg); if(parentEdOrg != null) { id = parentEdOrg.getId(); parentEdOrgKey = new EdOrgKey(id); edOrgKeys.add(parentEdOrgKey); } } else { //if edOrg is null, it means no parent edOrg either. parentEdOrg = null; } }while(parentEdOrg != null); for(EdOrgKey key:edOrgKeys) { ConfigMap configMap = getCustomConfig(token, key); // if api has config if (configMap != null && !configMap.isEmpty()) { Config edOrgComponentConfig = configMap.getComponentConfig(componentId); if(customComponentConfig == null) { customComponentConfig = edOrgComponentConfig; } else { //edOrgComponentConfig overwrites customComponentConfig customComponentConfig = edOrgComponentConfig.overWrite(customComponentConfig); } } } return getConfigByPath(customComponentConfig, componentId); } @Override @Cacheable(value = Constants.CACHE_USER_WIDGET_CONFIG) public Collection<Config> getWidgetConfigs(String token, EdOrgKey edOrgKey) { Map<String, String> attrs = new HashMap<String, String>(); attrs.put("type", Config.Type.WIDGET.toString()); return getConfigsByAttribute(token, edOrgKey, attrs); } @Override public Collection<Config> getConfigsByAttribute(String token, EdOrgKey edOrgKey, Map<String, String> attrs) { // id to config map Map<String, Config> configs = new HashMap<String, Config>(); Config config; // list files in driver dir File driverConfigDir = new File(this.driverConfigLocation); File[] driverConfigFiles = driverConfigDir.listFiles(); if (driverConfigFiles == null) { logger.error("Unable to read config directory"); throw new DashboardException("Unable to read config directory!!!!"); } for (File f : driverConfigFiles) { try { config = loadConfig(f); } catch (Exception e) { logger.error("Unable to read config " + f.getName() + ". Skipping file", e); continue; } // check the config params. if they all match, add to the config map. boolean matchAll = true; for (String attrName : attrs.keySet()) { String methodName = ""; try { // use reflection to call the right config object method methodName = "get" + Character.toUpperCase(attrName.charAt(0)) + attrName.substring(1); Method method = config.getClass().getDeclaredMethod (methodName, new Class[] {}); Object ret = method.invoke(config, new Object[] {}); // compare the result to the desired result if (!(ret.toString().equals(attrs.get(attrName)))) { matchAll = false; break; } } catch (Exception e) { matchAll = false; logger.error("Error calling config method: " + methodName); } } // add to config map if (matchAll) { configs.put(config.getId(), config); } } // get custom configs for (String id : configs.keySet()) { configs.put(id, getComponentConfig(token, edOrgKey, id)); } return configs.values(); } /** * Get the user's educational organization's custom configuration. * * @param token * The user's authentication token. * @return The education organization's custom configuration */ @Override public ConfigMap getCustomConfig(String token, EdOrgKey edOrgKey) { try { return getApiClient().getEdOrgCustomData(token, edOrgKey.getSliId()); } catch (Throwable t) { // it's a valid scenario when there is no district specific config. Default will be used in this case. return null; } } /** * Put or save the user's educational organization's custom configuration. * * @param token * The user's authentication token. * @param customConfigJson * The education organization's custom configuration JSON. */ @Override @CacheEvict(value = Constants.CACHE_USER_PANEL_CONFIG, allEntries = true) public void putCustomConfig(String token, EdOrgKey edOrgKey, ConfigMap configMap) { getApiClient().putEdOrgCustomData(token, edOrgKey.getSliId(), configMap); } /** * Save one custom configuration for an ed-org * */ @Override @CacheEvict(value = Constants.CACHE_USER_PANEL_CONFIG, allEntries = true) public void putCustomConfig(String token, EdOrgKey edOrgKey, Config config) { // get current custom config map from api ConfigMap configMap = getCustomConfig(token, edOrgKey); if (configMap == null) { configMap = new ConfigMap(); configMap.setConfig(new HashMap<String, Config>()); } // update with new config ConfigMap newConfigMap = configMap.cloneWithNewConfig(config); // write new config map getApiClient().putEdOrgCustomData(token, edOrgKey.getSliId(), newConfigMap); } }
US3292: Waterfall Logic Config
sli/dashboard/src/main/java/org/slc/sli/dashboard/manager/impl/ConfigManagerImpl.java
US3292: Waterfall Logic Config
<ide><path>li/dashboard/src/main/java/org/slc/sli/dashboard/manager/impl/ConfigManagerImpl.java <ide> // if api has config <ide> if (configMap != null && !configMap.isEmpty()) { <ide> Config edOrgComponentConfig = configMap.getComponentConfig(componentId); <del> if(customComponentConfig == null) { <del> customComponentConfig = edOrgComponentConfig; <del> } else { <del> //edOrgComponentConfig overwrites customComponentConfig <del> customComponentConfig = edOrgComponentConfig.overWrite(customComponentConfig); <add> if(edOrgComponentConfig != null) { <add> if(customComponentConfig == null) { <add> customComponentConfig = edOrgComponentConfig; <add> } else { <add> //edOrgComponentConfig overwrites customComponentConfig <add> customComponentConfig = edOrgComponentConfig.overWrite(customComponentConfig); <add> } <ide> } <ide> } <ide> }
Java
epl-1.0
a11ab2dc658bf21003543e04a87354dda509a5d8
0
apribeiro/RSLingo4Privacy-Studio
package org.xtext.example.mydsl.ui.handlers; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.xtext.resource.XtextResource; import org.eclipse.xtext.resource.XtextResourceSet; import org.xtext.example.mydsl.MyDslStandaloneSetup; import org.xtext.example.mydsl.myDsl.Collection; import org.xtext.example.mydsl.myDsl.Disclosure; import org.xtext.example.mydsl.myDsl.Enforcement; import org.xtext.example.mydsl.myDsl.Informative; import org.xtext.example.mydsl.myDsl.Policy; import org.xtext.example.mydsl.myDsl.PrivateData; import org.xtext.example.mydsl.myDsl.Recipient; import org.xtext.example.mydsl.myDsl.Retention; import org.xtext.example.mydsl.myDsl.Service; import org.xtext.example.mydsl.myDsl.Usage; import org.xtext.example.mydsl.ui.windows.MenuCommand; import org.xtext.example.mydsl.ui.windows.MenuCommandWindow; import com.google.inject.Injector; public class ExportExcelHandler extends AbstractHandler { private static final String GEN_FOLDER = "src-gen"; private static final String DOCS_FOLDER = "docs"; private static final String FILE_EXT = ".mydsl"; private static final String DEF_WORD_PATH = "RSL-IL4Privacy-ExcelTemplate.xlsx"; private final String PLUGIN_PATH = Platform.getInstallLocation() .getURL().getPath().substring(1) + "plugins/RSLingo4Privacy/"; @Override public Object execute(ExecutionEvent event) throws ExecutionException { ISelection selection = HandlerUtil.getActiveMenuSelection(event); // Check if the command was triggered using the ContextMenu if (selection != null) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; IFile file = (IFile) structuredSelection.getFirstElement(); generateExcel(file); } else { IWorkbenchWindow workbenchWindow = HandlerUtil.getActiveWorkbenchWindowChecked(event); MenuCommand cmd = new MenuCommand() { @Override public void execute(IProject project, IFile file) { generateExcel(file); } }; MenuCommandWindow window = new MenuCommandWindow(workbenchWindow.getShell(), cmd, false, FILE_EXT); window.open(); } return null; } private void generateExcel(IFile file) { IProject project = file.getProject(); IFolder srcGenFolder = project.getFolder(GEN_FOLDER); try { if (!srcGenFolder.exists()) { srcGenFolder.create(true, true, new NullProgressMonitor()); } IFolder docsFolder = srcGenFolder.getFolder(DOCS_FOLDER); if (!docsFolder.exists()) { docsFolder.create(true, true, new NullProgressMonitor()); } } catch (Exception e) { e.printStackTrace(); } // Start a new Thread to avoid blocking the UI Runnable runnable = new Runnable() { @Override public void run() { new org.eclipse.emf.mwe.utils.StandaloneSetup().setPlatformUri("../"); Injector injector = new MyDslStandaloneSetup().createInjectorAndDoEMFRegistration(); XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class); resourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE); Resource resource = resourceSet.getResource( URI.createURI("platform:/resource/" + file.getFullPath().toString()), true); //URI.createURI("platform:/resource/org.xtext.example.mydsl/src/example.mydsl"), true); Policy policy = (Policy) resource.getContents().get(0); try { InputStream from = new FileInputStream(PLUGIN_PATH + DEF_WORD_PATH); XSSFWorkbook workbook = new XSSFWorkbook(from); writeStatements(policy, workbook); writePrivateData(policy, workbook); writeServices(policy, workbook); writeRecipients(policy, workbook); writeEnforcements(policy, workbook); // Write the Document in file system File to = new File(project.getLocation().toOSString() + "/" + GEN_FOLDER + "/" + DOCS_FOLDER + "/" + file.getName() + ".xlsx"); FileOutputStream out = new FileOutputStream(to); workbook.write(out); out.close(); workbook.close(); project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); System.out.println(file.getName() + ".xlsx generated!"); } catch (Exception e) { e.printStackTrace(); } } }; new Thread(runnable).start(); } private void writeStatements(Policy policy, XSSFWorkbook workbook) { writeCollectionStatements(policy, workbook); writeDisclosureStatements(policy, workbook); writeRetentionStatements(policy, workbook); writeUsageStatements(policy, workbook); writeInformativeStatements(policy, workbook); // Delete Template Row XSSFSheet sheet = workbook.getSheet("Statements"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "StId").getRow(); // int lastRowNum = sheet.getLastRowNum(); // int tRowNum = tRow.getRowNum(); // // if (tRowNum >= 0 && tRowNum < lastRowNum) { // sheet.shiftRows(tRowNum + 1, lastRowNum, 1, true, true); // } sheet.removeRow(tRow); } private void writeCollectionStatements(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Statements"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "StId").getRow(); for (Collection collection : policy.getCollection()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "StId", collection.getName()); DocumentHelper.replaceText(nRow, "StDescription", collection.getDescription()); DocumentHelper.replaceText(nRow, "StCondition", collection.getCondition()); String modality = collection.getModalitykind().toLowerCase(); DocumentHelper.replaceText(nRow, "StModality", modality); DocumentHelper.replaceText(nRow, "StType", "Collection"); if (collection.getRefprivatedata().size() > 0) { DocumentHelper.replaceText(nRow, "StPDId", "pdid"); } else { DocumentHelper.replaceText(nRow, "StPDId", ""); } DocumentHelper.replaceText(nRow, "StRId", ""); if (collection.getRefertoservice().size() > 0) { DocumentHelper.replaceText(nRow, "StSId", "sid"); } else { DocumentHelper.replaceText(nRow, "StSId", ""); } if (collection.getRefertoEnforcement().size() > 0) { DocumentHelper.replaceText(nRow, "StEId", "eid"); } else { DocumentHelper.replaceText(nRow, "StEId", ""); } DocumentHelper.replaceText(nRow, "StPeriod", ""); } } private void writeDisclosureStatements(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Statements"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "StId").getRow(); for (Disclosure disclosure : policy.getDisclosure()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "StId", disclosure.getName()); DocumentHelper.replaceText(nRow, "StDescription", disclosure.getDescription()); DocumentHelper.replaceText(nRow, "StCondition", disclosure.getCondition()); String modality = disclosure.getModalitykind().toLowerCase(); DocumentHelper.replaceText(nRow, "StModality", modality); DocumentHelper.replaceText(nRow, "StType", "Disclosure"); if (disclosure.getRefprivatedata().size() > 0) { DocumentHelper.replaceText(nRow, "StPDId", "pdid"); } else { DocumentHelper.replaceText(nRow, "StPDId", ""); } if (disclosure.getReferToRecipient().size() > 0) { DocumentHelper.replaceText(nRow, "StRId", "rid"); } else { DocumentHelper.replaceText(nRow, "StRId", ""); } if (disclosure.getRefertoservice().size() > 0) { DocumentHelper.replaceText(nRow, "StSId", "sid"); } else { DocumentHelper.replaceText(nRow, "StSId", ""); } if (disclosure.getRefertoEnforcement().size() > 0) { DocumentHelper.replaceText(nRow, "StEId", "eid"); } else { DocumentHelper.replaceText(nRow, "StEId", ""); } DocumentHelper.replaceText(nRow, "StPeriod", ""); } } private void writeRetentionStatements(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Statements"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "StId").getRow(); for (Retention retention : policy.getRetention()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "StId", retention.getName()); DocumentHelper.replaceText(nRow, "StDescription", retention.getDescription()); DocumentHelper.replaceText(nRow, "StCondition", retention.getCondition()); String modality = retention.getModalitykind().toLowerCase(); DocumentHelper.replaceText(nRow, "StModality", modality); DocumentHelper.replaceText(nRow, "StType", "Retention"); if (retention.getRefprivatedata().size() > 0) { DocumentHelper.replaceText(nRow, "StPDId", "pdid"); } else { DocumentHelper.replaceText(nRow, "StPDId", ""); } DocumentHelper.replaceText(nRow, "StRId", ""); if (retention.getRefertoservice().size() > 0) { DocumentHelper.replaceText(nRow, "StSId", "sid"); } else { DocumentHelper.replaceText(nRow, "StSId", ""); } if (retention.getRefertoEnforcement().size() > 0) { DocumentHelper.replaceText(nRow, "StEId", "eid"); } else { DocumentHelper.replaceText(nRow, "StEId", ""); } DocumentHelper.replaceText(nRow, "StPeriod", retention.getPeriod()); } } private void writeUsageStatements(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Statements"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "StId").getRow(); for (Usage usage : policy.getUsage()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "StId", usage.getName()); DocumentHelper.replaceText(nRow, "StDescription", usage.getDescription()); DocumentHelper.replaceText(nRow, "StCondition", usage.getCondition()); String modality = usage.getModalitykind().toLowerCase(); DocumentHelper.replaceText(nRow, "StModality", modality); DocumentHelper.replaceText(nRow, "StType", "Usage"); if (usage.getRefprivatedata().size() > 0) { DocumentHelper.replaceText(nRow, "StPDId", "pdid"); } else { DocumentHelper.replaceText(nRow, "StPDId", ""); } DocumentHelper.replaceText(nRow, "StRId", ""); if (usage.getRefertoservice().size() > 0) { DocumentHelper.replaceText(nRow, "StSId", "sid"); } else { DocumentHelper.replaceText(nRow, "StSId", ""); } if (usage.getRefertoEnforcement().size() > 0) { DocumentHelper.replaceText(nRow, "StEId", "eid"); } else { DocumentHelper.replaceText(nRow, "StEId", ""); } DocumentHelper.replaceText(nRow, "StPeriod", ""); } } private void writeInformativeStatements(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Statements"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "StId").getRow(); for (Informative informative : policy.getInformative()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "StId", informative.getName()); DocumentHelper.replaceText(nRow, "StDescription", informative.getDescription()); DocumentHelper.replaceText(nRow, "StCondition", informative.getCondition()); String modality = informative.getModalitykind().toLowerCase(); DocumentHelper.replaceText(nRow, "StModality", modality); DocumentHelper.replaceText(nRow, "StType", "Informative"); if (informative.getRefprivatedata().size() > 0) { DocumentHelper.replaceText(nRow, "StPDId", "pdid"); } else { DocumentHelper.replaceText(nRow, "StPDId", ""); } DocumentHelper.replaceText(nRow, "StRId", ""); if (informative.getRefertoservice().size() > 0) { DocumentHelper.replaceText(nRow, "StSId", "sid"); } else { DocumentHelper.replaceText(nRow, "StSId", ""); } if (informative.getRefertoEnforcement().size() > 0) { DocumentHelper.replaceText(nRow, "StEId", "eid"); } else { DocumentHelper.replaceText(nRow, "StEId", ""); } DocumentHelper.replaceText(nRow, "StPeriod", ""); } } private void writeRecipients(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Recipients"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "RId").getRow(); for (Recipient recipient : policy.getRecipient()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "RId", recipient.getName()); DocumentHelper.replaceText(nRow, "RDescription", recipient.getDescription()); String scope = recipient.getRecipientScopeKind().toLowerCase(); DocumentHelper.replaceText(nRow, "RScope", scope); String type = recipient.getRecipientTypeKind().toLowerCase(); DocumentHelper.replaceText(nRow, "RType", type); if (recipient.getPartof().size() > 0) { DocumentHelper.replaceText(nRow, "SRId", "rid"); } else { DocumentHelper.replaceText(nRow, "SRId", ""); } } // Delete Template Row sheet.removeRow(tRow); } private void writeServices(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Services"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "SId").getRow(); for (Service service : policy.getService()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "SId", service.getName()); DocumentHelper.replaceText(nRow, "SName", service.getServicename()); DocumentHelper.replaceText(nRow, "SDescription", service.getDescription()); if (service.getRefprivatedata().size() > 0) { DocumentHelper.replaceText(nRow, "SPDId", "pdid"); } else { DocumentHelper.replaceText(nRow, "SPDId", ""); } if (service.getServicepartof().size() > 0) { DocumentHelper.replaceText(nRow, "SSSId", "ssid"); } else { DocumentHelper.replaceText(nRow, "SSSId", ""); } } // Delete Template Row sheet.removeRow(tRow); } private void writePrivateData(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("PrivateData"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "PDId").getRow(); for (PrivateData privateData : policy.getPrivateData()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "PDId", privateData.getName()); // FIXME Separate Type words DocumentHelper.replaceText(nRow, "PDType", privateData.getPrivateDataKind()); DocumentHelper.replaceText(nRow, "PDDescription", privateData.getPrivatedata()); if (privateData.getAttribute().size() > 0) { DocumentHelper.replaceText(nRow, "PDAttributes", "attributes"); } else { DocumentHelper.replaceText(nRow, "PDAttributes", ""); } } // Delete Template Row sheet.removeRow(tRow); } private void writeEnforcements(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Enforcements"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "EId").getRow(); for (Enforcement enforcement : policy.getEnforcement()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "EId", enforcement.getName()); DocumentHelper.replaceText(nRow, "EName", enforcement.getEnforcementName()); DocumentHelper.replaceText(nRow, "EDescription", enforcement.getEnforcementDescription()); DocumentHelper.replaceText(nRow, "EType", enforcement.getEnforcementKind()); } // Delete Template Row sheet.removeRow(tRow); } }
org.xtext.example.mydsl.ui/src/org/xtext/example/mydsl/ui/handlers/ExportExcelHandler.java
package org.xtext.example.mydsl.ui.handlers; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.xtext.resource.XtextResource; import org.eclipse.xtext.resource.XtextResourceSet; import org.xtext.example.mydsl.MyDslStandaloneSetup; import org.xtext.example.mydsl.myDsl.Collection; import org.xtext.example.mydsl.myDsl.Disclosure; import org.xtext.example.mydsl.myDsl.Enforcement; import org.xtext.example.mydsl.myDsl.Informative; import org.xtext.example.mydsl.myDsl.Policy; import org.xtext.example.mydsl.myDsl.PrivateData; import org.xtext.example.mydsl.myDsl.Recipient; import org.xtext.example.mydsl.myDsl.Retention; import org.xtext.example.mydsl.myDsl.Service; import org.xtext.example.mydsl.myDsl.Usage; import org.xtext.example.mydsl.ui.windows.MenuCommand; import org.xtext.example.mydsl.ui.windows.MenuCommandWindow; import com.google.inject.Injector; public class ExportExcelHandler extends AbstractHandler { private static final String GEN_FOLDER = "src-gen"; private static final String DOCS_FOLDER = "docs"; private static final String FILE_EXT = ".mydsl"; private static final String DEF_WORD_PATH = "RSL-IL4Privacy-ExcelTemplate.xlsx"; private final String PLUGIN_PATH = Platform.getInstallLocation() .getURL().getPath().substring(1) + "plugins/RSLingo4Privacy/"; @Override public Object execute(ExecutionEvent event) throws ExecutionException { ISelection selection = HandlerUtil.getActiveMenuSelection(event); // Check if the command was triggered using the ContextMenu if (selection != null) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; IFile file = (IFile) structuredSelection.getFirstElement(); generateExcel(file); } else { IWorkbenchWindow workbenchWindow = HandlerUtil.getActiveWorkbenchWindowChecked(event); MenuCommand cmd = new MenuCommand() { @Override public void execute(IProject project, IFile file) { generateExcel(file); } }; MenuCommandWindow window = new MenuCommandWindow(workbenchWindow.getShell(), cmd, false, FILE_EXT); window.open(); } return null; } private void generateExcel(IFile file) { IProject project = file.getProject(); IFolder srcGenFolder = project.getFolder(GEN_FOLDER); try { if (!srcGenFolder.exists()) { srcGenFolder.create(true, true, new NullProgressMonitor()); } IFolder docsFolder = srcGenFolder.getFolder(DOCS_FOLDER); if (!docsFolder.exists()) { docsFolder.create(true, true, new NullProgressMonitor()); } } catch (Exception e) { e.printStackTrace(); } // Start a new Thread to avoid blocking the UI Runnable runnable = new Runnable() { @Override public void run() { new org.eclipse.emf.mwe.utils.StandaloneSetup().setPlatformUri("../"); Injector injector = new MyDslStandaloneSetup().createInjectorAndDoEMFRegistration(); XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class); resourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE); Resource resource = resourceSet.getResource( URI.createURI("platform:/resource/" + file.getFullPath().toString()), true); //URI.createURI("platform:/resource/org.xtext.example.mydsl/src/example.mydsl"), true); Policy policy = (Policy) resource.getContents().get(0); try { InputStream from = new FileInputStream(PLUGIN_PATH + DEF_WORD_PATH); XSSFWorkbook workbook = new XSSFWorkbook(from); writeStatements(policy, workbook); writePrivateData(policy, workbook); writeServices(policy, workbook); writeRecipients(policy, workbook); writeEnforcements(policy, workbook); // Write the Document in file system File to = new File(project.getLocation().toOSString() + "/" + GEN_FOLDER + "/" + DOCS_FOLDER + "/" + file.getName() + ".xlsx"); FileOutputStream out = new FileOutputStream(to); workbook.write(out); out.close(); workbook.close(); project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); System.out.println(file.getName() + ".xlsx generated!"); } catch (Exception e) { e.printStackTrace(); } } }; new Thread(runnable).start(); } private void writeStatements(Policy policy, XSSFWorkbook workbook) { writeCollectionStatements(policy, workbook); writeDisclosureStatements(policy, workbook); writeRetentionStatements(policy, workbook); writeUsageStatements(policy, workbook); writeInformativeStatements(policy, workbook); // Delete Template Row // XSSFSheet sheet = workbook.getSheet("Statements"); // XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "StId").getRow(); // int lastRowNum = sheet.getLastRowNum(); // int tRowNum = tRow.getRowNum(); // // if (tRowNum >= 0 && tRowNum < lastRowNum) { // sheet.shiftRows(tRowNum + 1, lastRowNum, 1, true, true); // } // sheet.removeRow(tRow); } private void writeCollectionStatements(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Statements"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "StId").getRow(); for (Collection collection : policy.getCollection()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "StId", collection.getName()); DocumentHelper.replaceText(nRow, "StDescription", collection.getDescription()); DocumentHelper.replaceText(nRow, "StCondition", collection.getCondition()); String modality = collection.getModalitykind().toLowerCase(); DocumentHelper.replaceText(nRow, "StModality", modality); DocumentHelper.replaceText(nRow, "StType", "Collection"); if (collection.getRefprivatedata().size() > 0) { DocumentHelper.replaceText(nRow, "StPDId", "pdid"); } else { DocumentHelper.replaceText(nRow, "StPDId", ""); } DocumentHelper.replaceText(nRow, "StRId", ""); if (collection.getRefertoservice().size() > 0) { DocumentHelper.replaceText(nRow, "StSId", "sid"); } else { DocumentHelper.replaceText(nRow, "StSId", ""); } if (collection.getRefertoEnforcement().size() > 0) { DocumentHelper.replaceText(nRow, "StEId", "eid"); } else { DocumentHelper.replaceText(nRow, "StEId", ""); } DocumentHelper.replaceText(nRow, "StPeriod", ""); } } private void writeDisclosureStatements(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Statements"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "StId").getRow(); for (Disclosure disclosure : policy.getDisclosure()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "StId", disclosure.getName()); DocumentHelper.replaceText(nRow, "StDescription", disclosure.getDescription()); DocumentHelper.replaceText(nRow, "StCondition", disclosure.getCondition()); String modality = disclosure.getModalitykind().toLowerCase(); DocumentHelper.replaceText(nRow, "StModality", modality); DocumentHelper.replaceText(nRow, "StType", "Disclosure"); if (disclosure.getRefprivatedata().size() > 0) { DocumentHelper.replaceText(nRow, "StPDId", "pdid"); } else { DocumentHelper.replaceText(nRow, "StPDId", ""); } if (disclosure.getReferToRecipient().size() > 0) { DocumentHelper.replaceText(nRow, "StRId", "rid"); } else { DocumentHelper.replaceText(nRow, "StRId", ""); } if (disclosure.getRefertoservice().size() > 0) { DocumentHelper.replaceText(nRow, "StSId", "sid"); } else { DocumentHelper.replaceText(nRow, "StSId", ""); } if (disclosure.getRefertoEnforcement().size() > 0) { DocumentHelper.replaceText(nRow, "StEId", "eid"); } else { DocumentHelper.replaceText(nRow, "StEId", ""); } DocumentHelper.replaceText(nRow, "StPeriod", ""); } } private void writeRetentionStatements(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Statements"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "StId").getRow(); for (Retention retention : policy.getRetention()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "StId", retention.getName()); DocumentHelper.replaceText(nRow, "StDescription", retention.getDescription()); DocumentHelper.replaceText(nRow, "StCondition", retention.getCondition()); String modality = retention.getModalitykind().toLowerCase(); DocumentHelper.replaceText(nRow, "StModality", modality); DocumentHelper.replaceText(nRow, "StType", "Retention"); if (retention.getRefprivatedata().size() > 0) { DocumentHelper.replaceText(nRow, "StPDId", "pdid"); } else { DocumentHelper.replaceText(nRow, "StPDId", ""); } DocumentHelper.replaceText(nRow, "StRId", ""); if (retention.getRefertoservice().size() > 0) { DocumentHelper.replaceText(nRow, "StSId", "sid"); } else { DocumentHelper.replaceText(nRow, "StSId", ""); } if (retention.getRefertoEnforcement().size() > 0) { DocumentHelper.replaceText(nRow, "StEId", "eid"); } else { DocumentHelper.replaceText(nRow, "StEId", ""); } DocumentHelper.replaceText(nRow, "StPeriod", retention.getPeriod()); } } private void writeUsageStatements(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Statements"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "StId").getRow(); for (Usage usage : policy.getUsage()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "StId", usage.getName()); DocumentHelper.replaceText(nRow, "StDescription", usage.getDescription()); DocumentHelper.replaceText(nRow, "StCondition", usage.getCondition()); String modality = usage.getModalitykind().toLowerCase(); DocumentHelper.replaceText(nRow, "StModality", modality); DocumentHelper.replaceText(nRow, "StType", "Usage"); if (usage.getRefprivatedata().size() > 0) { DocumentHelper.replaceText(nRow, "StPDId", "pdid"); } else { DocumentHelper.replaceText(nRow, "StPDId", ""); } DocumentHelper.replaceText(nRow, "StRId", ""); if (usage.getRefertoservice().size() > 0) { DocumentHelper.replaceText(nRow, "StSId", "sid"); } else { DocumentHelper.replaceText(nRow, "StSId", ""); } if (usage.getRefertoEnforcement().size() > 0) { DocumentHelper.replaceText(nRow, "StEId", "eid"); } else { DocumentHelper.replaceText(nRow, "StEId", ""); } DocumentHelper.replaceText(nRow, "StPeriod", ""); } } private void writeInformativeStatements(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Statements"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "StId").getRow(); for (Informative informative : policy.getInformative()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "StId", informative.getName()); DocumentHelper.replaceText(nRow, "StDescription", informative.getDescription()); DocumentHelper.replaceText(nRow, "StCondition", informative.getCondition()); String modality = informative.getModalitykind().toLowerCase(); DocumentHelper.replaceText(nRow, "StModality", modality); DocumentHelper.replaceText(nRow, "StType", "Informative"); if (informative.getRefprivatedata().size() > 0) { DocumentHelper.replaceText(nRow, "StPDId", "pdid"); } else { DocumentHelper.replaceText(nRow, "StPDId", ""); } DocumentHelper.replaceText(nRow, "StRId", ""); if (informative.getRefertoservice().size() > 0) { DocumentHelper.replaceText(nRow, "StSId", "sid"); } else { DocumentHelper.replaceText(nRow, "StSId", ""); } if (informative.getRefertoEnforcement().size() > 0) { DocumentHelper.replaceText(nRow, "StEId", "eid"); } else { DocumentHelper.replaceText(nRow, "StEId", ""); } DocumentHelper.replaceText(nRow, "StPeriod", ""); } } private void writeRecipients(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Recipients"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "RId").getRow(); for (Recipient recipient : policy.getRecipient()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "RId", recipient.getName()); DocumentHelper.replaceText(nRow, "RDescription", recipient.getDescription()); String scope = recipient.getRecipientScopeKind().toLowerCase(); DocumentHelper.replaceText(nRow, "RScope", scope); String type = recipient.getRecipientTypeKind().toLowerCase(); DocumentHelper.replaceText(nRow, "RType", type); if (recipient.getPartof().size() > 0) { DocumentHelper.replaceText(nRow, "SRId", "rid"); } else { DocumentHelper.replaceText(nRow, "SRId", ""); } } } private void writeServices(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Services"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "SId").getRow(); for (Service service : policy.getService()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "SId", service.getName()); DocumentHelper.replaceText(nRow, "SName", service.getServicename()); DocumentHelper.replaceText(nRow, "SDescription", service.getDescription()); if (service.getRefprivatedata().size() > 0) { DocumentHelper.replaceText(nRow, "SPDId", "pdid"); } else { DocumentHelper.replaceText(nRow, "SPDId", ""); } if (service.getServicepartof().size() > 0) { DocumentHelper.replaceText(nRow, "SSSId", "ssid"); } else { DocumentHelper.replaceText(nRow, "SSSId", ""); } } } private void writePrivateData(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("PrivateData"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "PDId").getRow(); for (PrivateData privateData : policy.getPrivateData()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "PDId", privateData.getName()); // FIXME Separate Type words DocumentHelper.replaceText(nRow, "PDType", privateData.getPrivateDataKind()); DocumentHelper.replaceText(nRow, "PDDescription", privateData.getPrivatedata()); if (privateData.getAttribute().size() > 0) { DocumentHelper.replaceText(nRow, "PDAttributes", "attributes"); } else { DocumentHelper.replaceText(nRow, "PDAttributes", ""); } } } private void writeEnforcements(Policy policy, XSSFWorkbook workbook) { XSSFSheet sheet = workbook.getSheet("Enforcements"); XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "EId").getRow(); for (Enforcement enforcement : policy.getEnforcement()) { XSSFRow nRow = sheet.createRow(sheet.getLastRowNum() + 1); DocumentHelper.cloneRow(workbook, sheet, nRow, tRow); DocumentHelper.replaceText(nRow, "EId", enforcement.getName()); DocumentHelper.replaceText(nRow, "EName", enforcement.getEnforcementName()); DocumentHelper.replaceText(nRow, "EDescription", enforcement.getEnforcementDescription()); DocumentHelper.replaceText(nRow, "EType", enforcement.getEnforcementKind()); } } }
Delete template row after generation
org.xtext.example.mydsl.ui/src/org/xtext/example/mydsl/ui/handlers/ExportExcelHandler.java
Delete template row after generation
<ide><path>rg.xtext.example.mydsl.ui/src/org/xtext/example/mydsl/ui/handlers/ExportExcelHandler.java <ide> writeInformativeStatements(policy, workbook); <ide> <ide> // Delete Template Row <del>// XSSFSheet sheet = workbook.getSheet("Statements"); <del>// XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "StId").getRow(); <add> XSSFSheet sheet = workbook.getSheet("Statements"); <add> XSSFRow tRow = (XSSFRow) DocumentHelper.getCell(sheet, "StId").getRow(); <ide> // int lastRowNum = sheet.getLastRowNum(); <ide> // int tRowNum = tRow.getRowNum(); <ide> // <ide> // sheet.shiftRows(tRowNum + 1, lastRowNum, 1, true, true); <ide> // } <ide> <del>// sheet.removeRow(tRow); <add> sheet.removeRow(tRow); <ide> } <ide> <ide> private void writeCollectionStatements(Policy policy, XSSFWorkbook workbook) { <ide> DocumentHelper.replaceText(nRow, "SRId", ""); <ide> } <ide> } <add> <add> // Delete Template Row <add> sheet.removeRow(tRow); <ide> } <ide> <ide> private void writeServices(Policy policy, XSSFWorkbook workbook) { <ide> DocumentHelper.replaceText(nRow, "SSSId", ""); <ide> } <ide> } <add> <add> // Delete Template Row <add> sheet.removeRow(tRow); <ide> } <ide> <ide> private void writePrivateData(Policy policy, XSSFWorkbook workbook) { <ide> DocumentHelper.replaceText(nRow, "PDAttributes", ""); <ide> } <ide> } <add> <add> // Delete Template Row <add> sheet.removeRow(tRow); <ide> } <ide> <ide> private void writeEnforcements(Policy policy, XSSFWorkbook workbook) { <ide> DocumentHelper.replaceText(nRow, "EDescription", enforcement.getEnforcementDescription()); <ide> DocumentHelper.replaceText(nRow, "EType", enforcement.getEnforcementKind()); <ide> } <add> <add> // Delete Template Row <add> sheet.removeRow(tRow); <ide> } <ide> }
Java
mit
error: pathspec 'src/test/java/com/github/abel533/echarts/util/CommentsUtil.java' did not match any file(s) known to git
42c1ecf3ad3080fe0465f7411994a089f1966c20
1
abel533/ECharts,twentwo/ECharts,twentwo/ECharts,abel533/ECharts,ntvis/ECharts,Pluto-Y/ECharts,huhekai/ECharts,Pluto-Y/ECharts,ntvis/ECharts,huhekai/ECharts
/* * The MIT License (MIT) * * Copyright (c) 2014 [email protected] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.abel533.echarts.util; import java.io.*; import java.util.ArrayList; import java.util.List; /** * 自动生成链式调用方法 - 仅针对本项目之前的代码 * * @author liuzh */ public class CommentsUtil { public static final String[] EMPTY = new String[0]; public static void main(String[] args) { // System.out.println(getMethodFieldName("public Boolean getShow() {")); //System.out.println();// //输出全部类 // String srcPath = getSrcPath(); // File srcFoler = new File(srcPath); // List<File> all = allFiles(srcFoler); // for (File file : all) { // chainFile(file); // } commentsFile(new File("D:\\IdeaProjects\\GitHub\\ECharts\\src\\main\\java\\com\\github\\abel533\\echarts\\Tooltip.java")); } public static void commentsFile(File file) { BufferedReader reader = null; StringBuffer sb = new StringBuffer(); try { reader = new BufferedReader(new FileReader(file)); String line = null; String className = file.getName(); className = className.substring(0, className.lastIndexOf(".")); String prevLine = null; while ((line = reader.readLine()) != null) { String tempLline = line; if (tempLline.contains("private") || tempLline.contains("public") || tempLline.contains("protected")) { if (prevLine == null || !prevLine.contains("*")) { if (tempLline.contains("(") && tempLline.contains(")")) { //分解参数 tempLline = tempLline.trim(); String[] ps = getParameter(tempLline); if (ps == EMPTY) { sb.append("\t/**\n\t * 获取"+getMethodFieldName(tempLline)+"值 \n"); } else { for (String s : ps) { sb.append("\t/**\n\t * 设置" + s + "值 \n\t * \n"); sb.append("\t * @param " + s + "\n"); } } sb.append("\t */\n"); tempLline = "\t" + tempLline; } } } sb.append(tempLline + "\n"); prevLine = tempLline; } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(file)); writer.write(sb.toString()); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static String getMethodFieldName(String line) { int end = line.lastIndexOf("("); int start = line.lastIndexOf(" ", end); String name = line.substring(start + 1, end); if (name.startsWith("get")) { name = name.substring(3); name = name.substring(0, 1).toLowerCase() + name.substring(1); } return name; } public static String[] getParameter(String line) { if (line.contains("(") && line.contains(")")) { //分解参数 String all = line.substring(line.indexOf("(") + 1, line.lastIndexOf(")")); if (all.equals("")) { return EMPTY; } String[] alls = all.split(","); String[] parameters = new String[alls.length]; for (int i = 0; i < alls.length; i++) { parameters[i] = alls[i].split(" ")[1].trim(); } return parameters; } return EMPTY; } public static List<File> allFiles(File file) { List<File> result = new ArrayList<File>(); if (file.isFile()) { result.add(file); } else if (file.isDirectory()) { File[] files = file.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (dir.isDirectory()) { return true; } else if (name.toUpperCase().endsWith(".JAVA")) { return true; } return false; } }); for (File f : files) { result.addAll(allFiles(f)); } } return result; } public static String getSrcPath() { String basePath = getBasePath(); return basePath + "src/main/java"; } public static String getBasePath() { String path = CommentsUtil.class.getResource("/").getPath(); if (path.startsWith("/")) { path = path.substring(1); } if (path.indexOf("target1") > 0) { path = path.substring(0, path.indexOf("target")); } else if (path.indexOf("ECharts") > 0) { path = path.substring(0, path.indexOf("ECharts")) + "Echarts/"; } return path; } }
src/test/java/com/github/abel533/echarts/util/CommentsUtil.java
增加了一个针对当前项目自动生成注释的工具类。
src/test/java/com/github/abel533/echarts/util/CommentsUtil.java
增加了一个针对当前项目自动生成注释的工具类。
<ide><path>rc/test/java/com/github/abel533/echarts/util/CommentsUtil.java <add>/* <add> * The MIT License (MIT) <add> * <add> * Copyright (c) 2014 [email protected] <add> * <add> * Permission is hereby granted, free of charge, to any person obtaining a copy <add> * of this software and associated documentation files (the "Software"), to deal <add> * in the Software without restriction, including without limitation the rights <add> * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell <add> * copies of the Software, and to permit persons to whom the Software is <add> * furnished to do so, subject to the following conditions: <add> * <add> * The above copyright notice and this permission notice shall be included in <add> * all copies or substantial portions of the Software. <add> * <add> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR <add> * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, <add> * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE <add> * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER <add> * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, <add> * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <add> * THE SOFTWARE. <add> */ <add> <add>package com.github.abel533.echarts.util; <add> <add>import java.io.*; <add>import java.util.ArrayList; <add>import java.util.List; <add> <add>/** <add> * 自动生成链式调用方法 - 仅针对本项目之前的代码 <add> * <add> * @author liuzh <add> */ <add>public class CommentsUtil { <add> public static final String[] EMPTY = new String[0]; <add> <add> public static void main(String[] args) { <add>// System.out.println(getMethodFieldName("public Boolean getShow() {")); <add> //System.out.println();// <add> //输出全部类 <add>// String srcPath = getSrcPath(); <add>// File srcFoler = new File(srcPath); <add>// List<File> all = allFiles(srcFoler); <add>// for (File file : all) { <add>// chainFile(file); <add>// } <add> commentsFile(new File("D:\\IdeaProjects\\GitHub\\ECharts\\src\\main\\java\\com\\github\\abel533\\echarts\\Tooltip.java")); <add> } <add> <add> public static void commentsFile(File file) { <add> BufferedReader reader = null; <add> StringBuffer sb = new StringBuffer(); <add> try { <add> reader = new BufferedReader(new FileReader(file)); <add> String line = null; <add> String className = file.getName(); <add> className = className.substring(0, className.lastIndexOf(".")); <add> String prevLine = null; <add> while ((line = reader.readLine()) != null) { <add> String tempLline = line; <add> if (tempLline.contains("private") || tempLline.contains("public") || tempLline.contains("protected")) { <add> if (prevLine == null || !prevLine.contains("*")) { <add> if (tempLline.contains("(") && tempLline.contains(")")) { <add> //分解参数 <add> tempLline = tempLline.trim(); <add> String[] ps = getParameter(tempLline); <add> if (ps == EMPTY) { <add> sb.append("\t/**\n\t * 获取"+getMethodFieldName(tempLline)+"值 \n"); <add> } else { <add> for (String s : ps) { <add> sb.append("\t/**\n\t * 设置" + s + "值 \n\t * \n"); <add> sb.append("\t * @param " + s + "\n"); <add> } <add> } <add> sb.append("\t */\n"); <add> tempLline = "\t" + tempLline; <add> } <add> } <add> } <add> sb.append(tempLline + "\n"); <add> prevLine = tempLline; <add> } <add> } catch (Exception e) { <add> e.printStackTrace(); <add> } finally { <add> if (reader != null) { <add> try { <add> reader.close(); <add> } catch (IOException e) { <add> e.printStackTrace(); <add> } <add> } <add> } <add> BufferedWriter writer = null; <add> try { <add> writer = new BufferedWriter(new FileWriter(file)); <add> writer.write(sb.toString()); <add> } catch (Exception e) { <add> e.printStackTrace(); <add> } finally { <add> if (writer != null) { <add> try { <add> writer.close(); <add> } catch (IOException e) { <add> e.printStackTrace(); <add> } <add> } <add> } <add> } <add> <add> public static String getMethodFieldName(String line) { <add> int end = line.lastIndexOf("("); <add> int start = line.lastIndexOf(" ", end); <add> String name = line.substring(start + 1, end); <add> if (name.startsWith("get")) { <add> name = name.substring(3); <add> name = name.substring(0, 1).toLowerCase() + name.substring(1); <add> } <add> return name; <add> } <add> <add> public static String[] getParameter(String line) { <add> if (line.contains("(") && line.contains(")")) { <add> //分解参数 <add> String all = line.substring(line.indexOf("(") + 1, line.lastIndexOf(")")); <add> if (all.equals("")) { <add> return EMPTY; <add> } <add> String[] alls = all.split(","); <add> String[] parameters = new String[alls.length]; <add> for (int i = 0; i < alls.length; i++) { <add> parameters[i] = alls[i].split(" ")[1].trim(); <add> } <add> return parameters; <add> } <add> return EMPTY; <add> } <add> <add> public static List<File> allFiles(File file) { <add> List<File> result = new ArrayList<File>(); <add> if (file.isFile()) { <add> result.add(file); <add> } else if (file.isDirectory()) { <add> File[] files = file.listFiles(new FilenameFilter() { <add> @Override <add> public boolean accept(File dir, String name) { <add> if (dir.isDirectory()) { <add> return true; <add> } else if (name.toUpperCase().endsWith(".JAVA")) { <add> return true; <add> } <add> return false; <add> } <add> }); <add> for (File f : files) { <add> result.addAll(allFiles(f)); <add> } <add> } <add> return result; <add> } <add> <add> public static String getSrcPath() { <add> String basePath = getBasePath(); <add> return basePath + "src/main/java"; <add> } <add> <add> public static String getBasePath() { <add> String path = CommentsUtil.class.getResource("/").getPath(); <add> if (path.startsWith("/")) { <add> path = path.substring(1); <add> } <add> if (path.indexOf("target1") > 0) { <add> path = path.substring(0, path.indexOf("target")); <add> } else if (path.indexOf("ECharts") > 0) { <add> path = path.substring(0, path.indexOf("ECharts")) + "Echarts/"; <add> } <add> return path; <add> } <add>}
Java
apache-2.0
45f12a1c22c4424ed713b29307fe477b385db13f
0
timlevett/uPortal,ChristianMurphy/uPortal,Jasig/SSP-Platform,doodelicious/uPortal,ASU-Capstone/uPortal,andrewstuart/uPortal,chasegawa/uPortal,chasegawa/uPortal,stalele/uPortal,MichaelVose2/uPortal,MichaelVose2/uPortal,jl1955/uPortal5,kole9273/uPortal,GIP-RECIA/esup-uportal,pspaude/uPortal,jameswennmacher/uPortal,ASU-Capstone/uPortal-Forked,MichaelVose2/uPortal,Jasig/uPortal-start,jhelmer-unicon/uPortal,doodelicious/uPortal,GIP-RECIA/esco-portail,doodelicious/uPortal,andrewstuart/uPortal,bjagg/uPortal,jameswennmacher/uPortal,Jasig/SSP-Platform,Jasig/SSP-Platform,EdiaEducationTechnology/uPortal,jl1955/uPortal5,bjagg/uPortal,jhelmer-unicon/uPortal,MichaelVose2/uPortal,ASU-Capstone/uPortal,stalele/uPortal,vbonamy/esup-uportal,joansmith/uPortal,GIP-RECIA/esup-uportal,vertein/uPortal,apetro/uPortal,andrewstuart/uPortal,chasegawa/uPortal,GIP-RECIA/esco-portail,chasegawa/uPortal,jl1955/uPortal5,groybal/uPortal,apetro/uPortal,kole9273/uPortal,drewwills/uPortal,drewwills/uPortal,groybal/uPortal,cousquer/uPortal,jl1955/uPortal5,timlevett/uPortal,stalele/uPortal,pspaude/uPortal,apetro/uPortal,EsupPortail/esup-uportal,vbonamy/esup-uportal,EsupPortail/esup-uportal,kole9273/uPortal,andrewstuart/uPortal,phillips1021/uPortal,jonathanmtran/uPortal,Jasig/uPortal,vbonamy/esup-uportal,MichaelVose2/uPortal,Mines-Albi/esup-uportal,jl1955/uPortal5,timlevett/uPortal,groybal/uPortal,jhelmer-unicon/uPortal,jonathanmtran/uPortal,andrewstuart/uPortal,Mines-Albi/esup-uportal,ASU-Capstone/uPortal,jhelmer-unicon/uPortal,phillips1021/uPortal,drewwills/uPortal,Jasig/SSP-Platform,bjagg/uPortal,apetro/uPortal,pspaude/uPortal,joansmith/uPortal,jhelmer-unicon/uPortal,Mines-Albi/esup-uportal,EdiaEducationTechnology/uPortal,Jasig/SSP-Platform,chasegawa/uPortal,ASU-Capstone/uPortal,pspaude/uPortal,GIP-RECIA/esup-uportal,apetro/uPortal,EsupPortail/esup-uportal,jameswennmacher/uPortal,jameswennmacher/uPortal,vertein/uPortal,cousquer/uPortal,Mines-Albi/esup-uportal,groybal/uPortal,jonathanmtran/uPortal,ASU-Capstone/uPortal-Forked,ChristianMurphy/uPortal,EdiaEducationTechnology/uPortal,stalele/uPortal,ASU-Capstone/uPortal,joansmith/uPortal,joansmith/uPortal,Mines-Albi/esup-uportal,vertein/uPortal,phillips1021/uPortal,kole9273/uPortal,ASU-Capstone/uPortal-Forked,GIP-RECIA/esup-uportal,vertein/uPortal,EsupPortail/esup-uportal,phillips1021/uPortal,groybal/uPortal,drewwills/uPortal,vbonamy/esup-uportal,kole9273/uPortal,ASU-Capstone/uPortal-Forked,vbonamy/esup-uportal,GIP-RECIA/esup-uportal,mgillian/uPortal,doodelicious/uPortal,joansmith/uPortal,mgillian/uPortal,EsupPortail/esup-uportal,phillips1021/uPortal,Jasig/uPortal,Jasig/uPortal,mgillian/uPortal,doodelicious/uPortal,cousquer/uPortal,ChristianMurphy/uPortal,timlevett/uPortal,stalele/uPortal,jameswennmacher/uPortal,ASU-Capstone/uPortal-Forked,Jasig/uPortal-start,EdiaEducationTechnology/uPortal,GIP-RECIA/esco-portail
/** * Copyright 2004 The JA-SIG Collaborative. 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. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the JA-SIG Collaborative * (http://www.jasig.org/)." * * THIS SOFTWARE IS PROVIDED BY THE JA-SIG COLLABORATIVE "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 JA-SIG COLLABORATIVE 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. * */ package org.jasig.portal.container.services.information; import java.util.Properties; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; import org.apache.pluto.services.information.DynamicInformationProvider; import org.apache.pluto.services.information.InformationProviderService; import org.apache.pluto.services.information.StaticInformationProvider; import org.jasig.portal.container.services.PortletContainerService; /** * Implementation of Apache Pluto InformationProviderService. * @author Ken Weiner, [email protected] * @version $Revision$ */ public class InformationProviderServiceImpl implements PortletContainerService, InformationProviderService { private ServletConfig servletConfig = null; private Properties properties = null; private static StaticInformationProvider staticInfoProvider = null; private static final String dynamicInformationProviderRequestParameterName = "org.apache.pluto.services.information.DynamicInformationProvider"; // PortletContainerService methods public void init(ServletConfig servletConfig, Properties properties) throws Exception { this.servletConfig = servletConfig; this.properties = properties; staticInfoProvider = new StaticInformationProviderImpl(); ((StaticInformationProviderImpl)staticInfoProvider).init(servletConfig, properties); } public void destroy() throws Exception { properties = null; servletConfig = null; staticInfoProvider = null; } // InformationProviderService methods public StaticInformationProvider getStaticProvider() { return staticInfoProvider; } public DynamicInformationProvider getDynamicProvider(HttpServletRequest request) { DynamicInformationProvider provider = (DynamicInformationProvider)request.getAttribute(dynamicInformationProviderRequestParameterName); if (provider == null) { provider = new DynamicInformationProviderImpl(request,servletConfig); request.setAttribute(dynamicInformationProviderRequestParameterName, provider); } return provider; } }
source/org/jasig/portal/container/services/information/InformationProviderServiceImpl.java
/** * Copyright 2004 The JA-SIG Collaborative. 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. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the JA-SIG Collaborative * (http://www.jasig.org/)." * * THIS SOFTWARE IS PROVIDED BY THE JA-SIG COLLABORATIVE "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 JA-SIG COLLABORATIVE 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. * */ package org.jasig.portal.container.services.information; import java.util.Properties; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; import org.apache.pluto.services.information.DynamicInformationProvider; import org.apache.pluto.services.information.InformationProviderService; import org.apache.pluto.services.information.StaticInformationProvider; import org.jasig.portal.container.services.PortletContainerService; /** * Implementation of Apache Pluto InformationProviderService. * @author Ken Weiner, [email protected] * @version $Revision$ */ public class InformationProviderServiceImpl implements PortletContainerService, InformationProviderService { private ServletConfig servletConfig = null; private Properties properties = null; private static StaticInformationProvider staticInfoProvider = null; private static final String dynamicInformationProviderRequestParameterName = "org.apache.pluto.services.information.DynamicInformationProvider"; // PortletContainerService methods public void init(ServletConfig servletConfig, Properties properties) throws Exception { this.servletConfig = servletConfig; this.properties = properties; staticInfoProvider = new StaticInformationProviderImpl(); } public void destroy() throws Exception { properties = null; servletConfig = null; staticInfoProvider = null; } // InformationProviderService methods public StaticInformationProvider getStaticProvider() { return staticInfoProvider; } public DynamicInformationProvider getDynamicProvider(HttpServletRequest request) { DynamicInformationProvider provider = (DynamicInformationProvider)request.getAttribute(dynamicInformationProviderRequestParameterName); if (provider == null) { provider = new DynamicInformationProviderImpl(request,servletConfig); request.setAttribute(dynamicInformationProviderRequestParameterName, provider); } return provider; } }
Added code to initialize the static information provider implementation. git-svn-id: 477788cc2a8229a747c5b8073e47c1d0f6ec0604@8267 f5dbab47-78f9-eb45-b975-e544023573eb
source/org/jasig/portal/container/services/information/InformationProviderServiceImpl.java
Added code to initialize the static information provider implementation.
<ide><path>ource/org/jasig/portal/container/services/information/InformationProviderServiceImpl.java <ide> public void init(ServletConfig servletConfig, Properties properties) throws Exception { <ide> this.servletConfig = servletConfig; <ide> this.properties = properties; <del> staticInfoProvider = new StaticInformationProviderImpl(); <add> staticInfoProvider = new StaticInformationProviderImpl(); <add> ((StaticInformationProviderImpl)staticInfoProvider).init(servletConfig, properties); <ide> } <ide> <ide> public void destroy() throws Exception {
JavaScript
mit
a826b3f7f652be8c87c5db50bb6e73b514ebd067
0
michurin/chrome-extension-radio-paradise,michurin/chrome-extension-radio-paradise
/* * Radio Paradise player * Copyright (c) 2014 Alexey Michurin <[email protected]> * MIT License [http://www.opensource.org/licenses/mit-license.php] */ /*global window, chrome */ /*global storage */ 'use strict'; (function () { var bugreport_element = window.document.getElementById('bugreport'); var root_element = window.document.getElementById('bugreport-body'); bugreport_element.onclick = function () { root_element.style.display = 'block'; root_element.innerText = ''; storage.get(null, function (stor) { window.dom_keeper.get_all(function (cache) { root_element.innerText = 'Contributions and bug reports are welcome from anyone!\n' + 'Please attach this summary to your bug report.\n\n' + JSON.stringify({ ext_version: chrome.app.getDetails().version, user_agent: window.navigator.userAgent, storage: stor, runtime: { now: (new Date()).toUTCString(), last_error: (chrome.runtime.lastError || '-'), id: chrome.runtime.id, manifest: chrome.runtime.getManifest() }, cache: cache }, function(k, v) { var r; if (typeof v === 'undefined') { return 'undefined value'; } if (v.nodeType) { if (v.nodeType === 1) { r = {tag: v.tagName}; if (v.attributes.length > 0) { r.attributes = {}; Array.prototype.slice.call(v.attributes, 0).forEach(function (v) { r.attributes[v.name] = v.value; }); } if (v.childNodes.length > 0) { if (v.childNodes.length === 1) { r.child = v.childNodes[0]; } else { r.childs = Array.prototype.slice.call(v.childNodes, 0); } } return r; } else if (v.nodeType === 3) { return v.textContent; } else { return 'nodeType=' + v.nodeType; } } return v; }, 2) + '\n\n' + 'Try to explain what you did (steps to reproduce),\n' + 'what you experienced (screenshots) and what you expected\n' + '(unless that is obvious).\n\n' + 'Thanks for reporting!\n\n' + chrome.app.getDetails().author; }); // window.dom_keeper.get_all }); // storage.get }; // onclick }());
radio-paradise-extension/js/bugreport.js
/* * Radio Paradise player * Copyright (c) 2014 Alexey Michurin <[email protected]> * MIT License [http://www.opensource.org/licenses/mit-license.php] */ /*global window, chrome */ /*global storage */ 'use strict'; (function () { var bugreport_element = window.document.getElementById('bugreport'); var root_element = window.document.getElementById('bugreport-body'); bugreport_element.onclick = function () { root_element.style.display = 'block'; storage.get(null, function (stor) { window.dom_keeper.get_all(function (cache) { root_element.innerText = ''; root_element.innerText = 'Contributions and bug reports are welcome from anyone!\n' + 'Please attach this summary to your bug report.\n\n' + JSON.stringify({ ext_version: chrome.app.getDetails().version, user_agent: window.navigator.userAgent, storage: stor, runtime: { now: (new Date()).toUTCString(), last_error: (chrome.runtime.lastError || '-'), id: chrome.runtime.id, manifest: chrome.runtime.getManifest() }, cache: cache }, function(k, v) { var r; if (typeof v === 'undefined') { return 'undefined value'; } if (v.nodeType) { if (v.nodeType === 1) { r = {tag: v.tagName}; if (v.attributes.length > 0) { r.attributes = {}; Array.prototype.slice.call(v.attributes, 0).forEach(function (v) { r.attributes[v.name] = v.value; }); } if (v.childNodes.length > 0) { if (v.childNodes.length === 1) { r.child = v.childNodes[0]; } else { r.childs = Array.prototype.slice.call(v.childNodes, 0); } } return r; } else if (v.nodeType === 3) { return v.textContent; } else { return 'nodeType=' + v.nodeType; } } return v; }, 2) + '\n\n' + 'Try to explain what you did (steps to reproduce),\n' + 'what you experienced (screenshots) and what you expected\n' + '(unless that is obvious).\n\n' + 'Thanks for reporting!\n\n' + chrome.app.getDetails().author; }); }); }; }());
cosmetics; debugging
radio-paradise-extension/js/bugreport.js
cosmetics; debugging
<ide><path>adio-paradise-extension/js/bugreport.js <ide> var root_element = window.document.getElementById('bugreport-body'); <ide> <ide> bugreport_element.onclick = function () { <add> <ide> root_element.style.display = 'block'; <add> root_element.innerText = ''; <add> <ide> storage.get(null, function (stor) { <ide> window.dom_keeper.get_all(function (cache) { <ide> <del> root_element.innerText = ''; <ide> root_element.innerText = <ide> 'Contributions and bug reports are welcome from anyone!\n' + <ide> 'Please attach this summary to your bug report.\n\n' + <ide> 'Thanks for reporting!\n\n' + <ide> chrome.app.getDetails().author; <ide> <del> }); <del> }); <del> }; <add> }); // window.dom_keeper.get_all <add> }); // storage.get <add> <add> }; // onclick <ide> <ide> }());
Java
agpl-3.0
549822ec39485b90a9a82f1fb8dcd67d3cb53332
0
ColostateResearchServices/kc,iu-uits-es/kc,iu-uits-es/kc,geothomasp/kcmit,jwillia/kc-old1,kuali/kc,mukadder/kc,jwillia/kc-old1,ColostateResearchServices/kc,ColostateResearchServices/kc,geothomasp/kcmit,mukadder/kc,geothomasp/kcmit,mukadder/kc,geothomasp/kcmit,kuali/kc,UniversityOfHawaiiORS/kc,UniversityOfHawaiiORS/kc,UniversityOfHawaiiORS/kc,jwillia/kc-old1,geothomasp/kcmit,kuali/kc,iu-uits-es/kc,jwillia/kc-old1
/* * Copyright 2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php * * 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.kuali.kra.proposaldevelopment.web; import org.junit.Before; import org.junit.Test; import org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument; import com.gargoylesoftware.htmlunit.html.HtmlPage; /** * Web Test class for testing the Key Personnel Tab of the <code>{@link ProposalDevelopmentDocument}</code> * @author $Author: lprzybyl $ * @version $Revision: 1.7 $ */ public class KeyPersonnelWebTest extends ProposalDevelopmentWebTestBase { private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(KeyPersonnelWebTest.class); private static final String KEY_PERSONNEL_IMAGE_NAME = "methodToCall.headerTab.headerDispatch.save.navigateTo.keyPersonnel.x"; private static final String ERRORS_FOUND_ON_PAGE = "error(s) found on page"; private HtmlPage keyPersonnelPage; /** * @see org.kuali.kra.proposaldevelopment.web.ProposalDevelopmentWebTestBase#setUp() */ @Before public void setUp() throws Exception { super.setUp(); setDefaultRequiredFields(getProposalDevelopmentPage()); setKeyPersonnelPage(clickOn(getProposalDevelopmentPage(), KEY_PERSONNEL_IMAGE_NAME)); } /** * Assign key personnel page * * @param keyPersonnelPage <code>{@link HtmlPage}</code> instance of key personnel page */ public void setKeyPersonnelPage(HtmlPage keyPersonnelPage) { this.keyPersonnelPage = keyPersonnelPage; } /** * Generate a Key Personnel Page by going to the clicking on the link from the proposal page. * * @return <code>{@link HtmlPage}</code> instance of the key Personnel Page * @see #getProposalDevelopmentPage() */ public HtmlPage getKeyPersonnelPage() { return keyPersonnelPage; } /** * @see org.kuali.kra.KraWebTestBase#getDefaultDocumentPage() */ protected HtmlPage getDefaultDocumentPage() { return getKeyPersonnelPage(); } // ////////////////////////////////////////////////////////////////////// // Test Methods // // ////////////////////////////////////////////////////////////////////// /** * Test adding a principal investigator */ @Test public void addPrincipalInvestigator() throws Exception { HtmlPage keyPersonnelPage = lookup(getKeyPersonnelPage(), "org.kuali.kra.bo.Person"); assertEquals("Terry Durkin", getFieldValue(keyPersonnelPage, "newProposalPerson.fullName")); setFieldValue(keyPersonnelPage,"newProposalPerson.proposalPersonRoleId", "PI"); keyPersonnelPage = clickOn(getElementByName(keyPersonnelPage, "methodToCall.insertProposalPerson", true)); assertFalse(keyPersonnelPage.asText().contains(ERRORS_FOUND_ON_PAGE)); saveAndSearchDoc(keyPersonnelPage); } /** * Test adding a principal investigator */ @Test public void addPrincipalInvestigator_Rolodex() throws Exception { HtmlPage keyPersonnelPage = lookup(getKeyPersonnelPage(), "org.kuali.kra.bo.NonOrganizationalRolodex"); assertEquals("First Name Middle Name Last Name", getFieldValue(keyPersonnelPage, "newProposalPerson.fullName")); setFieldValue(keyPersonnelPage,"newProposalPerson.proposalPersonRoleId", "PI"); keyPersonnelPage = clickOn(getElementByName(keyPersonnelPage, "methodToCall.insertProposalPerson", true)); assertFalse(keyPersonnelPage.asText().contains(ERRORS_FOUND_ON_PAGE)); saveAndSearchDoc(keyPersonnelPage); } /** * Test adding a Key Person */ @Test public void addKeyPerson() throws Exception { HtmlPage keyPersonnelPage = lookup(getKeyPersonnelPage(), "org.kuali.kra.bo.Person"); assertEquals("Terry Durkin", getFieldValue(keyPersonnelPage, "newProposalPerson.fullName")); setFieldValue(keyPersonnelPage,"newProposalPerson.proposalPersonRoleId", "KP"); clickOn(getElementByName(keyPersonnelPage, "methodToCall.insertProposalPerson", true)); assertFalse(keyPersonnelPage.asText().contains(ERRORS_FOUND_ON_PAGE)); keyPersonnelPage = clickOn(getElementByName(keyPersonnelPage, "methodToCall.insertProposalPerson", true)); saveAndSearchDoc(keyPersonnelPage); } /** * @see org.kuali.kra.KraWebTestBase#testHelpLinks() */ @Test public void testHelpLinks() throws Exception { super.testHelpLinks(); } }
src/test/java/org/kuali/kra/proposaldevelopment/web/KeyPersonnelWebTest.java
/* * Copyright 2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php * * 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.kuali.kra.proposaldevelopment.web; import org.junit.Before; import org.junit.Test; import org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument; import com.gargoylesoftware.htmlunit.html.HtmlPage; /** * Web Test class for testing the Key Personnel Tab of the <code>{@link ProposalDevelopmentDocument}</code> * @author $Author: lprzybyl $ * @version $Revision: 1.6 $ */ public class KeyPersonnelWebTest extends ProposalDevelopmentWebTestBase { private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(KeyPersonnelWebTest.class); private static final String KEY_PERSONNEL_IMAGE_NAME = "methodToCall.headerTab.headerDispatch.save.navigateTo.keyPersonnel.x"; private static final String ERRORS_FOUND_ON_PAGE = "error(s) found on page"; private HtmlPage keyPersonnelPage; /** * @see org.kuali.kra.proposaldevelopment.web.ProposalDevelopmentWebTestBase#setUp() */ @Before public void setUp() throws Exception { super.setUp(); setDefaultRequiredFields(getProposalDevelopmentPage()); setKeyPersonnelPage(clickOn(getProposalDevelopmentPage(), KEY_PERSONNEL_IMAGE_NAME)); } /** * Assign key personnel page * * @param keyPersonnelPage <code>{@link HtmlPage}</code> instance of key personnel page */ public void setKeyPersonnelPage(HtmlPage keyPersonnelPage) { this.keyPersonnelPage = keyPersonnelPage; } /** * Generate a Key Personnel Page by going to the clicking on the link from the proposal page. * * @return <code>{@link HtmlPage}</code> instance of the key Personnel Page * @see #getProposalDevelopmentPage() */ public HtmlPage getKeyPersonnelPage() { return keyPersonnelPage; } /** * @see org.kuali.kra.KraWebTestBase#getDefaultDocumentPage() */ protected HtmlPage getDefaultDocumentPage() { return getKeyPersonnelPage(); } // ////////////////////////////////////////////////////////////////////// // Test Methods // // ////////////////////////////////////////////////////////////////////// /** * Test adding a principal investigator */ @Test public void addPrincipalInvestigator() throws Exception { HtmlPage keyPersonnelPage = lookup(getKeyPersonnelPage(), "org.kuali.kra.bo.Person"); assertEquals("Terry Durkin", getFieldValue(keyPersonnelPage, "newProposalPerson.fullName")); setFieldValue(keyPersonnelPage,"newProposalPerson.proposalPersonRoleId", "PI"); keyPersonnelPage = clickOn(getElementByName(keyPersonnelPage, "methodToCall.insertProposalPerson", true)); assertFalse(keyPersonnelPage.asText().contains(ERRORS_FOUND_ON_PAGE)); saveAndSearchDoc(keyPersonnelPage); } /** * Test adding a Key Person */ @Test public void addKeyPerson() throws Exception { HtmlPage keyPersonnelPage = lookup(getKeyPersonnelPage(), "org.kuali.kra.bo.Person"); assertEquals("Terry Durkin", getFieldValue(keyPersonnelPage, "newProposalPerson.fullName")); setFieldValue(keyPersonnelPage,"newProposalPerson.proposalPersonRoleId", "KP"); clickOn(getElementByName(keyPersonnelPage, "methodToCall.insertProposalPerson", true)); assertFalse(keyPersonnelPage.asText().contains(ERRORS_FOUND_ON_PAGE)); keyPersonnelPage = clickOn(getElementByName(keyPersonnelPage, "methodToCall.insertProposalPerson", true)); saveAndSearchDoc(keyPersonnelPage); } /** * @see org.kuali.kra.KraWebTestBase#testHelpLinks() */ @Test public void testHelpLinks() throws Exception { super.testHelpLinks(); } }
KRACOEUS-698 - Adding Unit Test to check Rolodex
src/test/java/org/kuali/kra/proposaldevelopment/web/KeyPersonnelWebTest.java
KRACOEUS-698 - Adding Unit Test to check Rolodex
<ide><path>rc/test/java/org/kuali/kra/proposaldevelopment/web/KeyPersonnelWebTest.java <ide> /** <ide> * Web Test class for testing the Key Personnel Tab of the <code>{@link ProposalDevelopmentDocument}</code> <ide> * @author $Author: lprzybyl $ <del> * @version $Revision: 1.6 $ <add> * @version $Revision: 1.7 $ <ide> */ <ide> public class KeyPersonnelWebTest extends ProposalDevelopmentWebTestBase { <ide> private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(KeyPersonnelWebTest.class); <ide> } <ide> <ide> /** <add> * Test adding a principal investigator <add> */ <add> @Test <add> public void addPrincipalInvestigator_Rolodex() throws Exception { <add> HtmlPage keyPersonnelPage = lookup(getKeyPersonnelPage(), "org.kuali.kra.bo.NonOrganizationalRolodex"); <add> assertEquals("First Name Middle Name Last Name", getFieldValue(keyPersonnelPage, "newProposalPerson.fullName")); <add> setFieldValue(keyPersonnelPage,"newProposalPerson.proposalPersonRoleId", "PI"); <add> <add> keyPersonnelPage = clickOn(getElementByName(keyPersonnelPage, "methodToCall.insertProposalPerson", true)); <add> <add> assertFalse(keyPersonnelPage.asText().contains(ERRORS_FOUND_ON_PAGE)); <add> saveAndSearchDoc(keyPersonnelPage); <add> } <add> <add> /** <ide> * Test adding a Key Person <ide> */ <ide> @Test
Java
epl-1.0
64443ecc5c89605914e744ca322a11240116d263
0
sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt
/************************************************************************************* * Copyright (c) 2004, 2007 Actuate Corporation and others. * 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 * * Contributors: * Actuate Corporation - Initial implementation. ************************************************************************************/ package org.eclipse.birt.report.designer.internal.ui.editors.script; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.core.model.views.outline.ScriptElementNode; import org.eclipse.birt.report.designer.core.util.mediator.IColleague; import org.eclipse.birt.report.designer.core.util.mediator.request.ReportRequest; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.internal.ui.views.data.DataViewPage; import org.eclipse.birt.report.designer.internal.ui.views.data.DataViewTreeViewerPage; import org.eclipse.birt.report.designer.internal.ui.views.outline.DesignerOutlinePage; import org.eclipse.birt.report.designer.internal.ui.views.property.ReportPropertySheetPage; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.IReportGraphicConstants; import org.eclipse.birt.report.designer.ui.ReportPlatformUIImages; import org.eclipse.birt.report.designer.ui.views.ProviderFactory; import org.eclipse.birt.report.designer.ui.views.attributes.AttributeViewPage; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.ExtendedItemHandle; import org.eclipse.birt.report.model.api.ScriptDataSourceHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.metadata.IArgumentInfo; import org.eclipse.birt.report.model.api.metadata.IArgumentInfoList; import org.eclipse.birt.report.model.api.metadata.IClassInfo; import org.eclipse.birt.report.model.api.metadata.IElementPropertyDefn; import org.eclipse.birt.report.model.api.metadata.IMethodInfo; import org.eclipse.birt.report.model.api.metadata.IPropertyDefn; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.draw2d.ColorConstants; import org.eclipse.gef.ui.actions.ActionRegistry; import org.eclipse.gef.ui.views.palette.PalettePage; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextListener; import org.eclipse.jface.text.TextEvent; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.forms.editor.IFormPage; import org.eclipse.ui.part.EditorPart; import org.eclipse.ui.part.MultiPageEditorSite; import org.eclipse.ui.texteditor.AbstractTextEditor; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.ui.views.properties.IPropertySheetPage; /** * Main class of javaScript editor * */ public class JSEditor extends EditorPart implements IColleague { protected static Logger logger = Logger.getLogger( JSEditor.class.getName( ) ); private static final String NO_EXPRESSION = Messages.getString( "JSEditor.Display.NoExpression" ); //$NON-NLS-1$ static final String VIEWER_CATEGORY_KEY = "Category"; //$NON-NLS-1$ static final String VIEWER_CATEGORY_CONTEXT = "context"; //$NON-NLS-1$ private IEditorPart editingDomainEditor; Combo cmbExpList = null; Combo cmbSubFunctions = null; public ComboViewer cmbExprListViewer; IPropertyDefn cmbItemLastSelected = null; boolean editorUIEnabled = true; private Button butReset; private Button butValidate; /** the icon for validator, default hide */ private Label validateIcon = null; /** the tool bar pane */ private Composite controller = null; private Label ano; private final HashMap selectionMap = new HashMap( ); private boolean isModified; private Object editObject; /** * Palette page */ public TreeViewPalettePage palettePage = new TreeViewPalettePage( ); public ComboViewer cmbSubFunctionsViewer; /** the script editor, dosen't include controller. */ private final IScriptEditor scriptEditor = createScriptEditor( ); /** the script validator */ private ScriptValidator scriptValidator = null; /** the flag if the text listener is enabled. */ private boolean isTextListenerEnable = true; /** the listener for text chaged. */ private final ITextListener textListener = new ITextListener( ) { /* * (non-Javadoc) * * @see org.eclipse.jface.text.ITextListener#textChanged(org.eclipse.jface.text.TextEvent) */ public void textChanged( TextEvent event ) { if ( isTextListenerEnable ) { markDirty( ); } } }; /** * JSEditor - constructor */ public JSEditor( IEditorPart parent ) { super( ); this.editingDomainEditor = parent; setSite( parent.getEditorSite( ) ); } /** * Creates script editor, dosen't include controller * * @return a script editor */ protected IScriptEditor createScriptEditor( ) { return new ScriptEditor( ); } /** * @see AbstractTextEditor#doSave( IProgressMonitor ) */ public void doSave( IProgressMonitor monitor ) { saveModel( ); } public boolean isDirty( ) { return isCodeModified( ); } /* * (non-Javadoc) * * @see org.eclipse.ui.editors.text.TextEditor#isSaveAsAllowed() */ public boolean isSaveAsAllowed( ) { return true; } /** * disposes all color objects */ public void dispose( ) { // colorManager.dispose( ); // remove the mediator listener // SessionHandleAdapter.getInstance( ) // .getMediator( ) // .removeColleague( this ); selectionMap.clear( ); editingDomainEditor = null; super.dispose( ); // ( (ReportMultiPageEditorSite) getSite( ) ).dispose( ); ( (MultiPageEditorSite) getSite( ) ).dispose( ); } // Parameter names are constructed by taking the java class name // and make the first letter lowercase. // If there are more than 2 uppercase letters, it's shortened as the list of // those. For instance IChartScriptContext becomes icsc protected static String convertToParameterName( String fullName ) { // strip the full qualified name fullName = fullName.substring( fullName.lastIndexOf( '.' ) + 1 ); int upCase = 0; SortedMap caps = new TreeMap( ); for ( int i = 0; i < fullName.length( ); i++ ) { char character = fullName.charAt( i ); if ( Character.isUpperCase( character ) ) { upCase++; caps.put( new Integer( i ), new Integer( character ) ); } } if ( upCase > 2 ) { StringBuffer result = new StringBuffer( ); for ( Iterator iter = caps.values( ).iterator( ); iter.hasNext( ); ) { result.append( (char) ( (Integer) iter.next( ) ).intValue( ) ); } return result.toString( ).toLowerCase( ); } else return fullName.substring( 0, 1 ).toLowerCase( ) + fullName.substring( 1 ); } private void updateScriptContext( DesignElementHandle handle, String method ) { List args = DEUtil.getDesignElementMethodArgumentsInfo( handle, method ); JSSyntaxContext context = scriptEditor.getContext(); context.clear( ); for ( Iterator iter = args.iterator( ); iter.hasNext( ); ) { IArgumentInfo element = (IArgumentInfo) iter.next( ); String name = element.getName( ); String type = element.getType( ); // try load system class info first, if failed, then try extension // class info if ( !context.setVariable( name, type ) ) { context.setVariable( name, element.getClassType( ) ); } } if ( handle instanceof ExtendedItemHandle ) { ExtendedItemHandle exHandle = (ExtendedItemHandle) handle; List mtds = exHandle.getMethods( method ); // TODO implement better function-wise code assistant. if ( mtds != null && mtds.size( ) > 0 ) { for ( int i = 0; i < mtds.size( ); i++ ) { IMethodInfo mi = (IMethodInfo) mtds.get( i ); for ( Iterator itr = mi.argumentListIterator( ); itr.hasNext( ); ) { IArgumentInfoList ailist = (IArgumentInfoList) itr.next( ); for ( Iterator argItr = ailist.argumentsIterator( ); argItr.hasNext( ); ) { IArgumentInfo aiinfo = (IArgumentInfo) argItr.next( ); IClassInfo ci = aiinfo.getClassType( ); String name = convertToParameterName( ci.getName( ) ); context.setVariable( name, ci ); } } } } } } public void createPartControl( Composite parent ) { Composite child = this.initEditorLayout( parent ); // Script combo cmbExprListViewer = new ComboViewer( cmbExpList ); JSExpListProvider provider = new JSExpListProvider( ); cmbExprListViewer.setContentProvider( provider ); cmbExprListViewer.setLabelProvider( provider ); cmbExprListViewer.setData( VIEWER_CATEGORY_KEY, VIEWER_CATEGORY_CONTEXT ); // SubFunctions combo JSSubFunctionListProvider subProvider = new JSSubFunctionListProvider( this ); // also add subProvider as listener of expr viewer. cmbExprListViewer.addSelectionChangedListener( subProvider ); cmbSubFunctionsViewer = new ComboViewer( cmbSubFunctions ); cmbSubFunctionsViewer.setContentProvider( subProvider ); cmbSubFunctionsViewer.setLabelProvider( subProvider ); cmbSubFunctionsViewer.addSelectionChangedListener( subProvider ); // Initialize the model for the document. Object model = getModel( ); if ( model != null ) { cmbExpList.setVisible( true ); cmbSubFunctions.setVisible( true ); setComboViewerInput( model ); } else { setComboViewerInput( Messages.getString( "JSEditor.Input.trial" ) ); //$NON-NLS-1$ } cmbExprListViewer.addSelectionChangedListener( palettePage.getSupport( ) ); cmbExprListViewer.addSelectionChangedListener( new ISelectionChangedListener( ) { /** * selectionChanged( event) - This listener implementation is * invoked when an item in the combo box is selected, - It saves the * current editor contents. - Updates the editor content with the * expression corresponding to the selected method name or * expression. name. */ public void selectionChanged( SelectionChangedEvent event ) { ISelection selection = event.getSelection( ); if ( selection != null ) { Object[] sel = ( (IStructuredSelection) selection ).toArray( ); if ( sel.length == 1 ) { if ( sel[0] instanceof IPropertyDefn ) { // Save the current expression into the DE // using DE // API DesignElementHandle desHandle = (DesignElementHandle) cmbExprListViewer.getInput( ); saveModelIfNeeds( ); // Update the editor to display the // expression // corresponding to the selected // combo item ( method name/ expression name // ) IPropertyDefn elePropDefn = (IPropertyDefn) sel[0]; cmbItemLastSelected = elePropDefn; setTextListenerEnable( false ); setEditorText( desHandle.getStringProperty( elePropDefn.getName( ) ) ); setTextListenerEnable( true ); setIsModified( false ); selectionMap.put( getModel( ), selection ); String method = cmbItemLastSelected.getName( ); updateScriptContext( desHandle, method ); } } } } } ); scriptEditor.createPartControl( child ); scriptValidator = new ScriptValidator( getViewer( ) ); // suport the mediator SessionHandleAdapter.getInstance( ).getMediator( ).addColleague( this ); disableEditor( ); getViewer( ).addTextListener( textListener ); } /** * Sets the status of the text listener. * * @param enabled * <code>true</code> if enable, <code>false</code> otherwise. */ private void setTextListenerEnable( boolean enabled ) { isTextListenerEnable = enabled; } /** * Get current edit element, not report design model. * * @return */ public Object getModel( ) { // return cmbExprListViewer.getInput( ); return editObject; } private void updateAnnotationLabel( Object handle ) { String name = ProviderFactory.createProvider( handle ) .getNodeDisplayName( handle ); if ( name == null ) { ano.setText( "" ); //$NON-NLS-1$ } else { ano.setText( name ); } } /* * (non-Javadoc) * * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) */ public Object getAdapter( Class adapter ) { if ( adapter == ActionRegistry.class ) { return scriptEditor.getActionRegistry( ); } else if ( adapter == PalettePage.class ) { if ( cmbExprListViewer != null ) { cmbExprListViewer.addSelectionChangedListener( palettePage.getSupport( ) ); } return palettePage; } if ( adapter == IContentOutlinePage.class ) { // ( (NonGEFSynchronizerWithMutiPageEditor) // getSelectionSynchronizer( ) ).add( (NonGEFSynchronizer) // outlinePage.getAdapter( NonGEFSynchronizer.class ) ); // Add JS Editor as a selection listener to Outline view selections. // outlinePage.addSelectionChangedListener( jsEditor ); DesignerOutlinePage outlinePage = new DesignerOutlinePage( SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) ); return outlinePage; } // return the property sheet page if ( adapter == IPropertySheetPage.class ) { ReportPropertySheetPage sheetPage = new ReportPropertySheetPage( ); return sheetPage; } if ( adapter == DataViewPage.class ) { DataViewTreeViewerPage page = new DataViewTreeViewerPage( SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) ); return page; } if ( adapter == AttributeViewPage.class ) { AttributeViewPage page = new AttributeViewPage( ); return page; } return super.getAdapter( adapter ); } /** * * initEditorLayout - initialize the UI components of the editor * */ private Composite initEditorLayout( Composite parent ) { // Create the editor parent composite. Composite mainPane = new Composite( parent, SWT.NONE ); GridLayout layout = new GridLayout( ); layout.verticalSpacing = 0; mainPane.setLayout( layout ); controller = createController( mainPane ); // Create the code editor pane. Composite jsEditorContainer = new Composite( mainPane, SWT.NONE ); GridData gdata = new GridData( GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL ); jsEditorContainer.setLayoutData( gdata ); jsEditorContainer.setLayout( new FillLayout( ) ); return jsEditorContainer; } /** * Creates tool bar pane. * * @param parent * the parent of controller * @return a tool bar pane */ protected Composite createController( Composite parent ) { Composite barPane = new Composite( parent, SWT.NONE ); GridLayout layout = new GridLayout( 8, false ); GridData gdata = new GridData( GridData.FILL_HORIZONTAL ); barPane.setLayout( layout ); barPane.setLayoutData( gdata ); initScriptLabel( barPane ); initComboBoxes( barPane ); // Creates Reset button butReset = new Button( barPane, SWT.PUSH ); butReset.setText( Messages.getString( "JSEditor.Button.Reset" ) ); //$NON-NLS-1$ GridData layoutData = new GridData( ); layoutData.horizontalIndent = 6; butReset.setLayoutData( layoutData ); butReset.addSelectionListener( new SelectionListener( ) { public void widgetSelected( SelectionEvent e ) { setEditorText( "" ); //$NON-NLS-1$ markDirty( ); } public void widgetDefaultSelected( SelectionEvent e ) { widgetSelected( e ); } } ); // Creates Validate button butValidate = new Button( barPane, SWT.PUSH ); butValidate.setText( Messages.getString( "JSEditor.Button.Validate" ) ); //$NON-NLS-1$ layoutData = new GridData( ); layoutData.horizontalIndent = 6; butValidate.setLayoutData( layoutData ); butValidate.addSelectionListener( new SelectionAdapter( ) { /* * (non-Javadoc) * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) */ public void widgetSelected( SelectionEvent e ) { doValidate( ); } } ); // Creates Validate icon, default empty. validateIcon = new Label( barPane, SWT.NULL ); Label column = new Label( barPane, SWT.SEPARATOR | SWT.VERTICAL ); layoutData = new GridData( ); layoutData.heightHint = 20; layoutData.horizontalIndent = 10; column.setLayoutData( layoutData ); ano = new Label( barPane, 0 ); layoutData = new GridData( GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_CENTER ); ano.setLayoutData( layoutData ); final Composite sep = new Composite( parent, 0 ); layoutData = new GridData( GridData.FILL_HORIZONTAL ); layoutData.heightHint = 1; sep.setLayoutData( layoutData ); sep.addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { GC gc = e.gc; Rectangle rect = sep.getBounds( ); gc.setForeground( ColorConstants.darkGray ); gc.drawLine( 0, 0, rect.width, 0 ); } } ); return barPane; } /** * Hides validate button & icon. */ protected void hideValidateButtonIcon( ) { hideControl( butValidate ); hideControl( validateIcon ); } /** * Hides a control from its parent composite. * * @param control * the control to hide */ private void hideControl( Control control ) { Object layoutData = control.getLayoutData( ); if ( layoutData == null ) { layoutData = new GridData( ); control.setLayoutData( layoutData ); } if ( layoutData instanceof GridData ) { GridData gridData = (GridData) layoutData; gridData.exclude = true; control.setLayoutData( gridData ); control.setVisible( false ); } } private void initScriptLabel( Composite parent ) { Label lblScript = new Label( parent, SWT.NONE ); lblScript.setText( Messages.getString( "JSEditor.Label.Script" ) ); //$NON-NLS-1$ final FontData fd = lblScript.getFont( ).getFontData( )[0]; Font labelFont = new Font( Display.getCurrent( ), fd.getName( ), fd.getHeight( ), SWT.BOLD ); lblScript.setFont( labelFont ); GridData layoutData = new GridData( SWT.BEGINNING ); lblScript.setLayoutData( layoutData ); } private void initComboBoxes( Composite parent ) { // Create the script combo box cmbExpList = new Combo( parent, SWT.READ_ONLY ); GridData layoutData = new GridData( GridData.BEGINNING ); layoutData.widthHint = 140; cmbExpList.setLayoutData( layoutData ); // Create the subfunction combo box cmbSubFunctions = new Combo( parent, SWT.DROP_DOWN | SWT.READ_ONLY ); cmbSubFunctions.setLayoutData( layoutData ); } /* * SelectionChanged. - Selection listener implementation for changes in * other views Selection of elements in other views, triggers this event. - * The code editor view is updated to show the methods corresponding to the * selected element. */ public void handleSelectionChanged( SelectionChangedEvent event ) { ISelection selection = event.getSelection( ); handleSelectionChanged( selection ); } public void handleSelectionChanged( ISelection selection ) { if ( editorUIEnabled == true ) { // save the previous editor content. // saveModelIfNeeds( ); saveModel( ); } if ( selection != null ) { Object[] sel = ( (IStructuredSelection) selection ).toArray( ); if ( sel.length == 1 ) { editObject = sel[0]; if ( sel[0] instanceof ScriptElementNode ) { editObject = ( (ScriptElementNode) editObject ).getParent( ); } } if ( editObject instanceof DesignElementHandle ) { // set the combo viewer input to the the selected element. palettePage.getSupport( ).setCurrentEditObject( editObject ); setComboViewerInput( editObject ); // clear the latest selected item. cmbItemLastSelected = null; try { setTextListenerEnable( false ); setEditorText( "" ); //$NON-NLS-1$ // enable/disable editor based on the items in the // expression list. if ( cmbExpList.getItemCount( ) > 0 ) { enableEditor( ); // Selects the first item in the expression list. selectItemInComboExpList( (ISelection) selectionMap.get( getModel( ) ) ); } else { disableEditor( ); } } finally { setTextListenerEnable( true ); } /* * if ( editObject instanceof ExtendedItemHandle ) { * setEditorText( ( (ExtendedItemHandle) editObject * ).getExternalScript( ) ); context.setVariable( "this", * "org.eclipse.birt.report.model.api.ExtendedItemHandle" ); * //$NON-NLS-1$ //$NON-NLS-2$ } */ checkDirty( ); palettePage.getSupport( ).updateParametersTree( ); } else { disableEditor( ); cmbExpList.removeAll( ); cmbSubFunctions.removeAll( ); cmbItemLastSelected = null; palettePage.getSupport( ).setCurrentEditObject( null ); } if ( sel.length > 0 ) { updateAnnotationLabel( sel[0] ); } } } private void checkDirty( ) { // ( (AbstractMultiPageLayoutEditor) editingDomainEditor ).checkDirty( // ); } private void selectItemInComboExpList( ISelection selection ) { ISelection sel = selection; if ( sel.isEmpty( ) && cmbExpList.getItemCount( ) > 0 ) { IPropertyDefn propDefn = (IPropertyDefn) cmbExprListViewer.getElementAt( 0 ); if ( propDefn != null ) { sel = new StructuredSelection( propDefn ); } } cmbExprListViewer.setSelection( sel ); return; } // /** // * selectItemInComboExpList - selects the specified input item in the // * expList - if input is null selects first item. // */ // private void selectItemInComboExpList( IPropertyDefn propDefn ) // { // if ( propDefn == null ) // { // if ( cmbExpList.getItemCount( ) > 0 ) // propDefn = (IPropertyDefn) this.cmbExprListViewer // .getElementAt( 0 ); // } // // if ( propDefn != null ) // selectItemInComboExpList( new StructuredSelection( propDefn ) ); // // } /** * setEditorText - sets the editor content. * * @param text */ private void setEditorText( String text ) { if ( scriptEditor == null ) { return; } scriptEditor.setScript( text ); if ( scriptValidator != null ) { scriptValidator.init( ); setValidateIcon( null, null ); } } /** * getEditorText() - gets the editor content. * */ private String getEditorText( ) { return scriptEditor.getScript( ); } /** * saveEditorContentsDE - saves the current editor contents to ROM using DE * API * * @param desHdl * @return true if updated else false. */ private boolean saveEditorContentsDE( DesignElementHandle desHdl ) { if ( desHdl != null && getEditorText( ) != null ) { try { if ( cmbItemLastSelected != null ) { desHdl.setStringProperty( cmbItemLastSelected.getName( ), getEditorText( ) ); } selectionMap.put( getModel( ), cmbExprListViewer.getSelection( ) ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); return false; } } return true; } /** * Saves input code to model * */ public void saveModel( ) { if ( isCodeModified( ) && editObject instanceof DesignElementHandle ) { saveEditorContentsDE( (DesignElementHandle) editObject ); } setIsModified( false ); } /** * @param b */ public void setIsModified( boolean b ) { isModified = b; } private boolean isCodeModified( ) { return isModified; } public void saveModelIfNeeds( ) { if ( checkEditorActive( ) ) { if ( isCodeModified( ) && editObject instanceof DesignElementHandle ) { saveEditorContentsDE( (DesignElementHandle) editObject ); } } } protected void markDirty( ) { if ( !isModified ) { setIsModified( true ); ( (IFormPage) editingDomainEditor ).getEditor( ) .editorDirtyStateChanged( ); firePropertyChange( PROP_DIRTY ); } } protected boolean checkEditorActive( ) { return true; } /** * Enables the editor UI components */ private void enableEditor( ) { if ( editorUIEnabled == false ) { getViewer( ).getTextWidget( ).setEnabled( true ); cmbExpList.setEnabled( true ); butReset.setEnabled( true ); butValidate.setEnabled( true ); editorUIEnabled = true; } setEditorText( "" ); //$NON-NLS-1$ } /** * Disables the editor UI components */ private void disableEditor( ) { if ( editorUIEnabled == true ) { getViewer( ).getTextWidget( ).setEnabled( false ); cmbExpList.setEnabled( false ); cmbSubFunctions.setEnabled( false ); butReset.setEnabled( false ); butValidate.setEnabled( false ); editorUIEnabled = false; } setEditorText( NO_EXPRESSION ); } /** * Gets source viewer in the editor * * @return source viewer */ public SourceViewer getViewer( ) { return (SourceViewer) scriptEditor.getViewer( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.core.util.mediator.IColleague#performRequest(org.eclipse.birt.report.designer.core.util.mediator.request.ReportRequest) */ public void performRequest( ReportRequest request ) { if ( ReportRequest.SELECTION.equals( request.getType( ) ) ) { handleSelectionChange( request.getSelectionModelList( ) ); } if ( ReportRequest.CREATE_ELEMENT.equals( request.getType( ) ) && request.getSelectionModelList( ).get( 0 ) instanceof ScriptDataSourceHandle ) { handleSelectionChange( request.getSelectionModelList( ) ); } } private void setComboViewerInput( Object model ) { cmbExprListViewer.setInput( model ); Object oldSelection = selectionMap.get( model ); if ( oldSelection == null ) { selectItemInComboExpList( new StructuredSelection( ) ); } else { selectItemInComboExpList( (ISelection) oldSelection ); } cmbSubFunctionsViewer.setInput( model ); int itemCount = cmbSubFunctions.getItemCount( ); if ( itemCount > 0 ) { cmbSubFunctions.select( 0 ); // select first element always } cmbSubFunctions.setEnabled( itemCount > 0 ); return; } private void setComboViewerInput( String message ) { cmbExprListViewer.setInput( message ); return; } /** * Reset the selection forcely. * * @param list */ public void handleSelectionChange( List list ) { if ( scriptEditor instanceof AbstractTextEditor ) { SelectionChangedEvent event = new SelectionChangedEvent( ( (AbstractTextEditor) scriptEditor ).getSelectionProvider( ), new StructuredSelection( list ) ); handleSelectionChanged( event ); } } /** * Returns the current script editor. * * @return the current script editor. */ protected IScriptEditor getScriptEditor( ) { return scriptEditor; } /** * Validates the contents of this editor. */ public void doValidate( ) { Image image = null; String message = null; if ( scriptValidator == null ) { return; } try { scriptValidator.validate( ); image = ReportPlatformUIImages.getImage( IReportGraphicConstants.ICON_SCRIPT_NOERROR ); message = Messages.getString( "JSEditor.Validate.NoError" ); } catch ( ParseException e ) { image = ReportPlatformUIImages.getImage( IReportGraphicConstants.ICON_SCRIPT_ERROR ); message = e.getLocalizedMessage( ); } finally { setValidateIcon( image, message ); setFocus( ); } } /** * Sets the validate icon with the specified image and tool tip text. * * * @param image * the icon image * @param tip * the tool tip text */ private void setValidateIcon( Image image, String tip ) { if ( validateIcon != null ) { validateIcon.setImage( image ); validateIcon.setToolTipText( tip ); if ( controller != null ) { controller.layout( ); } } } /* * (non-Javadoc) * * @see org.eclipse.ui.part.EditorPart#doSaveAs() */ public void doSaveAs( ) { scriptEditor.doSaveAs( ); } /* * (non-Javadoc) * * @see org.eclipse.ui.part.EditorPart#init(org.eclipse.ui.IEditorSite, org.eclipse.ui.IEditorInput) */ public void init( IEditorSite site, IEditorInput input ) throws PartInitException { setSite( site ); setInput( input ); scriptEditor.init( site, input ); } /* * (non-Javadoc) * * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ public void setFocus( ) { scriptEditor.setFocus( ); } } /** * class JSExpListProvider - Is the content and label provider for the * expression list * */ class JSExpListProvider implements IStructuredContentProvider, ILabelProvider { private static final String NO_TEXT = Messages.getString( "JSEditor.Text.NoText" ); //$NON-NLS-1$; public Object[] getElements( Object inputElement ) { if ( inputElement instanceof ExtendedItemHandle ) { ExtendedItemHandle extHandle = (ExtendedItemHandle) inputElement; List methods = extHandle.getMethods( ); List returnList = new ArrayList( ); for ( Iterator iter = methods.iterator( ); iter.hasNext( ); ) { IElementPropertyDefn method = (IElementPropertyDefn) iter.next( ); if ( extHandle.getMethods( method.getName( ) ) != null ) // TODO user visibility to filter context list instead subfunction count. // if ( extHandle.getElement( ) // .getDefn( ) // .isPropertyVisible( method.getName( ) ) ) { returnList.add( method ); } } return returnList.toArray( ); } else if ( inputElement instanceof DesignElementHandle ) { DesignElementHandle eleHandle = (DesignElementHandle) inputElement; if ( eleHandle.getDefn( ) != null ) { // Add methods only // return eleHandle.getDefn( ).getMethods( ).toArray( ); return eleHandle.getMethods( ).toArray( ); } } return new Object[]{}; } public void dispose( ) { } public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { viewer.refresh( ); } public String getText( Object element ) { if ( element instanceof IPropertyDefn ) { IPropertyDefn eleDef = (IPropertyDefn) element; return eleDef.getName( ); } return NO_TEXT; } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) */ public Image getImage( Object element ) { return null; } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.IBaseLabelProvider#addListener(org.eclipse.jface.viewers.ILabelProviderListener) */ public void addListener( ILabelProviderListener listener ) { } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.IBaseLabelProvider#isLabelProperty(java.lang.Object, * java.lang.String) */ public boolean isLabelProperty( Object element, String property ) { return false; } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.IBaseLabelProvider#removeListener(org.eclipse.jface.viewers.ILabelProviderListener) */ public void removeListener( ILabelProviderListener listener ) { } } class JSSubFunctionListProvider implements IStructuredContentProvider, ILabelProvider, ISelectionChangedListener { protected static Logger logger = Logger.getLogger( JSSubFunctionListProvider.class.getName( ) ); // private static final String NO_TEXT = Messages.getString( // "JSEditor.Text.NoText" ); //$NON-NLS-1$; private JSEditor editor; public JSSubFunctionListProvider( JSEditor editor ) { this.editor = editor; } public Object[] getElements( Object inputElement ) { List elements = new ArrayList( ); if ( inputElement instanceof ExtendedItemHandle ) { int selectedIndex = editor.cmbExpList.getSelectionIndex( ); if ( selectedIndex >= 0 ) { String scriptName = editor.cmbExpList.getItem( editor.cmbExpList.getSelectionIndex( ) ); ExtendedItemHandle extHandle = (ExtendedItemHandle) inputElement; List methods = extHandle.getMethods( scriptName ); if ( methods != null ) { elements.add( 0, Messages.getString( "JSEditor.cmb.NewEventFunction" ) ); //$NON-NLS-1$ elements.addAll( methods ); } } } return elements.toArray( ); } public void dispose( ) { } public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { if ( newInput != null ) viewer.refresh( ); } public Image getImage( Object element ) { return null; } public String getText( Object element ) { if ( element instanceof IMethodInfo ) { IMethodInfo eleDef = (IMethodInfo) element; return " " + eleDef.getName( );//$NON-NLS-1$ } else if ( element instanceof String ) { return (String) element; } return ""; //$NON-NLS-1$ } public void addListener( ILabelProviderListener listener ) { } public boolean isLabelProperty( Object element, String property ) { return false; } public void removeListener( ILabelProviderListener listener ) { } public void selectionChanged( SelectionChangedEvent event ) { boolean isContextChange = false; if ( event.getSource( ) instanceof ComboViewer ) { isContextChange = JSEditor.VIEWER_CATEGORY_CONTEXT.equals( ( (ComboViewer) event.getSource( ) ).getData( JSEditor.VIEWER_CATEGORY_KEY ) ); } ISelection selection = event.getSelection( ); if ( selection != null ) { Object[] sel = ( (IStructuredSelection) selection ).toArray( ); if ( sel.length == 1 ) { if ( isContextChange ) { editor.cmbSubFunctionsViewer.refresh( ); int itemCount = editor.cmbSubFunctions.getItemCount( ); if ( itemCount > 0 ) { // select first element always editor.cmbSubFunctions.select( 0 ); } editor.cmbSubFunctions.setEnabled( itemCount > 0 ); } else { if ( sel[0] instanceof IMethodInfo ) { IMethodInfo methodInfo = (IMethodInfo) sel[0]; String signature = createSignature( methodInfo ); try { IScriptEditor viewer = editor.getScriptEditor( ); if ( viewer instanceof AbstractTextEditor ) { AbstractTextEditor editor = (AbstractTextEditor) viewer; IDocument doc = ( editor.getDocumentProvider( ) ).getDocument( viewer.getEditorInput( ) ); int length = doc.getLength( ); doc.replace( length, 0, signature ); editor.selectAndReveal( length + 1, signature.length( ) ); } editor.setIsModified( true ); } catch ( BadLocationException e ) { logger.log(Level.SEVERE, e.getMessage(),e); } editor.cmbSubFunctions.select( 0 ); } } } } } // create the signature to insert in the document: // function functionName(param1, param2){} private String createSignature( IMethodInfo info ) { StringBuffer signature = new StringBuffer( ); String javaDoc = info.getJavaDoc( ); if ( javaDoc != null && javaDoc.length( ) > 0 ) { signature.append( "\n" ); //$NON-NLS-1$ signature.append( info.getJavaDoc( ) ); } signature.append( "\nfunction " ); //$NON-NLS-1$ signature.append( info.getName( ) ); signature.append( '(' ); Iterator iter = info.argumentListIterator( ); if ( iter.hasNext( ) ) { // only one iteraration, we ignore overload cases for now // need to do multiple iterations if overloaded methods should be // supported IArgumentInfoList argumentList = (IArgumentInfoList) iter.next( ); for ( Iterator argumentIter = argumentList.argumentsIterator( ); argumentIter.hasNext( ); ) { IArgumentInfo argument = (IArgumentInfo) argumentIter.next( ); String type = argument.getType( ); // convert string to parameter name signature.append( JSEditor.convertToParameterName( type ) ); if ( argumentIter.hasNext( ) ) { signature.append( ", " );//$NON-NLS-1$ } } } signature.append( ")\n{\n}\n" ); //$NON-NLS-1$ return signature.toString( ); } }
UI/org.eclipse.birt.report.designer.ui.editors.schematic/src/org/eclipse/birt/report/designer/internal/ui/editors/script/JSEditor.java
/************************************************************************************* * Copyright (c) 2004, 2007 Actuate Corporation and others. * 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 * * Contributors: * Actuate Corporation - Initial implementation. ************************************************************************************/ package org.eclipse.birt.report.designer.internal.ui.editors.script; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.core.model.views.outline.ScriptElementNode; import org.eclipse.birt.report.designer.core.util.mediator.IColleague; import org.eclipse.birt.report.designer.core.util.mediator.request.ReportRequest; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.internal.ui.views.data.DataViewPage; import org.eclipse.birt.report.designer.internal.ui.views.data.DataViewTreeViewerPage; import org.eclipse.birt.report.designer.internal.ui.views.outline.DesignerOutlinePage; import org.eclipse.birt.report.designer.internal.ui.views.property.ReportPropertySheetPage; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.IReportGraphicConstants; import org.eclipse.birt.report.designer.ui.ReportPlatformUIImages; import org.eclipse.birt.report.designer.ui.views.ProviderFactory; import org.eclipse.birt.report.designer.ui.views.attributes.AttributeViewPage; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.ExtendedItemHandle; import org.eclipse.birt.report.model.api.ScriptDataSourceHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.metadata.IArgumentInfo; import org.eclipse.birt.report.model.api.metadata.IArgumentInfoList; import org.eclipse.birt.report.model.api.metadata.IClassInfo; import org.eclipse.birt.report.model.api.metadata.IElementPropertyDefn; import org.eclipse.birt.report.model.api.metadata.IMethodInfo; import org.eclipse.birt.report.model.api.metadata.IPropertyDefn; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.draw2d.ColorConstants; import org.eclipse.gef.ui.actions.ActionRegistry; import org.eclipse.gef.ui.views.palette.PalettePage; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextListener; import org.eclipse.jface.text.TextEvent; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.forms.editor.IFormPage; import org.eclipse.ui.part.EditorPart; import org.eclipse.ui.part.MultiPageEditorSite; import org.eclipse.ui.texteditor.AbstractTextEditor; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.ui.views.properties.IPropertySheetPage; /** * Main class of javaScript editor * */ public class JSEditor extends EditorPart implements IColleague { protected static Logger logger = Logger.getLogger( JSEditor.class.getName( ) ); private static final String NO_EXPRESSION = Messages.getString( "JSEditor.Display.NoExpression" ); //$NON-NLS-1$ static final String VIEWER_CATEGORY_KEY = "Category"; //$NON-NLS-1$ static final String VIEWER_CATEGORY_CONTEXT = "context"; //$NON-NLS-1$ private IEditorPart editingDomainEditor; Combo cmbExpList = null; Combo cmbSubFunctions = null; public ComboViewer cmbExprListViewer; IPropertyDefn cmbItemLastSelected = null; boolean editorUIEnabled = true; private Button butReset; private Button butValidate; /** the icon for validator, default hide */ private Label validateIcon = null; /** the tool bar pane */ private Composite controller = null; private Label ano; private final HashMap selectionMap = new HashMap( ); private boolean isModified; private Object editObject; /** * Palette page */ public TreeViewPalettePage palettePage = new TreeViewPalettePage( ); public ComboViewer cmbSubFunctionsViewer; /** the script editor, dosen't include controller. */ private final IScriptEditor scriptEditor = createScriptEditor( ); /** the script validator */ private ScriptValidator scriptValidator = null; /** the flag if the text listener is enabled. */ private boolean isTextListenerEnable = true; /** the listener for text chaged. */ private final ITextListener textListener = new ITextListener( ) { /* * (non-Javadoc) * * @see org.eclipse.jface.text.ITextListener#textChanged(org.eclipse.jface.text.TextEvent) */ public void textChanged( TextEvent event ) { if ( isTextListenerEnable ) { markDirty( ); } } }; /** * JSEditor - constructor */ public JSEditor( IEditorPart parent ) { super( ); this.editingDomainEditor = parent; setSite( parent.getEditorSite( ) ); } /** * Creates script editor, dosen't include controller * * @return a script editor */ protected IScriptEditor createScriptEditor( ) { return new ScriptEditor( ); } /** * @see AbstractTextEditor#doSave( IProgressMonitor ) */ public void doSave( IProgressMonitor monitor ) { saveModel( ); } public boolean isDirty( ) { return isCodeModified( ); } /* * (non-Javadoc) * * @see org.eclipse.ui.editors.text.TextEditor#isSaveAsAllowed() */ public boolean isSaveAsAllowed( ) { return true; } /** * disposes all color objects */ public void dispose( ) { // colorManager.dispose( ); // remove the mediator listener // SessionHandleAdapter.getInstance( ) // .getMediator( ) // .removeColleague( this ); selectionMap.clear( ); editingDomainEditor = null; super.dispose( ); // ( (ReportMultiPageEditorSite) getSite( ) ).dispose( ); ( (MultiPageEditorSite) getSite( ) ).dispose( ); } // Parameter names are constructed by taking the java class name // and make the first letter lowercase. // If there are more than 2 uppercase letters, it's shortened as the list of // those. For instance IChartScriptContext becomes icsc protected static String convertToParameterName( String fullName ) { // strip the full qualified name fullName = fullName.substring( fullName.lastIndexOf( '.' ) + 1 ); int upCase = 0; SortedMap caps = new TreeMap( ); for ( int i = 0; i < fullName.length( ); i++ ) { char character = fullName.charAt( i ); if ( Character.isUpperCase( character ) ) { upCase++; caps.put( new Integer( i ), new Integer( character ) ); } } if ( upCase > 2 ) { StringBuffer result = new StringBuffer( ); for ( Iterator iter = caps.values( ).iterator( ); iter.hasNext( ); ) { result.append( (char) ( (Integer) iter.next( ) ).intValue( ) ); } return result.toString( ).toLowerCase( ); } else return fullName.substring( 0, 1 ).toLowerCase( ) + fullName.substring( 1 ); } private void updateScriptContext( DesignElementHandle handle, String method ) { List args = DEUtil.getDesignElementMethodArgumentsInfo( handle, method ); JSSyntaxContext context = scriptEditor.getContext(); context.clear( ); for ( Iterator iter = args.iterator( ); iter.hasNext( ); ) { IArgumentInfo element = (IArgumentInfo) iter.next( ); String name = element.getName( ); String type = element.getType( ); // try load system class info first, if failed, then try extension // class info if ( !context.setVariable( name, type ) ) { context.setVariable( name, element.getClassType( ) ); } } if ( handle instanceof ExtendedItemHandle ) { ExtendedItemHandle exHandle = (ExtendedItemHandle) handle; List mtds = exHandle.getMethods( method ); // TODO implement better function-wise code assistant. if ( mtds != null && mtds.size( ) > 0 ) { for ( int i = 0; i < mtds.size( ); i++ ) { IMethodInfo mi = (IMethodInfo) mtds.get( i ); for ( Iterator itr = mi.argumentListIterator( ); itr.hasNext( ); ) { IArgumentInfoList ailist = (IArgumentInfoList) itr.next( ); for ( Iterator argItr = ailist.argumentsIterator( ); argItr.hasNext( ); ) { IArgumentInfo aiinfo = (IArgumentInfo) argItr.next( ); IClassInfo ci = aiinfo.getClassType( ); String name = convertToParameterName( ci.getName( ) ); context.setVariable( name, ci ); } } } } } } public void createPartControl( Composite parent ) { Composite child = this.initEditorLayout( parent ); // Script combo cmbExprListViewer = new ComboViewer( cmbExpList ); JSExpListProvider provider = new JSExpListProvider( ); cmbExprListViewer.setContentProvider( provider ); cmbExprListViewer.setLabelProvider( provider ); cmbExprListViewer.setData( VIEWER_CATEGORY_KEY, VIEWER_CATEGORY_CONTEXT ); // SubFunctions combo JSSubFunctionListProvider subProvider = new JSSubFunctionListProvider( this ); // also add subProvider as listener of expr viewer. cmbExprListViewer.addSelectionChangedListener( subProvider ); cmbSubFunctionsViewer = new ComboViewer( cmbSubFunctions ); cmbSubFunctionsViewer.setContentProvider( subProvider ); cmbSubFunctionsViewer.setLabelProvider( subProvider ); cmbSubFunctionsViewer.addSelectionChangedListener( subProvider ); // Initialize the model for the document. Object model = getModel( ); if ( model != null ) { cmbExpList.setVisible( true ); cmbSubFunctions.setVisible( true ); setComboViewerInput( model ); } else { setComboViewerInput( Messages.getString( "JSEditor.Input.trial" ) ); //$NON-NLS-1$ } cmbExprListViewer.addSelectionChangedListener( palettePage.getSupport( ) ); cmbExprListViewer.addSelectionChangedListener( new ISelectionChangedListener( ) { /** * selectionChanged( event) - This listener implementation is * invoked when an item in the combo box is selected, - It saves the * current editor contents. - Updates the editor content with the * expression corresponding to the selected method name or * expression. name. */ public void selectionChanged( SelectionChangedEvent event ) { ISelection selection = event.getSelection( ); if ( selection != null ) { Object[] sel = ( (IStructuredSelection) selection ).toArray( ); if ( sel.length == 1 ) { if ( sel[0] instanceof IPropertyDefn ) { // Save the current expression into the DE // using DE // API DesignElementHandle desHandle = (DesignElementHandle) cmbExprListViewer.getInput( ); saveModelIfNeeds( ); // Update the editor to display the // expression // corresponding to the selected // combo item ( method name/ expression name // ) IPropertyDefn elePropDefn = (IPropertyDefn) sel[0]; cmbItemLastSelected = elePropDefn; setTextListenerEnable( false ); setEditorText( desHandle.getStringProperty( elePropDefn.getName( ) ) ); setTextListenerEnable( true ); setIsModified( false ); selectionMap.put( getModel( ), selection ); String method = cmbItemLastSelected.getName( ); updateScriptContext( desHandle, method ); } } } } } ); scriptEditor.createPartControl( child ); scriptValidator = new ScriptValidator( getViewer( ) ); // suport the mediator SessionHandleAdapter.getInstance( ).getMediator( ).addColleague( this ); disableEditor( ); getViewer( ).addTextListener( textListener ); } /** * Sets the status of the text listener. * * @param enabled * <code>true</code> if enable, <code>false</code> otherwise. */ private void setTextListenerEnable( boolean enabled ) { isTextListenerEnable = enabled; } /** * Get current edit element, not report design model. * * @return */ public Object getModel( ) { // return cmbExprListViewer.getInput( ); return editObject; } private void updateAnnotationLabel( Object handle ) { String name = ProviderFactory.createProvider( handle ) .getNodeDisplayName( handle ); if ( name == null ) { ano.setText( "" ); //$NON-NLS-1$ } else { ano.setText( name ); } } /* * (non-Javadoc) * * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) */ public Object getAdapter( Class adapter ) { if ( adapter == ActionRegistry.class ) { return scriptEditor.getActionRegistry( ); } else if ( adapter == PalettePage.class ) { if ( cmbExprListViewer != null ) { cmbExprListViewer.addSelectionChangedListener( palettePage.getSupport( ) ); } return palettePage; } if ( adapter == IContentOutlinePage.class ) { // ( (NonGEFSynchronizerWithMutiPageEditor) // getSelectionSynchronizer( ) ).add( (NonGEFSynchronizer) // outlinePage.getAdapter( NonGEFSynchronizer.class ) ); // Add JS Editor as a selection listener to Outline view selections. // outlinePage.addSelectionChangedListener( jsEditor ); DesignerOutlinePage outlinePage = new DesignerOutlinePage( SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) ); return outlinePage; } // return the property sheet page if ( adapter == IPropertySheetPage.class ) { ReportPropertySheetPage sheetPage = new ReportPropertySheetPage( ); return sheetPage; } if ( adapter == DataViewPage.class ) { DataViewTreeViewerPage page = new DataViewTreeViewerPage( SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) ); return page; } if ( adapter == AttributeViewPage.class ) { AttributeViewPage page = new AttributeViewPage( ); return page; } return super.getAdapter( adapter ); } /** * * initEditorLayout - initialize the UI components of the editor * */ private Composite initEditorLayout( Composite parent ) { // Create the editor parent composite. Composite mainPane = new Composite( parent, SWT.NONE ); GridLayout layout = new GridLayout( ); layout.verticalSpacing = 0; mainPane.setLayout( layout ); controller = createController( mainPane ); // Create the code editor pane. Composite jsEditorContainer = new Composite( mainPane, SWT.NONE ); GridData gdata = new GridData( GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL ); jsEditorContainer.setLayoutData( gdata ); jsEditorContainer.setLayout( new FillLayout( ) ); return jsEditorContainer; } /** * Creates tool bar pane. * * @param parent * the parent of controller * @return a tool bar pane */ protected Composite createController( Composite parent ) { Composite barPane = new Composite( parent, SWT.NONE ); GridLayout layout = new GridLayout( 8, false ); GridData gdata = new GridData( GridData.FILL_HORIZONTAL ); barPane.setLayout( layout ); barPane.setLayoutData( gdata ); initScriptLabel( barPane ); initComboBoxes( barPane ); // Creates Reset button butReset = new Button( barPane, SWT.PUSH ); butReset.setText( Messages.getString( "JSEditor.Button.Reset" ) ); //$NON-NLS-1$ GridData layoutData = new GridData( ); layoutData.horizontalIndent = 6; butReset.setLayoutData( layoutData ); butReset.addSelectionListener( new SelectionListener( ) { public void widgetSelected( SelectionEvent e ) { setEditorText( "" ); //$NON-NLS-1$ markDirty( ); } public void widgetDefaultSelected( SelectionEvent e ) { widgetSelected( e ); } } ); // Creates Validate button butValidate = new Button( barPane, SWT.PUSH ); butValidate.setText( Messages.getString( "JSEditor.Button.Validate" ) ); //$NON-NLS-1$ layoutData = new GridData( ); layoutData.horizontalIndent = 6; butValidate.setLayoutData( layoutData ); butValidate.addSelectionListener( new SelectionAdapter( ) { /* * (non-Javadoc) * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) */ public void widgetSelected( SelectionEvent e ) { doValidate( ); } } ); // Creates Validate icon, default empty. validateIcon = new Label( barPane, SWT.NULL ); Label column = new Label( barPane, SWT.SEPARATOR | SWT.VERTICAL ); layoutData = new GridData( ); layoutData.heightHint = 20; layoutData.horizontalIndent = 10; column.setLayoutData( layoutData ); ano = new Label( barPane, 0 ); layoutData = new GridData( GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_CENTER ); ano.setLayoutData( layoutData ); final Composite sep = new Composite( parent, 0 ); layoutData = new GridData( GridData.FILL_HORIZONTAL ); layoutData.heightHint = 1; sep.setLayoutData( layoutData ); sep.addPaintListener( new PaintListener( ) { public void paintControl( PaintEvent e ) { GC gc = e.gc; Rectangle rect = sep.getBounds( ); gc.setForeground( ColorConstants.darkGray ); gc.drawLine( 0, 0, rect.width, 0 ); } } ); return barPane; } private void initScriptLabel( Composite parent ) { Label lblScript = new Label( parent, SWT.NONE ); lblScript.setText( Messages.getString( "JSEditor.Label.Script" ) ); //$NON-NLS-1$ final FontData fd = lblScript.getFont( ).getFontData( )[0]; Font labelFont = new Font( Display.getCurrent( ), fd.getName( ), fd.getHeight( ), SWT.BOLD ); lblScript.setFont( labelFont ); GridData layoutData = new GridData( SWT.BEGINNING ); lblScript.setLayoutData( layoutData ); } private void initComboBoxes( Composite parent ) { // Create the script combo box cmbExpList = new Combo( parent, SWT.READ_ONLY ); GridData layoutData = new GridData( GridData.BEGINNING ); layoutData.widthHint = 140; cmbExpList.setLayoutData( layoutData ); // Create the subfunction combo box cmbSubFunctions = new Combo( parent, SWT.DROP_DOWN | SWT.READ_ONLY ); cmbSubFunctions.setLayoutData( layoutData ); } /* * SelectionChanged. - Selection listener implementation for changes in * other views Selection of elements in other views, triggers this event. - * The code editor view is updated to show the methods corresponding to the * selected element. */ public void handleSelectionChanged( SelectionChangedEvent event ) { ISelection selection = event.getSelection( ); handleSelectionChanged( selection ); } public void handleSelectionChanged( ISelection selection ) { if ( editorUIEnabled == true ) { // save the previous editor content. // saveModelIfNeeds( ); saveModel( ); } if ( selection != null ) { Object[] sel = ( (IStructuredSelection) selection ).toArray( ); if ( sel.length == 1 ) { editObject = sel[0]; if ( sel[0] instanceof ScriptElementNode ) { editObject = ( (ScriptElementNode) editObject ).getParent( ); } } if ( editObject instanceof DesignElementHandle ) { // set the combo viewer input to the the selected element. palettePage.getSupport( ).setCurrentEditObject( editObject ); setComboViewerInput( editObject ); // clear the latest selected item. cmbItemLastSelected = null; try { setTextListenerEnable( false ); setEditorText( "" ); //$NON-NLS-1$ // enable/disable editor based on the items in the // expression list. if ( cmbExpList.getItemCount( ) > 0 ) { enableEditor( ); // Selects the first item in the expression list. selectItemInComboExpList( (ISelection) selectionMap.get( getModel( ) ) ); } else { disableEditor( ); } } finally { setTextListenerEnable( true ); } /* * if ( editObject instanceof ExtendedItemHandle ) { * setEditorText( ( (ExtendedItemHandle) editObject * ).getExternalScript( ) ); context.setVariable( "this", * "org.eclipse.birt.report.model.api.ExtendedItemHandle" ); * //$NON-NLS-1$ //$NON-NLS-2$ } */ checkDirty( ); palettePage.getSupport( ).updateParametersTree( ); } else { disableEditor( ); cmbExpList.removeAll( ); cmbSubFunctions.removeAll( ); cmbItemLastSelected = null; palettePage.getSupport( ).setCurrentEditObject( null ); } if ( sel.length > 0 ) { updateAnnotationLabel( sel[0] ); } } } private void checkDirty( ) { // ( (AbstractMultiPageLayoutEditor) editingDomainEditor ).checkDirty( // ); } private void selectItemInComboExpList( ISelection selection ) { ISelection sel = selection; if ( sel.isEmpty( ) && cmbExpList.getItemCount( ) > 0 ) { IPropertyDefn propDefn = (IPropertyDefn) cmbExprListViewer.getElementAt( 0 ); if ( propDefn != null ) { sel = new StructuredSelection( propDefn ); } } cmbExprListViewer.setSelection( sel ); return; } // /** // * selectItemInComboExpList - selects the specified input item in the // * expList - if input is null selects first item. // */ // private void selectItemInComboExpList( IPropertyDefn propDefn ) // { // if ( propDefn == null ) // { // if ( cmbExpList.getItemCount( ) > 0 ) // propDefn = (IPropertyDefn) this.cmbExprListViewer // .getElementAt( 0 ); // } // // if ( propDefn != null ) // selectItemInComboExpList( new StructuredSelection( propDefn ) ); // // } /** * setEditorText - sets the editor content. * * @param text */ private void setEditorText( String text ) { if ( scriptEditor == null ) { return; } scriptEditor.setScript( text ); if ( scriptValidator != null ) { scriptValidator.init( ); setValidateIcon( null, null ); } } /** * getEditorText() - gets the editor content. * */ private String getEditorText( ) { return scriptEditor.getScript( ); } /** * saveEditorContentsDE - saves the current editor contents to ROM using DE * API * * @param desHdl * @return true if updated else false. */ private boolean saveEditorContentsDE( DesignElementHandle desHdl ) { if ( desHdl != null && getEditorText( ) != null ) { try { if ( cmbItemLastSelected != null ) { desHdl.setStringProperty( cmbItemLastSelected.getName( ), getEditorText( ) ); } selectionMap.put( getModel( ), cmbExprListViewer.getSelection( ) ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); return false; } } return true; } /** * Saves input code to model * */ public void saveModel( ) { if ( isCodeModified( ) && editObject instanceof DesignElementHandle ) { saveEditorContentsDE( (DesignElementHandle) editObject ); } setIsModified( false ); } /** * @param b */ public void setIsModified( boolean b ) { isModified = b; } private boolean isCodeModified( ) { return isModified; } public void saveModelIfNeeds( ) { if ( checkEditorActive( ) ) { if ( isCodeModified( ) && editObject instanceof DesignElementHandle ) { saveEditorContentsDE( (DesignElementHandle) editObject ); } } } protected void markDirty( ) { if ( !isModified ) { setIsModified( true ); ( (IFormPage) editingDomainEditor ).getEditor( ) .editorDirtyStateChanged( ); firePropertyChange( PROP_DIRTY ); } } protected boolean checkEditorActive( ) { return true; } /** * Enables the editor UI components */ private void enableEditor( ) { if ( editorUIEnabled == false ) { getViewer( ).getTextWidget( ).setEnabled( true ); cmbExpList.setEnabled( true ); butReset.setEnabled( true ); butValidate.setEnabled( true ); editorUIEnabled = true; } setEditorText( "" ); //$NON-NLS-1$ } /** * Disables the editor UI components */ private void disableEditor( ) { if ( editorUIEnabled == true ) { getViewer( ).getTextWidget( ).setEnabled( false ); cmbExpList.setEnabled( false ); cmbSubFunctions.setEnabled( false ); butReset.setEnabled( false ); butValidate.setEnabled( false ); editorUIEnabled = false; } setEditorText( NO_EXPRESSION ); } /** * Gets source viewer in the editor * * @return source viewer */ public SourceViewer getViewer( ) { return (SourceViewer) scriptEditor.getViewer( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.core.util.mediator.IColleague#performRequest(org.eclipse.birt.report.designer.core.util.mediator.request.ReportRequest) */ public void performRequest( ReportRequest request ) { if ( ReportRequest.SELECTION.equals( request.getType( ) ) ) { handleSelectionChange( request.getSelectionModelList( ) ); } if ( ReportRequest.CREATE_ELEMENT.equals( request.getType( ) ) && request.getSelectionModelList( ).get( 0 ) instanceof ScriptDataSourceHandle ) { handleSelectionChange( request.getSelectionModelList( ) ); } } private void setComboViewerInput( Object model ) { cmbExprListViewer.setInput( model ); Object oldSelection = selectionMap.get( model ); if ( oldSelection == null ) { selectItemInComboExpList( new StructuredSelection( ) ); } else { selectItemInComboExpList( (ISelection) oldSelection ); } cmbSubFunctionsViewer.setInput( model ); int itemCount = cmbSubFunctions.getItemCount( ); if ( itemCount > 0 ) { cmbSubFunctions.select( 0 ); // select first element always } cmbSubFunctions.setEnabled( itemCount > 0 ); return; } private void setComboViewerInput( String message ) { cmbExprListViewer.setInput( message ); return; } /** * Reset the selection forcely. * * @param list */ public void handleSelectionChange( List list ) { if ( scriptEditor instanceof AbstractTextEditor ) { SelectionChangedEvent event = new SelectionChangedEvent( ( (AbstractTextEditor) scriptEditor ).getSelectionProvider( ), new StructuredSelection( list ) ); handleSelectionChanged( event ); } } /** * Returns the current script editor. * * @return the current script editor. */ protected IScriptEditor getScriptEditor( ) { return scriptEditor; } /** * Validates the contents of this editor. */ public void doValidate( ) { Image image = null; String message = null; if ( scriptValidator == null ) { return; } try { scriptValidator.validate( ); image = ReportPlatformUIImages.getImage( IReportGraphicConstants.ICON_SCRIPT_NOERROR ); message = Messages.getString( "JSEditor.Validate.NoError" ); } catch ( ParseException e ) { image = ReportPlatformUIImages.getImage( IReportGraphicConstants.ICON_SCRIPT_ERROR ); message = e.getLocalizedMessage( ); } finally { setValidateIcon( image, message ); setFocus( ); } } /** * Sets the validate icon with the specified image and tool tip text. * * * @param image * the icon image * @param tip * the tool tip text */ private void setValidateIcon( Image image, String tip ) { if ( validateIcon != null ) { validateIcon.setImage( image ); validateIcon.setToolTipText( tip ); if ( controller != null ) { controller.layout( ); } } } /* * (non-Javadoc) * * @see org.eclipse.ui.part.EditorPart#doSaveAs() */ public void doSaveAs( ) { scriptEditor.doSaveAs( ); } /* * (non-Javadoc) * * @see org.eclipse.ui.part.EditorPart#init(org.eclipse.ui.IEditorSite, org.eclipse.ui.IEditorInput) */ public void init( IEditorSite site, IEditorInput input ) throws PartInitException { setSite( site ); setInput( input ); scriptEditor.init( site, input ); } /* * (non-Javadoc) * * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ public void setFocus( ) { scriptEditor.setFocus( ); } } /** * class JSExpListProvider - Is the content and label provider for the * expression list * */ class JSExpListProvider implements IStructuredContentProvider, ILabelProvider { private static final String NO_TEXT = Messages.getString( "JSEditor.Text.NoText" ); //$NON-NLS-1$; public Object[] getElements( Object inputElement ) { if ( inputElement instanceof ExtendedItemHandle ) { ExtendedItemHandle extHandle = (ExtendedItemHandle) inputElement; List methods = extHandle.getMethods( ); List returnList = new ArrayList( ); for ( Iterator iter = methods.iterator( ); iter.hasNext( ); ) { IElementPropertyDefn method = (IElementPropertyDefn) iter.next( ); if ( extHandle.getMethods( method.getName( ) ) != null ) // TODO user visibility to filter context list instead subfunction count. // if ( extHandle.getElement( ) // .getDefn( ) // .isPropertyVisible( method.getName( ) ) ) { returnList.add( method ); } } return returnList.toArray( ); } else if ( inputElement instanceof DesignElementHandle ) { DesignElementHandle eleHandle = (DesignElementHandle) inputElement; if ( eleHandle.getDefn( ) != null ) { // Add methods only // return eleHandle.getDefn( ).getMethods( ).toArray( ); return eleHandle.getMethods( ).toArray( ); } } return new Object[]{}; } public void dispose( ) { } public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { viewer.refresh( ); } public String getText( Object element ) { if ( element instanceof IPropertyDefn ) { IPropertyDefn eleDef = (IPropertyDefn) element; return eleDef.getName( ); } return NO_TEXT; } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) */ public Image getImage( Object element ) { return null; } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.IBaseLabelProvider#addListener(org.eclipse.jface.viewers.ILabelProviderListener) */ public void addListener( ILabelProviderListener listener ) { } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.IBaseLabelProvider#isLabelProperty(java.lang.Object, * java.lang.String) */ public boolean isLabelProperty( Object element, String property ) { return false; } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.IBaseLabelProvider#removeListener(org.eclipse.jface.viewers.ILabelProviderListener) */ public void removeListener( ILabelProviderListener listener ) { } } class JSSubFunctionListProvider implements IStructuredContentProvider, ILabelProvider, ISelectionChangedListener { protected static Logger logger = Logger.getLogger( JSSubFunctionListProvider.class.getName( ) ); // private static final String NO_TEXT = Messages.getString( // "JSEditor.Text.NoText" ); //$NON-NLS-1$; private JSEditor editor; public JSSubFunctionListProvider( JSEditor editor ) { this.editor = editor; } public Object[] getElements( Object inputElement ) { List elements = new ArrayList( ); if ( inputElement instanceof ExtendedItemHandle ) { int selectedIndex = editor.cmbExpList.getSelectionIndex( ); if ( selectedIndex >= 0 ) { String scriptName = editor.cmbExpList.getItem( editor.cmbExpList.getSelectionIndex( ) ); ExtendedItemHandle extHandle = (ExtendedItemHandle) inputElement; List methods = extHandle.getMethods( scriptName ); if ( methods != null ) { elements.add( 0, Messages.getString( "JSEditor.cmb.NewEventFunction" ) ); //$NON-NLS-1$ elements.addAll( methods ); } } } return elements.toArray( ); } public void dispose( ) { } public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { if ( newInput != null ) viewer.refresh( ); } public Image getImage( Object element ) { return null; } public String getText( Object element ) { if ( element instanceof IMethodInfo ) { IMethodInfo eleDef = (IMethodInfo) element; return " " + eleDef.getName( );//$NON-NLS-1$ } else if ( element instanceof String ) { return (String) element; } return ""; //$NON-NLS-1$ } public void addListener( ILabelProviderListener listener ) { } public boolean isLabelProperty( Object element, String property ) { return false; } public void removeListener( ILabelProviderListener listener ) { } public void selectionChanged( SelectionChangedEvent event ) { boolean isContextChange = false; if ( event.getSource( ) instanceof ComboViewer ) { isContextChange = JSEditor.VIEWER_CATEGORY_CONTEXT.equals( ( (ComboViewer) event.getSource( ) ).getData( JSEditor.VIEWER_CATEGORY_KEY ) ); } ISelection selection = event.getSelection( ); if ( selection != null ) { Object[] sel = ( (IStructuredSelection) selection ).toArray( ); if ( sel.length == 1 ) { if ( isContextChange ) { editor.cmbSubFunctionsViewer.refresh( ); int itemCount = editor.cmbSubFunctions.getItemCount( ); if ( itemCount > 0 ) { // select first element always editor.cmbSubFunctions.select( 0 ); } editor.cmbSubFunctions.setEnabled( itemCount > 0 ); } else { if ( sel[0] instanceof IMethodInfo ) { IMethodInfo methodInfo = (IMethodInfo) sel[0]; String signature = createSignature( methodInfo ); try { IScriptEditor viewer = editor.getScriptEditor( ); if ( viewer instanceof AbstractTextEditor ) { AbstractTextEditor editor = (AbstractTextEditor) viewer; IDocument doc = ( editor.getDocumentProvider( ) ).getDocument( viewer.getEditorInput( ) ); int length = doc.getLength( ); doc.replace( length, 0, signature ); editor.selectAndReveal( length + 1, signature.length( ) ); } editor.setIsModified( true ); } catch ( BadLocationException e ) { logger.log(Level.SEVERE, e.getMessage(),e); } editor.cmbSubFunctions.select( 0 ); } } } } } // create the signature to insert in the document: // function functionName(param1, param2){} private String createSignature( IMethodInfo info ) { StringBuffer signature = new StringBuffer( ); String javaDoc = info.getJavaDoc( ); if ( javaDoc != null && javaDoc.length( ) > 0 ) { signature.append( "\n" ); //$NON-NLS-1$ signature.append( info.getJavaDoc( ) ); } signature.append( "\nfunction " ); //$NON-NLS-1$ signature.append( info.getName( ) ); signature.append( '(' ); Iterator iter = info.argumentListIterator( ); if ( iter.hasNext( ) ) { // only one iteraration, we ignore overload cases for now // need to do multiple iterations if overloaded methods should be // supported IArgumentInfoList argumentList = (IArgumentInfoList) iter.next( ); for ( Iterator argumentIter = argumentList.argumentsIterator( ); argumentIter.hasNext( ); ) { IArgumentInfo argument = (IArgumentInfo) argumentIter.next( ); String type = argument.getType( ); // convert string to parameter name signature.append( JSEditor.convertToParameterName( type ) ); if ( argumentIter.hasNext( ) ) { signature.append( ", " );//$NON-NLS-1$ } } } signature.append( ")\n{\n}\n" ); //$NON-NLS-1$ return signature.toString( ); } }
Append hideValidateButtonIcon() method.
UI/org.eclipse.birt.report.designer.ui.editors.schematic/src/org/eclipse/birt/report/designer/internal/ui/editors/script/JSEditor.java
Append hideValidateButtonIcon() method.
<ide><path>I/org.eclipse.birt.report.designer.ui.editors.schematic/src/org/eclipse/birt/report/designer/internal/ui/editors/script/JSEditor.java <ide> import org.eclipse.swt.widgets.Button; <ide> import org.eclipse.swt.widgets.Combo; <ide> import org.eclipse.swt.widgets.Composite; <add>import org.eclipse.swt.widgets.Control; <ide> import org.eclipse.swt.widgets.Display; <ide> import org.eclipse.swt.widgets.Label; <ide> import org.eclipse.ui.IEditorInput; <ide> } ); <ide> <ide> return barPane; <add> } <add> <add> /** <add> * Hides validate button & icon. <add> */ <add> protected void hideValidateButtonIcon( ) <add> { <add> hideControl( butValidate ); <add> hideControl( validateIcon ); <add> } <add> <add> /** <add> * Hides a control from its parent composite. <add> * <add> * @param control <add> * the control to hide <add> */ <add> private void hideControl( Control control ) <add> { <add> Object layoutData = control.getLayoutData( ); <add> <add> if ( layoutData == null ) <add> { <add> layoutData = new GridData( ); <add> control.setLayoutData( layoutData ); <add> } <add> <add> if ( layoutData instanceof GridData ) <add> { <add> GridData gridData = (GridData) layoutData; <add> <add> gridData.exclude = true; <add> control.setLayoutData( gridData ); <add> control.setVisible( false ); <add> } <ide> } <ide> <ide> private void initScriptLabel( Composite parent )
JavaScript
mit
51418c8c9ff4dfcede36ec94baa82e07956bab2d
0
GroganBurners/ferveo,GroganBurners/ferveo,GroganBurners/ferveo
var mongoose = require("mongoose"); //mongoose.Promise = global.Promise; // ES6 mongoose.Promise = require('bluebird'); var Price = require('../models/price'); //Require the dev-dependencies var chai = require('chai'); var chaiHttp = require('chai-http'); var server = require('../app'); var should = chai.should(); var assert = chai.assert; describe('Test Prices API', function () { beforeEach(function (done) { //Before each test we empty the database Price.remove({}, function (err) { done(); }); }); it('it should GET all the prices (none in DB)', function (done) { chai.request(server) .get('/api/prices') .end(function (err, res) { res.should.have.status(200); res.body.should.be.a('array'); res.body.length.should.be.eql(0); done(); }); }); it('it should GET all the prices (one in DB)', function (done) { var pri = new Price({ name: "Gas Service" }); pri.save(function (err, price) { chai.request(server) .get('/api/prices') .end(function (err, res) { res.should.have.status(200); res.body.should.be.a('array'); res.body.length.should.be.eql(1); done(); }); }); }); it('it should GET all the prices (multiple in DB)', function (done) { var pr1 = new Price({ name: "Gas Service" }); var pr2 = new Price({ name: "Oil Service" }); Price.create(pr1, pr2, function (err, pr1, pr2) { chai.request(server) .get('/api/prices') .end(function (err, res) { res.should.have.status(200); res.body.should.be.a('array'); res.body.length.should.be.eql(2); done(); }); }); }); it('it should POST a price with just a name', function (done) { var pri = { name: "Gas Service" } chai.request(server) .post('/api/prices') .send(pri) .end(function (err, res) { res.should.have.status(200); res.body.should.be.a('object'); res.body.should.have.property('message').eql('Successfully created'); done(); }); }); it('it should POST a price with junk property and it\'s not persisted', function (done) { var pri = { name: "Gas Service", fake_property: "ignored" } chai.request(server) .post('/api/prices') .send(pri) .end(function (err, res) { res.should.have.status(200); res.body.should.be.a('object'); res.body.should.have.property('message').eql('Successfully created'); res.body.should.have.property('price'); res.body.price.should.have.property('name').eql('Gas Service'); res.body.price.should.not.have.property('fake_property'); done(); }); }); it('it should POST a price with same name and it\'s an error', function (done) { var pri = new Price({ name: "Gas Service" }); var pr2 = { name: "Gas Service" }; pri.save(function (err, price) { chai.request(server) .post('/api/prices') .send(pr2) .end(function (err, res) { res.should.have.status(409); res.body.should.be.a('object'); res.body.should.have.property('message').eql('Price Already Exists'); done(); }); }); }); it('it should GET a price by the given id', function (done) { var pr = new Price({ name: "Oil Price" }); pr.save(function (err, price) { pri = new Price(price._doc) chai.request(server) .get('/api/prices/' + pri._id.toString()) .send(price) .end(function (err, res) { res.should.have.status(200); res.body.should.be.a('object'); res.body.should.have.property('price'); res.body.should.have.property('name'); res.body.should.have.property('_id').eql(price._id.toString()); done(); }); }); }); it('it should fail to GET a price by non-existing id', function (done) { chai.request(server) .get('/api/prices/' + 'non-existing-id') .send({}) .end(function (err, res) { res.should.have.status(404); res.body.should.be.a('object'); res.body.should.have.property('message').eql('Error getting price'); done(); }); }); it('it should UPDATE a price by the given id', function (done) { var pr = new Price({ name: "Gas Fire Price" }); pr.save(function (err, price) { var pri = { name: "Gas Fire Price Updated", _id: price._doc._id } chai.request(server) .put('/api/prices/' + pri._id) .send(pri) .end(function (err, res) { console.log(res) res.should.have.status(200); res.body.should.be.a('object'); res.body.price.should.have.property('_id').eql(pri._id.toString()); res.body.price.should.have.property('name').eql('Gas Fire Price Updated'); res.body.should.have.property('message').eql('Successfully updated price'); done(); }); }); }); it('it should fail to UPDATE a price with a non existant id', function (done) { var pr = { name: "Gas Fire Price" }; chai.request(server) .put('/api/prices/' + 'non-existant-id') .send(pr) .end(function (err, res) { res.should.have.status(404); res.body.should.be.a('object'); res.body.should.have.property('message').eql('Error updating price'); done(); }); }); it('it should DELETE a price by the given id', function (done) { var pr = new Price({ name: "Gas Fire Price" }); pr.save(function (err, price) { pri = new Price(price._doc) chai.request(server) .delete('/api/prices/' + price._id) .send(price) .end(function (err, res) { res.should.have.status(200); res.body.should.be.a('object'); res.body.should.have.property('message').eql('Successfully deleted'); res.body.price.should.have.property('name').eql('Gas Fire Price'); done(); }); }); }); it('it should try to DELETE a price by non-existing id', function (done) { chai.request(server) .delete('/api/prices/' + 'non-existing-id') .send({}) .end(function (err, res) { res.should.have.status(404); res.body.should.be.a('object'); res.body.should.have.property('message').eql('Error deleting price'); done(); }); }); });
test/price.js
var mongoose = require("mongoose"); //mongoose.Promise = global.Promise; // ES6 mongoose.Promise = require('bluebird'); var Price = require('../models/price'); //Require the dev-dependencies var chai = require('chai'); var chaiHttp = require('chai-http'); var server = require('../app'); var should = chai.should(); var assert = chai.assert; describe('Test Prices API', function () { beforeEach(function (done) { //Before each test we empty the database Price.remove({}, function (err) { done(); }); }); it('it should GET all the prices (none in DB)', function (done) { chai.request(server) .get('/api/prices') .end(function (err, res) { res.should.have.status(200); res.body.should.be.a('array'); res.body.length.should.be.eql(0); done(); }); }); it('it should GET all the prices (one in DB)', function (done) { var pri = new Price({ name: "Gas Service" }); pri.save(function (err, price) { chai.request(server) .get('/api/prices') .end(function (err, res) { res.should.have.status(200); res.body.should.be.a('array'); res.body.length.should.be.eql(1); done(); }); }); }); it('it should GET all the prices (multiple in DB)', function (done) { var pr1 = new Price({ name: "Gas Service" }); var pr2 = new Price({ name: "Oil Service" }); Price.create(pr1, pr2, function (err, pr1, pr2) { chai.request(server) .get('/api/prices') .end(function (err, res) { res.should.have.status(200); res.body.should.be.a('array'); res.body.length.should.be.eql(2); done(); }); }); }); it('it should POST a price with just a name', function (done) { var pri = { name: "Gas Service" } chai.request(server) .post('/api/prices') .send(pri) .end(function (err, res) { res.should.have.status(200); res.body.should.be.a('object'); res.body.should.have.property('message').eql('Successfully created'); done(); }); }); it('it should POST a price with junk property and it\'s not persisted', function (done) { var pri = { name: "Gas Service", fake_property: "ignored" } chai.request(server) .post('/api/prices') .send(pri) .end(function (err, res) { res.should.have.status(200); res.body.should.be.a('object'); res.body.should.have.property('message').eql('Successfully created'); res.body.should.have.property('price'); res.body.price.should.have.property('name').eql('Gas Service'); res.body.price.should.not.have.property('fake_property'); done(); }); }); it('it should POST a price with same name and it\'s an error', function (done) { var pri = new Price({ name: "Gas Service" }); var pr2 = { name: "Gas Service" }; pri.save(function (err, price) { chai.request(server) .post('/api/prices') .send(pr2) .end(function (err, res) { res.should.have.status(409); res.body.should.be.a('object'); res.body.should.have.property('message').eql('Price Already Exists'); done(); }); }); }); it('it should GET a price by the given id', function (done) { var pr = new Price({ name: "Oil Price" }); pr.save(function (err, price) { pri = new Price(price._doc) chai.request(server) .get('/api/prices/' + price._id) .send(price) .end(function (err, res) { console.log(res) res.should.have.status(200); res.body.should.be.a('object'); res.body.should.have.property('price'); res.body.should.have.property('name'); res.body.should.have.property('_id').eql(price._id.toString()); done(); }); }); }); it('it should fail to GET a price by non-existing id', function (done) { chai.request(server) .get('/api/prices/' + 'non-existing-id') .send({}) .end(function (err, res) { res.should.have.status(404); res.body.should.be.a('object'); res.body.should.have.property('message').eql('Error getting price'); done(); }); }); it('it should UPDATE a price by the given id', function (done) { var pr = new Price({ name: "Gas Fire Price" }); pr.save(function (err, price) { var pri = price._doc chai.request(server) .put('/api/prices/' + price._id) .send(pri) .end(function (err, res) { res.should.have.status(200); res.body.should.be.a('object'); res.body.price.should.have.property('_id').eql(pri._id.toString()); res.body.price.should.have.property('name').eql('Gas Fire Price'); res.body.should.have.property('message').eql('Successfully updated price'); done(); }); }); }); it('it should fail to UPDATE a price with a non existant id', function (done) { var pr = { name: "Gas Fire Price" }; chai.request(server) .put('/api/prices/' + 'non-existant-id') .send(pr) .end(function (err, res) { res.should.have.status(404); res.body.should.be.a('object'); res.body.should.have.property('message').eql('Error updating price'); done(); }); }); it('it should DELETE a price by the given id', function (done) { var pr = new Price({ name: "Gas Fire Price" }); pr.save(function (err, price) { pri = new Price(price._doc) chai.request(server) .delete('/api/prices/' + price._id) .send(price) .end(function (err, res) { res.should.have.status(200); res.body.should.be.a('object'); res.body.should.have.property('message').eql('Successfully deleted'); res.body.price.should.have.property('name').eql('Gas Fire Price'); done(); }); }); }); it('it should try to DELETE a price by non-existing id', function (done) { chai.request(server) .delete('/api/prices/' + 'non-existing-id') .send({}) .end(function (err, res) { res.should.have.status(404); res.body.should.be.a('object'); res.body.should.have.property('message').eql('Error deleting price'); done(); }); }); });
Adding logging for failing tests
test/price.js
Adding logging for failing tests
<ide><path>est/price.js <ide> pr.save(function (err, price) { <ide> pri = new Price(price._doc) <ide> chai.request(server) <del> .get('/api/prices/' + price._id) <add> .get('/api/prices/' + pri._id.toString()) <ide> .send(price) <ide> .end(function (err, res) { <del> console.log(res) <ide> res.should.have.status(200); <ide> res.body.should.be.a('object'); <ide> res.body.should.have.property('price'); <ide> var pr = new Price({ name: "Gas Fire Price" }); <ide> <ide> pr.save(function (err, price) { <del> var pri = price._doc <del> chai.request(server) <del> .put('/api/prices/' + price._id) <add> var pri = { name: "Gas Fire Price Updated", _id: price._doc._id } <add> chai.request(server) <add> .put('/api/prices/' + pri._id) <ide> .send(pri) <ide> .end(function (err, res) { <add> console.log(res) <ide> res.should.have.status(200); <ide> res.body.should.be.a('object'); <ide> res.body.price.should.have.property('_id').eql(pri._id.toString()); <del> res.body.price.should.have.property('name').eql('Gas Fire Price'); <add> res.body.price.should.have.property('name').eql('Gas Fire Price Updated'); <ide> res.body.should.have.property('message').eql('Successfully updated price'); <ide> done(); <ide> });
Java
lgpl-2.1
456aedc6d18f613d25697b699b795207fa48bcd6
0
melqkiades/yelp,melqkiades/yelp,melqkiades/yelp,melqkiades/yelp
package org.insightcentre.richcontext; import net.recommenders.rival.core.DataModel; import net.recommenders.rival.core.DataModelFactory; import net.recommenders.rival.core.DataModelIF; import net.recommenders.rival.core.DataModelUtils; import net.recommenders.rival.evaluation.metric.error.MAE; import net.recommenders.rival.evaluation.metric.error.RMSE; import net.recommenders.rival.evaluation.metric.ranking.NDCG; import net.recommenders.rival.evaluation.metric.ranking.Precision; import net.recommenders.rival.evaluation.metric.ranking.Recall; import net.recommenders.rival.evaluation.strategy.EvaluationStrategy; import net.recommenders.rival.evaluation.strategy.RelPlusN; import net.recommenders.rival.evaluation.strategy.TestItems; import net.recommenders.rival.evaluation.strategy.UserTest; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; /** * Created by fpena on 05/09/2017. */ public class RichContextResultsProcessor { private int numFolds; private int at; private int additionalItems; private int numTopics; private double relevanceThreshold; private long seed; private Strategy strategy; private ContextFormat contextFormat; private Dataset dataset; private String outputFile; private boolean coldStart; private String ratingsFolderPath; private final String[] headers; private static final String RATING = "rating"; private static final String RANKING = "ranking"; public enum EvaluationSet { TRAIN_USERS, TEST_USERS, TEST_ONLY_USERS, TRAIN_ONLY_USERS, } private EvaluationSet evaluationSet; public enum Strategy { ALL_ITEMS(RATING), REL_PLUS_N(RANKING), TEST_ITEMS(RATING), TRAIN_ITEMS(RATING), USER_TEST(RATING); private final String predictionType; Strategy(String predictionType) { this.predictionType = predictionType; } public String getPredictionType() { return predictionType; } } public enum ContextFormat { NO_CONTEXT, CONTEXT_TOPIC_WEIGHTS, TOP_WORDS, PREDEFINED_CONTEXT, TOPIC_PREDEFINED_CONTEXT } public enum Dataset { YELP_HOTEL, YELP_RESTAURANT, FOURCITY_HOTEL, } public enum ProcessingTask { PREPARE_LIBFM, PROCESS_LIBFM_RESULTS, EVALUATE_LIBFM_RESULTS } public RichContextResultsProcessor( String cacheFolder, String outputFolder, String propertiesFile, EvaluationSet evaluationSet, Integer paramNumTopics, String itemType) throws IOException { Properties properties = Properties.loadProperties(propertiesFile); numFolds = properties.getCrossValidationNumFolds(); at = properties.getTopN(); relevanceThreshold = properties.getRelevanceThreshold(); seed = properties.getSeed(); strategy = Strategy.valueOf( (properties.getStrategy().toUpperCase(Locale.ENGLISH))); additionalItems = properties.getTopnNumItems(); contextFormat = RichContextResultsProcessor.ContextFormat.valueOf( properties.getContextFormat().toUpperCase(Locale.ENGLISH)); dataset = (itemType == null) ? RichContextResultsProcessor.Dataset.valueOf( properties.getDataset().toUpperCase(Locale.ENGLISH)) : RichContextResultsProcessor.Dataset.valueOf( itemType.toUpperCase(Locale.ENGLISH)); numTopics = (paramNumTopics == null) ? properties.getNumTopics() : paramNumTopics; coldStart = properties.getEvaluateColdStart(); outputFile = outputFolder + "rival_" + dataset.toString().toLowerCase() + "_results_folds_4.csv"; String jsonRatingsFile = cacheFolder + dataset.toString().toLowerCase() + "_recsys_formatted_context_records_ensemble_" + "numtopics-" + numTopics + "_iterations-100_passes-10_targetreview-specific_" + "normalized_contextformat-" + contextFormat.toString().toLowerCase() + "_lang-en_bow-NN_document_level-review_targettype-context_" + "min_item_reviews-10.json"; this.evaluationSet = evaluationSet; this.ratingsFolderPath = Utils.getRatingsFolderPath(jsonRatingsFile); headers = new String[] { "Algorithm", "Dataset", "Num_Topics", "Strategy", "Context_Format", "Cold-start", "NDCG@" + at, "Precision@" + at, "Recall@" + at, "RMSE", "MAE", "fold_0_ndcg", "fold_1_ndcg", "fold_2_ndcg", "fold_3_ndcg", "fold_4_ndcg", "fold_0_precision", "fold_1_precision", "fold_2_precision", "fold_3_precision", "fold_4_precision", "fold_0_recall", "fold_1_recall", "fold_2_recall", "fold_3_recall", "fold_4_recall", "fold_0_rmse", "fold_1_rmse", "fold_2_rmse", "fold_3_rmse", "fold_4_rmse", "fold_0_mae", "fold_1_mae", "fold_2_mae", "fold_3_mae", "fold_4_mae", }; } public String getOutputFile() { return outputFile; } public String[] getHeaders() { return headers; } /** * Takes the file generated by the recommender which stores the predictions * and parses the results, generating another file that is RiVal compatible */ private void parseRecommendationResultsLibfm() throws IOException, InterruptedException { System.out.println("Parse Recommendation Results LibFM"); for (int fold = 0; fold < numFolds; fold++) { // Collect the results from the recommender String foldPath = ratingsFolderPath + "fold_" + fold + "/"; // String testFile = foldPath + "test.csv"; String predictionsFile; String libfmResultsFile = foldPath + "libfm_results_" + strategy.getPredictionType() + ".txt"; // Results will be stored in this file, which is RiVal compatible String rivalRecommendationsFile = ratingsFolderPath + "fold_" + fold + "/recs_libfm_" + strategy.getPredictionType() + ".csv"; switch (strategy) { case TEST_ITEMS: case USER_TEST: predictionsFile = foldPath + "test.csv"; LibfmResultsParser.parseResults( predictionsFile, libfmResultsFile, false, rivalRecommendationsFile); break; case REL_PLUS_N: predictionsFile = foldPath + "predictions.csv"; LibfmResultsParser.parseResults( predictionsFile, libfmResultsFile, true, rivalRecommendationsFile); break; default: String msg = strategy.toString() + " evaluation strategy not supported"; throw new UnsupportedOperationException(msg); } System.out.println("Recommendations file name: " + rivalRecommendationsFile); } } /** * Prepares the strategy file to be used by Rival * * @param algorithm the algorithm used to make the predictions */ private void prepareStrategy(String algorithm) throws IOException { System.out.println("Prepare Rating Strategy"); for (int i = 0; i < numFolds; i++) { String foldPath = ratingsFolderPath + "fold_" + i + "/"; File trainingFile = new File(foldPath + "train.csv"); File testFile = new File(foldPath + "test.csv"); File recFile = new File(foldPath + "recs_" + algorithm + "_" + strategy.getPredictionType() + ".csv"); DataModelIF<Long, Long> trainingModel; DataModelIF<Long, Long> testModel; DataModelIF<Long, Long> recModel; System.out.println("Parsing Training Model"); trainingModel = new CsvParser().parseData(trainingFile); System.out.println("Parsing Test Model"); testModel = new CsvParser().parseData(testFile); System.out.println("Parsing Recommendation Model"); recModel = new CsvParser().parseData(recFile); EvaluationStrategy<Long, Long> evaluationStrategy; switch (strategy) { case TEST_ITEMS: evaluationStrategy = new TestItems( (DataModel)trainingModel, (DataModel)testModel, relevanceThreshold); break; case USER_TEST: evaluationStrategy = new UserTest( (DataModel)trainingModel, (DataModel)testModel, relevanceThreshold); break; case REL_PLUS_N: evaluationStrategy = new RelPlusN( trainingModel, testModel, additionalItems, relevanceThreshold, seed); break; default: String msg = strategy.toString() + " evaluation strategy not supported for rating"; throw new UnsupportedOperationException(msg); } DataModelIF<Long, Long> modelToEval = DataModelFactory.getDefaultModel(); for (Long user : recModel.getUsers()) { for (Long item : evaluationStrategy.getCandidateItemsToRank(user)) { if (!Double.isNaN(recModel.getUserItemPreference(user, item))) { modelToEval.addPreference(user, item, recModel.getUserItemPreference(user, item)); } } } DataModelUtils.saveDataModel( modelToEval, foldPath + "strategymodel_" + algorithm + "_" + strategy.toString().toLowerCase() + ".csv", true, "\t"); } } /** * Evaluates the performance of the recommender system indicated by the * {@code algorithm} parameter. This method requires that the strategy files * are already generated * * @param algorithm the algorithm used to make the predictions * @return a {@link Map} with the hyperparameters of the algorithm and the * performance metrics. */ private Map<String, String> evaluate(String algorithm) throws IOException { System.out.println("Evaluate"); double ndcgRes = 0.0; double recallRes = 0.0; double precisionRes = 0.0; double rmseRes = 0.0; double maeRes = 0.0; Map<String, String> results = new HashMap<>(); for (int i = 0; i < numFolds; i++) { String foldPath = ratingsFolderPath + "fold_" + i + "/"; File testFile = new File(foldPath + "test.csv"); String strategyFileName = foldPath + "strategymodel_" + algorithm + "_" + strategy.toString().toLowerCase() + ".csv"; File strategyFile = new File(strategyFileName); DataModelIF<Long, Long> testModel = new CsvParser().parseData(testFile); DataModelIF<Long, Long> recModel; switch (strategy) { case TEST_ITEMS: case USER_TEST: recModel = new CsvParser().parseData(strategyFile); break; case REL_PLUS_N: File trainingFile = new File(foldPath + "train.csv"); DataModelIF<Long, Long> trainModel = new CsvParser().parseData(trainingFile); Set<Long> trainUsers = new HashSet<>(); for (Long user : trainModel.getUsers()) { trainUsers.add(user); } System.out.println("Num train users = " + trainUsers.size()); Set<Long> testUsers = new HashSet<>(); for (Long user : testModel.getUsers()) { testUsers.add(user); } System.out.println("Num test users = " + testUsers.size()); Set<Long> users; System.out.println("Evaluation set: " + evaluationSet); switch (evaluationSet) { case TEST_USERS: users = testUsers; break; case TRAIN_USERS: users = trainUsers; break; case TEST_ONLY_USERS: testUsers.removeAll(trainUsers); users = testUsers; break; case TRAIN_ONLY_USERS: trainUsers.removeAll(testUsers); users = trainUsers; break; default: String msg = "Evaluation set " + evaluationSet + " not supported"; throw new UnsupportedOperationException(msg); } recModel = new CsvParser().parseData(strategyFile, users); // recModel = new CsvParser().parseData(strategyFile); break; default: throw new UnsupportedOperationException( strategy.toString() + " evaluation Strategy not supported"); } NDCG<Long, Long> ndcg = new NDCG<>(recModel, testModel, new int[]{at}); ndcg.compute(); ndcgRes += ndcg.getValueAt(at); results.put("fold_" + i + "_ndcg", String.valueOf(ndcg.getValueAt(at))); Recall<Long, Long> recall = new Recall<>( recModel, testModel, relevanceThreshold, new int[]{at}); recall.compute(); recallRes += recall.getValueAt(at); results.put("fold_" + i + "_recall", String.valueOf(recall.getValueAt(at))); RMSE<Long, Long> rmse = new RMSE<>(recModel, testModel); rmse.compute(); rmseRes += rmse.getValue(); results.put("fold_" + i + "_rmse", String.valueOf(rmse.getValue())); MAE<Long, Long> mae = new MAE<>(recModel, testModel); mae.compute(); maeRes += mae.getValue(); results.put("fold_" + i + "_mae", String.valueOf(mae.getValue())); Precision<Long, Long> precision = new Precision<>( recModel, testModel, relevanceThreshold, new int[]{at}); precision.compute(); precisionRes += precision.getValueAt(at); results.put("fold_" + i + "_precision", String.valueOf(precision.getValueAt(at))); } results.put("Dataset", dataset.toString()); results.put("Algorithm", algorithm); results.put("Num_Topics", String.valueOf(numTopics)); results.put("Strategy", strategy.toString()); results.put("Context_Format", contextFormat.toString()); results.put("Cold-start", String.valueOf(coldStart)); results.put("NDCG@" + at, String.valueOf(ndcgRes / numFolds)); results.put("Precision@" + at, String.valueOf(precisionRes / numFolds)); results.put("Recall@" + at, String.valueOf(recallRes / numFolds)); results.put("RMSE", String.valueOf(rmseRes / numFolds)); results.put("MAE", String.valueOf(maeRes / numFolds)); System.out.println("Dataset: " + dataset.toString()); System.out.println("Algorithm: " + algorithm); System.out.println("Num Topics: " + numTopics); System.out.println("Strategy: " + strategy.toString()); System.out.println("Context_Format: " + contextFormat.toString()); System.out.println("Cold-start: " + coldStart); System.out.println("NDCG@" + at + ": " + ndcgRes / numFolds); System.out.println("Precision@" + at + ": " + precisionRes / numFolds); System.out.println("Recall@" + at + ": " + recallRes / numFolds); System.out.println("RMSE: " + rmseRes / numFolds); System.out.println("MAE: " + maeRes / numFolds); return results; } /** * Runs the whole evaluation cycle starting after the recommendations have * been done. * * @param cacheFolder the folder that contains the dataset to be evaluated * @param outputFolder the folder where the results are going to be exported * @param propertiesFile the file that contains the hyperparameters for the * recommender * @param evaluationSet an enum that indicates which users are going to be * in the evaluation set. The possible values are: * {@code TRAIN_USERS, TEST_USERS, TRAIN_ONLY_USERS, TEST_ONLY_USERS} */ public static void processLibfmResults( String cacheFolder, String outputFolder, String propertiesFile, EvaluationSet evaluationSet, Integer numTopics, String itemType) throws IOException, InterruptedException { RichContextResultsProcessor evaluator = new RichContextResultsProcessor( cacheFolder, outputFolder, propertiesFile, evaluationSet, numTopics, itemType); evaluator.parseRecommendationResultsLibfm(); evaluator.prepareStrategy("libfm"); Map<String, String> results = evaluator.evaluate("libfm"); List<Map<String, String>> resultsList = new ArrayList<>(); resultsList.add(results); Utils.writeResultsToFile( resultsList, evaluator.getOutputFile(), evaluator.getHeaders()); } }
source/java/richcontext/src/main/java/org/insightcentre/richcontext/RichContextResultsProcessor.java
package org.insightcentre.richcontext; import net.recommenders.rival.core.DataModel; import net.recommenders.rival.core.DataModelFactory; import net.recommenders.rival.core.DataModelIF; import net.recommenders.rival.core.DataModelUtils; import net.recommenders.rival.evaluation.metric.error.MAE; import net.recommenders.rival.evaluation.metric.error.RMSE; import net.recommenders.rival.evaluation.metric.ranking.NDCG; import net.recommenders.rival.evaluation.metric.ranking.Precision; import net.recommenders.rival.evaluation.metric.ranking.Recall; import net.recommenders.rival.evaluation.strategy.EvaluationStrategy; import net.recommenders.rival.evaluation.strategy.RelPlusN; import net.recommenders.rival.evaluation.strategy.TestItems; import net.recommenders.rival.evaluation.strategy.UserTest; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; /** * Created by fpena on 05/09/2017. */ public class RichContextResultsProcessor { private int numFolds; private int at; private int additionalItems; private int numTopics; private double relevanceThreshold; private long seed; private Strategy strategy; private ContextFormat contextFormat; private Dataset dataset; private String outputFile; private boolean coldStart; private String ratingsFolderPath; private final String[] headers; private static final String RATING = "rating"; private static final String RANKING = "ranking"; public enum EvaluationSet { TRAIN_USERS, TEST_USERS, TEST_ONLY_USERS, TRAIN_ONLY_USERS, } private EvaluationSet evaluationSet; public enum Strategy { ALL_ITEMS(RATING), REL_PLUS_N(RANKING), TEST_ITEMS(RATING), TRAIN_ITEMS(RATING), USER_TEST(RATING); private final String predictionType; Strategy(String predictionType) { this.predictionType = predictionType; } public String getPredictionType() { return predictionType; } } public enum ContextFormat { NO_CONTEXT, CONTEXT_TOPIC_WEIGHTS, TOP_WORDS, PREDEFINED_CONTEXT, TOPIC_PREDEFINED_CONTEXT } public enum Dataset { YELP_HOTEL, YELP_RESTAURANT, FOURCITY_HOTEL, } public enum ProcessingTask { PREPARE_LIBFM, PROCESS_LIBFM_RESULTS, EVALUATE_LIBFM_RESULTS } public RichContextResultsProcessor( String cacheFolder, String outputFolder, String propertiesFile, EvaluationSet evaluationSet, Integer paramNumTopics, String itemType) throws IOException { Properties properties = Properties.loadProperties(propertiesFile); numFolds = properties.getCrossValidationNumFolds(); at = properties.getTopN(); relevanceThreshold = properties.getRelevanceThreshold(); seed = properties.getSeed(); strategy = Strategy.valueOf( (properties.getStrategy().toUpperCase(Locale.ENGLISH))); additionalItems = properties.getTopnNumItems(); contextFormat = RichContextResultsProcessor.ContextFormat.valueOf( properties.getContextFormat().toUpperCase(Locale.ENGLISH)); dataset = (itemType == null) ? RichContextResultsProcessor.Dataset.valueOf( properties.getDataset().toUpperCase(Locale.ENGLISH)) : RichContextResultsProcessor.Dataset.valueOf( itemType.toUpperCase(Locale.ENGLISH)); numTopics = (paramNumTopics == null) ? properties.getNumTopics() : paramNumTopics; coldStart = properties.getEvaluateColdStart(); outputFile = outputFolder + "rival_" + dataset.toString() + "_results_folds_4.csv"; String jsonRatingsFile = cacheFolder + dataset.toString().toLowerCase() + "_recsys_formatted_context_records_ensemble_" + "numtopics-" + numTopics + "_iterations-100_passes-10_targetreview-specific_" + "normalized_contextformat-" + contextFormat.toString().toLowerCase() + "_lang-en_bow-NN_document_level-review_targettype-context_" + "min_item_reviews-10.json"; this.evaluationSet = evaluationSet; this.ratingsFolderPath = Utils.getRatingsFolderPath(jsonRatingsFile); headers = new String[] { "Algorithm", "Dataset", "Num_Topics", "Strategy", "Context_Format", "Cold-start", "NDCG@" + at, "Precision@" + at, "Recall@" + at, "RMSE", "MAE", "fold_0_ndcg", "fold_1_ndcg", "fold_2_ndcg", "fold_3_ndcg", "fold_4_ndcg", "fold_0_precision", "fold_1_precision", "fold_2_precision", "fold_3_precision", "fold_4_precision", "fold_0_recall", "fold_1_recall", "fold_2_recall", "fold_3_recall", "fold_4_recall", "fold_0_rmse", "fold_1_rmse", "fold_2_rmse", "fold_3_rmse", "fold_4_rmse", "fold_0_mae", "fold_1_mae", "fold_2_mae", "fold_3_mae", "fold_4_mae", }; } public String getOutputFile() { return outputFile; } public String[] getHeaders() { return headers; } /** * Takes the file generated by the recommender which stores the predictions * and parses the results, generating another file that is RiVal compatible */ private void parseRecommendationResultsLibfm() throws IOException, InterruptedException { System.out.println("Parse Recommendation Results LibFM"); for (int fold = 0; fold < numFolds; fold++) { // Collect the results from the recommender String foldPath = ratingsFolderPath + "fold_" + fold + "/"; // String testFile = foldPath + "test.csv"; String predictionsFile; String libfmResultsFile = foldPath + "libfm_results_" + strategy.getPredictionType() + ".txt"; // Results will be stored in this file, which is RiVal compatible String rivalRecommendationsFile = ratingsFolderPath + "fold_" + fold + "/recs_libfm_" + strategy.getPredictionType() + ".csv"; switch (strategy) { case TEST_ITEMS: case USER_TEST: predictionsFile = foldPath + "test.csv"; LibfmResultsParser.parseResults( predictionsFile, libfmResultsFile, false, rivalRecommendationsFile); break; case REL_PLUS_N: predictionsFile = foldPath + "predictions.csv"; LibfmResultsParser.parseResults( predictionsFile, libfmResultsFile, true, rivalRecommendationsFile); break; default: String msg = strategy.toString() + " evaluation strategy not supported"; throw new UnsupportedOperationException(msg); } System.out.println("Recommendations file name: " + rivalRecommendationsFile); } } /** * Prepares the strategy file to be used by Rival * * @param algorithm the algorithm used to make the predictions */ private void prepareStrategy(String algorithm) throws IOException { System.out.println("Prepare Rating Strategy"); for (int i = 0; i < numFolds; i++) { String foldPath = ratingsFolderPath + "fold_" + i + "/"; File trainingFile = new File(foldPath + "train.csv"); File testFile = new File(foldPath + "test.csv"); File recFile = new File(foldPath + "recs_" + algorithm + "_" + strategy.getPredictionType() + ".csv"); DataModelIF<Long, Long> trainingModel; DataModelIF<Long, Long> testModel; DataModelIF<Long, Long> recModel; System.out.println("Parsing Training Model"); trainingModel = new CsvParser().parseData(trainingFile); System.out.println("Parsing Test Model"); testModel = new CsvParser().parseData(testFile); System.out.println("Parsing Recommendation Model"); recModel = new CsvParser().parseData(recFile); EvaluationStrategy<Long, Long> evaluationStrategy; switch (strategy) { case TEST_ITEMS: evaluationStrategy = new TestItems( (DataModel)trainingModel, (DataModel)testModel, relevanceThreshold); break; case USER_TEST: evaluationStrategy = new UserTest( (DataModel)trainingModel, (DataModel)testModel, relevanceThreshold); break; case REL_PLUS_N: evaluationStrategy = new RelPlusN( trainingModel, testModel, additionalItems, relevanceThreshold, seed); break; default: String msg = strategy.toString() + " evaluation strategy not supported for rating"; throw new UnsupportedOperationException(msg); } DataModelIF<Long, Long> modelToEval = DataModelFactory.getDefaultModel(); for (Long user : recModel.getUsers()) { for (Long item : evaluationStrategy.getCandidateItemsToRank(user)) { if (!Double.isNaN(recModel.getUserItemPreference(user, item))) { modelToEval.addPreference(user, item, recModel.getUserItemPreference(user, item)); } } } DataModelUtils.saveDataModel( modelToEval, foldPath + "strategymodel_" + algorithm + "_" + strategy.toString().toLowerCase() + ".csv", true, "\t"); } } /** * Evaluates the performance of the recommender system indicated by the * {@code algorithm} parameter. This method requires that the strategy files * are already generated * * @param algorithm the algorithm used to make the predictions * @return a {@link Map} with the hyperparameters of the algorithm and the * performance metrics. */ private Map<String, String> evaluate(String algorithm) throws IOException { System.out.println("Evaluate"); double ndcgRes = 0.0; double recallRes = 0.0; double precisionRes = 0.0; double rmseRes = 0.0; double maeRes = 0.0; Map<String, String> results = new HashMap<>(); for (int i = 0; i < numFolds; i++) { String foldPath = ratingsFolderPath + "fold_" + i + "/"; File testFile = new File(foldPath + "test.csv"); String strategyFileName = foldPath + "strategymodel_" + algorithm + "_" + strategy.toString().toLowerCase() + ".csv"; File strategyFile = new File(strategyFileName); DataModelIF<Long, Long> testModel = new CsvParser().parseData(testFile); DataModelIF<Long, Long> recModel; switch (strategy) { case TEST_ITEMS: case USER_TEST: recModel = new CsvParser().parseData(strategyFile); break; case REL_PLUS_N: File trainingFile = new File(foldPath + "train.csv"); DataModelIF<Long, Long> trainModel = new CsvParser().parseData(trainingFile); Set<Long> trainUsers = new HashSet<>(); for (Long user : trainModel.getUsers()) { trainUsers.add(user); } System.out.println("Num train users = " + trainUsers.size()); Set<Long> testUsers = new HashSet<>(); for (Long user : testModel.getUsers()) { testUsers.add(user); } System.out.println("Num test users = " + testUsers.size()); Set<Long> users; System.out.println("Evaluation set: " + evaluationSet); switch (evaluationSet) { case TEST_USERS: users = testUsers; break; case TRAIN_USERS: users = trainUsers; break; case TEST_ONLY_USERS: testUsers.removeAll(trainUsers); users = testUsers; break; case TRAIN_ONLY_USERS: trainUsers.removeAll(testUsers); users = trainUsers; break; default: String msg = "Evaluation set " + evaluationSet + " not supported"; throw new UnsupportedOperationException(msg); } recModel = new CsvParser().parseData(strategyFile, users); // recModel = new CsvParser().parseData(strategyFile); break; default: throw new UnsupportedOperationException( strategy.toString() + " evaluation Strategy not supported"); } NDCG<Long, Long> ndcg = new NDCG<>(recModel, testModel, new int[]{at}); ndcg.compute(); ndcgRes += ndcg.getValueAt(at); results.put("fold_" + i + "_ndcg", String.valueOf(ndcg.getValueAt(at))); Recall<Long, Long> recall = new Recall<>( recModel, testModel, relevanceThreshold, new int[]{at}); recall.compute(); recallRes += recall.getValueAt(at); results.put("fold_" + i + "_recall", String.valueOf(recall.getValueAt(at))); RMSE<Long, Long> rmse = new RMSE<>(recModel, testModel); rmse.compute(); rmseRes += rmse.getValue(); results.put("fold_" + i + "_rmse", String.valueOf(rmse.getValue())); MAE<Long, Long> mae = new MAE<>(recModel, testModel); mae.compute(); maeRes += mae.getValue(); results.put("fold_" + i + "_mae", String.valueOf(mae.getValue())); Precision<Long, Long> precision = new Precision<>( recModel, testModel, relevanceThreshold, new int[]{at}); precision.compute(); precisionRes += precision.getValueAt(at); results.put("fold_" + i + "_precision", String.valueOf(precision.getValueAt(at))); } results.put("Dataset", dataset.toString()); results.put("Algorithm", algorithm); results.put("Num_Topics", String.valueOf(numTopics)); results.put("Strategy", strategy.toString()); results.put("Context_Format", contextFormat.toString()); results.put("Cold-start", String.valueOf(coldStart)); results.put("NDCG@" + at, String.valueOf(ndcgRes / numFolds)); results.put("Precision@" + at, String.valueOf(precisionRes / numFolds)); results.put("Recall@" + at, String.valueOf(recallRes / numFolds)); results.put("RMSE", String.valueOf(rmseRes / numFolds)); results.put("MAE", String.valueOf(maeRes / numFolds)); System.out.println("Dataset: " + dataset.toString()); System.out.println("Algorithm: " + algorithm); System.out.println("Num Topics: " + numTopics); System.out.println("Strategy: " + strategy.toString()); System.out.println("Context_Format: " + contextFormat.toString()); System.out.println("Cold-start: " + coldStart); System.out.println("NDCG@" + at + ": " + ndcgRes / numFolds); System.out.println("Precision@" + at + ": " + precisionRes / numFolds); System.out.println("Recall@" + at + ": " + recallRes / numFolds); System.out.println("RMSE: " + rmseRes / numFolds); System.out.println("MAE: " + maeRes / numFolds); return results; } /** * Runs the whole evaluation cycle starting after the recommendations have * been done. * * @param cacheFolder the folder that contains the dataset to be evaluated * @param outputFolder the folder where the results are going to be exported * @param propertiesFile the file that contains the hyperparameters for the * recommender * @param evaluationSet an enum that indicates which users are going to be * in the evaluation set. The possible values are: * {@code TRAIN_USERS, TEST_USERS, TRAIN_ONLY_USERS, TEST_ONLY_USERS} */ public static void processLibfmResults( String cacheFolder, String outputFolder, String propertiesFile, EvaluationSet evaluationSet, Integer numTopics, String itemType) throws IOException, InterruptedException { RichContextResultsProcessor evaluator = new RichContextResultsProcessor( cacheFolder, outputFolder, propertiesFile, evaluationSet, numTopics, itemType); evaluator.parseRecommendationResultsLibfm(); evaluator.prepareStrategy("libfm"); Map<String, String> results = evaluator.evaluate("libfm"); List<Map<String, String>> resultsList = new ArrayList<>(); resultsList.add(results); Utils.writeResultsToFile( resultsList, evaluator.getOutputFile(), evaluator.getHeaders()); } }
Fixed the name of the output file in the RichContextResultProcessor class
source/java/richcontext/src/main/java/org/insightcentre/richcontext/RichContextResultsProcessor.java
Fixed the name of the output file in the RichContextResultProcessor class
<ide><path>ource/java/richcontext/src/main/java/org/insightcentre/richcontext/RichContextResultsProcessor.java <ide> paramNumTopics; <ide> coldStart = properties.getEvaluateColdStart(); <ide> outputFile = outputFolder + <del> "rival_" + dataset.toString() + "_results_folds_4.csv"; <add> "rival_" + dataset.toString().toLowerCase() + "_results_folds_4.csv"; <ide> <ide> String jsonRatingsFile = cacheFolder + dataset.toString().toLowerCase() + <ide> "_recsys_formatted_context_records_ensemble_" +
Java
apache-2.0
dde5a2d610faaad6b7631b1fdc014fb053379715
0
openengsb/loom-java
package org.openengsb.loom.java; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.openengsb.core.api.model.BeanDescription; import org.openengsb.core.api.remote.MethodCall; import org.openengsb.core.api.remote.MethodCallMessage; import org.openengsb.core.api.remote.MethodResult.ReturnType; import org.openengsb.core.api.remote.MethodResultMessage; import org.openengsb.core.api.security.Credentials; import org.openengsb.loom.java.util.JsonUtils; import org.osgi.framework.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RemoteServiceHandler implements InvocationHandler { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteServiceHandler.class); protected String serviceId; private RequestHandler requestHandler; private String principal; private Credentials credentials; public RemoteServiceHandler(String serviceId, RequestHandler requestHandler, String principal, Credentials credentials) { this.serviceId = serviceId; this.requestHandler = requestHandler; this.principal = principal; this.credentials = credentials; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (args == null) { args = new Object[0]; } if(method.getDeclaringClass().equals(Object.class)){ return method.invoke(this, args); } MethodCall methodCall = createMethodCall(method, args, serviceId); MethodCallMessage wrapped = wrapMethodCall(methodCall); MethodResultMessage response = requestHandler.process(wrapped); if (response.getResult().getType().equals(ReturnType.Object)) { JsonUtils.convertResult(response); } if (response.getResult().getType().equals(ReturnType.Exception)) { LOGGER.error(response.getResult().getClassName() + " - " + response.getResult().getArg()); throw new RemoteException(response.getResult().getClassName()); } return response.getResult().getArg(); } private MethodCallMessage wrapMethodCall(MethodCall methodCall) { MethodCallMessage methodCallRequest = new MethodCallMessage(methodCall); methodCallRequest.setPrincipal(principal); methodCallRequest.setCredentials(BeanDescription.fromObject(credentials)); return methodCallRequest; } private MethodCall createMethodCall(Method method, Object[] args, String serviceId) { MethodCall methodCall = new MethodCall(method.getName(), args); Map<String, String> metadata = new HashMap<String, String>(); if (serviceId != null) { metadata.put("serviceFilter", String.format("(&(%s=%s)(%s=%s))", Constants.OBJECTCLASS, method.getDeclaringClass().getName(), "service.pid", serviceId)); } else { metadata.put("serviceFilter", String.format("(%s=%s)", Constants.OBJECTCLASS, method.getDeclaringClass().getName())); } metadata.put("contextId", "root"); methodCall.setMetaData(metadata); return methodCall; } }
bridge/src/main/java/org/openengsb/loom/java/RemoteServiceHandler.java
package org.openengsb.loom.java; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.openengsb.core.api.model.BeanDescription; import org.openengsb.core.api.remote.MethodCall; import org.openengsb.core.api.remote.MethodCallMessage; import org.openengsb.core.api.remote.MethodResult.ReturnType; import org.openengsb.core.api.remote.MethodResultMessage; import org.openengsb.core.api.security.Credentials; import org.openengsb.loom.java.util.JsonUtils; import org.osgi.framework.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RemoteServiceHandler implements InvocationHandler { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteServiceHandler.class); protected String serviceId; private RequestHandler requestHandler; private String principal; private Credentials credentials; public RemoteServiceHandler(String serviceId, RequestHandler requestHandler, String principal, Credentials credentials) { this.serviceId = serviceId; this.requestHandler = requestHandler; this.principal = principal; this.credentials = credentials; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (args == null) { args = new Object[0]; } MethodCall methodCall = createMethodCall(method, args, serviceId); MethodCallMessage wrapped = wrapMethodCall(methodCall); MethodResultMessage response = requestHandler.process(wrapped); if (response.getResult().getType().equals(ReturnType.Object)) { JsonUtils.convertResult(response); } if (response.getResult().getType().equals(ReturnType.Exception)) { LOGGER.error(response.getResult().getClassName() + " - " + response.getResult().getArg()); throw new RemoteException(response.getResult().getClassName()); } return response.getResult().getArg(); } private MethodCallMessage wrapMethodCall(MethodCall methodCall) { MethodCallMessage methodCallRequest = new MethodCallMessage(methodCall); methodCallRequest.setPrincipal(principal); methodCallRequest.setCredentials(BeanDescription.fromObject(credentials)); return methodCallRequest; } private MethodCall createMethodCall(Method method, Object[] args, String serviceId) { MethodCall methodCall = new MethodCall(method.getName(), args); Map<String, String> metadata = new HashMap<String, String>(); if (serviceId != null) { metadata.put("serviceFilter", String.format("(&(%s=%s)(%s=%s))", Constants.OBJECTCLASS, method.getDeclaringClass().getName(), "service.pid", serviceId)); } else { metadata.put("serviceFilter", String.format("(%s=%s)", Constants.OBJECTCLASS, method.getDeclaringClass().getName())); } metadata.put("contextId", "root"); methodCall.setMetaData(metadata); return methodCall; } }
[OPENENGSB-3364] do not forward calls to object-methods
bridge/src/main/java/org/openengsb/loom/java/RemoteServiceHandler.java
[OPENENGSB-3364] do not forward calls to object-methods
<ide><path>ridge/src/main/java/org/openengsb/loom/java/RemoteServiceHandler.java <ide> if (args == null) { <ide> args = new Object[0]; <ide> } <add> if(method.getDeclaringClass().equals(Object.class)){ <add> return method.invoke(this, args); <add> } <ide> MethodCall methodCall = createMethodCall(method, args, serviceId); <ide> MethodCallMessage wrapped = wrapMethodCall(methodCall); <ide> MethodResultMessage response = requestHandler.process(wrapped);
JavaScript
apache-2.0
05b03be1877d45559b31b793dc25a2ec1ddfbcfa
0
YonatanKra/cesium,YonatanKra/cesium,AnalyticalGraphicsInc/cesium,progsung/cesium,likangning93/cesium,likangning93/cesium,CesiumGS/cesium,AnalyticalGraphicsInc/cesium,likangning93/cesium,CesiumGS/cesium,YonatanKra/cesium,progsung/cesium,CesiumGS/cesium,likangning93/cesium,YonatanKra/cesium,CesiumGS/cesium,CesiumGS/cesium,likangning93/cesium
/*global JSHINT */ /*global decodeBase64Data, embedInSandcastleTemplate */ /*global gallery_demos, has_new_gallery_demos, hello_world_index, VERSION*/// defined in gallery/gallery-index.js, created by build /*global sandcastleJsHintOptions*/// defined by jsHintOptions.js, created by build require({ baseUrl: '../../Source', packages: [{ name: 'dojo', location: '../ThirdParty/dojo-release-1.10.4/dojo' }, { name: 'dijit', location: '../ThirdParty/dojo-release-1.10.4/dijit' }, { name: 'Sandcastle', location: '../Apps/Sandcastle' }, { name: 'CodeMirror', location: '../ThirdParty/codemirror-4.6' }, { name: 'ThirdParty', location: '../Apps/Sandcastle/ThirdParty' }] }, [ 'CodeMirror/lib/codemirror', 'dijit/Dialog', 'dijit/form/Button', 'dijit/form/Form', 'dijit/form/Textarea', 'dijit/layout/ContentPane', 'dijit/popup', 'dijit/registry', 'dijit/TooltipDialog', 'dojo/_base/fx', 'dojo/_base/xhr', 'dojo/dom', 'dojo/dom-class', 'dojo/dom-construct', 'dojo/io-query', 'dojo/mouse', 'dojo/on', 'dojo/parser', 'dojo/promise/all', 'dojo/query', 'dojo/when', 'dojo/Deferred', 'dojo/request/script', 'Sandcastle/LinkButton', 'ThirdParty/clipboard.min', 'ThirdParty/pako.min', 'CodeMirror/addon/hint/show-hint', 'CodeMirror/addon/hint/javascript-hint', 'CodeMirror/mode/javascript/javascript', 'CodeMirror/mode/css/css', 'CodeMirror/mode/xml/xml', 'CodeMirror/mode/htmlmixed/htmlmixed', 'dijit/form/DropDownButton', 'dijit/form/ToggleButton', 'dijit/form/DropDownButton', 'dijit/form/TextBox', 'dijit/Menu', 'dijit/MenuBar', 'dijit/PopupMenuBarItem', 'dijit/MenuItem', 'dijit/layout/BorderContainer', 'dijit/layout/TabContainer', 'dijit/Toolbar', 'dijit/ToolbarSeparator', 'dojo/domReady!' ], function( CodeMirror, Dialog, Button, Form, TextArea, ContentPane, popup, registry, TooltipDialog, fx, xhr, dom, domClass, domConstruct, ioQuery, mouse, on, parser, all, query, when, Deferred, dojoscript, LinkButton, ClipboardJS, pako) { 'use strict'; // attach clipboard handling to our Copy button var clipboardjs = new ClipboardJS('.copyButton'); function defined(value) { return value !== undefined && value !== null; } parser.parse(); fx.fadeOut({ node : 'loading', onEnd : function() { domConstruct.destroy('loading'); } }).play(); var numberOfNewConsoleMessages = 0; var logOutput = document.getElementById('logOutput'); function appendConsole(className, message, showConsole) { var ele = document.createElement('span'); ele.className = className; ele.textContent = message + '\n'; logOutput.appendChild(ele); logOutput.parentNode.scrollTop = logOutput.clientHeight + 8 - logOutput.parentNode.clientHeight; if (showConsole) { hideGallery(); } else { ++numberOfNewConsoleMessages; registry.byId('logContainer').set('title', 'Console (' + numberOfNewConsoleMessages + ')'); } } var URL = window.URL || window.webkitURL; function findCssStyle(selectorText) { for (var iSheets = 0, lenSheets = document.styleSheets.length; iSheets < lenSheets; ++iSheets) { var rules = document.styleSheets[iSheets].cssRules; for (var iRules = 0, lenRules = rules.length; iRules < lenRules; ++iRules) { if (rules[iRules].selectorText === selectorText) { return rules[iRules]; } } } } var jsEditor; var htmlEditor; var suggestButton = registry.byId('buttonSuggest'); var docTimer; var docTabs = {}; var subtabs = {}; var docError = false; var galleryError = false; var deferredLoadError = false; var galleryTooltipTimer; var activeGalleryTooltipDemo; var demoTileHeightRule = findCssStyle('.demoTileThumbnail'); var cesiumContainer = registry.byId('cesiumContainer'); var docNode = dom.byId('docPopup'); var docMessage = dom.byId('docPopupMessage'); var local = { 'docTypes' : [], 'headers' : '<html><head></head><body>', 'bucketName' : '', 'emptyBucket' : '' }; var bucketTypes = {}; var demoTooltips = {}; var errorLines = []; var highlightLines = []; var searchTerm = ''; var searchRegExp; var hintTimer; var defaultDemo = 'Hello World'; var defaultLabel = 'Showcases'; var currentTab = defaultLabel; var newDemo; var demoHtml = ''; var demoCode = ''; var defaultHtml = '<style>\n@import url(../templates/bucket.css);\n</style>\n<div id=\"cesiumContainer\" class=\"fullSize\"></div>\n<div id=\"loadingOverlay\"><h1>Loading...</h1></div>\n<div id=\"toolbar\"></div>'; var galleryErrorMsg = document.createElement('span'); galleryErrorMsg.className = 'galleryError'; galleryErrorMsg.style.display = 'none'; galleryErrorMsg.textContent = 'No demos match your search terms.'; var bucketFrame = document.getElementById('bucketFrame'); var bucketPane = registry.byId('bucketPane'); var bucketWaiting = false; xhr.get({ url : '../../Build/Documentation/types.txt', handleAs : 'json', error : function(error) { docError = true; } }).then(function(value) { local.docTypes = value; }); var decoderSpan = document.createElement('span'); function encodeHTML(text) { decoderSpan.textContent = text; text = decoderSpan.innerHTML; decoderSpan.innerHTML = ''; return text; } function decodeHTML(text) { decoderSpan.innerHTML = text; text = decoderSpan.textContent; decoderSpan.innerHTML = ''; return text; } function highlightRun() { domClass.add(registry.byId('buttonRun').domNode, 'highlightToolbarButton'); } function clearRun() { domClass.remove(registry.byId('buttonRun').domNode, 'highlightToolbarButton'); } function openDocTab(title, link) { if (!defined(docTabs[title])) { docTabs[title] = new ContentPane({ title : title, focused : true, content : '<iframe class="fullFrame" src="' + link + '"></iframe>', closable : true, onClose : function() { docTabs[this.title] = undefined; // Return true to close the tab. return true; } }).placeAt(cesiumContainer); // After the iframe loads, re-scroll to selected field. docTabs[title].domNode.childNodes[0].onload = function() { this.onload = function() { }; this.src = link; }; cesiumContainer.selectChild(docTabs[title]); } else { // Tab already exists, but maybe not visible. Firefox needs the tab to // be revealed before a re-scroll can happen. Chrome works either way. cesiumContainer.selectChild(docTabs[title]); docTabs[title].domNode.childNodes[0].src = link; } } function showDocPopup() { var selectedText = jsEditor.getSelection(); var lowerText = selectedText.toLowerCase(); var onDocClick = function() { openDocTab(this.textContent, this.href); return false; }; docTimer = undefined; if (docError && selectedText && selectedText.length < 50) { hideGallery(); } else if (lowerText && lowerText in local.docTypes && typeof local.docTypes[lowerText].push === 'function') { docMessage.innerHTML = ''; for (var i = 0, len = local.docTypes[lowerText].length; i < len; ++i) { var member = local.docTypes[lowerText][i]; var ele = document.createElement('a'); ele.target = '_blank'; ele.textContent = member.replace('.html', '').replace('module-', '').replace('#.', '.').replace('#', '.'); ele.href = '../../Build/Documentation/' + member; ele.onclick = onDocClick; docMessage.appendChild(ele); } jsEditor.addWidget(jsEditor.getCursor(true), docNode); docNode.style.top = (parseInt(docNode.style.top, 10) - 5) + 'px'; } } function onCursorActivity() { docNode.style.left = '-999px'; if (defined(docTimer)) { window.clearTimeout(docTimer); } docTimer = window.setTimeout(showDocPopup, 500); } function makeLineLabel(msg, className) { var element = document.createElement('abbr'); element.className = className; switch (className) { case 'hintMarker': element.innerHTML = '&#9650;'; break; case 'errorMarker': element.innerHTML = '&times;'; break; default: element.innerHTML = '&#9654;'; } element.title = msg; return element; } function closeGalleryTooltip() { if (defined(activeGalleryTooltipDemo)) { popup.close(demoTooltips[activeGalleryTooltipDemo.name]); activeGalleryTooltipDemo = undefined; } } function openGalleryTooltip() { galleryTooltipTimer = undefined; var selectedTabName = registry.byId('innerPanel').selectedChildWidget.title; var suffix = selectedTabName + 'Demos'; if (selectedTabName === 'All') { suffix = 'all'; } else if (selectedTabName === 'Search Results') { suffix = 'searchDemo'; } if (defined(activeGalleryTooltipDemo)) { popup.open({ popup : demoTooltips[activeGalleryTooltipDemo.name], around : dom.byId(activeGalleryTooltipDemo.name + suffix), orient : ['above', 'below'] }); } } function scheduleGalleryTooltip(demo) { if (demo !== activeGalleryTooltipDemo) { activeGalleryTooltipDemo = demo; if (defined(galleryTooltipTimer)) { window.clearTimeout(galleryTooltipTimer); } galleryTooltipTimer = window.setTimeout(openGalleryTooltip, 220); } } function scriptLineToEditorLine(line) { // editor lines are zero-indexed, plus 3 lines of boilerplate return line - 4; } function clearErrorsAddHints() { var line; var i; var len; hintTimer = undefined; closeGalleryTooltip(); jsEditor.clearGutter('hintGutter'); jsEditor.clearGutter('highlightGutter'); jsEditor.clearGutter('errorGutter'); jsEditor.clearGutter('searchGutter'); while (errorLines.length > 0) { line = errorLines.pop(); jsEditor.removeLineClass(line, 'text'); } while (highlightLines.length > 0) { line = highlightLines.pop(); jsEditor.removeLineClass(line, 'text'); } var code = jsEditor.getValue(); if (searchTerm !== '') { var codeLines = code.split('\n'); for (i = 0, len = codeLines.length; i < len; ++i) { if (searchRegExp.test(codeLines[i])) { line = jsEditor.setGutterMarker(i, 'searchGutter', makeLineLabel('Search: ' + searchTerm, 'searchMarker')); jsEditor.addLineClass(line, 'text', 'searchLine'); errorLines.push(line); } } } // make a copy of the options, JSHint modifies the object it's given var options = JSON.parse(JSON.stringify(sandcastleJsHintOptions)); /*eslint-disable new-cap*/ if (!JSHINT(embedInSandcastleTemplate(jsEditor.getValue(), false), options)) { var hints = JSHINT.errors; for (i = 0, len = hints.length; i < len; ++i) { var hint = hints[i]; if (hint !== null && defined(hint.reason) && hint.line > 0) { line = jsEditor.setGutterMarker(scriptLineToEditorLine(hint.line), 'hintGutter', makeLineLabel(hint.reason, 'hintMarker')); jsEditor.addLineClass(line, 'text', 'hintLine'); errorLines.push(line); } } } /*eslint-enable new-cap*/ } function scheduleHint() { if (defined(hintTimer)) { window.clearTimeout(hintTimer); } hintTimer = setTimeout(clearErrorsAddHints, 550); highlightRun(); } function scheduleHintNoChange() { if (defined(hintTimer)) { window.clearTimeout(hintTimer); } hintTimer = setTimeout(clearErrorsAddHints, 550); } function scrollToLine(lineNumber) { if (defined(lineNumber)) { jsEditor.setCursor(lineNumber); // set selection twice in order to force the editor to scroll // to this location if the cursor is already there jsEditor.setSelection({ line : lineNumber - 1, ch : 0 }, { line : lineNumber - 1, ch : 0 }); jsEditor.focus(); jsEditor.setSelection({ line : lineNumber, ch : 0 }, { line : lineNumber, ch : 0 }); } } function highlightLine(lineNum) { var line; jsEditor.clearGutter('highlightGutter'); while (highlightLines.length > 0) { line = highlightLines.pop(); jsEditor.removeLineClass(line, 'text'); } if (lineNum > 0) { lineNum = scriptLineToEditorLine(lineNum); line = jsEditor.setGutterMarker(lineNum, 'highlightGutter', makeLineLabel('highlighted by demo', 'highlightMarker')); jsEditor.addLineClass(line, 'text', 'highlightLine'); highlightLines.push(line); scrollToLine(lineNum); } } var tabs = registry.byId('bottomPanel'); function showGallery() { tabs.selectChild(registry.byId('innerPanel')); } function hideGallery() { closeGalleryTooltip(); tabs.selectChild(registry.byId('logContainer')); } tabs.watch('selectedChildWidget', function(name, oldValue, newValue) { if (newValue === registry.byId('logContainer')) { numberOfNewConsoleMessages = 0; registry.byId('logContainer').set('title', 'Console'); } }); function registerScroll(demoContainer) { if (document.onmousewheel !== undefined) { demoContainer.addEventListener('mousewheel', function(e) { if (defined(e.wheelDelta) && e.wheelDelta) { demoContainer.scrollLeft -= e.wheelDelta * 70 / 120; } }, false); } else { demoContainer.addEventListener('DOMMouseScroll', function(e) { if (defined(e.detail) && e.detail) { demoContainer.scrollLeft += e.detail * 70 / 3; } }, false); } } CodeMirror.commands.runCesium = function(cm) { clearErrorsAddHints(); clearRun(); cesiumContainer.selectChild(bucketPane); // Check for a race condition in some browsers where the iframe hasn't loaded yet. if (bucketFrame.contentWindow.location.href.indexOf('bucket.html') > 0) { bucketFrame.contentWindow.location.reload(); } }; jsEditor = CodeMirror.fromTextArea(document.getElementById('code'), { mode : 'javascript', gutters : ['hintGutter', 'errorGutter', 'searchGutter', 'highlightGutter'], lineNumbers : true, matchBrackets : true, indentUnit : 4, extraKeys : { 'Ctrl-Space' : 'autocomplete', 'F8' : 'runCesium', 'Tab' : 'indentMore', 'Shift-Tab' : 'indentLess' } }); jsEditor.on('cursorActivity', onCursorActivity); jsEditor.on('change', scheduleHint); htmlEditor = CodeMirror.fromTextArea(document.getElementById('htmlBody'), { mode : 'text/html', lineNumbers : true, matchBrackets : true, indentUnit : 4, extraKeys : { 'F8' : 'runCesium', 'Tab' : 'indentMore', 'Shift-Tab' : 'indentLess' } }); window.onbeforeunload = function (e) { var htmlText = (htmlEditor.getValue()).replace(/\s/g, ''); var jsText = (jsEditor.getValue()).replace(/\s/g, ''); if (demoHtml !== htmlText || demoCode !== jsText) { return 'Be sure to save a copy of any important edits before leaving this page.'; } }; registry.byId('codeContainer').watch('selectedChildWidget', function(name, oldPane, newPane) { if (newPane.id === 'jsContainer') { jsEditor.focus(); } else if (newPane.id === 'htmlContainer') { htmlEditor.focus(); } }); var scriptCodeRegex = /\/\/Sandcastle_Begin\s*([\s\S]*)\/\/Sandcastle_End/; function activateBucketScripts(bucketDoc) { var headNodes = bucketDoc.head.childNodes; var node; var nodes = []; var i, len; for (i = 0, len = headNodes.length; i < len; ++i) { node = headNodes[i]; // header is included in blank frame. if (node.tagName === 'SCRIPT' && node.src.indexOf('Sandcastle-header.js') < 0) { nodes.push(node); } } for (i = 0, len = nodes.length; i < len; ++i) { bucketDoc.head.removeChild(nodes[i]); } // Apply user HTML to bucket. var htmlElement = bucketDoc.createElement('div'); htmlElement.innerHTML = htmlEditor.getValue(); bucketDoc.body.appendChild(htmlElement); var onScriptTagError = function() { if (bucketFrame.contentDocument === bucketDoc) { appendConsole('consoleError', 'Error loading ' + this.src, true); appendConsole('consoleError', "Make sure Cesium is built, see the Contributor's Guide for details.", true); } }; // Load each script after the previous one has loaded. var loadScript = function() { if (bucketFrame.contentDocument !== bucketDoc) { // A newer reload has happened, abort this. return; } if (nodes.length > 0) { while(nodes.length > 0){ node = nodes.shift(); var scriptElement = bucketDoc.createElement('script'); var hasSrc = false; for (var j = 0, numAttrs = node.attributes.length; j < numAttrs; ++j) { var name = node.attributes[j].name; var val = node.attributes[j].value; scriptElement.setAttribute(name, val); if (name === 'src' && val) { hasSrc = true; } } scriptElement.innerHTML = node.innerHTML; if (hasSrc) { scriptElement.onload = loadScript; scriptElement.onerror = onScriptTagError; bucketDoc.head.appendChild(scriptElement); } else { bucketDoc.head.appendChild(scriptElement); loadScript(); } } } else { // Apply user JS to bucket var element = bucketDoc.createElement('script'); // Firefox line numbers are zero-based, not one-based. var isFirefox = navigator.userAgent.indexOf('Firefox/') >= 0; element.textContent = embedInSandcastleTemplate(jsEditor.getValue(), isFirefox); bucketDoc.body.appendChild(element); } }; loadScript(); } function applyBucket() { if (local.emptyBucket && local.bucketName && typeof bucketTypes[local.bucketName] === 'string') { bucketWaiting = false; var bucketDoc = bucketFrame.contentDocument; if (local.headers.substring(0, local.emptyBucket.length) !== local.emptyBucket) { appendConsole('consoleError', 'Error, first part of ' + local.bucketName + ' must match first part of bucket.html exactly.', true); } else { var bodyAttributes = local.headers.match(/<body([^>]*?)>/)[1]; var attributeRegex = /([-a-z_]+)\s*="([^"]*?)"/ig; //group 1 attribute name, group 2 attribute value. Assumes double-quoted attributes. var attributeMatch; while ((attributeMatch = attributeRegex.exec(bodyAttributes)) !== null) { var attributeName = attributeMatch[1]; var attributeValue = attributeMatch[2]; if (attributeName === 'class') { bucketDoc.body.className = attributeValue; } else { bucketDoc.body.setAttribute(attributeName, attributeValue); } } var pos = local.headers.indexOf('</head>'); var extraHeaders = local.headers.substring(local.emptyBucket.length, pos); bucketDoc.head.innerHTML += extraHeaders; activateBucketScripts(bucketDoc); } } else { bucketWaiting = true; } } function applyBucketIfWaiting() { if (bucketWaiting) { applyBucket(); } } xhr.get({ url : 'templates/bucket.html', handleAs : 'text' }).then(function(value) { var pos = value.indexOf('</head>'); local.emptyBucket = value.substring(0, pos); applyBucketIfWaiting(); }); function loadBucket(bucketName) { if (local.bucketName !== bucketName) { local.bucketName = bucketName; if (defined(bucketTypes[bucketName])) { local.headers = bucketTypes[bucketName]; } else { local.headers = '<html><head></head><body data-sandcastle-bucket-loaded="no">'; xhr.get({ url : 'templates/' + bucketName, handleAs : 'text' }).then(function(value) { var pos = value.indexOf('<body'); pos = value.indexOf('>', pos); bucketTypes[bucketName] = value.substring(0, pos + 1); if (local.bucketName === bucketName) { local.headers = bucketTypes[bucketName]; } applyBucketIfWaiting(); }); } } } var queryObject = {}; if (window.location.search) { queryObject = ioQuery.queryToObject(window.location.search.substring(1)); } if (!defined(queryObject.src)) { queryObject.src = defaultDemo + '.html'; } if (!defined(queryObject.label)) { queryObject.label = defaultLabel; } function loadFromGallery(demo) { deferredLoadError = false; document.getElementById('saveAsFile').download = demo.name + '.html'; registry.byId('description').set('value', decodeHTML(demo.description).replace(/\\n/g, '\n')); registry.byId('label').set('value', decodeHTML(demo.label).replace(/\\n/g, '\n')); return requestDemo(demo.name).then(function(value) { demo.code = value; if (typeof demo.bucket === 'string') { loadBucket(demo.bucket); } function applyLoadedDemo(code, html) { jsEditor.setValue(code); jsEditor.clearHistory(); htmlEditor.setValue(html); htmlEditor.clearHistory(); demoCode = code.replace(/\s/g, ''); demoHtml = html.replace(/\s/g, ''); CodeMirror.commands.runCesium(jsEditor); clearRun(); } var json, code, html; if (defined(queryObject.gist)) { dojoscript.get('https://api.github.com/gists/' + queryObject.gist + '?access_token=dd8f755c2e5d9bbb26806bb93eaa2291f2047c60', { jsonp: 'callback' }).then(function(data) { var files = data.data.files; var code = files['Cesium-Sandcastle.js'].content; var htmlFile = files['Cesium-Sandcastle.html']; var html = defined(htmlFile) ? htmlFile.content : defaultHtml; // Use the default html for old gists applyLoadedDemo(code, html); }).otherwise(function(error) { appendConsole('consoleError', 'Unable to GET from GitHub API. This could be due to too many request, try again in an hour or copy and paste the code from the gist: https://gist.github.com/' + queryObject.gist, true); console.log(error); }); } else if (defined(queryObject.code)) { //The code query parameter is a Base64 encoded JSON string with `code` and `html` properties. json = JSON.parse(window.atob(queryObject.code)); code = json.code; html = json.html; applyLoadedDemo(code, html); } else if (window.location.hash.indexOf('#c=') === 0) { var base64String = window.location.hash.substr(3); var data = decodeBase64Data(base64String, pako); code = data.code; html = data.html; applyLoadedDemo(code, html); } else { var parser = new DOMParser(); var doc = parser.parseFromString(demo.code, 'text/html'); return waitForDoc(doc, function(){ return doc.querySelector('script[id="cesium_sandcastle_script"]'); }).then(function(){ var script = doc.querySelector('script[id="cesium_sandcastle_script"]'); if (!script) { appendConsole('consoleError', 'Error reading source file: ' + demo.name, true); return; } var scriptMatch = scriptCodeRegex.exec(script.textContent); if (!scriptMatch) { appendConsole('consoleError', 'Error reading source file: ' + demo.name, true); return; } var scriptCode = scriptMatch[1]; var htmlText = ''; var childIndex = 0; var childNode = doc.body.childNodes[childIndex]; while (childIndex < doc.body.childNodes.length && childNode !== script) { htmlText += childNode.nodeType === 1 ? childNode.outerHTML : childNode.nodeValue; childNode = doc.body.childNodes[++childIndex]; } htmlText = htmlText.replace(/^\s+/, ''); applyLoadedDemo(scriptCode, htmlText); }); } }); } window.addEventListener('popstate', function(e) { if (e.state && e.state.name && e.state.code) { loadFromGallery(e.state); document.title = e.state.name + ' - Cesium Sandcastle'; } }, false); window.addEventListener('message', function(e) { var line; // The iframe (bucket.html) sends this message on load. // This triggers the code to be injected into the iframe. if (e.data === 'reload') { var bucketDoc = bucketFrame.contentDocument; if (!local.bucketName) { // Reload fired, bucket not specified yet. return; } if (bucketDoc.body.getAttribute('data-sandcastle-loaded') !== 'yes') { bucketDoc.body.setAttribute('data-sandcastle-loaded', 'yes'); logOutput.innerHTML = ''; numberOfNewConsoleMessages = 0; registry.byId('logContainer').set('title', 'Console'); // This happens after a Run (F8) reloads bucket.html, to inject the editor code // into the iframe, causing the demo to run there. applyBucket(); if (docError) { appendConsole('consoleError', 'Documentation not available. Please run the "generateDocumentation" build script to generate Cesium documentation.', true); showGallery(); } if (galleryError) { appendConsole('consoleError', 'Error loading gallery, please run the build script.', true); } if (deferredLoadError) { appendConsole('consoleLog', 'Unable to load demo named ' + queryObject.src.replace('.html', '') + '. Redirecting to HelloWorld.\n', true); } } } else if (defined(e.data.log)) { // Console log messages from the iframe display in Sandcastle. appendConsole('consoleLog', e.data.log, false); } else if (defined(e.data.error)) { // Console error messages from the iframe display in Sandcastle var errorMsg = e.data.error; var lineNumber = e.data.lineNumber; if (defined(lineNumber)) { errorMsg += ' (on line '; if (e.data.url) { errorMsg += lineNumber + ' of ' + e.data.url + ')'; } else { lineNumber = scriptLineToEditorLine(lineNumber); errorMsg += (lineNumber + 1) + ')'; line = jsEditor.setGutterMarker(lineNumber, 'errorGutter', makeLineLabel(e.data.error, 'errorMarker')); jsEditor.addLineClass(line, 'text', 'errorLine'); errorLines.push(line); scrollToLine(lineNumber); } } appendConsole('consoleError', errorMsg, true); } else if (defined(e.data.warn)) { // Console warning messages from the iframe display in Sandcastle. appendConsole('consoleWarn', e.data.warn, true); } else if (defined(e.data.highlight)) { // Hovering objects in the embedded Cesium window. highlightLine(e.data.highlight); } }, true); registry.byId('jsContainer').on('show', function() { suggestButton.set('disabled', false); jsEditor.refresh(); }); registry.byId('htmlContainer').on('show', function() { suggestButton.set('disabled', true); htmlEditor.refresh(); }); registry.byId('search').on('change', function() { searchTerm = this.get('value'); searchRegExp = new RegExp(searchTerm, 'i'); var numDemosShown = 0; if (searchTerm !== '') { showSearchContainer(); var innerPanel = registry.byId('innerPanel'); innerPanel.selectChild(registry.byId('searchContainer')); for (var i = 0; i < gallery_demos.length; i++) { var demo = gallery_demos[i]; var demoName = demo.name; if (searchRegExp.test(demoName) || searchRegExp.test(demo.code)) { document.getElementById(demoName + 'searchDemo').style.display = 'inline-block'; ++numDemosShown; } else { document.getElementById(demoName + 'searchDemo').style.display = 'none'; } } } else { hideSearchContainer(); } if (numDemosShown) { galleryErrorMsg.style.display = 'none'; } else { galleryErrorMsg.style.display = 'inline-block'; } showGallery(); scheduleHintNoChange(); }); var searchContainer; function hideSearchContainer() { if (dom.byId('searchContainer')) { var innerPanel = registry.byId('innerPanel'); innerPanel.removeChild(searchContainer); } } function showSearchContainer() { if (!dom.byId('searchContainer')) { var innerPanel = registry.byId('innerPanel'); innerPanel.addChild(searchContainer); } } function getBaseUrl() { // omits query string and hash return location.protocol + '//' + location.host + location.pathname; } function makeCompressedBase64String(data) { // data stored in the hash as: // Base64 encoded, raw DEFLATE compressed JSON array where index 0 is code, index 1 is html var jsonString = JSON.stringify(data); // we save a few bytes by omitting the leading [" and trailing "] since they are always the same jsonString = jsonString.substr(2, jsonString.length - 4); var base64String = btoa(pako.deflate(jsonString, { raw: true, to: 'string', level: 9 })); base64String = base64String.replace(/\=+$/, ''); // remove padding return base64String; } registry.byId('buttonShareDrop').on('click', function() { var code = jsEditor.getValue(); var html = htmlEditor.getValue(); var base64String = makeCompressedBase64String([code, html]); var shareUrlBox = document.getElementById('shareUrl'); shareUrlBox.value = getBaseUrl() + '#c=' + base64String; shareUrlBox.select(); }); registry.byId('buttonImport').on('click', function() { var gistId = document.getElementById('gistId').value; var gistParameter = '&gist='; var gistIndex = gistId.indexOf(gistParameter); if (gistIndex !== -1) { gistId = gistId.substring(gistIndex + gistParameter.length); } window.location.href = getBaseUrl() + '?gist=' + gistId; }); function getPushStateUrl(demo) { var obj = {}; if (demo.name !== defaultDemo) { obj.src = demo.name + '.html'; } if (currentTab !== defaultLabel) { obj.label = currentTab; } var query = ioQuery.objectToQuery(obj); return query === '' ? query : '?' + query; } registry.byId('buttonNew').on('click', function() { var htmlText = (htmlEditor.getValue()).replace(/\s/g, ''); var jsText = (jsEditor.getValue()).replace(/\s/g, ''); var confirmChange = true; if (demoHtml !== htmlText || demoCode !== jsText) { confirmChange = window.confirm('You have unsaved changes. Are you sure you want to navigate away from this demo?'); } if (confirmChange) { window.history.pushState(newDemo, newDemo.name, getPushStateUrl(newDemo)); loadFromGallery(newDemo).then(function() { document.title = newDemo.name + ' - Cesium Sandcastle'; }); } }); // Clicking the 'Run' button simply reloads the iframe. registry.byId('buttonRun').on('click', function() { CodeMirror.commands.runCesium(jsEditor); }); registry.byId('buttonSuggest').on('click', function() { CodeMirror.commands.autocomplete(jsEditor); }); function getDemoHtml() { return local.headers + '\n' + htmlEditor.getValue() + '<script id="cesium_sandcastle_script">\n' + embedInSandcastleTemplate(jsEditor.getValue(), false) + '</script>\n' + '</body>\n' + '</html>\n'; } registry.byId('dropDownSaveAs').on('show', function() { var currentDemoName = queryObject.src; currentDemoName = currentDemoName.replace('.html', ''); var description = encodeHTML(registry.byId('description').get('value').replace(/\n/g, '\\n')).replace(/\"/g, '&quot;'); var label = encodeHTML(registry.byId('label').get('value').replace(/\n/g, '\\n')).replace(/\"/g, '&quot;'); var html = getDemoHtml(); html = html.replace('<title>', '<meta name="description" content="' + description + '">\n <title>'); html = html.replace('<title>', '<meta name="cesium-sandcastle-labels" content="' + label + '">\n <title>'); var octetBlob = new Blob([html], { 'type' : 'application/octet-stream', 'endings' : 'native' }); var octetBlobURL = URL.createObjectURL(octetBlob); dom.byId('saveAsFile').href = octetBlobURL; }); registry.byId('buttonNewWindow').on('click', function() { //Handle case where demo is in a sub-directory by modifying //the demo's HTML to add a base href. var baseHref = getBaseUrl(); var pos = baseHref.lastIndexOf('/'); baseHref = baseHref.substring(0, pos) + '/gallery/'; var code = jsEditor.getValue(); var html = htmlEditor.getValue(); var data = makeCompressedBase64String([code, html, baseHref]); var url = getBaseUrl(); url = url.replace('index.html','') + 'standalone.html' + '#c=' + data; window.open(url, '_blank'); window.focus(); }); registry.byId('buttonThumbnail').on('change', function(newValue) { if (newValue) { domClass.add('bucketFrame', 'makeThumbnail'); } else { domClass.remove('bucketFrame', 'makeThumbnail'); } }); var demoContainers = query('.demosContainer'); demoContainers.forEach(function(demoContainer) { registerScroll(demoContainer); }); var galleryContainer = registry.byId('innerPanel'); galleryContainer.demoTileHeightRule = demoTileHeightRule; galleryContainer.originalResize = galleryContainer.resize; galleryContainer.resize = function(changeSize, resultSize) { var newSize = changeSize.h - 88; if (newSize < 20) { demoTileHeightRule.style.display = 'none'; } else { demoTileHeightRule.style.display = 'inline'; demoTileHeightRule.style.height = Math.min(newSize, 150) + 'px'; } this.originalResize(changeSize, resultSize); }; function requestDemo(name) { return xhr.get({ url: 'gallery/' + name + '.html', handleAs: 'text', error: function(error) { loadFromGallery(gallery_demos[hello_world_index]).then(function() { deferredLoadError = true; }); } }); } // Work around Chrome 79 bug: https://github.com/AnalyticalGraphicsInc/cesium/issues/8460 function waitForDoc(doc, test) { var deferred = new Deferred(); if (test()) { deferred.resolve(doc); } else { var counter = 1; setTimeout(function() { if (test() || counter++ > 10) { deferred.resolve(doc); } }, 100 * counter); } return deferred.promise; } var newInLabel = 'New in ' + VERSION; function loadDemoFromFile(demo) { return requestDemo(demo.name).then(function(value) { // Store the file contents for later searching. demo.code = value; var parser = new DOMParser(); var doc = parser.parseFromString(value, 'text/html'); return waitForDoc(doc, function(){ return doc.body.getAttribute('data-sandcastle-bucket'); }); }).then(function(doc) { var bucket = doc.body.getAttribute('data-sandcastle-bucket'); demo.bucket = bucket ? bucket : 'bucket-requirejs.html'; var descriptionMeta = doc.querySelector('meta[name="description"]'); var description = descriptionMeta && descriptionMeta.getAttribute('content'); demo.description = description ? description : ''; var labelsMeta = doc.querySelector('meta[name="cesium-sandcastle-labels"]'); var labels = labelsMeta && labelsMeta.getAttribute('content'); if (demo.isNew) { demo.label = labels ? labels + ',' + newInLabel : newInLabel; } else { demo.label = labels ? labels : ''; } // Select the demo to load upon opening based on the query parameter. if (defined(queryObject.src)) { if (demo.name === queryObject.src.replace('.html', '')) { loadFromGallery(demo).then(function() { window.history.replaceState(demo, demo.name, getPushStateUrl(demo)); if (defined(queryObject.gist)) { document.title = 'Gist Import - Cesium Sandcastle'; } else { document.title = demo.name + ' - Cesium Sandcastle'; } }); } } // Create a tooltip containing the demo's description. demoTooltips[demo.name] = new TooltipDialog({ id : demo.name + 'TooltipDialog', style : 'width: 200px; font-size: 12px;', content : demo.description.replace(/\\n/g, '<br/>') }); addFileToTab(demo); return demo; }); } var loading = true; function setSubtab(tabName) { currentTab = defined(tabName) && !loading ? tabName : queryObject.label; queryObject.label = tabName; loading = false; } function insertSortedById(parentTab, galleryButton) { var child; for (child = parentTab.lastChild; child !== null; child = child.previousSibling) { if (galleryButton.id >= child.id) { parentTab.insertBefore(galleryButton, child.nextSibling); return; } } parentTab.appendChild(galleryButton); } function addFileToGallery(demo) { var searchDemos = dom.byId('searchDemos'); insertSortedById(searchDemos, createGalleryButton(demo, 'searchDemo')); return loadDemoFromFile(demo); } function onShowCallback() { return function() { setSubtab(this.title); }; } function addFileToTab(demo) { if (demo.label !== '') { var labels = demo.label.split(','); for (var j = 0; j < labels.length; j++) { var label = labels[j]; label = label.trim(); if (!dom.byId(label + 'Demos')) { var cp = new ContentPane({ content : '<div id="' + label + 'Container" class="demosContainer"><div class="demos" id="' + label + 'Demos"></div></div>', title : label, onShow : onShowCallback() }).placeAt('innerPanel'); subtabs[label] = cp; registerScroll(dom.byId(label + 'Container')); } var tabName = label + 'Demos'; var tab = dom.byId(tabName); insertSortedById(tab, createGalleryButton(demo, tabName)); } } } function createGalleryButton(demo, tabName) { var imgSrc = 'templates/Gallery_tile.jpg'; if (defined(demo.img)) { imgSrc = 'gallery/' + demo.img; } var demoLink = document.createElement('a'); demoLink.id = demo.name + tabName; demoLink.className = 'linkButton'; demoLink.href = 'gallery/' + encodeURIComponent(demo.name) + '.html'; if (demo.name === 'Hello World') { newDemo = demo; } demoLink.onclick = function(e) { if (mouse.isMiddle(e)) { window.open('gallery/' + demo.name + '.html'); } else { var htmlText = (htmlEditor.getValue()).replace(/\s/g, ''); var jsText = (jsEditor.getValue()).replace(/\s/g, ''); var confirmChange = true; if (demoHtml !== htmlText || demoCode !== jsText) { confirmChange = window.confirm('You have unsaved changes. Are you sure you want to navigate away from this demo?'); } if (confirmChange) { delete queryObject.gist; delete queryObject.code; window.history.pushState(demo, demo.name, getPushStateUrl(demo)); loadFromGallery(demo).then(function() { document.title = demo.name + ' - Cesium Sandcastle'; }); } } e.preventDefault(); }; new LinkButton({ 'label' : '<div class="demoTileTitle">' + demo.name + '</div>' + '<img src="' + imgSrc + '" class="demoTileThumbnail" alt="" onDragStart="return false;" />' }).placeAt(demoLink); on(demoLink, 'mouseover', function() { scheduleGalleryTooltip(demo); }); on(demoLink, 'mouseout', function() { closeGalleryTooltip(); }); return demoLink; } var promise; if (!defined(gallery_demos)) { galleryErrorMsg.textContent = 'No demos found, please run the build script.'; galleryErrorMsg.style.display = 'inline-block'; } else { var label = 'Showcases'; var cp = new ContentPane({ content : '<div id="showcasesContainer" class="demosContainer"><div class="demos" id="ShowcasesDemos"></div></div>', title : 'Showcases', onShow : function() { setSubtab(this.title); } }).placeAt('innerPanel'); subtabs[label] = cp; registerScroll(dom.byId('showcasesContainer')); if (has_new_gallery_demos) { var name = 'New in ' + VERSION; subtabs[name] = new ContentPane({ content: '<div id="' + name + 'Container" class="demosContainer"><div class="demos" id="' + name + 'Demos"></div></div>', title: name, onShow: function() { setSubtab(this.title); } }).placeAt('innerPanel'); registerScroll(dom.byId(name + 'Container')); } var i; var len = gallery_demos.length; var queryInGalleryIndex = false; var queryName = queryObject.src.replace('.html', ''); var promises = []; for (i = 0; i < len; ++i) { promises.push(addFileToGallery(gallery_demos[i])); } promise = all(promises).then(function(results) { var resultsLength = results.length; for (i = 0; i < resultsLength; ++i) { if (results[i].name === queryName) { queryInGalleryIndex = true; } } label = 'All'; cp = new ContentPane({ content : '<div id="allContainer" class="demosContainer"><div class="demos" id="allDemos"></div></div>', title : label, onShow : function() { setSubtab(this.title); } }).placeAt('innerPanel'); subtabs[label] = cp; registerScroll(dom.byId('allContainer')); var demos = dom.byId('allDemos'); for (i = 0; i < len; ++i) { var demo = gallery_demos[i]; if (!/Development/i.test(demo.label)) { insertSortedById(demos, createGalleryButton(demo, 'all')); } } if (!queryInGalleryIndex) { var emptyDemo = { name : queryName, description : '' }; gallery_demos.push(emptyDemo); return addFileToGallery(emptyDemo); } }); } when(promise).then(function() { dom.byId('searchDemos').appendChild(galleryErrorMsg); searchContainer = registry.byId('searchContainer'); hideSearchContainer(); registry.byId('innerPanel').selectChild(subtabs[currentTab]); }); });
Apps/Sandcastle/CesiumSandcastle.js
/*global JSHINT */ /*global decodeBase64Data, embedInSandcastleTemplate */ /*global gallery_demos, has_new_gallery_demos, hello_world_index, VERSION*/// defined in gallery/gallery-index.js, created by build /*global sandcastleJsHintOptions*/// defined by jsHintOptions.js, created by build require({ baseUrl: '../../Source', packages: [{ name: 'dojo', location: '../ThirdParty/dojo-release-1.10.4/dojo' }, { name: 'dijit', location: '../ThirdParty/dojo-release-1.10.4/dijit' }, { name: 'Sandcastle', location: '../Apps/Sandcastle' }, { name: 'CodeMirror', location: '../ThirdParty/codemirror-4.6' }, { name: 'ThirdParty', location: '../Apps/Sandcastle/ThirdParty' }] }, [ 'CodeMirror/lib/codemirror', 'dijit/Dialog', 'dijit/form/Button', 'dijit/form/Form', 'dijit/form/Textarea', 'dijit/layout/ContentPane', 'dijit/popup', 'dijit/registry', 'dijit/TooltipDialog', 'dojo/_base/fx', 'dojo/_base/xhr', 'dojo/dom', 'dojo/dom-class', 'dojo/dom-construct', 'dojo/io-query', 'dojo/mouse', 'dojo/on', 'dojo/parser', 'dojo/promise/all', 'dojo/query', 'dojo/when', 'dojo/request/script', 'Sandcastle/LinkButton', 'ThirdParty/clipboard.min', 'ThirdParty/pako.min', 'CodeMirror/addon/hint/show-hint', 'CodeMirror/addon/hint/javascript-hint', 'CodeMirror/mode/javascript/javascript', 'CodeMirror/mode/css/css', 'CodeMirror/mode/xml/xml', 'CodeMirror/mode/htmlmixed/htmlmixed', 'dijit/form/DropDownButton', 'dijit/form/ToggleButton', 'dijit/form/DropDownButton', 'dijit/form/TextBox', 'dijit/Menu', 'dijit/MenuBar', 'dijit/PopupMenuBarItem', 'dijit/MenuItem', 'dijit/layout/BorderContainer', 'dijit/layout/TabContainer', 'dijit/Toolbar', 'dijit/ToolbarSeparator', 'dojo/domReady!' ], function( CodeMirror, Dialog, Button, Form, TextArea, ContentPane, popup, registry, TooltipDialog, fx, xhr, dom, domClass, domConstruct, ioQuery, mouse, on, parser, all, query, when, dojoscript, LinkButton, ClipboardJS, pako) { 'use strict'; // attach clipboard handling to our Copy button var clipboardjs = new ClipboardJS('.copyButton'); function defined(value) { return value !== undefined && value !== null; } parser.parse(); fx.fadeOut({ node : 'loading', onEnd : function() { domConstruct.destroy('loading'); } }).play(); var numberOfNewConsoleMessages = 0; var logOutput = document.getElementById('logOutput'); function appendConsole(className, message, showConsole) { var ele = document.createElement('span'); ele.className = className; ele.textContent = message + '\n'; logOutput.appendChild(ele); logOutput.parentNode.scrollTop = logOutput.clientHeight + 8 - logOutput.parentNode.clientHeight; if (showConsole) { hideGallery(); } else { ++numberOfNewConsoleMessages; registry.byId('logContainer').set('title', 'Console (' + numberOfNewConsoleMessages + ')'); } } var URL = window.URL || window.webkitURL; function findCssStyle(selectorText) { for (var iSheets = 0, lenSheets = document.styleSheets.length; iSheets < lenSheets; ++iSheets) { var rules = document.styleSheets[iSheets].cssRules; for (var iRules = 0, lenRules = rules.length; iRules < lenRules; ++iRules) { if (rules[iRules].selectorText === selectorText) { return rules[iRules]; } } } } var jsEditor; var htmlEditor; var suggestButton = registry.byId('buttonSuggest'); var docTimer; var docTabs = {}; var subtabs = {}; var docError = false; var galleryError = false; var deferredLoadError = false; var galleryTooltipTimer; var activeGalleryTooltipDemo; var demoTileHeightRule = findCssStyle('.demoTileThumbnail'); var cesiumContainer = registry.byId('cesiumContainer'); var docNode = dom.byId('docPopup'); var docMessage = dom.byId('docPopupMessage'); var local = { 'docTypes' : [], 'headers' : '<html><head></head><body>', 'bucketName' : '', 'emptyBucket' : '' }; var bucketTypes = {}; var demoTooltips = {}; var errorLines = []; var highlightLines = []; var searchTerm = ''; var searchRegExp; var hintTimer; var defaultDemo = 'Hello World'; var defaultLabel = 'Showcases'; var currentTab = defaultLabel; var newDemo; var demoHtml = ''; var demoCode = ''; var defaultHtml = '<style>\n@import url(../templates/bucket.css);\n</style>\n<div id=\"cesiumContainer\" class=\"fullSize\"></div>\n<div id=\"loadingOverlay\"><h1>Loading...</h1></div>\n<div id=\"toolbar\"></div>'; var galleryErrorMsg = document.createElement('span'); galleryErrorMsg.className = 'galleryError'; galleryErrorMsg.style.display = 'none'; galleryErrorMsg.textContent = 'No demos match your search terms.'; var bucketFrame = document.getElementById('bucketFrame'); var bucketPane = registry.byId('bucketPane'); var bucketWaiting = false; xhr.get({ url : '../../Build/Documentation/types.txt', handleAs : 'json', error : function(error) { docError = true; } }).then(function(value) { local.docTypes = value; }); var decoderSpan = document.createElement('span'); function encodeHTML(text) { decoderSpan.textContent = text; text = decoderSpan.innerHTML; decoderSpan.innerHTML = ''; return text; } function decodeHTML(text) { decoderSpan.innerHTML = text; text = decoderSpan.textContent; decoderSpan.innerHTML = ''; return text; } function highlightRun() { domClass.add(registry.byId('buttonRun').domNode, 'highlightToolbarButton'); } function clearRun() { domClass.remove(registry.byId('buttonRun').domNode, 'highlightToolbarButton'); } function openDocTab(title, link) { if (!defined(docTabs[title])) { docTabs[title] = new ContentPane({ title : title, focused : true, content : '<iframe class="fullFrame" src="' + link + '"></iframe>', closable : true, onClose : function() { docTabs[this.title] = undefined; // Return true to close the tab. return true; } }).placeAt(cesiumContainer); // After the iframe loads, re-scroll to selected field. docTabs[title].domNode.childNodes[0].onload = function() { this.onload = function() { }; this.src = link; }; cesiumContainer.selectChild(docTabs[title]); } else { // Tab already exists, but maybe not visible. Firefox needs the tab to // be revealed before a re-scroll can happen. Chrome works either way. cesiumContainer.selectChild(docTabs[title]); docTabs[title].domNode.childNodes[0].src = link; } } function showDocPopup() { var selectedText = jsEditor.getSelection(); var lowerText = selectedText.toLowerCase(); var onDocClick = function() { openDocTab(this.textContent, this.href); return false; }; docTimer = undefined; if (docError && selectedText && selectedText.length < 50) { hideGallery(); } else if (lowerText && lowerText in local.docTypes && typeof local.docTypes[lowerText].push === 'function') { docMessage.innerHTML = ''; for (var i = 0, len = local.docTypes[lowerText].length; i < len; ++i) { var member = local.docTypes[lowerText][i]; var ele = document.createElement('a'); ele.target = '_blank'; ele.textContent = member.replace('.html', '').replace('module-', '').replace('#.', '.').replace('#', '.'); ele.href = '../../Build/Documentation/' + member; ele.onclick = onDocClick; docMessage.appendChild(ele); } jsEditor.addWidget(jsEditor.getCursor(true), docNode); docNode.style.top = (parseInt(docNode.style.top, 10) - 5) + 'px'; } } function onCursorActivity() { docNode.style.left = '-999px'; if (defined(docTimer)) { window.clearTimeout(docTimer); } docTimer = window.setTimeout(showDocPopup, 500); } function makeLineLabel(msg, className) { var element = document.createElement('abbr'); element.className = className; switch (className) { case 'hintMarker': element.innerHTML = '&#9650;'; break; case 'errorMarker': element.innerHTML = '&times;'; break; default: element.innerHTML = '&#9654;'; } element.title = msg; return element; } function closeGalleryTooltip() { if (defined(activeGalleryTooltipDemo)) { popup.close(demoTooltips[activeGalleryTooltipDemo.name]); activeGalleryTooltipDemo = undefined; } } function openGalleryTooltip() { galleryTooltipTimer = undefined; var selectedTabName = registry.byId('innerPanel').selectedChildWidget.title; var suffix = selectedTabName + 'Demos'; if (selectedTabName === 'All') { suffix = 'all'; } else if (selectedTabName === 'Search Results') { suffix = 'searchDemo'; } if (defined(activeGalleryTooltipDemo)) { popup.open({ popup : demoTooltips[activeGalleryTooltipDemo.name], around : dom.byId(activeGalleryTooltipDemo.name + suffix), orient : ['above', 'below'] }); } } function scheduleGalleryTooltip(demo) { if (demo !== activeGalleryTooltipDemo) { activeGalleryTooltipDemo = demo; if (defined(galleryTooltipTimer)) { window.clearTimeout(galleryTooltipTimer); } galleryTooltipTimer = window.setTimeout(openGalleryTooltip, 220); } } function scriptLineToEditorLine(line) { // editor lines are zero-indexed, plus 3 lines of boilerplate return line - 4; } function clearErrorsAddHints() { var line; var i; var len; hintTimer = undefined; closeGalleryTooltip(); jsEditor.clearGutter('hintGutter'); jsEditor.clearGutter('highlightGutter'); jsEditor.clearGutter('errorGutter'); jsEditor.clearGutter('searchGutter'); while (errorLines.length > 0) { line = errorLines.pop(); jsEditor.removeLineClass(line, 'text'); } while (highlightLines.length > 0) { line = highlightLines.pop(); jsEditor.removeLineClass(line, 'text'); } var code = jsEditor.getValue(); if (searchTerm !== '') { var codeLines = code.split('\n'); for (i = 0, len = codeLines.length; i < len; ++i) { if (searchRegExp.test(codeLines[i])) { line = jsEditor.setGutterMarker(i, 'searchGutter', makeLineLabel('Search: ' + searchTerm, 'searchMarker')); jsEditor.addLineClass(line, 'text', 'searchLine'); errorLines.push(line); } } } // make a copy of the options, JSHint modifies the object it's given var options = JSON.parse(JSON.stringify(sandcastleJsHintOptions)); /*eslint-disable new-cap*/ if (!JSHINT(embedInSandcastleTemplate(jsEditor.getValue(), false), options)) { var hints = JSHINT.errors; for (i = 0, len = hints.length; i < len; ++i) { var hint = hints[i]; if (hint !== null && defined(hint.reason) && hint.line > 0) { line = jsEditor.setGutterMarker(scriptLineToEditorLine(hint.line), 'hintGutter', makeLineLabel(hint.reason, 'hintMarker')); jsEditor.addLineClass(line, 'text', 'hintLine'); errorLines.push(line); } } } /*eslint-enable new-cap*/ } function scheduleHint() { if (defined(hintTimer)) { window.clearTimeout(hintTimer); } hintTimer = setTimeout(clearErrorsAddHints, 550); highlightRun(); } function scheduleHintNoChange() { if (defined(hintTimer)) { window.clearTimeout(hintTimer); } hintTimer = setTimeout(clearErrorsAddHints, 550); } function scrollToLine(lineNumber) { if (defined(lineNumber)) { jsEditor.setCursor(lineNumber); // set selection twice in order to force the editor to scroll // to this location if the cursor is already there jsEditor.setSelection({ line : lineNumber - 1, ch : 0 }, { line : lineNumber - 1, ch : 0 }); jsEditor.focus(); jsEditor.setSelection({ line : lineNumber, ch : 0 }, { line : lineNumber, ch : 0 }); } } function highlightLine(lineNum) { var line; jsEditor.clearGutter('highlightGutter'); while (highlightLines.length > 0) { line = highlightLines.pop(); jsEditor.removeLineClass(line, 'text'); } if (lineNum > 0) { lineNum = scriptLineToEditorLine(lineNum); line = jsEditor.setGutterMarker(lineNum, 'highlightGutter', makeLineLabel('highlighted by demo', 'highlightMarker')); jsEditor.addLineClass(line, 'text', 'highlightLine'); highlightLines.push(line); scrollToLine(lineNum); } } var tabs = registry.byId('bottomPanel'); function showGallery() { tabs.selectChild(registry.byId('innerPanel')); } function hideGallery() { closeGalleryTooltip(); tabs.selectChild(registry.byId('logContainer')); } tabs.watch('selectedChildWidget', function(name, oldValue, newValue) { if (newValue === registry.byId('logContainer')) { numberOfNewConsoleMessages = 0; registry.byId('logContainer').set('title', 'Console'); } }); function registerScroll(demoContainer) { if (document.onmousewheel !== undefined) { demoContainer.addEventListener('mousewheel', function(e) { if (defined(e.wheelDelta) && e.wheelDelta) { demoContainer.scrollLeft -= e.wheelDelta * 70 / 120; } }, false); } else { demoContainer.addEventListener('DOMMouseScroll', function(e) { if (defined(e.detail) && e.detail) { demoContainer.scrollLeft += e.detail * 70 / 3; } }, false); } } CodeMirror.commands.runCesium = function(cm) { clearErrorsAddHints(); clearRun(); cesiumContainer.selectChild(bucketPane); // Check for a race condition in some browsers where the iframe hasn't loaded yet. if (bucketFrame.contentWindow.location.href.indexOf('bucket.html') > 0) { bucketFrame.contentWindow.location.reload(); } }; jsEditor = CodeMirror.fromTextArea(document.getElementById('code'), { mode : 'javascript', gutters : ['hintGutter', 'errorGutter', 'searchGutter', 'highlightGutter'], lineNumbers : true, matchBrackets : true, indentUnit : 4, extraKeys : { 'Ctrl-Space' : 'autocomplete', 'F8' : 'runCesium', 'Tab' : 'indentMore', 'Shift-Tab' : 'indentLess' } }); jsEditor.on('cursorActivity', onCursorActivity); jsEditor.on('change', scheduleHint); htmlEditor = CodeMirror.fromTextArea(document.getElementById('htmlBody'), { mode : 'text/html', lineNumbers : true, matchBrackets : true, indentUnit : 4, extraKeys : { 'F8' : 'runCesium', 'Tab' : 'indentMore', 'Shift-Tab' : 'indentLess' } }); window.onbeforeunload = function (e) { var htmlText = (htmlEditor.getValue()).replace(/\s/g, ''); var jsText = (jsEditor.getValue()).replace(/\s/g, ''); if (demoHtml !== htmlText || demoCode !== jsText) { return 'Be sure to save a copy of any important edits before leaving this page.'; } }; registry.byId('codeContainer').watch('selectedChildWidget', function(name, oldPane, newPane) { if (newPane.id === 'jsContainer') { jsEditor.focus(); } else if (newPane.id === 'htmlContainer') { htmlEditor.focus(); } }); var scriptCodeRegex = /\/\/Sandcastle_Begin\s*([\s\S]*)\/\/Sandcastle_End/; function activateBucketScripts(bucketDoc) { var headNodes = bucketDoc.head.childNodes; var node; var nodes = []; var i, len; for (i = 0, len = headNodes.length; i < len; ++i) { node = headNodes[i]; // header is included in blank frame. if (node.tagName === 'SCRIPT' && node.src.indexOf('Sandcastle-header.js') < 0) { nodes.push(node); } } for (i = 0, len = nodes.length; i < len; ++i) { bucketDoc.head.removeChild(nodes[i]); } // Apply user HTML to bucket. var htmlElement = bucketDoc.createElement('div'); htmlElement.innerHTML = htmlEditor.getValue(); bucketDoc.body.appendChild(htmlElement); var onScriptTagError = function() { if (bucketFrame.contentDocument === bucketDoc) { appendConsole('consoleError', 'Error loading ' + this.src, true); appendConsole('consoleError', "Make sure Cesium is built, see the Contributor's Guide for details.", true); } }; // Load each script after the previous one has loaded. var loadScript = function() { if (bucketFrame.contentDocument !== bucketDoc) { // A newer reload has happened, abort this. return; } if (nodes.length > 0) { while(nodes.length > 0){ node = nodes.shift(); var scriptElement = bucketDoc.createElement('script'); var hasSrc = false; for (var j = 0, numAttrs = node.attributes.length; j < numAttrs; ++j) { var name = node.attributes[j].name; var val = node.attributes[j].value; scriptElement.setAttribute(name, val); if (name === 'src' && val) { hasSrc = true; } } scriptElement.innerHTML = node.innerHTML; if (hasSrc) { scriptElement.onload = loadScript; scriptElement.onerror = onScriptTagError; bucketDoc.head.appendChild(scriptElement); } else { bucketDoc.head.appendChild(scriptElement); loadScript(); } } } else { // Apply user JS to bucket var element = bucketDoc.createElement('script'); // Firefox line numbers are zero-based, not one-based. var isFirefox = navigator.userAgent.indexOf('Firefox/') >= 0; element.textContent = embedInSandcastleTemplate(jsEditor.getValue(), isFirefox); bucketDoc.body.appendChild(element); } }; loadScript(); } function applyBucket() { if (local.emptyBucket && local.bucketName && typeof bucketTypes[local.bucketName] === 'string') { bucketWaiting = false; var bucketDoc = bucketFrame.contentDocument; if (local.headers.substring(0, local.emptyBucket.length) !== local.emptyBucket) { appendConsole('consoleError', 'Error, first part of ' + local.bucketName + ' must match first part of bucket.html exactly.', true); } else { var bodyAttributes = local.headers.match(/<body([^>]*?)>/)[1]; var attributeRegex = /([-a-z_]+)\s*="([^"]*?)"/ig; //group 1 attribute name, group 2 attribute value. Assumes double-quoted attributes. var attributeMatch; while ((attributeMatch = attributeRegex.exec(bodyAttributes)) !== null) { var attributeName = attributeMatch[1]; var attributeValue = attributeMatch[2]; if (attributeName === 'class') { bucketDoc.body.className = attributeValue; } else { bucketDoc.body.setAttribute(attributeName, attributeValue); } } var pos = local.headers.indexOf('</head>'); var extraHeaders = local.headers.substring(local.emptyBucket.length, pos); bucketDoc.head.innerHTML += extraHeaders; activateBucketScripts(bucketDoc); } } else { bucketWaiting = true; } } function applyBucketIfWaiting() { if (bucketWaiting) { applyBucket(); } } xhr.get({ url : 'templates/bucket.html', handleAs : 'text' }).then(function(value) { var pos = value.indexOf('</head>'); local.emptyBucket = value.substring(0, pos); applyBucketIfWaiting(); }); function loadBucket(bucketName) { if (local.bucketName !== bucketName) { local.bucketName = bucketName; if (defined(bucketTypes[bucketName])) { local.headers = bucketTypes[bucketName]; } else { local.headers = '<html><head></head><body data-sandcastle-bucket-loaded="no">'; xhr.get({ url : 'templates/' + bucketName, handleAs : 'text' }).then(function(value) { var pos = value.indexOf('<body'); pos = value.indexOf('>', pos); bucketTypes[bucketName] = value.substring(0, pos + 1); if (local.bucketName === bucketName) { local.headers = bucketTypes[bucketName]; } applyBucketIfWaiting(); }); } } } var queryObject = {}; if (window.location.search) { queryObject = ioQuery.queryToObject(window.location.search.substring(1)); } if (!defined(queryObject.src)) { queryObject.src = defaultDemo + '.html'; } if (!defined(queryObject.label)) { queryObject.label = defaultLabel; } function loadFromGallery(demo) { deferredLoadError = false; document.getElementById('saveAsFile').download = demo.name + '.html'; registry.byId('description').set('value', decodeHTML(demo.description).replace(/\\n/g, '\n')); registry.byId('label').set('value', decodeHTML(demo.label).replace(/\\n/g, '\n')); return requestDemo(demo.name).then(function(value) { demo.code = value; if (typeof demo.bucket === 'string') { loadBucket(demo.bucket); } function applyLoadedDemo(code, html) { jsEditor.setValue(code); jsEditor.clearHistory(); htmlEditor.setValue(html); htmlEditor.clearHistory(); demoCode = code.replace(/\s/g, ''); demoHtml = html.replace(/\s/g, ''); CodeMirror.commands.runCesium(jsEditor); clearRun(); } var json, code, html; if (defined(queryObject.gist)) { dojoscript.get('https://api.github.com/gists/' + queryObject.gist + '?access_token=dd8f755c2e5d9bbb26806bb93eaa2291f2047c60', { jsonp: 'callback' }).then(function(data) { var files = data.data.files; var code = files['Cesium-Sandcastle.js'].content; var htmlFile = files['Cesium-Sandcastle.html']; var html = defined(htmlFile) ? htmlFile.content : defaultHtml; // Use the default html for old gists applyLoadedDemo(code, html); }).otherwise(function(error) { appendConsole('consoleError', 'Unable to GET from GitHub API. This could be due to too many request, try again in an hour or copy and paste the code from the gist: https://gist.github.com/' + queryObject.gist, true); console.log(error); }); } else if (defined(queryObject.code)) { //The code query parameter is a Base64 encoded JSON string with `code` and `html` properties. json = JSON.parse(window.atob(queryObject.code)); code = json.code; html = json.html; applyLoadedDemo(code, html); } else if (window.location.hash.indexOf('#c=') === 0) { var base64String = window.location.hash.substr(3); var data = decodeBase64Data(base64String, pako); code = data.code; html = data.html; applyLoadedDemo(code, html); } else { var parser = new DOMParser(); var doc = parser.parseFromString(demo.code, 'text/html'); var script = doc.querySelector('script[id="cesium_sandcastle_script"]'); if (!script) { appendConsole('consoleError', 'Error reading source file: ' + demo.name, true); return; } var scriptMatch = scriptCodeRegex.exec(script.textContent); if (!scriptMatch) { appendConsole('consoleError', 'Error reading source file: ' + demo.name, true); return; } var scriptCode = scriptMatch[1]; var htmlText = ''; var childIndex = 0; var childNode = doc.body.childNodes[childIndex]; while (childIndex < doc.body.childNodes.length && childNode !== script) { htmlText += childNode.nodeType === 1 ? childNode.outerHTML : childNode.nodeValue; childNode = doc.body.childNodes[++childIndex]; } htmlText = htmlText.replace(/^\s+/, ''); applyLoadedDemo(scriptCode, htmlText); } }); } window.addEventListener('popstate', function(e) { if (e.state && e.state.name && e.state.code) { loadFromGallery(e.state); document.title = e.state.name + ' - Cesium Sandcastle'; } }, false); window.addEventListener('message', function(e) { var line; // The iframe (bucket.html) sends this message on load. // This triggers the code to be injected into the iframe. if (e.data === 'reload') { var bucketDoc = bucketFrame.contentDocument; if (!local.bucketName) { // Reload fired, bucket not specified yet. return; } if (bucketDoc.body.getAttribute('data-sandcastle-loaded') !== 'yes') { bucketDoc.body.setAttribute('data-sandcastle-loaded', 'yes'); logOutput.innerHTML = ''; numberOfNewConsoleMessages = 0; registry.byId('logContainer').set('title', 'Console'); // This happens after a Run (F8) reloads bucket.html, to inject the editor code // into the iframe, causing the demo to run there. applyBucket(); if (docError) { appendConsole('consoleError', 'Documentation not available. Please run the "generateDocumentation" build script to generate Cesium documentation.', true); showGallery(); } if (galleryError) { appendConsole('consoleError', 'Error loading gallery, please run the build script.', true); } if (deferredLoadError) { appendConsole('consoleLog', 'Unable to load demo named ' + queryObject.src.replace('.html', '') + '. Redirecting to HelloWorld.\n', true); } } } else if (defined(e.data.log)) { // Console log messages from the iframe display in Sandcastle. appendConsole('consoleLog', e.data.log, false); } else if (defined(e.data.error)) { // Console error messages from the iframe display in Sandcastle var errorMsg = e.data.error; var lineNumber = e.data.lineNumber; if (defined(lineNumber)) { errorMsg += ' (on line '; if (e.data.url) { errorMsg += lineNumber + ' of ' + e.data.url + ')'; } else { lineNumber = scriptLineToEditorLine(lineNumber); errorMsg += (lineNumber + 1) + ')'; line = jsEditor.setGutterMarker(lineNumber, 'errorGutter', makeLineLabel(e.data.error, 'errorMarker')); jsEditor.addLineClass(line, 'text', 'errorLine'); errorLines.push(line); scrollToLine(lineNumber); } } appendConsole('consoleError', errorMsg, true); } else if (defined(e.data.warn)) { // Console warning messages from the iframe display in Sandcastle. appendConsole('consoleWarn', e.data.warn, true); } else if (defined(e.data.highlight)) { // Hovering objects in the embedded Cesium window. highlightLine(e.data.highlight); } }, true); registry.byId('jsContainer').on('show', function() { suggestButton.set('disabled', false); jsEditor.refresh(); }); registry.byId('htmlContainer').on('show', function() { suggestButton.set('disabled', true); htmlEditor.refresh(); }); registry.byId('search').on('change', function() { searchTerm = this.get('value'); searchRegExp = new RegExp(searchTerm, 'i'); var numDemosShown = 0; if (searchTerm !== '') { showSearchContainer(); var innerPanel = registry.byId('innerPanel'); innerPanel.selectChild(registry.byId('searchContainer')); for (var i = 0; i < gallery_demos.length; i++) { var demo = gallery_demos[i]; var demoName = demo.name; if (searchRegExp.test(demoName) || searchRegExp.test(demo.code)) { document.getElementById(demoName + 'searchDemo').style.display = 'inline-block'; ++numDemosShown; } else { document.getElementById(demoName + 'searchDemo').style.display = 'none'; } } } else { hideSearchContainer(); } if (numDemosShown) { galleryErrorMsg.style.display = 'none'; } else { galleryErrorMsg.style.display = 'inline-block'; } showGallery(); scheduleHintNoChange(); }); var searchContainer; function hideSearchContainer() { if (dom.byId('searchContainer')) { var innerPanel = registry.byId('innerPanel'); innerPanel.removeChild(searchContainer); } } function showSearchContainer() { if (!dom.byId('searchContainer')) { var innerPanel = registry.byId('innerPanel'); innerPanel.addChild(searchContainer); } } function getBaseUrl() { // omits query string and hash return location.protocol + '//' + location.host + location.pathname; } function makeCompressedBase64String(data) { // data stored in the hash as: // Base64 encoded, raw DEFLATE compressed JSON array where index 0 is code, index 1 is html var jsonString = JSON.stringify(data); // we save a few bytes by omitting the leading [" and trailing "] since they are always the same jsonString = jsonString.substr(2, jsonString.length - 4); var base64String = btoa(pako.deflate(jsonString, { raw: true, to: 'string', level: 9 })); base64String = base64String.replace(/\=+$/, ''); // remove padding return base64String; } registry.byId('buttonShareDrop').on('click', function() { var code = jsEditor.getValue(); var html = htmlEditor.getValue(); var base64String = makeCompressedBase64String([code, html]); var shareUrlBox = document.getElementById('shareUrl'); shareUrlBox.value = getBaseUrl() + '#c=' + base64String; shareUrlBox.select(); }); registry.byId('buttonImport').on('click', function() { var gistId = document.getElementById('gistId').value; var gistParameter = '&gist='; var gistIndex = gistId.indexOf(gistParameter); if (gistIndex !== -1) { gistId = gistId.substring(gistIndex + gistParameter.length); } window.location.href = getBaseUrl() + '?gist=' + gistId; }); function getPushStateUrl(demo) { var obj = {}; if (demo.name !== defaultDemo) { obj.src = demo.name + '.html'; } if (currentTab !== defaultLabel) { obj.label = currentTab; } var query = ioQuery.objectToQuery(obj); return query === '' ? query : '?' + query; } registry.byId('buttonNew').on('click', function() { var htmlText = (htmlEditor.getValue()).replace(/\s/g, ''); var jsText = (jsEditor.getValue()).replace(/\s/g, ''); var confirmChange = true; if (demoHtml !== htmlText || demoCode !== jsText) { confirmChange = window.confirm('You have unsaved changes. Are you sure you want to navigate away from this demo?'); } if (confirmChange) { window.history.pushState(newDemo, newDemo.name, getPushStateUrl(newDemo)); loadFromGallery(newDemo).then(function() { document.title = newDemo.name + ' - Cesium Sandcastle'; }); } }); // Clicking the 'Run' button simply reloads the iframe. registry.byId('buttonRun').on('click', function() { CodeMirror.commands.runCesium(jsEditor); }); registry.byId('buttonSuggest').on('click', function() { CodeMirror.commands.autocomplete(jsEditor); }); function getDemoHtml() { return local.headers + '\n' + htmlEditor.getValue() + '<script id="cesium_sandcastle_script">\n' + embedInSandcastleTemplate(jsEditor.getValue(), false) + '</script>\n' + '</body>\n' + '</html>\n'; } registry.byId('dropDownSaveAs').on('show', function() { var currentDemoName = queryObject.src; currentDemoName = currentDemoName.replace('.html', ''); var description = encodeHTML(registry.byId('description').get('value').replace(/\n/g, '\\n')).replace(/\"/g, '&quot;'); var label = encodeHTML(registry.byId('label').get('value').replace(/\n/g, '\\n')).replace(/\"/g, '&quot;'); var html = getDemoHtml(); html = html.replace('<title>', '<meta name="description" content="' + description + '">\n <title>'); html = html.replace('<title>', '<meta name="cesium-sandcastle-labels" content="' + label + '">\n <title>'); var octetBlob = new Blob([html], { 'type' : 'application/octet-stream', 'endings' : 'native' }); var octetBlobURL = URL.createObjectURL(octetBlob); dom.byId('saveAsFile').href = octetBlobURL; }); registry.byId('buttonNewWindow').on('click', function() { //Handle case where demo is in a sub-directory by modifying //the demo's HTML to add a base href. var baseHref = getBaseUrl(); var pos = baseHref.lastIndexOf('/'); baseHref = baseHref.substring(0, pos) + '/gallery/'; var code = jsEditor.getValue(); var html = htmlEditor.getValue(); var data = makeCompressedBase64String([code, html, baseHref]); var url = getBaseUrl(); url = url.replace('index.html','') + 'standalone.html' + '#c=' + data; window.open(url, '_blank'); window.focus(); }); registry.byId('buttonThumbnail').on('change', function(newValue) { if (newValue) { domClass.add('bucketFrame', 'makeThumbnail'); } else { domClass.remove('bucketFrame', 'makeThumbnail'); } }); var demoContainers = query('.demosContainer'); demoContainers.forEach(function(demoContainer) { registerScroll(demoContainer); }); var galleryContainer = registry.byId('innerPanel'); galleryContainer.demoTileHeightRule = demoTileHeightRule; galleryContainer.originalResize = galleryContainer.resize; galleryContainer.resize = function(changeSize, resultSize) { var newSize = changeSize.h - 88; if (newSize < 20) { demoTileHeightRule.style.display = 'none'; } else { demoTileHeightRule.style.display = 'inline'; demoTileHeightRule.style.height = Math.min(newSize, 150) + 'px'; } this.originalResize(changeSize, resultSize); }; function requestDemo(name) { return xhr.get({ url: 'gallery/' + name + '.html', handleAs: 'text', error: function(error) { loadFromGallery(gallery_demos[hello_world_index]).then(function() { deferredLoadError = true; }); } }); } var newInLabel = 'New in ' + VERSION; function loadDemoFromFile(demo) { return requestDemo(demo.name).then(function(value) { // Store the file contents for later searching. demo.code = value; var parser = new DOMParser(); var doc = parser.parseFromString(value, 'text/html'); var bucket = doc.body.getAttribute('data-sandcastle-bucket'); demo.bucket = bucket ? bucket : 'bucket-requirejs.html'; var descriptionMeta = doc.querySelector('meta[name="description"]'); var description = descriptionMeta && descriptionMeta.getAttribute('content'); demo.description = description ? description : ''; var labelsMeta = doc.querySelector('meta[name="cesium-sandcastle-labels"]'); var labels = labelsMeta && labelsMeta.getAttribute('content'); if (demo.isNew) { demo.label = labels ? labels + ',' + newInLabel : newInLabel; } else { demo.label = labels ? labels : ''; } // Select the demo to load upon opening based on the query parameter. if (defined(queryObject.src)) { if (demo.name === queryObject.src.replace('.html', '')) { loadFromGallery(demo).then(function() { window.history.replaceState(demo, demo.name, getPushStateUrl(demo)); if (defined(queryObject.gist)) { document.title = 'Gist Import - Cesium Sandcastle'; } else { document.title = demo.name + ' - Cesium Sandcastle'; } }); } } // Create a tooltip containing the demo's description. demoTooltips[demo.name] = new TooltipDialog({ id : demo.name + 'TooltipDialog', style : 'width: 200px; font-size: 12px;', content : demo.description.replace(/\\n/g, '<br/>') }); addFileToTab(demo); return demo; }); } var loading = true; function setSubtab(tabName) { currentTab = defined(tabName) && !loading ? tabName : queryObject.label; queryObject.label = tabName; loading = false; } function insertSortedById(parentTab, galleryButton) { var child; for (child = parentTab.lastChild; child !== null; child = child.previousSibling) { if (galleryButton.id >= child.id) { parentTab.insertBefore(galleryButton, child.nextSibling); return; } } parentTab.appendChild(galleryButton); } function addFileToGallery(demo) { var searchDemos = dom.byId('searchDemos'); insertSortedById(searchDemos, createGalleryButton(demo, 'searchDemo')); return loadDemoFromFile(demo); } function onShowCallback() { return function() { setSubtab(this.title); }; } function addFileToTab(demo) { if (demo.label !== '') { var labels = demo.label.split(','); for (var j = 0; j < labels.length; j++) { var label = labels[j]; label = label.trim(); if (!dom.byId(label + 'Demos')) { var cp = new ContentPane({ content : '<div id="' + label + 'Container" class="demosContainer"><div class="demos" id="' + label + 'Demos"></div></div>', title : label, onShow : onShowCallback() }).placeAt('innerPanel'); subtabs[label] = cp; registerScroll(dom.byId(label + 'Container')); } var tabName = label + 'Demos'; var tab = dom.byId(tabName); insertSortedById(tab, createGalleryButton(demo, tabName)); } } } function createGalleryButton(demo, tabName) { var imgSrc = 'templates/Gallery_tile.jpg'; if (defined(demo.img)) { imgSrc = 'gallery/' + demo.img; } var demoLink = document.createElement('a'); demoLink.id = demo.name + tabName; demoLink.className = 'linkButton'; demoLink.href = 'gallery/' + encodeURIComponent(demo.name) + '.html'; if (demo.name === 'Hello World') { newDemo = demo; } demoLink.onclick = function(e) { if (mouse.isMiddle(e)) { window.open('gallery/' + demo.name + '.html'); } else { var htmlText = (htmlEditor.getValue()).replace(/\s/g, ''); var jsText = (jsEditor.getValue()).replace(/\s/g, ''); var confirmChange = true; if (demoHtml !== htmlText || demoCode !== jsText) { confirmChange = window.confirm('You have unsaved changes. Are you sure you want to navigate away from this demo?'); } if (confirmChange) { delete queryObject.gist; delete queryObject.code; window.history.pushState(demo, demo.name, getPushStateUrl(demo)); loadFromGallery(demo).then(function() { document.title = demo.name + ' - Cesium Sandcastle'; }); } } e.preventDefault(); }; new LinkButton({ 'label' : '<div class="demoTileTitle">' + demo.name + '</div>' + '<img src="' + imgSrc + '" class="demoTileThumbnail" alt="" onDragStart="return false;" />' }).placeAt(demoLink); on(demoLink, 'mouseover', function() { scheduleGalleryTooltip(demo); }); on(demoLink, 'mouseout', function() { closeGalleryTooltip(); }); return demoLink; } var promise; if (!defined(gallery_demos)) { galleryErrorMsg.textContent = 'No demos found, please run the build script.'; galleryErrorMsg.style.display = 'inline-block'; } else { var label = 'Showcases'; var cp = new ContentPane({ content : '<div id="showcasesContainer" class="demosContainer"><div class="demos" id="ShowcasesDemos"></div></div>', title : 'Showcases', onShow : function() { setSubtab(this.title); } }).placeAt('innerPanel'); subtabs[label] = cp; registerScroll(dom.byId('showcasesContainer')); if (has_new_gallery_demos) { var name = 'New in ' + VERSION; subtabs[name] = new ContentPane({ content: '<div id="' + name + 'Container" class="demosContainer"><div class="demos" id="' + name + 'Demos"></div></div>', title: name, onShow: function() { setSubtab(this.title); } }).placeAt('innerPanel'); registerScroll(dom.byId(name + 'Container')); } var i; var len = gallery_demos.length; var queryInGalleryIndex = false; var queryName = queryObject.src.replace('.html', ''); var promises = []; for (i = 0; i < len; ++i) { promises.push(addFileToGallery(gallery_demos[i])); } promise = all(promises).then(function(results) { var resultsLength = results.length; for (i = 0; i < resultsLength; ++i) { if (results[i].name === queryName) { queryInGalleryIndex = true; } } label = 'All'; cp = new ContentPane({ content : '<div id="allContainer" class="demosContainer"><div class="demos" id="allDemos"></div></div>', title : label, onShow : function() { setSubtab(this.title); } }).placeAt('innerPanel'); subtabs[label] = cp; registerScroll(dom.byId('allContainer')); var demos = dom.byId('allDemos'); for (i = 0; i < len; ++i) { var demo = gallery_demos[i]; if (!/Development/i.test(demo.label)) { insertSortedById(demos, createGalleryButton(demo, 'all')); } } if (!queryInGalleryIndex) { var emptyDemo = { name : queryName, description : '' }; gallery_demos.push(emptyDemo); return addFileToGallery(emptyDemo); } }); } when(promise).then(function() { dom.byId('searchDemos').appendChild(galleryErrorMsg); searchContainer = registry.byId('searchContainer'); hideSearchContainer(); registry.byId('innerPanel').selectChild(subtabs[currentTab]); }); });
Workaround Chrome 79 bug.
Apps/Sandcastle/CesiumSandcastle.js
Workaround Chrome 79 bug.
<ide><path>pps/Sandcastle/CesiumSandcastle.js <ide> 'dojo/promise/all', <ide> 'dojo/query', <ide> 'dojo/when', <add> 'dojo/Deferred', <ide> 'dojo/request/script', <ide> 'Sandcastle/LinkButton', <ide> 'ThirdParty/clipboard.min', <ide> all, <ide> query, <ide> when, <add> Deferred, <ide> dojoscript, <ide> LinkButton, <ide> ClipboardJS, <ide> var parser = new DOMParser(); <ide> var doc = parser.parseFromString(demo.code, 'text/html'); <ide> <add> return waitForDoc(doc, function(){ <add> return doc.querySelector('script[id="cesium_sandcastle_script"]'); <add> }).then(function(){ <add> <ide> var script = doc.querySelector('script[id="cesium_sandcastle_script"]'); <ide> if (!script) { <ide> appendConsole('consoleError', 'Error reading source file: ' + demo.name, true); <ide> htmlText = htmlText.replace(/^\s+/, ''); <ide> <ide> applyLoadedDemo(scriptCode, htmlText); <add> }); <ide> } <ide> }); <ide> } <ide> }); <ide> } <ide> <add> // Work around Chrome 79 bug: https://github.com/AnalyticalGraphicsInc/cesium/issues/8460 <add> function waitForDoc(doc, test) { <add> var deferred = new Deferred(); <add> if (test()) { <add> deferred.resolve(doc); <add> } else { <add> var counter = 1; <add> setTimeout(function() { <add> if (test() || counter++ > 10) { <add> deferred.resolve(doc); <add> } <add> }, 100 * counter); <add> } <add> return deferred.promise; <add> } <add> <ide> var newInLabel = 'New in ' + VERSION; <ide> function loadDemoFromFile(demo) { <ide> return requestDemo(demo.name).then(function(value) { <ide> <ide> var parser = new DOMParser(); <ide> var doc = parser.parseFromString(value, 'text/html'); <add> return waitForDoc(doc, function(){ <add> return doc.body.getAttribute('data-sandcastle-bucket'); <add> }); <add> }).then(function(doc) { <ide> <ide> var bucket = doc.body.getAttribute('data-sandcastle-bucket'); <ide> demo.bucket = bucket ? bucket : 'bucket-requirejs.html';
Java
mit
ddbb56dafc71365813cf5fe24235575d8b2ecf6a
0
ayushkr19/MedAlt
package com.bits.medalt.app; import android.app.Fragment; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.bits.medalt.app.com.bits.medalt.db.Medicine; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; /** * Created by ayush on 15/3/14. * @author Ayush Kumar */ public class QueryFragment extends Fragment implements View.OnClickListener{ String TAG = "MedAlt"; EditText editText; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); editText = (EditText) rootView.findViewById(R.id.et_query); Button button = (Button) rootView.findViewById(R.id.bt_query); button.setOnClickListener(this); return rootView; } @Override public void onClick(View v) { if (editText.getText().toString() != null) { new QueryDownloader().execute(editText.getText().toString()); } } public class QueryDownloader extends AsyncTask<String, String, String> { //private String BASE_URL = "http://ayushkr19.kd.io/query.php"; //private String BASE_URL = "http://192.168.1.2/query.php"; //private String BASE_URL = "http://ayushkumar.site90.net/query_webhost.php"; private String BASE_URL = "http://ayushkumar.site90.net/select_test.php"; int QueryLength = 0; int status = 0; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { String data = ""; try { data = downloadQueryData(params[0]); }catch (IOException e){ Log.d(TAG,"QueryDownloader doInBackground IOException"); } return data; } @Override protected void onPostExecute(String s) { if (getActivity()!=null) { Toast.makeText(getActivity(),s,Toast.LENGTH_LONG).show(); } new MedicineParser().execute(s); super.onPostExecute(s); } private String downloadQueryData(String query) throws IOException { String data = ""; InputStream iStream = null; HttpURLConnection urlConnection = null; try{ URL url = new URL(BASE_URL); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setReadTimeout(4000); urlConnection.setDoOutput(true); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("query",query)); String formatted_query = getQuery(params); urlConnection.setFixedLengthStreamingMode(QueryLength); urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); OutputStream outputStream = urlConnection.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8")); bufferedWriter.write(formatted_query); bufferedWriter.flush(); bufferedWriter.close(); urlConnection.connect(); status = urlConnection.getResponseCode(); Log.d(TAG,"downloadQueryData Status " + status); iStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); StringBuilder sb = new StringBuilder(); String line = ""; while( ( line = br.readLine()) != null){ sb.append(line); } data = sb.toString(); Log.d(TAG, "downloadQueryData" + data); br.close(); }catch(Exception e){ Log.d(TAG, "Exception (downloadQueryData): " + e.toString()); }finally{ if (iStream!=null && urlConnection!=null) { iStream.close(); urlConnection.disconnect(); } } return data; } private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (NameValuePair pair : params) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(pair.getName(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(pair.getValue(), "UTF-8")); } QueryLength = result.toString().getBytes().length; return result.toString(); } } public class MedicineParser extends AsyncTask<String,String,ArrayList<Medicine>>{ @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected ArrayList<Medicine> doInBackground(String... params) { JSONArray jsonArray = StringToJSONArray(params[0]); ArrayList<Medicine> medicineArrayList = JSONArrayToMedicine(jsonArray); return medicineArrayList; } @Override protected void onPostExecute(ArrayList<Medicine> medicines) { super.onPostExecute(medicines); } private JSONArray StringToJSONArray(String data){ JSONArray jsonArray = null; try{ jsonArray = new JSONArray(data); }catch (JSONException e){ Log.d(TAG,"JSONException (StringToJsonArray) :"); } return jsonArray; } private ArrayList<Medicine> JSONArrayToMedicine(JSONArray jsonArray){ ArrayList<Medicine> medicineArrayList = new ArrayList<Medicine>(); for(int i=0; i<jsonArray.length(); i++){ JSONObject jsonObject = null; try { jsonObject = jsonArray.getJSONObject(i); String trade_name = jsonObject.getString("trade_name"); String api = jsonObject.getString("api"); String dosage = jsonObject.getString("dosage"); String category = jsonObject.getString("category"); Medicine medicine = new Medicine(trade_name,api,dosage,category); medicineArrayList.add(medicine); } catch (JSONException e) { Log.d(TAG,"JOSNArrayToMedicine exception"); } } return medicineArrayList; } } }
app/src/main/java/com/bits/medalt/app/QueryFragment.java
package com.bits.medalt.app; import android.app.Fragment; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; /** * Created by ayush on 15/3/14. * @author Ayush Kumar */ public class QueryFragment extends Fragment implements View.OnClickListener{ String TAG = "MedAlt"; EditText editText; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); editText = (EditText) rootView.findViewById(R.id.et_query); Button button = (Button) rootView.findViewById(R.id.bt_query); button.setOnClickListener(this); return rootView; } @Override public void onClick(View v) { if (editText.getText().toString() != null) { new QueryDownloader().execute(editText.getText().toString()); } } public class QueryDownloader extends AsyncTask<String, String, String> { //private String BASE_URL = "http://ayushkr19.kd.io/query.php"; //private String BASE_URL = "http://192.168.1.2/query.php"; //private String BASE_URL = "http://ayushkumar.site90.net/query_webhost.php"; private String BASE_URL = "http://ayushkumar.site90.net/select_test.php"; int QueryLength = 0; int status = 0; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { String data = ""; try { data = downloadQueryData(params[0]); }catch (IOException e){ Log.d(TAG,"QueryDownloader doInBackground IOException"); } return data; } @Override protected void onPostExecute(String s) { if (getActivity()!=null) { Toast.makeText(getActivity(),s,Toast.LENGTH_LONG).show(); } new MedicineParser().execute(s); super.onPostExecute(s); } private String downloadQueryData(String query) throws IOException { String data = ""; InputStream iStream = null; HttpURLConnection urlConnection = null; try{ URL url = new URL(BASE_URL); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setReadTimeout(4000); urlConnection.setDoOutput(true); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("query",query)); String formatted_query = getQuery(params); urlConnection.setFixedLengthStreamingMode(QueryLength); urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); OutputStream outputStream = urlConnection.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8")); bufferedWriter.write(formatted_query); bufferedWriter.flush(); bufferedWriter.close(); urlConnection.connect(); status = urlConnection.getResponseCode(); Log.d(TAG,"downloadQueryData Status " + status); iStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); StringBuilder sb = new StringBuilder(); String line = ""; while( ( line = br.readLine()) != null){ sb.append(line); } data = sb.toString(); Log.d(TAG, "downloadQueryData" + data); br.close(); }catch(Exception e){ Log.d(TAG, "Exception (downloadQueryData): " + e.toString()); }finally{ if (iStream!=null && urlConnection!=null) { iStream.close(); urlConnection.disconnect(); } } return data; } private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (NameValuePair pair : params) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(pair.getName(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(pair.getValue(), "UTF-8")); } QueryLength = result.toString().getBytes().length; return result.toString(); } } public class MedicineParser extends AsyncTask<String,String,String>{ @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { JSONArray jsonArray = StringToJSONArray(params[0]); return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); } private JSONArray StringToJSONArray(String data){ JSONArray jsonArray = null; try{ jsonArray = new JSONArray(data); }catch (JSONException e){ Log.d(TAG,"JSONException (StringToJsonArray) :"); } return jsonArray; } } }
Add JSONArrayToMedicine in QueryFragment.java
app/src/main/java/com/bits/medalt/app/QueryFragment.java
Add JSONArrayToMedicine in QueryFragment.java
<ide><path>pp/src/main/java/com/bits/medalt/app/QueryFragment.java <ide> import android.widget.TextView; <ide> import android.widget.Toast; <ide> <add>import com.bits.medalt.app.com.bits.medalt.db.Medicine; <add> <ide> import org.apache.http.NameValuePair; <ide> import org.apache.http.message.BasicNameValuePair; <ide> import org.json.JSONArray; <ide> import org.json.JSONException; <add>import org.json.JSONObject; <ide> <ide> import java.io.BufferedReader; <ide> import java.io.BufferedWriter; <ide> <ide> } <ide> <del> public class MedicineParser extends AsyncTask<String,String,String>{ <add> public class MedicineParser extends AsyncTask<String,String,ArrayList<Medicine>>{ <ide> <ide> @Override <ide> protected void onPreExecute() { <ide> <ide> <ide> @Override <del> protected String doInBackground(String... params) { <add> protected ArrayList<Medicine> doInBackground(String... params) { <ide> JSONArray jsonArray = StringToJSONArray(params[0]); <del> <del> return null; <del> } <del> <del> @Override <del> protected void onPostExecute(String s) { <del> super.onPostExecute(s); <add> ArrayList<Medicine> medicineArrayList = JSONArrayToMedicine(jsonArray); <add> return medicineArrayList; <add> } <add> <add> @Override <add> protected void onPostExecute(ArrayList<Medicine> medicines) { <add> <add> <add> super.onPostExecute(medicines); <ide> } <ide> <ide> private JSONArray StringToJSONArray(String data){ <ide> } <ide> return jsonArray; <ide> } <add> <add> private ArrayList<Medicine> JSONArrayToMedicine(JSONArray jsonArray){ <add> ArrayList<Medicine> medicineArrayList = new ArrayList<Medicine>(); <add> for(int i=0; i<jsonArray.length(); i++){ <add> JSONObject jsonObject = null; <add> try { <add> jsonObject = jsonArray.getJSONObject(i); <add> String trade_name = jsonObject.getString("trade_name"); <add> String api = jsonObject.getString("api"); <add> String dosage = jsonObject.getString("dosage"); <add> String category = jsonObject.getString("category"); <add> <add> Medicine medicine = new Medicine(trade_name,api,dosage,category); <add> medicineArrayList.add(medicine); <add> } catch (JSONException e) { <add> Log.d(TAG,"JOSNArrayToMedicine exception"); <add> } <add> } <add> <add> return medicineArrayList; <add> } <ide> } <ide> }
Java
apache-2.0
37702b75f166c43b34d771a27ae5ffe5ea6c5659
0
nicolargo/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,signed/intellij-community,amith01994/intellij-community,petteyg/intellij-community,holmes/intellij-community,diorcety/intellij-community,izonder/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,dslomov/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,blademainer/intellij-community,allotria/intellij-community,fnouama/intellij-community,samthor/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,vladmm/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,caot/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,hurricup/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,blademainer/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,diorcety/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,signed/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,blademainer/intellij-community,clumsy/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,ernestp/consulo,pwoodworth/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,holmes/intellij-community,vvv1559/intellij-community,da1z/intellij-community,caot/intellij-community,FHannes/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,clumsy/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,caot/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,nicolargo/intellij-community,slisson/intellij-community,vladmm/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,allotria/intellij-community,asedunov/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,da1z/intellij-community,fnouama/intellij-community,asedunov/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,supersven/intellij-community,robovm/robovm-studio,blademainer/intellij-community,allotria/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,semonte/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,kool79/intellij-community,signed/intellij-community,fitermay/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,fitermay/intellij-community,amith01994/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,vladmm/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,petteyg/intellij-community,holmes/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,signed/intellij-community,ryano144/intellij-community,allotria/intellij-community,petteyg/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,slisson/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,consulo/consulo,amith01994/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,allotria/intellij-community,signed/intellij-community,asedunov/intellij-community,amith01994/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,da1z/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,diorcety/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,semonte/intellij-community,gnuhub/intellij-community,supersven/intellij-community,izonder/intellij-community,ahb0327/intellij-community,slisson/intellij-community,izonder/intellij-community,vladmm/intellij-community,fitermay/intellij-community,dslomov/intellij-community,amith01994/intellij-community,slisson/intellij-community,jagguli/intellij-community,robovm/robovm-studio,asedunov/intellij-community,holmes/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,retomerz/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,robovm/robovm-studio,asedunov/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,kool79/intellij-community,petteyg/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,slisson/intellij-community,xfournet/intellij-community,petteyg/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,ibinti/intellij-community,retomerz/intellij-community,fitermay/intellij-community,vladmm/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,signed/intellij-community,fitermay/intellij-community,robovm/robovm-studio,adedayo/intellij-community,allotria/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,caot/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,holmes/intellij-community,ryano144/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,caot/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,fitermay/intellij-community,signed/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,supersven/intellij-community,supersven/intellij-community,supersven/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,diorcety/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,supersven/intellij-community,izonder/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,hurricup/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,izonder/intellij-community,Distrotech/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,semonte/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,gnuhub/intellij-community,consulo/consulo,SerCeMan/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,da1z/intellij-community,slisson/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,ernestp/consulo,adedayo/intellij-community,lucafavatella/intellij-community,ernestp/consulo,akosyakov/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,adedayo/intellij-community,kool79/intellij-community,kdwink/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,samthor/intellij-community,consulo/consulo,MER-GROUP/intellij-community,Lekanich/intellij-community,kool79/intellij-community,petteyg/intellij-community,semonte/intellij-community,asedunov/intellij-community,adedayo/intellij-community,blademainer/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,hurricup/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,ryano144/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,amith01994/intellij-community,da1z/intellij-community,youdonghai/intellij-community,semonte/intellij-community,blademainer/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,caot/intellij-community,salguarnieri/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,caot/intellij-community,fitermay/intellij-community,da1z/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,jagguli/intellij-community,allotria/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,retomerz/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,signed/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,holmes/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,allotria/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,ibinti/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,hurricup/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,slisson/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,consulo/consulo,asedunov/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,signed/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,da1z/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,consulo/consulo,vvv1559/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,supersven/intellij-community,kdwink/intellij-community,samthor/intellij-community,signed/intellij-community,dslomov/intellij-community,hurricup/intellij-community,fnouama/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,FHannes/intellij-community,vladmm/intellij-community,holmes/intellij-community,hurricup/intellij-community,adedayo/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,ibinti/intellij-community,dslomov/intellij-community,apixandru/intellij-community,slisson/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,kool79/intellij-community,supersven/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,izonder/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,consulo/consulo,nicolargo/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,izonder/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,xfournet/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,clumsy/intellij-community,da1z/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,clumsy/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,fitermay/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,holmes/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Created by IntelliJ IDEA. * User: amrk * Date: Jul 2, 2005 * Time: 12:22:07 AM */ package com.theoryinpractice.testng.configuration; import com.intellij.ExtensionPoints; import com.intellij.debugger.engine.DebuggerUtils; import com.intellij.execution.*; import com.intellij.execution.configurations.*; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.ProgramRunner; import com.intellij.execution.testframework.*; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.execution.util.JavaParametersUtil; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.module.LanguageLevelUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator; import com.intellij.openapi.progress.impl.ProgressManagerImpl; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.ex.JavaSdkUtil; import com.intellij.openapi.roots.LanguageLevelProjectExtension; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Getter; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiFile; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.PathUtil; import com.intellij.util.net.NetUtils; import com.theoryinpractice.testng.model.*; import com.theoryinpractice.testng.ui.TestNGConsoleView; import com.theoryinpractice.testng.ui.TestNGResults; import com.theoryinpractice.testng.ui.actions.RerunFailedTestsAction; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.testng.CommandLineArgs; import org.testng.IDEATestNGListener; import org.testng.RemoteTestNGStarter; import org.testng.annotations.AfterClass; import org.testng.remote.RemoteArgs; import org.testng.remote.RemoteTestNG; import org.testng.remote.strprotocol.MessageHelper; import org.testng.remote.strprotocol.SerializedMessageSender; import javax.swing.*; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; public class TestNGRunnableState extends JavaCommandLineState { private static final Logger LOG = Logger.getInstance("TestNG Runner"); private final ConfigurationPerRunnerSettings myConfigurationPerRunnerSettings; private final TestNGConfiguration config; private final RunnerSettings runnerSettings; protected final IDEARemoteTestRunnerClient client; private int port; private String debugPort; private File myTempFile; private BackgroundableProcessIndicator mySearchForTestIndicator; private ServerSocket myServerSocket; public TestNGRunnableState(ExecutionEnvironment environment, TestNGConfiguration config) { super(environment); this.runnerSettings = environment.getRunnerSettings(); myConfigurationPerRunnerSettings = environment.getConfigurationSettings(); this.config = config; //TODO need to narrow this down a bit //setModulesToCompile(ModuleManager.getInstance(config.getProject()).getModules()); client = new IDEARemoteTestRunnerClient(); // Want debugging? if (runnerSettings.getData() instanceof DebuggingRunnerData) { DebuggingRunnerData debuggingRunnerData = ((DebuggingRunnerData)runnerSettings.getData()); debugPort = debuggingRunnerData.getDebugPort(); if (debugPort.length() == 0) { try { debugPort = DebuggerUtils.getInstance().findAvailableDebugAddress(true); } catch (ExecutionException e) { LOG.error(e); } debuggingRunnerData.setDebugPort(debugPort); } debuggingRunnerData.setLocal(true); } } @Override public ExecutionResult execute(@NotNull final Executor executor, @NotNull final ProgramRunner runner) throws ExecutionException { OSProcessHandler processHandler = startProcess(); final TreeRootNode unboundOutputRoot = new TreeRootNode(); final TestNGConsoleView console = new TestNGConsoleView(config, runnerSettings, myConfigurationPerRunnerSettings, unboundOutputRoot, executor); console.initUI(); unboundOutputRoot.setPrinter(console.getPrinter()); Disposer.register(console, unboundOutputRoot); for (RunConfigurationExtension ext : Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) { ext.handleStartProcess(config, processHandler); } final SearchingForTestsTask task = createSearchingForTestsTask(myServerSocket, config, myTempFile); processHandler.addProcessListener(new ProcessAdapter() { @Override public void processTerminated(final ProcessEvent event) { unboundOutputRoot.flush(); if (mySearchForTestIndicator != null && !mySearchForTestIndicator.isCanceled()) { mySearchForTestIndicator.cancel(); task.connect(); } SwingUtilities.invokeLater(new Runnable() { public void run() { final Project project = config.getProject(); if (project.isDisposed()) return; final TestConsoleProperties consoleProperties = console.getProperties(); if (consoleProperties == null) return; final String testRunDebugId = consoleProperties.isDebug() ? ToolWindowId.DEBUG : ToolWindowId.RUN; final TestNGResults resultsView = console.getResultsView(); final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project); if (!Comparing.strEqual(toolWindowManager.getActiveToolWindowId(), testRunDebugId)) { toolWindowManager.notifyByBalloon(testRunDebugId, resultsView == null || resultsView.getStatus() == MessageHelper.SKIPPED_TEST ? MessageType.WARNING : (resultsView.getStatus() == MessageHelper.FAILED_TEST ? MessageType.ERROR : MessageType.INFO), resultsView == null ? "Tests were not started" : resultsView.getStatusLine(), null, null); } } }); } @Override public void startNotified(final ProcessEvent event) { TestNGRemoteListener listener = new TestNGRemoteListener(console, unboundOutputRoot); client.prepareListening(listener, port); mySearchForTestIndicator = new BackgroundableProcessIndicator(task) { @Override public void cancel() { try {//ensure that serverSocket.accept was interrupted if (!myServerSocket.isClosed()) { new Socket(InetAddress.getLocalHost(), myServerSocket.getLocalPort()); } } catch (Throwable e) { LOG.info(e); } super.cancel(); } }; ProgressManagerImpl.runProcessWithProgressAsynchronously(task, mySearchForTestIndicator); } @Override public void processWillTerminate(ProcessEvent event, boolean willBeDestroyed) { final TestNGResults resultsView = console.getResultsView(); if (resultsView != null) { resultsView.finish(); } } private int myInsertIndex = 0; @Override public void onTextAvailable(final ProcessEvent event, final Key outputType) { final TestProxy currentTest = console.getCurrentTest(); final String text = event.getText(); final ConsoleViewContentType consoleViewType = ConsoleViewContentType.getConsoleViewType(outputType); final Printable printable = new Printable() { public void printOn(final Printer printer) { printer.print(text, consoleViewType); } }; if (currentTest != null) { currentTest.addLast(printable); } else { unboundOutputRoot.insert(printable, myInsertIndex); } myInsertIndex++; } }); console.attachToProcess(processHandler); RerunFailedTestsAction rerunFailedTestsAction = new RerunFailedTestsAction(console.getComponent()); rerunFailedTestsAction.init(console.getProperties(), runnerSettings, myConfigurationPerRunnerSettings); rerunFailedTestsAction.setModelProvider(new Getter<TestFrameworkRunningModel>() { public TestFrameworkRunningModel get() { return console.getResultsView(); } }); final DefaultExecutionResult result = new DefaultExecutionResult(console, processHandler); result.setRestartActions(rerunFailedTestsAction); return result; } @Override protected JavaParameters createJavaParameters() throws ExecutionException { final Project project = config.getProject(); final JavaParameters javaParameters = new JavaParameters(); javaParameters.setupEnvs(config.getPersistantData().getEnvs(), config.getPersistantData().PASS_PARENT_ENVS); javaParameters.getVMParametersList().add("-ea"); javaParameters.setMainClass("org.testng.RemoteTestNGStarter"); javaParameters.setWorkingDirectory(config.getWorkingDirectory()); javaParameters.getClassPath().add(PathUtil.getJarPathForClass(RemoteTestNGStarter.class)); //the next few lines are awkward for a reason, using compareTo for some reason causes a JVM class verification error! Module module = config.getConfigurationModule().getModule(); LanguageLevel effectiveLanguageLevel = module == null ? LanguageLevelProjectExtension.getInstance(project).getLanguageLevel() : LanguageLevelUtil.getEffectiveLanguageLevel(module); final boolean is15 = effectiveLanguageLevel != LanguageLevel.JDK_1_4 && effectiveLanguageLevel != LanguageLevel.JDK_1_3; LOG.info("Language level is " + effectiveLanguageLevel.toString()); LOG.info("is15 is " + is15); // Configure rest of jars JavaParametersUtil.configureConfiguration(javaParameters, config); Sdk jdk = module == null ? ProjectRootManager.getInstance(project).getProjectSdk() : ModuleRootManager.getInstance(module).getSdk(); javaParameters.setJdk(jdk); final Object[] patchers = Extensions.getExtensions(ExtensionPoints.JUNIT_PATCHER); for (Object patcher : patchers) { ((JUnitPatcher)patcher).patchJavaParameters(module, javaParameters); } JavaSdkUtil.addRtJar(javaParameters.getClassPath()); // Append coverage parameters if appropriate for (RunConfigurationExtension ext : Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) { ext.updateJavaParameters(config, javaParameters, getRunnerSettings()); } LOG.info("Test scope is: " + config.getPersistantData().getScope()); if (config.getPersistantData().getScope() == TestSearchScope.WHOLE_PROJECT) { LOG.info("Configuring for whole project"); JavaParametersUtil.configureProject(config.getProject(), javaParameters, JavaParameters.JDK_AND_CLASSES_AND_TESTS, config.ALTERNATIVE_JRE_PATH_ENABLED ? config.ALTERNATIVE_JRE_PATH : null); } else { LOG.info("Configuring for module:" + config.getConfigurationModule().getModuleName()); JavaParametersUtil.configureModule(config.getConfigurationModule(), javaParameters, JavaParameters.JDK_AND_CLASSES_AND_TESTS, config.ALTERNATIVE_JRE_PATH_ENABLED ? config.ALTERNATIVE_JRE_PATH : null); } javaParameters.getClassPath().add(is15 ? PathUtil.getJarPathForClass(AfterClass.class) : //testng-jdk15.jar new File(PathManager.getPreinstalledPluginsPath(), "testng/lib-jdk14/testng-jdk14.jar") .getPath());//todo !do not hard code lib name! try { port = NetUtils.findAvailableSocketPort(); } catch (IOException e) { throw new ExecutionException("Unable to bind to port " + port, e); } final TestData data = config.getPersistantData(); javaParameters.getProgramParametersList().add(supportSerializationProtocol(config) ? RemoteArgs.PORT : CommandLineArgs.PORT, String.valueOf(port)); if (data.getOutputDirectory() != null && !"".equals(data.getOutputDirectory())) { javaParameters.getProgramParametersList().add(CommandLineArgs.OUTPUT_DIRECTORY, data.getOutputDirectory()); } javaParameters.getProgramParametersList().add(CommandLineArgs.USE_DEFAULT_LISTENERS, String.valueOf(data.USE_DEFAULT_REPORTERS)); @NonNls final StringBuilder buf = new StringBuilder(); if (data.TEST_LISTENERS != null && !data.TEST_LISTENERS.isEmpty()) { buf.append(StringUtil.join(data.TEST_LISTENERS, ";")); } for (Object o : Extensions.getExtensions(IDEATestNGListener.EP_NAME)) { boolean enabled = true; for (RunConfigurationExtension extension : Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) { if (extension.isListenerDisabled(config, o)) { enabled = false; break; } } if (enabled) { if (buf.length() > 0) buf.append(";"); buf.append(o.getClass().getName()); javaParameters.getClassPath().add(PathUtil.getJarPathForClass(o.getClass())); } } if (buf.length() > 0) javaParameters.getProgramParametersList().add(CommandLineArgs.LISTENER, buf.toString()); /* // Always include the source paths - just makes things easier :) VirtualFile[] sources; if ((data.getScope() == TestSearchScope.WHOLE_PROJECT && TestType.PACKAGE.getType().equals(data.TEST_OBJECT)) || module == null) { sources = ProjectRootManager.getInstance(project).getContentSourceRoots(); } else { sources = ModuleRootManager.getInstance(module).getSourceRoots(); } if (sources.length > 0) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < sources.length; i++) { VirtualFile source = sources[i]; sb.append(source.getPath()); if (i < sources.length - 1) { sb.append(';'); } } javaParameters.getProgramParametersList().add(TestNGCommandLineArgs.SRC_COMMAND_OPT, sb.toString()); }*/ try { myServerSocket = new ServerSocket(0, 0, InetAddress.getByName(null)); javaParameters.getProgramParametersList().add("-socket" + myServerSocket.getLocalPort()); myTempFile = FileUtil.createTempFile("idea_testng", ".tmp"); myTempFile.deleteOnExit(); javaParameters.getProgramParametersList().add("-temp", myTempFile.getAbsolutePath()); } catch (IOException e) { LOG.error(e); } // Configure for debugging if (runnerSettings.getData() instanceof DebuggingRunnerData) { ParametersList params = javaParameters.getVMParametersList(); String hostname = "localhost"; try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { } params.add("-Xdebug"); params.add("-Xrunjdwp:transport=dt_socket,address=" + hostname + ':' + debugPort + ",suspend=y,server=n"); // params.add(debugPort); } return javaParameters; } protected SearchingForTestsTask createSearchingForTestsTask(ServerSocket serverSocket, final TestNGConfiguration config, final File tempFile) { return new SearchingForTestsTask(serverSocket, config, tempFile, client); } public static boolean supportSerializationProtocol(TestNGConfiguration config) { final Project project = config.getProject(); final GlobalSearchScope scopeToDetermineTestngIn; if (config.getPersistantData().getScope() == TestSearchScope.WHOLE_PROJECT) { scopeToDetermineTestngIn = GlobalSearchScope.allScope(project); } else { scopeToDetermineTestngIn = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(config.getConfigurationModule().getModule()); } final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final PsiClass aClass = facade.findClass(SerializedMessageSender.class.getName(), scopeToDetermineTestngIn); if (aClass == null) return false; final PsiClass[] starters = facade.findClasses(RemoteTestNG.class.getName(), scopeToDetermineTestngIn); for (PsiClass starter : starters) { if (starter.findFieldByName("m_serPort", false) == null) { LOG.info("Multiple TestNG versions found"); return false; } } return true; } }
plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGRunnableState.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Created by IntelliJ IDEA. * User: amrk * Date: Jul 2, 2005 * Time: 12:22:07 AM */ package com.theoryinpractice.testng.configuration; import com.intellij.ExtensionPoints; import com.intellij.debugger.engine.DebuggerUtils; import com.intellij.execution.*; import com.intellij.execution.configurations.*; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.ProgramRunner; import com.intellij.execution.testframework.*; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.execution.util.JavaParametersUtil; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.module.LanguageLevelUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator; import com.intellij.openapi.progress.impl.ProgressManagerImpl; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.ex.JavaSdkUtil; import com.intellij.openapi.roots.LanguageLevelProjectExtension; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Getter; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.PathUtil; import com.intellij.util.net.NetUtils; import com.theoryinpractice.testng.model.*; import com.theoryinpractice.testng.ui.TestNGConsoleView; import com.theoryinpractice.testng.ui.TestNGResults; import com.theoryinpractice.testng.ui.actions.RerunFailedTestsAction; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.testng.CommandLineArgs; import org.testng.IDEATestNGListener; import org.testng.RemoteTestNGStarter; import org.testng.annotations.AfterClass; import org.testng.remote.RemoteArgs; import org.testng.remote.strprotocol.MessageHelper; import org.testng.remote.strprotocol.SerializedMessageSender; import javax.swing.*; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; public class TestNGRunnableState extends JavaCommandLineState { private static final Logger LOG = Logger.getInstance("TestNG Runner"); private final ConfigurationPerRunnerSettings myConfigurationPerRunnerSettings; private final TestNGConfiguration config; private final RunnerSettings runnerSettings; protected final IDEARemoteTestRunnerClient client; private int port; private String debugPort; private File myTempFile; private BackgroundableProcessIndicator mySearchForTestIndicator; private ServerSocket myServerSocket; public TestNGRunnableState(ExecutionEnvironment environment, TestNGConfiguration config) { super(environment); this.runnerSettings = environment.getRunnerSettings(); myConfigurationPerRunnerSettings = environment.getConfigurationSettings(); this.config = config; //TODO need to narrow this down a bit //setModulesToCompile(ModuleManager.getInstance(config.getProject()).getModules()); client = new IDEARemoteTestRunnerClient(); // Want debugging? if (runnerSettings.getData() instanceof DebuggingRunnerData) { DebuggingRunnerData debuggingRunnerData = ((DebuggingRunnerData)runnerSettings.getData()); debugPort = debuggingRunnerData.getDebugPort(); if (debugPort.length() == 0) { try { debugPort = DebuggerUtils.getInstance().findAvailableDebugAddress(true); } catch (ExecutionException e) { LOG.error(e); } debuggingRunnerData.setDebugPort(debugPort); } debuggingRunnerData.setLocal(true); } } @Override public ExecutionResult execute(@NotNull final Executor executor, @NotNull final ProgramRunner runner) throws ExecutionException { OSProcessHandler processHandler = startProcess(); final TreeRootNode unboundOutputRoot = new TreeRootNode(); final TestNGConsoleView console = new TestNGConsoleView(config, runnerSettings, myConfigurationPerRunnerSettings, unboundOutputRoot, executor); console.initUI(); unboundOutputRoot.setPrinter(console.getPrinter()); Disposer.register(console, unboundOutputRoot); for (RunConfigurationExtension ext : Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) { ext.handleStartProcess(config, processHandler); } final SearchingForTestsTask task = createSearchingForTestsTask(myServerSocket, config, myTempFile); processHandler.addProcessListener(new ProcessAdapter() { @Override public void processTerminated(final ProcessEvent event) { unboundOutputRoot.flush(); if (mySearchForTestIndicator != null && !mySearchForTestIndicator.isCanceled()) { mySearchForTestIndicator.cancel(); task.connect(); } SwingUtilities.invokeLater(new Runnable() { public void run() { final Project project = config.getProject(); if (project.isDisposed()) return; final TestConsoleProperties consoleProperties = console.getProperties(); if (consoleProperties == null) return; final String testRunDebugId = consoleProperties.isDebug() ? ToolWindowId.DEBUG : ToolWindowId.RUN; final TestNGResults resultsView = console.getResultsView(); final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project); if (!Comparing.strEqual(toolWindowManager.getActiveToolWindowId(), testRunDebugId)) { toolWindowManager.notifyByBalloon(testRunDebugId, resultsView == null || resultsView.getStatus() == MessageHelper.SKIPPED_TEST ? MessageType.WARNING : (resultsView.getStatus() == MessageHelper.FAILED_TEST ? MessageType.ERROR : MessageType.INFO), resultsView == null ? "Tests were not started" : resultsView.getStatusLine(), null, null); } } }); } @Override public void startNotified(final ProcessEvent event) { TestNGRemoteListener listener = new TestNGRemoteListener(console, unboundOutputRoot); client.prepareListening(listener, port); mySearchForTestIndicator = new BackgroundableProcessIndicator(task) { @Override public void cancel() { try {//ensure that serverSocket.accept was interrupted if (!myServerSocket.isClosed()) { new Socket(InetAddress.getLocalHost(), myServerSocket.getLocalPort()); } } catch (Throwable e) { LOG.info(e); } super.cancel(); } }; ProgressManagerImpl.runProcessWithProgressAsynchronously(task, mySearchForTestIndicator); } @Override public void processWillTerminate(ProcessEvent event, boolean willBeDestroyed) { final TestNGResults resultsView = console.getResultsView(); if (resultsView != null) { resultsView.finish(); } } private int myInsertIndex = 0; @Override public void onTextAvailable(final ProcessEvent event, final Key outputType) { final TestProxy currentTest = console.getCurrentTest(); final String text = event.getText(); final ConsoleViewContentType consoleViewType = ConsoleViewContentType.getConsoleViewType(outputType); final Printable printable = new Printable() { public void printOn(final Printer printer) { printer.print(text, consoleViewType); } }; if (currentTest != null) { currentTest.addLast(printable); } else { unboundOutputRoot.insert(printable, myInsertIndex); } myInsertIndex++; } }); console.attachToProcess(processHandler); RerunFailedTestsAction rerunFailedTestsAction = new RerunFailedTestsAction(console.getComponent()); rerunFailedTestsAction.init(console.getProperties(), runnerSettings, myConfigurationPerRunnerSettings); rerunFailedTestsAction.setModelProvider(new Getter<TestFrameworkRunningModel>() { public TestFrameworkRunningModel get() { return console.getResultsView(); } }); final DefaultExecutionResult result = new DefaultExecutionResult(console, processHandler); result.setRestartActions(rerunFailedTestsAction); return result; } @Override protected JavaParameters createJavaParameters() throws ExecutionException { final Project project = config.getProject(); final JavaParameters javaParameters = new JavaParameters(); javaParameters.setupEnvs(config.getPersistantData().getEnvs(), config.getPersistantData().PASS_PARENT_ENVS); javaParameters.getVMParametersList().add("-ea"); javaParameters.setMainClass("org.testng.RemoteTestNGStarter"); javaParameters.setWorkingDirectory(config.getWorkingDirectory()); javaParameters.getClassPath().add(PathUtil.getJarPathForClass(RemoteTestNGStarter.class)); //the next few lines are awkward for a reason, using compareTo for some reason causes a JVM class verification error! Module module = config.getConfigurationModule().getModule(); LanguageLevel effectiveLanguageLevel = module == null ? LanguageLevelProjectExtension.getInstance(project).getLanguageLevel() : LanguageLevelUtil.getEffectiveLanguageLevel(module); final boolean is15 = effectiveLanguageLevel != LanguageLevel.JDK_1_4 && effectiveLanguageLevel != LanguageLevel.JDK_1_3; LOG.info("Language level is " + effectiveLanguageLevel.toString()); LOG.info("is15 is " + is15); // Configure rest of jars JavaParametersUtil.configureConfiguration(javaParameters, config); Sdk jdk = module == null ? ProjectRootManager.getInstance(project).getProjectSdk() : ModuleRootManager.getInstance(module).getSdk(); javaParameters.setJdk(jdk); final Object[] patchers = Extensions.getExtensions(ExtensionPoints.JUNIT_PATCHER); for (Object patcher : patchers) { ((JUnitPatcher)patcher).patchJavaParameters(module, javaParameters); } JavaSdkUtil.addRtJar(javaParameters.getClassPath()); // Append coverage parameters if appropriate for (RunConfigurationExtension ext : Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) { ext.updateJavaParameters(config, javaParameters, getRunnerSettings()); } LOG.info("Test scope is: " + config.getPersistantData().getScope()); if (config.getPersistantData().getScope() == TestSearchScope.WHOLE_PROJECT) { LOG.info("Configuring for whole project"); JavaParametersUtil.configureProject(config.getProject(), javaParameters, JavaParameters.JDK_AND_CLASSES_AND_TESTS, config.ALTERNATIVE_JRE_PATH_ENABLED ? config.ALTERNATIVE_JRE_PATH : null); } else { LOG.info("Configuring for module:" + config.getConfigurationModule().getModuleName()); JavaParametersUtil.configureModule(config.getConfigurationModule(), javaParameters, JavaParameters.JDK_AND_CLASSES_AND_TESTS, config.ALTERNATIVE_JRE_PATH_ENABLED ? config.ALTERNATIVE_JRE_PATH : null); } javaParameters.getClassPath().add(is15 ? PathUtil.getJarPathForClass(AfterClass.class) : //testng-jdk15.jar new File(PathManager.getPreinstalledPluginsPath(), "testng/lib-jdk14/testng-jdk14.jar") .getPath());//todo !do not hard code lib name! try { port = NetUtils.findAvailableSocketPort(); } catch (IOException e) { throw new ExecutionException("Unable to bind to port " + port, e); } final TestData data = config.getPersistantData(); javaParameters.getProgramParametersList().add(supportSerializationProtocol(config) ? RemoteArgs.PORT : CommandLineArgs.PORT, String.valueOf(port)); if (data.getOutputDirectory() != null && !"".equals(data.getOutputDirectory())) { javaParameters.getProgramParametersList().add(CommandLineArgs.OUTPUT_DIRECTORY, data.getOutputDirectory()); } javaParameters.getProgramParametersList().add(CommandLineArgs.USE_DEFAULT_LISTENERS, String.valueOf(data.USE_DEFAULT_REPORTERS)); @NonNls final StringBuilder buf = new StringBuilder(); if (data.TEST_LISTENERS != null && !data.TEST_LISTENERS.isEmpty()) { buf.append(StringUtil.join(data.TEST_LISTENERS, ";")); } for (Object o : Extensions.getExtensions(IDEATestNGListener.EP_NAME)) { boolean enabled = true; for (RunConfigurationExtension extension : Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) { if (extension.isListenerDisabled(config, o)) { enabled = false; break; } } if (enabled) { if (buf.length() > 0) buf.append(";"); buf.append(o.getClass().getName()); javaParameters.getClassPath().add(PathUtil.getJarPathForClass(o.getClass())); } } if (buf.length() > 0) javaParameters.getProgramParametersList().add(CommandLineArgs.LISTENER, buf.toString()); /* // Always include the source paths - just makes things easier :) VirtualFile[] sources; if ((data.getScope() == TestSearchScope.WHOLE_PROJECT && TestType.PACKAGE.getType().equals(data.TEST_OBJECT)) || module == null) { sources = ProjectRootManager.getInstance(project).getContentSourceRoots(); } else { sources = ModuleRootManager.getInstance(module).getSourceRoots(); } if (sources.length > 0) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < sources.length; i++) { VirtualFile source = sources[i]; sb.append(source.getPath()); if (i < sources.length - 1) { sb.append(';'); } } javaParameters.getProgramParametersList().add(TestNGCommandLineArgs.SRC_COMMAND_OPT, sb.toString()); }*/ try { myServerSocket = new ServerSocket(0, 0, InetAddress.getByName(null)); javaParameters.getProgramParametersList().add("-socket" + myServerSocket.getLocalPort()); myTempFile = FileUtil.createTempFile("idea_testng", ".tmp"); myTempFile.deleteOnExit(); javaParameters.getProgramParametersList().add("-temp", myTempFile.getAbsolutePath()); } catch (IOException e) { LOG.error(e); } // Configure for debugging if (runnerSettings.getData() instanceof DebuggingRunnerData) { ParametersList params = javaParameters.getVMParametersList(); String hostname = "localhost"; try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { } params.add("-Xdebug"); params.add("-Xrunjdwp:transport=dt_socket,address=" + hostname + ':' + debugPort + ",suspend=y,server=n"); // params.add(debugPort); } return javaParameters; } protected SearchingForTestsTask createSearchingForTestsTask(ServerSocket serverSocket, final TestNGConfiguration config, final File tempFile) { return new SearchingForTestsTask(serverSocket, config, tempFile, client); } public static boolean supportSerializationProtocol(TestNGConfiguration config) { final Project project = config.getProject(); final GlobalSearchScope scopeToDetermineTestngIn; if (config.getPersistantData().getScope() == TestSearchScope.WHOLE_PROJECT) { scopeToDetermineTestngIn = GlobalSearchScope.allScope(project); } else { scopeToDetermineTestngIn = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(config.getConfigurationModule().getModule()); } final TestData data = config.getPersistantData(); return JavaPsiFacade.getInstance(project) .findClass(SerializedMessageSender.class.getName(), scopeToDetermineTestngIn) != null; } }
multiple testng versions preferences (IDEA-69809)
plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGRunnableState.java
multiple testng versions preferences (IDEA-69809)
<ide><path>lugins/testng/src/com/theoryinpractice/testng/configuration/TestNGRunnableState.java <ide> import com.intellij.openapi.util.Key; <ide> import com.intellij.openapi.util.io.FileUtil; <ide> import com.intellij.openapi.util.text.StringUtil; <add>import com.intellij.openapi.vfs.VirtualFile; <ide> import com.intellij.openapi.wm.ToolWindowId; <ide> import com.intellij.openapi.wm.ToolWindowManager; <ide> import com.intellij.pom.java.LanguageLevel; <ide> import com.intellij.psi.JavaPsiFacade; <add>import com.intellij.psi.PsiClass; <add>import com.intellij.psi.PsiFile; <ide> import com.intellij.psi.search.GlobalSearchScope; <ide> import com.intellij.util.PathUtil; <ide> import com.intellij.util.net.NetUtils; <ide> import com.theoryinpractice.testng.ui.actions.RerunFailedTestsAction; <ide> import org.jetbrains.annotations.NonNls; <ide> import org.jetbrains.annotations.NotNull; <add>import org.jetbrains.annotations.Nullable; <ide> import org.testng.CommandLineArgs; <ide> import org.testng.IDEATestNGListener; <ide> import org.testng.RemoteTestNGStarter; <ide> import org.testng.annotations.AfterClass; <ide> import org.testng.remote.RemoteArgs; <add>import org.testng.remote.RemoteTestNG; <ide> import org.testng.remote.strprotocol.MessageHelper; <ide> import org.testng.remote.strprotocol.SerializedMessageSender; <ide> <ide> scopeToDetermineTestngIn = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(config.getConfigurationModule().getModule()); <ide> } <ide> <del> final TestData data = config.getPersistantData(); <del> <del> return JavaPsiFacade.getInstance(project) <del> .findClass(SerializedMessageSender.class.getName(), scopeToDetermineTestngIn) != null; <add> final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); <add> final PsiClass aClass = facade.findClass(SerializedMessageSender.class.getName(), scopeToDetermineTestngIn); <add> if (aClass == null) return false; <add> <add> final PsiClass[] starters = facade.findClasses(RemoteTestNG.class.getName(), scopeToDetermineTestngIn); <add> for (PsiClass starter : starters) { <add> if (starter.findFieldByName("m_serPort", false) == null) { <add> LOG.info("Multiple TestNG versions found"); <add> return false; <add> } <add> } <add> return true; <ide> } <ide> }
Java
apache-2.0
040e8a2277a6229346d2086531fb52454ccffca5
0
kuali/kc-rice,geothomasp/kualico-rice-kc,rojlarge/rice-kc,rojlarge/rice-kc,jwillia/kc-rice1,ewestfal/rice,ewestfal/rice-svn2git-test,smith750/rice,sonamuthu/rice-1,bsmith83/rice-1,bhutchinson/rice,ewestfal/rice-svn2git-test,jwillia/kc-rice1,rojlarge/rice-kc,ewestfal/rice-svn2git-test,ewestfal/rice,shahess/rice,shahess/rice,gathreya/rice-kc,geothomasp/kualico-rice-kc,bsmith83/rice-1,sonamuthu/rice-1,ewestfal/rice-svn2git-test,bhutchinson/rice,gathreya/rice-kc,UniversityOfHawaiiORS/rice,sonamuthu/rice-1,bhutchinson/rice,jwillia/kc-rice1,kuali/kc-rice,geothomasp/kualico-rice-kc,gathreya/rice-kc,bhutchinson/rice,rojlarge/rice-kc,cniesen/rice,rojlarge/rice-kc,ewestfal/rice,cniesen/rice,cniesen/rice,smith750/rice,sonamuthu/rice-1,shahess/rice,smith750/rice,geothomasp/kualico-rice-kc,geothomasp/kualico-rice-kc,UniversityOfHawaiiORS/rice,shahess/rice,kuali/kc-rice,UniversityOfHawaiiORS/rice,bsmith83/rice-1,UniversityOfHawaiiORS/rice,gathreya/rice-kc,ewestfal/rice,shahess/rice,gathreya/rice-kc,cniesen/rice,ewestfal/rice,kuali/kc-rice,jwillia/kc-rice1,smith750/rice,bsmith83/rice-1,kuali/kc-rice,smith750/rice,cniesen/rice,bhutchinson/rice,UniversityOfHawaiiORS/rice,jwillia/kc-rice1
/* * Copyright 2005-2006 The Kuali Foundation. * * * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php * * 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.kuali.rice.kew.dto; import java.io.Serializable; import java.util.Calendar; import org.kuali.rice.kew.util.KEWConstants; import org.kuali.rice.kim.bo.group.dto.GroupInfo; /** * A transport object representing an ActionRequestValue. * * @author Kuali Rice Team ([email protected]) */ public class ActionRequestDTO implements Serializable { private final static String ACKNOWLEDGE_REQ = "K"; private final static String FYI_REQ = "F"; private final static String APPROVE_REQ = "A"; private final static String COMPLETE_REQ = "C"; static final long serialVersionUID = 1074824814950100121L; private Long actionRequestId; private String actionRequested; private String status; private Boolean currentIndicator = Boolean.TRUE; private Calendar dateCreated; private Long responsibilityId; private Long routeHeaderId; private String routeMethodName; private Integer priority; private String annotation; private Long actionTakenId; private Long groupId; private GroupInfo groupVO; private UserDTO userVO; private String recipientTypeCd; private String approvePolicy; private String responsibilityDesc; private Integer routeLevel; private Integer docVersion; private String emplyId; private String roleName; private Boolean ignorePrevAction; private UserIdDTO userIdVO; private String delegationType; private ActionRequestDTO parentActionRequest; private Long parentActionRequestId; private String qualifiedRoleName; private String qualifiedRoleNameLabel; private ActionRequestDTO[] childrenRequests; private ActionTakenDTO actionTaken; private String nodeName; private Long nodeInstanceId; public ActionRequestDTO() {} public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getActionRequested() { return actionRequested; } public Long getActionRequestId() { return actionRequestId; } public Long getActionTakenId() { return actionTakenId; } public String getAnnotation() { return annotation; } public Calendar getDateCreated() { return dateCreated; } public Integer getDocVersion() { return docVersion; } public Integer getPriority() { return priority; } public String getResponsibilityDesc() { return responsibilityDesc; } public Long getResponsibilityId() { return responsibilityId; } public Long getRouteHeaderId() { return routeHeaderId; } public Integer getRouteLevel() { return routeLevel; } public String getRouteMethodName() { return routeMethodName; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public void setRouteMethodName(String routeMethodName) { this.routeMethodName = routeMethodName; } public void setRouteLevel(Integer routeLevel) { this.routeLevel = routeLevel; } public void setRouteHeaderId(Long routeHeaderId) { this.routeHeaderId = routeHeaderId; } public void setResponsibilityId(Long responsibilityId) { this.responsibilityId = responsibilityId; } public void setResponsibilityDesc(String responsibilityDesc) { this.responsibilityDesc = responsibilityDesc; } public void setPriority(Integer priority) { this.priority = priority; } public void setDocVersion(Integer docVersion) { this.docVersion = docVersion; } public void setDateCreated(Calendar dateCreated) { this.dateCreated = dateCreated; } public void setAnnotation(String annotation) { this.annotation = annotation; } public void setActionTakenId(Long actionTakenId) { this.actionTakenId = actionTakenId; } public void setActionRequestId(Long actionRequestId) { this.actionRequestId = actionRequestId; } public void setActionRequested(String actionRequested) { this.actionRequested = actionRequested; } public String getRecipientTypeCd() { return recipientTypeCd; } public void setRecipientTypeCd(String recipientTypeCd) { this.recipientTypeCd = recipientTypeCd; } public String getApprovePolicy() { return approvePolicy; } public void setApprovePolicy(String approvePolicy) { this.approvePolicy = approvePolicy; } public Boolean getIgnorePrevAction() { return ignorePrevAction; } public UserDTO getUserDTO() { return userVO; } public void setUserDTO(UserDTO userVO) { this.userVO = userVO; } public boolean isNotificationRequest() { return isAcknowledgeRequest() || isFyiRequest(); } public boolean isApprovalRequest() { return APPROVE_REQ.equals(actionRequested) || COMPLETE_REQ.equals(actionRequested); } public void setEmplyId(String emplyId) { this.emplyId = emplyId; } /** * * @return * @deprecated */ public String getEmplyId() { return emplyId; } public Boolean isIgnorePrevAction() { return ignorePrevAction; } public void setIgnorePrevAction(Boolean ignorePrevAction) { this.ignorePrevAction = ignorePrevAction; } public boolean isAcknowledgeRequest() { return ACKNOWLEDGE_REQ.equals(actionRequested); } public boolean isFyiRequest() { return FYI_REQ.equals(actionRequested); } public boolean isPending() { return isInitialized() || isActivated(); } public boolean isCompleteRequest() { return KEWConstants.ACTION_REQUEST_COMPLETE_REQ.equals(actionRequested); } public boolean isInitialized() { return KEWConstants.ACTION_REQUEST_INITIALIZED.equals(status); } public boolean isActivated() { return KEWConstants.ACTION_REQUEST_ACTIVATED.equals(status); } public boolean isDone() { return KEWConstants.ACTION_REQUEST_DONE_STATE.equals(status); } public boolean isUserRequest() { return KEWConstants.ACTION_REQUEST_USER_RECIPIENT_CD.equals(getRecipientTypeCd()); } public boolean isGroupRequest() { return KEWConstants.ACTION_REQUEST_GROUP_RECIPIENT_CD.equals(getRecipientTypeCd()); } public boolean isRoleRequest() { return KEWConstants.ACTION_REQUEST_ROLE_RECIPIENT_CD.equals(getRecipientTypeCd()); } public UserIdDTO getUserIdVO() { return userIdVO; } public void setUserIdVO(UserIdDTO userIdVO) { this.userIdVO = userIdVO; } public Boolean getCurrentIndicator() { return currentIndicator; } public void setCurrentIndicator(Boolean currentIndicator) { this.currentIndicator = currentIndicator; } public String getDelegationType() { return delegationType; } public void setDelegationType(String delegationType) { this.delegationType = delegationType; } public ActionRequestDTO getParentActionRequest() { return parentActionRequest; } public void setParentActionRequest(ActionRequestDTO parentActionRequest) { this.parentActionRequest = parentActionRequest; } public Long getParentActionRequestId() { return parentActionRequestId; } public void setParentActionRequestId(Long parentActionRequestId) { this.parentActionRequestId = parentActionRequestId; } public String getQualifiedRoleName() { return qualifiedRoleName; } public void setQualifiedRoleName(String qualifiedRoleName) { this.qualifiedRoleName = qualifiedRoleName; } public String getQualifiedRoleNameLabel() { return qualifiedRoleNameLabel; } public void setQualifiedRoleNameLabel(String qualifiedRoleNameLabel) { this.qualifiedRoleNameLabel = qualifiedRoleNameLabel; } public ActionTakenDTO getActionTaken() { return actionTaken; } public void setActionTaken(ActionTakenDTO actionTaken) { this.actionTaken = actionTaken; } public ActionRequestDTO[] getChildrenRequests() { return childrenRequests; } public void setChildrenRequests(ActionRequestDTO[] childrenRequests) { this.childrenRequests = childrenRequests; } public void addChildRequest(ActionRequestDTO childRequest) { if (getChildrenRequests() == null) { setChildrenRequests(new ActionRequestDTO[0]); } ActionRequestDTO[] newChildrenRequests = new ActionRequestDTO[getChildrenRequests().length+1]; System.arraycopy(getChildrenRequests(), 0, newChildrenRequests, 0, getChildrenRequests().length); newChildrenRequests[getChildrenRequests().length] = childRequest; setChildrenRequests(newChildrenRequests); } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } public Long getNodeInstanceId() { return nodeInstanceId; } public void setNodeInstanceId(Long nodeInstanceId) { this.nodeInstanceId = nodeInstanceId; } public boolean isDelegateRequest() { if (getParentActionRequest() != null) { if (getParentActionRequest().isRoleRequest()) { return getParentActionRequest().isDelegateRequest(); } return true; } return false; } public boolean isAdHocRequest() { return KEWConstants.ADHOC_REQUEST_RESPONSIBILITY_ID.equals(getResponsibilityId()); } public boolean isGeneratedRequest() { return KEWConstants.MACHINE_GENERATED_RESPONSIBILITY_ID.equals(getResponsibilityId()); } public boolean isExceptionRequest() { return KEWConstants.EXCEPTION_REQUEST_RESPONSIBILITY_ID.equals(getResponsibilityId()); } public boolean isRouteModuleRequest() { return getResponsibilityId().longValue() > 0; } /** * @return the groupVO */ public GroupInfo getGroupVO() { return this.groupVO; } /** * @param groupVO the groupVO to set */ public void setGroupVO(GroupInfo groupVO) { this.groupVO = groupVO; } }
api/src/main/java/org/kuali/rice/kew/dto/ActionRequestDTO.java
/* * Copyright 2005-2006 The Kuali Foundation. * * * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php * * 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.kuali.rice.kew.dto; import java.io.Serializable; import java.util.Calendar; import org.kuali.rice.kew.util.KEWConstants; /** * A transport object representing an ActionRequestValue. * * @author Kuali Rice Team ([email protected]) */ public class ActionRequestDTO implements Serializable { private final static String ACKNOWLEDGE_REQ = "K"; private final static String FYI_REQ = "F"; private final static String APPROVE_REQ = "A"; private final static String COMPLETE_REQ = "C"; static final long serialVersionUID = 1074824814950100121L; private Long actionRequestId; private String actionRequested; private String status; private Boolean currentIndicator = Boolean.TRUE; private Calendar dateCreated; private Long responsibilityId; private Long routeHeaderId; private String routeMethodName; private Integer priority; private String annotation; private Long actionTakenId; private Long workgroupId; private WorkgroupDTO workgroupVO; private UserDTO userVO; private String recipientTypeCd; private String approvePolicy; private String responsibilityDesc; private Integer routeLevel; private Integer docVersion; private String emplyId; private String roleName; private Boolean ignorePrevAction; private UserIdDTO userIdVO; private String delegationType; private ActionRequestDTO parentActionRequest; private Long parentActionRequestId; private String qualifiedRoleName; private String qualifiedRoleNameLabel; private ActionRequestDTO[] childrenRequests; private ActionTakenDTO actionTaken; private String nodeName; private Long nodeInstanceId; public ActionRequestDTO() {} public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getActionRequested() { return actionRequested; } public Long getActionRequestId() { return actionRequestId; } public Long getActionTakenId() { return actionTakenId; } public String getAnnotation() { return annotation; } public Calendar getDateCreated() { return dateCreated; } public Integer getDocVersion() { return docVersion; } public Integer getPriority() { return priority; } public String getResponsibilityDesc() { return responsibilityDesc; } public Long getResponsibilityId() { return responsibilityId; } public Long getRouteHeaderId() { return routeHeaderId; } public Integer getRouteLevel() { return routeLevel; } public String getRouteMethodName() { return routeMethodName; } public String getStatus() { return status; } public Long getWorkgroupId() { return workgroupId; } public void setWorkgroupId(Long workgroupId) { this.workgroupId = workgroupId; } public void setStatus(String status) { this.status = status; } public void setRouteMethodName(String routeMethodName) { this.routeMethodName = routeMethodName; } public void setRouteLevel(Integer routeLevel) { this.routeLevel = routeLevel; } public void setRouteHeaderId(Long routeHeaderId) { this.routeHeaderId = routeHeaderId; } public void setResponsibilityId(Long responsibilityId) { this.responsibilityId = responsibilityId; } public void setResponsibilityDesc(String responsibilityDesc) { this.responsibilityDesc = responsibilityDesc; } public void setPriority(Integer priority) { this.priority = priority; } public void setDocVersion(Integer docVersion) { this.docVersion = docVersion; } public void setDateCreated(Calendar dateCreated) { this.dateCreated = dateCreated; } public void setAnnotation(String annotation) { this.annotation = annotation; } public void setActionTakenId(Long actionTakenId) { this.actionTakenId = actionTakenId; } public void setActionRequestId(Long actionRequestId) { this.actionRequestId = actionRequestId; } public void setActionRequested(String actionRequested) { this.actionRequested = actionRequested; } public String getRecipientTypeCd() { return recipientTypeCd; } public void setRecipientTypeCd(String recipientTypeCd) { this.recipientTypeCd = recipientTypeCd; } public String getApprovePolicy() { return approvePolicy; } public void setApprovePolicy(String approvePolicy) { this.approvePolicy = approvePolicy; } public Boolean getIgnorePrevAction() { return ignorePrevAction; } public UserDTO getUserDTO() { return userVO; } public void setUserDTO(UserDTO userVO) { this.userVO = userVO; } public WorkgroupDTO getWorkgroupDTO() { return workgroupVO; } public void setWorkgroupDTO(WorkgroupDTO workgroupVO) { this.workgroupVO = workgroupVO; } public boolean isNotificationRequest() { return isAcknowledgeRequest() || isFyiRequest(); } public boolean isApprovalRequest() { return APPROVE_REQ.equals(actionRequested) || COMPLETE_REQ.equals(actionRequested); } public void setEmplyId(String emplyId) { this.emplyId = emplyId; } /** * * @return * @deprecated */ public String getEmplyId() { return emplyId; } public Boolean isIgnorePrevAction() { return ignorePrevAction; } public void setIgnorePrevAction(Boolean ignorePrevAction) { this.ignorePrevAction = ignorePrevAction; } public boolean isAcknowledgeRequest() { return ACKNOWLEDGE_REQ.equals(actionRequested); } public boolean isFyiRequest() { return FYI_REQ.equals(actionRequested); } public boolean isPending() { return isInitialized() || isActivated(); } public boolean isCompleteRequest() { return KEWConstants.ACTION_REQUEST_COMPLETE_REQ.equals(actionRequested); } public boolean isInitialized() { return KEWConstants.ACTION_REQUEST_INITIALIZED.equals(status); } public boolean isActivated() { return KEWConstants.ACTION_REQUEST_ACTIVATED.equals(status); } public boolean isDone() { return KEWConstants.ACTION_REQUEST_DONE_STATE.equals(status); } public boolean isUserRequest() { return KEWConstants.ACTION_REQUEST_USER_RECIPIENT_CD.equals(getRecipientTypeCd()); } public boolean isWorkgroupRequest() { return KEWConstants.ACTION_REQUEST_WORKGROUP_RECIPIENT_CD.equals(getRecipientTypeCd()); } public boolean isRoleRequest() { return KEWConstants.ACTION_REQUEST_ROLE_RECIPIENT_CD.equals(getRecipientTypeCd()); } public UserIdDTO getUserIdVO() { return userIdVO; } public void setUserIdVO(UserIdDTO userIdVO) { this.userIdVO = userIdVO; } public Boolean getCurrentIndicator() { return currentIndicator; } public void setCurrentIndicator(Boolean currentIndicator) { this.currentIndicator = currentIndicator; } public String getDelegationType() { return delegationType; } public void setDelegationType(String delegationType) { this.delegationType = delegationType; } public ActionRequestDTO getParentActionRequest() { return parentActionRequest; } public void setParentActionRequest(ActionRequestDTO parentActionRequest) { this.parentActionRequest = parentActionRequest; } public Long getParentActionRequestId() { return parentActionRequestId; } public void setParentActionRequestId(Long parentActionRequestId) { this.parentActionRequestId = parentActionRequestId; } public String getQualifiedRoleName() { return qualifiedRoleName; } public void setQualifiedRoleName(String qualifiedRoleName) { this.qualifiedRoleName = qualifiedRoleName; } public String getQualifiedRoleNameLabel() { return qualifiedRoleNameLabel; } public void setQualifiedRoleNameLabel(String qualifiedRoleNameLabel) { this.qualifiedRoleNameLabel = qualifiedRoleNameLabel; } public ActionTakenDTO getActionTaken() { return actionTaken; } public void setActionTaken(ActionTakenDTO actionTaken) { this.actionTaken = actionTaken; } public ActionRequestDTO[] getChildrenRequests() { return childrenRequests; } public void setChildrenRequests(ActionRequestDTO[] childrenRequests) { this.childrenRequests = childrenRequests; } public void addChildRequest(ActionRequestDTO childRequest) { if (getChildrenRequests() == null) { setChildrenRequests(new ActionRequestDTO[0]); } ActionRequestDTO[] newChildrenRequests = new ActionRequestDTO[getChildrenRequests().length+1]; System.arraycopy(getChildrenRequests(), 0, newChildrenRequests, 0, getChildrenRequests().length); newChildrenRequests[getChildrenRequests().length] = childRequest; setChildrenRequests(newChildrenRequests); } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } public Long getNodeInstanceId() { return nodeInstanceId; } public void setNodeInstanceId(Long nodeInstanceId) { this.nodeInstanceId = nodeInstanceId; } public boolean isDelegateRequest() { if (getParentActionRequest() != null) { if (getParentActionRequest().isRoleRequest()) { return getParentActionRequest().isDelegateRequest(); } return true; } return false; } public boolean isAdHocRequest() { return KEWConstants.ADHOC_REQUEST_RESPONSIBILITY_ID.equals(getResponsibilityId()); } public boolean isGeneratedRequest() { return KEWConstants.MACHINE_GENERATED_RESPONSIBILITY_ID.equals(getResponsibilityId()); } public boolean isExceptionRequest() { return KEWConstants.EXCEPTION_REQUEST_RESPONSIBILITY_ID.equals(getResponsibilityId()); } public boolean isRouteModuleRequest() { return getResponsibilityId().longValue() > 0; } }
KULRICE-2437 replaced kew workgroup with kim group
api/src/main/java/org/kuali/rice/kew/dto/ActionRequestDTO.java
KULRICE-2437 replaced kew workgroup with kim group
<ide><path>pi/src/main/java/org/kuali/rice/kew/dto/ActionRequestDTO.java <ide> import java.util.Calendar; <ide> <ide> import org.kuali.rice.kew.util.KEWConstants; <add>import org.kuali.rice.kim.bo.group.dto.GroupInfo; <ide> <ide> <ide> /** <ide> private Integer priority; <ide> private String annotation; <ide> private Long actionTakenId; <del> private Long workgroupId; <del> private WorkgroupDTO workgroupVO; <add> private Long groupId; <add> private GroupInfo groupVO; <ide> private UserDTO userVO; <ide> private String recipientTypeCd; <ide> private String approvePolicy; <ide> public String getStatus() { <ide> return status; <ide> } <del> <del> public Long getWorkgroupId() { <del> return workgroupId; <del> } <del> <del> public void setWorkgroupId(Long workgroupId) { <del> this.workgroupId = workgroupId; <del> } <del> <add> <ide> public void setStatus(String status) { <ide> this.status = status; <ide> } <ide> <ide> public void setUserDTO(UserDTO userVO) { <ide> this.userVO = userVO; <del> } <del> <del> public WorkgroupDTO getWorkgroupDTO() { <del> return workgroupVO; <del> } <del> <del> public void setWorkgroupDTO(WorkgroupDTO workgroupVO) { <del> this.workgroupVO = workgroupVO; <ide> } <ide> <ide> public boolean isNotificationRequest() { <ide> return KEWConstants.ACTION_REQUEST_USER_RECIPIENT_CD.equals(getRecipientTypeCd()); <ide> } <ide> <del> public boolean isWorkgroupRequest() { <del> return KEWConstants.ACTION_REQUEST_WORKGROUP_RECIPIENT_CD.equals(getRecipientTypeCd()); <add> public boolean isGroupRequest() { <add> return KEWConstants.ACTION_REQUEST_GROUP_RECIPIENT_CD.equals(getRecipientTypeCd()); <ide> } <ide> <ide> public boolean isRoleRequest() { <ide> public boolean isRouteModuleRequest() { <ide> return getResponsibilityId().longValue() > 0; <ide> } <add> <add> /** <add> * @return the groupVO <add> */ <add> public GroupInfo getGroupVO() { <add> return this.groupVO; <add> } <add> <add> /** <add> * @param groupVO the groupVO to set <add> */ <add> public void setGroupVO(GroupInfo groupVO) { <add> this.groupVO = groupVO; <add> } <ide> }
Java
mit
5694fe60ee62ae0174dbd372933daf7250144fa4
0
McJty/DeepResonance
package mcjty.deepresonance.varia; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidTank; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidTankProperties; import javax.annotation.Nullable; /** * Created by Elec332 on 11-8-2016. */ public abstract class FluidTankWrapper implements IFluidHandler, IFluidTank { public static FluidTankWrapper of(final IFluidTank tank){ return new FluidTankWrapper() { @Override protected IFluidTank getTank() { return tank; } }; } public FluidTankWrapper(){ final IFluidTankProperties prop = new Properties(this); this.properties = new IFluidTankProperties[]{ prop }; } private IFluidTankProperties[] properties; protected abstract IFluidTank getTank(); @Override public IFluidTankProperties[] getTankProperties() { return properties; } @Override public int fill(FluidStack resource, boolean doFill) { if (!canFillFluidType(resource)) { return 0; } return getTank().fill(resource, doFill); } @Override public FluidStack drain(FluidStack resource, boolean doDrain) { FluidStack f = getTank().getFluid(); if (!canDrainFluidType(f) || resource == null || f == null || resource.isFluidEqual(f)) { return null; } return getTank().drain(resource.amount, doDrain); } @Override public FluidStack drain(int maxDrain, boolean doDrain) { if (!canDrainFluidType(getTank().getFluid())) { return null; } return getTank().drain(maxDrain, doDrain); } @Nullable @Override public FluidStack getFluid() { FluidStack tankStack = getTank().getFluid(); return tankStack == null ? null : tankStack.copy(); } @Override public int getFluidAmount() { return getTank().getFluidAmount(); } @Override public int getCapacity() { return getTank().getCapacity(); } @Override public FluidTankInfo getInfo() { return getTank().getInfo(); } protected boolean canFill() { return true; } protected boolean canDrain() { return true; } protected boolean canFillFluidType(FluidStack fluidStack) { if (fluidStack == null){ return false; } FluidStack f = getTank().getFluid(); if (f == null){ return canFillFluidTypeInternal(fluidStack); } return f.getFluid() == fluidStack.getFluid(); } protected boolean canFillFluidTypeInternal(FluidStack fluidStack) { return canFill(); } protected boolean canDrainFluidType(FluidStack fluidStack) { return fluidStack != null && canDrain(); } private class Properties implements IFluidTankProperties { private Properties(FluidTankWrapper tank){ this.tank = tank; } private final FluidTankWrapper tank; @Nullable @Override public FluidStack getContents() { FluidStack stack = tank.getTank().getFluid(); return stack == null ? null : stack.copy(); } @Override public int getCapacity() { return tank.getTank().getCapacity(); } @Override public boolean canFill() { return tank.canFill(); } @Override public boolean canDrain() { return tank.canDrain(); } @Override public boolean canFillFluidType(FluidStack fluidStack) { return tank.canFillFluidType(fluidStack); } @Override public boolean canDrainFluidType(FluidStack fluidStack) { return tank.canDrainFluidType(fluidStack); } } }
src/main/java/mcjty/deepresonance/varia/FluidTankWrapper.java
package mcjty.deepresonance.varia; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidTank; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidTankProperties; import javax.annotation.Nullable; /** * Created by Elec332 on 11-8-2016. */ public abstract class FluidTankWrapper implements IFluidHandler, IFluidTank { public static FluidTankWrapper of(final IFluidTank tank){ return new FluidTankWrapper() { @Override protected IFluidTank getTank() { return tank; } }; } public FluidTankWrapper(){ final IFluidTankProperties prop = new Properties(this); this.properties = new IFluidTankProperties[]{ prop }; } private IFluidTankProperties[] properties; protected abstract IFluidTank getTank(); @Override public IFluidTankProperties[] getTankProperties() { return properties; } @Override public int fill(FluidStack resource, boolean doFill) { if (!canFillFluidType(resource)) { return 0; } return getTank().fill(resource, doFill); } @Override public FluidStack drain(FluidStack resource, boolean doDrain) { FluidStack f = getTank().getFluid(); if (!canDrainFluidType(f) || resource == null || f == null || resource.getFluid() != f.getFluid()) { return null; } return getTank().drain(resource.amount, doDrain); } @Override public FluidStack drain(int maxDrain, boolean doDrain) { if (!canDrainFluidType(getTank().getFluid())) { return null; } return getTank().drain(maxDrain, doDrain); } @Nullable @Override public FluidStack getFluid() { FluidStack tankStack = getTank().getFluid(); return tankStack == null ? null : tankStack.copy(); } @Override public int getFluidAmount() { return getTank().getFluidAmount(); } @Override public int getCapacity() { return getTank().getCapacity(); } @Override public FluidTankInfo getInfo() { return getTank().getInfo(); } protected boolean canFill() { return true; } protected boolean canDrain() { return true; } protected boolean canFillFluidType(FluidStack fluidStack) { if (fluidStack == null){ return false; } FluidStack f = getTank().getFluid(); if (f == null){ return canFillFluidTypeInternal(fluidStack); } return f.getFluid() == fluidStack.getFluid(); } protected boolean canFillFluidTypeInternal(FluidStack fluidStack) { return canFill(); } protected boolean canDrainFluidType(FluidStack fluidStack) { return fluidStack != null && canDrain(); } private class Properties implements IFluidTankProperties { private Properties(FluidTankWrapper tank){ this.tank = tank; } private final FluidTankWrapper tank; @Nullable @Override public FluidStack getContents() { FluidStack stack = tank.getTank().getFluid(); return stack == null ? null : stack.copy(); } @Override public int getCapacity() { return tank.getTank().getCapacity(); } @Override public boolean canFill() { return tank.canFill(); } @Override public boolean canDrain() { return tank.canDrain(); } @Override public boolean canFillFluidType(FluidStack fluidStack) { return tank.canFillFluidType(fluidStack); } @Override public boolean canDrainFluidType(FluidStack fluidStack) { return tank.canDrainFluidType(fluidStack); } } }
Fix equality check
src/main/java/mcjty/deepresonance/varia/FluidTankWrapper.java
Fix equality check
<ide><path>rc/main/java/mcjty/deepresonance/varia/FluidTankWrapper.java <ide> @Override <ide> public FluidStack drain(FluidStack resource, boolean doDrain) { <ide> FluidStack f = getTank().getFluid(); <del> if (!canDrainFluidType(f) || resource == null || f == null || resource.getFluid() != f.getFluid()) { <add> if (!canDrainFluidType(f) || resource == null || f == null || resource.isFluidEqual(f)) { <ide> return null; <ide> } <ide> return getTank().drain(resource.amount, doDrain);
Java
lgpl-2.1
c5de7d1f39a82acff20a8421acf3691d182562f9
0
xwiki-contrib/application-nestedpagesmigrator
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.contrib.nestedpagesmigrator.internal; import javax.inject.Inject; import javax.inject.Singleton; import org.xwiki.component.annotation.Component; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.component.manager.ComponentManager; import org.xwiki.contrib.nestedpagesmigrator.MigrationConfiguration; import org.xwiki.contrib.nestedpagesmigrator.MigrationException; import org.xwiki.contrib.nestedpagesmigrator.MigrationPlanTree; import org.xwiki.contrib.nestedpagesmigrator.NestedPagesMigrator; /** * @version $Id: $ */ @Component @Singleton public class DefaultNestedPagesMigrator implements NestedPagesMigrator { @Inject ComponentManager componentManager; @Override public MigrationPlanTree computeMigrationPlan(MigrationConfiguration configuration) throws MigrationException { try { MigrationPlanCreator migrationPlanCreator = componentManager.getInstance(MigrationPlanCreator.class); return migrationPlanCreator.computeMigrationPlan(configuration); } catch (ComponentLookupException e) { throw new MigrationException("Unexpected error.", e); } } }
application-nestedpagesmigrator-api/src/main/java/org/xwiki/contrib/nestedpagesmigrator/internal/DefaultNestedPagesMigrator.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.contrib.nestedpagesmigrator.internal; import javax.inject.Inject; import javax.inject.Singleton; import org.xwiki.component.annotation.Component; import org.xwiki.contrib.nestedpagesmigrator.MigrationConfiguration; import org.xwiki.contrib.nestedpagesmigrator.MigrationException; import org.xwiki.contrib.nestedpagesmigrator.MigrationPlanTree; import org.xwiki.contrib.nestedpagesmigrator.NestedPagesMigrator; /** * @version $Id: $ */ @Component @Singleton public class DefaultNestedPagesMigrator implements NestedPagesMigrator { @Inject MigrationPlanCreator migrationPlanCreator; @Override public MigrationPlanTree computeMigrationPlan(MigrationConfiguration configuration) throws MigrationException { return migrationPlanCreator.computeMigrationPlan(configuration); } }
NPMIG-3: Handle the case where 2 different pages could have the same target. * Cleaning.
application-nestedpagesmigrator-api/src/main/java/org/xwiki/contrib/nestedpagesmigrator/internal/DefaultNestedPagesMigrator.java
NPMIG-3: Handle the case where 2 different pages could have the same target.
<ide><path>pplication-nestedpagesmigrator-api/src/main/java/org/xwiki/contrib/nestedpagesmigrator/internal/DefaultNestedPagesMigrator.java <ide> import javax.inject.Singleton; <ide> <ide> import org.xwiki.component.annotation.Component; <add>import org.xwiki.component.manager.ComponentLookupException; <add>import org.xwiki.component.manager.ComponentManager; <ide> import org.xwiki.contrib.nestedpagesmigrator.MigrationConfiguration; <ide> import org.xwiki.contrib.nestedpagesmigrator.MigrationException; <ide> import org.xwiki.contrib.nestedpagesmigrator.MigrationPlanTree; <ide> public class DefaultNestedPagesMigrator implements NestedPagesMigrator <ide> { <ide> @Inject <del> MigrationPlanCreator migrationPlanCreator; <add> ComponentManager componentManager; <ide> <ide> @Override <ide> public MigrationPlanTree computeMigrationPlan(MigrationConfiguration configuration) throws MigrationException <ide> { <del> return migrationPlanCreator.computeMigrationPlan(configuration); <add> try { <add> MigrationPlanCreator migrationPlanCreator = componentManager.getInstance(MigrationPlanCreator.class); <add> return migrationPlanCreator.computeMigrationPlan(configuration); <add> } catch (ComponentLookupException e) { <add> throw new MigrationException("Unexpected error.", e); <add> } <ide> } <ide> }
Java
apache-2.0
598d3806d00be87c56978eb3013059a8ee7ac65d
0
spotify/docker-client,rgrunber/docker-client,spotify/docker-client,MarcoLotz/docker-client,rgrunber/docker-client,MarcoLotz/docker-client
/* * Copyright (c) 2014 Spotify AB. * * 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.spotify.docker.client.messages; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; @JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE, setterVisibility = NONE) public class HostConfig { @JsonProperty("Binds") private ImmutableList<String> binds; @JsonProperty("ContainerIDFile") private String containerIDFile; @JsonProperty("LxcConf") private ImmutableList<LxcConfParameter> lxcConf; @JsonProperty("Privileged") private Boolean privileged; @JsonProperty("PortBindings") private Map<String, List<PortBinding>> portBindings; @JsonProperty("Links") private ImmutableList<String> links; @JsonProperty("PublishAllPorts") private Boolean publishAllPorts; @JsonProperty("Dns") private ImmutableList<String> dns; @JsonProperty("DnsSearch") private ImmutableList<String> dnsSearch; @JsonProperty("ExtraHosts") private ImmutableList<String> extraHosts; @JsonProperty("VolumesFrom") private ImmutableList<String> volumesFrom; @JsonProperty("CapAdd") private ImmutableList<String> capAdd; @JsonProperty("CapDrop") private ImmutableList<String> capDrop; @JsonProperty("NetworkMode") private String networkMode; @JsonProperty("SecurityOpt") private ImmutableList<String> securityOpt; @JsonProperty("Devices") private ImmutableList<Device> devices; @JsonProperty("Memory") private Long memory; @JsonProperty("MemorySwap") private Long memorySwap; @JsonProperty("MemoryReservation") private Long memoryReservation; @JsonProperty("CpuShares") private Long cpuShares; @JsonProperty("CpusetCpus") private String cpusetCpus; @JsonProperty("CpuQuota") private Long cpuQuota; @JsonProperty("CgroupParent") private String cgroupParent; @JsonProperty("RestartPolicy") private RestartPolicy restartPolicy; @JsonProperty("LogConfig") private LogConfig logConfig; @JsonProperty("IpcMode") private String ipcMode; @JsonProperty("Ulimits") private ImmutableList<Ulimit> ulimits; @JsonProperty("PidMode") private String pidMode; @JsonProperty("ShmSize") private Long shmSize; @JsonProperty("OomKillDisable") private Boolean oomKillDisable; @JsonProperty("OomScoreAdj") private Integer oomScoreAdj; private HostConfig() { } private HostConfig(final Builder builder) { this.binds = builder.binds; this.containerIDFile = builder.containerIDFile; this.lxcConf = builder.lxcConf; this.privileged = builder.privileged; this.portBindings = builder.portBindings; this.links = builder.links; this.publishAllPorts = builder.publishAllPorts; this.dns = builder.dns; this.dnsSearch = builder.dnsSearch; this.extraHosts = builder.extraHosts; this.volumesFrom = builder.volumesFrom; this.capAdd = builder.capAdd; this.capDrop = builder.capDrop; this.networkMode = builder.networkMode; this.securityOpt = builder.securityOpt; this.devices = builder.devices; this.memory = builder.memory; this.memorySwap = builder.memorySwap; this.memoryReservation = builder.memoryReservation; this.cpuShares = builder.cpuShares; this.cpusetCpus = builder.cpusetCpus; this.cpuQuota = builder.cpuQuota; this.cgroupParent = builder.cgroupParent; this.restartPolicy = builder.restartPolicy; this.logConfig = builder.logConfig; this.ipcMode = builder.ipcMode; this.ulimits = builder.ulimits; this.pidMode = builder.pidMode; this.shmSize = builder.shmSize; this.oomKillDisable = builder.oomKillDisable; this.oomScoreAdj = builder.oomScoreAdj; } public List<String> binds() { return binds; } public String containerIDFile() { return containerIDFile; } public List<LxcConfParameter> lxcConf() { return lxcConf; } public Boolean privileged() { return privileged; } public Map<String, List<PortBinding>> portBindings() { return (portBindings == null) ? null : Collections.unmodifiableMap(portBindings); } public List<String> links() { return links; } public Boolean publishAllPorts() { return publishAllPorts; } public List<String> dns() { return dns; } public List<String> dnsSearch() { return dnsSearch; } public List<String> extraHosts() { return extraHosts; } public List<String> volumesFrom() { return volumesFrom; } public List<String> capAdd() { return capAdd; } public List<String> capDrop() { return capDrop; } public String networkMode() { return networkMode; } public List<String> securityOpt() { return securityOpt; } public List<Device> devices() { return devices; } public Long memory() { return memory; } public Long memorySwap() { return memorySwap; } public Long getMemoryReservation() { return memoryReservation; } public Long cpuShares() { return cpuShares; } public String cpusetCpus() { return cpusetCpus; } public Long cpuQuota() { return cpuQuota; } public String cgroupParent() { return cgroupParent; } public RestartPolicy restartPolicy() { return restartPolicy; } public LogConfig logConfig() { return logConfig; } public String ipcMode() { return ipcMode; } public List<Ulimit> ulimits() { return ulimits; } public Long shmSize() { return shmSize; } public Boolean oomKillDisable() { return oomKillDisable; } public Integer oomScoreAdj() { return oomScoreAdj; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final HostConfig that = (HostConfig) o; return Objects.equals(this.binds, that.binds) && Objects.equals(this.containerIDFile, that.containerIDFile) && Objects.equals(this.lxcConf, that.lxcConf) && Objects.equals(this.privileged, that.privileged) && Objects.equals(this.portBindings, that.portBindings) && Objects.equals(this.links, that.links) && Objects.equals(this.publishAllPorts, that.publishAllPorts) && Objects.equals(this.dns, that.dns) && Objects.equals(this.dnsSearch, that.dnsSearch) && Objects.equals(this.extraHosts, that.extraHosts) && Objects.equals(this.volumesFrom, that.volumesFrom) && Objects.equals(this.capAdd, that.capAdd) && Objects.equals(this.capDrop, that.capDrop) && Objects.equals(this.networkMode, that.networkMode) && Objects.equals(this.securityOpt, that.securityOpt) && Objects.equals(this.devices, that.devices) && Objects.equals(this.memory, that.memory) && Objects.equals(this.memorySwap, that.memorySwap) && Objects.equals(this.memoryReservation, that.memoryReservation) && Objects.equals(this.cpuShares, that.cpuShares) && Objects.equals(this.cpusetCpus, that.cpusetCpus) && Objects.equals(this.cpuQuota, that.cpuQuota) && Objects.equals(this.cgroupParent, that.cgroupParent) && Objects.equals(this.restartPolicy, that.restartPolicy) && Objects.equals(this.logConfig, that.logConfig) && Objects.equals(this.ipcMode, that.ipcMode) && Objects.equals(this.ulimits, that.ulimits) && Objects.equals(this.oomKillDisable, that.oomKillDisable) && Objects.equals(this.oomScoreAdj, that.oomScoreAdj); } @Override public int hashCode() { return Objects.hash(binds, containerIDFile, lxcConf, privileged, portBindings, links, publishAllPorts, dns, dnsSearch, extraHosts, volumesFrom, capAdd, capDrop, networkMode, securityOpt, devices, memory, memorySwap, memoryReservation, cpuShares, cpusetCpus, cpuQuota, cgroupParent, restartPolicy, logConfig, ipcMode, ulimits, pidMode, shmSize, oomKillDisable, oomScoreAdj); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("binds", binds) .add("containerIDFile", containerIDFile) .add("lxcConf", lxcConf) .add("privileged", privileged) .add("portBindings", portBindings) .add("links", links) .add("publishAllPorts", publishAllPorts) .add("dns", dns) .add("dnsSearch", dnsSearch) .add("extraHosts", extraHosts) .add("volumesFrom", volumesFrom) .add("capAdd", capAdd) .add("capDrop", capDrop) .add("networkMode", networkMode) .add("securityOpt", securityOpt) .add("devices", devices) .add("memory", memory) .add("memorySwap", memorySwap) .add("memoryReservation", memoryReservation) .add("cpuShares", cpuShares) .add("cpusetCpus", cpusetCpus) .add("cpuQuota", cpuQuota) .add("cgroupParent", cgroupParent) .add("restartPolicy", restartPolicy) .add("logConfig", logConfig) .add("ipcMode", ipcMode) .add("ulimits", ulimits) .add("pidMode", pidMode) .add("shmSize", shmSize) .add("oomKillDisable", oomKillDisable) .add("oomScoreAdj", oomScoreAdj) .toString(); } public static class LxcConfParameter { @JsonProperty("Key") private String key; @JsonProperty("Value") private String value; public LxcConfParameter(final String key, final String value) { this.key = key; this.value = value; } public String key() { return key; } public String value() { return value; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final LxcConfParameter that = (LxcConfParameter) o; return Objects.equals(this.key, that.key) && Objects.equals(this.value, that.value); } @Override public int hashCode() { return Objects.hash(key, value); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("key", key) .add("value", value) .toString(); } } public static class RestartPolicy { @JsonProperty("Name") private String name; @JsonProperty("MaximumRetryCount") private Integer maxRetryCount; public static RestartPolicy always() { return new RestartPolicy("always", null); } public static RestartPolicy unlessStopped() { return new RestartPolicy("unless-stopped", null); } public static RestartPolicy onFailure(Integer maxRetryCount) { return new RestartPolicy("on-failure", maxRetryCount); } // for mapper private RestartPolicy() { } private RestartPolicy(String name, Integer maxRetryCount) { this.name = name; this.maxRetryCount = maxRetryCount; } public String name() { return name; } public Integer maxRetryCount() { return maxRetryCount; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final RestartPolicy that = (RestartPolicy) o; return Objects.equals(this.name, that.name) && Objects.equals(this.maxRetryCount, that.maxRetryCount); } @Override public int hashCode() { return Objects.hash(name, maxRetryCount); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", name) .add("maxRetryCount", maxRetryCount) .toString(); } } public Builder toBuilder() { return new Builder(this); } public static Builder builder() { return new Builder(); } public static class Builder { private ImmutableList<String> binds; private String containerIDFile; private ImmutableList<LxcConfParameter> lxcConf; private Boolean privileged; private Map<String, List<PortBinding>> portBindings; private ImmutableList<String> links; private Boolean publishAllPorts; private ImmutableList<String> dns; private ImmutableList<String> dnsSearch; private ImmutableList<String> extraHosts; private ImmutableList<String> volumesFrom; private ImmutableList<String> capAdd; private ImmutableList<String> capDrop; private String networkMode; private ImmutableList<String> securityOpt; private ImmutableList<Device> devices; private Long memory; private Long memorySwap; private Long memoryReservation; private Long cpuShares; private String cpusetCpus; private Long cpuQuota; private String cgroupParent; private RestartPolicy restartPolicy; private LogConfig logConfig; private String ipcMode; private ImmutableList<Ulimit> ulimits; private String pidMode; private Long shmSize; private Boolean oomKillDisable; private Integer oomScoreAdj; private Builder() { } private Builder(final HostConfig hostConfig) { this.binds = hostConfig.binds; this.containerIDFile = hostConfig.containerIDFile; this.lxcConf = hostConfig.lxcConf; this.privileged = hostConfig.privileged; this.portBindings = hostConfig.portBindings; this.links = hostConfig.links; this.publishAllPorts = hostConfig.publishAllPorts; this.dns = hostConfig.dns; this.dnsSearch = hostConfig.dnsSearch; this.extraHosts = hostConfig.extraHosts; this.volumesFrom = hostConfig.volumesFrom; this.capAdd = hostConfig.capAdd; this.capDrop = hostConfig.capDrop; this.networkMode = hostConfig.networkMode; this.securityOpt = hostConfig.securityOpt; this.devices = hostConfig.devices; this.memory = hostConfig.memory; this.memorySwap = hostConfig.memorySwap; this.memoryReservation = hostConfig.memoryReservation; this.cpuShares = hostConfig.cpuShares; this.cpusetCpus = hostConfig.cpusetCpus; this.cpuQuota = hostConfig.cpuQuota; this.cgroupParent = hostConfig.cgroupParent; this.restartPolicy = hostConfig.restartPolicy; this.logConfig = hostConfig.logConfig; this.ipcMode = hostConfig.ipcMode; this.ulimits = hostConfig.ulimits; this.pidMode = hostConfig.pidMode; this.shmSize = hostConfig.shmSize; this.oomKillDisable = hostConfig.oomKillDisable; this.oomScoreAdj = hostConfig.oomScoreAdj; } /** * Set the list of binds to the parameter, replacing any existing value. * <p>To append to the list instead, use one of the appendBinds() methods.</p> * * @param binds A list of volume bindings for this container. Each volume binding is a string. * @return The builder */ public Builder binds(final List<String> binds) { if (binds != null && !binds.isEmpty()) { this.binds = copyWithoutDuplicates(binds); } return this; } /** * Set the list of binds to the parameter, replacing any existing value. * <p>To append to the list instead, use one of the appendBinds() methods.</p> * * @param binds An array of volume bindings for this container. Each volume binding is a string. * @return The builder */ public Builder binds(final String... binds) { if (binds != null && binds.length > 0) { return binds(Lists.newArrayList(binds)); } return this; } /** * Set the list of binds to the parameter, replacing any existing value. * <p>To append to the list instead, use one of the appendBinds() methods.</p> * * @param binds An array of volume bindings for this container. Each volume binding is a * {@link Bind} object. * @return The builder */ public Builder binds(final Bind... binds) { if (binds == null || binds.length == 0) { return this; } return binds(toStringList(binds)); } private static List<String> toStringList(final Bind[] binds) { final List<String> bindStrings = Lists.newArrayList(); for (final Bind bind : binds) { bindStrings.add(bind.toString()); } return bindStrings; } /** * Append binds to the existing list in this builder. * * @param newBinds An iterable of volume bindings for this container. Each volume binding is a * String. * @return The builder */ public Builder appendBinds(final Iterable<String> newBinds) { final List<String> list = new ArrayList<>(); if (this.binds != null) { list.addAll(this.binds); } list.addAll(Lists.newArrayList(newBinds)); this.binds = copyWithoutDuplicates(list); return this; } /** * Append binds to the existing list in this builder. * * @param binds An array of volume bindings for this container. Each volume binding is a * {@link Bind} object. * @return The builder */ public Builder appendBinds(final Bind... binds) { appendBinds(toStringList(binds)); return this; } /** * Append binds to the existing list in this builder. * * @param binds An array of volume bindings for this container. Each volume binding is a String. * @return The builder */ public Builder appendBinds(final String... binds) { appendBinds(Lists.newArrayList(binds)); return this; } private static <T> ImmutableList<T> copyWithoutDuplicates(final List<T> input) { final List<T> list = new ArrayList<>(input.size()); for (final T element : input) { if (!list.contains(element)) { list.add(element); } } return ImmutableList.copyOf(list); } public List<String> binds() { return binds; } public Builder containerIDFile(final String containerIDFile) { this.containerIDFile = containerIDFile; return this; } public String containerIDFile() { return containerIDFile; } public Builder lxcConf(final List<LxcConfParameter> lxcConf) { if (lxcConf != null && !lxcConf.isEmpty()) { this.lxcConf = ImmutableList.copyOf(lxcConf); } return this; } public Builder lxcConf(final LxcConfParameter... lxcConf) { if (lxcConf != null && lxcConf.length > 0) { this.lxcConf = ImmutableList.copyOf(lxcConf); } return this; } public List<LxcConfParameter> lxcConf() { return lxcConf; } public Builder privileged(final Boolean privileged) { this.privileged = privileged; return this; } public Boolean privileged() { return privileged; } public Builder portBindings(final Map<String, List<PortBinding>> portBindings) { if (portBindings != null && !portBindings.isEmpty()) { this.portBindings = Maps.newHashMap(portBindings); } return this; } public Map<String, List<PortBinding>> portBindings() { return portBindings; } public Builder links(final List<String> links) { if (links != null && !links.isEmpty()) { this.links = ImmutableList.copyOf(links); } return this; } public Builder links(final String... links) { if (links != null && links.length > 0) { this.links = ImmutableList.copyOf(links); } return this; } public List<String> links() { return links; } public Builder publishAllPorts(final Boolean publishAllPorts) { this.publishAllPorts = publishAllPorts; return this; } public Boolean publishAllPorts() { return publishAllPorts; } public Builder dns(final List<String> dns) { if (dns != null && !dns.isEmpty()) { this.dns = ImmutableList.copyOf(dns); } return this; } public Builder dns(final String... dns) { if (dns != null && dns.length > 0) { this.dns = ImmutableList.copyOf(dns); } return this; } public List<String> dns() { return dns; } public Builder dnsSearch(final List<String> dnsSearch) { if (dnsSearch != null && !dnsSearch.isEmpty()) { this.dnsSearch = ImmutableList.copyOf(dnsSearch); } return this; } public Builder dnsSearch(final String... dnsSearch) { if (dnsSearch != null && dnsSearch.length > 0) { this.dnsSearch = ImmutableList.copyOf(dnsSearch); } return this; } public List<String> dnsSearch() { return dnsSearch; } public Builder extraHosts(final List<String> extraHosts) { if (extraHosts != null && !extraHosts.isEmpty()) { this.extraHosts = ImmutableList.copyOf(extraHosts); } return this; } public Builder extraHosts(final String... extraHosts) { if (extraHosts != null && extraHosts.length > 0) { this.extraHosts = ImmutableList.copyOf(extraHosts); } return this; } public List<String> extraHosts() { return extraHosts; } public Builder volumesFrom(final List<String> volumesFrom) { if (volumesFrom != null && !volumesFrom.isEmpty()) { this.volumesFrom = ImmutableList.copyOf(volumesFrom); } return this; } public Builder volumesFrom(final String... volumesFrom) { if (volumesFrom != null && volumesFrom.length > 0) { this.volumesFrom = ImmutableList.copyOf(volumesFrom); } return this; } public List<String> volumesFrom() { return volumesFrom; } public Builder capAdd(final List<String> capAdd) { if (capAdd != null && !capAdd.isEmpty()) { this.capAdd = ImmutableList.copyOf(capAdd); } return this; } public Builder capAdd(final String... capAdd) { if (capAdd != null && capAdd.length > 0) { this.capAdd = ImmutableList.copyOf(capAdd); } return this; } public List<String> capAdd() { return capAdd; } public Builder capDrop(final List<String> capDrop) { if (capDrop != null && !capDrop.isEmpty()) { this.capDrop = ImmutableList.copyOf(capDrop); } return this; } public Builder capDrop(final String... capDrop) { if (capDrop != null && capDrop.length > 0) { this.capDrop = ImmutableList.copyOf(capDrop); } return this; } public List<String> capDrop() { return capDrop; } public Builder networkMode(final String networkMode) { this.networkMode = networkMode; return this; } public String networkMode() { return networkMode; } public Builder securityOpt(final List<String> securityOpt) { if (securityOpt != null && !securityOpt.isEmpty()) { this.securityOpt = ImmutableList.copyOf(securityOpt); } return this; } public Builder securityOpt(final String... securityOpt) { if (securityOpt != null && securityOpt.length > 0) { this.securityOpt = ImmutableList.copyOf(securityOpt); } return this; } public List<String> securityOpt() { return securityOpt; } public Builder devices(final List<Device> devices) { if (devices != null && !devices.isEmpty()) { this.devices = ImmutableList.copyOf(devices); } return this; } public Builder devices(final Device... devices) { if (devices != null && devices.length > 0) { this.devices = ImmutableList.copyOf(devices); } return this; } public List<Device> devices() { return devices; } public Builder memory(final Long memory) { this.memory = memory; return this; } public Long memory() { return memory; } public Builder memorySwap(final Long memorySwap) { this.memorySwap = memorySwap; return this; } public Long memorySwap() { return memorySwap; } public Builder memoryReservation(final Long memoryReservation) { this.memoryReservation = memoryReservation; return this; } public Long memoryReservation() { return memoryReservation; } public Builder cpuShares(final Long cpuShares) { this.cpuShares = cpuShares; return this; } public Long cpuShares() { return cpuShares; } public Builder cpusetCpus(final String cpusetCpus) { this.cpusetCpus = cpusetCpus; return this; } public String cpusetCpus() { return cpusetCpus; } public Builder cpuQuota(final Long cpuQuota) { this.cpuQuota = cpuQuota; return this; } public Long cpuQuota() { return cpuQuota; } public Builder cgroupParent(final String cgroupParent) { this.cgroupParent = cgroupParent; return this; } public String cgroupParent() { return cgroupParent; } public Builder restartPolicy(final RestartPolicy restartPolicy) { this.restartPolicy = restartPolicy; return this; } public Builder logConfig(final LogConfig logConfig) { this.logConfig = logConfig; return this; } public RestartPolicy restartPolicy() { return restartPolicy; } public LogConfig logConfig() { return logConfig; } public Builder ipcMode(final String ipcMode) { this.ipcMode = ipcMode; return this; } public String ipcMode() { return ipcMode; } public Builder ulimits(final List<Ulimit> ulimits) { this.ulimits = ImmutableList.copyOf(ulimits); return this; } /** * Set the PID (Process) Namespace mode for the container. * Use this method to join another container's PID namespace. To use the host * PID namespace, use {@link #hostPidMode()}. * @param container Join the namespace of this container (Name or ID) * @return Builder */ public Builder containerPidMode(final String container) { this.pidMode = "container:" + container; return this; } /** * Set the PID (Process) Namespace mode for the container. * Use this method to use the host's PID namespace. To use another container's * PID namespace, use {@link #containerPidMode(String)}. * @return Builder */ public Builder hostPidMode() { this.pidMode = "host"; return this; } public Builder shmSize(final Long shmSize) { this.shmSize = shmSize; return this; } public Long shmSize() { return shmSize; } public Builder oomKillDisable(final Boolean oomKillDisable) { this.oomKillDisable = oomKillDisable; return this; } public Boolean oomKillDisable() { return oomKillDisable; } public Builder oomScoreAdj(final Integer oomScoreAdj) { this.oomScoreAdj = oomScoreAdj; return this; } public Integer oomScoreAdj() { return oomScoreAdj; } public HostConfig build() { return new HostConfig(this); } } public static class Bind { private String to; private String from; private Boolean readOnly; private Bind(final Builder builder) { this.to = builder.to; this.from = builder.from; this.readOnly = builder.readOnly; } public static BuilderTo to(final String to) { return new BuilderTo(to); } public static BuilderFrom from(final String from) { return new BuilderFrom(from); } public String toString() { if (to == null || to.equals("")) { return ""; } else if (from == null || from.equals("")) { return to; } else if (readOnly == null || !readOnly) { return from + ":" + to; } else { return from + ":" + to + ":ro"; } } public static class BuilderTo { private String to; public BuilderTo(final String to) { this.to = to; } public Builder from(final String from) { return new Builder(this, from); } } public static class BuilderFrom { private String from; public BuilderFrom(final String from) { this.from = from; } public Bind.Builder to(final String to) { return new Builder(this, to); } } public static class Builder { private String to; private String from; private Boolean readOnly = false; private Builder() {} private Builder(final BuilderTo toBuilder, final String from) { this.to = toBuilder.to; this.from = from; } private Builder(final BuilderFrom fromBuilder, final String to) { this.to = to; this.from = fromBuilder.from; } public Builder to(final String to) { this.to = to; return this; } public String to() { return to; } public Builder from(final String from) { this.from = from; return this; } public String from() { return from; } public Builder readOnly(final Boolean readOnly) { this.readOnly = readOnly; return this; } public Boolean readOnly() { return readOnly; } public Bind build() { return new Bind(this); } } } public static class Ulimit { @JsonProperty("Name") private String name; @JsonProperty("Soft") private Integer soft; @JsonProperty("Hard") private Integer hard; public Ulimit() { } private Ulimit(final Builder builder) { this.name = builder.name; this.soft = builder.soft; this.hard = builder.hard; } public static Builder builder() { return new Builder(); } public String name() { return name; } public Integer soft() { return soft; } public Integer hard() { return hard; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Ulimit that = (Ulimit) o; return Objects.equals(this.name, that.name) && Objects.equals(this.soft, that.soft) && Objects.equals(this.hard, that.hard); } @Override public int hashCode() { return Objects.hash(name, soft, hard); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", name) .add("soft", soft) .add("hard", hard) .toString(); } public static class Builder { private String name; private Integer soft; private Integer hard; private Builder() {} public Ulimit build() { return new Ulimit(this); } public Builder name(final String name) { this.name = name; return this; } public Builder soft(final Integer soft) { this.soft = soft; return this; } public Builder hard(final Integer hard) { this.hard = hard; return this; } } } }
src/main/java/com/spotify/docker/client/messages/HostConfig.java
/* * Copyright (c) 2014 Spotify AB. * * 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.spotify.docker.client.messages; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; @JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE, setterVisibility = NONE) public class HostConfig { @JsonProperty("Binds") private ImmutableList<String> binds; @JsonProperty("ContainerIDFile") private String containerIDFile; @JsonProperty("LxcConf") private ImmutableList<LxcConfParameter> lxcConf; @JsonProperty("Privileged") private Boolean privileged; @JsonProperty("PortBindings") private Map<String, List<PortBinding>> portBindings; @JsonProperty("Links") private ImmutableList<String> links; @JsonProperty("PublishAllPorts") private Boolean publishAllPorts; @JsonProperty("Dns") private ImmutableList<String> dns; @JsonProperty("DnsSearch") private ImmutableList<String> dnsSearch; @JsonProperty("ExtraHosts") private ImmutableList<String> extraHosts; @JsonProperty("VolumesFrom") private ImmutableList<String> volumesFrom; @JsonProperty("CapAdd") private ImmutableList<String> capAdd; @JsonProperty("CapDrop") private ImmutableList<String> capDrop; @JsonProperty("NetworkMode") private String networkMode; @JsonProperty("SecurityOpt") private ImmutableList<String> securityOpt; @JsonProperty("Devices") private ImmutableList<Device> devices; @JsonProperty("Memory") private Long memory; @JsonProperty("MemorySwap") private Long memorySwap; @JsonProperty("MemoryReservation") private Long memoryReservation; @JsonProperty("CpuShares") private Long cpuShares; @JsonProperty("CpusetCpus") private String cpusetCpus; @JsonProperty("CpuQuota") private Long cpuQuota; @JsonProperty("CgroupParent") private String cgroupParent; @JsonProperty("RestartPolicy") private RestartPolicy restartPolicy; @JsonProperty("LogConfig") private LogConfig logConfig; @JsonProperty("IpcMode") private String ipcMode; @JsonProperty("Ulimits") private ImmutableList<Ulimit> ulimits; @JsonProperty("PidMode") private String pidMode; @JsonProperty("ShmSize") private Long shmSize; private HostConfig() { } private HostConfig(final Builder builder) { this.binds = builder.binds; this.containerIDFile = builder.containerIDFile; this.lxcConf = builder.lxcConf; this.privileged = builder.privileged; this.portBindings = builder.portBindings; this.links = builder.links; this.publishAllPorts = builder.publishAllPorts; this.dns = builder.dns; this.dnsSearch = builder.dnsSearch; this.extraHosts = builder.extraHosts; this.volumesFrom = builder.volumesFrom; this.capAdd = builder.capAdd; this.capDrop = builder.capDrop; this.networkMode = builder.networkMode; this.securityOpt = builder.securityOpt; this.devices = builder.devices; this.memory = builder.memory; this.memorySwap = builder.memorySwap; this.memoryReservation = builder.memoryReservation; this.cpuShares = builder.cpuShares; this.cpusetCpus = builder.cpusetCpus; this.cpuQuota = builder.cpuQuota; this.cgroupParent = builder.cgroupParent; this.restartPolicy = builder.restartPolicy; this.logConfig = builder.logConfig; this.ipcMode = builder.ipcMode; this.ulimits = builder.ulimits; this.pidMode = builder.pidMode; this.shmSize = builder.shmSize; } public List<String> binds() { return binds; } public String containerIDFile() { return containerIDFile; } public List<LxcConfParameter> lxcConf() { return lxcConf; } public Boolean privileged() { return privileged; } public Map<String, List<PortBinding>> portBindings() { return (portBindings == null) ? null : Collections.unmodifiableMap(portBindings); } public List<String> links() { return links; } public Boolean publishAllPorts() { return publishAllPorts; } public List<String> dns() { return dns; } public List<String> dnsSearch() { return dnsSearch; } public List<String> extraHosts() { return extraHosts; } public List<String> volumesFrom() { return volumesFrom; } public List<String> capAdd() { return capAdd; } public List<String> capDrop() { return capDrop; } public String networkMode() { return networkMode; } public List<String> securityOpt() { return securityOpt; } public List<Device> devices() { return devices; } public Long memory() { return memory; } public Long memorySwap() { return memorySwap; } public Long getMemoryReservation() { return memoryReservation; } public Long cpuShares() { return cpuShares; } public String cpusetCpus() { return cpusetCpus; } public Long cpuQuota() { return cpuQuota; } public String cgroupParent() { return cgroupParent; } public RestartPolicy restartPolicy() { return restartPolicy; } public LogConfig logConfig() { return logConfig; } public String ipcMode() { return ipcMode; } public List<Ulimit> ulimits() { return ulimits; } public Long shmSize() { return shmSize; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final HostConfig that = (HostConfig) o; return Objects.equals(this.binds, that.binds) && Objects.equals(this.containerIDFile, that.containerIDFile) && Objects.equals(this.lxcConf, that.lxcConf) && Objects.equals(this.privileged, that.privileged) && Objects.equals(this.portBindings, that.portBindings) && Objects.equals(this.links, that.links) && Objects.equals(this.publishAllPorts, that.publishAllPorts) && Objects.equals(this.dns, that.dns) && Objects.equals(this.dnsSearch, that.dnsSearch) && Objects.equals(this.extraHosts, that.extraHosts) && Objects.equals(this.volumesFrom, that.volumesFrom) && Objects.equals(this.capAdd, that.capAdd) && Objects.equals(this.capDrop, that.capDrop) && Objects.equals(this.networkMode, that.networkMode) && Objects.equals(this.securityOpt, that.securityOpt) && Objects.equals(this.devices, that.devices) && Objects.equals(this.memory, that.memory) && Objects.equals(this.memorySwap, that.memorySwap) && Objects.equals(this.memoryReservation, that.memoryReservation) && Objects.equals(this.cpuShares, that.cpuShares) && Objects.equals(this.cpusetCpus, that.cpusetCpus) && Objects.equals(this.cpuQuota, that.cpuQuota) && Objects.equals(this.cgroupParent, that.cgroupParent) && Objects.equals(this.restartPolicy, that.restartPolicy) && Objects.equals(this.logConfig, that.logConfig) && Objects.equals(this.ipcMode, that.ipcMode) && Objects.equals(this.ulimits, that.ulimits); } @Override public int hashCode() { return Objects.hash(binds, containerIDFile, lxcConf, privileged, portBindings, links, publishAllPorts, dns, dnsSearch, extraHosts, volumesFrom, capAdd, capDrop, networkMode, securityOpt, devices, memory, memorySwap, memoryReservation, cpuShares, cpusetCpus, cpuQuota, cgroupParent, restartPolicy, logConfig, ipcMode, ulimits, pidMode, shmSize); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("binds", binds) .add("containerIDFile", containerIDFile) .add("lxcConf", lxcConf) .add("privileged", privileged) .add("portBindings", portBindings) .add("links", links) .add("publishAllPorts", publishAllPorts) .add("dns", dns) .add("dnsSearch", dnsSearch) .add("extraHosts", extraHosts) .add("volumesFrom", volumesFrom) .add("capAdd", capAdd) .add("capDrop", capDrop) .add("networkMode", networkMode) .add("securityOpt", securityOpt) .add("devices", devices) .add("memory", memory) .add("memorySwap", memorySwap) .add("memoryReservation", memoryReservation) .add("cpuShares", cpuShares) .add("cpusetCpus", cpusetCpus) .add("cpuQuota", cpuQuota) .add("cgroupParent", cgroupParent) .add("restartPolicy", restartPolicy) .add("logConfig", logConfig) .add("ipcMode", ipcMode) .add("ulimits", ulimits) .add("pidMode", pidMode) .add("shmSize", shmSize) .toString(); } public static class LxcConfParameter { @JsonProperty("Key") private String key; @JsonProperty("Value") private String value; public LxcConfParameter(final String key, final String value) { this.key = key; this.value = value; } public String key() { return key; } public String value() { return value; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final LxcConfParameter that = (LxcConfParameter) o; return Objects.equals(this.key, that.key) && Objects.equals(this.value, that.value); } @Override public int hashCode() { return Objects.hash(key, value); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("key", key) .add("value", value) .toString(); } } public static class RestartPolicy { @JsonProperty("Name") private String name; @JsonProperty("MaximumRetryCount") private Integer maxRetryCount; public static RestartPolicy always() { return new RestartPolicy("always", null); } public static RestartPolicy unlessStopped() { return new RestartPolicy("unless-stopped", null); } public static RestartPolicy onFailure(Integer maxRetryCount) { return new RestartPolicy("on-failure", maxRetryCount); } // for mapper private RestartPolicy() { } private RestartPolicy(String name, Integer maxRetryCount) { this.name = name; this.maxRetryCount = maxRetryCount; } public String name() { return name; } public Integer maxRetryCount() { return maxRetryCount; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final RestartPolicy that = (RestartPolicy) o; return Objects.equals(this.name, that.name) && Objects.equals(this.maxRetryCount, that.maxRetryCount); } @Override public int hashCode() { return Objects.hash(name, maxRetryCount); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", name) .add("maxRetryCount", maxRetryCount) .toString(); } } public Builder toBuilder() { return new Builder(this); } public static Builder builder() { return new Builder(); } public static class Builder { private ImmutableList<String> binds; private String containerIDFile; private ImmutableList<LxcConfParameter> lxcConf; private Boolean privileged; private Map<String, List<PortBinding>> portBindings; private ImmutableList<String> links; private Boolean publishAllPorts; private ImmutableList<String> dns; private ImmutableList<String> dnsSearch; private ImmutableList<String> extraHosts; private ImmutableList<String> volumesFrom; private ImmutableList<String> capAdd; private ImmutableList<String> capDrop; private String networkMode; private ImmutableList<String> securityOpt; private ImmutableList<Device> devices; private Long memory; private Long memorySwap; private Long memoryReservation; private Long cpuShares; private String cpusetCpus; private Long cpuQuota; private String cgroupParent; private RestartPolicy restartPolicy; private LogConfig logConfig; private String ipcMode; private ImmutableList<Ulimit> ulimits; private String pidMode; private Long shmSize; private Builder() { } private Builder(final HostConfig hostConfig) { this.binds = hostConfig.binds; this.containerIDFile = hostConfig.containerIDFile; this.lxcConf = hostConfig.lxcConf; this.privileged = hostConfig.privileged; this.portBindings = hostConfig.portBindings; this.links = hostConfig.links; this.publishAllPorts = hostConfig.publishAllPorts; this.dns = hostConfig.dns; this.dnsSearch = hostConfig.dnsSearch; this.extraHosts = hostConfig.extraHosts; this.volumesFrom = hostConfig.volumesFrom; this.capAdd = hostConfig.capAdd; this.capDrop = hostConfig.capDrop; this.networkMode = hostConfig.networkMode; this.securityOpt = hostConfig.securityOpt; this.devices = hostConfig.devices; this.memory = hostConfig.memory; this.memorySwap = hostConfig.memorySwap; this.memoryReservation = hostConfig.memoryReservation; this.cpuShares = hostConfig.cpuShares; this.cpusetCpus = hostConfig.cpusetCpus; this.cpuQuota = hostConfig.cpuQuota; this.cgroupParent = hostConfig.cgroupParent; this.restartPolicy = hostConfig.restartPolicy; this.logConfig = hostConfig.logConfig; this.ipcMode = hostConfig.ipcMode; this.ulimits = hostConfig.ulimits; this.pidMode = hostConfig.pidMode; this.shmSize = hostConfig.shmSize; } /** * Set the list of binds to the parameter, replacing any existing value. * <p>To append to the list instead, use one of the appendBinds() methods.</p> * * @param binds A list of volume bindings for this container. Each volume binding is a string. * @return The builder */ public Builder binds(final List<String> binds) { if (binds != null && !binds.isEmpty()) { this.binds = copyWithoutDuplicates(binds); } return this; } /** * Set the list of binds to the parameter, replacing any existing value. * <p>To append to the list instead, use one of the appendBinds() methods.</p> * * @param binds An array of volume bindings for this container. Each volume binding is a string. * @return The builder */ public Builder binds(final String... binds) { if (binds != null && binds.length > 0) { return binds(Lists.newArrayList(binds)); } return this; } /** * Set the list of binds to the parameter, replacing any existing value. * <p>To append to the list instead, use one of the appendBinds() methods.</p> * * @param binds An array of volume bindings for this container. Each volume binding is a * {@link Bind} object. * @return The builder */ public Builder binds(final Bind... binds) { if (binds == null || binds.length == 0) { return this; } return binds(toStringList(binds)); } private static List<String> toStringList(final Bind[] binds) { final List<String> bindStrings = Lists.newArrayList(); for (final Bind bind : binds) { bindStrings.add(bind.toString()); } return bindStrings; } /** * Append binds to the existing list in this builder. * * @param newBinds An iterable of volume bindings for this container. Each volume binding is a * String. * @return The builder */ public Builder appendBinds(final Iterable<String> newBinds) { final List<String> list = new ArrayList<>(); if (this.binds != null) { list.addAll(this.binds); } list.addAll(Lists.newArrayList(newBinds)); this.binds = copyWithoutDuplicates(list); return this; } /** * Append binds to the existing list in this builder. * * @param binds An array of volume bindings for this container. Each volume binding is a * {@link Bind} object. * @return The builder */ public Builder appendBinds(final Bind... binds) { appendBinds(toStringList(binds)); return this; } /** * Append binds to the existing list in this builder. * * @param binds An array of volume bindings for this container. Each volume binding is a String. * @return The builder */ public Builder appendBinds(final String... binds) { appendBinds(Lists.newArrayList(binds)); return this; } private static <T> ImmutableList<T> copyWithoutDuplicates(final List<T> input) { final List<T> list = new ArrayList<>(input.size()); for (final T element : input) { if (!list.contains(element)) { list.add(element); } } return ImmutableList.copyOf(list); } public List<String> binds() { return binds; } public Builder containerIDFile(final String containerIDFile) { this.containerIDFile = containerIDFile; return this; } public String containerIDFile() { return containerIDFile; } public Builder lxcConf(final List<LxcConfParameter> lxcConf) { if (lxcConf != null && !lxcConf.isEmpty()) { this.lxcConf = ImmutableList.copyOf(lxcConf); } return this; } public Builder lxcConf(final LxcConfParameter... lxcConf) { if (lxcConf != null && lxcConf.length > 0) { this.lxcConf = ImmutableList.copyOf(lxcConf); } return this; } public List<LxcConfParameter> lxcConf() { return lxcConf; } public Builder privileged(final Boolean privileged) { this.privileged = privileged; return this; } public Boolean privileged() { return privileged; } public Builder portBindings(final Map<String, List<PortBinding>> portBindings) { if (portBindings != null && !portBindings.isEmpty()) { this.portBindings = Maps.newHashMap(portBindings); } return this; } public Map<String, List<PortBinding>> portBindings() { return portBindings; } public Builder links(final List<String> links) { if (links != null && !links.isEmpty()) { this.links = ImmutableList.copyOf(links); } return this; } public Builder links(final String... links) { if (links != null && links.length > 0) { this.links = ImmutableList.copyOf(links); } return this; } public List<String> links() { return links; } public Builder publishAllPorts(final Boolean publishAllPorts) { this.publishAllPorts = publishAllPorts; return this; } public Boolean publishAllPorts() { return publishAllPorts; } public Builder dns(final List<String> dns) { if (dns != null && !dns.isEmpty()) { this.dns = ImmutableList.copyOf(dns); } return this; } public Builder dns(final String... dns) { if (dns != null && dns.length > 0) { this.dns = ImmutableList.copyOf(dns); } return this; } public List<String> dns() { return dns; } public Builder dnsSearch(final List<String> dnsSearch) { if (dnsSearch != null && !dnsSearch.isEmpty()) { this.dnsSearch = ImmutableList.copyOf(dnsSearch); } return this; } public Builder dnsSearch(final String... dnsSearch) { if (dnsSearch != null && dnsSearch.length > 0) { this.dnsSearch = ImmutableList.copyOf(dnsSearch); } return this; } public List<String> dnsSearch() { return dnsSearch; } public Builder extraHosts(final List<String> extraHosts) { if (extraHosts != null && !extraHosts.isEmpty()) { this.extraHosts = ImmutableList.copyOf(extraHosts); } return this; } public Builder extraHosts(final String... extraHosts) { if (extraHosts != null && extraHosts.length > 0) { this.extraHosts = ImmutableList.copyOf(extraHosts); } return this; } public List<String> extraHosts() { return extraHosts; } public Builder volumesFrom(final List<String> volumesFrom) { if (volumesFrom != null && !volumesFrom.isEmpty()) { this.volumesFrom = ImmutableList.copyOf(volumesFrom); } return this; } public Builder volumesFrom(final String... volumesFrom) { if (volumesFrom != null && volumesFrom.length > 0) { this.volumesFrom = ImmutableList.copyOf(volumesFrom); } return this; } public List<String> volumesFrom() { return volumesFrom; } public Builder capAdd(final List<String> capAdd) { if (capAdd != null && !capAdd.isEmpty()) { this.capAdd = ImmutableList.copyOf(capAdd); } return this; } public Builder capAdd(final String... capAdd) { if (capAdd != null && capAdd.length > 0) { this.capAdd = ImmutableList.copyOf(capAdd); } return this; } public List<String> capAdd() { return capAdd; } public Builder capDrop(final List<String> capDrop) { if (capDrop != null && !capDrop.isEmpty()) { this.capDrop = ImmutableList.copyOf(capDrop); } return this; } public Builder capDrop(final String... capDrop) { if (capDrop != null && capDrop.length > 0) { this.capDrop = ImmutableList.copyOf(capDrop); } return this; } public List<String> capDrop() { return capDrop; } public Builder networkMode(final String networkMode) { this.networkMode = networkMode; return this; } public String networkMode() { return networkMode; } public Builder securityOpt(final List<String> securityOpt) { if (securityOpt != null && !securityOpt.isEmpty()) { this.securityOpt = ImmutableList.copyOf(securityOpt); } return this; } public Builder securityOpt(final String... securityOpt) { if (securityOpt != null && securityOpt.length > 0) { this.securityOpt = ImmutableList.copyOf(securityOpt); } return this; } public List<String> securityOpt() { return securityOpt; } public Builder devices(final List<Device> devices) { if (devices != null && !devices.isEmpty()) { this.devices = ImmutableList.copyOf(devices); } return this; } public Builder devices(final Device... devices) { if (devices != null && devices.length > 0) { this.devices = ImmutableList.copyOf(devices); } return this; } public List<Device> devices() { return devices; } public Builder memory(final Long memory) { this.memory = memory; return this; } public Long memory() { return memory; } public Builder memorySwap(final Long memorySwap) { this.memorySwap = memorySwap; return this; } public Long memorySwap() { return memorySwap; } public Builder memoryReservation(final Long memoryReservation) { this.memoryReservation = memoryReservation; return this; } public Long memoryReservation() { return memoryReservation; } public Builder cpuShares(final Long cpuShares) { this.cpuShares = cpuShares; return this; } public Long cpuShares() { return cpuShares; } public Builder cpusetCpus(final String cpusetCpus) { this.cpusetCpus = cpusetCpus; return this; } public String cpusetCpus() { return cpusetCpus; } public Builder cpuQuota(final Long cpuQuota) { this.cpuQuota = cpuQuota; return this; } public Long cpuQuota() { return cpuQuota; } public Builder cgroupParent(final String cgroupParent) { this.cgroupParent = cgroupParent; return this; } public String cgroupParent() { return cgroupParent; } public Builder restartPolicy(final RestartPolicy restartPolicy) { this.restartPolicy = restartPolicy; return this; } public Builder logConfig(final LogConfig logConfig) { this.logConfig = logConfig; return this; } public RestartPolicy restartPolicy() { return restartPolicy; } public LogConfig logConfig() { return logConfig; } public Builder ipcMode(final String ipcMode) { this.ipcMode = ipcMode; return this; } public String ipcMode() { return ipcMode; } public Builder ulimits(final List<Ulimit> ulimits) { this.ulimits = ImmutableList.copyOf(ulimits); return this; } /** * Set the PID (Process) Namespace mode for the container. * Use this method to join another container's PID namespace. To use the host * PID namespace, use {@link #hostPidMode()}. * @param container Join the namespace of this container (Name or ID) * @return Builder */ public Builder containerPidMode(final String container) { this.pidMode = "container:" + container; return this; } /** * Set the PID (Process) Namespace mode for the container. * Use this method to use the host's PID namespace. To use another container's * PID namespace, use {@link #containerPidMode(String)}. * @return Builder */ public Builder hostPidMode() { this.pidMode = "host"; return this; } public Builder shmSize(final Long shmSize) { this.shmSize = shmSize; return this; } public Long shmSize() { return shmSize; } public HostConfig build() { return new HostConfig(this); } } public static class Bind { private String to; private String from; private Boolean readOnly; private Bind(final Builder builder) { this.to = builder.to; this.from = builder.from; this.readOnly = builder.readOnly; } public static BuilderTo to(final String to) { return new BuilderTo(to); } public static BuilderFrom from(final String from) { return new BuilderFrom(from); } public String toString() { if (to == null || to.equals("")) { return ""; } else if (from == null || from.equals("")) { return to; } else if (readOnly == null || !readOnly) { return from + ":" + to; } else { return from + ":" + to + ":ro"; } } public static class BuilderTo { private String to; public BuilderTo(final String to) { this.to = to; } public Builder from(final String from) { return new Builder(this, from); } } public static class BuilderFrom { private String from; public BuilderFrom(final String from) { this.from = from; } public Bind.Builder to(final String to) { return new Builder(this, to); } } public static class Builder { private String to; private String from; private Boolean readOnly = false; private Builder() {} private Builder(final BuilderTo toBuilder, final String from) { this.to = toBuilder.to; this.from = from; } private Builder(final BuilderFrom fromBuilder, final String to) { this.to = to; this.from = fromBuilder.from; } public Builder to(final String to) { this.to = to; return this; } public String to() { return to; } public Builder from(final String from) { this.from = from; return this; } public String from() { return from; } public Builder readOnly(final Boolean readOnly) { this.readOnly = readOnly; return this; } public Boolean readOnly() { return readOnly; } public Bind build() { return new Bind(this); } } } public static class Ulimit { @JsonProperty("Name") private String name; @JsonProperty("Soft") private Integer soft; @JsonProperty("Hard") private Integer hard; public Ulimit() { } private Ulimit(final Builder builder) { this.name = builder.name; this.soft = builder.soft; this.hard = builder.hard; } public static Builder builder() { return new Builder(); } public String name() { return name; } public Integer soft() { return soft; } public Integer hard() { return hard; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Ulimit that = (Ulimit) o; return Objects.equals(this.name, that.name) && Objects.equals(this.soft, that.soft) && Objects.equals(this.hard, that.hard); } @Override public int hashCode() { return Objects.hash(name, soft, hard); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", name) .add("soft", soft) .add("hard", hard) .toString(); } public static class Builder { private String name; private Integer soft; private Integer hard; private Builder() {} public Ulimit build() { return new Ulimit(this); } public Builder name(final String name) { this.name = name; return this; } public Builder soft(final Integer soft) { this.soft = soft; return this; } public Builder hard(final Integer hard) { this.hard = hard; return this; } } } }
Add HostConfig.oomKillDisable and oomScoreAdj
src/main/java/com/spotify/docker/client/messages/HostConfig.java
Add HostConfig.oomKillDisable and oomScoreAdj
<ide><path>rc/main/java/com/spotify/docker/client/messages/HostConfig.java <ide> @JsonProperty("Ulimits") private ImmutableList<Ulimit> ulimits; <ide> @JsonProperty("PidMode") private String pidMode; <ide> @JsonProperty("ShmSize") private Long shmSize; <add> @JsonProperty("OomKillDisable") private Boolean oomKillDisable; <add> @JsonProperty("OomScoreAdj") private Integer oomScoreAdj; <ide> <ide> private HostConfig() { <ide> } <ide> this.ulimits = builder.ulimits; <ide> this.pidMode = builder.pidMode; <ide> this.shmSize = builder.shmSize; <add> this.oomKillDisable = builder.oomKillDisable; <add> this.oomScoreAdj = builder.oomScoreAdj; <ide> } <ide> <ide> public List<String> binds() { <ide> <ide> public Long shmSize() { <ide> return shmSize; <add> } <add> <add> public Boolean oomKillDisable() { <add> return oomKillDisable; <add> } <add> <add> public Integer oomScoreAdj() { <add> return oomScoreAdj; <ide> } <ide> <ide> @Override <ide> Objects.equals(this.restartPolicy, that.restartPolicy) && <ide> Objects.equals(this.logConfig, that.logConfig) && <ide> Objects.equals(this.ipcMode, that.ipcMode) && <del> Objects.equals(this.ulimits, that.ulimits); <add> Objects.equals(this.ulimits, that.ulimits) && <add> Objects.equals(this.oomKillDisable, that.oomKillDisable) && <add> Objects.equals(this.oomScoreAdj, that.oomScoreAdj); <ide> } <ide> <ide> @Override <ide> publishAllPorts, dns, dnsSearch, extraHosts, volumesFrom, capAdd, <ide> capDrop, networkMode, securityOpt, devices, memory, memorySwap, <ide> memoryReservation, cpuShares, cpusetCpus, cpuQuota, cgroupParent, <del> restartPolicy, logConfig, ipcMode, ulimits, pidMode, shmSize); <add> restartPolicy, logConfig, ipcMode, ulimits, pidMode, shmSize, <add> oomKillDisable, oomScoreAdj); <ide> } <ide> <ide> @Override <ide> .add("ulimits", ulimits) <ide> .add("pidMode", pidMode) <ide> .add("shmSize", shmSize) <add> .add("oomKillDisable", oomKillDisable) <add> .add("oomScoreAdj", oomScoreAdj) <ide> .toString(); <ide> } <ide> <ide> private ImmutableList<Ulimit> ulimits; <ide> private String pidMode; <ide> private Long shmSize; <add> private Boolean oomKillDisable; <add> private Integer oomScoreAdj; <ide> <ide> private Builder() { <ide> } <ide> this.ulimits = hostConfig.ulimits; <ide> this.pidMode = hostConfig.pidMode; <ide> this.shmSize = hostConfig.shmSize; <add> this.oomKillDisable = hostConfig.oomKillDisable; <add> this.oomScoreAdj = hostConfig.oomScoreAdj; <ide> } <ide> <ide> /** <ide> return shmSize; <ide> } <ide> <add> public Builder oomKillDisable(final Boolean oomKillDisable) { <add> this.oomKillDisable = oomKillDisable; <add> return this; <add> } <add> <add> public Boolean oomKillDisable() { <add> return oomKillDisable; <add> } <add> <add> public Builder oomScoreAdj(final Integer oomScoreAdj) { <add> this.oomScoreAdj = oomScoreAdj; <add> return this; <add> } <add> <add> public Integer oomScoreAdj() { <add> return oomScoreAdj; <add> } <add> <ide> public HostConfig build() { <ide> return new HostConfig(this); <ide> }
Java
lgpl-2.1
6709f017026705f96661b07e9cbedde898b3a212
0
wesley1001/orbeon-forms,wesley1001/orbeon-forms,brunobuzzi/orbeon-forms,joansmith/orbeon-forms,joansmith/orbeon-forms,orbeon/orbeon-forms,orbeon/orbeon-forms,evlist/orbeon-forms,martinluther/orbeon-forms,tanbo800/orbeon-forms,wesley1001/orbeon-forms,martinluther/orbeon-forms,orbeon/orbeon-forms,ajw625/orbeon-forms,ajw625/orbeon-forms,joansmith/orbeon-forms,tanbo800/orbeon-forms,joansmith/orbeon-forms,evlist/orbeon-forms,martinluther/orbeon-forms,wesley1001/orbeon-forms,tanbo800/orbeon-forms,martinluther/orbeon-forms,brunobuzzi/orbeon-forms,evlist/orbeon-forms,tanbo800/orbeon-forms,brunobuzzi/orbeon-forms,brunobuzzi/orbeon-forms,ajw625/orbeon-forms,orbeon/orbeon-forms,evlist/orbeon-forms,evlist/orbeon-forms,ajw625/orbeon-forms
/** * Copyright (C) 2010 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.processor.pdf; import com.lowagie.text.pdf.BaseFont; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.externalcontext.ServletURLRewriter; import org.orbeon.oxf.externalcontext.URLRewriter; import org.orbeon.oxf.pipeline.api.ExternalContext; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.processor.ProcessorInput; import org.orbeon.oxf.processor.ProcessorInputOutputInfo; import org.orbeon.oxf.processor.serializer.legacy.HttpBinarySerializer; import org.orbeon.oxf.properties.Properties; import org.orbeon.oxf.properties.PropertySet; import org.orbeon.oxf.resources.URLFactory; import org.orbeon.oxf.util.*; import org.w3c.dom.Document; import org.xhtmlrenderer.pdf.ITextRenderer; import org.xhtmlrenderer.pdf.ITextUserAgent; import org.xhtmlrenderer.resource.ImageResource; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; /** * XHTML to PDF converter using the Flying Saucer library. */ public class XHTMLToPDFProcessor extends HttpBinarySerializer {// TODO: HttpBinarySerializer is supposedly deprecated private static final Logger logger = LoggerFactory.createLogger(XHTMLToPDFProcessor.class); public static String DEFAULT_CONTENT_TYPE = "application/pdf"; public XHTMLToPDFProcessor() { addInputInfo(new ProcessorInputOutputInfo(INPUT_DATA)); } protected String getDefaultContentType() { return DEFAULT_CONTENT_TYPE; } protected void readInput(final PipelineContext pipelineContext, final ProcessorInput input, Config config, OutputStream outputStream) { final ExternalContext externalContext = NetUtils.getExternalContext(); // Read the input as a DOM final Document domDocument = readInputAsDOM(pipelineContext, input); // Create renderer and add our own callback final float DEFAULT_DOTS_PER_POINT = 20f * 4f / 3f; final int DEFAULT_DOTS_PER_PIXEL = 14; // Use servlet URL rewriter for resources, even in portlet mode, so that resources are served over HTTP by // the servlet and not looping back through the portal. // NOTE: We could imagine loading resources through a local portlet submission. To do this, we need to properly // abstract the xforms:submission code. final URLRewriter servletRewriter = new ServletURLRewriter(externalContext.getRequest()); final ITextRenderer renderer = new ITextRenderer(DEFAULT_DOTS_PER_POINT, DEFAULT_DOTS_PER_PIXEL); // Embed fonts if needed, based on configuration properties embedFonts(renderer); try { final ITextUserAgent callback = new ITextUserAgent(renderer.getOutputDevice()) { // Called for: // // - CSS URLs // - image URLs // - link clicked / form submission (not relevant for our usage) // - resolveAndOpenStream below public String resolveURI(String uri) { // Our own resolver // All resources we care about here are resource URLs. The PDF pipeline makes sure that the servlet // URL rewriter processes the XHTML output to rewrite resource URLs to absolute paths, including // the servlet context and version number if needed. In addition, CSS resources must either use // relative paths when pointing to other CSS files or images, or go through the XForms CSS rewriter, // which also generates absolute paths. // So all we need to do here is rewrite the resulting path to an absolute URL. // NOTE: We used to call rewriteResourceURL() here as the PDF pipeline did not do URL rewriting. // However this caused issues, for example resources like background images referred by CSS files // could be rewritten twice: once by the XForms resource rewriter, and a second time here. return externalContext.rewriteServiceURL(uri, ExternalContext.Response.REWRITE_MODE_ABSOLUTE | ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_NO_CONTEXT); } // Called by: // // - getCSSResource // - getImageResource below // - getBinaryResource (not sure when called) // - getXMLResource (not sure when called) protected InputStream resolveAndOpenStream(String uri) { try { final String resolvedURI = resolveURI(uri); // TODO: Use xforms:submission code instead // Tell callee we are loading that we are a servlet environment, as in effect we act like // a browser retrieving resources directly, not like a portlet. This is the case also if we are // called by the proxy portlet or if we are directly within a portlet. final Map<String, String[]> headers = new HashMap<String, String[]>(); headers.put("Orbeon-Container", new String[] { "servlet" }); final ConnectionResult connectionResult = new Connection().open(externalContext, new IndentedLogger(logger, ""), false, Connection.Method.GET.name(), URLFactory.createURL(resolvedURI), null, null, null, null, null, headers, Connection.getForwardHeaders()); if (connectionResult.statusCode != 200) { connectionResult.close(); throw new OXFException("Got invalid return code while loading resource: " + uri + ", " + connectionResult.statusCode); } pipelineContext.addContextListener(new PipelineContext.ContextListener() { public void contextDestroyed(boolean success) { connectionResult.close(); } }); return connectionResult.getResponseInputStream(); } catch (IOException e) { throw new OXFException(e); } } public ImageResource getImageResource(String uri) { final InputStream is = resolveAndOpenStream(uri); final String localURI = NetUtils.inputStreamToAnyURI(is, NetUtils.REQUEST_SCOPE); return super.getImageResource(localURI); } }; callback.setSharedContext(renderer.getSharedContext()); renderer.getSharedContext().setUserAgentCallback(callback); // renderer.getSharedContext().setDPI(150); // Set the document to process renderer.setDocument(domDocument, // No base URL if can't get request URL from context externalContext.getRequest() == null ? null : externalContext.getRequest().getRequestURL()); // Do the layout and create the resulting PDF renderer.layout(); final List pages = renderer.getRootBox().getLayer().getPages(); try { // Page count might be zero, and if so createPDF if (pages != null && pages.size() > 0) { renderer.createPDF(outputStream); } else { // TODO: log? } } catch (Exception e) { throw new OXFException(e); } finally { try { outputStream.close(); } catch (IOException e) { // NOP // TODO: log? } } } finally { // Free resources associated with the rendering context renderer.getSharedContext().reset(); } } public static void embedFonts(ITextRenderer renderer) { final PropertySet propertySet = Properties.instance().getPropertySet(); for (final String propertyName : propertySet.getPropertiesStartsWith("oxf.fr.pdf.font.path")) { final String path = StringUtils.trimToNull(propertySet.getString(propertyName)); if (path != null) { try { // Overriding the font family is optional final String family; { final String[] tokens = StringUtils.split(propertyName, '.'); if (tokens.length >= 6) { final String id = tokens[5]; family = StringUtils.trimToNull(propertySet.getString("oxf.fr.pdf.font.family" + '.' + id)); } else { family = null; } } // Add the font renderer.getFontResolver().addFont(path, family, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, null); } catch (Exception e) { logger.warn("Failed to load font by path: '" + path + "' specified with property '" + propertyName + "'"); } } } } }
src/java/org/orbeon/oxf/processor/pdf/XHTMLToPDFProcessor.java
/** * Copyright (C) 2010 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.processor.pdf; import com.lowagie.text.pdf.BaseFont; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.externalcontext.ServletURLRewriter; import org.orbeon.oxf.externalcontext.URLRewriter; import org.orbeon.oxf.pipeline.api.ExternalContext; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.processor.ProcessorInput; import org.orbeon.oxf.processor.ProcessorInputOutputInfo; import org.orbeon.oxf.processor.serializer.legacy.HttpBinarySerializer; import org.orbeon.oxf.properties.Properties; import org.orbeon.oxf.properties.PropertySet; import org.orbeon.oxf.util.*; import org.w3c.dom.Document; import org.xhtmlrenderer.pdf.ITextRenderer; import org.xhtmlrenderer.pdf.ITextUserAgent; import org.xhtmlrenderer.resource.ImageResource; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; /** * XHTML to PDF converter using the Flying Saucer library. */ public class XHTMLToPDFProcessor extends HttpBinarySerializer {// TODO: HttpBinarySerializer is supposedly deprecated private static final Logger logger = LoggerFactory.createLogger(XHTMLToPDFProcessor.class); public static String DEFAULT_CONTENT_TYPE = "application/pdf"; public XHTMLToPDFProcessor() { addInputInfo(new ProcessorInputOutputInfo(INPUT_DATA)); } protected String getDefaultContentType() { return DEFAULT_CONTENT_TYPE; } protected void readInput(final PipelineContext pipelineContext, final ProcessorInput input, Config config, OutputStream outputStream) { final ExternalContext externalContext = NetUtils.getExternalContext(); // Read the input as a DOM final Document domDocument = readInputAsDOM(pipelineContext, input); // Create renderer and add our own callback final float DEFAULT_DOTS_PER_POINT = 20f * 4f / 3f; final int DEFAULT_DOTS_PER_PIXEL = 14; // Use servlet URL rewriter for resources, even in portlet mode, so that resources are served over HTTP by // the servlet and not looping back through the portal. // NOTE: We could imagine loading resources through a local portlet submission. To do this, we need to properly // abstract the xforms:submission code. final URLRewriter servletRewriter = new ServletURLRewriter(externalContext.getRequest()); final ITextRenderer renderer = new ITextRenderer(DEFAULT_DOTS_PER_POINT, DEFAULT_DOTS_PER_PIXEL); // Embed fonts if needed, based on configuration properties embedFonts(renderer); try { final ITextUserAgent callback = new ITextUserAgent(renderer.getOutputDevice()) { // Called for: // // - CSS URLs // - image URLs // - link clicked / form submission (not relevant for our usage) // - resolveAndOpenStream below public String resolveURI(String uri) { // Our own resolver // All resources we care about here are resource URLs. The PDF pipeline makes sure that the servlet // URL rewriter processes the XHTML output to rewrite resource URLs to absolute paths, including // the servlet context and version number if needed. In addition, CSS resources must either use // relative paths when pointing to other CSS files or images, or go through the XForms CSS rewriter, // which also generates absolute paths. // So all we need to do here is rewrite the resulting path to an absolute URL. // NOTE: We used to call rewriteResourceURL() here as the PDF pipeline did not do URL rewriting. // However this caused issues, for example resources like background images referred by CSS files // could be rewritten twice: once by the XForms resource rewriter, and a second time here. return externalContext.rewriteServiceURL(uri, ExternalContext.Response.REWRITE_MODE_ABSOLUTE | ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_NO_CONTEXT); } // Called by: // // - getCSSResource // - getImageResource below // - getBinaryResource (not sure when called) // - getXMLResource (not sure when called) protected InputStream resolveAndOpenStream(String uri) { try { final String resolvedURI = resolveURI(uri); // TODO: Use xforms:submission code instead // Tell callee we are loading that we are a servlet environment, as in effect we act like // a browser retrieving resources directly, not like a portlet. This is the case also if we are // called by the proxy portlet or if we are directly within a portlet. final Map<String, String[]> headers = new HashMap<String, String[]>(); headers.put("Orbeon-Container", new String[] { "servlet" }); final ConnectionResult connectionResult = new Connection().open(externalContext, new IndentedLogger(logger, ""), false, Connection.Method.GET.name(), new URL(resolvedURI), null, null, null, null, null, headers, Connection.getForwardHeaders()); if (connectionResult.statusCode != 200) { connectionResult.close(); throw new OXFException("Got invalid return code while loading resource: " + uri + ", " + connectionResult.statusCode); } pipelineContext.addContextListener(new PipelineContext.ContextListener() { public void contextDestroyed(boolean success) { connectionResult.close(); } }); return connectionResult.getResponseInputStream(); } catch (IOException e) { throw new OXFException(e); } } public ImageResource getImageResource(String uri) { final InputStream is = resolveAndOpenStream(uri); final String localURI = NetUtils.inputStreamToAnyURI(is, NetUtils.REQUEST_SCOPE); return super.getImageResource(localURI); } }; callback.setSharedContext(renderer.getSharedContext()); renderer.getSharedContext().setUserAgentCallback(callback); // renderer.getSharedContext().setDPI(150); // Set the document to process renderer.setDocument(domDocument, // No base URL if can't get request URL from context externalContext.getRequest() == null ? null : externalContext.getRequest().getRequestURL()); // Do the layout and create the resulting PDF renderer.layout(); final List pages = renderer.getRootBox().getLayer().getPages(); try { // Page count might be zero, and if so createPDF if (pages != null && pages.size() > 0) { renderer.createPDF(outputStream); } else { // TODO: log? } } catch (Exception e) { throw new OXFException(e); } finally { try { outputStream.close(); } catch (IOException e) { // NOP // TODO: log? } } } finally { // Free resources associated with the rendering context renderer.getSharedContext().reset(); } } public static void embedFonts(ITextRenderer renderer) { final PropertySet propertySet = Properties.instance().getPropertySet(); for (final String propertyName : propertySet.getPropertiesStartsWith("oxf.fr.pdf.font.path")) { final String path = StringUtils.trimToNull(propertySet.getString(propertyName)); if (path != null) { try { // Overriding the font family is optional final String family; { final String[] tokens = StringUtils.split(propertyName, '.'); if (tokens.length >= 6) { final String id = tokens[5]; family = StringUtils.trimToNull(propertySet.getString("oxf.fr.pdf.font.family" + '.' + id)); } else { family = null; } } // Add the font renderer.getFontResolver().addFont(path, family, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, null); } catch (Exception e) { logger.warn("Failed to load font by path: '" + path + "' specified with property '" + propertyName + "'"); } } } } }
Fix #118 "PDF: SSL support doesn't work"
src/java/org/orbeon/oxf/processor/pdf/XHTMLToPDFProcessor.java
Fix #118 "PDF: SSL support doesn't work"
<ide><path>rc/java/org/orbeon/oxf/processor/pdf/XHTMLToPDFProcessor.java <ide> import org.orbeon.oxf.processor.serializer.legacy.HttpBinarySerializer; <ide> import org.orbeon.oxf.properties.Properties; <ide> import org.orbeon.oxf.properties.PropertySet; <add>import org.orbeon.oxf.resources.URLFactory; <ide> import org.orbeon.oxf.util.*; <ide> import org.w3c.dom.Document; <ide> import org.xhtmlrenderer.pdf.ITextRenderer; <ide> <ide> final ConnectionResult connectionResult <ide> = new Connection().open(externalContext, new IndentedLogger(logger, ""), false, Connection.Method.GET.name(), <del> new URL(resolvedURI), null, null, null, null, null, headers, Connection.getForwardHeaders()); <add> URLFactory.createURL(resolvedURI), null, null, null, null, null, headers, Connection.getForwardHeaders()); <ide> <ide> if (connectionResult.statusCode != 200) { <ide> connectionResult.close();
Java
apache-2.0
e1d10433aff4d63c197b6ce617ed56d89a15bc2a
0
apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj
/* * 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.uima.cas.impl; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URL; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.Spliterator; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Predicate; import org.apache.uima.UIMAFramework; import org.apache.uima.UIMARuntimeException; import org.apache.uima.UimaSerializable; import org.apache.uima.cas.AbstractCas_ImplBase; import org.apache.uima.cas.ArrayFS; import org.apache.uima.cas.BooleanArrayFS; import org.apache.uima.cas.ByteArrayFS; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.cas.CASRuntimeException; import org.apache.uima.cas.CasOwner; import org.apache.uima.cas.CommonArrayFS; import org.apache.uima.cas.ComponentInfo; import org.apache.uima.cas.ConstraintFactory; import org.apache.uima.cas.DoubleArrayFS; import org.apache.uima.cas.FSIndex; import org.apache.uima.cas.FSIndexRepository; import org.apache.uima.cas.FSIterator; import org.apache.uima.cas.FSMatchConstraint; import org.apache.uima.cas.Feature; import org.apache.uima.cas.FeaturePath; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.FeatureValuePath; import org.apache.uima.cas.FloatArrayFS; import org.apache.uima.cas.IntArrayFS; import org.apache.uima.cas.LongArrayFS; import org.apache.uima.cas.Marker; import org.apache.uima.cas.SerialFormat; import org.apache.uima.cas.ShortArrayFS; import org.apache.uima.cas.SofaFS; import org.apache.uima.cas.SofaID; import org.apache.uima.cas.StringArrayFS; import org.apache.uima.cas.Type; import org.apache.uima.cas.TypeSystem; import org.apache.uima.cas.admin.CASAdminException; import org.apache.uima.cas.admin.CASFactory; import org.apache.uima.cas.admin.CASMgr; import org.apache.uima.cas.admin.FSIndexComparator; import org.apache.uima.cas.admin.FSIndexRepositoryMgr; import org.apache.uima.cas.admin.TypeSystemMgr; import org.apache.uima.cas.impl.FSsTobeAddedback.FSsTobeAddedbackSingle; import org.apache.uima.cas.impl.SlotKinds.SlotKind; import org.apache.uima.cas.text.AnnotationFS; import org.apache.uima.cas.text.AnnotationIndex; import org.apache.uima.cas.text.Language; import org.apache.uima.internal.util.IntVector; import org.apache.uima.internal.util.Misc; import org.apache.uima.internal.util.PositiveIntSet; import org.apache.uima.internal.util.PositiveIntSet_impl; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.cas.AnnotationBase; import org.apache.uima.jcas.cas.BooleanArray; import org.apache.uima.jcas.cas.ByteArray; import org.apache.uima.jcas.cas.DoubleArray; import org.apache.uima.jcas.cas.EmptyFSList; import org.apache.uima.jcas.cas.EmptyFloatList; import org.apache.uima.jcas.cas.EmptyIntegerList; import org.apache.uima.jcas.cas.EmptyList; import org.apache.uima.jcas.cas.EmptyStringList; import org.apache.uima.jcas.cas.FSArray; import org.apache.uima.jcas.cas.FloatArray; import org.apache.uima.jcas.cas.IntegerArray; import org.apache.uima.jcas.cas.LongArray; import org.apache.uima.jcas.cas.ShortArray; import org.apache.uima.jcas.cas.Sofa; import org.apache.uima.jcas.cas.StringArray; import org.apache.uima.jcas.cas.TOP; import org.apache.uima.jcas.impl.JCasHashMap; import org.apache.uima.jcas.impl.JCasImpl; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.util.AutoCloseableNoException; import org.apache.uima.util.Level; /** * Implements the CAS interfaces. This class must be public because we need to * be able to create instance of it from outside the package. Use at your own * risk. May change without notice. * */ public class CASImpl extends AbstractCas_ImplBase implements CAS, CASMgr, LowLevelCAS, TypeSystemConstants { private static final String TRACE_FSS = "uima.trace_fs_creation_and_updating"; public static final boolean IS_USE_V2_IDS = false; // if false, ids increment by 1 private static final boolean trace = false; // debug public static final boolean traceFSs = // false; // debug - trace FS creation and update Misc.getNoValueSystemProperty(TRACE_FSS); public static final boolean traceCow = false; // debug - trace copy on write actions, index adds / deletes private static final String traceFile = "traceFSs.log.txt"; private static final PrintStream traceOut; static { try { if (traceFSs) { System.out.println("Creating traceFSs file in directory " + System.getProperty("user.dir")); traceOut = traceFSs ? new PrintStream(new BufferedOutputStream(new FileOutputStream(traceFile, false))) : null; } else { traceOut = null; } } catch (Exception e) { throw new RuntimeException(e); } } private static final boolean MEASURE_SETINT = false; // debug static final AtomicInteger casIdProvider = new AtomicInteger(0); // Notes on the implementation // --------------------------- // Floats are handled by casting them to ints when they are stored // in the heap. Conveniently, 0 casts to 0.0f, which is the default // value. public static final int NULL = 0; // Boolean scalar values are stored as ints in the fs heap. // TRUE is 1 and false is 0. public static final int TRUE = 1; public static final int FALSE = 0; public static final int DEFAULT_INITIAL_HEAP_SIZE = 500_000; public static final int DEFAULT_RESET_HEAP_SIZE = 5_000_000; /** * The UIMA framework detects (unless disabled, for high performance) updates to indexed FS which update * key values used as keys in indexes. Normally the framework will protect against index corruption by * temporarily removing the FS from the indexes, then do the update to the feature value, and then addback * the changed FS. * <p> * Users can use the protectIndexes() methods to explicitly control this remove - add back cycle, for instance * to "batch" together several updates to multiple features in a FS. * <p> * Some build processes may want to FAIL if any unprotected updates of this kind occur, instead of having the * framework silently recover them. This is enabled by having the framework throw an exception; this is controlled * by this global JVM property, which, if defined, causes the framework to throw an exception rather than recover. * */ public static final String THROW_EXCEPTION_FS_UPDATES_CORRUPTS = "uima.exception_when_fs_update_corrupts_index"; // public for test case use public static boolean IS_THROW_EXCEPTION_CORRUPT_INDEX = Misc.getNoValueSystemProperty(THROW_EXCEPTION_FS_UPDATES_CORRUPTS); /** * Define this JVM property to enable checking for invalid updates to features which are used as * keys by any index. * <ul> * <li>The following are the same: -Duima.check_invalid_fs_updates and -Duima.check_invalid_fs_updates=true</li> * </ul> */ public static final String REPORT_FS_UPDATES_CORRUPTS = "uima.report_fs_update_corrupts_index"; private static final boolean IS_REPORT_FS_UPDATE_CORRUPTS_INDEX = IS_THROW_EXCEPTION_CORRUPT_INDEX || Misc.getNoValueSystemProperty(REPORT_FS_UPDATES_CORRUPTS); /** * Set this JVM property to false for high performance, (no checking); * insure you don't have the report flag (above) turned on - otherwise it will force this to "true". */ public static final String DISABLE_PROTECT_INDEXES = "uima.disable_auto_protect_indexes"; /** * the protect indexes flag is on by default, but may be turned of via setting the property. * * This is overridden if a report is requested or the exception detection is on. */ private static final boolean IS_DISABLED_PROTECT_INDEXES = Misc.getNoValueSystemProperty(DISABLE_PROTECT_INDEXES) && !IS_REPORT_FS_UPDATE_CORRUPTS_INDEX && !IS_THROW_EXCEPTION_CORRUPT_INDEX; public static final String ALWAYS_HOLD_ONTO_FSS = "uima.enable_id_to_feature_structure_map_for_all_fss"; static final boolean IS_ALWAYS_HOLD_ONTO_FSS = // debug Misc.getNoValueSystemProperty(ALWAYS_HOLD_ONTO_FSS); // private static final int REF_DATA_FOR_ALLOC_SIZE = 1024; // private static final int INT_DATA_FOR_ALLOC_SIZE = 1024; // // this next seemingly non-sensical static block // is to force the classes needed by Eclipse debugging to load // otherwise, you get a com.sun.jdi.ClassNotLoadedException when // the class is used as part of formatting debugging messages static { new DebugNameValuePair(null, null); new DebugFSLogicalStructure(); } // Static classes representing shared instance data // - shared data is computed once for all views /** * Journaling changes for computing delta cas. * Each instance represents one or more changes for one feature structure * A particular Feature Structure may have multiple FsChange instances * but we attempt to minimize this */ public static class FsChange { /** ref to the FS being modified */ final TOP fs; /** * which feature (by offset) is modified */ final BitSet featuresModified; final PositiveIntSet arrayUpdates; FsChange(TOP fs) { this.fs = fs; TypeImpl ti = fs._getTypeImpl(); featuresModified = (ti.highestOffset == -1) ? null : new BitSet(ti.highestOffset + 1); arrayUpdates = (ti.isArray()) ? new PositiveIntSet_impl() : null; } void addFeatData(int v) { featuresModified.set(v); } void addArrayData(int v, int nbrOfConsecutive) { for (int i = 0; i < nbrOfConsecutive; i++) { arrayUpdates.add(v++); } } void addArrayData(PositiveIntSet indexesPlus1) { indexesPlus1.forAllInts(i -> arrayUpdates.add(i - 1)); } @Override public int hashCode() { return 31 + ((fs == null) ? 0 : fs._id); } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof FsChange)) return false; return ((FsChange)obj).fs._id == fs._id; } } // fields shared among all CASes belong to views of a common base CAS static class SharedViewData { /** * map from FS ids to FSs. */ final private Id2FS id2fs; /** set to > 0 to reuse an id, 0 otherwise */ private int reuseId = 0; // Base CAS for all views final private CASImpl baseCAS; /** * These fields are here, not in TypeSystemImpl, because different CASes may have different indexes but share the same type system * They hold the same data (constant per CAS) but are accessed with different indexes */ private final BitSet featureCodesInIndexKeys = new BitSet(1024); // 128 bytes // private final BitSet featureJiInIndexKeys = new BitSet(1024); // indexed by JCas Feature Index, not feature code. // A map from SofaNumbers which are also view numbers to IndexRepositories. // these numbers are dense, and start with 1. 1 is the initial view. 0 is the base cas ArrayList<FSIndexRepositoryImpl> sofa2indexMap; /** * A map from Sofa numbers to CAS views. * number 0 - not used * number 1 - used for view named "_InitialView" * number 2-n used for other views * * Note: this is not reset with "Cas Reset" because views (really, their associated index repos) * take a lot of setup for the indexes. * However, the maximum view count is reset; so creation of new views "reuses" these pre-setup indexRepos * associated with these views. */ ArrayList<CASImpl> sofaNbr2ViewMap; /** * a set of instantiated sofaNames */ private Set<String> sofaNameSet; // Flag that initial Sofa has been created private boolean initialSofaCreated = false; // Count of Views created in this cas // equals count of sofas except if initial view has no sofa. int viewCount; // The ClassLoader that should be used by the JCas to load the generated // FS cover classes for this CAS. Defaults to the ClassLoader used // to load the CASImpl class. private ClassLoader jcasClassLoader = this.getClass().getClassLoader(); /***************************** * PEAR Support *****************************/ /** * Only support one level of PEAR nesting; for more general approach, make this a deque */ private ClassLoader previousJCasClassLoader = null; /** * Save area for suspending this while we create a base instance */ private ClassLoader suspendPreviousJCasClassLoader; /** * A map from IDs to already created trampoline FSs for the base FS with that id. * These are used when in a Pear and retrieving a FS (via index or deref) and you want the * Pear version for that ID. * There are potentially multiple maps - one per PEAR Classpath */ private JCasHashMap id2tramp = null; /** * a map from IDs of FSs that have a Pear version, to the base (non-Pear) version * used to locate the base version for adding to indexes */ private JCasHashMap id2base = null; private final Map<ClassLoader, JCasHashMap> cl2id2tramp = new IdentityHashMap<>(); /** * The current (active, switches at Pear boundaries) FsGenerators (excluding array-generators) * key = type code * read-only, unsynchronized for this CAS * Cache for setting this kept in TypeSystemImpl, by classloader * - shared among all CASs that use that Type System and class loader * -- in turn, initialized from FSClassRegistry, once per classloader / typesystem combo * * Pear generators are mostly null except for instances where the PEAR has redefined * the JCas cover class */ private FsGenerator3[] generators; /** * When generating a new instance of a FS in a PEAR where there's an alternate JCas class impl, * generate the base version, and make the alternate a trampoline to it. * Note: in future, if it is known that this FS is never used outside of this PEAR, then can * skip generating the double version */ private FsGenerator3[] baseGenerators; // If this CAS can be flushed (reset) or not. // often, the framework disables this before calling users code private boolean flushEnabled = true; // not final because set with reinit deserialization private TypeSystemImpl tsi; private ComponentInfo componentInfo; /** * This tracks the changes for delta cas * May also in the future support Journaling by component, * allowing determination of which component in a flow * created/updated a FeatureStructure (not implmented) * * TrackingMarkers are held on to by things outside of the * Cas, to support switching from one tracking marker to * another (currently not used, but designed to support * Component Journaling). * * We track changes on a granularity of features * and for features which are arrays, which element of the array * (This last to enable efficient delta serializations of * giant arrays of things, where you've only updated a few items) * * The FsChange doesn't store the changed data, only stores the * ref info needed to get to what was changed. */ private MarkerImpl trackingMark; /** * Track modified preexistingFSs * Note this is a map, keyed by the FS, so all changes are merged when added */ private Map<TOP, FsChange> modifiedPreexistingFSs; /** * This list currently only contains at most 1 element. * If Journaling is implemented, it may contain an * element per component being journaled. */ private List<MarkerImpl> trackingMarkList; /** * This stack corresponds to nested protectIndexes contexts. Normally should be very shallow. */ private final ArrayList<FSsTobeAddedback> fssTobeAddedback = new ArrayList<FSsTobeAddedback>(); /** * This version is for single fs use, by binary deserializers and by automatic mode * Only one user at a time is allowed. */ private final FSsTobeAddedbackSingle fsTobeAddedbackSingle = (FSsTobeAddedbackSingle) FSsTobeAddedback.createSingle(); /** * Set to true while this is in use. */ boolean fsTobeAddedbackSingleInUse = false; /** * temporarily set to true by deserialization routines doing their own management of this check */ boolean disableAutoCorruptionCheck = false; // used to generate FSIDs, increments by 1 for each use. First id == 1 /** * The fsId of the last created FS * used to generate FSIDs, increments by 1 for each use. First id == 1 */ private int fsIdGenerator = 0; /** * The version 2 size on the main heap of the last created FS */ private int lastFsV2Size = 1; /** * used to "capture" the fsIdGenerator value for a read-only CAS to be visible in * other threads */ AtomicInteger fsIdLastValue = new AtomicInteger(0); // mostly for debug - counts # times cas is reset private final AtomicInteger casResets = new AtomicInteger(0); // unique ID for a created CAS view, not updated if CAS is reset and reused private final int casId = casIdProvider.incrementAndGet(); // shared singltons, created at type system commit private EmptyFSList emptyFSList; private EmptyFloatList emptyFloatList; private EmptyIntegerList emptyIntegerList; private EmptyStringList emptyStringList; private FloatArray emptyFloatArray; private FSArray emptyFSArray; private IntegerArray emptyIntegerArray; private StringArray emptyStringArray; private DoubleArray emptyDoubleArray; private LongArray emptyLongArray; private ShortArray emptyShortArray; private ByteArray emptyByteArray; private BooleanArray emptyBooleanArray; /** * Created at startup time, lives as long as the CAS lives * Serves to reference code for binary cas ser/des that used to live * in this class, but was moved out */ private final BinaryCasSerDes bcsd; /** * Created when doing binary or form4 non-delta (de)serialization, used in subsequent delta ser/deserialization * Created when doing binary or form4 non-delta ser/deserialization, used in subsequent delta (de)serialization * Reset with CasReset or deltaMergesComplete API call */ private CommonSerDesSequential csds; /************************************************* * VERSION 2 LOW_LEVEL_API COMPATIBILITY SUPPORT * *************************************************/ /** * A StringSet used only to support ll_get/setInt api * get adds string to this and returns the int handle * set retrieves the string, given the handle * lazy initialized */ private StringSet llstringSet = null; /** * A LongSet used only to support v2 ll_get/setInt api * get adds long to this and returns the int handle * set retrieves the long, given the handle * lazy initialized */ private LongSet lllongSet = null; // For tracing FS creation and updating, normally disabled private final StringBuilder traceFScreationSb = traceFSs ? new StringBuilder() : null; private final StringBuilder traceCowSb = traceCow ? new StringBuilder() : null; private int traceFSid = 0; private boolean traceFSisCreate; private final IntVector id2addr = traceFSs ? new IntVector() : null; private int nextId2Addr = 1; // only for tracing, to convert id's to v2 addresses final private int initialHeapSize; private SharedViewData(CASImpl baseCAS, int initialHeapSize, TypeSystemImpl tsi) { this.baseCAS = baseCAS; this.tsi = tsi; this.initialHeapSize = initialHeapSize; bcsd = new BinaryCasSerDes(baseCAS); id2fs = new Id2FS(initialHeapSize); if (traceFSs) id2addr.add(0); } void clearCasReset() { // fss fsIdGenerator = 0; id2fs.clear(); // pear caches id2tramp = null; id2base = null; for (JCasHashMap m : cl2id2tramp.values()) { m.clear(); } // index corruption avoidance fssTobeAddedback.clear(); fsTobeAddedbackSingle.clear(); fsTobeAddedbackSingleInUse = false; disableAutoCorruptionCheck = false; // misc flushEnabled = true; componentInfo = null; bcsd.clear(); csds = null; llstringSet = null; traceFSid = 0; if (traceFSs) { traceFScreationSb.setLength(0); id2addr.removeAllElements(); id2addr.add(0); nextId2Addr = 1; } emptyFloatList = null; // these cleared in case new ts redefines? emptyFSList = null; emptyIntegerList = null; emptyStringList = null; emptyFloatArray = null; emptyFSArray = null; emptyIntegerArray = null; emptyStringArray = null; emptyDoubleArray = null; emptyLongArray = null; emptyShortArray = null; emptyByteArray = null; emptyBooleanArray = null; clearNonSharedInstanceData(); } /** * called by resetNoQuestions and cas complete reinit */ void clearSofaInfo() { sofaNameSet.clear(); initialSofaCreated = false; } /** * Called from CasComplete deserialization (reinit). * * Skips the resetNoQuestions operation of flushing the indexes, * since these will be reinitialized with potentially new definitions. * * Clears additional data related to having the * - type system potentially change * - the features belonging to indexes change * */ void clear() { resetNoQuestions(false); // false - skip flushing the index repos // type system + index spec tsi = null; featureCodesInIndexKeys.clear(); // featureJiInIndexKeys.clear(); /** * Clear the existing views, except keep the info for the initial view * so that the cas complete deserialization after setting up the new index repository in the base cas * can "refresh" the existing initial view (if present; if not present, a new one is created). */ if (sofaNbr2ViewMap.size() >= 1) { // have initial view - preserve it CASImpl localInitialView = sofaNbr2ViewMap.get(1); sofaNbr2ViewMap.clear(); Misc.setWithExpand(sofaNbr2ViewMap, 1, localInitialView); viewCount = 1; } else { sofaNbr2ViewMap.clear(); viewCount = 0; } } private void resetNoQuestions(boolean flushIndexRepos) { casResets.incrementAndGet(); if (trace) { System.out.println("CAS Reset in thread " + Thread.currentThread().getName() + " for CasId = " + casId + ", new reset count = " + casResets.get()); } clearCasReset(); // also clears cached FSs if (flushIndexRepos) { flushIndexRepositoriesAllViews(); } clearTrackingMarks(); clearSofaInfo(); // but keep initial view, and other views // because setting up the index infrastructure is expensive viewCount = 1; // initial view traceFSid = 0; if (traceFSs) traceFScreationSb.setLength(0); componentInfo = null; // https://issues.apache.org/jira/browse/UIMA-5097 } private void flushIndexRepositoriesAllViews() { int numViews = viewCount; for (int view = 1; view <= numViews; view++) { CASImpl tcas = (CASImpl) ((view == 1) ? getInitialView() : getViewFromSofaNbr(view)); if (tcas != null) { tcas.indexRepository.flush(); } } // safety : in case this public method is called on other than the base cas baseCAS.indexRepository.flush(); // for base view, other views flushed above } private void clearNonSharedInstanceData() { int numViews = viewCount; for (int view = 1; view <= numViews; view++) { CASImpl tcas = (CASImpl) ((view == 1) ? getInitialView() : getViewFromSofaNbr(view)); if (tcas != null) { tcas.mySofaRef = null; // was in v2: (1 == view) ? -1 : 0; tcas.docAnnotIter = null; } } } private void clearTrackingMarks() { // resets all markers that might be held by things outside the Cas // Currently (2009) this list has a max of 1 element // Future impl may have one element per component for component Journaling if (trackingMarkList != null) { for (int i=0; i < trackingMarkList.size(); i++) { trackingMarkList.get(i).isValid = false; } } trackingMark = null; if (null != modifiedPreexistingFSs) { modifiedPreexistingFSs.clear(); } trackingMarkList = null; } void switchClassLoader(ClassLoader newClassLoader) { if (null == newClassLoader) { // is null if no cl set return; } if (newClassLoader != jcasClassLoader) { if (null != previousJCasClassLoader) { /** Multiply nested classloaders not supported. Original base loader: {0}, current nested loader: {1}, trying to switch to loader: {2}.*/ throw new CASRuntimeException(CASRuntimeException.SWITCH_CLASS_LOADER_NESTED, previousJCasClassLoader, jcasClassLoader, newClassLoader); } // System.out.println("Switching to new class loader"); previousJCasClassLoader = jcasClassLoader; jcasClassLoader = newClassLoader; generators = tsi.getGeneratorsForClassLoader(newClassLoader, true); // true - isPear assert null == id2tramp; // is null outside of a pear id2tramp = cl2id2tramp.get(newClassLoader); if (null == id2tramp) { cl2id2tramp.put(newClassLoader, id2tramp = new JCasHashMap(32)); } if (id2base == null) { id2base = new JCasHashMap(32); } } } void restoreClassLoader() { if (null == previousJCasClassLoader) { return; } // System.out.println("Switching back to previous class loader"); jcasClassLoader = previousJCasClassLoader; previousJCasClassLoader = null; generators = baseGenerators; id2tramp = null; } private int getNextFsId(TOP fs) { if (reuseId != 0) { // l.setStrongRef(fs, reuseId); return reuseId; } // l.add(fs); // if (id2fs.size() != (2 + fsIdGenerator.get())) { // System.out.println("debug out of sync id generator and id2fs size"); // } // assert(l.size() == (2 + fsIdGenerator)); final int p = fsIdGenerator; final int r = fsIdGenerator += IS_USE_V2_IDS ? lastFsV2Size : 1; if (r < p) { throw new RuntimeException("UIMA Cas Internal id value overflowed maximum int value"); } if (IS_USE_V2_IDS) { // this computation is partial - misses length of arrays stored on heap // because that info not yet available lastFsV2Size = fs._getTypeImpl().getFsSpaceReq(); } return r; } private CASImpl getViewFromSofaNbr(int nbr) { final ArrayList<CASImpl> sn2v = sofaNbr2ViewMap; if (nbr < sn2v.size()) { return sn2v.get(nbr); } return null; } // For internal platform use only CASImpl getInitialView() { CASImpl couldBeThis = getViewFromSofaNbr(1); if (couldBeThis != null) { return couldBeThis; } // create the initial view, without a Sofa CASImpl aView = new CASImpl(baseCAS, (SofaFS) null); setViewForSofaNbr(1, aView); assert (viewCount <= 1); viewCount = 1; return aView; } void setViewForSofaNbr(int nbr, CASImpl view) { Misc.setWithExpand(sofaNbr2ViewMap, nbr, view); } } /***************************************************************** * Non-shared instance data kept per CAS view incl base CAS *****************************************************************/ // package protected to let other things share this info final SharedViewData svd; // shared view data /** The index repository. Referenced by XmiCasSerializer */ FSIndexRepositoryImpl indexRepository; // private Object[] currentRefDataForAlloc = new Object[REF_DATA_FOR_ALLOC_SIZE]; // private Object[] returnRefDataForAlloc; // private int[] currentIntDataForAlloc = new int[INT_DATA_FOR_ALLOC_SIZE]; // private int[] returnIntDataForAlloc; // private int nextRefDataOffsetForAlloc = 0; // private int nextIntDataOffsetForAlloc = 0; /** * The Feature Structure for the sofa FS for this view, or * null * //-1 if the sofa FS is for the initial view, or * // 0 if there is no sofa FS - for instance, in the "base cas" */ private Sofa mySofaRef = null; /** the corresponding JCas object */ JCasImpl jcas = null; /** * Copies of frequently accessed data pulled up for * locality of reference - only an optimization * - each value needs to be reset appropriately * - getters check for null, and if null, do the get. */ private TypeSystemImpl tsi_local; /** * for Pear generation - set this to the base FS * not in SharedViewData to reduce object traversal when * generating FSs */ FeatureStructureImplC pearBaseFs = null; /** * Optimization - keep a documentAnnotationIterator handy for getting a ref to the doc annot * Initialized lazily, synchronized * One per cas view */ private volatile FSIterator<Annotation> docAnnotIter = null; // private StackTraceElement[] addbackSingleTrace = null; // for debug use only, normally commented out // CASImpl(TypeSystemImpl typeSystem) { // this(typeSystem, DEFAULT_INITIAL_HEAP_SIZE); // } // // Reference existing CAS // // For use when creating views of the CAS // CASImpl(CAS cas) { // this.setCAS(cas); // this.useFSCache = false; // initTypeVariables(); // } /* * Configure a new (base view) CASImpl, **not a new view** typeSystem can be * null, in which case a new instance of TypeSystemImpl is set up, but not * committed. If typeSystem is not null, it is committed (locked). ** Note: it * is assumed that the caller of this will always set up the initial view ** * by calling */ public CASImpl(TypeSystemImpl typeSystem, int initialHeapSize ) { super(); TypeSystemImpl ts; final boolean externalTypeSystem = (typeSystem != null); if (externalTypeSystem) { ts = typeSystem; } else { ts = (TypeSystemImpl) CASFactory.createTypeSystem(); // creates also new CASMetadata and // FSClassRegistry instances } this.svd = new SharedViewData(this, initialHeapSize, ts); // this.svd.baseCAS = this; // this.svd.heap = new Heap(initialHeapSize); if (externalTypeSystem) { commitTypeSystem(); } this.svd.sofa2indexMap = new ArrayList<>(); this.svd.sofaNbr2ViewMap = new ArrayList<>(); this.svd.sofaNameSet = new HashSet<String>(); this.svd.initialSofaCreated = false; this.svd.viewCount = 0; this.svd.clearTrackingMarks(); } public CASImpl() { this((TypeSystemImpl) null, DEFAULT_INITIAL_HEAP_SIZE); } // In May 2007, appears to have 1 caller, createCASMgr in Serialization class, // could have out-side the framework callers because it is public. public CASImpl(CASMgrSerializer ser) { this(ser.getTypeSystem(), DEFAULT_INITIAL_HEAP_SIZE); checkInternalCodes(ser); // assert(ts != null); // assert(getTypeSystem() != null); this.indexRepository = ser.getIndexRepository(this); } // Use this when creating a CAS view CASImpl(CASImpl cas, SofaFS aSofa) { // these next fields are final and must be set in the constructor this.svd = cas.svd; this.mySofaRef = (Sofa) aSofa; // get the indexRepository for this Sofa this.indexRepository = (this.mySofaRef == null) ? (FSIndexRepositoryImpl) cas.getSofaIndexRepository(1) : (FSIndexRepositoryImpl) cas.getSofaIndexRepository(aSofa); if (null == this.indexRepository) { // create the indexRepository for this CAS // use the baseIR to create a lightweight IR copy FSIndexRepositoryImpl baseIndexRepo = (FSIndexRepositoryImpl) cas.getBaseIndexRepository(); this.indexRepository = new FSIndexRepositoryImpl(this, baseIndexRepo); // the index creation depends on "indexRepository" already being set baseIndexRepo.name2indexMap.keySet().stream().forEach(key -> this.indexRepository.createIndex(baseIndexRepo, key)); this.indexRepository.commit(); // save new sofa index if (this.mySofaRef == null) { cas.setSofaIndexRepository(1, this.indexRepository); } else { cas.setSofaIndexRepository(aSofa, this.indexRepository); } } } // Use this when creating a CAS view void refreshView(CAS cas, SofaFS aSofa) { if (aSofa != null) { // save address of SofaFS this.mySofaRef = (Sofa) aSofa; } else { // this is the InitialView this.mySofaRef = null; } // toss the JCas, if it exists this.jcas = null; // create the indexRepository for this Sofa final FSIndexRepositoryImpl baseIndexRepo = (FSIndexRepositoryImpl) ((CASImpl) cas).getBaseIndexRepository(); this.indexRepository = new FSIndexRepositoryImpl(this,baseIndexRepo); // the index creation depends on "indexRepository" already being set baseIndexRepo.name2indexMap.keySet().stream().forEach(key -> this.indexRepository.createIndex(baseIndexRepo, key)); this.indexRepository.commit(); // save new sofa index if (this.mySofaRef == null) { ((CASImpl) cas).setSofaIndexRepository(1, this.indexRepository); } else { ((CASImpl) cas).setSofaIndexRepository(aSofa, this.indexRepository); } } private void checkInternalCodes(CASMgrSerializer ser) throws CASAdminException { if ((ser.topTypeCode > 0) && (ser.topTypeCode != topTypeCode)) { throw new CASAdminException(CASAdminException.DESERIALIZATION_ERROR); } if (ser.featureOffsets == null) { return; } // if (ser.featureOffsets.length != this.svd.casMetadata.featureOffset.length) { // throw new CASAdminException(CASAdminException.DESERIALIZATION_ERROR); // } TypeSystemImpl tsi = getTypeSystemImpl(); for (int i = 1; i < ser.featureOffsets.length; i++) { FeatureImpl fi = tsi.getFeatureForCode_checked(i); int adjOffset = fi.isInInt ? 0 : fi.getRangeImpl().nbrOfUsedIntDataSlots; if (ser.featureOffsets[i] != (fi.getOffset() + adjOffset)) { throw new CASAdminException(CASAdminException.DESERIALIZATION_ERROR); } } } // ---------------------------------------- // accessors for data in SharedViewData // ---------------------------------------- void addSofaViewName(String id) { svd.sofaNameSet.add(id); } void setViewCount(int n) { svd.viewCount = n; } void addbackSingle(TOP fs) { if (!svd.fsTobeAddedbackSingleInUse) { Misc.internalError(); } svd.fsTobeAddedbackSingle.addback(fs); svd.fsTobeAddedbackSingleInUse = false; } void addbackSingleIfWasRemoved(boolean wasRemoved, TOP fs) { if (wasRemoved) { addbackSingle(fs); } svd.fsTobeAddedbackSingleInUse = false; } private FSsTobeAddedback getAddback(int size) { if (svd.fsTobeAddedbackSingleInUse) { Misc.internalError(); } return svd.fssTobeAddedback.get(size - 1); } FSsTobeAddedbackSingle getAddbackSingle() { if (svd.fsTobeAddedbackSingleInUse) { // System.out.println(Misc.dumpCallers(addbackSingleTrace, 2, 100)); Misc.internalError(); } // addbackSingleTrace = Thread.currentThread().getStackTrace(); svd.fsTobeAddedbackSingleInUse = true; svd.fsTobeAddedbackSingle.clear(); // safety return svd.fsTobeAddedbackSingle; } void featureCodes_inIndexKeysAdd(int featCode/*, int registryIndex*/) { svd.featureCodesInIndexKeys.set(featCode); // skip adding if no JCas registry entry for this feature // if (registryIndex >= 0) { // svd.featureJiInIndexKeys.set(registryIndex); // } } @Override public void enableReset(boolean flag) { this.svd.flushEnabled = flag; } @Override public final TypeSystem getTypeSystem() { return getTypeSystemImpl(); } public final TypeSystemImpl getTypeSystemImpl() { if (tsi_local == null) { tsi_local = this.svd.tsi; } return this.tsi_local; } /** * Set the shared svd type system ref, in all views * @param ts */ void installTypeSystemInAllViews(TypeSystemImpl ts) { this.svd.tsi = ts; final List<CASImpl> sn2v = this.svd.sofaNbr2ViewMap; if (sn2v.size() > 0) { for (CASImpl view : sn2v.subList(1, sn2v.size())) { view.tsi_local = ts; } } this.getBaseCAS().tsi_local = ts; } @Override public ConstraintFactory getConstraintFactory() { return ConstraintFactory.instance(); } /** * Create the appropriate Feature Structure Java instance * - from whatever the generator for this type specifies. * * @param type the type to create * @return a Java object representing the FeatureStructure impl in Java. */ @Override public <T extends FeatureStructure> T createFS(Type type) { final TypeImpl ti = (TypeImpl) type; if (!ti.isCreatableAndNotBuiltinArray()) { throw new CASRuntimeException(CASRuntimeException.NON_CREATABLE_TYPE, type.getName(), "CAS.createFS()"); } return (T) createFSAnnotCheck(ti); } private <T extends FeatureStructureImplC> T createFSAnnotCheck(TypeImpl ti) { if (ti.isAnnotationBaseType()) { // not here, will be checked later in AnnotationBase constructor // if (this.isBaseCas()) { // throw new CASRuntimeException(CASRuntimeException.DISALLOW_CREATE_ANNOTATION_IN_BASE_CAS, ti.getName()); // } getSofaRef(); // materialize this if not present; required for setting the sofa ref // must happen before the annotation is created, for compressed form 6 serialization order // to insure sofa precedes the ref of it } FsGenerator3 g = svd.generators[ti.getCode()]; // get generator or null return (g != null) ? (T) g.createFS(ti, this) // pear case, with no overriding pear - use base : (T) createFsFromGenerator(svd.baseGenerators, ti); // // // // not pear or no special cover class for this // // // TOP fs = createFsFromGenerator(svd.baseGenerators, ti); // // FsGenerator g = svd.generators[ti.getCode()]; // get pear generator or null // return (g != null) // ? (T) pearConvert(fs, g) // : (T) fs; // } // // return (T) createFsFromGenerator(svd.generators, ti); } /** * Called during construction of FS. * For normal FS "new" operators, if in PEAR context, make the base version * @param fs * @param ti * @return true if made a base for a trampoline */ boolean maybeMakeBaseVersionForPear(FeatureStructureImplC fs, TypeImpl ti) { if (!inPearContext()) return false; FsGenerator3 g = svd.generators[ti.getCode()]; // get pear generator or null if (g == null) return false; TOP baseFs; try { suspendPearContext(); svd.reuseId = fs._id; baseFs = createFsFromGenerator(svd.baseGenerators, ti); } finally { restorePearContext(); svd.reuseId = 0; } svd.id2base.put(baseFs); pearBaseFs = baseFs; return true; } private TOP createFsFromGenerator(FsGenerator3[] gs, TypeImpl ti) { return gs[ti.getCode()].createFS(ti, this); } public TOP createArray(TypeImpl array_type, int arrayLength) { TypeImpl_array tia = (TypeImpl_array) array_type; TypeImpl componentType = tia.getComponentType(); if (componentType.isPrimitive()) { checkArrayPreconditions(arrayLength); switch (componentType.getCode()) { case intTypeCode: return new IntegerArray(array_type, this, arrayLength); case floatTypeCode: return new FloatArray(array_type, this, arrayLength); case booleanTypeCode: return new BooleanArray(array_type, this, arrayLength); case byteTypeCode: return new ByteArray(array_type, this, arrayLength); case shortTypeCode: return new ShortArray(array_type, this, arrayLength); case longTypeCode: return new LongArray(array_type, this, arrayLength); case doubleTypeCode: return new DoubleArray(array_type, this, arrayLength); case stringTypeCode: return new StringArray(array_type, this, arrayLength); default: throw Misc.internalError(); } } return (TOP) createArrayFS(array_type, arrayLength); } /* * =============== These methods might be deprecated in favor of * new FSArray(jcas, length) etc. * except that these run with the CAS, not JCas * (non-Javadoc) * @see org.apache.uima.cas.CAS#createArrayFS(int) */ @Override public ArrayFS createArrayFS(int length) { return createArrayFS(getTypeSystemImpl().fsArrayType, length); } private ArrayFS createArrayFS(TypeImpl type, int length) { checkArrayPreconditions(length); return new FSArray(type, this, length); } @Override public IntArrayFS createIntArrayFS(int length) { checkArrayPreconditions(length); return new IntegerArray(getTypeSystemImpl().intArrayType, this, length); } @Override public FloatArrayFS createFloatArrayFS(int length) { checkArrayPreconditions(length); return new FloatArray(getTypeSystemImpl().floatArrayType, this, length); } @Override public StringArrayFS createStringArrayFS(int length) { checkArrayPreconditions(length); return new StringArray(getTypeSystemImpl().stringArrayType, this, length); } // return true if only one sofa and it is the default text sofa public boolean isBackwardCompatibleCas() { // check that there is exactly one sofa if (this.svd.viewCount != 1) { return false; } if (!this.svd.initialSofaCreated) { return false; } Sofa sofa = this.getInitialView().getSofa(); // check for mime type exactly equal to "text" String sofaMime = sofa.getMimeType(); if (!"text".equals(sofaMime)) { return false; } // check that sofaURI and sofaArray are not set String sofaUri = sofa.getSofaURI(); if (sofaUri != null) { return false; } TOP sofaArray = sofa.getSofaArray(); if (sofaArray != null) { return false; } // check that name is NAME_DEFAULT_SOFA String sofaname = sofa.getSofaID(); return NAME_DEFAULT_SOFA.equals(sofaname); } int getViewCount() { return this.svd.viewCount; } FSIndexRepository getSofaIndexRepository(SofaFS aSofa) { return getSofaIndexRepository(aSofa.getSofaRef()); } FSIndexRepositoryImpl getSofaIndexRepository(int aSofaRef) { if (aSofaRef >= this.svd.sofa2indexMap.size()) { return null; } return this.svd.sofa2indexMap.get(aSofaRef); } void setSofaIndexRepository(SofaFS aSofa, FSIndexRepositoryImpl indxRepos) { setSofaIndexRepository(aSofa.getSofaRef(), indxRepos); } void setSofaIndexRepository(int aSofaRef, FSIndexRepositoryImpl indxRepos) { Misc.setWithExpand(this.svd.sofa2indexMap, aSofaRef, indxRepos); } /** * @deprecated */ @Override @Deprecated public SofaFS createSofa(SofaID sofaID, String mimeType) { // extract absolute SofaName string from the ID SofaFS aSofa = createSofa(sofaID.getSofaID(), mimeType); getView(aSofa); // will create the view, needed to make the // resetNoQuestions and other things that // iterate over views work. return aSofa; } Sofa createSofa(String sofaName, String mimeType) { return createSofa(++this.svd.viewCount, sofaName, mimeType); } Sofa createSofa(int sofaNum, String sofaName, String mimeType) { if (this.svd.sofaNameSet.contains(sofaName)) { throw new CASRuntimeException(CASRuntimeException.SOFANAME_ALREADY_EXISTS, sofaName); } final boolean viewAlreadyExists = sofaNum == this.svd.viewCount; if (!viewAlreadyExists) { if (sofaNum == 1) { // skip the test for sofaNum == 1 - this can be set "later" if (this.svd.viewCount == 0) { this.svd.viewCount = 1; } // else it is == or higher, so don't reset it down } else { // sofa is not initial sofa - is guaranteed to be set when view created // if (sofaNum != this.svd.viewCount + 1) { // System.out.println("debug"); // } assert (sofaNum == this.svd.viewCount + 1); this.svd.viewCount = sofaNum; } } Sofa sofa = new Sofa( getTypeSystemImpl().sofaType, this.getBaseCAS(), // view for a sofa is the base cas to correspond to where it gets indexed sofaNum, sofaName, mimeType); this.getBaseIndexRepository().addFS(sofa); this.svd.sofaNameSet.add(sofaName); if (!viewAlreadyExists) { getView(sofa); // create the view that goes with this Sofa } return sofa; } boolean hasView(String name) { return this.svd.sofaNameSet.contains(name); } Sofa createInitialSofa(String mimeType) { Sofa sofa = createSofa(1, CAS.NAME_DEFAULT_SOFA, mimeType); registerInitialSofa(); this.mySofaRef = sofa; return sofa; } void registerInitialSofa() { this.svd.initialSofaCreated = true; } boolean isInitialSofaCreated() { return this.svd.initialSofaCreated; } /** * @deprecated */ @Override @Deprecated public SofaFS getSofa(SofaID sofaID) { // extract absolute SofaName string from the ID return getSofa(sofaID.getSofaID()); } private SofaFS getSofa(String sofaName) { FSIterator<Sofa> iterator = this.svd.baseCAS.getSofaIterator(); while (iterator.hasNext()) { SofaFS sofa = iterator.next(); if (sofaName.equals(sofa.getSofaID())) { return sofa; } } throw new CASRuntimeException(CASRuntimeException.SOFANAME_NOT_FOUND, sofaName); } SofaFS getSofa(int sofaRef) { SofaFS aSofa = (SofaFS) this.ll_getFSForRef(sofaRef); if (aSofa == null) { CASRuntimeException e = new CASRuntimeException(CASRuntimeException.SOFAREF_NOT_FOUND); throw e; } return aSofa; } public int ll_getSofaNum(int sofaRef) { return ((Sofa)getFsFromId_checked(sofaRef)).getSofaNum(); } public String ll_getSofaID(int sofaRef) { return ((Sofa)getFsFromId_checked(sofaRef)).getSofaID(); } public String ll_getSofaDataString(int sofaAddr) { return ((Sofa)getFsFromId_checked(sofaAddr)).getSofaString(); } public CASImpl getBaseCAS() { return this.svd.baseCAS; } @Override public <T extends SofaFS> FSIterator<T> getSofaIterator() { FSIndex<T> sofaIndex = this.svd.baseCAS.indexRepository.<T>getIndex(CAS.SOFA_INDEX_NAME); return sofaIndex.iterator(); } // For internal use only public Sofa getSofaRef() { if (this.mySofaRef == null) { // create the SofaFS for _InitialView ... // ... and reset mySofaRef to point to it this.mySofaRef = this.createInitialSofa(null); } return this.mySofaRef; } // For internal use only public InputStream getSofaDataStream(SofaFS aSofa) { Sofa sofa = (Sofa) aSofa; String sd = sofa.getLocalStringData(); if (null != sd) { ByteArrayInputStream bis; try { bis = new ByteArrayInputStream(sd.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // never happen } return bis; } else if (null != aSofa.getLocalFSData()) { TOP fs = (TOP) sofa.getLocalFSData(); ByteBuffer buf = null; switch(fs._getTypeCode()) { case stringArrayTypeCode: { StringBuilder sb = new StringBuilder(); final String[] theArray = ((StringArray) fs)._getTheArray(); for (int i = 0; i < theArray.length; i++) { if (i != 0) { sb.append('\n'); } sb.append(theArray[i]); } try { return new ByteArrayInputStream(sb.toString().getBytes("UTF-8") ); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // never happen } } case intArrayTypeCode: { final int[] theArray = ((IntegerArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 4)).asIntBuffer().put(theArray, 0, theArray.length); break; } case floatArrayTypeCode: { final float[] theArray = ((FloatArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 4)).asFloatBuffer().put(theArray, 0, theArray.length); break; } case byteArrayTypeCode: { final byte[] theArray = ((ByteArray) fs)._getTheArray(); buf = ByteBuffer.wrap(theArray); break; } case shortArrayTypeCode: { final short[] theArray = ((ShortArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 2)).asShortBuffer().put(theArray, 0, theArray.length); break; } case longArrayTypeCode: { final long[] theArray = ((LongArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 8)).asLongBuffer().put(theArray, 0, theArray.length); break; } case doubleArrayTypeCode: { final double[] theArray = ((DoubleArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 8)).asDoubleBuffer().put(theArray, 0, theArray.length); break; } default: throw Misc.internalError(); } ByteArrayInputStream bis = new ByteArrayInputStream(buf.array()); return bis; } else if (null != aSofa.getSofaURI()) { URL url; try { url = new URL(aSofa.getSofaURI()); return url.openStream(); } catch (IOException exc) { throw new CASRuntimeException(CASRuntimeException.SOFADATASTREAM_ERROR, exc.getMessage()); } } return null; } @Override public<T extends FeatureStructure> FSIterator<T> createFilteredIterator(FSIterator<T> it, FSMatchConstraint cons) { return new FilteredIterator<T>(it, cons); } public TypeSystemImpl commitTypeSystem() { TypeSystemImpl ts = getTypeSystemImpl(); // For CAS pools, the type system could have already been committed // Skip the initFSClassReg if so, because it may have been updated to a JCas // version by another CAS processing in the pool // @see org.apache.uima.cas.impl.FSClassRegistry // avoid race: two instances of a CAS from a pool attempting to commit the // ts // at the same time final ClassLoader cl = getJCasClassLoader(); synchronized (ts) { // //debug // System.out.format("debug committing ts %s classLoader %s%n", ts.hashCode(), cl); if (!ts.isCommitted()) { TypeSystemImpl tsc = ts.commit(getJCasClassLoader()); if (tsc != ts) { installTypeSystemInAllViews(tsc); ts = tsc; } } } svd.baseGenerators = svd.generators = ts.getGeneratorsForClassLoader(cl, false); // false - not PEAR createIndexRepository(); return ts; } private void createIndexRepository() { if (!this.getTypeSystemMgr().isCommitted()) { throw new CASAdminException(CASAdminException.MUST_COMMIT_TYPE_SYSTEM); } if (this.indexRepository == null) { this.indexRepository = new FSIndexRepositoryImpl(this); } } @Override public FSIndexRepositoryMgr getIndexRepositoryMgr() { // assert(this.cas.getIndexRepository() != null); return this.indexRepository; } /** * @deprecated * @param fs - */ @Deprecated public void commitFS(FeatureStructure fs) { getIndexRepository().addFS(fs); } @Override public FeaturePath createFeaturePath() { return new FeaturePathImpl(); } // Implement the ConstraintFactory interface. /** * @see org.apache.uima.cas.admin.CASMgr#getTypeSystemMgr() */ @Override public TypeSystemMgr getTypeSystemMgr() { return getTypeSystemImpl(); } @Override public void reset() { if (!this.svd.flushEnabled) { throw new CASAdminException(CASAdminException.FLUSH_DISABLED); } if (this == this.svd.baseCAS) { resetNoQuestions(); return; } // called from a CAS view. // clear CAS ... this.svd.baseCAS.resetNoQuestions(); } public void resetNoQuestions() { svd.resetNoQuestions(true); } /** * @deprecated Use {@link #reset reset()}instead. */ @Override @Deprecated public void flush() { reset(); } @Override public FSIndexRepository getIndexRepository() { if (this == this.svd.baseCAS) { // BaseCas has no indexes for users return null; } if (this.indexRepository.isCommitted()) { return this.indexRepository; } return null; } FSIndexRepository getBaseIndexRepository() { if (this.svd.baseCAS.indexRepository.isCommitted()) { return this.svd.baseCAS.indexRepository; } return null; } FSIndexRepositoryImpl getBaseIndexRepositoryImpl() { return this.svd.baseCAS.indexRepository; } void addSofaFsToIndex(SofaFS sofa) { this.svd.baseCAS.getBaseIndexRepository().addFS(sofa); } void registerView(Sofa aSofa) { this.mySofaRef = aSofa; } /** * @see org.apache.uima.cas.CAS#fs2listIterator(FSIterator) */ @Override public <T extends FeatureStructure> ListIterator<T> fs2listIterator(FSIterator<T> it) { // return new FSListIteratorImpl<T>(it); return it; // in v3, FSIterator extends listIterator } /** * @see org.apache.uima.cas.admin.CASMgr#getCAS() */ @Override public CAS getCAS() { if (this.indexRepository.isCommitted()) { return this; } throw new CASAdminException(CASAdminException.MUST_COMMIT_INDEX_REPOSITORY); } // public void setFSClassRegistry(FSClassRegistry fsClassReg) { // this.svd.casMetadata.fsClassRegistry = fsClassReg; // } // JCasGen'd cover classes use this to add their generators to the class // registry // Note that this now (June 2007) a no-op for JCasGen'd generators // Also previously (but not now) used in JCas initialization to copy-down super generators to subtypes // as needed public FSClassRegistry getFSClassRegistry() { return null; // return getTypeSystemImpl().getFSClassRegistry(); } /** * @param fs the Feature Structure being updated * @param fi the Feature of fs being updated, or null if fs is an array * @param arrayIndexStart * @param nbrOfConsecutive */ private void logFSUpdate(TOP fs, FeatureImpl fi, int arrayIndexStart, int nbrOfConsecutive) { //log the FS final Map<TOP, FsChange> changes = this.svd.modifiedPreexistingFSs; //create or use last FsChange element FsChange change = changes.computeIfAbsent(fs, key -> new FsChange(key)); if (fi == null) { Misc.assertUie(arrayIndexStart >= 0); change.addArrayData(arrayIndexStart, nbrOfConsecutive); } else { change.addFeatData(fi.getOffset()); } } /** * @param fs the Feature Structure being updated * @param arrayIndexStart * @param nbrOfConsecutive */ private void logFSUpdate(TOP fs, PositiveIntSet indexesPlus1) { //log the FS final Map<TOP, FsChange> changes = this.svd.modifiedPreexistingFSs; //create or use last FsChange element FsChange change = changes.computeIfAbsent(fs, key -> new FsChange(key)); change.addArrayData(indexesPlus1); } private void logFSUpdate(TOP fs, FeatureImpl fi) { logFSUpdate(fs, fi, -1, -1); // indicate non-array call } /** * This is your link from the low-level API to the high-level API. Use this * method to create a FeatureStructure object from an address. Note that the * reverse is not supported by public APIs (i.e., there is currently no way to * get at the address of a FeatureStructure. Maybe we will need to change * that. * * The "create" in "createFS" is a misnomer - the FS must already be created. * * @param id The id of the feature structure to be created. * @param <T> The Java class associated with this feature structure * @return A FeatureStructure object. */ public <T extends TOP> T createFS(int id) { return getFsFromId_checked(id); } public int getArraySize(CommonArrayFS fs) { return fs.size(); } @Override public int ll_getArraySize(int id) { return getArraySize(getFsFromId_checked(id)); } final void setWithCheckAndJournal(TOP fs, FeatureImpl fi, Runnable setter) { if (fs._inSetSortedIndex()) { boolean wasRemoved = checkForInvalidFeatureSetting(fs, fi.getCode()); setter.run(); if (wasRemoved) { maybeAddback(fs); } } else { setter.run(); } maybeLogUpdate(fs, fi); } final public void setWithCheckAndJournal(TOP fs, int featCode, Runnable setter) { if (fs._inSetSortedIndex()) { boolean wasRemoved = checkForInvalidFeatureSetting(fs, featCode); setter.run(); if (wasRemoved) { maybeAddback(fs); } } else { setter.run(); } maybeLogUpdate(fs, featCode); } // public void setWithCheck(FeatureStructureImplC fs, FeatureImpl feat, Runnable setter) { // boolean wasRemoved = checkForInvalidFeatureSetting(fs, feat); // setter.run(); // if (wasRemoved) { // maybeAddback(fs); // } // } /** * This method called by setters in JCas gen'd classes when * the setter must check for journaling * @param fs - * @param fi - * @param setter - */ public final void setWithJournal(FeatureStructureImplC fs, FeatureImpl fi, Runnable setter) { setter.run(); maybeLogUpdate(fs, fi); } public final boolean isLoggingNeeded(FeatureStructureImplC fs) { return this.svd.trackingMark != null && !this.svd.trackingMark.isNew(fs._id); } /** * @param fs the Feature Structure being updated * @param feat the feature of fs being updated, or null if fs is a primitive array * @param i the index being updated */ final public void maybeLogArrayUpdate(FeatureStructureImplC fs, FeatureImpl feat, int i) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, feat, i, 1); } } /** * @param fs the Feature Structure being updated * @param indexesPlus1 - a set of indexes (plus 1) that have been update */ final public void maybeLogArrayUpdates(FeatureStructureImplC fs, PositiveIntSet indexesPlus1) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, indexesPlus1); } } /** * @param fs a primitive array FS * @param startingIndex - * @param length number of consequtive items */ public final void maybeLogArrayUpdates(FeatureStructureImplC fs, int startingIndex, int length) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, null, startingIndex, length); } } final public void maybeLogUpdate(FeatureStructureImplC fs, FeatureImpl feat) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, feat); } } final public void maybeLogUpdate(FeatureStructureImplC fs, int featCode) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP)fs, getFeatFromCode_checked(featCode)); } } final public boolean isLogging() { return this.svd.trackingMark != null; } // /** // * Common setter code for features in Feature Structures // * // * These come in two styles: one with int values, one with Object values // * Object values are FS or Strings or JavaObjects // */ // // /** // * low level setter // * // * @param fs the feature structure // * @param feat the feature to set // * @param value - // */ // // public void setFeatureValue(FeatureStructureImplC fs, FeatureImpl feat, int value) { // fs.setIntValue(feat, value); //// boolean wasRemoved = checkForInvalidFeatureSetting(fs, feat.getCode()); //// fs._intData[feat.getAdjustedOffset()] = value; //// if (wasRemoved) { //// maybeAddback(fs); //// } //// maybeLogUpdate(fs, feat); // } /** * version for longs, uses two slots * Only called from FeatureStructureImplC after determining * there is no local field to use * Is here because of 3 calls to things in this class * @param fsIn the feature structure * @param feat the feature to set * @param v - */ public void setLongValue(FeatureStructureImplC fsIn, FeatureImpl feat, long v) { TOP fs = (TOP) fsIn; if (fs._inSetSortedIndex()) { boolean wasRemoved = checkForInvalidFeatureSetting(fs, feat.getCode()); fs._setLongValueNcNj(feat, v); if (wasRemoved) { maybeAddback(fs); } } else { fs._setLongValueNcNj(feat, v); } maybeLogUpdate(fs, feat); } void setFeatureValue(int fsRef, int featureCode, TOP value) { getFsFromId_checked(fsRef).setFeatureValue(getFeatFromCode_checked(featureCode), value); } /** * internal use - special setter for setting feature values, including * special handling if the feature is for the sofaArray, * when deserializing * @param fs - * @param feat - * @param value - */ public static void setFeatureValueMaybeSofa(TOP fs, FeatureImpl feat, TOP value) { if (fs instanceof Sofa) { assert feat.getCode() == sofaArrayFeatCode; ((Sofa)fs).setLocalSofaData(value); } else { fs.setFeatureValue(feat, value); } } /** * Internal use, for cases where deserializing - special case setting sofString to skip updating the document annotation * @param fs - * @param feat - * @param s - */ public static void setFeatureValueFromStringNoDocAnnotUpdate(FeatureStructureImplC fs, FeatureImpl feat, String s) { if (fs instanceof Sofa && feat.getCode() == sofaStringFeatCode) { ((Sofa)fs).setLocalSofaDataNoDocAnnotUpdate(s); } else { setFeatureValueFromString(fs, feat, s); } } /** * Supports setting slots to "0" for null values * @param fs The feature structure to update * @param feat the feature to update- * @param s the string representation of the value, could be null */ public static void setFeatureValueFromString(FeatureStructureImplC fs, FeatureImpl feat, String s) { final TypeImpl range = feat.getRangeImpl(); if (fs instanceof Sofa) { // sofa has special setters Sofa sofa = (Sofa) fs; switch (feat.getCode()) { case sofaMimeFeatCode : sofa.setMimeType(s); break; case sofaStringFeatCode: sofa.setLocalSofaData(s); break; case sofaUriFeatCode: sofa.setRemoteSofaURI(s); break; default: // left empty - ignore trying to set final fields } return; } if (feat.isInInt) { switch (range.getCode()) { case floatTypeCode : fs.setFloatValue(feat, (s == null) ? 0F : Float.parseFloat(s)); break; case booleanTypeCode : fs.setBooleanValue(feat, (s == null) ? false : Boolean.parseBoolean(s)); break; case longTypeCode : fs.setLongValue(feat, (s == null) ? 0L : Long.parseLong(s)); break; case doubleTypeCode : fs.setDoubleValue(feat, (s == null) ? 0D : Double.parseDouble(s)); break; case byteTypeCode : fs.setByteValue(feat, (s == null) ? 0 : Byte.parseByte(s)); break; case shortTypeCode : fs.setShortValue(feat, (s == null) ? 0 : Short.parseShort(s)); break; case intTypeCode : fs.setIntValue(feat, (s == null) ? 0 : Integer.parseInt(s)); break; default: fs.setIntValue(feat, (s == null) ? 0 : Integer.parseInt(s)); } } else if (range.isRefType) { if (s == null) { fs.setFeatureValue(feat, null); } else { // Setting a reference value "{0}" from a string is not supported. throw new CASRuntimeException(CASRuntimeException.SET_REF_FROM_STRING_NOT_SUPPORTED, feat.getName()); } } else if (range.isStringOrStringSubtype()) { // includes TypeImplSubString // is String or Substring fs.setStringValue(feat, (s == null) ? null : s); // } else if (range == getTypeSystemImpl().javaObjectType) { // fs.setJavaObjectValue(feat, (s == null) ? null : deserializeJavaObject(s)); } else { Misc.internalError(); } } // private Object deserializeJavaObject(String s) { // throw new UnsupportedOperationException("Deserializing JavaObjects not yet implemented"); // } // // static String serializeJavaObject(Object s) { // throw new UnsupportedOperationException("Serializing JavaObjects not yet implemented"); // } /* * This should be the only place where the encoding of floats and doubles in terms of ints is specified * Someday we may want to preserve NAN things using "raw" versions */ public static final float int2float(int i) { return Float.intBitsToFloat(i); } public static final int float2int(float f) { return Float.floatToIntBits(f); } public static final double long2double(long l) { return Double.longBitsToDouble(l); } public static final long double2long(double d) { return Double.doubleToLongBits(d); } // Type access methods. public final boolean isStringType(Type type) { return type instanceof TypeImpl_string; } public final boolean isAbstractArrayType(Type type) { return isArrayType(type); } public final boolean isArrayType(Type type) { return ((TypeImpl) type).isArray(); } public final boolean isPrimitiveArrayType(Type type) { return (type instanceof TypeImpl_array) && ! type.getComponentType().isPrimitive(); } public final boolean isIntArrayType(Type type) { return (type == getTypeSystemImpl().intArrayType); } public final boolean isFloatArrayType(Type type) { return ((TypeImpl)type).getCode() == floatArrayTypeCode; } public final boolean isStringArrayType(Type type) { return ((TypeImpl)type).getCode() == stringArrayTypeCode; } public final boolean isBooleanArrayType(Type type) { return ((TypeImpl)type).getCode() == booleanArrayTypeCode; } public final boolean isByteArrayType(Type type) { return ((TypeImpl)type).getCode() == byteArrayTypeCode; } public final boolean isShortArrayType(Type type) { return ((TypeImpl)type).getCode() == byteArrayTypeCode; } public final boolean isLongArrayType(Type type) { return ((TypeImpl)type).getCode() == longArrayTypeCode; } public final boolean isDoubleArrayType(Type type) { return ((TypeImpl)type).getCode() == doubleArrayTypeCode; } public final boolean isFSArrayType(Type type) { return ((TypeImpl)type).getCode() == fsArrayTypeCode; } public final boolean isIntType(Type type) { return ((TypeImpl)type).getCode() == intTypeCode; } public final boolean isFloatType(Type type) { return ((TypeImpl)type).getCode() == floatTypeCode; } public final boolean isByteType(Type type) { return ((TypeImpl)type).getCode() == byteTypeCode; } public final boolean isBooleanType(Type type) { return ((TypeImpl)type).getCode() == floatTypeCode; } public final boolean isShortType(Type type) { return ((TypeImpl)type).getCode() == shortTypeCode; } public final boolean isLongType(Type type) { return ((TypeImpl)type).getCode() == longTypeCode; } public final boolean isDoubleType(Type type) { return ((TypeImpl)type).getCode() == doubleTypeCode; } /* * Only called on base CAS */ /** * @see org.apache.uima.cas.admin.CASMgr#initCASIndexes() */ @Override public void initCASIndexes() throws CASException { final TypeSystemImpl ts = getTypeSystemImpl(); if (!ts.isCommitted()) { throw new CASException(CASException.MUST_COMMIT_TYPE_SYSTEM); } FSIndexComparator comp = this.indexRepository.createComparator(); comp.setType(ts.sofaType); comp.addKey(ts.sofaNum, FSIndexComparator.STANDARD_COMPARE); this.indexRepository.createIndex(comp, CAS.SOFA_INDEX_NAME, FSIndex.BAG_INDEX); comp = this.indexRepository.createComparator(); comp.setType(ts.annotType); comp.addKey(ts.startFeat, FSIndexComparator.STANDARD_COMPARE); comp.addKey(ts.endFeat, FSIndexComparator.REVERSE_STANDARD_COMPARE); comp.addKey(this.indexRepository.getDefaultTypeOrder(), FSIndexComparator.STANDARD_COMPARE); this.indexRepository.createIndex(comp, CAS.STD_ANNOTATION_INDEX); } // /////////////////////////////////////////////////////////////////////////// // CAS support ... create CAS view of aSofa // For internal use only public CAS getView(int sofaNum) { return svd.getViewFromSofaNbr(sofaNum); } @Override public CAS getCurrentView() { return getView(CAS.NAME_DEFAULT_SOFA); } // /////////////////////////////////////////////////////////////////////////// // JCas support @Override public JCas getJCas() { if (this.jcas == null) { this.jcas = JCasImpl.getJCas(this); } return this.jcas; } public JCasImpl getJCasImpl() { if (this.jcas == null) { this.jcas = JCasImpl.getJCas(this); } return this.jcas; } // /** // * Internal use only // * // * @return corresponding JCas, assuming it exists // */ // public JCas getExistingJCas() { // return this.jcas; // } // // Create JCas view of aSofa @Override public JCas getJCas(SofaFS aSofa) throws CASException { // Create base JCas, if needed this.svd.baseCAS.getJCas(); return getView(aSofa).getJCas(); /* * // If a JCas already exists for this Sofa, return it JCas aJCas = (JCas) * this.svd.baseCAS.sofa2jcasMap.get(Integer.valueOf(aSofa.getSofaRef())); if * (null != aJCas) { return aJCas; } // Get view of aSofa CASImpl view = * (CASImpl) getView(aSofa); // wrap in JCas aJCas = view.getJCas(); * this.sofa2jcasMap.put(Integer.valueOf(aSofa.getSofaRef()), aJCas); return * aJCas; */ } /** * @deprecated */ @Override @Deprecated public JCas getJCas(SofaID aSofaID) throws CASException { SofaFS sofa = getSofa(aSofaID); // sofa guaranteed to be non-null by above method. return getJCas(sofa); } // For internal platform use only CASImpl getInitialView() { return svd.getInitialView(); } @Override public CAS createView(String aSofaID) { // do sofa mapping for current component String absoluteSofaName = null; if (getCurrentComponentInfo() != null) { absoluteSofaName = getCurrentComponentInfo().mapToSofaID(aSofaID); } if (absoluteSofaName == null) { absoluteSofaName = aSofaID; } // Can't use name of Initial View if (CAS.NAME_DEFAULT_SOFA.equals(absoluteSofaName)) { throw new CASRuntimeException(CASRuntimeException.SOFANAME_ALREADY_EXISTS, aSofaID); } Sofa newSofa = createSofa(absoluteSofaName, null); CAS newView = getView(newSofa); ((CASImpl) newView).registerView(newSofa); return newView; } @Override public CAS getView(String aSofaID) { // do sofa mapping for current component String absoluteSofaName = null; if (getCurrentComponentInfo() != null) { absoluteSofaName = getCurrentComponentInfo().mapToSofaID(aSofaID); } if (absoluteSofaName == null) { absoluteSofaName = aSofaID; } // if this resolves to the Initial View, return view(1)... // ... as the Sofa for this view may not exist yet if (CAS.NAME_DEFAULT_SOFA.equals(absoluteSofaName)) { return getInitialView(); } // get Sofa and switch to view SofaFS sofa = getSofa(absoluteSofaName); // sofa guaranteed to be non-null by above method // unless sofa doesn't exist, which will cause a throw. return getView(sofa); } /* * (non-Javadoc) * * @see org.apache.uima.cas.CAS#getView(org.apache.uima.cas.SofaFS) * * Callers of this can have created Sofas in the CAS without views: using the * old deprecated createSofa apis (this is being fixed so these will create * the views) via deserialization, which will put the sofaFSs into the CAS * without creating the views, and then call this to create the views. - for * deserialization: there are 2 kinds: 1 is xmi the other is binary. - for * xmi: there is 1.4.x compatible and 2.1 compatible. The older format can * have sofaNbrs in the order 2, 3, 4, 1 (initial sofa), 5, 6, 7 The newer * format has them in order. For deserialized sofas, we insure here that there * are no duplicates. This is not done in the deserializers - they use either * heap dumping (binary) or generic fs creators (xmi). * * Goal is to detect case where check is needed (sofa exists, but view not yet * created). This is done by looking for cases where sofaNbr &gt; curViewCount. * This only works if the sofaNbrs go up by 1 (except for the initial sofa) in * the input sequence of calls. */ @Override public CASImpl getView(SofaFS aSofa) { Sofa sofa = (Sofa) aSofa; final int sofaNbr = sofa.getSofaRef(); // final Integer sofaNbrInteger = Integer.valueOf(sofaNbr); CASImpl aView = svd.getViewFromSofaNbr(sofaNbr); if (null == aView) { // This is the deserializer case, or the case where an older API created a // sofa, // which is now creating the associated view // create a new CAS view aView = new CASImpl(this.svd.baseCAS, sofa); svd.setViewForSofaNbr(sofaNbr, aView); verifySofaNameUniqueIfDeserializedViewAdded(sofaNbr, sofa); return aView; } // for deserialization - might be reusing a view, and need to tie new Sofa // to old View if (null == aView.mySofaRef) { aView.mySofaRef = sofa; } verifySofaNameUniqueIfDeserializedViewAdded(sofaNbr, aSofa); return aView; } // boolean isSofaView(int sofaAddr) { // if (mySofaRef == null) { // // don't create initial sofa // return false; // } // return mySofaRef == sofaAddr; // } /* * for Sofas being added (determined by sofaNbr &gt; curViewCount): verify sofa * name is not already present, and record it for future tests * * Only should do the name test & update in the case of deserialized new sofas * coming in. These will come in, in order. Exception is "_InitialView" which * could come in the middle. If it comes in the middle, no test will be done * for duplicates, and it won't be added to set of known names. This is ok * because the createVIew special cases this test. Users could corrupt an xmi * input, which would make this logic fail. */ private void verifySofaNameUniqueIfDeserializedViewAdded(int sofaNbr, SofaFS aSofa) { final int curViewCount = this.svd.viewCount; if (curViewCount < sofaNbr) { // Only true for deserialized sofas with new views being either created, // or // hooked-up from CASes that were freshly reset, which have multiple // views. // Assume sofa numbers are incrementing by 1 assert (sofaNbr == curViewCount + 1); this.svd.viewCount = sofaNbr; String id = aSofa.getSofaID(); // final Feature idFeat = // getTypeSystem().getFeatureByFullName(CAS.FEATURE_FULL_NAME_SOFAID); // String id = // ll_getStringValue(((FeatureStructureImpl)aSofa).getAddress(), // ((FeatureImpl) idFeat).getCode()); Misc.assertUie(this.svd.sofaNameSet.contains(id)); // this.svd.sofaNameSet.add(id); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getTypeSystem() */ @Override public LowLevelTypeSystem ll_getTypeSystem() { return getTypeSystemImpl().getLowLevelTypeSystem(); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getIndexRepository() */ @Override public LowLevelIndexRepository ll_getIndexRepository() { return this.indexRepository; } /** * * @param fs * @param domType * @param featCode */ private final void checkLowLevelParams(TOP fs, TypeImpl domType, int featCode) { checkFeature(featCode); checkTypeHasFeature(domType, featCode); } /** * Check that the featCode is a feature of the domain type * @param domTypeCode * @param featCode */ private final void checkTypeHasFeature(TypeImpl domainType, int featureCode) { checkTypeHasFeature(domainType, getFeatFromCode_checked(featureCode)); } private final void checkTypeHasFeature(TypeImpl domainType, FeatureImpl feature) { if (!domainType.isAppropriateFeature(feature)) { throw new LowLevelException(LowLevelException.FEAT_DOM_ERROR, Integer.valueOf(domainType.getCode()), domainType.getName(), Integer.valueOf(feature.getCode()), feature.getName()); } } /** * Check the range is appropriate for this type/feature. Throws * LowLevelException if it isn't. * * @param domType * domain type * @param ranType * range type * @param feat * feature */ public final void checkTypingConditions(Type domType, Type ranType, Feature feat) { TypeImpl domainTi = (TypeImpl) domType; FeatureImpl fi = (FeatureImpl) feat; checkTypeHasFeature(domainTi, fi); if (!((TypeImpl) fi.getRange()).subsumes((TypeImpl) ranType)) { throw new LowLevelException(LowLevelException.FEAT_RAN_ERROR, Integer.valueOf(fi.getCode()), feat.getName(), Integer.valueOf(((TypeImpl)ranType).getCode()), ranType.getName()); } } /** * Validate a feature's range is a ref to a feature structure * @param featCode * @throws LowLevelException */ private final void checkFsRan(FeatureImpl fi) throws LowLevelException { if (!fi.getRangeImpl().isRefType) { throw new LowLevelException(LowLevelException.FS_RAN_TYPE_ERROR, Integer.valueOf(fi.getCode()), fi.getName(), fi.getRange().getName()); } } private final void checkFeature(int featureCode) { if (!getTypeSystemImpl().isFeature(featureCode)) { throw new LowLevelException(LowLevelException.INVALID_FEATURE_CODE, Integer.valueOf(featureCode)); } } private TypeImpl getTypeFromCode(int typeCode) { return getTypeSystemImpl().getTypeForCode(typeCode); } private TypeImpl getTypeFromCode_checked(int typeCode) { return getTypeSystemImpl().getTypeForCode_checked(typeCode); } private FeatureImpl getFeatFromCode_checked(int featureCode) { return getTypeSystemImpl().getFeatureForCode_checked(featureCode); } public final <T extends TOP> T getFsFromId_checked(int fsRef) { T r = getFsFromId(fsRef); if (r == null) { if (fsRef == 0) { return null; } LowLevelException e = new LowLevelException(LowLevelException.INVALID_FS_REF, Integer.valueOf(fsRef)); // this form to enable seeing this even if the // throwable is silently handled. // System.err.println("debug " + e); throw e; } return r; } @Override public final boolean ll_isRefType(int typeCode) { return getTypeFromCode(typeCode).isRefType; } @Override public final int ll_getTypeClass(int typeCode) { return TypeSystemImpl.getTypeClass(getTypeFromCode(typeCode)); } // backwards compatibility only @Override public final int ll_createFS(int typeCode) { return ll_createFS(typeCode, true); } @Override public final int ll_createFS(int typeCode, boolean doCheck) { TypeImpl ti = (TypeImpl) getTypeSystemImpl().ll_getTypeForCode(typeCode); if (doCheck) { if (ti == null || !ti.isCreatableAndNotBuiltinArray()) { throw new LowLevelException(LowLevelException.CREATE_FS_OF_TYPE_ERROR, Integer.valueOf(typeCode)); } } TOP fs = (TOP) createFS(ti); if (!fs._isPearTrampoline()) { if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally(fs); // hold on to it if nothing else is } else { svd.id2fs.put(fs); // just like above, but has assert that wasn't there previously } } return fs._id; } /** * used for ll_setIntValue which changes type code * @param ti - the type of the created FS * @param id - the id to use * @return the FS */ private TOP createFsWithExistingId(TypeImpl ti, int id) { svd.reuseId = id; try { TOP fs = createFS(ti); svd.id2fs.putChange(id, fs); return fs; } finally { svd.reuseId = 0; } } /* /** * @param arrayLength * @return the id of the created array * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_createArray(int, int) */ @Override public int ll_createArray(int typeCode, int arrayLength) { TOP fs = createArray(getTypeFromCode_checked(typeCode), arrayLength); if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally(fs); } else { svd.id2fs.put(fs); } return fs._id; } /** * (for backwards compatibility with V2 CASImpl) * Create a temporary (i.e., per document) array FS on the heap. * * @param type * The type code of the array to be created. * @param len * The length of the array to be created. * @return - * @exception ArrayIndexOutOfBoundsException * If <code>type</code> is not a type. */ public int createTempArray(int type, int len) { return ll_createArray(type, len); } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createByteArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().byteArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createBooleanArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().booleanArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createShortArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().shortArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createLongArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().longArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createDoubleArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().doubleArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createArray(int typeCode, int arrayLength, boolean doChecks) { TypeImpl ti = getTypeFromCode_checked(typeCode); if (doChecks) { if (!ti.isArray()) { throw new LowLevelException(LowLevelException.CREATE_ARRAY_OF_TYPE_ERROR, Integer.valueOf(typeCode), ti.getName()); } if (arrayLength < 0) { throw new LowLevelException(LowLevelException.ILLEGAL_ARRAY_LENGTH, Integer.valueOf(arrayLength)); } } TOP fs = createArray(ti, arrayLength); svd.id2fs.put(fs); return fs._id; } public void validateArraySize(int length) { if (length < 0) { /** Array size must be &gt;= 0. */ throw new CASRuntimeException(CASRuntimeException.ILLEGAL_ARRAY_SIZE); } } /** * Safety - any time the low level API to a FS is requested, * hold on to that FS until CAS reset to mimic how v2 works. */ @Override public final int ll_getFSRef(FeatureStructure fs) { if (null == fs) { return NULL; } TOP fst = (TOP) fs; if (fst._isPearTrampoline()) { return fst._id; // no need to hold on to this one - it's in jcas hash maps } // uncond. because this method can be called multiple times svd.id2fs.putUnconditionally(fst); // hold on to it return ((FeatureStructureImplC)fs)._id; } @Override public <T extends TOP> T ll_getFSForRef(int id) { return getFsFromId_checked(id); } /** * Handle some unusual backwards compatibility cases * featureCode = 0 - implies getting the type code * feature range is int - normal * feature range is a fs reference, return the id * feature range is a string: add the string if not already present to the string heap, return the int handle. * @param fsRef - * @param featureCode - * @return - */ @Override public final int ll_getIntValue(int fsRef, int featureCode) { TOP fs = getFsFromId_checked(fsRef); if (featureCode == 0) { return fs._getTypeImpl().getCode(); // case where the type is being requested } FeatureImpl fi = getFeatFromCode_checked(featureCode); SlotKind kind = fi.getSlotKind(); switch(kind) { case Slot_HeapRef: return fs.getFeatureValue(fi)._id; case Slot_Boolean: case Slot_Byte: case Slot_Short: case Slot_Int: case Slot_Float: return fs._getIntValueNc(fi); case Slot_StrRef: return getCodeForString(fs._getStringValueNc(fi)); case Slot_LongRef: return getCodeForLong(fs._getLongValueNc(fi)); case Slot_DoubleRef: return getCodeForLong(CASImpl.double2long(fs._getDoubleValueNc(fi))); default: throw new CASRuntimeException( CASRuntimeException.INAPPROP_RANGE, fi.getName(), "int", fi.getRange().getName()); } } // public final int ll_getIntValueFeatOffset(int fsRef, int featureOffset) { // return ll_getFSForRef(fsRef)._intData[featureOffset]; // } @Override public final float ll_getFloatValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getFloatValue(getFeatFromCode_checked(featureCode)); } @Override public final String ll_getStringValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getStringValue(getFeatFromCode_checked(featureCode)); } // public final String ll_getStringValueFeatOffset(int fsRef, int featureOffset) { // return (String) getFsFromId_checked(fsRef)._refData[featureOffset]; // } @Override public final int ll_getRefValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getFeatureValue(getFeatFromCode_checked(featureCode))._id(); } // public final int ll_getRefValueFeatOffset(int fsRef, int featureOffset) { // return ((FeatureStructureImplC)getFsFromId_checked(fsRef)._refData[featureOffset]).id(); // } @Override public final int ll_getIntValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getIntValue(fsRef, featureCode); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getFloatValue(int, int, * boolean) */ @Override public final float ll_getFloatValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getFloatValue(fsRef, featureCode); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getStringValue(int, int, * boolean) */ @Override public final String ll_getStringValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getStringValue(fsRef, featureCode); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getRefValue(int, int, boolean) */ @Override public final int ll_getRefValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkFsRefConditions(fsRef, featureCode); } return getFsFromId_checked(fsRef).getFeatureValue(getFeatFromCode_checked(featureCode))._id(); } /** * This is the method all normal FS feature "setters" call before doing the set operation * on values where the range could be used as an index key. * <p> * If enabled, it will check if the update may corrupt any index in any view. The check tests * whether the feature is being used as a key in one or more indexes and if the FS is in one or more * corruptable view indexes. * <p> * If true, then: * <ul> * <li>it may remove and remember (for later adding-back) the FS from all corruptable indexes * (bag indexes are not corruptable via updating, so these are skipped). * The addback occurs later either via an explicit call to do so, or the end of a protectIndex block, or. * (if autoIndexProtect is enabled) after the individual feature update is completed.</li> * <li>it may give a WARN level message to the log. This enables users to * implement their own optimized handling of this for "high performance" * applications which do not want the overhead of runtime checking. </li></ul> * <p> * * @param fs - the FS to test if it is in the indexes * @param featCode - the feature being tested * @return true if something may need to be added back */ private boolean checkForInvalidFeatureSetting(TOP fs, int featCode) { if (doInvalidFeatSettingCheck(fs)) { if (!svd.featureCodesInIndexKeys.get(featCode)) { // skip if no index uses this feature return false; } boolean wasRemoved = checkForInvalidFeatureSetting2(fs); if (wasRemoved && doCorruptReport()) { featModWhileInIndexReport(fs, featCode); } return wasRemoved; } return false; } /** * version for deserializers, and for set document language, using their own store for toBeAdded * Doesn't report updating of corruptable slots. * @param fs - * @param featCode - * @param toBeAdded - * @return - */ boolean checkForInvalidFeatureSetting(TOP fs, int featCode, FSsTobeAddedback toBeAdded) { if (doInvalidFeatSettingCheck(fs)) { if (!svd.featureCodesInIndexKeys.get(featCode)) { // skip if no index uses this feature return false; } boolean wasRemoved = removeFromCorruptableIndexAnyView(fs, toBeAdded); // if (wasRemoved && doCorruptReport()) { // featModWhileInIndexReport(fs, featCode); // } return wasRemoved; } return false; } /** * version for deserializers, using their own store for toBeAdded * and not bothering to check for particular features * Doesn't report updating of corruptable slots. * @param fs - * @param featCode - * @param toBeAdded - * @return - */ boolean checkForInvalidFeatureSetting(TOP fs, FSsTobeAddedback toBeAdded) { if (doInvalidFeatSettingCheck(fs)) { boolean wasRemoved = removeFromCorruptableIndexAnyView(fs, toBeAdded); // if (wasRemoved && doCorruptReport()) { // featModWhileInIndexReport(fs, null); // } return wasRemoved; } return false; } // // version of above, but using jcasFieldRegistryIndex // private boolean checkForInvalidFeatureSettingJFRI(TOP fs, int jcasFieldRegistryIndex) { // if (doInvalidFeatSettingCheck(fs) && // svd.featureJiInIndexKeys.get(jcasFieldRegistryIndex)) { // // boolean wasRemoved = checkForInvalidFeatureSetting2(fs); // //// if (wasRemoved && doCorruptReport()) { //// featModWhileInIndexReport(fs, getFeatFromRegistry(jcasFieldRegistryIndex)); //// } // return wasRemoved; // } // return false; // } private boolean checkForInvalidFeatureSetting2(TOP fs) { final int ssz = svd.fssTobeAddedback.size(); // next method skips if the fsRef is not in the index (cache) boolean wasRemoved = removeFromCorruptableIndexAnyView( fs, (ssz > 0) ? getAddback(ssz) : // validates single not in use getAddbackSingle() // validates single usage at a time ); if (!wasRemoved && svd.fsTobeAddedbackSingleInUse) { svd.fsTobeAddedbackSingleInUse = false; } return wasRemoved; } // public FeatureImpl getFeatFromRegistry(int jcasFieldRegistryIndex) { // return getFSClassRegistry().featuresFromJFRI[jcasFieldRegistryIndex]; // } private boolean doCorruptReport() { return // skip message if wasn't removed // skip message if protected in explicit block IS_REPORT_FS_UPDATE_CORRUPTS_INDEX && svd.fssTobeAddedback.size() == 0; } /** * * @param fs - * @return false if the fs is not in a set or sorted index (bit in fs), or * the auto protect is disabled and we're not in an explicit protect block */ private boolean doInvalidFeatSettingCheck(TOP fs) { if (!fs._inSetSortedIndex()) { return false; } final int ssz = svd.fssTobeAddedback.size(); // skip if protection is disabled, and no explicit protection block if (IS_DISABLED_PROTECT_INDEXES && ssz == 0) { return false; } return true; } private void featModWhileInIndexReport(FeatureStructure fs, int featCode) { featModWhileInIndexReport(fs, getFeatFromCode_checked(featCode)); } private void featModWhileInIndexReport(FeatureStructure fs, FeatureImpl fi) { // prepare a message which includes the feature which is a key, the fs, and // the call stack. StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); new Throwable().printStackTrace(pw); pw.close(); String msg = String.format( "While FS was in the index, the feature \"%s\"" + ", which is used as a key in one or more indexes, " + "was modified\n FS = \"%s\"\n%s%n", (fi == null)? "for-all-features" : fi.getName(), fs.toString(), sw.toString()); UIMAFramework.getLogger().log(Level.WARNING, msg); if (IS_THROW_EXCEPTION_CORRUPT_INDEX) { throw new UIMARuntimeException(UIMARuntimeException.ILLEGAL_FS_FEAT_UPDATE, new Object[]{}); } } /** * Only called if there was something removed that needs to be added back * * skip the addback (to defer it until later) if: * - running in block mode (you can tell this if svd.fssTobeAddedback.size() &gt; 0) or * if running in block mode, the add back is delayed until the end of the block * * @param fs the fs to add back */ public void maybeAddback(TOP fs) { if (svd.fssTobeAddedback.size() == 0) { assert(svd.fsTobeAddedbackSingleInUse); svd.fsTobeAddedbackSingle.addback(fs); svd.fsTobeAddedbackSingleInUse = false; } } boolean removeFromCorruptableIndexAnyView(final TOP fs, FSsTobeAddedback toBeAdded) { return removeFromIndexAnyView(fs, toBeAdded, FSIndexRepositoryImpl.SKIP_BAG_INDEXES); } /** * This might be called from low level set int value, if we support switching types, and we want to * remove the old type from all indexes. * @param fs the fs to maybe remove * @param toBeAdded a place to record the removal so we can add it back later * @param isSkipBagIndexes is true usually, we don't need to remove/readd to bag indexes (except for the case * of supporting switching types via low level set int for v2 backwards compatibility) * @return true if was removed from one or more indexes */ boolean removeFromIndexAnyView(final TOP fs, FSsTobeAddedback toBeAdded, boolean isSkipBagIndexes) { final TypeImpl ti = ((FeatureStructureImplC)fs)._getTypeImpl(); if (ti.isAnnotationBaseType()) { boolean r = removeAndRecord(fs, (FSIndexRepositoryImpl) fs._casView.getIndexRepository(), toBeAdded, isSkipBagIndexes); fs._resetInSetSortedIndex(); return r; } // not a subtype of AnnotationBase, need to check all views (except base) // sofas indexed in the base view are not corruptable. final Iterator<CAS> viewIterator = getViewIterator(); boolean wasRemoved = false; while (viewIterator.hasNext()) { wasRemoved |= removeAndRecord(fs, (FSIndexRepositoryImpl) viewIterator.next().getIndexRepository(), toBeAdded, isSkipBagIndexes); } fs._resetInSetSortedIndex(); return wasRemoved; } /** * remove a FS from all indexes in this view (except bag indexes, if isSkipBagIndex is true) * @param fs the fs to be removed * @param ir the view * @param toBeAdded the place to record how many times it was in the index, per view * @param isSkipBagIndex set to true for corruptable removes, false for remove in all cases from all indexes * @return true if it was removed, false if it wasn't in any corruptable index. */ private boolean removeAndRecord(TOP fs, FSIndexRepositoryImpl ir, FSsTobeAddedback toBeAdded, boolean isSkipBagIndex) { boolean wasRemoved = ir.removeFS_ret(fs, isSkipBagIndex); if (wasRemoved) { toBeAdded.recordRemove(fs, ir, 1); } return wasRemoved; } /** * Special considerations: * Interface with corruption checking * For backwards compatibility: * handle cases where feature is: * int - normal * 0 - change type code * a ref: treat int as FS "addr" * not an int: handle like v2 where reasonable */ @Override public final void ll_setIntValue(int fsRef, int featureCode, int value) { TOP fs = getFsFromId_checked(fsRef); if (featureCode == 0) { switchFsType(fs, value); return; } FeatureImpl fi = getFeatFromCode_checked(featureCode); if (fs._getTypeImpl().isArray()) { throw new UnsupportedOperationException("ll_setIntValue not permitted to set a feature of an array"); } SlotKind kind = fi.getSlotKind(); switch(kind) { case Slot_HeapRef: if (fi.getCode() == annotBaseSofaFeatCode) { // setting the sofa ref of an annotationBase // can't change this so just verify it's the same TOP sofa = fs.getFeatureValue(fi); if (sofa._id != value) { throw new UnsupportedOperationException("ll_setIntValue not permitted to change a sofaRef feature"); } return; // if the same, just ignore, already set } TOP ref = fs._casView.getFsFromId_checked(value); fs.setFeatureValue(fi, ref); // does the right feature check, too return; case Slot_Boolean: case Slot_Byte: case Slot_Short: case Slot_Int: case Slot_Float: fs._setIntValueCJ(fi, value); break; case Slot_StrRef: String s = getStringForCode(value); if (s == null && value != 0) { Misc.internalError(new Exception("ll_setIntValue got null string for non-0 handle: " + value)); } fs._setRefValueNfcCJ(fi, getStringForCode(value)); break; case Slot_LongRef: case Slot_DoubleRef: Long lng = getLongForCode(value); if (lng == null) { Misc.internalError(new Exception("ll_setIntValue got null Long/Double for handle: " + value)); } fs._setLongValueNfcCJ(fi, lng); break; default: CASRuntimeException e = new CASRuntimeException(CASRuntimeException.INAPPROP_RANGE, fi.getName(), "int", fi.getRange().getName()); // System.err.println("debug " + e); throw e; } } private String getStringForCode(int i) { if (null == svd.llstringSet) { return null; } return svd.llstringSet.getStringForCode(i); } private int getCodeForString(String s) { if (null == svd.llstringSet) { svd.llstringSet = new StringSet(); } return svd.llstringSet.getCodeForString(s); // avoids adding duplicates } private Long getLongForCode(int i) { if (null == svd.lllongSet) { return null; } return svd.lllongSet.getLongForCode(i); } private int getCodeForLong(long s) { if (null == svd.lllongSet) { svd.lllongSet = new LongSet(); } return svd.lllongSet.getCodeForLong(s); // avoids adding duplicates } private void switchFsType(TOP fs, int value) { // throw new UnsupportedOperationException(); // case where the type is being changed // if the new type is a sub/super type of the existing type, // some field data may be copied // if not, no data is copied. // // Item is removed from index and re-indexed // to emulate what V2 did, // the indexing didn't change // all the slots were the same // boolean wasRemoved = removeFromIndexAnyView(fs, getAddbackSingle(), FSIndexRepositoryImpl.INCLUDE_BAG_INDEXES); if (!wasRemoved) { svd.fsTobeAddedbackSingleInUse = false; } TypeImpl newType = getTypeFromCode_checked(value); Class<?> newClass = newType.getJavaClass(); if ((fs instanceof UimaSerializable) || UimaSerializable.class.isAssignableFrom(newClass)) { throw new UnsupportedOperationException("can't switch type to/from UimaSerializable"); } // Measurement - record which type gets switched to which other type // count how many times // record which JCas cover class goes with each type // key = old type, new type, old jcas cover class, new jcas cover class // value = count MeasureSwitchType mst = null; if (MEASURE_SETINT) { MeasureSwitchType key = new MeasureSwitchType(fs._getTypeImpl(), newType); synchronized (measureSwitches) { // map access / updating must be synchronized mst = measureSwitches.get(key); if (null == mst) { measureSwitches.put(key, key); mst = key; } mst.count ++; mst.newSubsumesOld = newType.subsumes(fs._getTypeImpl()); mst.oldSubsumesNew = fs._getTypeImpl().subsumes(newType); } } if (newClass == fs._getTypeImpl().getJavaClass() || newType.subsumes(fs._getTypeImpl())) { // switch in place fs._setTypeImpl(newType); return; } // if types don't subsume each other, we // deviate a bit from V2 behavior // and skip copying the feature slots boolean isOkToCopyFeatures = // true || // debug fs._getTypeImpl().subsumes(newType) || newType.subsumes(fs._getTypeImpl()); // throw new CASRuntimeException(CASRuntimeException.ILLEGAL_TYPE_CHANGE, newType.getName(), fs._getTypeImpl().getName()); TOP newFs = createFsWithExistingId(newType, fs._id); // updates id -> fs map // initialize fields: if (isOkToCopyFeatures) { newFs._copyIntAndRefArraysFrom(fs); } // if (wasRemoved) { // addbackSingle(newFs); // } // replace refs in existing FSs with new // will miss any fs's held by user code - no way to fix that without // universal indirection - very inefficient, so just accept for now long st = System.nanoTime(); walkReachablePlusFSsSorted(fsItem -> { if (fsItem._getTypeImpl().hasRefFeature) { if (fsItem instanceof FSArray) { TOP[] a = ((FSArray)fsItem)._getTheArray(); for (int i = 0; i < a.length; i++) { if (fs == a[i]) { a[i] = newFs; } } return; } final int sz = fsItem._getTypeImpl().nbrOfUsedRefDataSlots; for (int i = 0; i < sz; i++) { Object o = fsItem._getRefValueCommon(i); if (o == fs) { fsItem._setRefValueCommon(i, newFs); // fsItem._refData[i] = newFs; } } } }, null, // mark null, // null or predicate for filtering what gets added null); // null or type mapper, skips if not in other ts if (MEASURE_SETINT) { mst.scantime += System.nanoTime() - st; } } @Override public final void ll_setFloatValue(int fsRef, int featureCode, float value) { getFsFromId_checked(fsRef).setFloatValue(getFeatFromCode_checked(featureCode), value); } // public final void ll_setFloatValueNoIndexCorruptionCheck(int fsRef, int featureCode, float value) { // setFeatureValueNoIndexCorruptionCheck(fsRef, featureCode, float2int(value)); // } @Override public final void ll_setStringValue(int fsRef, int featureCode, String value) { getFsFromId_checked(fsRef).setStringValue(getFeatFromCode_checked(featureCode), value); } @Override public final void ll_setRefValue(int fsRef, int featureCode, int value) { // no index check because refs can't be keys setFeatureValue(fsRef, featureCode, getFsFromId_checked(value)); } @Override public final void ll_setIntValue(int fsRef, int featureCode, int value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setIntValue(fsRef, featureCode, value); } @Override public final void ll_setFloatValue(int fsRef, int featureCode, float value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setFloatValue(fsRef, featureCode, value); } @Override public final void ll_setStringValue(int fsRef, int featureCode, String value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setStringValue(fsRef, featureCode, value); } @Override public final void ll_setCharBufferValue(int fsRef, int featureCode, char[] buffer, int start, int length, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setCharBufferValue(fsRef, featureCode, buffer, start, length); } @Override public final void ll_setCharBufferValue(int fsRef, int featureCode, char[] buffer, int start, int length) { ll_setStringValue(fsRef, featureCode, new String(buffer, start, length)); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_copyCharBufferValue(int, int, * char, int) */ @Override public int ll_copyCharBufferValue(int fsRef, int featureCode, char[] buffer, int start) { String str = ll_getStringValue(fsRef, featureCode); if (str == null) { return -1; } final int len = str.length(); final int requestedMax = start + len; // Check that the buffer is long enough to copy the whole string. If it isn't long enough, we // copy up to buffer.length - start characters. final int max = (buffer.length < requestedMax) ? (buffer.length - start) : len; for (int i = 0; i < max; i++) { buffer[start + i] = str.charAt(i); } return len; } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getCharBufferValueSize(int, * int) */ @Override public int ll_getCharBufferValueSize(int fsRef, int featureCode) { String str = ll_getStringValue(fsRef, featureCode); return str.length(); } @Override public final void ll_setRefValue(int fsRef, int featureCode, int value, boolean doTypeChecks) { if (doTypeChecks) { checkFsRefConditions(fsRef, featureCode); } ll_setRefValue(fsRef, featureCode, value); } public final int getIntArrayValue(IntegerArray array, int i) { return array.get(i); } public final float getFloatArrayValue(FloatArray array, int i) { return array.get(i); } public final String getStringArrayValue(StringArray array, int i) { return array.get(i); } public final FeatureStructure getRefArrayValue(FSArray array, int i) { return array.get(i); } @Override public final int ll_getIntArrayValue(int fsRef, int position) { return getIntArrayValue(((IntegerArray)getFsFromId_checked(fsRef)), position); } @Override public final float ll_getFloatArrayValue(int fsRef, int position) { return getFloatArrayValue(((FloatArray)getFsFromId_checked(fsRef)), position); } @Override public final String ll_getStringArrayValue(int fsRef, int position) { return getStringArrayValue(((StringArray)getFsFromId_checked(fsRef)), position); } @Override public final int ll_getRefArrayValue(int fsRef, int position) { return ((TOP)getRefArrayValue(((FSArray)getFsFromId_checked(fsRef)), position))._id(); } private void throwAccessTypeError(int fsRef, int typeCode) { throw new LowLevelException(LowLevelException.ACCESS_TYPE_ERROR, Integer.valueOf(fsRef), Integer.valueOf(typeCode), getTypeSystemImpl().ll_getTypeForCode(typeCode).getName(), getTypeSystemImpl().ll_getTypeForCode(ll_getFSRefType(fsRef)).getName()); } public final void checkArrayBounds(int fsRef, int pos) { final int arrayLength = ll_getArraySize(fsRef); if ((pos < 0) || (pos >= arrayLength)) { throw new ArrayIndexOutOfBoundsException(pos); // LowLevelException e = new LowLevelException( // LowLevelException.ARRAY_INDEX_OUT_OF_RANGE); // e.addArgument(Integer.toString(pos)); // throw e; } } public final void checkArrayBounds(int arrayLength, int pos, int length) { if ((pos < 0) || (length < 0) || ((pos + length) > arrayLength)) { throw new LowLevelException(LowLevelException.ARRAY_INDEX_LENGTH_OUT_OF_RANGE, Integer.toString(pos), Integer.toString(length)); } } /** * Check that the fsRef is valid. * Check that the fs is featureCode belongs to the fs * Check that the featureCode is one of the features of the domain type of the fsRef * feat could be primitive, string, ref to another feature * * @param fsRef * @param typeCode * @param featureCode */ private final void checkNonArrayConditions(int fsRef, int featureCode) { TOP fs = getFsFromId_checked(fsRef); final TypeImpl domainType = (TypeImpl) fs.getType(); // checkTypeAt(domType, fs); // since the type is from the FS, it's always OK checkFeature(featureCode); // checks that the featureCode is in the range of all feature codes TypeSystemImpl tsi = getTypeSystemImpl(); FeatureImpl fi = tsi.getFeatureForCode_checked(featureCode); checkTypeHasFeature(domainType, fi); // checks that the feature code is one of the features of the type // checkFsRan(fi); } private final void checkFsRefConditions(int fsRef, int featureCode) { TOP fs = getFsFromId_checked(fsRef); checkLowLevelParams(fs, fs._getTypeImpl(), featureCode); // checks type has feature TypeSystemImpl tsi = getTypeSystemImpl(); FeatureImpl fi = tsi.getFeatureForCode_checked(featureCode); checkFsRan(fi); // next not needed because checkFsRan already validates this // checkFsRef(fsRef + this.svd.casMetadata.featureOffset[featureCode]); } // private final void checkArrayConditions(int fsRef, int typeCode, // int position) { // checkTypeSubsumptionAt(fsRef, typeCode); // // skip this next test because // // a) it's done implicitly in the bounds check and // // b) it fails for arrays stored outside of the main heap (e.g., // byteArrays, etc.) // // checkFsRef(getArrayStartAddress(fsRef) + position); // checkArrayBounds(fsRef, position); // } private final void checkPrimitiveArrayConditions(int fsRef, int typeCode, int position) { if (typeCode != ll_getFSRefType(fsRef)) { throwAccessTypeError(fsRef, typeCode); } checkArrayBounds(fsRef, position); } @Override public final int ll_getIntArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, intArrayTypeCode, position); } return ll_getIntArrayValue(fsRef, position); } @Override public float ll_getFloatArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, floatArrayTypeCode, position); } return ll_getFloatArrayValue(fsRef, position); } @Override public String ll_getStringArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, stringArrayTypeCode, position); } return ll_getStringArrayValue(fsRef, position); } @Override public int ll_getRefArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, fsArrayTypeCode, position); } return ll_getRefArrayValue(fsRef, position); } @Override public void ll_setIntArrayValue(int fsRef, int position, int value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, intArrayTypeCode, position); } ll_setIntArrayValue(fsRef, position, value); } @Override public void ll_setFloatArrayValue(int fsRef, int position, float value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, floatArrayTypeCode, position); } ll_setFloatArrayValue(fsRef, position, value); } @Override public void ll_setStringArrayValue(int fsRef, int position, String value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, stringArrayTypeCode, position); } ll_setStringArrayValue(fsRef, position, value); } @Override public void ll_setRefArrayValue(int fsRef, int position, int value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, fsArrayTypeCode, position); } ll_setRefArrayValue(fsRef, position, value); } /* ************************ * Low Level Array Setters * ************************/ @Override public void ll_setIntArrayValue(int fsRef, int position, int value) { IntegerArray array = getFsFromId_checked(fsRef); array.set(position, value); // that set operation does required journaling } @Override public void ll_setFloatArrayValue(int fsRef, int position, float value) { FloatArray array = getFsFromId_checked(fsRef); array.set(position, value); // that set operation does required journaling } @Override public void ll_setStringArrayValue(int fsRef, int position, String value) { StringArray array = getFsFromId_checked(fsRef); array.set(position, value); // that set operation does required journaling } @Override public void ll_setRefArrayValue(int fsRef, int position, int value) { FSArray array = getFsFromId_checked(fsRef); array.set(position, getFsFromId_checked(value)); // that set operation does required journaling } /** * @param fsRef an id for a FS * @return the type code for this FS */ @Override public int ll_getFSRefType(int fsRef) { return getFsFromId_checked(fsRef)._getTypeCode(); } @Override public int ll_getFSRefType(int fsRef, boolean doChecks) { // type code is always valid return ll_getFSRefType(fsRef); } @Override public LowLevelCAS getLowLevelCAS() { return this; } @Override public int size() { throw new UIMARuntimeException(UIMARuntimeException.INTERNAL_ERROR); } /* * (non-Javadoc) * * @see org.apache.uima.cas.admin.CASMgr#getJCasClassLoader() */ @Override public ClassLoader getJCasClassLoader() { return this.svd.jcasClassLoader; } /* * Called to set the overall jcas class loader to use. * * @see org.apache.uima.cas.admin.CASMgr#setJCasClassLoader(java.lang.ClassLoader) */ @Override public void setJCasClassLoader(ClassLoader classLoader) { this.svd.jcasClassLoader = classLoader; } // Internal use only, public for cross package use // Assumes: The JCasClassLoader for a CAS is set up initially when the CAS is // created // and not switched (other than by this code) once it is set. // Callers of this method always code the "restoreClassLoaderUnlockCAS" in // pairs, // protected as needed with try - finally blocks. // // Special handling is needed for CAS Mulipliers - they can modify a cas up to // the point they no longer "own" it. // So the try / finally approach doesn't fit public void switchClassLoaderLockCas(Object userCode) { switchClassLoaderLockCasCL(userCode.getClass().getClassLoader()); } public void switchClassLoaderLockCasCL(ClassLoader newClassLoader) { // lock out CAS functions to which annotator should not have access enableReset(false); svd.switchClassLoader(newClassLoader); } // // internal use, public for cross-package ref // public boolean usingBaseClassLoader() { // return (this.svd.jcasClassLoader == this.svd.previousJCasClassLoader); // } public void restoreClassLoaderUnlockCas() { // unlock CAS functions enableReset(true); // this might be called without the switch ever being called svd.restoreClassLoader(); } @Override public FeatureValuePath createFeatureValuePath(String featureValuePath) throws CASRuntimeException { return FeatureValuePathImpl.getFeaturePath(featureValuePath); } @Override public void setOwner(CasOwner aCasOwner) { CASImpl baseCas = getBaseCAS(); if (baseCas != this) { baseCas.setOwner(aCasOwner); } else { super.setOwner(aCasOwner); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.AbstractCas_ImplBase#release() */ @Override public void release() { CASImpl baseCas = getBaseCAS(); if (baseCas != this) { baseCas.release(); } else { super.release(); } } /* ********************************** * A R R A Y C R E A T I O N ************************************/ @Override public ByteArrayFS createByteArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new ByteArray(this.getJCas(), length); } @Override public BooleanArrayFS createBooleanArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new BooleanArray(this.getJCas(), length); } @Override public ShortArrayFS createShortArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new ShortArray(this.getJCas(), length); } @Override public LongArrayFS createLongArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new LongArray(this.getJCas(), length); } @Override public DoubleArrayFS createDoubleArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new DoubleArray(this.getJCas(), length); } @Override public byte ll_getByteValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getByteValue(getFeatFromCode_checked(featureCode)); } @Override public byte ll_getByteValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getByteValue(fsRef, featureCode); } @Override public boolean ll_getBooleanValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getBooleanValue(getFeatFromCode_checked(featureCode)); } @Override public boolean ll_getBooleanValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getBooleanValue(fsRef, featureCode); } @Override public short ll_getShortValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getShortValue(getFeatFromCode_checked(featureCode)); } @Override public short ll_getShortValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getShortValue(fsRef, featureCode); } // impossible to implement in v3; change callers // public long ll_getLongValue(int offset) { // return this.getLongHeap().getHeapValue(offset); // } @Override public long ll_getLongValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getLongValue(getFeatFromCode_checked(featureCode)); } // public long ll_getLongValueFeatOffset(int fsRef, int offset) { // TOP fs = getFsFromId_checked(fsRef); // return fs.getLongValueOffset(offset); // } @Override public long ll_getLongValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getLongValue(fsRef, featureCode); } @Override public double ll_getDoubleValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getDoubleValue(getFeatFromCode_checked(featureCode)); } // public double ll_getDoubleValueFeatOffset(int fsRef, int offset) { // TOP fs = getFsFromId_checked(fsRef); // return fs.getDoubleValueOffset(offset); // } @Override public double ll_getDoubleValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getDoubleValue(fsRef, featureCode); } @Override public void ll_setBooleanValue(int fsRef, int featureCode, boolean value) { getFsFromId_checked(fsRef).setBooleanValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setBooleanValue(int fsRef, int featureCode, boolean value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setBooleanValue(fsRef, featureCode, value); } @Override public final void ll_setByteValue(int fsRef, int featureCode, byte value) { getFsFromId_checked(fsRef).setByteValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setByteValue(int fsRef, int featureCode, byte value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setByteValue(fsRef, featureCode, value); } @Override public final void ll_setShortValue(int fsRef, int featureCode, short value) { getFsFromId_checked(fsRef).setShortValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setShortValue(int fsRef, int featureCode, short value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setShortValue(fsRef, featureCode, value); } @Override public void ll_setLongValue(int fsRef, int featureCode, long value) { getFsFromId_checked(fsRef).setLongValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setLongValue(int fsRef, int featureCode, long value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setLongValue(fsRef, featureCode, value); } @Override public void ll_setDoubleValue(int fsRef, int featureCode, double value) { getFsFromId_checked(fsRef).setDoubleValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setDoubleValue(int fsRef, int featureCode, double value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setDoubleValue(fsRef, featureCode, value); } @Override public byte ll_getByteArrayValue(int fsRef, int position) { return ((ByteArray) getFsFromId_checked(fsRef)).get(position); } @Override public byte ll_getByteArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getByteArrayValue(fsRef, position); } @Override public boolean ll_getBooleanArrayValue(int fsRef, int position) { return ((BooleanArray) getFsFromId_checked(fsRef)).get(position); } @Override public boolean ll_getBooleanArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getBooleanArrayValue(fsRef, position); } @Override public short ll_getShortArrayValue(int fsRef, int position) { return ((ShortArray) getFsFromId_checked(fsRef)).get(position); } @Override public short ll_getShortArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getShortArrayValue(fsRef, position); } @Override public long ll_getLongArrayValue(int fsRef, int position) { return ((LongArray) getFsFromId_checked(fsRef)).get(position); } @Override public long ll_getLongArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getLongArrayValue(fsRef, position); } @Override public double ll_getDoubleArrayValue(int fsRef, int position) { return ((DoubleArray) getFsFromId_checked(fsRef)).get(position); } @Override public double ll_getDoubleArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getDoubleArrayValue(fsRef, position); } @Override public void ll_setByteArrayValue(int fsRef, int position, byte value) { ((ByteArray) getFsFromId_checked(fsRef)).set(position, value); } @Override public void ll_setByteArrayValue(int fsRef, int position, byte value, boolean doTypeChecks) { ll_setByteArrayValue(fsRef, position, value);} @Override public void ll_setBooleanArrayValue(int fsRef, int position, boolean b) { ((BooleanArray) getFsFromId_checked(fsRef)).set(position, b); } @Override public void ll_setBooleanArrayValue(int fsRef, int position, boolean value, boolean doTypeChecks) { ll_setBooleanArrayValue(fsRef, position, value); } @Override public void ll_setShortArrayValue(int fsRef, int position, short value) { ((ShortArray) getFsFromId_checked(fsRef)).set(position, value); } @Override public void ll_setShortArrayValue(int fsRef, int position, short value, boolean doTypeChecks) { ll_setShortArrayValue(fsRef, position, value); } @Override public void ll_setLongArrayValue(int fsRef, int position, long value) { ((LongArray) getFsFromId_checked(fsRef)).set(position, value); } @Override public void ll_setLongArrayValue(int fsRef, int position, long value, boolean doTypeChecks) { ll_setLongArrayValue(fsRef, position, value); } @Override public void ll_setDoubleArrayValue(int fsRef, int position, double d) { ((DoubleArray) getFsFromId_checked(fsRef)).set(position, d); } @Override public void ll_setDoubleArrayValue(int fsRef, int position, double value, boolean doTypeChecks) { ll_setDoubleArrayValue(fsRef, position, value); } public boolean isAnnotationType(Type t) { return ((TypeImpl)t).isAnnotationType(); } /** * @param t the type code to test * @return true if that type is subsumed by AnnotationBase type */ public boolean isSubtypeOfAnnotationBaseType(int t) { TypeImpl ti = getTypeFromCode(t); return (ti == null) ? false : ti.isAnnotationBaseType(); } public boolean isBaseCas() { return this == getBaseCAS(); } @Override public Annotation createAnnotation(Type type, int begin, int end) { // duplicates a later check // if (this.isBaseCas()) { // // Can't create annotation on base CAS // throw new CASRuntimeException(CASRuntimeException.INVALID_BASE_CAS_METHOD, "createAnnotation(Type, int, int)"); // } Annotation fs = (Annotation) createFS(type); fs.setBegin(begin); fs.setEnd(end); return fs; } public int ll_createAnnotation(int typeCode, int begin, int end) { TOP fs = createAnnotation(getTypeFromCode(typeCode), begin, end); svd.id2fs.put(fs); // to prevent gc from reclaiming return fs._id(); } /** * The generic spec T extends AnnotationFS (rather than AnnotationFS) allows the method * JCasImpl getAnnotationIndex to return Annotation instead of AnnotationFS * @param <T> the Java class associated with the annotation index * @return the annotation index */ @Override public <T extends AnnotationFS> AnnotationIndex<T> getAnnotationIndex() { return (AnnotationIndex<T>) indexRepository.getAnnotationIndex(getTypeSystemImpl().annotType); } /* (non-Javadoc) * @see org.apache.uima.cas.CAS#getAnnotationIndex(org.apache.uima.cas.Type) */ @Override public <T extends AnnotationFS> AnnotationIndex<T> getAnnotationIndex(Type type) throws CASRuntimeException { return (AnnotationIndex<T>) indexRepository.getAnnotationIndex((TypeImpl) type); } /** * @see org.apache.uima.cas.CAS#getAnnotationType() */ @Override public Type getAnnotationType() { return getTypeSystemImpl().annotType; } /** * @see org.apache.uima.cas.CAS#getEndFeature() */ @Override public Feature getEndFeature() { return getTypeSystemImpl().endFeat; } /** * @see org.apache.uima.cas.CAS#getBeginFeature() */ @Override public Feature getBeginFeature() { return getTypeSystemImpl().startFeat; } private <T extends AnnotationFS> T createDocumentAnnotation(int length) { final TypeSystemImpl ts = getTypeSystemImpl(); // Remove any existing document annotations. FSIterator<T> it = this.<T>getAnnotationIndex(ts.docType).iterator(); List<T> list = new ArrayList<T>(); while (it.isValid()) { list.add(it.get()); it.moveToNext(); } for (int i = 0; i < list.size(); i++) { getIndexRepository().removeFS(list.get(i)); } return (T) createDocumentAnnotationNoRemove(length); } private <T extends Annotation> T createDocumentAnnotationNoRemove(int length) { T docAnnot = createDocumentAnnotationNoRemoveNoIndex(length); addFsToIndexes(docAnnot); return docAnnot; } public <T extends Annotation> T createDocumentAnnotationNoRemoveNoIndex(int length) { final TypeSystemImpl ts = getTypeSystemImpl(); AnnotationFS docAnnot = createAnnotation(ts.docType, 0, length); docAnnot.setStringValue(ts.langFeat, CAS.DEFAULT_LANGUAGE_NAME); return (T) docAnnot; } public int ll_createDocumentAnnotation(int length) { final int fsRef = ll_createDocumentAnnotationNoIndex(0, length); ll_getIndexRepository().ll_addFS(fsRef); return fsRef; } public int ll_createDocumentAnnotationNoIndex(int begin, int end) { final TypeSystemImpl ts = getTypeSystemImpl(); int fsRef = ll_createAnnotation(ts.docType.getCode(), begin, end); ll_setStringValue(fsRef, ts.langFeat.getCode(), CAS.DEFAULT_LANGUAGE_NAME); return fsRef; } // For the "built-in" instance of Document Annotation, set the // "end" feature to be the length of the sofa string /** * updates the document annotation (only if the sofa's local string data != null) * setting the end feature to be the length of the sofa string, if any. * creates the document annotation if not present * only works if not in the base cas * */ public void updateDocumentAnnotation() { if (!mySofaIsValid() || this == this.svd.baseCAS) { return; } String newDoc = this.mySofaRef.getLocalStringData(); if (null != newDoc) { Annotation docAnnot = getDocumentAnnotationNoCreate(); if (docAnnot != null) { // use a local instance of the add-back memory because this may be called as a side effect of updating a sofa FSsTobeAddedback tobeAddedback = FSsTobeAddedback.createSingle(); boolean wasRemoved = this.checkForInvalidFeatureSetting( docAnnot, getTypeSystemImpl().endFeat.getCode(), tobeAddedback); docAnnot._setIntValueNfc(endFeatAdjOffset, newDoc.length()); if (wasRemoved) { tobeAddedback.addback(docAnnot); } } else { // not in the index (yet) createDocumentAnnotation(newDoc.length()); } } return; } /** * Generic issue: The returned document annotation could be either an instance of * DocumentAnnotation or a subclass of it, or an instance of Annotation - the Java cover class used for * annotations when JCas is not being used. */ @Override public <T extends AnnotationFS> T getDocumentAnnotation() { T docAnnot = (T) getDocumentAnnotationNoCreate(); if (null == docAnnot) { return (T) createDocumentAnnotationNoRemove(0); } else { return docAnnot; } } public <T extends AnnotationFS> T getDocumentAnnotationNoCreate() { if (this == this.svd.baseCAS) { // base CAS has no document return null; } FSIterator<Annotation> it = getDocAnnotIter(); it.moveToFirst(); // revalidate in case index updated if (it.isValid()) { Annotation r = it.get(); return (T) (inPearContext() ? pearConvert(r) : r); } return null; } private FSIterator<Annotation> getDocAnnotIter() { if (docAnnotIter != null) { return docAnnotIter; } synchronized (this) { if (docAnnotIter == null) { docAnnotIter = this.<Annotation>getAnnotationIndex(getTypeSystemImpl().docType).iterator(); } return docAnnotIter; } } /** * * @return the fs addr of the document annotation found via the index, or 0 if not there */ public int ll_getDocumentAnnotation() { AnnotationFS r = getDocumentAnnotationNoCreate(); return (r == null) ? 0 : r._id(); } @Override public String getDocumentLanguage() { if (this == this.svd.baseCAS) { // base CAS has no document return null; } return getDocumentAnnotation().getStringValue(getTypeSystemImpl().langFeat); } @Override public String getDocumentText() { return this.getSofaDataString(); } @Override public String getSofaDataString() { if (this == this.svd.baseCAS) { // base CAS has no document return null; } return mySofaIsValid() ? mySofaRef.getLocalStringData() : null; } @Override public FeatureStructure getSofaDataArray() { if (this == this.svd.baseCAS) { // base CAS has no Sofa return null; } return mySofaIsValid() ? mySofaRef.getLocalFSData() : null; } @Override public String getSofaDataURI() { if (this == this.svd.baseCAS) { // base CAS has no Sofa return null; } return mySofaIsValid() ? mySofaRef.getSofaURI() : null; } @Override public InputStream getSofaDataStream() { if (this == this.svd.baseCAS) { // base CAS has no Sofa nothin return null; } // return mySofaRef.getSofaDataStream(); // this just goes to the next method return mySofaIsValid() ? this.getSofaDataStream(mySofaRef) : null; } @Override public String getSofaMimeType() { if (this == this.svd.baseCAS) { // base CAS has no Sofa return null; } return mySofaIsValid() ? mySofaRef.getSofaMime() : null; } @Override public Sofa getSofa() { return mySofaRef; } /** * @return the addr of the sofaFS associated with this view, or 0 */ @Override public int ll_getSofa() { return mySofaIsValid() ? mySofaRef._id() : 0; } @Override public String getViewName() { return (this == svd.getViewFromSofaNbr(1)) ? CAS.NAME_DEFAULT_SOFA : mySofaIsValid() ? mySofaRef.getSofaID() : null; } private boolean mySofaIsValid() { return this.mySofaRef != null; } void setDocTextFromDeserializtion(String text) { if (mySofaIsValid()) { Sofa sofa = getSofaRef(); // creates sofa if doesn't already exist sofa.setLocalSofaDataNoDocAnnotUpdate(text); } } @Override public void setDocumentLanguage(String languageCode) { if (this == this.svd.baseCAS) { throw new CASRuntimeException(CASRuntimeException.INVALID_BASE_CAS_METHOD, "setDocumentLanguage(String)"); } Annotation docAnnot = getDocumentAnnotation(); FeatureImpl languageFeature = getTypeSystemImpl().langFeat; languageCode = Language.normalize(languageCode); boolean wasRemoved = this.checkForInvalidFeatureSetting(docAnnot, languageFeature.getCode(), this.getAddbackSingle()); docAnnot.setStringValue(getTypeSystemImpl().langFeat, languageCode); addbackSingleIfWasRemoved(wasRemoved, docAnnot); } private void setSofaThingsMime(Consumer<Sofa> c, String msg) { if (this == this.svd.baseCAS) { throw new CASRuntimeException(CASRuntimeException.INVALID_BASE_CAS_METHOD, msg); } Sofa sofa = getSofaRef(); c.accept(sofa); } @Override public void setDocumentText(String text) { setSofaDataString(text, "text"); } @Override public void setSofaDataString(String text, String mime) throws CASRuntimeException { setSofaThingsMime(sofa -> sofa.setLocalSofaData(text, mime), "setSofaDataString(text, mime)"); } @Override public void setSofaDataArray(FeatureStructure array, String mime) { setSofaThingsMime(sofa -> sofa.setLocalSofaData(array, mime), "setSofaDataArray(FeatureStructure, mime)"); } @Override public void setSofaDataURI(String uri, String mime) throws CASRuntimeException { setSofaThingsMime(sofa -> sofa.setRemoteSofaURI(uri, mime), "setSofaDataURI(String, String)"); } @Override public void setCurrentComponentInfo(ComponentInfo info) { // always store component info in base CAS this.svd.componentInfo = info; } ComponentInfo getCurrentComponentInfo() { return this.svd.componentInfo; } /** * @see org.apache.uima.cas.CAS#addFsToIndexes(FeatureStructure fs) */ @Override public void addFsToIndexes(FeatureStructure fs) { // if (fs instanceof AnnotationBaseFS) { // final CAS sofaView = ((AnnotationBaseFS) fs).getView(); // if (sofaView != this) { // CASRuntimeException e = new CASRuntimeException( // CASRuntimeException.ANNOTATION_IN_WRONG_INDEX, new String[] { fs.toString(), // sofaView.getSofa().getSofaID(), this.getSofa().getSofaID() }); // throw e; // } // } this.indexRepository.addFS(fs); } /** * @see org.apache.uima.cas.CAS#removeFsFromIndexes(FeatureStructure fs) */ @Override public void removeFsFromIndexes(FeatureStructure fs) { this.indexRepository.removeFS(fs); } /** * @param fs the AnnotationBase instance * @return the view associated with this FS where it could be indexed */ public CASImpl getSofaCasView(AnnotationBase fs) { return fs._casView; // Sofa sofa = fs.getSofa(); // // if (null != sofa && sofa != this.getSofa()) { // return (CASImpl) this.getView(sofa.getSofaNum()); // } // // /* Note: sofa == null means annotation created from low-level APIs, without setting sofa feature // * Ignore this for backwards compatibility */ // return this; } @Override public CASImpl ll_getSofaCasView(int id) { return getSofaCasView(getFsFromId_checked(id)); } // public Iterator<CAS> getViewIterator() { // List<CAS> viewList = new ArrayList<CAS>(); // // add initial view if it has no sofa // if (!((CASImpl) getInitialView()).mySofaIsValid()) { // viewList.add(getInitialView()); // } // // add views with Sofas // FSIterator<SofaFS> sofaIter = getSofaIterator(); // while (sofaIter.hasNext()) { // viewList.add(getView(sofaIter.next())); // } // return viewList.iterator(); // } /** * Creates the initial view (without a sofa) if not present * @return the number of views, excluding the base view, including the initial view (even if not initially present or no sofa) */ public int getNumberOfViews() { CASImpl initialView = getInitialView(); // creates one if not existing, w/o sofa int nbrSofas = this.svd.baseCAS.indexRepository.getIndex(CAS.SOFA_INDEX_NAME).size(); return initialView.mySofaIsValid() ? nbrSofas : 1 + nbrSofas; } public int getNumberOfSofas() { return this.svd.baseCAS.indexRepository.getIndex(CAS.SOFA_INDEX_NAME).size(); } /* * (non-Javadoc) * * @see org.apache.uima.cas.CAS#getViewIterator() */ @Override public <T extends CAS> Iterator<T> getViewIterator() { return new Iterator<T>() { final CASImpl initialView = getInitialView(); // creates one if not existing, w/o sofa boolean isInitialView_but_noSofa = !initialView.mySofaIsValid(); // true if has no Sofa in initial view // but is reset to false once iterator moves // off of initial view. // if initial view has a sofa, we just use the // sofa iterator instead. final FSIterator<Sofa> sofaIter = getSofaIterator(); @Override public boolean hasNext() { if (isInitialView_but_noSofa) { return true; } return sofaIter.hasNext(); } @Override public T next() { if (isInitialView_but_noSofa) { isInitialView_but_noSofa = false; // no incr of sofa iterator because it was missing initial view return (T) initialView; } return (T) getView(sofaIter.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * excludes initial view if its sofa is not valid * * @return iterator over all views except the base view */ public Iterator<CASImpl> getViewImplIterator() { return new Iterator<CASImpl>() { final CASImpl initialView = getInitialView(); // creates one if not existing, w/o sofa boolean isInitialView_but_noSofa = !initialView.mySofaIsValid(); // true if has no Sofa in initial view // but is reset to false once iterator moves // off of initial view. // if initial view has a sofa, we just use the // sofa iterator instead. final FSIterator<Sofa> sofaIter = getSofaIterator(); @Override public boolean hasNext() { if (isInitialView_but_noSofa) { // set to false once iterator moves off of first value return true; } return sofaIter.hasNext(); } @Override public CASImpl next() { if (isInitialView_but_noSofa) { isInitialView_but_noSofa = false; // no incr of sofa iterator because it was missing initial view return initialView; } return getView(sofaIter.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * iterate over all views in view order (by view number) * @param processViews */ void forAllViews(Consumer<CASImpl> processViews) { final int numViews = this.getNumberOfViews(); for (int viewNbr = 1; viewNbr <= numViews; viewNbr++) { CASImpl view = (viewNbr == 1) ? getInitialView() : (CASImpl) getView(viewNbr); processViews.accept(view); } // // Iterator<CASImpl> it = getViewImplIterator(); // while (it.hasNext()) { // processViews.accept(it.next()); // } } void forAllSofas(Consumer<Sofa> processSofa) { FSIterator<Sofa> it = getSofaIterator(); while (it.hasNext()) { processSofa.accept(it.nextNvc()); } } /** * Excludes base view's ir, * Includes the initial view's ir only if it has a sofa defined * @param processIr the code to execute */ void forAllIndexRepos(Consumer<FSIndexRepositoryImpl> processIr) { final int numViews = this.getViewCount(); for (int viewNum = 1; viewNum <= numViews; viewNum++) { processIr.accept(this.getSofaIndexRepository(viewNum)); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.CAS#getViewIterator(java.lang.String) */ @Override public Iterator<CAS> getViewIterator(String localViewNamePrefix) { // do sofa mapping for current component String absolutePrefix = null; if (getCurrentComponentInfo() != null) { absolutePrefix = getCurrentComponentInfo().mapToSofaID(localViewNamePrefix); } if (absolutePrefix == null) { absolutePrefix = localViewNamePrefix; } // find Sofas with this prefix List<CAS> viewList = new ArrayList<CAS>(); FSIterator<Sofa> sofaIter = getSofaIterator(); while (sofaIter.hasNext()) { SofaFS sofa = sofaIter.next(); String sofaId = sofa.getSofaID(); if (sofaId.startsWith(absolutePrefix)) { if ((sofaId.length() == absolutePrefix.length()) || (sofaId.charAt(absolutePrefix.length()) == '.')) { viewList.add(getView(sofa)); } } } return viewList.iterator(); } /** * protectIndexes * * Within the scope of protectIndexes, * feature updates are checked, and if found to be a key, and the FS is in a corruptible index, * then the FS is removed from the indexes (in all necessary views) (perhaps multiple times * if the FS was added to the indexes multiple times), and this removal is recorded on * an new instance of FSsTobeReindexed appended to fssTobeAddedback. * * Later, when the protectIndexes is closed, the tobe items are added back to the indexes. */ @Override public AutoCloseableNoException protectIndexes() { FSsTobeAddedback r = FSsTobeAddedback.createMultiple(this); svd.fssTobeAddedback.add(r); return r; } void dropProtectIndexesLevel () { svd.fssTobeAddedback.remove(svd.fssTobeAddedback.size() -1); } /** * This design is to support normal operations where the * addbacks could be nested * It also handles cases where nested ones were inadvertently left open * Three cases: * 1) the addbacks are the last element in the stack * - remove it from the stack * 2) the addbacks are (no longer) in the list * - leave stack alone * 3) the addbacks are in the list but not at the end * - remove it and all later ones * * If the "withProtectedindexes" approach is used, it guarantees proper * nesting, but the Runnable can't throw checked exceptions. * * You can do your own try-finally blocks (or use the try with resources * form in Java 8 to do a similar thing with no restrictions on what the * body can contain. * * @param addbacks */ void addbackModifiedFSs (FSsTobeAddedback addbacks) { final List<FSsTobeAddedback> listOfAddbackInfos = svd.fssTobeAddedback; if (listOfAddbackInfos.get(listOfAddbackInfos.size() - 1) == addbacks) { listOfAddbackInfos.remove(listOfAddbackInfos.size()); } else { int pos = listOfAddbackInfos.indexOf(addbacks); if (pos >= 0) { for (int i = listOfAddbackInfos.size() - 1; i > pos; i--) { FSsTobeAddedback toAddBack = listOfAddbackInfos.remove(i); toAddBack.addback(); } } } addbacks.addback(); } /** * * @param r an inner block of code to be run with */ @Override public void protectIndexes(Runnable r) { AutoCloseable addbacks = protectIndexes(); try { r.run(); } finally { addbackModifiedFSs((FSsTobeAddedback) addbacks); } } /** * The current implementation only supports 1 marker call per * CAS. Subsequent calls will throw an error. * * The design is intended to support (at some future point) * multiple markers; for this to work, the intent is to * extend the MarkerImpl to keep track of indexes into * these IntVectors specifying where that marker starts/ends. */ @Override public Marker createMarker() { if (!this.svd.flushEnabled) { throw new CASAdminException(CASAdminException.FLUSH_DISABLED); } this.svd.trackingMark = new MarkerImpl(this.getLastUsedFsId() + 1, this); if (this.svd.modifiedPreexistingFSs == null) { this.svd.modifiedPreexistingFSs = new IdentityHashMap<>(); } if (this.svd.modifiedPreexistingFSs.size() > 0) { errorMultipleMarkers(); } if (this.svd.trackingMarkList == null) { this.svd.trackingMarkList = new ArrayList<MarkerImpl>(); } else {errorMultipleMarkers();} this.svd.trackingMarkList.add(this.svd.trackingMark); return this.svd.trackingMark; } private void errorMultipleMarkers() { throw new CASRuntimeException(CASRuntimeException.MULTIPLE_CREATE_MARKER); } // made public https://issues.apache.org/jira/browse/UIMA-2478 public MarkerImpl getCurrentMark() { return this.svd.trackingMark; } /** * * @return an array of FsChange items, one per modified Fs, * sorted in order of fs._id */ FsChange[] getModifiedFSList() { final Map<TOP, FsChange> mods = this.svd.modifiedPreexistingFSs; FsChange[] r = mods.values().toArray(new FsChange[mods.size()]); Arrays.sort(r, 0, mods.size(), (c1, c2) -> Integer.compare(c1.fs._id, c2.fs._id)); return r; } boolean isInModifiedPreexisting(TOP fs) { return this.svd.modifiedPreexistingFSs.containsKey(fs); } @Override public String toString() { String sofa = (mySofaRef == null) ? (isBaseCas() ? "Base CAS" : "_InitialView or no Sofa") : mySofaRef.getSofaID(); // (mySofaRef == 0) ? "no Sofa" : return this.getClass().getSimpleName() + ":" + getCasId() + "[view: " + sofa + "]"; } int getCasResets() { return svd.casResets.get(); } int getCasId() { return svd.casId; } final public int getNextFsId(TOP fs) { return svd.getNextFsId(fs); } public void adjustLastFsV2size(int arrayLength) { svd.lastFsV2Size += 1 + arrayLength; // 1 is for array length value } /** * Test case use * @param fss the FSs to include in the id 2 fs map */ public void setId2FSs(FeatureStructure ... fss) { for (FeatureStructure fs : fss) { if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally((TOP)fs); } else { svd.id2fs.put((TOP)fs); } } } // Not currently used // public Int2ObjHashMap<TOP> getId2FSs() { // return svd.id2fs.getId2fs(); // } // final private int getNextFsId() { // return ++ svd.fsIdGenerator; // } final public int getLastUsedFsId() { return svd.fsIdGenerator; } /** * Call this to capture the current value of fsIdGenerator and make it * available to other threads. * * Must be called on a thread that has been synchronized with the thread used for creating FSs for this CAS. */ final public void captureLastFsIdForOtherThread() { svd.fsIdLastValue.set(svd.fsIdGenerator); } public <T extends TOP> T getFsFromId(int id) { return (T) this.svd.id2fs.get(id); } // /** // * plus means all reachable, plus maybe others not reachable but not yet gc'd // * @param action - // */ // public void walkReachablePlusFSsSorted(Consumer<TOP> action) { // this.svd.id2fs.walkReachablePlusFSsSorted(action); // } // /** // * called for delta serialization - walks just the new items above the line // * @param action - // * @param fromId - the id of the first item to walk from // */ // public void walkReachablePlusFSsSorted(Consumer<TOP> action, int fromId) { // this.svd.id2fs.walkReachablePlueFSsSorted(action, fromId); // } /** * find all of the FSs via the indexes plus what's reachable. * sort into order by id, * * Apply the action to those * Return the list of sorted FSs * * @param action_filtered action to perform on each item after filtering * @param mark null or the mark * @param includeFilter null or a filter (exclude items not in other type system) * @param typeMapper null or how to map to other type system, used to skip things missing in other type system * @return sorted list of all found items (ignoring mark) */ public List<TOP> walkReachablePlusFSsSorted( Consumer<TOP> action_filtered, MarkerImpl mark, Predicate<TOP> includeFilter, CasTypeSystemMapper typeMapper) { List<TOP> all = new AllFSs(this, mark, includeFilter, typeMapper).getAllFSsAllViews_sofas_reachable().getAllFSsSorted(); List<TOP> filtered = filterAboveMark(all, mark); for (TOP fs : filtered) { action_filtered.accept(fs); } return all; } static List<TOP> filterAboveMark(List<TOP> all, MarkerImpl mark) { if (null == mark) { return all; } int c = Collections.binarySearch(all, TOP._createSearchKey(mark.nextFSId), (fs1, fs2) -> Integer.compare(fs1._id, fs2._id)); if (c < 0) { c = (-c) - 1; } return all.subList(c, all.size()); } // /** // * Get the Java class corresponding to a particular type // * Only valid after type system commit // * // * @param type // * @return // */ // public <T extends FeatureStructure> Class<T> getClass4Type(Type type) { // TypeSystemImpl tsi = getTypeSystemImpl(); // if (!tsi.isCommitted()) { // throw new CASRuntimeException(CASRuntimeException.GET_CLASS_FOR_TYPE_BEFORE_TS_COMMIT); // } // // } public final static boolean isSameCAS(CAS c1, CAS c2) { CASImpl ci1 = (CASImpl) c1.getLowLevelCAS(); CASImpl ci2 = (CASImpl) c2.getLowLevelCAS(); return ci1.getBaseCAS() == ci2.getBaseCAS(); } public boolean isInCAS(FeatureStructure fs) { return ((TOP)fs)._casView.getBaseCAS() == this.getBaseCAS(); } // /** // * // * @param typecode - // * @return Object that can be cast to either a 2 or 3 arg createFs functional interface // * FsGenerator or FsGeneratorArray // */ // private Object getFsGenerator(int typecode) { // return getTypeSystemImpl().getGenerator(typecode); // } public final void checkArrayPreconditions(int len) throws CASRuntimeException { // Check array size. if (len < 0) { throw new CASRuntimeException(CASRuntimeException.ILLEGAL_ARRAY_SIZE); } } public EmptyFSList emptyFSList() { if (null == svd.emptyFSList) { svd.emptyFSList = new EmptyFSList(getTypeSystemImpl().fsEListType, this); } return svd.emptyFSList; } /* * @see org.apache.uima.cas.CAS#emptyFloatList() */ public EmptyFloatList emptyFloatList() { if (null == svd.emptyFloatList) { svd.emptyFloatList = new EmptyFloatList(getTypeSystemImpl().floatEListType, this); } return svd.emptyFloatList; } public EmptyIntegerList emptyIntegerList() { if (null == svd.emptyIntegerList) { svd.emptyIntegerList = new EmptyIntegerList(getTypeSystemImpl().intEListType, this); } return svd.emptyIntegerList; } public EmptyStringList emptyStringList() { if (null == svd.emptyStringList) { svd.emptyStringList = new EmptyStringList(getTypeSystemImpl().stringEListType, this); } return svd.emptyStringList; } public CommonArrayFS emptyArray(Type type) { switch (((TypeImpl)type).getCode()) { case TypeSystemConstants.booleanArrayTypeCode : return emptyBooleanArray(); case TypeSystemConstants.byteArrayTypeCode : return emptyByteArray(); case TypeSystemConstants.shortArrayTypeCode : return emptyShortArray(); case TypeSystemConstants.intArrayTypeCode : return emptyIntegerArray(); case TypeSystemConstants.floatArrayTypeCode : return emptyFloatArray(); case TypeSystemConstants.longArrayTypeCode : return emptyLongArray(); case TypeSystemConstants.doubleArrayTypeCode : return emptyDoubleArray(); case TypeSystemConstants.stringArrayTypeCode : return emptyStringArray(); default: // TypeSystemConstants.fsArrayTypeCode or any other type return emptyFSArray(); } } public FloatArray emptyFloatArray() { if (null == svd.emptyFloatArray) { svd.emptyFloatArray = new FloatArray(this.getJCas(), 0); } return svd.emptyFloatArray; } public FSArray emptyFSArray() { if (null == svd.emptyFSArray) { svd.emptyFSArray = new FSArray(this.getJCas(), 0); } return svd.emptyFSArray; } public IntegerArray emptyIntegerArray() { if (null == svd.emptyIntegerArray) { svd.emptyIntegerArray = new IntegerArray(this.getJCas(), 0); } return svd.emptyIntegerArray; } public StringArray emptyStringArray() { if (null == svd.emptyStringArray) { svd.emptyStringArray = new StringArray(this.getJCas(), 0); } return svd.emptyStringArray; } public DoubleArray emptyDoubleArray() { if (null == svd.emptyDoubleArray) { svd.emptyDoubleArray = new DoubleArray(this.getJCas(), 0); } return svd.emptyDoubleArray; } public LongArray emptyLongArray() { if (null == svd.emptyLongArray) { svd.emptyLongArray = new LongArray(this.getJCas(), 0); } return svd.emptyLongArray; } public ShortArray emptyShortArray() { if (null == svd.emptyShortArray) { svd.emptyShortArray = new ShortArray(this.getJCas(), 0); } return svd.emptyShortArray; } public ByteArray emptyByteArray() { if (null == svd.emptyByteArray) { svd.emptyByteArray = new ByteArray(this.getJCas(), 0); } return svd.emptyByteArray; } public BooleanArray emptyBooleanArray() { if (null == svd.emptyBooleanArray) { svd.emptyBooleanArray = new BooleanArray(this.getJCas(), 0); } return svd.emptyBooleanArray; } /** * @param rangeCode special codes for serialization use only * @return the empty list (shared) corresponding to the type */ public EmptyList emptyList(int rangeCode) { return (rangeCode == CasSerializerSupport.TYPE_CLASS_INTLIST) ? emptyIntegerList() : (rangeCode == CasSerializerSupport.TYPE_CLASS_FLOATLIST) ? emptyFloatList() : (rangeCode == CasSerializerSupport.TYPE_CLASS_STRINGLIST) ? emptyStringList() : emptyFSList(); } /** * Get an empty list from the type code of a list * @param typeCode - * @return - */ public EmptyList emptyListFromTypeCode(int typeCode) { switch (typeCode) { case fsListTypeCode: case fsEListTypeCode: case fsNeListTypeCode: return emptyFSList(); case floatListTypeCode: case floatEListTypeCode: case floatNeListTypeCode: return emptyFloatList(); case intListTypeCode: case intEListTypeCode: case intNeListTypeCode: return emptyIntegerList(); case stringListTypeCode: case stringEListTypeCode: case stringNeListTypeCode: return emptyStringList(); default: throw new IllegalArgumentException(); } } // /** // * Copies a feature, from one fs to another // * FSs may belong to different CASes, but must have the same type system // * Features must have compatible ranges // * The target must not be indexed // * The target must be a "new" (above the "mark") FS // * @param fsSrc source FS // * @param fi Feature to copy // * @param fsTgt target FS // */ // public static void copyFeature(TOP fsSrc, FeatureImpl fi, TOP fsTgt) { // if (!copyFeatureExceptFsRef(fsSrc, fi, fsTgt, fi)) { // if (!fi.isAnnotBaseSofaRef) { // fsTgt._setFeatureValueNcNj(fi, fsSrc._getFeatureValueNc(fi)); // } // } // } /** * Copies a feature from one fs to another * FSs may be in different type systems * Doesn't copy a feature ref, but instead returns false. * This is because feature refs can't cross CASes * @param fsSrc source FS * @param fiSrc feature in source to copy * @param fsTgt target FS * @param fiTgt feature in target to set * @return false if feature is an fsRef */ public static boolean copyFeatureExceptFsRef(TOP fsSrc, FeatureImpl fiSrc, TOP fsTgt, FeatureImpl fiTgt) { switch (fiSrc.getRangeImpl().getCode()) { case booleanTypeCode : fsTgt._setBooleanValueNcNj( fiTgt, fsSrc._getBooleanValueNc( fiSrc)); break; case byteTypeCode : fsTgt._setByteValueNcNj( fiTgt, fsSrc._getByteValueNc( fiSrc)); break; case shortTypeCode : fsTgt._setShortValueNcNj( fiTgt, fsSrc._getShortValueNc( fiSrc)); break; case intTypeCode : fsTgt._setIntValueNcNj( fiTgt, fsSrc._getIntValueNc( fiSrc)); break; case longTypeCode : fsTgt._setLongValueNcNj( fiTgt, fsSrc._getLongValueNc( fiSrc)); break; case floatTypeCode : fsTgt._setFloatValueNcNj( fiTgt, fsSrc._getFloatValueNc( fiSrc)); break; case doubleTypeCode : fsTgt._setDoubleValueNcNj( fiTgt, fsSrc._getDoubleValueNc( fiSrc)); break; case stringTypeCode : fsTgt._setStringValueNcNj( fiTgt, fsSrc._getStringValueNc( fiSrc)); break; // case javaObjectTypeCode : fsTgt._setJavaObjectValueNcNj(fiTgt, fsSrc.getJavaObjectValue(fiSrc)); break; // skip setting sofaRef - it's final and can't be set default: if (fiSrc.getRangeImpl().isStringSubtype()) { fsTgt._setStringValueNcNj( fiTgt, fsSrc._getStringValueNc( fiSrc)); break; // does substring range check } return false; } // end of switch return true; } public static CommonArrayFS copyArray(TOP srcArray) { CommonArrayFS srcCA = (CommonArrayFS) srcArray; CommonArrayFS copy = (CommonArrayFS) srcArray._casView.createArray(srcArray._getTypeImpl(), srcCA.size()); copy.copyValuesFrom(srcCA); return copy; } public BinaryCasSerDes getBinaryCasSerDes() { return svd.bcsd; } /** * @return the saved CommonSerDesSequential info */ CommonSerDesSequential getCsds() { return svd.csds; } void setCsds(CommonSerDesSequential csds) { svd.csds = csds; } CommonSerDesSequential newCsds() { return svd.csds = new CommonSerDesSequential(this.getBaseCAS()); } /** * A space-freeing optimization for use cases where (multiple) delta CASes are being deserialized into this CAS and merged. */ public void deltaMergesComplete() { svd.csds = null; } /****************************************** * PEAR support * Don't modify the type system because it is in use on multiple threads * * Handling of id2fs for low level APIs: * FSs in id2fs map are the outer non-pear ones * Any gets do pear conversion if needed. * ******************************************/ /** * Convert base FS to Pear equivalent * 3 cases: * 1) no trampoline needed, no conversion, return the original fs * 2) trampoline already exists - return that one * 3) create new trampoline * @param aFs * @return */ static <T extends FeatureStructure> T pearConvert(T aFs) { if (null == aFs) { return null; } final TOP fs = (TOP) aFs; final CASImpl view = fs._casView; final TypeImpl ti = fs._getTypeImpl(); final FsGenerator3 generator = view.svd.generators[ti.getCode()]; if (null == generator) { return aFs; } return (T) view.pearConvert(fs, generator); } /** * Inner method - after determining there is a generator * First see if already have generated the pear version, and if so, * use that. * Otherwise, create the pear version and save in trampoline table * @param fs * @param g * @return */ private TOP pearConvert(TOP fs, FsGenerator3 g) { return svd.id2tramp.putIfAbsent(fs._id, k -> { svd.reuseId = k; // create new FS using base FS's ID pearBaseFs = fs; TOP r; // createFS below is modified because of pearBaseFs non-null to // "share" the int and data arrays try { r = g.createFS(fs._getTypeImpl(), this); } finally { svd.reuseId = 0; pearBaseFs = null; } assert r != null; if (r instanceof UimaSerializable) { throw new UnsupportedOperationException( "Pears with Alternate implementations of JCas classes implementing UimaSerializable not supported."); // ((UimaSerializable) fs)._save_to_cas_data(); // updates in r too // ((UimaSerializable) r)._init_from_cas_data(); } return r; }); } /** * Given a trampoline FS, return the corresponding base Fs * Supports adding Fs (which must be a non-trampoline version) to indexes * @param fs trampoline fs * @return the corresponding base fs */ <T extends TOP> T getBaseFsFromTrampoline(T fs) { TOP r = svd.id2base.get(fs._id); assert r != null; return (T) r; } /* ***************************************** * DEBUGGING and TRACING ******************************************/ public void traceFSCreate(FeatureStructureImplC fs) { StringBuilder b = svd.traceFScreationSb; if (b.length() > 0) { traceFSflush(); } // normally commented-out for matching with v2 // // mark annotations created by subiterator // if (fs._getTypeCode() == TypeSystemConstants.annotTypeCode) { // StackTraceElement[] stktr = Thread.currentThread().getStackTrace(); // if (stktr.length > 7 && stktr[6].getClassName().equals("org.apache.uima.cas.impl.Subiterator")) { // b.append('*'); // } // } svd.id2addr.add(svd.nextId2Addr); svd.nextId2Addr += fs._getTypeImpl().getFsSpaceReq((TOP)fs); traceFSfs(fs); svd.traceFSisCreate = true; if (fs._getTypeImpl().isArray()) { b.append(" l:").append(((CommonArrayFS)fs).size()); } } void traceFSfs(FeatureStructureImplC fs) { StringBuilder b = svd.traceFScreationSb; svd.traceFSid = fs._id; b.append("c:").append(String.format("%-3d", getCasId())); String viewName = fs._casView.getViewName(); if (null == viewName) { viewName = "base"; } b.append(" v:").append(Misc.elide(viewName, 8)); b.append(" i:").append(String.format("%-5s", geti2addr(fs._id))); b.append(" t:").append(Misc.elide(fs._getTypeImpl().getShortName(), 10)); } void traceIndexMod(boolean isAdd, TOP fs, boolean isAddbackOrSkipBag) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append(isAdd ? (isAddbackOrSkipBag ? "abk_idx " : "add_idx ") : (isAddbackOrSkipBag ? "rmv_auto_idx " : "rmv_norm_idx ")); // b.append(fs.toString()); b.append(fs._getTypeImpl().getShortName()).append(":").append(fs._id); if (fs instanceof Annotation) { Annotation ann = (Annotation) fs; b.append(" begin: ").append(ann.getBegin()); b.append(" end: ").append(ann.getEnd()); b.append(" txt: \"").append(Misc.elide(ann.getCoveredText(), 10)).append("\""); } traceOut.println(b); } void traceCowCopy(FsIndex_singletype<?> index) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append("cow-copy:"); b.append(" i: ").append(index); traceOut.println(b); } void traceCowCopyUse(FsIndex_singletype<?> index) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append("cow-copy-used:"); b.append(" i: ").append(index); traceOut.println(b); } void traceCowReinit(String kind, FsIndex_singletype<?> index) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append("cow-redo: "); b.append(kind); b.append(" i: ").append(index); b.append(" c: "); b.append(Misc.getCaller()); traceOut.println(b); } /** only used for tracing, enables tracing 2 slots for long/double */ private FeatureImpl prevFi; void traceFSfeat(FeatureStructureImplC fs, FeatureImpl fi, Object v) { //debug FeatureImpl originalFi = fi; StringBuilder b = svd.traceFScreationSb; assert (b.length() > 0); if (fs._id != svd.traceFSid) { traceFSfeatUpdate(fs); } if (fi == null) { // happens on 2nd setInt call from cas copier copyfeatures for Long / Double switch(prevFi.getSlotKind()) { case Slot_DoubleRef: v = fs._getDoubleValueNc(prevFi); break; // correct double and long case Slot_LongRef: v = fs._getLongValueNc(prevFi); break; // correct double and long default: Misc.internalError(); } fi = prevFi; prevFi = null; } else { prevFi = fi; } String fn = fi.getShortName(); // correct calls done by cas copier fast loop if (fi.getSlotKind() == SlotKind.Slot_DoubleRef) { if (v instanceof Integer) { return; // wait till the next part is traced } else if (v instanceof Long) { v = CASImpl.long2double((long)v); } } if (fi.getSlotKind() == SlotKind.Slot_LongRef && (v instanceof Integer)) { return; // output done on the next int call } String fv = getTraceRepOfObj(fi, v); // if (geti2addr(fs._id).equals("79") && // fn.equals("sofa")) { // new Throwable().printStackTrace(traceOut); // } // // debug // if (fn.equals("lemma") && // fv.startsWith("Lemma:") && // debug1cnt < 2) { // debug1cnt ++; // traceOut.println("setting lemma feat:"); // new Throwable().printStackTrace(traceOut); // } // debug // if (fs._getTypeImpl().getShortName().equals("Passage") && // "score".equals(fn) && // debug2cnt < 5) { // debug2cnt++; // traceOut.println("setting score feat in Passage"); // new Throwable().printStackTrace(traceOut); // } // debug int i_v = Math.max(0, 10 - fn.length()); int i_n = Math.max(0, 10 - fv.length()); fn = Misc.elide(fn, 10 + i_n, false); fv = Misc.elide(fv, 10 + i_v, false); // debug // if (!svd.traceFSisCreate && fn.equals("uninf.dWord") && fv.equals("XsgTokens")) { // traceOut.println("debug uninf.dWord:XsgTokens: " + Misc.getCallers(3, 10)); // } b.append(' ').append(Misc.elide(fn + ':' + fv, 21)); // value of a feature: // - "null" or // - if FS: type:id (converted to addr) // - v.toString() } private static int debug2cnt = 0; /** * @param v * @return value of the feature: * "null" or if FS: type:id (converted to addr) or v.toString() * Note: white space in strings converted to "_' characters */ private String getTraceRepOfObj(FeatureImpl fi, Object v) { if (v instanceof TOP) { TOP fs = (TOP) v; return Misc.elide(fs.getType().getShortName(), 5, false) + ':' + geti2addr(fs._id); } if (v == null) return "null"; if (v instanceof String) { String s = Misc.elide((String) v, 50, false); return Misc.replaceWhiteSpace(s, "_"); } if (v instanceof Integer) { int iv = (int) v; switch (fi.getSlotKind()) { case Slot_Boolean: return (iv == 1) ? "true" : "false"; case Slot_Byte: case Slot_Short: case Slot_Int: return Integer.toString(iv); case Slot_Float: return Float.toString(int2float(iv)); } } if (v instanceof Long) { long vl = (long) v; return (fi.getSlotKind() == SlotKind.Slot_DoubleRef) ? Double.toString(long2double(vl)) : Long.toString(vl); } return Misc.replaceWhiteSpace(v.toString(), "_"); } private String geti2addr(int id) { if (id >= svd.id2addr.size()) { return Integer.toString(id) + '!'; } return Integer.toString(svd.id2addr.get(id)); } void traceFSfeatUpdate(FeatureStructureImplC fs) { traceFSflush(); traceFSfs(fs); svd.traceFSisCreate = false; } public StringBuilder traceFSflush() { if (!traceFSs) return null; StringBuilder b = svd.traceFScreationSb; if (b.length() > 0) { traceOut.println((svd.traceFSisCreate ? "cr: " : "up: ") + b); b.setLength(0); svd.traceFSisCreate = false; } return b; } private static class MeasureSwitchType { TypeImpl oldType; TypeImpl newType; String oldJCasClassName; String newJCasClassName; int count = 0; boolean newSubsumesOld; boolean oldSubsumesNew; long scantime = 0; MeasureSwitchType(TypeImpl oldType, TypeImpl newType) { this.oldType = oldType; this.oldJCasClassName = oldType.getJavaClass().getName(); this.newType = newType; this.newJCasClassName = newType.getJavaClass().getName(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((newJCasClassName == null) ? 0 : newJCasClassName.hashCode()); result = prime * result + ((newType == null) ? 0 : newType.hashCode()); result = prime * result + ((oldJCasClassName == null) ? 0 : oldJCasClassName.hashCode()); result = prime * result + ((oldType == null) ? 0 : oldType.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof MeasureSwitchType)) { return false; } MeasureSwitchType other = (MeasureSwitchType) obj; if (newJCasClassName == null) { if (other.newJCasClassName != null) { return false; } } else if (!newJCasClassName.equals(other.newJCasClassName)) { return false; } if (newType == null) { if (other.newType != null) { return false; } } else if (!newType.equals(other.newType)) { return false; } if (oldJCasClassName == null) { if (other.oldJCasClassName != null) { return false; } } else if (!oldJCasClassName.equals(other.oldJCasClassName)) { return false; } if (oldType == null) { if (other.oldType != null) { return false; } } else if (!oldType.equals(other.oldType)) { return false; } return true; } } private static final Map<MeasureSwitchType, MeasureSwitchType> measureSwitches = new HashMap<>(); static { if (MEASURE_SETINT) { Runtime.getRuntime().addShutdownHook(new Thread(null, () -> { System.out.println("debug Switch Types dump, # entries: " + measureSwitches.size()); int s1 = 0, s2 = 0, s3 = 0; for (MeasureSwitchType mst : measureSwitches.keySet()) { s1 = Math.max(s1, mst.oldType.getName().length()); s2 = Math.max(s2, mst.newType.getName().length()); s3 = Math.max(s3, mst.oldJCasClassName.length()); } for (MeasureSwitchType mst : measureSwitches.keySet()) { System.out.format("count: %,6d scantime = %,7d ms, subsumes: %s %s, type: %-" + s1 + "s newType: %-" + s2 + "s, cl: %-" + s3 + "s, newCl: %s%n", mst.count, mst.scantime / 1000000, mst.newSubsumesOld ? "n>o" : " ", mst.oldSubsumesNew ? "o>w" : " ", mst.oldType.getName(), mst.newType.getName(), mst.oldJCasClassName, mst.newJCasClassName); } // if (traceFSs) { // System.err.println("debug closing traceFSs output"); // traceOut.close(); // } }, "Dump SwitchTypes")); } // this is definitely needed if (traceFSs) { Runtime.getRuntime().addShutdownHook(new Thread(null, () -> { System.out.println("closing traceOut"); traceOut.close(); }, "close trace output")); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.admin.CASMgr#setCAS(org.apache.uima.cas.CAS) * Internal use Never called Kept because it's in the interface. */ @Override @Deprecated public void setCAS(CAS cas) {} /** * @return true if in Pear context, or external context outside AnalysisEngine having a UIMA Extension class loader * e.g., if calling a call-back routine loaded outside the AE. */ boolean inPearContext() { return svd.previousJCasClassLoader != null; } /** * Pear context suspended while creating a base version, when we need to create a new FS * (we need to create both the base and the trampoline version) */ private void suspendPearContext() { svd.suspendPreviousJCasClassLoader = svd.previousJCasClassLoader; svd.previousJCasClassLoader = null; } private void restorePearContext() { svd.previousJCasClassLoader = svd.suspendPreviousJCasClassLoader; } /** * * @return the initial heap size specified or defaulted */ public int getInitialHeapSize() { return this.svd.initialHeapSize; } // backwards compatibility - reinit calls // just the public apis /** * Deserializer for Java-object serialized instance of CASSerializer * Used by Soap * @param ser - The instance to convert back to a CAS */ public void reinit(CASSerializer ser) { svd.bcsd.reinit(ser); } /** * Deserializer for CASCompleteSerializer instances - includes type system and index definitions * Never delta * @param casCompSer - */ public void reinit(CASCompleteSerializer casCompSer) { svd.bcsd.reinit(casCompSer); } /** * --------------------------------------------------------------------- * see Blob Format in CASSerializer * * This reads in and deserializes CAS data from a stream. Byte swapping may be * needed if the blob is from C++ -- C++ blob serialization writes data in * native byte order. * * Supports delta deserialization. For that, the the csds from the serialization event must be used. * * @param istream - * @return - the format of the input stream detected * @throws CASRuntimeException wraps IOException */ public SerialFormat reinit(InputStream istream) throws CASRuntimeException { return svd.bcsd.reinit(istream); } void maybeHoldOntoFS(FeatureStructureImplC fs) { if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally((TOP)fs); } } public void swapInPearVersion(Object[] a) { if (!inPearContext()) { return; } for (int i = 0; i < a.length; i++) { Object ao = a[i]; if (ao instanceof TOP) { a[i] = pearConvert((TOP) ao); } } } public Collection<?> collectNonPearVersions(Collection<?> c) { if (c.size() == 0 || !inPearContext()) { return c; } ArrayList<Object> items = new ArrayList<>(c.size()); for (Object o : c) { if (o instanceof TOP) { items.add(pearConvert((TOP) o)); } } return items; } public <T> Spliterator<T> makePearAware(Spliterator<T> baseSi) { if (!inPearContext()) { return baseSi; } return new Spliterator<T>() { @Override public boolean tryAdvance(Consumer<? super T> action) { return baseSi.tryAdvance(item -> action.accept( (item instanceof TOP) ? (T) pearConvert((TOP)item) : item)); } @Override public Spliterator<T> trySplit() { return baseSi.trySplit(); } @Override public long estimateSize() { return baseSi.estimateSize(); } @Override public int characteristics() { return baseSi.characteristics(); } }; } // int allocIntData(int sz) { // // if (sz > INT_DATA_FOR_ALLOC_SIZE / 4) { // returnIntDataForAlloc = new int[sz]; // return 0; // } // // if (sz + nextIntDataOffsetForAlloc > INT_DATA_FOR_ALLOC_SIZE) { // // too large to fit, alloc a new one // currentIntDataForAlloc = new int[INT_DATA_FOR_ALLOC_SIZE]; // nextIntDataOffsetForAlloc = 0; // } // int r = nextIntDataOffsetForAlloc; // nextIntDataOffsetForAlloc += sz; // returnIntDataForAlloc = currentIntDataForAlloc; // return r; // } // // int[] getReturnIntDataForAlloc() { // return returnIntDataForAlloc; // } // // int allocRefData(int sz) { // // if (sz > REF_DATA_FOR_ALLOC_SIZE / 4) { // returnRefDataForAlloc = new Object[sz]; // return 0; // } // // if (sz + nextRefDataOffsetForAlloc > REF_DATA_FOR_ALLOC_SIZE) { // // too large to fit, alloc a new one // currentRefDataForAlloc = new Object[REF_DATA_FOR_ALLOC_SIZE]; // nextRefDataOffsetForAlloc = 0; // } // int r = nextRefDataOffsetForAlloc; // nextRefDataOffsetForAlloc += sz; // returnRefDataForAlloc = currentRefDataForAlloc; // return r; // } // // Object[] getReturnRefDataForAlloc() { // return returnRefDataForAlloc; // } }
uimaj-core/src/main/java/org/apache/uima/cas/impl/CASImpl.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.uima.cas.impl; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URL; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.Spliterator; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Predicate; import org.apache.uima.UIMAFramework; import org.apache.uima.UIMARuntimeException; import org.apache.uima.UimaSerializable; import org.apache.uima.cas.AbstractCas_ImplBase; import org.apache.uima.cas.ArrayFS; import org.apache.uima.cas.BooleanArrayFS; import org.apache.uima.cas.ByteArrayFS; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.cas.CASRuntimeException; import org.apache.uima.cas.CasOwner; import org.apache.uima.cas.CommonArrayFS; import org.apache.uima.cas.ComponentInfo; import org.apache.uima.cas.ConstraintFactory; import org.apache.uima.cas.DoubleArrayFS; import org.apache.uima.cas.FSIndex; import org.apache.uima.cas.FSIndexRepository; import org.apache.uima.cas.FSIterator; import org.apache.uima.cas.FSMatchConstraint; import org.apache.uima.cas.Feature; import org.apache.uima.cas.FeaturePath; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.FeatureValuePath; import org.apache.uima.cas.FloatArrayFS; import org.apache.uima.cas.IntArrayFS; import org.apache.uima.cas.LongArrayFS; import org.apache.uima.cas.Marker; import org.apache.uima.cas.SerialFormat; import org.apache.uima.cas.ShortArrayFS; import org.apache.uima.cas.SofaFS; import org.apache.uima.cas.SofaID; import org.apache.uima.cas.StringArrayFS; import org.apache.uima.cas.Type; import org.apache.uima.cas.TypeSystem; import org.apache.uima.cas.admin.CASAdminException; import org.apache.uima.cas.admin.CASFactory; import org.apache.uima.cas.admin.CASMgr; import org.apache.uima.cas.admin.FSIndexComparator; import org.apache.uima.cas.admin.FSIndexRepositoryMgr; import org.apache.uima.cas.admin.TypeSystemMgr; import org.apache.uima.cas.impl.FSsTobeAddedback.FSsTobeAddedbackSingle; import org.apache.uima.cas.impl.SlotKinds.SlotKind; import org.apache.uima.cas.text.AnnotationFS; import org.apache.uima.cas.text.AnnotationIndex; import org.apache.uima.cas.text.Language; import org.apache.uima.internal.util.IntVector; import org.apache.uima.internal.util.Misc; import org.apache.uima.internal.util.PositiveIntSet; import org.apache.uima.internal.util.PositiveIntSet_impl; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.cas.AnnotationBase; import org.apache.uima.jcas.cas.BooleanArray; import org.apache.uima.jcas.cas.ByteArray; import org.apache.uima.jcas.cas.DoubleArray; import org.apache.uima.jcas.cas.EmptyFSList; import org.apache.uima.jcas.cas.EmptyFloatList; import org.apache.uima.jcas.cas.EmptyIntegerList; import org.apache.uima.jcas.cas.EmptyList; import org.apache.uima.jcas.cas.EmptyStringList; import org.apache.uima.jcas.cas.FSArray; import org.apache.uima.jcas.cas.FloatArray; import org.apache.uima.jcas.cas.IntegerArray; import org.apache.uima.jcas.cas.LongArray; import org.apache.uima.jcas.cas.ShortArray; import org.apache.uima.jcas.cas.Sofa; import org.apache.uima.jcas.cas.StringArray; import org.apache.uima.jcas.cas.TOP; import org.apache.uima.jcas.impl.JCasHashMap; import org.apache.uima.jcas.impl.JCasImpl; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.util.AutoCloseableNoException; import org.apache.uima.util.Level; /** * Implements the CAS interfaces. This class must be public because we need to * be able to create instance of it from outside the package. Use at your own * risk. May change without notice. * */ public class CASImpl extends AbstractCas_ImplBase implements CAS, CASMgr, LowLevelCAS, TypeSystemConstants { private static final String TRACE_FSS = "uima.trace_fs_creation_and_updating"; public static final boolean IS_USE_V2_IDS = false; // if false, ids increment by 1 private static final boolean trace = false; // debug public static final boolean traceFSs = // false; // debug - trace FS creation and update Misc.getNoValueSystemProperty(TRACE_FSS); public static final boolean traceCow = false; // debug - trace copy on write actions, index adds / deletes private static final String traceFile = "traceFSs.log.txt"; private static final PrintStream traceOut; static { try { if (traceFSs) { System.out.println("Creating traceFSs file in directory " + System.getProperty("user.dir")); traceOut = traceFSs ? new PrintStream(new BufferedOutputStream(new FileOutputStream(traceFile, false))) : null; } else { traceOut = null; } } catch (Exception e) { throw new RuntimeException(e); } } private static final boolean MEASURE_SETINT = false; // debug static final AtomicInteger casIdProvider = new AtomicInteger(0); // Notes on the implementation // --------------------------- // Floats are handled by casting them to ints when they are stored // in the heap. Conveniently, 0 casts to 0.0f, which is the default // value. public static final int NULL = 0; // Boolean scalar values are stored as ints in the fs heap. // TRUE is 1 and false is 0. public static final int TRUE = 1; public static final int FALSE = 0; public static final int DEFAULT_INITIAL_HEAP_SIZE = 500_000; public static final int DEFAULT_RESET_HEAP_SIZE = 5_000_000; /** * The UIMA framework detects (unless disabled, for high performance) updates to indexed FS which update * key values used as keys in indexes. Normally the framework will protect against index corruption by * temporarily removing the FS from the indexes, then do the update to the feature value, and then addback * the changed FS. * <p> * Users can use the protectIndexes() methods to explicitly control this remove - add back cycle, for instance * to "batch" together several updates to multiple features in a FS. * <p> * Some build processes may want to FAIL if any unprotected updates of this kind occur, instead of having the * framework silently recover them. This is enabled by having the framework throw an exception; this is controlled * by this global JVM property, which, if defined, causes the framework to throw an exception rather than recover. * */ public static final String THROW_EXCEPTION_FS_UPDATES_CORRUPTS = "uima.exception_when_fs_update_corrupts_index"; // public for test case use public static boolean IS_THROW_EXCEPTION_CORRUPT_INDEX = Misc.getNoValueSystemProperty(THROW_EXCEPTION_FS_UPDATES_CORRUPTS); /** * Define this JVM property to enable checking for invalid updates to features which are used as * keys by any index. * <ul> * <li>The following are the same: -Duima.check_invalid_fs_updates and -Duima.check_invalid_fs_updates=true</li> * </ul> */ public static final String REPORT_FS_UPDATES_CORRUPTS = "uima.report_fs_update_corrupts_index"; private static final boolean IS_REPORT_FS_UPDATE_CORRUPTS_INDEX = IS_THROW_EXCEPTION_CORRUPT_INDEX || Misc.getNoValueSystemProperty(REPORT_FS_UPDATES_CORRUPTS); /** * Set this JVM property to false for high performance, (no checking); * insure you don't have the report flag (above) turned on - otherwise it will force this to "true". */ public static final String DISABLE_PROTECT_INDEXES = "uima.disable_auto_protect_indexes"; /** * the protect indexes flag is on by default, but may be turned of via setting the property. * * This is overridden if a report is requested or the exception detection is on. */ private static final boolean IS_DISABLED_PROTECT_INDEXES = Misc.getNoValueSystemProperty(DISABLE_PROTECT_INDEXES) && !IS_REPORT_FS_UPDATE_CORRUPTS_INDEX && !IS_THROW_EXCEPTION_CORRUPT_INDEX; public static final String ALWAYS_HOLD_ONTO_FSS = "uima.enable_id_to_feature_structure_map_for_all_fss"; static final boolean IS_ALWAYS_HOLD_ONTO_FSS = // debug Misc.getNoValueSystemProperty(ALWAYS_HOLD_ONTO_FSS); // private static final int REF_DATA_FOR_ALLOC_SIZE = 1024; // private static final int INT_DATA_FOR_ALLOC_SIZE = 1024; // // this next seemingly non-sensical static block // is to force the classes needed by Eclipse debugging to load // otherwise, you get a com.sun.jdi.ClassNotLoadedException when // the class is used as part of formatting debugging messages static { new DebugNameValuePair(null, null); new DebugFSLogicalStructure(); } // Static classes representing shared instance data // - shared data is computed once for all views /** * Journaling changes for computing delta cas. * Each instance represents one or more changes for one feature structure * A particular Feature Structure may have multiple FsChange instances * but we attempt to minimize this */ public static class FsChange { /** ref to the FS being modified */ final TOP fs; /** * which feature (by offset) is modified */ final BitSet featuresModified; final PositiveIntSet arrayUpdates; FsChange(TOP fs) { this.fs = fs; TypeImpl ti = fs._getTypeImpl(); featuresModified = (ti.highestOffset == -1) ? null : new BitSet(ti.highestOffset + 1); arrayUpdates = (ti.isArray()) ? new PositiveIntSet_impl() : null; } void addFeatData(int v) { featuresModified.set(v); } void addArrayData(int v, int nbrOfConsecutive) { for (int i = 0; i < nbrOfConsecutive; i++) { arrayUpdates.add(v++); } } void addArrayData(PositiveIntSet indexesPlus1) { indexesPlus1.forAllInts(i -> arrayUpdates.add(i - 1)); } @Override public int hashCode() { return 31 + ((fs == null) ? 0 : fs._id); } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof FsChange)) return false; return ((FsChange)obj).fs._id == fs._id; } } // fields shared among all CASes belong to views of a common base CAS static class SharedViewData { /** * map from FS ids to FSs. */ final private Id2FS id2fs; /** set to > 0 to reuse an id, 0 otherwise */ private int reuseId = 0; // Base CAS for all views final private CASImpl baseCAS; /** * These fields are here, not in TypeSystemImpl, because different CASes may have different indexes but share the same type system * They hold the same data (constant per CAS) but are accessed with different indexes */ private final BitSet featureCodesInIndexKeys = new BitSet(1024); // 128 bytes // private final BitSet featureJiInIndexKeys = new BitSet(1024); // indexed by JCas Feature Index, not feature code. // A map from SofaNumbers which are also view numbers to IndexRepositories. // these numbers are dense, and start with 1. 1 is the initial view. 0 is the base cas ArrayList<FSIndexRepositoryImpl> sofa2indexMap; /** * A map from Sofa numbers to CAS views. * number 0 - not used * number 1 - used for view named "_InitialView" * number 2-n used for other views * * Note: this is not reset with "Cas Reset" because views (really, their associated index repos) * take a lot of setup for the indexes. * However, the maximum view count is reset; so creation of new views "reuses" these pre-setup indexRepos * associated with these views. */ ArrayList<CASImpl> sofaNbr2ViewMap; /** * a set of instantiated sofaNames */ private Set<String> sofaNameSet; // Flag that initial Sofa has been created private boolean initialSofaCreated = false; // Count of Views created in this cas // equals count of sofas except if initial view has no sofa. int viewCount; // The ClassLoader that should be used by the JCas to load the generated // FS cover classes for this CAS. Defaults to the ClassLoader used // to load the CASImpl class. private ClassLoader jcasClassLoader = this.getClass().getClassLoader(); /***************************** * PEAR Support *****************************/ /** * Only support one level of PEAR nesting; for more general approach, make this a deque */ private ClassLoader previousJCasClassLoader = null; /** * Save area for suspending this while we create a base instance */ private ClassLoader suspendPreviousJCasClassLoader; /** * A map from IDs to already created trampoline FSs for the base FS with that id. * These are used when in a Pear and retrieving a FS (via index or deref) and you want the * Pear version for that ID. * There are potentially multiple maps - one per PEAR Classpath */ private JCasHashMap id2tramp = null; /** * a map from IDs of FSs that have a Pear version, to the base (non-Pear) version * used to locate the base version for adding to indexes */ private JCasHashMap id2base = null; private final Map<ClassLoader, JCasHashMap> cl2id2tramp = new IdentityHashMap<>(); /** * The current (active, switches at Pear boundaries) FsGenerators (excluding array-generators) * key = type code * read-only, unsynchronized for this CAS * Cache for setting this kept in TypeSystemImpl, by classloader * - shared among all CASs that use that Type System and class loader * -- in turn, initialized from FSClassRegistry, once per classloader / typesystem combo * * Pear generators are mostly null except for instances where the PEAR has redefined * the JCas cover class */ private FsGenerator3[] generators; /** * When generating a new instance of a FS in a PEAR where there's an alternate JCas class impl, * generate the base version, and make the alternate a trampoline to it. * Note: in future, if it is known that this FS is never used outside of this PEAR, then can * skip generating the double version */ private FsGenerator3[] baseGenerators; // If this CAS can be flushed (reset) or not. // often, the framework disables this before calling users code private boolean flushEnabled = true; // not final because set with reinit deserialization private TypeSystemImpl tsi; private ComponentInfo componentInfo; /** * This tracks the changes for delta cas * May also in the future support Journaling by component, * allowing determination of which component in a flow * created/updated a FeatureStructure (not implmented) * * TrackingMarkers are held on to by things outside of the * Cas, to support switching from one tracking marker to * another (currently not used, but designed to support * Component Journaling). * * We track changes on a granularity of features * and for features which are arrays, which element of the array * (This last to enable efficient delta serializations of * giant arrays of things, where you've only updated a few items) * * The FsChange doesn't store the changed data, only stores the * ref info needed to get to what was changed. */ private MarkerImpl trackingMark; /** * Track modified preexistingFSs * Note this is a map, keyed by the FS, so all changes are merged when added */ private Map<TOP, FsChange> modifiedPreexistingFSs; /** * This list currently only contains at most 1 element. * If Journaling is implemented, it may contain an * element per component being journaled. */ private List<MarkerImpl> trackingMarkList; /** * This stack corresponds to nested protectIndexes contexts. Normally should be very shallow. */ private final ArrayList<FSsTobeAddedback> fssTobeAddedback = new ArrayList<FSsTobeAddedback>(); /** * This version is for single fs use, by binary deserializers and by automatic mode * Only one user at a time is allowed. */ private final FSsTobeAddedbackSingle fsTobeAddedbackSingle = (FSsTobeAddedbackSingle) FSsTobeAddedback.createSingle(); /** * Set to true while this is in use. */ boolean fsTobeAddedbackSingleInUse = false; /** * temporarily set to true by deserialization routines doing their own management of this check */ boolean disableAutoCorruptionCheck = false; // used to generate FSIDs, increments by 1 for each use. First id == 1 /** * The fsId of the last created FS * used to generate FSIDs, increments by 1 for each use. First id == 1 */ private int fsIdGenerator = 0; /** * The version 2 size on the main heap of the last created FS */ private int lastFsV2Size = 1; /** * used to "capture" the fsIdGenerator value for a read-only CAS to be visible in * other threads */ AtomicInteger fsIdLastValue = new AtomicInteger(0); // mostly for debug - counts # times cas is reset private final AtomicInteger casResets = new AtomicInteger(0); // unique ID for a created CAS view, not updated if CAS is reset and reused private final int casId = casIdProvider.incrementAndGet(); // shared singltons, created at type system commit private EmptyFSList emptyFSList; private EmptyFloatList emptyFloatList; private EmptyIntegerList emptyIntegerList; private EmptyStringList emptyStringList; private FloatArray emptyFloatArray; private FSArray emptyFSArray; private IntegerArray emptyIntegerArray; private StringArray emptyStringArray; private DoubleArray emptyDoubleArray; private LongArray emptyLongArray; private ShortArray emptyShortArray; private ByteArray emptyByteArray; private BooleanArray emptyBooleanArray; /** * Created at startup time, lives as long as the CAS lives * Serves to reference code for binary cas ser/des that used to live * in this class, but was moved out */ private final BinaryCasSerDes bcsd; /** * Created when doing binary or form4 non-delta (de)serialization, used in subsequent delta ser/deserialization * Created when doing binary or form4 non-delta ser/deserialization, used in subsequent delta (de)serialization * Reset with CasReset or deltaMergesComplete API call */ private CommonSerDesSequential csds; /************************************************* * VERSION 2 LOW_LEVEL_API COMPATIBILITY SUPPORT * *************************************************/ /** * A StringSet used only to support ll_get/setInt api * get adds string to this and returns the int handle * set retrieves the string, given the handle * lazy initialized */ private StringSet llstringSet = null; /** * A LongSet used only to support v2 ll_get/setInt api * get adds long to this and returns the int handle * set retrieves the long, given the handle * lazy initialized */ private LongSet lllongSet = null; // For tracing FS creation and updating, normally disabled private final StringBuilder traceFScreationSb = traceFSs ? new StringBuilder() : null; private final StringBuilder traceCowSb = traceCow ? new StringBuilder() : null; private int traceFSid = 0; private boolean traceFSisCreate; private final IntVector id2addr = traceFSs ? new IntVector() : null; private int nextId2Addr = 1; // only for tracing, to convert id's to v2 addresses final private int initialHeapSize; private SharedViewData(CASImpl baseCAS, int initialHeapSize, TypeSystemImpl tsi) { this.baseCAS = baseCAS; this.tsi = tsi; this.initialHeapSize = initialHeapSize; bcsd = new BinaryCasSerDes(baseCAS); id2fs = new Id2FS(initialHeapSize); if (traceFSs) id2addr.add(0); } void clearCasReset() { // fss fsIdGenerator = 0; id2fs.clear(); // pear caches id2tramp = null; id2base = null; for (JCasHashMap m : cl2id2tramp.values()) { m.clear(); } // index corruption avoidance fssTobeAddedback.clear(); fsTobeAddedbackSingle.clear(); fsTobeAddedbackSingleInUse = false; disableAutoCorruptionCheck = false; // misc flushEnabled = true; componentInfo = null; bcsd.clear(); csds = null; llstringSet = null; traceFSid = 0; if (traceFSs) { traceFScreationSb.setLength(0); id2addr.removeAllElements(); id2addr.add(0); nextId2Addr = 1; } emptyFloatList = null; // these cleared in case new ts redefines? emptyFSList = null; emptyIntegerList = null; emptyStringList = null; emptyFloatArray = null; emptyFSArray = null; emptyIntegerArray = null; emptyStringArray = null; emptyDoubleArray = null; emptyLongArray = null; emptyShortArray = null; emptyByteArray = null; emptyBooleanArray = null; clearNonSharedInstanceData(); } /** * called by resetNoQuestions and cas complete reinit */ void clearSofaInfo() { sofaNameSet.clear(); initialSofaCreated = false; } /** * Called from CasComplete deserialization (reinit). * * Skips the resetNoQuestions operation of flushing the indexes, * since these will be reinitialized with potentially new definitions. * * Clears additional data related to having the * - type system potentially change * - the features belonging to indexes change * */ void clear() { resetNoQuestions(false); // false - skip flushing the index repos // type system + index spec tsi = null; featureCodesInIndexKeys.clear(); // featureJiInIndexKeys.clear(); /** * Clear the existing views, except keep the info for the initial view * so that the cas complete deserialization after setting up the new index repository in the base cas * can "refresh" the existing initial view (if present; if not present, a new one is created). */ if (sofaNbr2ViewMap.size() >= 1) { // have initial view - preserve it CASImpl localInitialView = sofaNbr2ViewMap.get(1); sofaNbr2ViewMap.clear(); Misc.setWithExpand(sofaNbr2ViewMap, 1, localInitialView); viewCount = 1; } else { sofaNbr2ViewMap.clear(); viewCount = 0; } } private void resetNoQuestions(boolean flushIndexRepos) { casResets.incrementAndGet(); if (trace) { System.out.println("CAS Reset in thread " + Thread.currentThread().getName() + " for CasId = " + casId + ", new reset count = " + casResets.get()); } clearCasReset(); // also clears cached FSs if (flushIndexRepos) { flushIndexRepositoriesAllViews(); } clearTrackingMarks(); clearSofaInfo(); // but keep initial view, and other views // because setting up the index infrastructure is expensive viewCount = 1; // initial view traceFSid = 0; if (traceFSs) traceFScreationSb.setLength(0); componentInfo = null; // https://issues.apache.org/jira/browse/UIMA-5097 } private void flushIndexRepositoriesAllViews() { int numViews = viewCount; for (int view = 1; view <= numViews; view++) { CASImpl tcas = (CASImpl) ((view == 1) ? getInitialView() : getViewFromSofaNbr(view)); if (tcas != null) { tcas.indexRepository.flush(); } } // safety : in case this public method is called on other than the base cas baseCAS.indexRepository.flush(); // for base view, other views flushed above } private void clearNonSharedInstanceData() { int numViews = viewCount; for (int view = 1; view <= numViews; view++) { CASImpl tcas = (CASImpl) ((view == 1) ? getInitialView() : getViewFromSofaNbr(view)); if (tcas != null) { tcas.mySofaRef = null; // was in v2: (1 == view) ? -1 : 0; tcas.docAnnotIter = null; } } } private void clearTrackingMarks() { // resets all markers that might be held by things outside the Cas // Currently (2009) this list has a max of 1 element // Future impl may have one element per component for component Journaling if (trackingMarkList != null) { for (int i=0; i < trackingMarkList.size(); i++) { trackingMarkList.get(i).isValid = false; } } trackingMark = null; if (null != modifiedPreexistingFSs) { modifiedPreexistingFSs.clear(); } trackingMarkList = null; } void switchClassLoader(ClassLoader newClassLoader) { if (null == newClassLoader) { // is null if no cl set return; } if (newClassLoader != jcasClassLoader) { if (null != previousJCasClassLoader) { /** Multiply nested classloaders not supported. Original base loader: {0}, current nested loader: {1}, trying to switch to loader: {2}.*/ throw new CASRuntimeException(CASRuntimeException.SWITCH_CLASS_LOADER_NESTED, previousJCasClassLoader, jcasClassLoader, newClassLoader); } // System.out.println("Switching to new class loader"); previousJCasClassLoader = jcasClassLoader; jcasClassLoader = newClassLoader; generators = tsi.getGeneratorsForClassLoader(newClassLoader, true); // true - isPear assert null == id2tramp; // is null outside of a pear id2tramp = cl2id2tramp.get(newClassLoader); if (null == id2tramp) { cl2id2tramp.put(newClassLoader, id2tramp = new JCasHashMap(32)); } if (id2base == null) { id2base = new JCasHashMap(32); } } } void restoreClassLoader() { if (null == previousJCasClassLoader) { return; } // System.out.println("Switching back to previous class loader"); jcasClassLoader = previousJCasClassLoader; previousJCasClassLoader = null; generators = baseGenerators; id2tramp = null; } private int getNextFsId(TOP fs) { if (reuseId != 0) { // l.setStrongRef(fs, reuseId); return reuseId; } // l.add(fs); // if (id2fs.size() != (2 + fsIdGenerator.get())) { // System.out.println("debug out of sync id generator and id2fs size"); // } // assert(l.size() == (2 + fsIdGenerator)); final int p = fsIdGenerator; final int r = fsIdGenerator += IS_USE_V2_IDS ? lastFsV2Size : 1; if (r < p) { throw new RuntimeException("UIMA Cas Internal id value overflowed maximum int value"); } if (IS_USE_V2_IDS) { // this computation is partial - misses length of arrays stored on heap // because that info not yet available lastFsV2Size = fs._getTypeImpl().getFsSpaceReq(); } return r; } private CASImpl getViewFromSofaNbr(int nbr) { final ArrayList<CASImpl> sn2v = sofaNbr2ViewMap; if (nbr < sn2v.size()) { return sn2v.get(nbr); } return null; } // For internal platform use only CASImpl getInitialView() { CASImpl couldBeThis = getViewFromSofaNbr(1); if (couldBeThis != null) { return couldBeThis; } // create the initial view, without a Sofa CASImpl aView = new CASImpl(baseCAS, (SofaFS) null); setViewForSofaNbr(1, aView); assert (viewCount <= 1); viewCount = 1; return aView; } void setViewForSofaNbr(int nbr, CASImpl view) { Misc.setWithExpand(sofaNbr2ViewMap, nbr, view); } } /***************************************************************** * Non-shared instance data kept per CAS view incl base CAS *****************************************************************/ // package protected to let other things share this info final SharedViewData svd; // shared view data /** The index repository. Referenced by XmiCasSerializer */ FSIndexRepositoryImpl indexRepository; // private Object[] currentRefDataForAlloc = new Object[REF_DATA_FOR_ALLOC_SIZE]; // private Object[] returnRefDataForAlloc; // private int[] currentIntDataForAlloc = new int[INT_DATA_FOR_ALLOC_SIZE]; // private int[] returnIntDataForAlloc; // private int nextRefDataOffsetForAlloc = 0; // private int nextIntDataOffsetForAlloc = 0; /** * The Feature Structure for the sofa FS for this view, or * null * //-1 if the sofa FS is for the initial view, or * // 0 if there is no sofa FS - for instance, in the "base cas" */ private Sofa mySofaRef = null; /** the corresponding JCas object */ JCasImpl jcas = null; /** * Copies of frequently accessed data pulled up for * locality of reference - only an optimization * - each value needs to be reset appropriately * - getters check for null, and if null, do the get. */ private TypeSystemImpl tsi_local; /** * for Pear generation - set this to the base FS * not in SharedViewData to reduce object traversal when * generating FSs */ FeatureStructureImplC pearBaseFs = null; /** * Optimization - keep a documentAnnotationIterator handy for getting a ref to the doc annot * Initialized lazily, synchronized * One per cas view */ private volatile FSIterator<Annotation> docAnnotIter = null; // private StackTraceElement[] addbackSingleTrace = null; // for debug use only, normally commented out // CASImpl(TypeSystemImpl typeSystem) { // this(typeSystem, DEFAULT_INITIAL_HEAP_SIZE); // } // // Reference existing CAS // // For use when creating views of the CAS // CASImpl(CAS cas) { // this.setCAS(cas); // this.useFSCache = false; // initTypeVariables(); // } /* * Configure a new (base view) CASImpl, **not a new view** typeSystem can be * null, in which case a new instance of TypeSystemImpl is set up, but not * committed. If typeSystem is not null, it is committed (locked). ** Note: it * is assumed that the caller of this will always set up the initial view ** * by calling */ public CASImpl(TypeSystemImpl typeSystem, int initialHeapSize ) { super(); TypeSystemImpl ts; final boolean externalTypeSystem = (typeSystem != null); if (externalTypeSystem) { ts = typeSystem; } else { ts = (TypeSystemImpl) CASFactory.createTypeSystem(); // creates also new CASMetadata and // FSClassRegistry instances } this.svd = new SharedViewData(this, initialHeapSize, ts); // this.svd.baseCAS = this; // this.svd.heap = new Heap(initialHeapSize); if (externalTypeSystem) { commitTypeSystem(); } this.svd.sofa2indexMap = new ArrayList<>(); this.svd.sofaNbr2ViewMap = new ArrayList<>(); this.svd.sofaNameSet = new HashSet<String>(); this.svd.initialSofaCreated = false; this.svd.viewCount = 0; this.svd.clearTrackingMarks(); } public CASImpl() { this((TypeSystemImpl) null, DEFAULT_INITIAL_HEAP_SIZE); } // In May 2007, appears to have 1 caller, createCASMgr in Serialization class, // could have out-side the framework callers because it is public. public CASImpl(CASMgrSerializer ser) { this(ser.getTypeSystem(), DEFAULT_INITIAL_HEAP_SIZE); checkInternalCodes(ser); // assert(ts != null); // assert(getTypeSystem() != null); this.indexRepository = ser.getIndexRepository(this); } // Use this when creating a CAS view CASImpl(CASImpl cas, SofaFS aSofa) { // these next fields are final and must be set in the constructor this.svd = cas.svd; this.mySofaRef = (Sofa) aSofa; // get the indexRepository for this Sofa this.indexRepository = (this.mySofaRef == null) ? (FSIndexRepositoryImpl) cas.getSofaIndexRepository(1) : (FSIndexRepositoryImpl) cas.getSofaIndexRepository(aSofa); if (null == this.indexRepository) { // create the indexRepository for this CAS // use the baseIR to create a lightweight IR copy FSIndexRepositoryImpl baseIndexRepo = (FSIndexRepositoryImpl) cas.getBaseIndexRepository(); this.indexRepository = new FSIndexRepositoryImpl(this, baseIndexRepo); // the index creation depends on "indexRepository" already being set baseIndexRepo.name2indexMap.keySet().stream().forEach(key -> this.indexRepository.createIndex(baseIndexRepo, key)); this.indexRepository.commit(); // save new sofa index if (this.mySofaRef == null) { cas.setSofaIndexRepository(1, this.indexRepository); } else { cas.setSofaIndexRepository(aSofa, this.indexRepository); } } } // Use this when creating a CAS view void refreshView(CAS cas, SofaFS aSofa) { if (aSofa != null) { // save address of SofaFS this.mySofaRef = (Sofa) aSofa; } else { // this is the InitialView this.mySofaRef = null; } // toss the JCas, if it exists this.jcas = null; // create the indexRepository for this Sofa final FSIndexRepositoryImpl baseIndexRepo = (FSIndexRepositoryImpl) ((CASImpl) cas).getBaseIndexRepository(); this.indexRepository = new FSIndexRepositoryImpl(this,baseIndexRepo); // the index creation depends on "indexRepository" already being set baseIndexRepo.name2indexMap.keySet().stream().forEach(key -> this.indexRepository.createIndex(baseIndexRepo, key)); this.indexRepository.commit(); // save new sofa index if (this.mySofaRef == null) { ((CASImpl) cas).setSofaIndexRepository(1, this.indexRepository); } else { ((CASImpl) cas).setSofaIndexRepository(aSofa, this.indexRepository); } } private void checkInternalCodes(CASMgrSerializer ser) throws CASAdminException { if ((ser.topTypeCode > 0) && (ser.topTypeCode != topTypeCode)) { throw new CASAdminException(CASAdminException.DESERIALIZATION_ERROR); } if (ser.featureOffsets == null) { return; } // if (ser.featureOffsets.length != this.svd.casMetadata.featureOffset.length) { // throw new CASAdminException(CASAdminException.DESERIALIZATION_ERROR); // } TypeSystemImpl tsi = getTypeSystemImpl(); for (int i = 1; i < ser.featureOffsets.length; i++) { FeatureImpl fi = tsi.getFeatureForCode_checked(i); int adjOffset = fi.isInInt ? 0 : fi.getRangeImpl().nbrOfUsedIntDataSlots; if (ser.featureOffsets[i] != (fi.getOffset() + adjOffset)) { throw new CASAdminException(CASAdminException.DESERIALIZATION_ERROR); } } } // ---------------------------------------- // accessors for data in SharedViewData // ---------------------------------------- void addSofaViewName(String id) { svd.sofaNameSet.add(id); } void setViewCount(int n) { svd.viewCount = n; } void addbackSingle(TOP fs) { if (!svd.fsTobeAddedbackSingleInUse) { Misc.internalError(); } svd.fsTobeAddedbackSingle.addback(fs); svd.fsTobeAddedbackSingleInUse = false; } void addbackSingleIfWasRemoved(boolean wasRemoved, TOP fs) { if (wasRemoved) { addbackSingle(fs); } svd.fsTobeAddedbackSingleInUse = false; } private FSsTobeAddedback getAddback(int size) { if (svd.fsTobeAddedbackSingleInUse) { Misc.internalError(); } return svd.fssTobeAddedback.get(size - 1); } FSsTobeAddedbackSingle getAddbackSingle() { if (svd.fsTobeAddedbackSingleInUse) { // System.out.println(Misc.dumpCallers(addbackSingleTrace, 2, 100)); Misc.internalError(); } // addbackSingleTrace = Thread.currentThread().getStackTrace(); svd.fsTobeAddedbackSingleInUse = true; svd.fsTobeAddedbackSingle.clear(); // safety return svd.fsTobeAddedbackSingle; } void featureCodes_inIndexKeysAdd(int featCode/*, int registryIndex*/) { svd.featureCodesInIndexKeys.set(featCode); // skip adding if no JCas registry entry for this feature // if (registryIndex >= 0) { // svd.featureJiInIndexKeys.set(registryIndex); // } } @Override public void enableReset(boolean flag) { this.svd.flushEnabled = flag; } @Override public final TypeSystem getTypeSystem() { return getTypeSystemImpl(); } public final TypeSystemImpl getTypeSystemImpl() { if (tsi_local == null) { tsi_local = this.svd.tsi; } return this.tsi_local; } /** * Set the shared svd type system ref, in all views * @param ts */ void installTypeSystemInAllViews(TypeSystemImpl ts) { this.svd.tsi = ts; final List<CASImpl> sn2v = this.svd.sofaNbr2ViewMap; if (sn2v.size() > 0) { for (CASImpl view : sn2v.subList(1, sn2v.size())) { view.tsi_local = ts; } } this.getBaseCAS().tsi_local = ts; } @Override public ConstraintFactory getConstraintFactory() { return ConstraintFactory.instance(); } /** * Create the appropriate Feature Structure Java instance * - from whatever the generator for this type specifies. * * @param type the type to create * @return a Java object representing the FeatureStructure impl in Java. */ @Override public <T extends FeatureStructure> T createFS(Type type) { final TypeImpl ti = (TypeImpl) type; if (!ti.isCreatableAndNotBuiltinArray()) { throw new CASRuntimeException(CASRuntimeException.NON_CREATABLE_TYPE, type.getName(), "CAS.createFS()"); } return (T) createFSAnnotCheck(ti); } private <T extends FeatureStructureImplC> T createFSAnnotCheck(TypeImpl ti) { if (ti.isAnnotationBaseType()) { // not here, will be checked later in AnnotationBase constructor // if (this.isBaseCas()) { // throw new CASRuntimeException(CASRuntimeException.DISALLOW_CREATE_ANNOTATION_IN_BASE_CAS, ti.getName()); // } getSofaRef(); // materialize this if not present; required for setting the sofa ref // must happen before the annotation is created, for compressed form 6 serialization order // to insure sofa precedes the ref of it } FsGenerator3 g = svd.generators[ti.getCode()]; // get generator or null return (g != null) ? (T) g.createFS(ti, this) // pear case, with no overriding pear - use base : (T) createFsFromGenerator(svd.baseGenerators, ti); // // // // not pear or no special cover class for this // // // TOP fs = createFsFromGenerator(svd.baseGenerators, ti); // // FsGenerator g = svd.generators[ti.getCode()]; // get pear generator or null // return (g != null) // ? (T) pearConvert(fs, g) // : (T) fs; // } // // return (T) createFsFromGenerator(svd.generators, ti); } /** * Called during construction of FS. * For normal FS "new" operators, if in PEAR context, make the base version * @param fs * @param ti * @return true if made a base for a trampoline */ boolean maybeMakeBaseVersionForPear(FeatureStructureImplC fs, TypeImpl ti) { if (!inPearContext()) return false; FsGenerator3 g = svd.generators[ti.getCode()]; // get pear generator or null if (g == null) return false; TOP baseFs; try { suspendPearContext(); svd.reuseId = fs._id; baseFs = createFsFromGenerator(svd.baseGenerators, ti); } finally { restorePearContext(); svd.reuseId = 0; } svd.id2base.put(baseFs); pearBaseFs = baseFs; return true; } private TOP createFsFromGenerator(FsGenerator3[] gs, TypeImpl ti) { return gs[ti.getCode()].createFS(ti, this); } public TOP createArray(TypeImpl array_type, int arrayLength) { TypeImpl_array tia = (TypeImpl_array) array_type; TypeImpl componentType = tia.getComponentType(); if (componentType.isPrimitive()) { checkArrayPreconditions(arrayLength); switch (componentType.getCode()) { case intTypeCode: return new IntegerArray(array_type, this, arrayLength); case floatTypeCode: return new FloatArray(array_type, this, arrayLength); case booleanTypeCode: return new BooleanArray(array_type, this, arrayLength); case byteTypeCode: return new ByteArray(array_type, this, arrayLength); case shortTypeCode: return new ShortArray(array_type, this, arrayLength); case longTypeCode: return new LongArray(array_type, this, arrayLength); case doubleTypeCode: return new DoubleArray(array_type, this, arrayLength); case stringTypeCode: return new StringArray(array_type, this, arrayLength); default: throw Misc.internalError(); } } return (TOP) createArrayFS(array_type, arrayLength); } /* * =============== These methods might be deprecated in favor of * new FSArray(jcas, length) etc. * except that these run with the CAS, not JCas * (non-Javadoc) * @see org.apache.uima.cas.CAS#createArrayFS(int) */ @Override public ArrayFS createArrayFS(int length) { return createArrayFS(getTypeSystemImpl().fsArrayType, length); } private ArrayFS createArrayFS(TypeImpl type, int length) { checkArrayPreconditions(length); return new FSArray(type, this, length); } @Override public IntArrayFS createIntArrayFS(int length) { checkArrayPreconditions(length); return new IntegerArray(getTypeSystemImpl().intArrayType, this, length); } @Override public FloatArrayFS createFloatArrayFS(int length) { checkArrayPreconditions(length); return new FloatArray(getTypeSystemImpl().floatArrayType, this, length); } @Override public StringArrayFS createStringArrayFS(int length) { checkArrayPreconditions(length); return new StringArray(getTypeSystemImpl().stringArrayType, this, length); } // return true if only one sofa and it is the default text sofa public boolean isBackwardCompatibleCas() { // check that there is exactly one sofa if (this.svd.viewCount != 1) { return false; } if (!this.svd.initialSofaCreated) { return false; } Sofa sofa = this.getInitialView().getSofa(); // check for mime type exactly equal to "text" String sofaMime = sofa.getMimeType(); if (!"text".equals(sofaMime)) { return false; } // check that sofaURI and sofaArray are not set String sofaUri = sofa.getSofaURI(); if (sofaUri != null) { return false; } TOP sofaArray = sofa.getSofaArray(); if (sofaArray != null) { return false; } // check that name is NAME_DEFAULT_SOFA String sofaname = sofa.getSofaID(); return NAME_DEFAULT_SOFA.equals(sofaname); } int getViewCount() { return this.svd.viewCount; } FSIndexRepository getSofaIndexRepository(SofaFS aSofa) { return getSofaIndexRepository(aSofa.getSofaRef()); } FSIndexRepositoryImpl getSofaIndexRepository(int aSofaRef) { if (aSofaRef >= this.svd.sofa2indexMap.size()) { return null; } return this.svd.sofa2indexMap.get(aSofaRef); } void setSofaIndexRepository(SofaFS aSofa, FSIndexRepositoryImpl indxRepos) { setSofaIndexRepository(aSofa.getSofaRef(), indxRepos); } void setSofaIndexRepository(int aSofaRef, FSIndexRepositoryImpl indxRepos) { Misc.setWithExpand(this.svd.sofa2indexMap, aSofaRef, indxRepos); } /** * @deprecated */ @Override @Deprecated public SofaFS createSofa(SofaID sofaID, String mimeType) { // extract absolute SofaName string from the ID SofaFS aSofa = createSofa(sofaID.getSofaID(), mimeType); getView(aSofa); // will create the view, needed to make the // resetNoQuestions and other things that // iterate over views work. return aSofa; } Sofa createSofa(String sofaName, String mimeType) { return createSofa(++this.svd.viewCount, sofaName, mimeType); } Sofa createSofa(int sofaNum, String sofaName, String mimeType) { if (this.svd.sofaNameSet.contains(sofaName)) { throw new CASRuntimeException(CASRuntimeException.SOFANAME_ALREADY_EXISTS, sofaName); } final boolean viewAlreadyExists = sofaNum == this.svd.viewCount; if (!viewAlreadyExists) { if (sofaNum == 1) { // skip the test for sofaNum == 1 - this can be set "later" if (this.svd.viewCount == 0) { this.svd.viewCount = 1; } // else it is == or higher, so don't reset it down } else { // sofa is not initial sofa - is guaranteed to be set when view created // if (sofaNum != this.svd.viewCount + 1) { // System.out.println("debug"); // } assert (sofaNum == this.svd.viewCount + 1); this.svd.viewCount = sofaNum; } } Sofa sofa = new Sofa( getTypeSystemImpl().sofaType, this.getBaseCAS(), // view for a sofa is the base cas to correspond to where it gets indexed sofaNum, sofaName, mimeType); this.getBaseIndexRepository().addFS(sofa); this.svd.sofaNameSet.add(sofaName); if (!viewAlreadyExists) { getView(sofa); // create the view that goes with this Sofa } return sofa; } boolean hasView(String name) { return this.svd.sofaNameSet.contains(name); } Sofa createInitialSofa(String mimeType) { Sofa sofa = createSofa(1, CAS.NAME_DEFAULT_SOFA, mimeType); registerInitialSofa(); this.mySofaRef = sofa; return sofa; } void registerInitialSofa() { this.svd.initialSofaCreated = true; } boolean isInitialSofaCreated() { return this.svd.initialSofaCreated; } /** * @deprecated */ @Override @Deprecated public SofaFS getSofa(SofaID sofaID) { // extract absolute SofaName string from the ID return getSofa(sofaID.getSofaID()); } private SofaFS getSofa(String sofaName) { FSIterator<Sofa> iterator = this.svd.baseCAS.getSofaIterator(); while (iterator.hasNext()) { SofaFS sofa = iterator.next(); if (sofaName.equals(sofa.getSofaID())) { return sofa; } } throw new CASRuntimeException(CASRuntimeException.SOFANAME_NOT_FOUND, sofaName); } SofaFS getSofa(int sofaRef) { SofaFS aSofa = (SofaFS) this.ll_getFSForRef(sofaRef); if (aSofa == null) { CASRuntimeException e = new CASRuntimeException(CASRuntimeException.SOFAREF_NOT_FOUND); throw e; } return aSofa; } public int ll_getSofaNum(int sofaRef) { return ((Sofa)getFsFromId_checked(sofaRef)).getSofaNum(); } public String ll_getSofaID(int sofaRef) { return ((Sofa)getFsFromId_checked(sofaRef)).getSofaID(); } public String ll_getSofaDataString(int sofaAddr) { return ((Sofa)getFsFromId_checked(sofaAddr)).getSofaString(); } public CASImpl getBaseCAS() { return this.svd.baseCAS; } @Override public <T extends SofaFS> FSIterator<T> getSofaIterator() { FSIndex<T> sofaIndex = this.svd.baseCAS.indexRepository.<T>getIndex(CAS.SOFA_INDEX_NAME); return sofaIndex.iterator(); } // For internal use only public Sofa getSofaRef() { if (this.mySofaRef == null) { // create the SofaFS for _InitialView ... // ... and reset mySofaRef to point to it this.mySofaRef = this.createInitialSofa(null); } return this.mySofaRef; } // For internal use only public InputStream getSofaDataStream(SofaFS aSofa) { Sofa sofa = (Sofa) aSofa; String sd = sofa.getLocalStringData(); if (null != sd) { ByteArrayInputStream bis; try { bis = new ByteArrayInputStream(sd.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // never happen } return bis; } else if (null != aSofa.getLocalFSData()) { TOP fs = (TOP) sofa.getLocalFSData(); ByteBuffer buf = null; switch(fs._getTypeCode()) { case stringArrayTypeCode: { StringBuilder sb = new StringBuilder(); final String[] theArray = ((StringArray) fs)._getTheArray(); for (int i = 0; i < theArray.length; i++) { if (i != 0) { sb.append('\n'); } sb.append(theArray[i]); } try { return new ByteArrayInputStream(sb.toString().getBytes("UTF-8") ); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // never happen } } case intArrayTypeCode: { final int[] theArray = ((IntegerArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 4)).asIntBuffer().put(theArray, 0, theArray.length); break; } case floatArrayTypeCode: { final float[] theArray = ((FloatArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 4)).asFloatBuffer().put(theArray, 0, theArray.length); break; } case byteArrayTypeCode: { final byte[] theArray = ((ByteArray) fs)._getTheArray(); buf = ByteBuffer.wrap(theArray); break; } case shortArrayTypeCode: { final short[] theArray = ((ShortArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 2)).asShortBuffer().put(theArray, 0, theArray.length); break; } case longArrayTypeCode: { final long[] theArray = ((LongArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 8)).asLongBuffer().put(theArray, 0, theArray.length); break; } case doubleArrayTypeCode: { final double[] theArray = ((DoubleArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 8)).asDoubleBuffer().put(theArray, 0, theArray.length); break; } default: throw Misc.internalError(); } ByteArrayInputStream bis = new ByteArrayInputStream(buf.array()); return bis; } else if (null != aSofa.getSofaURI()) { URL url; try { url = new URL(aSofa.getSofaURI()); return url.openStream(); } catch (IOException exc) { throw new CASRuntimeException(CASRuntimeException.SOFADATASTREAM_ERROR, exc.getMessage()); } } return null; } @Override public<T extends FeatureStructure> FSIterator<T> createFilteredIterator(FSIterator<T> it, FSMatchConstraint cons) { return new FilteredIterator<T>(it, cons); } public TypeSystemImpl commitTypeSystem() { TypeSystemImpl ts = getTypeSystemImpl(); // For CAS pools, the type system could have already been committed // Skip the initFSClassReg if so, because it may have been updated to a JCas // version by another CAS processing in the pool // @see org.apache.uima.cas.impl.FSClassRegistry // avoid race: two instances of a CAS from a pool attempting to commit the // ts // at the same time final ClassLoader cl = getJCasClassLoader(); synchronized (ts) { // //debug // System.out.format("debug committing ts %s classLoader %s%n", ts.hashCode(), cl); if (!ts.isCommitted()) { TypeSystemImpl tsc = ts.commit(getJCasClassLoader()); if (tsc != ts) { installTypeSystemInAllViews(tsc); ts = tsc; } } } svd.baseGenerators = svd.generators = ts.getGeneratorsForClassLoader(cl, false); // false - not PEAR createIndexRepository(); return ts; } private void createIndexRepository() { if (!this.getTypeSystemMgr().isCommitted()) { throw new CASAdminException(CASAdminException.MUST_COMMIT_TYPE_SYSTEM); } if (this.indexRepository == null) { this.indexRepository = new FSIndexRepositoryImpl(this); } } @Override public FSIndexRepositoryMgr getIndexRepositoryMgr() { // assert(this.cas.getIndexRepository() != null); return this.indexRepository; } /** * @deprecated * @param fs - */ @Deprecated public void commitFS(FeatureStructure fs) { getIndexRepository().addFS(fs); } @Override public FeaturePath createFeaturePath() { return new FeaturePathImpl(); } // Implement the ConstraintFactory interface. /** * @see org.apache.uima.cas.admin.CASMgr#getTypeSystemMgr() */ @Override public TypeSystemMgr getTypeSystemMgr() { return getTypeSystemImpl(); } @Override public void reset() { if (!this.svd.flushEnabled) { throw new CASAdminException(CASAdminException.FLUSH_DISABLED); } if (this == this.svd.baseCAS) { resetNoQuestions(); return; } // called from a CAS view. // clear CAS ... this.svd.baseCAS.resetNoQuestions(); } public void resetNoQuestions() { svd.resetNoQuestions(true); } /** * @deprecated Use {@link #reset reset()}instead. */ @Override @Deprecated public void flush() { reset(); } @Override public FSIndexRepository getIndexRepository() { if (this == this.svd.baseCAS) { // BaseCas has no indexes for users return null; } if (this.indexRepository.isCommitted()) { return this.indexRepository; } return null; } FSIndexRepository getBaseIndexRepository() { if (this.svd.baseCAS.indexRepository.isCommitted()) { return this.svd.baseCAS.indexRepository; } return null; } FSIndexRepositoryImpl getBaseIndexRepositoryImpl() { return this.svd.baseCAS.indexRepository; } void addSofaFsToIndex(SofaFS sofa) { this.svd.baseCAS.getBaseIndexRepository().addFS(sofa); } void registerView(Sofa aSofa) { this.mySofaRef = aSofa; } /** * @see org.apache.uima.cas.CAS#fs2listIterator(FSIterator) */ @Override public <T extends FeatureStructure> ListIterator<T> fs2listIterator(FSIterator<T> it) { // return new FSListIteratorImpl<T>(it); return it; // in v3, FSIterator extends listIterator } /** * @see org.apache.uima.cas.admin.CASMgr#getCAS() */ @Override public CAS getCAS() { if (this.indexRepository.isCommitted()) { return this; } throw new CASAdminException(CASAdminException.MUST_COMMIT_INDEX_REPOSITORY); } // public void setFSClassRegistry(FSClassRegistry fsClassReg) { // this.svd.casMetadata.fsClassRegistry = fsClassReg; // } // JCasGen'd cover classes use this to add their generators to the class // registry // Note that this now (June 2007) a no-op for JCasGen'd generators // Also previously (but not now) used in JCas initialization to copy-down super generators to subtypes // as needed public FSClassRegistry getFSClassRegistry() { return null; // return getTypeSystemImpl().getFSClassRegistry(); } /** * @param fs the Feature Structure being updated * @param fi the Feature of fs being updated, or null if fs is an array * @param arrayIndexStart * @param nbrOfConsecutive */ private void logFSUpdate(TOP fs, FeatureImpl fi, int arrayIndexStart, int nbrOfConsecutive) { //log the FS final Map<TOP, FsChange> changes = this.svd.modifiedPreexistingFSs; //create or use last FsChange element FsChange change = changes.computeIfAbsent(fs, key -> new FsChange(key)); if (fi == null) { Misc.assertUie(arrayIndexStart >= 0); change.addArrayData(arrayIndexStart, nbrOfConsecutive); } else { change.addFeatData(fi.getOffset()); } } /** * @param fs the Feature Structure being updated * @param arrayIndexStart * @param nbrOfConsecutive */ private void logFSUpdate(TOP fs, PositiveIntSet indexesPlus1) { //log the FS final Map<TOP, FsChange> changes = this.svd.modifiedPreexistingFSs; //create or use last FsChange element FsChange change = changes.computeIfAbsent(fs, key -> new FsChange(key)); change.addArrayData(indexesPlus1); } private void logFSUpdate(TOP fs, FeatureImpl fi) { logFSUpdate(fs, fi, -1, -1); // indicate non-array call } /** * This is your link from the low-level API to the high-level API. Use this * method to create a FeatureStructure object from an address. Note that the * reverse is not supported by public APIs (i.e., there is currently no way to * get at the address of a FeatureStructure. Maybe we will need to change * that. * * The "create" in "createFS" is a misnomer - the FS must already be created. * * @param id The id of the feature structure to be created. * @param <T> The Java class associated with this feature structure * @return A FeatureStructure object. */ public <T extends TOP> T createFS(int id) { return getFsFromId_checked(id); } public int getArraySize(CommonArrayFS fs) { return fs.size(); } @Override public int ll_getArraySize(int id) { return getArraySize(getFsFromId_checked(id)); } final void setWithCheckAndJournal(TOP fs, FeatureImpl fi, Runnable setter) { if (fs._inSetSortedIndex()) { boolean wasRemoved = checkForInvalidFeatureSetting(fs, fi.getCode()); setter.run(); if (wasRemoved) { maybeAddback(fs); } } else { setter.run(); } maybeLogUpdate(fs, fi); } final public void setWithCheckAndJournal(TOP fs, int featCode, Runnable setter) { if (fs._inSetSortedIndex()) { boolean wasRemoved = checkForInvalidFeatureSetting(fs, featCode); setter.run(); if (wasRemoved) { maybeAddback(fs); } } else { setter.run(); } maybeLogUpdate(fs, featCode); } // public void setWithCheck(FeatureStructureImplC fs, FeatureImpl feat, Runnable setter) { // boolean wasRemoved = checkForInvalidFeatureSetting(fs, feat); // setter.run(); // if (wasRemoved) { // maybeAddback(fs); // } // } /** * This method called by setters in JCas gen'd classes when * the setter must check for journaling * @param fs - * @param fi - * @param setter - */ public final void setWithJournal(FeatureStructureImplC fs, FeatureImpl fi, Runnable setter) { setter.run(); maybeLogUpdate(fs, fi); } public final boolean isLoggingNeeded(FeatureStructureImplC fs) { return this.svd.trackingMark != null && !this.svd.trackingMark.isNew(fs._id); } /** * @param fs the Feature Structure being updated * @param feat the feature of fs being updated, or null if fs is a primitive array * @param i the index being updated */ final public void maybeLogArrayUpdate(FeatureStructureImplC fs, FeatureImpl feat, int i) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, feat, i, 1); } } /** * @param fs the Feature Structure being updated * @param indexesPlus1 - a set of indexes (plus 1) that have been update */ final public void maybeLogArrayUpdates(FeatureStructureImplC fs, PositiveIntSet indexesPlus1) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, indexesPlus1); } } /** * @param fs a primitive array FS * @param startingIndex - * @param length number of consequtive items */ public final void maybeLogArrayUpdates(FeatureStructureImplC fs, int startingIndex, int length) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, null, startingIndex, length); } } final public void maybeLogUpdate(FeatureStructureImplC fs, FeatureImpl feat) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, feat); } } final public void maybeLogUpdate(FeatureStructureImplC fs, int featCode) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP)fs, getFeatFromCode_checked(featCode)); } } final public boolean isLogging() { return this.svd.trackingMark != null; } // /** // * Common setter code for features in Feature Structures // * // * These come in two styles: one with int values, one with Object values // * Object values are FS or Strings or JavaObjects // */ // // /** // * low level setter // * // * @param fs the feature structure // * @param feat the feature to set // * @param value - // */ // // public void setFeatureValue(FeatureStructureImplC fs, FeatureImpl feat, int value) { // fs.setIntValue(feat, value); //// boolean wasRemoved = checkForInvalidFeatureSetting(fs, feat.getCode()); //// fs._intData[feat.getAdjustedOffset()] = value; //// if (wasRemoved) { //// maybeAddback(fs); //// } //// maybeLogUpdate(fs, feat); // } /** * version for longs, uses two slots * Only called from FeatureStructureImplC after determining * there is no local field to use * Is here because of 3 calls to things in this class * @param fsIn the feature structure * @param feat the feature to set * @param v - */ public void setLongValue(FeatureStructureImplC fsIn, FeatureImpl feat, long v) { TOP fs = (TOP) fsIn; if (fs._inSetSortedIndex()) { boolean wasRemoved = checkForInvalidFeatureSetting(fs, feat.getCode()); fs._setLongValueNcNj(feat, v); if (wasRemoved) { maybeAddback(fs); } } else { fs._setLongValueNcNj(feat, v); } maybeLogUpdate(fs, feat); } void setFeatureValue(int fsRef, int featureCode, TOP value) { getFsFromId_checked(fsRef).setFeatureValue(getFeatFromCode_checked(featureCode), value); } /** * internal use - special setter for setting feature values, including * special handling if the feature is for the sofaArray, * when deserializing * @param fs - * @param feat - * @param value - */ public static void setFeatureValueMaybeSofa(TOP fs, FeatureImpl feat, TOP value) { if (fs instanceof Sofa) { assert feat.getCode() == sofaArrayFeatCode; ((Sofa)fs).setLocalSofaData(value); } else { fs.setFeatureValue(feat, value); } } /** * Internal use, for cases where deserializing - special case setting sofString to skip updating the document annotation * @param fs - * @param feat - * @param s - */ public static void setFeatureValueFromStringNoDocAnnotUpdate(FeatureStructureImplC fs, FeatureImpl feat, String s) { if (fs instanceof Sofa && feat.getCode() == sofaStringFeatCode) { ((Sofa)fs).setLocalSofaDataNoDocAnnotUpdate(s); } else { setFeatureValueFromString(fs, feat, s); } } /** * Supports setting slots to "0" for null values * @param fs The feature structure to update * @param feat the feature to update- * @param s the string representation of the value, could be null */ public static void setFeatureValueFromString(FeatureStructureImplC fs, FeatureImpl feat, String s) { final TypeImpl range = feat.getRangeImpl(); if (fs instanceof Sofa) { // sofa has special setters Sofa sofa = (Sofa) fs; switch (feat.getCode()) { case sofaMimeFeatCode : sofa.setMimeType(s); break; case sofaStringFeatCode: sofa.setLocalSofaData(s); break; case sofaUriFeatCode: sofa.setRemoteSofaURI(s); break; default: // left empty - ignore trying to set final fields } return; } if (feat.isInInt) { switch (range.getCode()) { case floatTypeCode : fs.setFloatValue(feat, (s == null) ? 0F : Float.parseFloat(s)); break; case booleanTypeCode : fs.setBooleanValue(feat, (s == null) ? false : Boolean.parseBoolean(s)); break; case longTypeCode : fs.setLongValue(feat, (s == null) ? 0L : Long.parseLong(s)); break; case doubleTypeCode : fs.setDoubleValue(feat, (s == null) ? 0D : Double.parseDouble(s)); break; case byteTypeCode : fs.setByteValue(feat, (s == null) ? 0 : Byte.parseByte(s)); break; case shortTypeCode : fs.setShortValue(feat, (s == null) ? 0 : Short.parseShort(s)); break; case intTypeCode : fs.setIntValue(feat, (s == null) ? 0 : Integer.parseInt(s)); break; default: fs.setIntValue(feat, (s == null) ? 0 : Integer.parseInt(s)); } } else if (range.isRefType) { if (s == null) { fs.setFeatureValue(feat, null); } else { // Setting a reference value "{0}" from a string is not supported. throw new CASRuntimeException(CASRuntimeException.SET_REF_FROM_STRING_NOT_SUPPORTED, feat.getName()); } } else if (range.isStringOrStringSubtype()) { // includes TypeImplSubString // is String or Substring fs.setStringValue(feat, (s == null) ? null : s); // } else if (range == getTypeSystemImpl().javaObjectType) { // fs.setJavaObjectValue(feat, (s == null) ? null : deserializeJavaObject(s)); } else { Misc.internalError(); } } // private Object deserializeJavaObject(String s) { // throw new UnsupportedOperationException("Deserializing JavaObjects not yet implemented"); // } // // static String serializeJavaObject(Object s) { // throw new UnsupportedOperationException("Serializing JavaObjects not yet implemented"); // } /* * This should be the only place where the encoding of floats and doubles in terms of ints is specified * Someday we may want to preserve NAN things using "raw" versions */ public static final float int2float(int i) { return Float.intBitsToFloat(i); } public static final int float2int(float f) { return Float.floatToIntBits(f); } public static final double long2double(long l) { return Double.longBitsToDouble(l); } public static final long double2long(double d) { return Double.doubleToLongBits(d); } // Type access methods. public final boolean isStringType(Type type) { return type instanceof TypeImpl_string; } public final boolean isAbstractArrayType(Type type) { return isArrayType(type); } public final boolean isArrayType(Type type) { return ((TypeImpl) type).isArray(); } public final boolean isPrimitiveArrayType(Type type) { return (type instanceof TypeImpl_array) && ! type.getComponentType().isPrimitive(); } public final boolean isIntArrayType(Type type) { return (type == getTypeSystemImpl().intArrayType); } public final boolean isFloatArrayType(Type type) { return ((TypeImpl)type).getCode() == floatArrayTypeCode; } public final boolean isStringArrayType(Type type) { return ((TypeImpl)type).getCode() == stringArrayTypeCode; } public final boolean isBooleanArrayType(Type type) { return ((TypeImpl)type).getCode() == booleanArrayTypeCode; } public final boolean isByteArrayType(Type type) { return ((TypeImpl)type).getCode() == byteArrayTypeCode; } public final boolean isShortArrayType(Type type) { return ((TypeImpl)type).getCode() == byteArrayTypeCode; } public final boolean isLongArrayType(Type type) { return ((TypeImpl)type).getCode() == longArrayTypeCode; } public final boolean isDoubleArrayType(Type type) { return ((TypeImpl)type).getCode() == doubleArrayTypeCode; } public final boolean isFSArrayType(Type type) { return ((TypeImpl)type).getCode() == fsArrayTypeCode; } public final boolean isIntType(Type type) { return ((TypeImpl)type).getCode() == intTypeCode; } public final boolean isFloatType(Type type) { return ((TypeImpl)type).getCode() == floatTypeCode; } public final boolean isByteType(Type type) { return ((TypeImpl)type).getCode() == byteTypeCode; } public final boolean isBooleanType(Type type) { return ((TypeImpl)type).getCode() == floatTypeCode; } public final boolean isShortType(Type type) { return ((TypeImpl)type).getCode() == shortTypeCode; } public final boolean isLongType(Type type) { return ((TypeImpl)type).getCode() == longTypeCode; } public final boolean isDoubleType(Type type) { return ((TypeImpl)type).getCode() == doubleTypeCode; } /* * Only called on base CAS */ /** * @see org.apache.uima.cas.admin.CASMgr#initCASIndexes() */ @Override public void initCASIndexes() throws CASException { final TypeSystemImpl ts = getTypeSystemImpl(); if (!ts.isCommitted()) { throw new CASException(CASException.MUST_COMMIT_TYPE_SYSTEM); } FSIndexComparator comp = this.indexRepository.createComparator(); comp.setType(ts.sofaType); comp.addKey(ts.sofaNum, FSIndexComparator.STANDARD_COMPARE); this.indexRepository.createIndex(comp, CAS.SOFA_INDEX_NAME, FSIndex.BAG_INDEX); comp = this.indexRepository.createComparator(); comp.setType(ts.annotType); comp.addKey(ts.startFeat, FSIndexComparator.STANDARD_COMPARE); comp.addKey(ts.endFeat, FSIndexComparator.REVERSE_STANDARD_COMPARE); comp.addKey(this.indexRepository.getDefaultTypeOrder(), FSIndexComparator.STANDARD_COMPARE); this.indexRepository.createIndex(comp, CAS.STD_ANNOTATION_INDEX); } // /////////////////////////////////////////////////////////////////////////// // CAS support ... create CAS view of aSofa // For internal use only public CAS getView(int sofaNum) { return svd.getViewFromSofaNbr(sofaNum); } @Override public CAS getCurrentView() { return getView(CAS.NAME_DEFAULT_SOFA); } // /////////////////////////////////////////////////////////////////////////// // JCas support @Override public JCas getJCas() { if (this.jcas == null) { this.jcas = JCasImpl.getJCas(this); } return this.jcas; } public JCasImpl getJCasImpl() { if (this.jcas == null) { this.jcas = JCasImpl.getJCas(this); } return this.jcas; } // /** // * Internal use only // * // * @return corresponding JCas, assuming it exists // */ // public JCas getExistingJCas() { // return this.jcas; // } // // Create JCas view of aSofa @Override public JCas getJCas(SofaFS aSofa) throws CASException { // Create base JCas, if needed this.svd.baseCAS.getJCas(); return getView(aSofa).getJCas(); /* * // If a JCas already exists for this Sofa, return it JCas aJCas = (JCas) * this.svd.baseCAS.sofa2jcasMap.get(Integer.valueOf(aSofa.getSofaRef())); if * (null != aJCas) { return aJCas; } // Get view of aSofa CASImpl view = * (CASImpl) getView(aSofa); // wrap in JCas aJCas = view.getJCas(); * this.sofa2jcasMap.put(Integer.valueOf(aSofa.getSofaRef()), aJCas); return * aJCas; */ } /** * @deprecated */ @Override @Deprecated public JCas getJCas(SofaID aSofaID) throws CASException { SofaFS sofa = getSofa(aSofaID); // sofa guaranteed to be non-null by above method. return getJCas(sofa); } // For internal platform use only CASImpl getInitialView() { return svd.getInitialView(); } @Override public CAS createView(String aSofaID) { // do sofa mapping for current component String absoluteSofaName = null; if (getCurrentComponentInfo() != null) { absoluteSofaName = getCurrentComponentInfo().mapToSofaID(aSofaID); } if (absoluteSofaName == null) { absoluteSofaName = aSofaID; } // Can't use name of Initial View if (CAS.NAME_DEFAULT_SOFA.equals(absoluteSofaName)) { throw new CASRuntimeException(CASRuntimeException.SOFANAME_ALREADY_EXISTS, aSofaID); } Sofa newSofa = createSofa(absoluteSofaName, null); CAS newView = getView(newSofa); ((CASImpl) newView).registerView(newSofa); return newView; } @Override public CAS getView(String aSofaID) { // do sofa mapping for current component String absoluteSofaName = null; if (getCurrentComponentInfo() != null) { absoluteSofaName = getCurrentComponentInfo().mapToSofaID(aSofaID); } if (absoluteSofaName == null) { absoluteSofaName = aSofaID; } // if this resolves to the Initial View, return view(1)... // ... as the Sofa for this view may not exist yet if (CAS.NAME_DEFAULT_SOFA.equals(absoluteSofaName)) { return getInitialView(); } // get Sofa and switch to view SofaFS sofa = getSofa(absoluteSofaName); // sofa guaranteed to be non-null by above method // unless sofa doesn't exist, which will cause a throw. return getView(sofa); } /* * (non-Javadoc) * * @see org.apache.uima.cas.CAS#getView(org.apache.uima.cas.SofaFS) * * Callers of this can have created Sofas in the CAS without views: using the * old deprecated createSofa apis (this is being fixed so these will create * the views) via deserialization, which will put the sofaFSs into the CAS * without creating the views, and then call this to create the views. - for * deserialization: there are 2 kinds: 1 is xmi the other is binary. - for * xmi: there is 1.4.x compatible and 2.1 compatible. The older format can * have sofaNbrs in the order 2, 3, 4, 1 (initial sofa), 5, 6, 7 The newer * format has them in order. For deserialized sofas, we insure here that there * are no duplicates. This is not done in the deserializers - they use either * heap dumping (binary) or generic fs creators (xmi). * * Goal is to detect case where check is needed (sofa exists, but view not yet * created). This is done by looking for cases where sofaNbr &gt; curViewCount. * This only works if the sofaNbrs go up by 1 (except for the initial sofa) in * the input sequence of calls. */ @Override public CASImpl getView(SofaFS aSofa) { Sofa sofa = (Sofa) aSofa; final int sofaNbr = sofa.getSofaRef(); // final Integer sofaNbrInteger = Integer.valueOf(sofaNbr); CASImpl aView = svd.getViewFromSofaNbr(sofaNbr); if (null == aView) { // This is the deserializer case, or the case where an older API created a // sofa, // which is now creating the associated view // create a new CAS view aView = new CASImpl(this.svd.baseCAS, sofa); svd.setViewForSofaNbr(sofaNbr, aView); verifySofaNameUniqueIfDeserializedViewAdded(sofaNbr, sofa); return aView; } // for deserialization - might be reusing a view, and need to tie new Sofa // to old View if (null == aView.mySofaRef) { aView.mySofaRef = sofa; } verifySofaNameUniqueIfDeserializedViewAdded(sofaNbr, aSofa); return aView; } // boolean isSofaView(int sofaAddr) { // if (mySofaRef == null) { // // don't create initial sofa // return false; // } // return mySofaRef == sofaAddr; // } /* * for Sofas being added (determined by sofaNbr &gt; curViewCount): verify sofa * name is not already present, and record it for future tests * * Only should do the name test & update in the case of deserialized new sofas * coming in. These will come in, in order. Exception is "_InitialView" which * could come in the middle. If it comes in the middle, no test will be done * for duplicates, and it won't be added to set of known names. This is ok * because the createVIew special cases this test. Users could corrupt an xmi * input, which would make this logic fail. */ private void verifySofaNameUniqueIfDeserializedViewAdded(int sofaNbr, SofaFS aSofa) { final int curViewCount = this.svd.viewCount; if (curViewCount < sofaNbr) { // Only true for deserialized sofas with new views being either created, // or // hooked-up from CASes that were freshly reset, which have multiple // views. // Assume sofa numbers are incrementing by 1 assert (sofaNbr == curViewCount + 1); this.svd.viewCount = sofaNbr; String id = aSofa.getSofaID(); // final Feature idFeat = // getTypeSystem().getFeatureByFullName(CAS.FEATURE_FULL_NAME_SOFAID); // String id = // ll_getStringValue(((FeatureStructureImpl)aSofa).getAddress(), // ((FeatureImpl) idFeat).getCode()); Misc.assertUie(this.svd.sofaNameSet.contains(id)); // this.svd.sofaNameSet.add(id); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getTypeSystem() */ @Override public LowLevelTypeSystem ll_getTypeSystem() { return getTypeSystemImpl().getLowLevelTypeSystem(); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getIndexRepository() */ @Override public LowLevelIndexRepository ll_getIndexRepository() { return this.indexRepository; } /** * * @param fs * @param domType * @param featCode */ private final void checkLowLevelParams(TOP fs, TypeImpl domType, int featCode) { checkFeature(featCode); checkTypeHasFeature(domType, featCode); } /** * Check that the featCode is a feature of the domain type * @param domTypeCode * @param featCode */ private final void checkTypeHasFeature(TypeImpl domainType, int featureCode) { checkTypeHasFeature(domainType, getFeatFromCode_checked(featureCode)); } private final void checkTypeHasFeature(TypeImpl domainType, FeatureImpl feature) { if (!domainType.isAppropriateFeature(feature)) { throw new LowLevelException(LowLevelException.FEAT_DOM_ERROR, Integer.valueOf(domainType.getCode()), domainType.getName(), Integer.valueOf(feature.getCode()), feature.getName()); } } /** * Check the range is appropriate for this type/feature. Throws * LowLevelException if it isn't. * * @param domType * domain type * @param ranType * range type * @param feat * feature */ public final void checkTypingConditions(Type domType, Type ranType, Feature feat) { TypeImpl domainTi = (TypeImpl) domType; FeatureImpl fi = (FeatureImpl) feat; checkTypeHasFeature(domainTi, fi); if (!((TypeImpl) fi.getRange()).subsumes((TypeImpl) ranType)) { throw new LowLevelException(LowLevelException.FEAT_RAN_ERROR, Integer.valueOf(fi.getCode()), feat.getName(), Integer.valueOf(((TypeImpl)ranType).getCode()), ranType.getName()); } } /** * Validate a feature's range is a ref to a feature structure * @param featCode * @throws LowLevelException */ private final void checkFsRan(FeatureImpl fi) throws LowLevelException { if (!fi.getRangeImpl().isRefType) { throw new LowLevelException(LowLevelException.FS_RAN_TYPE_ERROR, Integer.valueOf(fi.getCode()), fi.getName(), fi.getRange().getName()); } } private final void checkFeature(int featureCode) { if (!getTypeSystemImpl().isFeature(featureCode)) { throw new LowLevelException(LowLevelException.INVALID_FEATURE_CODE, Integer.valueOf(featureCode)); } } private TypeImpl getTypeFromCode(int typeCode) { return getTypeSystemImpl().getTypeForCode(typeCode); } private TypeImpl getTypeFromCode_checked(int typeCode) { return getTypeSystemImpl().getTypeForCode_checked(typeCode); } private FeatureImpl getFeatFromCode_checked(int featureCode) { return getTypeSystemImpl().getFeatureForCode_checked(featureCode); } public final <T extends TOP> T getFsFromId_checked(int fsRef) { T r = getFsFromId(fsRef); if (r == null) { if (fsRef == 0) { return null; } LowLevelException e = new LowLevelException(LowLevelException.INVALID_FS_REF, Integer.valueOf(fsRef)); // this form to enable seeing this even if the // throwable is silently handled. // System.err.println("debug " + e); throw e; } return r; } @Override public final boolean ll_isRefType(int typeCode) { return getTypeFromCode(typeCode).isRefType; } @Override public final int ll_getTypeClass(int typeCode) { return TypeSystemImpl.getTypeClass(getTypeFromCode(typeCode)); } // backwards compatibility only @Override public final int ll_createFS(int typeCode) { return ll_createFS(typeCode, true); } @Override public final int ll_createFS(int typeCode, boolean doCheck) { TypeImpl ti = (TypeImpl) getTypeSystemImpl().ll_getTypeForCode(typeCode); if (doCheck) { if (ti == null || !ti.isCreatableAndNotBuiltinArray()) { throw new LowLevelException(LowLevelException.CREATE_FS_OF_TYPE_ERROR, Integer.valueOf(typeCode)); } } TOP fs = (TOP) createFS(ti); if (!fs._isPearTrampoline()) { if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally(fs); // hold on to it if nothing else is } else { svd.id2fs.put(fs); // just like above, but has assert that wasn't there previously } } return fs._id; } /** * used for ll_setIntValue which changes type code * @param ti - the type of the created FS * @param id - the id to use * @return the FS */ private TOP createFsWithExistingId(TypeImpl ti, int id) { svd.reuseId = id; try { TOP fs = createFS(ti); svd.id2fs.putChange(id, fs); return fs; } finally { svd.reuseId = 0; } } /* /** * @param arrayLength * @return the id of the created array * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_createArray(int, int) */ @Override public int ll_createArray(int typeCode, int arrayLength) { TOP fs = createArray(getTypeFromCode_checked(typeCode), arrayLength); if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally(fs); } else { svd.id2fs.put(fs); } return fs._id; } /** * (for backwards compatibility with V2 CASImpl) * Create a temporary (i.e., per document) array FS on the heap. * * @param type * The type code of the array to be created. * @param len * The length of the array to be created. * @return - * @exception ArrayIndexOutOfBoundsException * If <code>type</code> is not a type. */ public int createTempArray(int type, int len) { return ll_createArray(type, len); } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createByteArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().byteArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createBooleanArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().booleanArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createShortArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().shortArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createLongArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().longArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createDoubleArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().doubleArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createArray(int typeCode, int arrayLength, boolean doChecks) { TypeImpl ti = getTypeFromCode_checked(typeCode); if (doChecks) { if (!ti.isArray()) { throw new LowLevelException(LowLevelException.CREATE_ARRAY_OF_TYPE_ERROR, Integer.valueOf(typeCode), ti.getName()); } if (arrayLength < 0) { throw new LowLevelException(LowLevelException.ILLEGAL_ARRAY_LENGTH, Integer.valueOf(arrayLength)); } } TOP fs = createArray(ti, arrayLength); svd.id2fs.put(fs); return fs._id; } public void validateArraySize(int length) { if (length < 0) { /** Array size must be &gt;= 0. */ throw new CASRuntimeException(CASRuntimeException.ILLEGAL_ARRAY_SIZE); } } /** * Safety - any time the low level API to a FS is requested, * hold on to that FS until CAS reset to mimic how v2 works. */ @Override public final int ll_getFSRef(FeatureStructure fs) { if (null == fs) { return NULL; } TOP fst = (TOP) fs; if (fst._isPearTrampoline()) { return fst._id; // no need to hold on to this one - it's in jcas hash maps } // uncond. because this method can be called multiple times svd.id2fs.putUnconditionally(fst); // hold on to it return ((FeatureStructureImplC)fs)._id; } @Override public <T extends TOP> T ll_getFSForRef(int id) { return getFsFromId_checked(id); } /** * Handle some unusual backwards compatibility cases * featureCode = 0 - implies getting the type code * feature range is int - normal * feature range is a fs reference, return the id * feature range is a string: add the string if not already present to the string heap, return the int handle. * @param fsRef - * @param featureCode - * @return - */ @Override public final int ll_getIntValue(int fsRef, int featureCode) { TOP fs = getFsFromId_checked(fsRef); if (featureCode == 0) { return fs._getTypeImpl().getCode(); // case where the type is being requested } FeatureImpl fi = getFeatFromCode_checked(featureCode); SlotKind kind = fi.getSlotKind(); switch(kind) { case Slot_HeapRef: return fs.getFeatureValue(fi)._id; case Slot_Boolean: case Slot_Byte: case Slot_Short: case Slot_Int: case Slot_Float: return fs._getIntValueNc(fi); case Slot_StrRef: return getCodeForString(fs._getStringValueNc(fi)); case Slot_LongRef: return getCodeForLong(fs._getLongValueNc(fi)); case Slot_DoubleRef: return getCodeForLong(CASImpl.double2long(fs._getDoubleValueNc(fi))); default: throw new CASRuntimeException( CASRuntimeException.INAPPROP_RANGE, fi.getName(), "int", fi.getRange().getName()); } } // public final int ll_getIntValueFeatOffset(int fsRef, int featureOffset) { // return ll_getFSForRef(fsRef)._intData[featureOffset]; // } @Override public final float ll_getFloatValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getFloatValue(getFeatFromCode_checked(featureCode)); } @Override public final String ll_getStringValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getStringValue(getFeatFromCode_checked(featureCode)); } // public final String ll_getStringValueFeatOffset(int fsRef, int featureOffset) { // return (String) getFsFromId_checked(fsRef)._refData[featureOffset]; // } @Override public final int ll_getRefValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getFeatureValue(getFeatFromCode_checked(featureCode))._id(); } // public final int ll_getRefValueFeatOffset(int fsRef, int featureOffset) { // return ((FeatureStructureImplC)getFsFromId_checked(fsRef)._refData[featureOffset]).id(); // } @Override public final int ll_getIntValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getIntValue(fsRef, featureCode); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getFloatValue(int, int, * boolean) */ @Override public final float ll_getFloatValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getFloatValue(fsRef, featureCode); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getStringValue(int, int, * boolean) */ @Override public final String ll_getStringValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getStringValue(fsRef, featureCode); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getRefValue(int, int, boolean) */ @Override public final int ll_getRefValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkFsRefConditions(fsRef, featureCode); } return getFsFromId_checked(fsRef).getFeatureValue(getFeatFromCode_checked(featureCode))._id(); } /** * This is the method all normal FS feature "setters" call before doing the set operation * on values where the range could be used as an index key. * <p> * If enabled, it will check if the update may corrupt any index in any view. The check tests * whether the feature is being used as a key in one or more indexes and if the FS is in one or more * corruptable view indexes. * <p> * If true, then: * <ul> * <li>it may remove and remember (for later adding-back) the FS from all corruptable indexes * (bag indexes are not corruptable via updating, so these are skipped). * The addback occurs later either via an explicit call to do so, or the end of a protectIndex block, or. * (if autoIndexProtect is enabled) after the individual feature update is completed.</li> * <li>it may give a WARN level message to the log. This enables users to * implement their own optimized handling of this for "high performance" * applications which do not want the overhead of runtime checking. </li></ul> * <p> * * @param fs - the FS to test if it is in the indexes * @param featCode - the feature being tested * @return true if something may need to be added back */ private boolean checkForInvalidFeatureSetting(TOP fs, int featCode) { if (doInvalidFeatSettingCheck(fs)) { if (!svd.featureCodesInIndexKeys.get(featCode)) { // skip if no index uses this feature return false; } boolean wasRemoved = checkForInvalidFeatureSetting2(fs); if (wasRemoved && doCorruptReport()) { featModWhileInIndexReport(fs, featCode); } return wasRemoved; } return false; } /** * version for deserializers, and for set document language, using their own store for toBeAdded * Doesn't report updating of corruptable slots. * @param fs - * @param featCode - * @param toBeAdded - * @return - */ boolean checkForInvalidFeatureSetting(TOP fs, int featCode, FSsTobeAddedback toBeAdded) { if (doInvalidFeatSettingCheck(fs)) { if (!svd.featureCodesInIndexKeys.get(featCode)) { // skip if no index uses this feature return false; } boolean wasRemoved = removeFromCorruptableIndexAnyView(fs, toBeAdded); // if (wasRemoved && doCorruptReport()) { // featModWhileInIndexReport(fs, featCode); // } return wasRemoved; } return false; } /** * version for deserializers, using their own store for toBeAdded * and not bothering to check for particular features * Doesn't report updating of corruptable slots. * @param fs - * @param featCode - * @param toBeAdded - * @return - */ boolean checkForInvalidFeatureSetting(TOP fs, FSsTobeAddedback toBeAdded) { if (doInvalidFeatSettingCheck(fs)) { boolean wasRemoved = removeFromCorruptableIndexAnyView(fs, toBeAdded); // if (wasRemoved && doCorruptReport()) { // featModWhileInIndexReport(fs, null); // } return wasRemoved; } return false; } // // version of above, but using jcasFieldRegistryIndex // private boolean checkForInvalidFeatureSettingJFRI(TOP fs, int jcasFieldRegistryIndex) { // if (doInvalidFeatSettingCheck(fs) && // svd.featureJiInIndexKeys.get(jcasFieldRegistryIndex)) { // // boolean wasRemoved = checkForInvalidFeatureSetting2(fs); // //// if (wasRemoved && doCorruptReport()) { //// featModWhileInIndexReport(fs, getFeatFromRegistry(jcasFieldRegistryIndex)); //// } // return wasRemoved; // } // return false; // } private boolean checkForInvalidFeatureSetting2(TOP fs) { final int ssz = svd.fssTobeAddedback.size(); // next method skips if the fsRef is not in the index (cache) boolean wasRemoved = removeFromCorruptableIndexAnyView( fs, (ssz > 0) ? getAddback(ssz) : // validates single not in use getAddbackSingle() // validates single usage at a time ); if (!wasRemoved && svd.fsTobeAddedbackSingleInUse) { svd.fsTobeAddedbackSingleInUse = false; } return wasRemoved; } // public FeatureImpl getFeatFromRegistry(int jcasFieldRegistryIndex) { // return getFSClassRegistry().featuresFromJFRI[jcasFieldRegistryIndex]; // } private boolean doCorruptReport() { return // skip message if wasn't removed // skip message if protected in explicit block IS_REPORT_FS_UPDATE_CORRUPTS_INDEX && svd.fssTobeAddedback.size() == 0; } /** * * @param fs - * @return false if the fs is not in a set or sorted index (bit in fs), or * the auto protect is disabled and we're not in an explicit protect block */ private boolean doInvalidFeatSettingCheck(TOP fs) { if (!fs._inSetSortedIndex()) { return false; } final int ssz = svd.fssTobeAddedback.size(); // skip if protection is disabled, and no explicit protection block if (IS_DISABLED_PROTECT_INDEXES && ssz == 0) { return false; } return true; } private void featModWhileInIndexReport(FeatureStructure fs, int featCode) { featModWhileInIndexReport(fs, getFeatFromCode_checked(featCode)); } private void featModWhileInIndexReport(FeatureStructure fs, FeatureImpl fi) { // prepare a message which includes the feature which is a key, the fs, and // the call stack. StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); new Throwable().printStackTrace(pw); pw.close(); String msg = String.format( "While FS was in the index, the feature \"%s\"" + ", which is used as a key in one or more indexes, " + "was modified\n FS = \"%s\"\n%s%n", (fi == null)? "for-all-features" : fi.getName(), fs.toString(), sw.toString()); UIMAFramework.getLogger().log(Level.WARNING, msg); if (IS_THROW_EXCEPTION_CORRUPT_INDEX) { throw new UIMARuntimeException(UIMARuntimeException.ILLEGAL_FS_FEAT_UPDATE, new Object[]{}); } } /** * Only called if there was something removed that needs to be added back * * skip the addback (to defer it until later) if: * - running in block mode (you can tell this if svd.fssTobeAddedback.size() &gt; 0) or * if running in block mode, the add back is delayed until the end of the block * * @param fs the fs to add back */ public void maybeAddback(TOP fs) { if (svd.fssTobeAddedback.size() == 0) { assert(svd.fsTobeAddedbackSingleInUse); svd.fsTobeAddedbackSingle.addback(fs); svd.fsTobeAddedbackSingleInUse = false; } } boolean removeFromCorruptableIndexAnyView(final TOP fs, FSsTobeAddedback toBeAdded) { return removeFromIndexAnyView(fs, toBeAdded, FSIndexRepositoryImpl.SKIP_BAG_INDEXES); } /** * This might be called from low level set int value, if we support switching types, and we want to * remove the old type from all indexes. * @param fs the fs to maybe remove * @param toBeAdded a place to record the removal so we can add it back later * @param isSkipBagIndexes is true usually, we don't need to remove/readd to bag indexes (except for the case * of supporting switching types via low level set int for v2 backwards compatibility) * @return true if was removed from one or more indexes */ boolean removeFromIndexAnyView(final TOP fs, FSsTobeAddedback toBeAdded, boolean isSkipBagIndexes) { final TypeImpl ti = ((FeatureStructureImplC)fs)._getTypeImpl(); if (ti.isAnnotationBaseType()) { boolean r = removeAndRecord(fs, (FSIndexRepositoryImpl) fs._casView.getIndexRepository(), toBeAdded, isSkipBagIndexes); fs._resetInSetSortedIndex(); return r; } // not a subtype of AnnotationBase, need to check all views (except base) // sofas indexed in the base view are not corruptable. final Iterator<CAS> viewIterator = getViewIterator(); boolean wasRemoved = false; while (viewIterator.hasNext()) { wasRemoved |= removeAndRecord(fs, (FSIndexRepositoryImpl) viewIterator.next().getIndexRepository(), toBeAdded, isSkipBagIndexes); } fs._resetInSetSortedIndex(); return wasRemoved; } /** * remove a FS from all indexes in this view (except bag indexes, if isSkipBagIndex is true) * @param fs the fs to be removed * @param ir the view * @param toBeAdded the place to record how many times it was in the index, per view * @param isSkipBagIndex set to true for corruptable removes, false for remove in all cases from all indexes * @return true if it was removed, false if it wasn't in any corruptable index. */ private boolean removeAndRecord(TOP fs, FSIndexRepositoryImpl ir, FSsTobeAddedback toBeAdded, boolean isSkipBagIndex) { boolean wasRemoved = ir.removeFS_ret(fs, isSkipBagIndex); if (wasRemoved) { toBeAdded.recordRemove(fs, ir, 1); } return wasRemoved; } /** * Special considerations: * Interface with corruption checking * For backwards compatibility: * handle cases where feature is: * int - normal * 0 - change type code * a ref: treat int as FS "addr" * not an int: handle like v2 where reasonable */ @Override public final void ll_setIntValue(int fsRef, int featureCode, int value) { TOP fs = getFsFromId_checked(fsRef); if (featureCode == 0) { switchFsType(fs, value); return; } FeatureImpl fi = getFeatFromCode_checked(featureCode); if (fs._getTypeImpl().isArray()) { throw new UnsupportedOperationException("ll_setIntValue not permitted to set a feature of an array"); } SlotKind kind = fi.getSlotKind(); switch(kind) { case Slot_HeapRef: if (fi.getCode() == annotBaseSofaFeatCode) { // setting the sofa ref of an annotationBase // can't change this so just verify it's the same TOP sofa = fs.getFeatureValue(fi); if (sofa._id != value) { throw new UnsupportedOperationException("ll_setIntValue not permitted to change a sofaRef feature"); } return; // if the same, just ignore, already set } TOP ref = fs._casView.getFsFromId_checked(value); fs.setFeatureValue(fi, ref); // does the right feature check, too return; case Slot_Boolean: case Slot_Byte: case Slot_Short: case Slot_Int: case Slot_Float: fs._setIntValueCJ(fi, value); break; case Slot_StrRef: String s = getStringForCode(value); if (s == null && value != 0) { Misc.internalError(new Exception("ll_setIntValue got null string for non-0 handle: " + value)); } fs._setRefValueNfcCJ(fi, getStringForCode(value)); break; case Slot_LongRef: case Slot_DoubleRef: Long lng = getLongForCode(value); if (lng == null) { Misc.internalError(new Exception("ll_setIntValue got null Long/Double for handle: " + value)); } fs._setLongValueNfcCJ(fi, lng); break; default: CASRuntimeException e = new CASRuntimeException(CASRuntimeException.INAPPROP_RANGE, fi.getName(), "int", fi.getRange().getName()); // System.err.println("debug " + e); throw e; } } private String getStringForCode(int i) { if (null == svd.llstringSet) { return null; } return svd.llstringSet.getStringForCode(i); } private int getCodeForString(String s) { if (null == svd.llstringSet) { svd.llstringSet = new StringSet(); } return svd.llstringSet.getCodeForString(s); // avoids adding duplicates } private Long getLongForCode(int i) { if (null == svd.lllongSet) { return null; } return svd.lllongSet.getLongForCode(i); } private int getCodeForLong(long s) { if (null == svd.lllongSet) { svd.lllongSet = new LongSet(); } return svd.lllongSet.getCodeForLong(s); // avoids adding duplicates } private void switchFsType(TOP fs, int value) { // throw new UnsupportedOperationException(); // case where the type is being changed // if the new type is a sub/super type of the existing type, // some field data may be copied // if not, no data is copied. // // Item is removed from index and re-indexed // to emulate what V2 did, // the indexing didn't change // all the slots were the same // boolean wasRemoved = removeFromIndexAnyView(fs, getAddbackSingle(), FSIndexRepositoryImpl.INCLUDE_BAG_INDEXES); if (!wasRemoved) { svd.fsTobeAddedbackSingleInUse = false; } TypeImpl newType = getTypeFromCode_checked(value); Class<?> newClass = newType.getJavaClass(); if ((fs instanceof UimaSerializable) || UimaSerializable.class.isAssignableFrom(newClass)) { throw new UnsupportedOperationException("can't switch type to/from UimaSerializable"); } // Measurement - record which type gets switched to which other type // count how many times // record which JCas cover class goes with each type // key = old type, new type, old jcas cover class, new jcas cover class // value = count MeasureSwitchType mst = null; if (MEASURE_SETINT) { MeasureSwitchType key = new MeasureSwitchType(fs._getTypeImpl(), newType); synchronized (measureSwitches) { // map access / updating must be synchronized mst = measureSwitches.get(key); if (null == mst) { measureSwitches.put(key, key); mst = key; } mst.count ++; mst.newSubsumesOld = newType.subsumes(fs._getTypeImpl()); mst.oldSubsumesNew = fs._getTypeImpl().subsumes(newType); } } if (newClass == fs._getTypeImpl().getJavaClass() || newType.subsumes(fs._getTypeImpl())) { // switch in place fs._setTypeImpl(newType); return; } // if types don't subsume each other, we // deviate a bit from V2 behavior // and skip copying the feature slots boolean isOkToCopyFeatures = // true || // debug fs._getTypeImpl().subsumes(newType) || newType.subsumes(fs._getTypeImpl()); // throw new CASRuntimeException(CASRuntimeException.ILLEGAL_TYPE_CHANGE, newType.getName(), fs._getTypeImpl().getName()); TOP newFs = createFsWithExistingId(newType, fs._id); // updates id -> fs map // initialize fields: if (isOkToCopyFeatures) { newFs._copyIntAndRefArraysFrom(fs); } // if (wasRemoved) { // addbackSingle(newFs); // } // replace refs in existing FSs with new // will miss any fs's held by user code - no way to fix that without // universal indirection - very inefficient, so just accept for now long st = System.nanoTime(); walkReachablePlusFSsSorted(fsItem -> { if (fsItem._getTypeImpl().hasRefFeature) { if (fsItem instanceof FSArray) { TOP[] a = ((FSArray)fsItem)._getTheArray(); for (int i = 0; i < a.length; i++) { if (fs == a[i]) { a[i] = newFs; } } return; } final int sz = fsItem._getTypeImpl().nbrOfUsedRefDataSlots; for (int i = 0; i < sz; i++) { Object o = fsItem._getRefValueCommon(i); if (o == fs) { fsItem._setRefValueCommon(i, newFs); // fsItem._refData[i] = newFs; } } } }, null, // mark null, // null or predicate for filtering what gets added null); // null or type mapper, skips if not in other ts if (MEASURE_SETINT) { mst.scantime += System.nanoTime() - st; } } @Override public final void ll_setFloatValue(int fsRef, int featureCode, float value) { getFsFromId_checked(fsRef).setFloatValue(getFeatFromCode_checked(featureCode), value); } // public final void ll_setFloatValueNoIndexCorruptionCheck(int fsRef, int featureCode, float value) { // setFeatureValueNoIndexCorruptionCheck(fsRef, featureCode, float2int(value)); // } @Override public final void ll_setStringValue(int fsRef, int featureCode, String value) { getFsFromId_checked(fsRef).setStringValue(getFeatFromCode_checked(featureCode), value); } @Override public final void ll_setRefValue(int fsRef, int featureCode, int value) { // no index check because refs can't be keys setFeatureValue(fsRef, featureCode, getFsFromId_checked(value)); } @Override public final void ll_setIntValue(int fsRef, int featureCode, int value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setIntValue(fsRef, featureCode, value); } @Override public final void ll_setFloatValue(int fsRef, int featureCode, float value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setFloatValue(fsRef, featureCode, value); } @Override public final void ll_setStringValue(int fsRef, int featureCode, String value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setStringValue(fsRef, featureCode, value); } @Override public final void ll_setCharBufferValue(int fsRef, int featureCode, char[] buffer, int start, int length, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setCharBufferValue(fsRef, featureCode, buffer, start, length); } @Override public final void ll_setCharBufferValue(int fsRef, int featureCode, char[] buffer, int start, int length) { ll_setStringValue(fsRef, featureCode, new String(buffer, start, length)); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_copyCharBufferValue(int, int, * char, int) */ @Override public int ll_copyCharBufferValue(int fsRef, int featureCode, char[] buffer, int start) { String str = ll_getStringValue(fsRef, featureCode); if (str == null) { return -1; } final int len = str.length(); final int requestedMax = start + len; // Check that the buffer is long enough to copy the whole string. If it isn't long enough, we // copy up to buffer.length - start characters. final int max = (buffer.length < requestedMax) ? (buffer.length - start) : len; for (int i = 0; i < max; i++) { buffer[start + i] = str.charAt(i); } return len; } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getCharBufferValueSize(int, * int) */ @Override public int ll_getCharBufferValueSize(int fsRef, int featureCode) { String str = ll_getStringValue(fsRef, featureCode); return str.length(); } @Override public final void ll_setRefValue(int fsRef, int featureCode, int value, boolean doTypeChecks) { if (doTypeChecks) { checkFsRefConditions(fsRef, featureCode); } ll_setRefValue(fsRef, featureCode, value); } public final int getIntArrayValue(IntegerArray array, int i) { return array.get(i); } public final float getFloatArrayValue(FloatArray array, int i) { return array.get(i); } public final String getStringArrayValue(StringArray array, int i) { return array.get(i); } public final FeatureStructure getRefArrayValue(FSArray array, int i) { return array.get(i); } @Override public final int ll_getIntArrayValue(int fsRef, int position) { return getIntArrayValue(((IntegerArray)getFsFromId_checked(fsRef)), position); } @Override public final float ll_getFloatArrayValue(int fsRef, int position) { return getFloatArrayValue(((FloatArray)getFsFromId_checked(fsRef)), position); } @Override public final String ll_getStringArrayValue(int fsRef, int position) { return getStringArrayValue(((StringArray)getFsFromId_checked(fsRef)), position); } @Override public final int ll_getRefArrayValue(int fsRef, int position) { return ((TOP)getRefArrayValue(((FSArray)getFsFromId_checked(fsRef)), position))._id(); } private void throwAccessTypeError(int fsRef, int typeCode) { throw new LowLevelException(LowLevelException.ACCESS_TYPE_ERROR, Integer.valueOf(fsRef), Integer.valueOf(typeCode), getTypeSystemImpl().ll_getTypeForCode(typeCode).getName(), getTypeSystemImpl().ll_getTypeForCode(ll_getFSRefType(fsRef)).getName()); } public final void checkArrayBounds(int fsRef, int pos) { final int arrayLength = ll_getArraySize(fsRef); if ((pos < 0) || (pos >= arrayLength)) { throw new ArrayIndexOutOfBoundsException(pos); // LowLevelException e = new LowLevelException( // LowLevelException.ARRAY_INDEX_OUT_OF_RANGE); // e.addArgument(Integer.toString(pos)); // throw e; } } public final void checkArrayBounds(int arrayLength, int pos, int length) { if ((pos < 0) || (length < 0) || ((pos + length) > arrayLength)) { throw new LowLevelException(LowLevelException.ARRAY_INDEX_LENGTH_OUT_OF_RANGE, Integer.toString(pos), Integer.toString(length)); } } /** * Check that the fsRef is valid. * Check that the fs is featureCode belongs to the fs * Check that the featureCode is one of the features of the domain type of the fsRef * feat could be primitive, string, ref to another feature * * @param fsRef * @param typeCode * @param featureCode */ private final void checkNonArrayConditions(int fsRef, int featureCode) { TOP fs = getFsFromId_checked(fsRef); final TypeImpl domainType = (TypeImpl) fs.getType(); // checkTypeAt(domType, fs); // since the type is from the FS, it's always OK checkFeature(featureCode); // checks that the featureCode is in the range of all feature codes TypeSystemImpl tsi = getTypeSystemImpl(); FeatureImpl fi = tsi.getFeatureForCode_checked(featureCode); checkTypeHasFeature(domainType, fi); // checks that the feature code is one of the features of the type // checkFsRan(fi); } private final void checkFsRefConditions(int fsRef, int featureCode) { TOP fs = getFsFromId_checked(fsRef); checkLowLevelParams(fs, fs._getTypeImpl(), featureCode); // checks type has feature TypeSystemImpl tsi = getTypeSystemImpl(); FeatureImpl fi = tsi.getFeatureForCode_checked(featureCode); checkFsRan(fi); // next not needed because checkFsRan already validates this // checkFsRef(fsRef + this.svd.casMetadata.featureOffset[featureCode]); } // private final void checkArrayConditions(int fsRef, int typeCode, // int position) { // checkTypeSubsumptionAt(fsRef, typeCode); // // skip this next test because // // a) it's done implicitly in the bounds check and // // b) it fails for arrays stored outside of the main heap (e.g., // byteArrays, etc.) // // checkFsRef(getArrayStartAddress(fsRef) + position); // checkArrayBounds(fsRef, position); // } private final void checkPrimitiveArrayConditions(int fsRef, int typeCode, int position) { if (typeCode != ll_getFSRefType(fsRef)) { throwAccessTypeError(fsRef, typeCode); } checkArrayBounds(fsRef, position); } @Override public final int ll_getIntArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, intArrayTypeCode, position); } return ll_getIntArrayValue(fsRef, position); } @Override public float ll_getFloatArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, floatArrayTypeCode, position); } return ll_getFloatArrayValue(fsRef, position); } @Override public String ll_getStringArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, stringArrayTypeCode, position); } return ll_getStringArrayValue(fsRef, position); } @Override public int ll_getRefArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, fsArrayTypeCode, position); } return ll_getRefArrayValue(fsRef, position); } @Override public void ll_setIntArrayValue(int fsRef, int position, int value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, intArrayTypeCode, position); } ll_setIntArrayValue(fsRef, position, value); } @Override public void ll_setFloatArrayValue(int fsRef, int position, float value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, floatArrayTypeCode, position); } ll_setFloatArrayValue(fsRef, position, value); } @Override public void ll_setStringArrayValue(int fsRef, int position, String value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, stringArrayTypeCode, position); } ll_setStringArrayValue(fsRef, position, value); } @Override public void ll_setRefArrayValue(int fsRef, int position, int value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, fsArrayTypeCode, position); } ll_setRefArrayValue(fsRef, position, value); } /* ************************ * Low Level Array Setters * ************************/ @Override public void ll_setIntArrayValue(int fsRef, int position, int value) { IntegerArray array = getFsFromId_checked(fsRef); array.set(position, value); // that set operation does required journaling } @Override public void ll_setFloatArrayValue(int fsRef, int position, float value) { FloatArray array = getFsFromId_checked(fsRef); array.set(position, value); // that set operation does required journaling } @Override public void ll_setStringArrayValue(int fsRef, int position, String value) { StringArray array = getFsFromId_checked(fsRef); array.set(position, value); // that set operation does required journaling } @Override public void ll_setRefArrayValue(int fsRef, int position, int value) { FSArray array = getFsFromId_checked(fsRef); array.set(position, getFsFromId_checked(value)); // that set operation does required journaling } /** * @param fsRef an id for a FS * @return the type code for this FS */ @Override public int ll_getFSRefType(int fsRef) { return getFsFromId_checked(fsRef)._getTypeCode(); } @Override public int ll_getFSRefType(int fsRef, boolean doChecks) { // type code is always valid return ll_getFSRefType(fsRef); } @Override public LowLevelCAS getLowLevelCAS() { return this; } @Override public int size() { throw new UIMARuntimeException(UIMARuntimeException.INTERNAL_ERROR); } /* * (non-Javadoc) * * @see org.apache.uima.cas.admin.CASMgr#getJCasClassLoader() */ @Override public ClassLoader getJCasClassLoader() { return this.svd.jcasClassLoader; } /* * Called to set the overall jcas class loader to use. * * @see org.apache.uima.cas.admin.CASMgr#setJCasClassLoader(java.lang.ClassLoader) */ @Override public void setJCasClassLoader(ClassLoader classLoader) { this.svd.jcasClassLoader = classLoader; } // Internal use only, public for cross package use // Assumes: The JCasClassLoader for a CAS is set up initially when the CAS is // created // and not switched (other than by this code) once it is set. // Callers of this method always code the "restoreClassLoaderUnlockCAS" in // pairs, // protected as needed with try - finally blocks. // // Special handling is needed for CAS Mulipliers - they can modify a cas up to // the point they no longer "own" it. // So the try / finally approach doesn't fit public void switchClassLoaderLockCas(Object userCode) { switchClassLoaderLockCasCL(userCode.getClass().getClassLoader()); } public void switchClassLoaderLockCasCL(ClassLoader newClassLoader) { // lock out CAS functions to which annotator should not have access enableReset(false); svd.switchClassLoader(newClassLoader); } // // internal use, public for cross-package ref // public boolean usingBaseClassLoader() { // return (this.svd.jcasClassLoader == this.svd.previousJCasClassLoader); // } public void restoreClassLoaderUnlockCas() { // unlock CAS functions enableReset(true); // this might be called without the switch ever being called svd.restoreClassLoader(); } @Override public FeatureValuePath createFeatureValuePath(String featureValuePath) throws CASRuntimeException { return FeatureValuePathImpl.getFeaturePath(featureValuePath); } @Override public void setOwner(CasOwner aCasOwner) { CASImpl baseCas = getBaseCAS(); if (baseCas != this) { baseCas.setOwner(aCasOwner); } else { super.setOwner(aCasOwner); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.AbstractCas_ImplBase#release() */ @Override public void release() { CASImpl baseCas = getBaseCAS(); if (baseCas != this) { baseCas.release(); } else { super.release(); } } /* ********************************** * A R R A Y C R E A T I O N ************************************/ @Override public ByteArrayFS createByteArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new ByteArray(this.getJCas(), length); } @Override public BooleanArrayFS createBooleanArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new BooleanArray(this.getJCas(), length); } @Override public ShortArrayFS createShortArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new ShortArray(this.getJCas(), length); } @Override public LongArrayFS createLongArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new LongArray(this.getJCas(), length); } @Override public DoubleArrayFS createDoubleArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new DoubleArray(this.getJCas(), length); } @Override public byte ll_getByteValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getByteValue(getFeatFromCode_checked(featureCode)); } @Override public byte ll_getByteValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getByteValue(fsRef, featureCode); } @Override public boolean ll_getBooleanValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getBooleanValue(getFeatFromCode_checked(featureCode)); } @Override public boolean ll_getBooleanValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getBooleanValue(fsRef, featureCode); } @Override public short ll_getShortValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getShortValue(getFeatFromCode_checked(featureCode)); } @Override public short ll_getShortValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getShortValue(fsRef, featureCode); } // impossible to implement in v3; change callers // public long ll_getLongValue(int offset) { // return this.getLongHeap().getHeapValue(offset); // } @Override public long ll_getLongValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getLongValue(getFeatFromCode_checked(featureCode)); } // public long ll_getLongValueFeatOffset(int fsRef, int offset) { // TOP fs = getFsFromId_checked(fsRef); // return fs.getLongValueOffset(offset); // } @Override public long ll_getLongValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getLongValue(fsRef, featureCode); } @Override public double ll_getDoubleValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getDoubleValue(getFeatFromCode_checked(featureCode)); } // public double ll_getDoubleValueFeatOffset(int fsRef, int offset) { // TOP fs = getFsFromId_checked(fsRef); // return fs.getDoubleValueOffset(offset); // } @Override public double ll_getDoubleValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getDoubleValue(fsRef, featureCode); } @Override public void ll_setBooleanValue(int fsRef, int featureCode, boolean value) { getFsFromId_checked(fsRef).setBooleanValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setBooleanValue(int fsRef, int featureCode, boolean value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setBooleanValue(fsRef, featureCode, value); } @Override public final void ll_setByteValue(int fsRef, int featureCode, byte value) { getFsFromId_checked(fsRef).setByteValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setByteValue(int fsRef, int featureCode, byte value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setByteValue(fsRef, featureCode, value); } @Override public final void ll_setShortValue(int fsRef, int featureCode, short value) { getFsFromId_checked(fsRef).setShortValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setShortValue(int fsRef, int featureCode, short value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setShortValue(fsRef, featureCode, value); } @Override public void ll_setLongValue(int fsRef, int featureCode, long value) { getFsFromId_checked(fsRef).setLongValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setLongValue(int fsRef, int featureCode, long value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setLongValue(fsRef, featureCode, value); } @Override public void ll_setDoubleValue(int fsRef, int featureCode, double value) { getFsFromId_checked(fsRef).setDoubleValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setDoubleValue(int fsRef, int featureCode, double value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setDoubleValue(fsRef, featureCode, value); } @Override public byte ll_getByteArrayValue(int fsRef, int position) { return ((ByteArray) getFsFromId_checked(fsRef)).get(position); } @Override public byte ll_getByteArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getByteArrayValue(fsRef, position); } @Override public boolean ll_getBooleanArrayValue(int fsRef, int position) { return ((BooleanArray) getFsFromId_checked(fsRef)).get(position); } @Override public boolean ll_getBooleanArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getBooleanArrayValue(fsRef, position); } @Override public short ll_getShortArrayValue(int fsRef, int position) { return ((ShortArray) getFsFromId_checked(fsRef)).get(position); } @Override public short ll_getShortArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getShortArrayValue(fsRef, position); } @Override public long ll_getLongArrayValue(int fsRef, int position) { return ((LongArray) getFsFromId_checked(fsRef)).get(position); } @Override public long ll_getLongArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getLongArrayValue(fsRef, position); } @Override public double ll_getDoubleArrayValue(int fsRef, int position) { return ((DoubleArray) getFsFromId_checked(fsRef)).get(position); } @Override public double ll_getDoubleArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getDoubleArrayValue(fsRef, position); } @Override public void ll_setByteArrayValue(int fsRef, int position, byte value) { ((ByteArray) getFsFromId_checked(fsRef)).set(position, value); } @Override public void ll_setByteArrayValue(int fsRef, int position, byte value, boolean doTypeChecks) { ll_setByteArrayValue(fsRef, position, value);} @Override public void ll_setBooleanArrayValue(int fsRef, int position, boolean b) { ((BooleanArray) getFsFromId_checked(fsRef)).set(position, b); } @Override public void ll_setBooleanArrayValue(int fsRef, int position, boolean value, boolean doTypeChecks) { ll_setBooleanArrayValue(fsRef, position, value); } @Override public void ll_setShortArrayValue(int fsRef, int position, short value) { ((ShortArray) getFsFromId_checked(fsRef)).set(position, value); } @Override public void ll_setShortArrayValue(int fsRef, int position, short value, boolean doTypeChecks) { ll_setShortArrayValue(fsRef, position, value); } @Override public void ll_setLongArrayValue(int fsRef, int position, long value) { ((LongArray) getFsFromId_checked(fsRef)).set(position, value); } @Override public void ll_setLongArrayValue(int fsRef, int position, long value, boolean doTypeChecks) { ll_setLongArrayValue(fsRef, position, value); } @Override public void ll_setDoubleArrayValue(int fsRef, int position, double d) { ((DoubleArray) getFsFromId_checked(fsRef)).set(position, d); } @Override public void ll_setDoubleArrayValue(int fsRef, int position, double value, boolean doTypeChecks) { ll_setDoubleArrayValue(fsRef, position, value); } public boolean isAnnotationType(Type t) { return ((TypeImpl)t).isAnnotationType(); } /** * @param t the type code to test * @return true if that type is subsumed by AnnotationBase type */ public boolean isSubtypeOfAnnotationBaseType(int t) { TypeImpl ti = getTypeFromCode(t); return (ti == null) ? false : ti.isAnnotationBaseType(); } public boolean isBaseCas() { return this == getBaseCAS(); } @Override public Annotation createAnnotation(Type type, int begin, int end) { // duplicates a later check // if (this.isBaseCas()) { // // Can't create annotation on base CAS // throw new CASRuntimeException(CASRuntimeException.INVALID_BASE_CAS_METHOD, "createAnnotation(Type, int, int)"); // } Annotation fs = (Annotation) createFS(type); fs.setBegin(begin); fs.setEnd(end); return fs; } public int ll_createAnnotation(int typeCode, int begin, int end) { TOP fs = createAnnotation(getTypeFromCode(typeCode), begin, end); svd.id2fs.put(fs); // to prevent gc from reclaiming return fs._id(); } /** * The generic spec T extends AnnotationFS (rather than AnnotationFS) allows the method * JCasImpl getAnnotationIndex to return Annotation instead of AnnotationFS * @param <T> the Java class associated with the annotation index * @return the annotation index */ @Override public <T extends AnnotationFS> AnnotationIndex<T> getAnnotationIndex() { return (AnnotationIndex<T>) indexRepository.getAnnotationIndex(getTypeSystemImpl().annotType); } /* (non-Javadoc) * @see org.apache.uima.cas.CAS#getAnnotationIndex(org.apache.uima.cas.Type) */ @Override public <T extends AnnotationFS> AnnotationIndex<T> getAnnotationIndex(Type type) throws CASRuntimeException { return (AnnotationIndex<T>) indexRepository.getAnnotationIndex((TypeImpl) type); } /** * @see org.apache.uima.cas.CAS#getAnnotationType() */ @Override public Type getAnnotationType() { return getTypeSystemImpl().annotType; } /** * @see org.apache.uima.cas.CAS#getEndFeature() */ @Override public Feature getEndFeature() { return getTypeSystemImpl().endFeat; } /** * @see org.apache.uima.cas.CAS#getBeginFeature() */ @Override public Feature getBeginFeature() { return getTypeSystemImpl().startFeat; } private <T extends AnnotationFS> T createDocumentAnnotation(int length) { final TypeSystemImpl ts = getTypeSystemImpl(); // Remove any existing document annotations. FSIterator<T> it = this.<T>getAnnotationIndex(ts.docType).iterator(); List<T> list = new ArrayList<T>(); while (it.isValid()) { list.add(it.get()); it.moveToNext(); } for (int i = 0; i < list.size(); i++) { getIndexRepository().removeFS(list.get(i)); } return (T) createDocumentAnnotationNoRemove(length); } private <T extends Annotation> T createDocumentAnnotationNoRemove(int length) { T docAnnot = createDocumentAnnotationNoRemoveNoIndex(length); addFsToIndexes(docAnnot); return docAnnot; } public <T extends Annotation> T createDocumentAnnotationNoRemoveNoIndex(int length) { final TypeSystemImpl ts = getTypeSystemImpl(); AnnotationFS docAnnot = createAnnotation(ts.docType, 0, length); docAnnot.setStringValue(ts.langFeat, CAS.DEFAULT_LANGUAGE_NAME); return (T) docAnnot; } public int ll_createDocumentAnnotation(int length) { final int fsRef = ll_createDocumentAnnotationNoIndex(0, length); ll_getIndexRepository().ll_addFS(fsRef); return fsRef; } public int ll_createDocumentAnnotationNoIndex(int begin, int end) { final TypeSystemImpl ts = getTypeSystemImpl(); int fsRef = ll_createAnnotation(ts.docType.getCode(), begin, end); ll_setStringValue(fsRef, ts.langFeat.getCode(), CAS.DEFAULT_LANGUAGE_NAME); return fsRef; } // For the "built-in" instance of Document Annotation, set the // "end" feature to be the length of the sofa string /** * updates the document annotation (only if the sofa's local string data != null) * setting the end feature to be the length of the sofa string, if any. * creates the document annotation if not present * only works if not in the base cas * */ public void updateDocumentAnnotation() { if (!mySofaIsValid() || this == this.svd.baseCAS) { return; } String newDoc = this.mySofaRef.getLocalStringData(); if (null != newDoc) { Annotation docAnnot = getDocumentAnnotationNoCreate(); if (docAnnot != null) { // use a local instance of the add-back memory because this may be called as a side effect of updating a sofa FSsTobeAddedback tobeAddedback = FSsTobeAddedback.createSingle(); boolean wasRemoved = this.checkForInvalidFeatureSetting( docAnnot, getTypeSystemImpl().endFeat.getCode(), tobeAddedback); docAnnot._setIntValueNfc(endFeatAdjOffset, newDoc.length()); if (wasRemoved) { tobeAddedback.addback(docAnnot); } } else { // not in the index (yet) createDocumentAnnotation(newDoc.length()); } } return; } /** * Generic issue: The returned document annotation could be either an instance of * DocumentAnnotation or a subclass of it, or an instance of Annotation - the Java cover class used for * annotations when JCas is not being used. */ @Override public <T extends AnnotationFS> T getDocumentAnnotation() { T docAnnot = (T) getDocumentAnnotationNoCreate(); if (null == docAnnot) { return (T) createDocumentAnnotationNoRemove(0); } else { return docAnnot; } } public <T extends AnnotationFS> T getDocumentAnnotationNoCreate() { if (this == this.svd.baseCAS) { // base CAS has no document return null; } FSIterator<Annotation> it = getDocAnnotIter(); it.moveToFirst(); // revalidate in case index updated if (it.isValid()) { Annotation r = it.get(); return (T) (inPearContext() ? pearConvert(r) : r); } return null; } private FSIterator<Annotation> getDocAnnotIter() { if (docAnnotIter != null) { return docAnnotIter; } synchronized (this) { if (docAnnotIter == null) { docAnnotIter = this.<Annotation>getAnnotationIndex(getTypeSystemImpl().docType).iterator(); } return docAnnotIter; } } /** * * @return the fs addr of the document annotation found via the index, or 0 if not there */ public int ll_getDocumentAnnotation() { AnnotationFS r = getDocumentAnnotationNoCreate(); return (r == null) ? 0 : r._id(); } @Override public String getDocumentLanguage() { if (this == this.svd.baseCAS) { // base CAS has no document return null; } return getDocumentAnnotation().getStringValue(getTypeSystemImpl().langFeat); } @Override public String getDocumentText() { return this.getSofaDataString(); } @Override public String getSofaDataString() { if (this == this.svd.baseCAS) { // base CAS has no document return null; } return mySofaIsValid() ? mySofaRef.getLocalStringData() : null; } @Override public FeatureStructure getSofaDataArray() { if (this == this.svd.baseCAS) { // base CAS has no Sofa return null; } return mySofaIsValid() ? mySofaRef.getLocalFSData() : null; } @Override public String getSofaDataURI() { if (this == this.svd.baseCAS) { // base CAS has no Sofa return null; } return mySofaIsValid() ? mySofaRef.getSofaURI() : null; } @Override public InputStream getSofaDataStream() { if (this == this.svd.baseCAS) { // base CAS has no Sofa nothin return null; } // return mySofaRef.getSofaDataStream(); // this just goes to the next method return mySofaIsValid() ? this.getSofaDataStream(mySofaRef) : null; } @Override public String getSofaMimeType() { if (this == this.svd.baseCAS) { // base CAS has no Sofa return null; } return mySofaIsValid() ? mySofaRef.getSofaMime() : null; } @Override public Sofa getSofa() { return mySofaRef; } /** * @return the addr of the sofaFS associated with this view, or 0 */ @Override public int ll_getSofa() { return mySofaIsValid() ? mySofaRef._id() : 0; } @Override public String getViewName() { return (this == svd.getViewFromSofaNbr(1)) ? CAS.NAME_DEFAULT_SOFA : mySofaIsValid() ? mySofaRef.getSofaID() : null; } private boolean mySofaIsValid() { return this.mySofaRef != null; } void setDocTextFromDeserializtion(String text) { if (mySofaIsValid()) { Sofa sofa = getSofaRef(); // creates sofa if doesn't already exist sofa.setLocalSofaDataNoDocAnnotUpdate(text); } } @Override public void setDocumentLanguage(String languageCode) { if (this == this.svd.baseCAS) { throw new CASRuntimeException(CASRuntimeException.INVALID_BASE_CAS_METHOD, "setDocumentLanguage(String)"); } Annotation docAnnot = getDocumentAnnotation(); FeatureImpl languageFeature = getTypeSystemImpl().langFeat; languageCode = Language.normalize(languageCode); boolean wasRemoved = this.checkForInvalidFeatureSetting(docAnnot, languageFeature.getCode(), this.getAddbackSingle()); docAnnot.setStringValue(getTypeSystemImpl().langFeat, languageCode); addbackSingleIfWasRemoved(wasRemoved, docAnnot); } private void setSofaThingsMime(Consumer<Sofa> c, String msg) { if (this == this.svd.baseCAS) { throw new CASRuntimeException(CASRuntimeException.INVALID_BASE_CAS_METHOD, msg); } Sofa sofa = getSofaRef(); c.accept(sofa); } @Override public void setDocumentText(String text) { setSofaDataString(text, "text"); } @Override public void setSofaDataString(String text, String mime) throws CASRuntimeException { setSofaThingsMime(sofa -> sofa.setLocalSofaData(text, mime), "setSofaDataString(text, mime)"); } @Override public void setSofaDataArray(FeatureStructure array, String mime) { setSofaThingsMime(sofa -> sofa.setLocalSofaData(array, mime), "setSofaDataArray(FeatureStructure, mime)"); } @Override public void setSofaDataURI(String uri, String mime) throws CASRuntimeException { setSofaThingsMime(sofa -> sofa.setRemoteSofaURI(uri, mime), "setSofaDataURI(String, String)"); } @Override public void setCurrentComponentInfo(ComponentInfo info) { // always store component info in base CAS this.svd.componentInfo = info; } ComponentInfo getCurrentComponentInfo() { return this.svd.componentInfo; } /** * @see org.apache.uima.cas.CAS#addFsToIndexes(FeatureStructure fs) */ @Override public void addFsToIndexes(FeatureStructure fs) { // if (fs instanceof AnnotationBaseFS) { // final CAS sofaView = ((AnnotationBaseFS) fs).getView(); // if (sofaView != this) { // CASRuntimeException e = new CASRuntimeException( // CASRuntimeException.ANNOTATION_IN_WRONG_INDEX, new String[] { fs.toString(), // sofaView.getSofa().getSofaID(), this.getSofa().getSofaID() }); // throw e; // } // } this.indexRepository.addFS(fs); } /** * @see org.apache.uima.cas.CAS#removeFsFromIndexes(FeatureStructure fs) */ @Override public void removeFsFromIndexes(FeatureStructure fs) { this.indexRepository.removeFS(fs); } /** * @param fs the AnnotationBase instance * @return the view associated with this FS where it could be indexed */ public CASImpl getSofaCasView(AnnotationBase fs) { return fs._casView; // Sofa sofa = fs.getSofa(); // // if (null != sofa && sofa != this.getSofa()) { // return (CASImpl) this.getView(sofa.getSofaNum()); // } // // /* Note: sofa == null means annotation created from low-level APIs, without setting sofa feature // * Ignore this for backwards compatibility */ // return this; } @Override public CASImpl ll_getSofaCasView(int id) { return getSofaCasView(getFsFromId_checked(id)); } // public Iterator<CAS> getViewIterator() { // List<CAS> viewList = new ArrayList<CAS>(); // // add initial view if it has no sofa // if (!((CASImpl) getInitialView()).mySofaIsValid()) { // viewList.add(getInitialView()); // } // // add views with Sofas // FSIterator<SofaFS> sofaIter = getSofaIterator(); // while (sofaIter.hasNext()) { // viewList.add(getView(sofaIter.next())); // } // return viewList.iterator(); // } /** * Creates the initial view (without a sofa) if not present * @return the number of views, excluding the base view, including the initial view (even if not initially present or no sofa) */ public int getNumberOfViews() { CASImpl initialView = getInitialView(); // creates one if not existing, w/o sofa int nbrSofas = this.svd.baseCAS.indexRepository.getIndex(CAS.SOFA_INDEX_NAME).size(); return initialView.mySofaIsValid() ? nbrSofas : 1 + nbrSofas; } public int getNumberOfSofas() { return this.svd.baseCAS.indexRepository.getIndex(CAS.SOFA_INDEX_NAME).size(); } /* * (non-Javadoc) * * @see org.apache.uima.cas.CAS#getViewIterator() */ @Override public <T extends CAS> Iterator<T> getViewIterator() { return new Iterator<T>() { final CASImpl initialView = getInitialView(); // creates one if not existing, w/o sofa boolean isInitialView_but_noSofa = !initialView.mySofaIsValid(); // true if has no Sofa in initial view // but is reset to false once iterator moves // off of initial view. // if initial view has a sofa, we just use the // sofa iterator instead. final FSIterator<Sofa> sofaIter = getSofaIterator(); @Override public boolean hasNext() { if (isInitialView_but_noSofa) { return true; } return sofaIter.hasNext(); } @Override public T next() { if (isInitialView_but_noSofa) { isInitialView_but_noSofa = false; // no incr of sofa iterator because it was missing initial view return (T) initialView; } return (T) getView(sofaIter.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * excludes initial view if its sofa is not valid * * @return iterator over all views except the base view */ public Iterator<CASImpl> getViewImplIterator() { return new Iterator<CASImpl>() { final CASImpl initialView = getInitialView(); // creates one if not existing, w/o sofa boolean isInitialView_but_noSofa = !initialView.mySofaIsValid(); // true if has no Sofa in initial view // but is reset to false once iterator moves // off of initial view. // if initial view has a sofa, we just use the // sofa iterator instead. final FSIterator<Sofa> sofaIter = getSofaIterator(); @Override public boolean hasNext() { if (isInitialView_but_noSofa) { // set to false once iterator moves off of first value return true; } return sofaIter.hasNext(); } @Override public CASImpl next() { if (isInitialView_but_noSofa) { isInitialView_but_noSofa = false; // no incr of sofa iterator because it was missing initial view return initialView; } return getView(sofaIter.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * iterate over all views in view order (by view number) * @param processViews */ void forAllViews(Consumer<CASImpl> processViews) { final int numViews = this.getNumberOfViews(); for (int viewNbr = 1; viewNbr <= numViews; viewNbr++) { CASImpl view = (viewNbr == 1) ? getInitialView() : (CASImpl) getView(viewNbr); processViews.accept(view); } // // Iterator<CASImpl> it = getViewImplIterator(); // while (it.hasNext()) { // processViews.accept(it.next()); // } } void forAllSofas(Consumer<Sofa> processSofa) { FSIterator<Sofa> it = getSofaIterator(); while (it.hasNext()) { processSofa.accept(it.nextNvc()); } } /** * Excludes base view's ir, * Includes the initial view's ir only if it has a sofa defined * @param processIr the code to execute */ void forAllIndexRepos(Consumer<FSIndexRepositoryImpl> processIr) { final int numViews = this.getViewCount(); for (int viewNum = 1; viewNum <= numViews; viewNum++) { processIr.accept(this.getSofaIndexRepository(viewNum)); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.CAS#getViewIterator(java.lang.String) */ @Override public Iterator<CAS> getViewIterator(String localViewNamePrefix) { // do sofa mapping for current component String absolutePrefix = null; if (getCurrentComponentInfo() != null) { absolutePrefix = getCurrentComponentInfo().mapToSofaID(localViewNamePrefix); } if (absolutePrefix == null) { absolutePrefix = localViewNamePrefix; } // find Sofas with this prefix List<CAS> viewList = new ArrayList<CAS>(); FSIterator<Sofa> sofaIter = getSofaIterator(); while (sofaIter.hasNext()) { SofaFS sofa = sofaIter.next(); String sofaId = sofa.getSofaID(); if (sofaId.startsWith(absolutePrefix)) { if ((sofaId.length() == absolutePrefix.length()) || (sofaId.charAt(absolutePrefix.length()) == '.')) { viewList.add(getView(sofa)); } } } return viewList.iterator(); } /** * protectIndexes * * Within the scope of protectIndexes, * feature updates are checked, and if found to be a key, and the FS is in a corruptible index, * then the FS is removed from the indexes (in all necessary views) (perhaps multiple times * if the FS was added to the indexes multiple times), and this removal is recorded on * an new instance of FSsTobeReindexed appended to fssTobeAddedback. * * Later, when the protectIndexes is closed, the tobe items are added back to the indexes. */ @Override public AutoCloseableNoException protectIndexes() { FSsTobeAddedback r = FSsTobeAddedback.createMultiple(this); svd.fssTobeAddedback.add(r); return r; } void dropProtectIndexesLevel () { svd.fssTobeAddedback.remove(svd.fssTobeAddedback.size() -1); } /** * This design is to support normal operations where the * addbacks could be nested * It also handles cases where nested ones were inadvertently left open * Three cases: * 1) the addbacks are the last element in the stack * - remove it from the stack * 2) the addbacks are (no longer) in the list * - leave stack alone * 3) the addbacks are in the list but not at the end * - remove it and all later ones * * If the "withProtectedindexes" approach is used, it guarantees proper * nesting, but the Runnable can't throw checked exceptions. * * You can do your own try-finally blocks (or use the try with resources * form in Java 8 to do a similar thing with no restrictions on what the * body can contain. * * @param addbacks */ void addbackModifiedFSs (FSsTobeAddedback addbacks) { final List<FSsTobeAddedback> listOfAddbackInfos = svd.fssTobeAddedback; if (listOfAddbackInfos.get(listOfAddbackInfos.size() - 1) == addbacks) { listOfAddbackInfos.remove(listOfAddbackInfos.size()); } else { int pos = listOfAddbackInfos.indexOf(addbacks); if (pos >= 0) { for (int i = listOfAddbackInfos.size() - 1; i > pos; i--) { FSsTobeAddedback toAddBack = listOfAddbackInfos.remove(i); toAddBack.addback(); } } } addbacks.addback(); } /** * * @param r an inner block of code to be run with */ @Override public void protectIndexes(Runnable r) { AutoCloseable addbacks = protectIndexes(); try { r.run(); } finally { addbackModifiedFSs((FSsTobeAddedback) addbacks); } } /** * The current implementation only supports 1 marker call per * CAS. Subsequent calls will throw an error. * * The design is intended to support (at some future point) * multiple markers; for this to work, the intent is to * extend the MarkerImpl to keep track of indexes into * these IntVectors specifying where that marker starts/ends. */ @Override public Marker createMarker() { if (!this.svd.flushEnabled) { throw new CASAdminException(CASAdminException.FLUSH_DISABLED); } this.svd.trackingMark = new MarkerImpl(this.getLastUsedFsId() + 1, this); if (this.svd.modifiedPreexistingFSs == null) { this.svd.modifiedPreexistingFSs = new IdentityHashMap<>(); } if (this.svd.modifiedPreexistingFSs.size() > 0) { errorMultipleMarkers(); } if (this.svd.trackingMarkList == null) { this.svd.trackingMarkList = new ArrayList<MarkerImpl>(); } else {errorMultipleMarkers();} this.svd.trackingMarkList.add(this.svd.trackingMark); return this.svd.trackingMark; } private void errorMultipleMarkers() { throw new CASRuntimeException(CASRuntimeException.MULTIPLE_CREATE_MARKER); } // made public https://issues.apache.org/jira/browse/UIMA-2478 public MarkerImpl getCurrentMark() { return this.svd.trackingMark; } /** * * @return an array of FsChange items, one per modified Fs, * sorted in order of fs._id */ FsChange[] getModifiedFSList() { final Map<TOP, FsChange> mods = this.svd.modifiedPreexistingFSs; FsChange[] r = mods.values().toArray(new FsChange[mods.size()]); Arrays.sort(r, 0, mods.size(), (c1, c2) -> Integer.compare(c1.fs._id, c2.fs._id)); return r; } boolean isInModifiedPreexisting(TOP fs) { return this.svd.modifiedPreexistingFSs.containsKey(fs); } @Override public String toString() { String sofa = (mySofaRef == null) ? (isBaseCas() ? "Base CAS" : "_InitialView or no Sofa") : mySofaRef.getSofaID(); // (mySofaRef == 0) ? "no Sofa" : return this.getClass().getSimpleName() + ":" + getCasId() + "[view: " + sofa + "]"; } int getCasResets() { return svd.casResets.get(); } int getCasId() { return svd.casId; } final public int getNextFsId(TOP fs) { return svd.getNextFsId(fs); } public void adjustLastFsV2size(int arrayLength) { svd.lastFsV2Size += 1 + arrayLength; // 1 is for array length value } /** * Test case use * @param fss the FSs to include in the id 2 fs map */ public void setId2FSs(FeatureStructure ... fss) { for (FeatureStructure fs : fss) { if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally((TOP)fs); } else { svd.id2fs.put((TOP)fs); } } } // Not currently used // public Int2ObjHashMap<TOP> getId2FSs() { // return svd.id2fs.getId2fs(); // } // final private int getNextFsId() { // return ++ svd.fsIdGenerator; // } final public int getLastUsedFsId() { return svd.fsIdGenerator; } /** * Call this to capture the current value of fsIdGenerator and make it * available to other threads. * * Must be called on a thread that has been synchronized with the thread used for creating FSs for this CAS. */ final public void captureLastFsIdForOtherThread() { svd.fsIdLastValue.set(svd.fsIdGenerator); } public <T extends TOP> T getFsFromId(int id) { return (T) this.svd.id2fs.get(id); } // /** // * plus means all reachable, plus maybe others not reachable but not yet gc'd // * @param action - // */ // public void walkReachablePlusFSsSorted(Consumer<TOP> action) { // this.svd.id2fs.walkReachablePlusFSsSorted(action); // } // /** // * called for delta serialization - walks just the new items above the line // * @param action - // * @param fromId - the id of the first item to walk from // */ // public void walkReachablePlusFSsSorted(Consumer<TOP> action, int fromId) { // this.svd.id2fs.walkReachablePlueFSsSorted(action, fromId); // } /** * find all of the FSs via the indexes plus what's reachable. * sort into order by id, * * Apply the action to those * Return the list of sorted FSs * * @param action_filtered action to perform on each item after filtering * @param mark null or the mark * @param includeFilter null or a filter (exclude items not in other type system) * @param typeMapper null or how to map to other type system, used to skip things missing in other type system * @return sorted list of all found items (ignoring mark) */ public List<TOP> walkReachablePlusFSsSorted( Consumer<TOP> action_filtered, MarkerImpl mark, Predicate<TOP> includeFilter, CasTypeSystemMapper typeMapper) { List<TOP> all = new AllFSs(this, mark, includeFilter, typeMapper).getAllFSsAllViews_sofas_reachable().getAllFSsSorted(); List<TOP> filtered = filterAboveMark(all, mark); for (TOP fs : filtered) { action_filtered.accept(fs); } return all; } static List<TOP> filterAboveMark(List<TOP> all, MarkerImpl mark) { if (null == mark) { return all; } int c = Collections.binarySearch(all, TOP._createSearchKey(mark.nextFSId), (fs1, fs2) -> Integer.compare(fs1._id, fs2._id)); if (c < 0) { c = (-c) - 1; } return all.subList(c, all.size()); } // /** // * Get the Java class corresponding to a particular type // * Only valid after type system commit // * // * @param type // * @return // */ // public <T extends FeatureStructure> Class<T> getClass4Type(Type type) { // TypeSystemImpl tsi = getTypeSystemImpl(); // if (!tsi.isCommitted()) { // throw new CASRuntimeException(CASRuntimeException.GET_CLASS_FOR_TYPE_BEFORE_TS_COMMIT); // } // // } public final static boolean isSameCAS(CAS c1, CAS c2) { CASImpl ci1 = (CASImpl) c1.getLowLevelCAS(); CASImpl ci2 = (CASImpl) c2.getLowLevelCAS(); return ci1.getBaseCAS() == ci2.getBaseCAS(); } public boolean isInCAS(FeatureStructure fs) { return ((TOP)fs)._casView.getBaseCAS() == this.getBaseCAS(); } // /** // * // * @param typecode - // * @return Object that can be cast to either a 2 or 3 arg createFs functional interface // * FsGenerator or FsGeneratorArray // */ // private Object getFsGenerator(int typecode) { // return getTypeSystemImpl().getGenerator(typecode); // } public final void checkArrayPreconditions(int len) throws CASRuntimeException { // Check array size. if (len < 0) { throw new CASRuntimeException(CASRuntimeException.ILLEGAL_ARRAY_SIZE); } } public EmptyFSList emptyFSList() { if (null == svd.emptyFSList) { svd.emptyFSList = new EmptyFSList(getTypeSystemImpl().fsEListType, this); } return svd.emptyFSList; } /* * @see org.apache.uima.cas.CAS#emptyFloatList() */ public EmptyFloatList emptyFloatList() { if (null == svd.emptyFloatList) { svd.emptyFloatList = new EmptyFloatList(getTypeSystemImpl().floatEListType, this); } return svd.emptyFloatList; } public EmptyIntegerList emptyIntegerList() { if (null == svd.emptyIntegerList) { svd.emptyIntegerList = new EmptyIntegerList(getTypeSystemImpl().intEListType, this); } return svd.emptyIntegerList; } public EmptyStringList emptyStringList() { if (null == svd.emptyStringList) { svd.emptyStringList = new EmptyStringList(getTypeSystemImpl().stringEListType, this); } return svd.emptyStringList; } public CommonArrayFS emptyArray(Type type) { switch (((TypeImpl)type).getCode()) { case TypeSystemConstants.booleanArrayTypeCode : return emptyBooleanArray(); case TypeSystemConstants.byteArrayTypeCode : return emptyByteArray(); case TypeSystemConstants.shortArrayTypeCode : return emptyShortArray(); case TypeSystemConstants.intArrayTypeCode : return emptyIntegerArray(); case TypeSystemConstants.floatArrayTypeCode : return emptyFloatArray(); case TypeSystemConstants.longArrayTypeCode : return emptyLongArray(); case TypeSystemConstants.doubleArrayTypeCode : return emptyDoubleArray(); case TypeSystemConstants.stringArrayTypeCode : return emptyStringArray(); case TypeSystemConstants.fsArrayTypeCode : return emptyFSArray(); default: throw Misc.internalError(); } } public FloatArray emptyFloatArray() { if (null == svd.emptyFloatArray) { svd.emptyFloatArray = new FloatArray(this.getJCas(), 0); } return svd.emptyFloatArray; } public FSArray emptyFSArray() { if (null == svd.emptyFSArray) { svd.emptyFSArray = new FSArray(this.getJCas(), 0); } return svd.emptyFSArray; } public IntegerArray emptyIntegerArray() { if (null == svd.emptyIntegerArray) { svd.emptyIntegerArray = new IntegerArray(this.getJCas(), 0); } return svd.emptyIntegerArray; } public StringArray emptyStringArray() { if (null == svd.emptyStringArray) { svd.emptyStringArray = new StringArray(this.getJCas(), 0); } return svd.emptyStringArray; } public DoubleArray emptyDoubleArray() { if (null == svd.emptyDoubleArray) { svd.emptyDoubleArray = new DoubleArray(this.getJCas(), 0); } return svd.emptyDoubleArray; } public LongArray emptyLongArray() { if (null == svd.emptyLongArray) { svd.emptyLongArray = new LongArray(this.getJCas(), 0); } return svd.emptyLongArray; } public ShortArray emptyShortArray() { if (null == svd.emptyShortArray) { svd.emptyShortArray = new ShortArray(this.getJCas(), 0); } return svd.emptyShortArray; } public ByteArray emptyByteArray() { if (null == svd.emptyByteArray) { svd.emptyByteArray = new ByteArray(this.getJCas(), 0); } return svd.emptyByteArray; } public BooleanArray emptyBooleanArray() { if (null == svd.emptyBooleanArray) { svd.emptyBooleanArray = new BooleanArray(this.getJCas(), 0); } return svd.emptyBooleanArray; } /** * @param rangeCode special codes for serialization use only * @return the empty list (shared) corresponding to the type */ public EmptyList emptyList(int rangeCode) { return (rangeCode == CasSerializerSupport.TYPE_CLASS_INTLIST) ? emptyIntegerList() : (rangeCode == CasSerializerSupport.TYPE_CLASS_FLOATLIST) ? emptyFloatList() : (rangeCode == CasSerializerSupport.TYPE_CLASS_STRINGLIST) ? emptyStringList() : emptyFSList(); } /** * Get an empty list from the type code of a list * @param typeCode - * @return - */ public EmptyList emptyListFromTypeCode(int typeCode) { switch (typeCode) { case fsListTypeCode: case fsEListTypeCode: case fsNeListTypeCode: return emptyFSList(); case floatListTypeCode: case floatEListTypeCode: case floatNeListTypeCode: return emptyFloatList(); case intListTypeCode: case intEListTypeCode: case intNeListTypeCode: return emptyIntegerList(); case stringListTypeCode: case stringEListTypeCode: case stringNeListTypeCode: return emptyStringList(); default: throw new IllegalArgumentException(); } } // /** // * Copies a feature, from one fs to another // * FSs may belong to different CASes, but must have the same type system // * Features must have compatible ranges // * The target must not be indexed // * The target must be a "new" (above the "mark") FS // * @param fsSrc source FS // * @param fi Feature to copy // * @param fsTgt target FS // */ // public static void copyFeature(TOP fsSrc, FeatureImpl fi, TOP fsTgt) { // if (!copyFeatureExceptFsRef(fsSrc, fi, fsTgt, fi)) { // if (!fi.isAnnotBaseSofaRef) { // fsTgt._setFeatureValueNcNj(fi, fsSrc._getFeatureValueNc(fi)); // } // } // } /** * Copies a feature from one fs to another * FSs may be in different type systems * Doesn't copy a feature ref, but instead returns false. * This is because feature refs can't cross CASes * @param fsSrc source FS * @param fiSrc feature in source to copy * @param fsTgt target FS * @param fiTgt feature in target to set * @return false if feature is an fsRef */ public static boolean copyFeatureExceptFsRef(TOP fsSrc, FeatureImpl fiSrc, TOP fsTgt, FeatureImpl fiTgt) { switch (fiSrc.getRangeImpl().getCode()) { case booleanTypeCode : fsTgt._setBooleanValueNcNj( fiTgt, fsSrc._getBooleanValueNc( fiSrc)); break; case byteTypeCode : fsTgt._setByteValueNcNj( fiTgt, fsSrc._getByteValueNc( fiSrc)); break; case shortTypeCode : fsTgt._setShortValueNcNj( fiTgt, fsSrc._getShortValueNc( fiSrc)); break; case intTypeCode : fsTgt._setIntValueNcNj( fiTgt, fsSrc._getIntValueNc( fiSrc)); break; case longTypeCode : fsTgt._setLongValueNcNj( fiTgt, fsSrc._getLongValueNc( fiSrc)); break; case floatTypeCode : fsTgt._setFloatValueNcNj( fiTgt, fsSrc._getFloatValueNc( fiSrc)); break; case doubleTypeCode : fsTgt._setDoubleValueNcNj( fiTgt, fsSrc._getDoubleValueNc( fiSrc)); break; case stringTypeCode : fsTgt._setStringValueNcNj( fiTgt, fsSrc._getStringValueNc( fiSrc)); break; // case javaObjectTypeCode : fsTgt._setJavaObjectValueNcNj(fiTgt, fsSrc.getJavaObjectValue(fiSrc)); break; // skip setting sofaRef - it's final and can't be set default: if (fiSrc.getRangeImpl().isStringSubtype()) { fsTgt._setStringValueNcNj( fiTgt, fsSrc._getStringValueNc( fiSrc)); break; // does substring range check } return false; } // end of switch return true; } public static CommonArrayFS copyArray(TOP srcArray) { CommonArrayFS srcCA = (CommonArrayFS) srcArray; CommonArrayFS copy = (CommonArrayFS) srcArray._casView.createArray(srcArray._getTypeImpl(), srcCA.size()); copy.copyValuesFrom(srcCA); return copy; } public BinaryCasSerDes getBinaryCasSerDes() { return svd.bcsd; } /** * @return the saved CommonSerDesSequential info */ CommonSerDesSequential getCsds() { return svd.csds; } void setCsds(CommonSerDesSequential csds) { svd.csds = csds; } CommonSerDesSequential newCsds() { return svd.csds = new CommonSerDesSequential(this.getBaseCAS()); } /** * A space-freeing optimization for use cases where (multiple) delta CASes are being deserialized into this CAS and merged. */ public void deltaMergesComplete() { svd.csds = null; } /****************************************** * PEAR support * Don't modify the type system because it is in use on multiple threads * * Handling of id2fs for low level APIs: * FSs in id2fs map are the outer non-pear ones * Any gets do pear conversion if needed. * ******************************************/ /** * Convert base FS to Pear equivalent * 3 cases: * 1) no trampoline needed, no conversion, return the original fs * 2) trampoline already exists - return that one * 3) create new trampoline * @param aFs * @return */ static <T extends FeatureStructure> T pearConvert(T aFs) { if (null == aFs) { return null; } final TOP fs = (TOP) aFs; final CASImpl view = fs._casView; final TypeImpl ti = fs._getTypeImpl(); final FsGenerator3 generator = view.svd.generators[ti.getCode()]; if (null == generator) { return aFs; } return (T) view.pearConvert(fs, generator); } /** * Inner method - after determining there is a generator * First see if already have generated the pear version, and if so, * use that. * Otherwise, create the pear version and save in trampoline table * @param fs * @param g * @return */ private TOP pearConvert(TOP fs, FsGenerator3 g) { return svd.id2tramp.putIfAbsent(fs._id, k -> { svd.reuseId = k; // create new FS using base FS's ID pearBaseFs = fs; TOP r; // createFS below is modified because of pearBaseFs non-null to // "share" the int and data arrays try { r = g.createFS(fs._getTypeImpl(), this); } finally { svd.reuseId = 0; pearBaseFs = null; } assert r != null; if (r instanceof UimaSerializable) { throw new UnsupportedOperationException( "Pears with Alternate implementations of JCas classes implementing UimaSerializable not supported."); // ((UimaSerializable) fs)._save_to_cas_data(); // updates in r too // ((UimaSerializable) r)._init_from_cas_data(); } return r; }); } /** * Given a trampoline FS, return the corresponding base Fs * Supports adding Fs (which must be a non-trampoline version) to indexes * @param fs trampoline fs * @return the corresponding base fs */ <T extends TOP> T getBaseFsFromTrampoline(T fs) { TOP r = svd.id2base.get(fs._id); assert r != null; return (T) r; } /* ***************************************** * DEBUGGING and TRACING ******************************************/ public void traceFSCreate(FeatureStructureImplC fs) { StringBuilder b = svd.traceFScreationSb; if (b.length() > 0) { traceFSflush(); } // normally commented-out for matching with v2 // // mark annotations created by subiterator // if (fs._getTypeCode() == TypeSystemConstants.annotTypeCode) { // StackTraceElement[] stktr = Thread.currentThread().getStackTrace(); // if (stktr.length > 7 && stktr[6].getClassName().equals("org.apache.uima.cas.impl.Subiterator")) { // b.append('*'); // } // } svd.id2addr.add(svd.nextId2Addr); svd.nextId2Addr += fs._getTypeImpl().getFsSpaceReq((TOP)fs); traceFSfs(fs); svd.traceFSisCreate = true; if (fs._getTypeImpl().isArray()) { b.append(" l:").append(((CommonArrayFS)fs).size()); } } void traceFSfs(FeatureStructureImplC fs) { StringBuilder b = svd.traceFScreationSb; svd.traceFSid = fs._id; b.append("c:").append(String.format("%-3d", getCasId())); String viewName = fs._casView.getViewName(); if (null == viewName) { viewName = "base"; } b.append(" v:").append(Misc.elide(viewName, 8)); b.append(" i:").append(String.format("%-5s", geti2addr(fs._id))); b.append(" t:").append(Misc.elide(fs._getTypeImpl().getShortName(), 10)); } void traceIndexMod(boolean isAdd, TOP fs, boolean isAddbackOrSkipBag) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append(isAdd ? (isAddbackOrSkipBag ? "abk_idx " : "add_idx ") : (isAddbackOrSkipBag ? "rmv_auto_idx " : "rmv_norm_idx ")); // b.append(fs.toString()); b.append(fs._getTypeImpl().getShortName()).append(":").append(fs._id); if (fs instanceof Annotation) { Annotation ann = (Annotation) fs; b.append(" begin: ").append(ann.getBegin()); b.append(" end: ").append(ann.getEnd()); b.append(" txt: \"").append(Misc.elide(ann.getCoveredText(), 10)).append("\""); } traceOut.println(b); } void traceCowCopy(FsIndex_singletype<?> index) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append("cow-copy:"); b.append(" i: ").append(index); traceOut.println(b); } void traceCowCopyUse(FsIndex_singletype<?> index) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append("cow-copy-used:"); b.append(" i: ").append(index); traceOut.println(b); } void traceCowReinit(String kind, FsIndex_singletype<?> index) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append("cow-redo: "); b.append(kind); b.append(" i: ").append(index); b.append(" c: "); b.append(Misc.getCaller()); traceOut.println(b); } /** only used for tracing, enables tracing 2 slots for long/double */ private FeatureImpl prevFi; void traceFSfeat(FeatureStructureImplC fs, FeatureImpl fi, Object v) { //debug FeatureImpl originalFi = fi; StringBuilder b = svd.traceFScreationSb; assert (b.length() > 0); if (fs._id != svd.traceFSid) { traceFSfeatUpdate(fs); } if (fi == null) { // happens on 2nd setInt call from cas copier copyfeatures for Long / Double switch(prevFi.getSlotKind()) { case Slot_DoubleRef: v = fs._getDoubleValueNc(prevFi); break; // correct double and long case Slot_LongRef: v = fs._getLongValueNc(prevFi); break; // correct double and long default: Misc.internalError(); } fi = prevFi; prevFi = null; } else { prevFi = fi; } String fn = fi.getShortName(); // correct calls done by cas copier fast loop if (fi.getSlotKind() == SlotKind.Slot_DoubleRef) { if (v instanceof Integer) { return; // wait till the next part is traced } else if (v instanceof Long) { v = CASImpl.long2double((long)v); } } if (fi.getSlotKind() == SlotKind.Slot_LongRef && (v instanceof Integer)) { return; // output done on the next int call } String fv = getTraceRepOfObj(fi, v); // if (geti2addr(fs._id).equals("79") && // fn.equals("sofa")) { // new Throwable().printStackTrace(traceOut); // } // // debug // if (fn.equals("lemma") && // fv.startsWith("Lemma:") && // debug1cnt < 2) { // debug1cnt ++; // traceOut.println("setting lemma feat:"); // new Throwable().printStackTrace(traceOut); // } // debug // if (fs._getTypeImpl().getShortName().equals("Passage") && // "score".equals(fn) && // debug2cnt < 5) { // debug2cnt++; // traceOut.println("setting score feat in Passage"); // new Throwable().printStackTrace(traceOut); // } // debug int i_v = Math.max(0, 10 - fn.length()); int i_n = Math.max(0, 10 - fv.length()); fn = Misc.elide(fn, 10 + i_n, false); fv = Misc.elide(fv, 10 + i_v, false); // debug // if (!svd.traceFSisCreate && fn.equals("uninf.dWord") && fv.equals("XsgTokens")) { // traceOut.println("debug uninf.dWord:XsgTokens: " + Misc.getCallers(3, 10)); // } b.append(' ').append(Misc.elide(fn + ':' + fv, 21)); // value of a feature: // - "null" or // - if FS: type:id (converted to addr) // - v.toString() } private static int debug2cnt = 0; /** * @param v * @return value of the feature: * "null" or if FS: type:id (converted to addr) or v.toString() * Note: white space in strings converted to "_' characters */ private String getTraceRepOfObj(FeatureImpl fi, Object v) { if (v instanceof TOP) { TOP fs = (TOP) v; return Misc.elide(fs.getType().getShortName(), 5, false) + ':' + geti2addr(fs._id); } if (v == null) return "null"; if (v instanceof String) { String s = Misc.elide((String) v, 50, false); return Misc.replaceWhiteSpace(s, "_"); } if (v instanceof Integer) { int iv = (int) v; switch (fi.getSlotKind()) { case Slot_Boolean: return (iv == 1) ? "true" : "false"; case Slot_Byte: case Slot_Short: case Slot_Int: return Integer.toString(iv); case Slot_Float: return Float.toString(int2float(iv)); } } if (v instanceof Long) { long vl = (long) v; return (fi.getSlotKind() == SlotKind.Slot_DoubleRef) ? Double.toString(long2double(vl)) : Long.toString(vl); } return Misc.replaceWhiteSpace(v.toString(), "_"); } private String geti2addr(int id) { if (id >= svd.id2addr.size()) { return Integer.toString(id) + '!'; } return Integer.toString(svd.id2addr.get(id)); } void traceFSfeatUpdate(FeatureStructureImplC fs) { traceFSflush(); traceFSfs(fs); svd.traceFSisCreate = false; } public StringBuilder traceFSflush() { if (!traceFSs) return null; StringBuilder b = svd.traceFScreationSb; if (b.length() > 0) { traceOut.println((svd.traceFSisCreate ? "cr: " : "up: ") + b); b.setLength(0); svd.traceFSisCreate = false; } return b; } private static class MeasureSwitchType { TypeImpl oldType; TypeImpl newType; String oldJCasClassName; String newJCasClassName; int count = 0; boolean newSubsumesOld; boolean oldSubsumesNew; long scantime = 0; MeasureSwitchType(TypeImpl oldType, TypeImpl newType) { this.oldType = oldType; this.oldJCasClassName = oldType.getJavaClass().getName(); this.newType = newType; this.newJCasClassName = newType.getJavaClass().getName(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((newJCasClassName == null) ? 0 : newJCasClassName.hashCode()); result = prime * result + ((newType == null) ? 0 : newType.hashCode()); result = prime * result + ((oldJCasClassName == null) ? 0 : oldJCasClassName.hashCode()); result = prime * result + ((oldType == null) ? 0 : oldType.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof MeasureSwitchType)) { return false; } MeasureSwitchType other = (MeasureSwitchType) obj; if (newJCasClassName == null) { if (other.newJCasClassName != null) { return false; } } else if (!newJCasClassName.equals(other.newJCasClassName)) { return false; } if (newType == null) { if (other.newType != null) { return false; } } else if (!newType.equals(other.newType)) { return false; } if (oldJCasClassName == null) { if (other.oldJCasClassName != null) { return false; } } else if (!oldJCasClassName.equals(other.oldJCasClassName)) { return false; } if (oldType == null) { if (other.oldType != null) { return false; } } else if (!oldType.equals(other.oldType)) { return false; } return true; } } private static final Map<MeasureSwitchType, MeasureSwitchType> measureSwitches = new HashMap<>(); static { if (MEASURE_SETINT) { Runtime.getRuntime().addShutdownHook(new Thread(null, () -> { System.out.println("debug Switch Types dump, # entries: " + measureSwitches.size()); int s1 = 0, s2 = 0, s3 = 0; for (MeasureSwitchType mst : measureSwitches.keySet()) { s1 = Math.max(s1, mst.oldType.getName().length()); s2 = Math.max(s2, mst.newType.getName().length()); s3 = Math.max(s3, mst.oldJCasClassName.length()); } for (MeasureSwitchType mst : measureSwitches.keySet()) { System.out.format("count: %,6d scantime = %,7d ms, subsumes: %s %s, type: %-" + s1 + "s newType: %-" + s2 + "s, cl: %-" + s3 + "s, newCl: %s%n", mst.count, mst.scantime / 1000000, mst.newSubsumesOld ? "n>o" : " ", mst.oldSubsumesNew ? "o>w" : " ", mst.oldType.getName(), mst.newType.getName(), mst.oldJCasClassName, mst.newJCasClassName); } // if (traceFSs) { // System.err.println("debug closing traceFSs output"); // traceOut.close(); // } }, "Dump SwitchTypes")); } // this is definitely needed if (traceFSs) { Runtime.getRuntime().addShutdownHook(new Thread(null, () -> { System.out.println("closing traceOut"); traceOut.close(); }, "close trace output")); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.admin.CASMgr#setCAS(org.apache.uima.cas.CAS) * Internal use Never called Kept because it's in the interface. */ @Override @Deprecated public void setCAS(CAS cas) {} /** * @return true if in Pear context, or external context outside AnalysisEngine having a UIMA Extension class loader * e.g., if calling a call-back routine loaded outside the AE. */ boolean inPearContext() { return svd.previousJCasClassLoader != null; } /** * Pear context suspended while creating a base version, when we need to create a new FS * (we need to create both the base and the trampoline version) */ private void suspendPearContext() { svd.suspendPreviousJCasClassLoader = svd.previousJCasClassLoader; svd.previousJCasClassLoader = null; } private void restorePearContext() { svd.previousJCasClassLoader = svd.suspendPreviousJCasClassLoader; } /** * * @return the initial heap size specified or defaulted */ public int getInitialHeapSize() { return this.svd.initialHeapSize; } // backwards compatibility - reinit calls // just the public apis /** * Deserializer for Java-object serialized instance of CASSerializer * Used by Soap * @param ser - The instance to convert back to a CAS */ public void reinit(CASSerializer ser) { svd.bcsd.reinit(ser); } /** * Deserializer for CASCompleteSerializer instances - includes type system and index definitions * Never delta * @param casCompSer - */ public void reinit(CASCompleteSerializer casCompSer) { svd.bcsd.reinit(casCompSer); } /** * --------------------------------------------------------------------- * see Blob Format in CASSerializer * * This reads in and deserializes CAS data from a stream. Byte swapping may be * needed if the blob is from C++ -- C++ blob serialization writes data in * native byte order. * * Supports delta deserialization. For that, the the csds from the serialization event must be used. * * @param istream - * @return - the format of the input stream detected * @throws CASRuntimeException wraps IOException */ public SerialFormat reinit(InputStream istream) throws CASRuntimeException { return svd.bcsd.reinit(istream); } void maybeHoldOntoFS(FeatureStructureImplC fs) { if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally((TOP)fs); } } public void swapInPearVersion(Object[] a) { if (!inPearContext()) { return; } for (int i = 0; i < a.length; i++) { Object ao = a[i]; if (ao instanceof TOP) { a[i] = pearConvert((TOP) ao); } } } public Collection<?> collectNonPearVersions(Collection<?> c) { if (c.size() == 0 || !inPearContext()) { return c; } ArrayList<Object> items = new ArrayList<>(c.size()); for (Object o : c) { if (o instanceof TOP) { items.add(pearConvert((TOP) o)); } } return items; } public <T> Spliterator<T> makePearAware(Spliterator<T> baseSi) { if (!inPearContext()) { return baseSi; } return new Spliterator<T>() { @Override public boolean tryAdvance(Consumer<? super T> action) { return baseSi.tryAdvance(item -> action.accept( (item instanceof TOP) ? (T) pearConvert((TOP)item) : item)); } @Override public Spliterator<T> trySplit() { return baseSi.trySplit(); } @Override public long estimateSize() { return baseSi.estimateSize(); } @Override public int characteristics() { return baseSi.characteristics(); } }; } // int allocIntData(int sz) { // // if (sz > INT_DATA_FOR_ALLOC_SIZE / 4) { // returnIntDataForAlloc = new int[sz]; // return 0; // } // // if (sz + nextIntDataOffsetForAlloc > INT_DATA_FOR_ALLOC_SIZE) { // // too large to fit, alloc a new one // currentIntDataForAlloc = new int[INT_DATA_FOR_ALLOC_SIZE]; // nextIntDataOffsetForAlloc = 0; // } // int r = nextIntDataOffsetForAlloc; // nextIntDataOffsetForAlloc += sz; // returnIntDataForAlloc = currentIntDataForAlloc; // return r; // } // // int[] getReturnIntDataForAlloc() { // return returnIntDataForAlloc; // } // // int allocRefData(int sz) { // // if (sz > REF_DATA_FOR_ALLOC_SIZE / 4) { // returnRefDataForAlloc = new Object[sz]; // return 0; // } // // if (sz + nextRefDataOffsetForAlloc > REF_DATA_FOR_ALLOC_SIZE) { // // too large to fit, alloc a new one // currentRefDataForAlloc = new Object[REF_DATA_FOR_ALLOC_SIZE]; // nextRefDataOffsetForAlloc = 0; // } // int r = nextRefDataOffsetForAlloc; // nextRefDataOffsetForAlloc += sz; // returnRefDataForAlloc = currentRefDataForAlloc; // return r; // } // // Object[] getReturnRefDataForAlloc() { // return returnRefDataForAlloc; // } }
[UIMA-5621] fix to support empty arrays of fsarry of specific types git-svn-id: d56ff9e7d7ea0b208561738885f328c1a8397aa6@1812402 13f79535-47bb-0310-9956-ffa450edef68
uimaj-core/src/main/java/org/apache/uima/cas/impl/CASImpl.java
[UIMA-5621] fix to support empty arrays of fsarry of specific types
<ide><path>imaj-core/src/main/java/org/apache/uima/cas/impl/CASImpl.java <ide> return emptyDoubleArray(); <ide> case TypeSystemConstants.stringArrayTypeCode : <ide> return emptyStringArray(); <del> case TypeSystemConstants.fsArrayTypeCode : <add> default: // TypeSystemConstants.fsArrayTypeCode or any other type <ide> return emptyFSArray(); <del> default: throw Misc.internalError(); <ide> } <ide> } <ide>
Java
apache-2.0
05c6b73740400461b921625c5d2451957bf9f574
0
metlos/hawkular-inventory,jpkrohling/hawkular-inventory,jkandasa/hawkular-inventory,jkandasa/hawkular-inventory,hawkular/hawkular-inventory,pilhuhn/hawkular-inventory,pavolloffay/hawkular-inventory,metlos/hawkular-inventory,Jiri-Kremser/hawkular-inventory,jpkrohling/hawkular-inventory,Jiri-Kremser/hawkular-inventory,tsegismont/hawkular-inventory,tsegismont/hawkular-inventory,pilhuhn/hawkular-inventory,pavolloffay/hawkular-inventory,hawkular/hawkular-inventory
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hawkular.inventory.api.model; import com.google.gson.annotations.Expose; import javax.xml.bind.annotation.XmlAttribute; /** * Base class for entities in a tenant (i.e. everything but the {@link Tenant tenant}s themselves and relationships). * * @author Lukas Krejci * @since 1.0 */ abstract class OwnedEntity extends Entity { @XmlAttribute(name = "tenant") @Expose private final String tenantId; /** JAXB support */ OwnedEntity() { tenantId = null; } OwnedEntity(String tenantId, String id) { super(id); if (tenantId == null) { throw new IllegalArgumentException("tenantId == null"); } this.tenantId = tenantId; } public String getTenantId() { return tenantId; } @Override public boolean equals(Object o) { if (this == o) return true; if (!super.equals(o)) return false; OwnedEntity entity = (OwnedEntity) o; return tenantId.equals(entity.tenantId); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + tenantId.hashCode(); return result; } @Override protected void appendToString(StringBuilder toStringBuilder) { super.appendToString(toStringBuilder); toStringBuilder.append(", tenantId='").append(tenantId).append("'"); } }
api/src/main/java/org/hawkular/inventory/api/model/OwnedEntity.java
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hawkular.inventory.api.model; import javax.xml.bind.annotation.XmlAttribute; /** * Base class for entities in a tenant (i.e. everything but the {@link Tenant tenant}s themselves and relationships). * * @author Lukas Krejci * @since 1.0 */ abstract class OwnedEntity extends Entity { @XmlAttribute(name = "tenant") private final String tenantId; /** JAXB support */ OwnedEntity() { tenantId = null; } OwnedEntity(String tenantId, String id) { super(id); if (tenantId == null) { throw new IllegalArgumentException("tenantId == null"); } this.tenantId = tenantId; } public String getTenantId() { return tenantId; } @Override public boolean equals(Object o) { if (this == o) return true; if (!super.equals(o)) return false; OwnedEntity entity = (OwnedEntity) o; return tenantId.equals(entity.tenantId); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + tenantId.hashCode(); return result; } @Override protected void appendToString(StringBuilder toStringBuilder) { super.appendToString(toStringBuilder); toStringBuilder.append(", tenantId='").append(tenantId).append("'"); } }
[HWKINVENT-28] tenantId was not exposed in GSON-serialized entities.
api/src/main/java/org/hawkular/inventory/api/model/OwnedEntity.java
[HWKINVENT-28] tenantId was not exposed in GSON-serialized entities.
<ide><path>pi/src/main/java/org/hawkular/inventory/api/model/OwnedEntity.java <ide> */ <ide> package org.hawkular.inventory.api.model; <ide> <add>import com.google.gson.annotations.Expose; <add> <ide> import javax.xml.bind.annotation.XmlAttribute; <ide> <ide> /** <ide> abstract class OwnedEntity extends Entity { <ide> <ide> @XmlAttribute(name = "tenant") <add> @Expose <ide> private final String tenantId; <ide> <ide> /** JAXB support */
Java
apache-2.0
7c74c6705072aa2669e06de1ea6e80139a371aa3
0
Neoskai/greycat,Neoskai/greycat,Neoskai/greycat,electricalwind/greycat,Neoskai/greycat,datathings/greycat,datathings/greycat,electricalwind/greycat,electricalwind/greycat,electricalwind/greycat,datathings/greycat,datathings/greycat,datathings/greycat,electricalwind/greycat,Neoskai/greycat,electricalwind/greycat,datathings/greycat,Neoskai/greycat
package org.mwg.ml.algorithm.regression; import org.mwg.Callback; import org.mwg.Constants; import org.mwg.Graph; import org.mwg.Type; import org.mwg.ml.AbstractMLNode; import org.mwg.ml.RegressionNode; import org.mwg.ml.common.matrix.operation.PolynomialFit; import org.mwg.utility.Enforcer; import org.mwg.plugin.NodeState; public class PolynomialNode extends AbstractMLNode implements RegressionNode { /** * Tolerated error that can be configure per node to drive the learning process */ public static final String PRECISION = "precision"; public static final double PRECISION_DEF = 1; public static final String VALUE = "value"; /** * Name of the algorithm to be used in the meta model */ public final static String NAME = "PolynomialNode"; //Internal state variables private and starts with _ public static final String INTERNAL_WEIGHT_KEY = "weight"; public static final String INTERNAL_STEP_KEY = "step"; private static final String INTERNAL_TIME_BUFFER = "times"; private static final String INTERNAL_VALUES_BUFFER = "values"; private static final String INTERNAL_NB_PAST_KEY = "nb"; private static final String INTERNAL_LAST_TIME_KEY = "lastTime"; //Other default parameters that should not be changed externally: public static final String MAX_DEGREE = "maxdegree"; public static final int MAX_DEGREE_DEF = 20; // maximum polynomial degree private final static String NOT_MANAGED_ATT_ERROR = "Polynomial node can only handle value attribute, please use a super node to store other data"; private static final Enforcer enforcer = new Enforcer().asPositiveDouble(PRECISION); private static final Enforcer degenforcer = new Enforcer().asPositiveInt(MAX_DEGREE); public PolynomialNode(long p_world, long p_time, long p_id, Graph p_graph) { super(p_world, p_time, p_id, p_graph); } //Override default Abstract node default setters and getters @Override public void setProperty(String propertyName, byte propertyType, Object propertyValue) { if (propertyName.equals(VALUE)) { learn(Double.parseDouble(propertyValue.toString()), null); } else if (propertyName.equals(PRECISION)) { enforcer.check(propertyName, propertyType, propertyValue); super.setProperty(propertyName, propertyType, propertyValue); } else if (propertyName.equals(MAX_DEGREE)){ degenforcer.check(propertyName, propertyType, propertyValue); super.setProperty(propertyName, Type.INT, (int) propertyValue); } else { throw new RuntimeException(NOT_MANAGED_ATT_ERROR); } } @Override public Object get(String propertyName) { if (propertyName.equals(VALUE)) { final Double[] res = {null}; //ToDo fix callback - return extrapolate(new Callback<Double>() { @Override public void on(Double result) { res[0] = result; } }); return res[0]; } else { return super.get(propertyName); } } @Override public void learn(double value, Callback<Boolean> callback) { NodeState previousState = unphasedState(); //past state, not cloned long timeOrigin = previousState.time(); long nodeTime = time(); double precision = previousState.getFromKeyWithDefault(PRECISION, PRECISION_DEF); double[] weight = (double[]) previousState.getFromKey(INTERNAL_WEIGHT_KEY); //Initial feed for the very first time, the weight is set directly with the first value that arrives if (weight == null) { weight = new double[1]; weight[0] = value; previousState.setFromKey(INTERNAL_WEIGHT_KEY, Type.DOUBLE_ARRAY, weight); previousState.setFromKey(INTERNAL_NB_PAST_KEY, Type.INT, 1); previousState.setFromKey(INTERNAL_STEP_KEY, Type.LONG, 0l); previousState.setFromKey(INTERNAL_LAST_TIME_KEY, Type.LONG, 0l); previousState.setFromKey(INTERNAL_TIME_BUFFER, Type.DOUBLE_ARRAY, new double[]{0}); previousState.setFromKey(INTERNAL_VALUES_BUFFER, Type.DOUBLE_ARRAY, new double[]{value}); if (callback != null) { callback.on(true); } return; } //Check if we are inserting in the past: long previousTime = timeOrigin + (Long) previousState.getFromKey(INTERNAL_LAST_TIME_KEY); if (nodeTime > previousTime) { // For the second time point, test and check for the step in time Long stp = (Long) previousState.getFromKey(INTERNAL_STEP_KEY); long lastTime = nodeTime - timeOrigin; if (stp == null || stp == 0) { if (lastTime == 0) { weight = new double[1]; weight[0] = value; previousState.setFromKey(INTERNAL_WEIGHT_KEY, Type.DOUBLE_ARRAY, weight); previousState.setFromKey(INTERNAL_TIME_BUFFER, Type.DOUBLE_ARRAY, new double[]{0}); previousState.setFromKey(INTERNAL_VALUES_BUFFER, Type.DOUBLE_ARRAY, new double[]{value}); if (callback != null) { callback.on(true); } return; } else { stp = lastTime; previousState.setFromKey(INTERNAL_STEP_KEY, Type.LONG, stp); } } //Then, first step, check if the current model already fits the new value: int deg = weight.length - 1; Integer num = (Integer) previousState.getFromKey(INTERNAL_NB_PAST_KEY); double t = (nodeTime - timeOrigin); t = t / stp; double maxError = maxErr(precision, deg); int maxd = previousState.getFromKeyWithDefault(MAX_DEGREE, MAX_DEGREE_DEF); double[] times = updateBuffer(previousState, t, maxd, INTERNAL_TIME_BUFFER); double[] values = updateBuffer(previousState, value, maxd, INTERNAL_VALUES_BUFFER); //If yes, update some states parameters and return if (Math.abs(PolynomialFit.extrapolate(t, weight) - value) <= maxError) { previousState.setFromKey(INTERNAL_NB_PAST_KEY, Type.INT, num + 1); previousState.setFromKey(INTERNAL_LAST_TIME_KEY, Type.LONG, lastTime); if (callback != null) { callback.on(true); } return; } //If not increase polynomial degrees int newdeg = Math.min(times.length, maxd); while (deg < newdeg && times.length < maxd * 4) { maxError = maxErr(precision, deg); PolynomialFit pf = new PolynomialFit(deg); pf.fit(times, values); if (tempError(pf.getCoef(), times, values) <= maxError) { weight = pf.getCoef(); previousState.setFromKey(INTERNAL_NB_PAST_KEY, Type.INT, num + 1); previousState.setFromKey(INTERNAL_WEIGHT_KEY, Type.DOUBLE_ARRAY, weight); previousState.setFromKey(INTERNAL_LAST_TIME_KEY, Type.LONG, lastTime); if (callback != null) { callback.on(true); } return; } deg++; } //It does not fit, create a new state and split the polynomial, different splits if we are dealing with the future or with the past long newstep = nodeTime - previousTime; NodeState phasedState = newState(previousTime); //force clone double[] nvalues = new double[2]; double[] ntimes = new double[2]; ntimes[0] = 0; ntimes[1] = 1; nvalues[0] = values[values.length - 2]; nvalues[1] = value; //Test if the newly created polynomial is of degree 0 or 1. maxError = maxErr(precision, 0); if (Math.abs(nvalues[1] - nvalues[0]) <= maxError) { // Here it's a degree 0 weight = new double[1]; weight[0] = nvalues[0]; } else { //Here it's a degree 1 weight = new double[2]; weight[0] = nvalues[0]; weight[1] = nvalues[1] - nvalues[0]; } previousState.setFromKey(INTERNAL_TIME_BUFFER, Type.DOUBLE_ARRAY, null); previousState.setFromKey(INTERNAL_VALUES_BUFFER, Type.DOUBLE_ARRAY, null); //create and set the phase set phasedState.setFromKey(INTERNAL_TIME_BUFFER, Type.DOUBLE_ARRAY, ntimes); phasedState.setFromKey(INTERNAL_VALUES_BUFFER, Type.DOUBLE_ARRAY, nvalues); phasedState.setFromKey(PRECISION, Type.DOUBLE, precision); phasedState.setFromKey(MAX_DEGREE, Type.INT, maxd); phasedState.setFromKey(INTERNAL_WEIGHT_KEY, Type.DOUBLE_ARRAY, weight); phasedState.setFromKey(INTERNAL_NB_PAST_KEY, Type.INT, 2); phasedState.setFromKey(INTERNAL_STEP_KEY, Type.LONG, newstep); phasedState.setFromKey(INTERNAL_LAST_TIME_KEY, Type.LONG, newstep); if (callback != null) { callback.on(true); } return; } else { // 2 phased states need to be created //TODO Insert in past. } if (callback != null) { callback.on(false); } } private static double[] updateBuffer(NodeState state, double t, int maxdeg, String key) { double[] ts = (double[]) state.getFromKey(key); if (ts == null) { ts = new double[1]; ts[0] = t; state.setFromKey(key, Type.DOUBLE_ARRAY, ts); return ts; } else if (ts.length < maxdeg * 4) { double[] nts = new double[ts.length + 1]; System.arraycopy(ts, 0, nts, 0, ts.length); nts[ts.length] = t; state.setFromKey(key, Type.DOUBLE_ARRAY, nts); return nts; } else { double[] nts = new double[ts.length]; System.arraycopy(ts, 1, nts, 0, ts.length - 1); nts[ts.length - 1] = t; state.setFromKey(key, Type.DOUBLE_ARRAY, nts); return nts; } } @Override public void extrapolate(Callback<Double> callback) { long time = time(); NodeState state = unphasedState(); long timeOrigin = state.time(); double[] weight = (double[]) state.getFromKey(INTERNAL_WEIGHT_KEY); if (weight == null) { if (callback != null) { callback.on(0.0); } return; } Long inferSTEP = (Long) state.getFromKey(INTERNAL_STEP_KEY); if (inferSTEP == null || inferSTEP == 0) { if (callback != null) { callback.on(weight[0]); } return; } double t = (time - timeOrigin); Long lastTime = (Long) state.getFromKey(INTERNAL_LAST_TIME_KEY); if (t > lastTime) { t = (double) lastTime; } t = t / inferSTEP; if (callback != null) { callback.on(PolynomialFit.extrapolate(t, weight)); } } private double maxErr(double precision, int degree) { //double tol = precision; /* if (_prioritization == Prioritization.HIGHDEGREES) { tol = precision / Math.pow(2, _maxDegree - degree); } else if (_prioritization == Prioritization.LOWDEGREES) {*/ //double tol = precision / Math.pow(2, degree + 0.5); /* } else if (_prioritization == Prioritization.SAMEPRIORITY) { tol = precision * degree * 2 / (2 * _maxDegree); }*/ return precision / Math.pow(2, degree + 1); } private double tempError(double[] computedWeights, double[] times, double[] values) { double maxErr = 0; double temp; for (int i = 0; i < times.length; i++) { temp = Math.abs(values[i] - PolynomialFit.extrapolate(times[i], computedWeights)); if (temp > maxErr) { maxErr = temp; } } return maxErr; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{\"world\":"); builder.append(world()); builder.append(",\"time\":"); builder.append(time()); builder.append(",\"id\":"); builder.append(id()); final NodeState state = this._resolver.resolveState(this); if (state != null) { double[] weight = (double[]) state.getFromKey(INTERNAL_WEIGHT_KEY); if (weight != null) { builder.append("\"polynomial\":\""); for (int i = 0; i < weight.length; i++) { if (i != 0) { builder.append("+("); } builder.append(weight[i]); if (i == 1) { builder.append("*t"); } else if (i > 1) { builder.append("*t^"); builder.append(i); } if (i != 0) { builder.append(")"); } } builder.append("\""); } builder.append("}"); } return builder.toString(); } }
plugins/ml/src/main/java/org/mwg/ml/algorithm/regression/PolynomialNode.java
package org.mwg.ml.algorithm.regression; import org.mwg.Callback; import org.mwg.Constants; import org.mwg.Graph; import org.mwg.Type; import org.mwg.ml.AbstractMLNode; import org.mwg.ml.RegressionNode; import org.mwg.ml.common.matrix.operation.PolynomialFit; import org.mwg.utility.Enforcer; import org.mwg.plugin.NodeState; public class PolynomialNode extends AbstractMLNode implements RegressionNode { /** * Tolerated error that can be configure per node to drive the learning process */ public static final String PRECISION = "precision"; public static final double PRECISION_DEF = 1; public static final String VALUE = "value"; /** * Name of the algorithm to be used in the meta model */ public final static String NAME = "PolynomialNode"; //Internal state variables private and starts with _ public static final String INTERNAL_WEIGHT_KEY = "weight"; public static final String INTERNAL_STEP_KEY = "step"; private static final String INTERNAL_TIME_BUFFER = "times"; private static final String INTERNAL_VALUES_BUFFER = "values"; private static final String INTERNAL_NB_PAST_KEY = "nb"; private static final String INTERNAL_LAST_TIME_KEY = "lastTime"; //Other default parameters that should not be changed externally: public static final String MAX_DEGREE = "maxdegree"; public static final int MAX_DEGREE_DEF = 20; // maximum polynomial degree private final static String NOT_MANAGED_ATT_ERROR = "Polynomial node can only handle value attribute, please use a super node to store other data"; private static final Enforcer enforcer = new Enforcer().asPositiveDouble(PRECISION); private static final Enforcer degenforcer = new Enforcer().asPositiveInt(MAX_DEGREE); public PolynomialNode(long p_world, long p_time, long p_id, Graph p_graph) { super(p_world, p_time, p_id, p_graph); } //Override default Abstract node default setters and getters @Override public void setProperty(String propertyName, byte propertyType, Object propertyValue) { if (propertyName.equals(VALUE)) { learn(Double.parseDouble(propertyValue.toString()), null); } else if (propertyName.equals(PRECISION)) { enforcer.check(propertyName, propertyType, propertyValue); super.setProperty(propertyName, propertyType, propertyValue); } else if (propertyName.equals(MAX_DEGREE)){ degenforcer.check(propertyName, propertyType, propertyValue); super.setProperty(propertyName, propertyType, propertyValue); } else { throw new RuntimeException(NOT_MANAGED_ATT_ERROR); } } @Override public Object get(String propertyName) { if (propertyName.equals(VALUE)) { final Double[] res = {null}; //ToDo fix callback - return extrapolate(new Callback<Double>() { @Override public void on(Double result) { res[0] = result; } }); return res[0]; } else { return super.get(propertyName); } } @Override public void learn(double value, Callback<Boolean> callback) { NodeState previousState = unphasedState(); //past state, not cloned long timeOrigin = previousState.time(); long nodeTime = time(); double precision = previousState.getFromKeyWithDefault(PRECISION, PRECISION_DEF); double[] weight = (double[]) previousState.getFromKey(INTERNAL_WEIGHT_KEY); //Initial feed for the very first time, the weight is set directly with the first value that arrives if (weight == null) { weight = new double[1]; weight[0] = value; previousState.setFromKey(INTERNAL_WEIGHT_KEY, Type.DOUBLE_ARRAY, weight); previousState.setFromKey(INTERNAL_NB_PAST_KEY, Type.INT, 1); previousState.setFromKey(INTERNAL_STEP_KEY, Type.LONG, 0l); previousState.setFromKey(INTERNAL_LAST_TIME_KEY, Type.LONG, 0l); previousState.setFromKey(INTERNAL_TIME_BUFFER, Type.DOUBLE_ARRAY, new double[]{0}); previousState.setFromKey(INTERNAL_VALUES_BUFFER, Type.DOUBLE_ARRAY, new double[]{value}); if (callback != null) { callback.on(true); } return; } //Check if we are inserting in the past: long previousTime = timeOrigin + (Long) previousState.getFromKey(INTERNAL_LAST_TIME_KEY); if (nodeTime > previousTime) { // For the second time point, test and check for the step in time Long stp = (Long) previousState.getFromKey(INTERNAL_STEP_KEY); long lastTime = nodeTime - timeOrigin; if (stp == null || stp == 0) { if (lastTime == 0) { weight = new double[1]; weight[0] = value; previousState.setFromKey(INTERNAL_WEIGHT_KEY, Type.DOUBLE_ARRAY, weight); previousState.setFromKey(INTERNAL_TIME_BUFFER, Type.DOUBLE_ARRAY, new double[]{0}); previousState.setFromKey(INTERNAL_VALUES_BUFFER, Type.DOUBLE_ARRAY, new double[]{value}); if (callback != null) { callback.on(true); } return; } else { stp = lastTime; previousState.setFromKey(INTERNAL_STEP_KEY, Type.LONG, stp); } } //Then, first step, check if the current model already fits the new value: int deg = weight.length - 1; Integer num = (Integer) previousState.getFromKey(INTERNAL_NB_PAST_KEY); double t = (nodeTime - timeOrigin); t = t / stp; double maxError = maxErr(precision, deg); int maxd = previousState.getFromKeyWithDefault(MAX_DEGREE, MAX_DEGREE_DEF); double[] times = updateBuffer(previousState, t, maxd, INTERNAL_TIME_BUFFER); double[] values = updateBuffer(previousState, value, maxd, INTERNAL_VALUES_BUFFER); //If yes, update some states parameters and return if (Math.abs(PolynomialFit.extrapolate(t, weight) - value) <= maxError) { previousState.setFromKey(INTERNAL_NB_PAST_KEY, Type.INT, num + 1); previousState.setFromKey(INTERNAL_LAST_TIME_KEY, Type.LONG, lastTime); if (callback != null) { callback.on(true); } return; } //If not increase polynomial degrees int newdeg = Math.min(times.length, maxd); while (deg < newdeg && times.length < maxd * 4) { maxError = maxErr(precision, deg); PolynomialFit pf = new PolynomialFit(deg); pf.fit(times, values); if (tempError(pf.getCoef(), times, values) <= maxError) { weight = pf.getCoef(); previousState.setFromKey(INTERNAL_NB_PAST_KEY, Type.INT, num + 1); previousState.setFromKey(INTERNAL_WEIGHT_KEY, Type.DOUBLE_ARRAY, weight); previousState.setFromKey(INTERNAL_LAST_TIME_KEY, Type.LONG, lastTime); if (callback != null) { callback.on(true); } return; } deg++; } //It does not fit, create a new state and split the polynomial, different splits if we are dealing with the future or with the past long newstep = nodeTime - previousTime; NodeState phasedState = newState(previousTime); //force clone double[] nvalues = new double[2]; double[] ntimes = new double[2]; ntimes[0] = 0; ntimes[1] = 1; nvalues[0] = values[values.length - 2]; nvalues[1] = value; //Test if the newly created polynomial is of degree 0 or 1. maxError = maxErr(precision, 0); if (Math.abs(nvalues[1] - nvalues[0]) <= maxError) { // Here it's a degree 0 weight = new double[1]; weight[0] = nvalues[0]; } else { //Here it's a degree 1 weight = new double[2]; weight[0] = nvalues[0]; weight[1] = nvalues[1] - nvalues[0]; } previousState.setFromKey(INTERNAL_TIME_BUFFER, Type.DOUBLE_ARRAY, null); previousState.setFromKey(INTERNAL_VALUES_BUFFER, Type.DOUBLE_ARRAY, null); //create and set the phase set phasedState.setFromKey(INTERNAL_TIME_BUFFER, Type.DOUBLE_ARRAY, ntimes); phasedState.setFromKey(INTERNAL_VALUES_BUFFER, Type.DOUBLE_ARRAY, nvalues); phasedState.setFromKey(PRECISION, Type.DOUBLE, precision); phasedState.setFromKey(MAX_DEGREE, Type.INT, maxd); phasedState.setFromKey(INTERNAL_WEIGHT_KEY, Type.DOUBLE_ARRAY, weight); phasedState.setFromKey(INTERNAL_NB_PAST_KEY, Type.INT, 2); phasedState.setFromKey(INTERNAL_STEP_KEY, Type.LONG, newstep); phasedState.setFromKey(INTERNAL_LAST_TIME_KEY, Type.LONG, newstep); if (callback != null) { callback.on(true); } return; } else { // 2 phased states need to be created //TODO Insert in past. } if (callback != null) { callback.on(false); } } private static double[] updateBuffer(NodeState state, double t, int maxdeg, String key) { double[] ts = (double[]) state.getFromKey(key); if (ts == null) { ts = new double[1]; ts[0] = t; state.setFromKey(key, Type.DOUBLE_ARRAY, ts); return ts; } else if (ts.length < maxdeg * 4) { double[] nts = new double[ts.length + 1]; System.arraycopy(ts, 0, nts, 0, ts.length); nts[ts.length] = t; state.setFromKey(key, Type.DOUBLE_ARRAY, nts); return nts; } else { double[] nts = new double[ts.length]; System.arraycopy(ts, 1, nts, 0, ts.length - 1); nts[ts.length - 1] = t; state.setFromKey(key, Type.DOUBLE_ARRAY, nts); return nts; } } @Override public void extrapolate(Callback<Double> callback) { long time = time(); NodeState state = unphasedState(); long timeOrigin = state.time(); double[] weight = (double[]) state.getFromKey(INTERNAL_WEIGHT_KEY); if (weight == null) { if (callback != null) { callback.on(0.0); } return; } Long inferSTEP = (Long) state.getFromKey(INTERNAL_STEP_KEY); if (inferSTEP == null || inferSTEP == 0) { if (callback != null) { callback.on(weight[0]); } return; } double t = (time - timeOrigin); Long lastTime = (Long) state.getFromKey(INTERNAL_LAST_TIME_KEY); if (t > lastTime) { t = (double) lastTime; } t = t / inferSTEP; if (callback != null) { callback.on(PolynomialFit.extrapolate(t, weight)); } } private double maxErr(double precision, int degree) { //double tol = precision; /* if (_prioritization == Prioritization.HIGHDEGREES) { tol = precision / Math.pow(2, _maxDegree - degree); } else if (_prioritization == Prioritization.LOWDEGREES) {*/ //double tol = precision / Math.pow(2, degree + 0.5); /* } else if (_prioritization == Prioritization.SAMEPRIORITY) { tol = precision * degree * 2 / (2 * _maxDegree); }*/ return precision / Math.pow(2, degree + 1); } private double tempError(double[] computedWeights, double[] times, double[] values) { double maxErr = 0; double temp; for (int i = 0; i < times.length; i++) { temp = Math.abs(values[i] - PolynomialFit.extrapolate(times[i], computedWeights)); if (temp > maxErr) { maxErr = temp; } } return maxErr; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{\"world\":"); builder.append(world()); builder.append(",\"time\":"); builder.append(time()); builder.append(",\"id\":"); builder.append(id()); final NodeState state = this._resolver.resolveState(this); if (state != null) { double[] weight = (double[]) state.getFromKey(INTERNAL_WEIGHT_KEY); if (weight != null) { builder.append("\"polynomial\":\""); for (int i = 0; i < weight.length; i++) { if (i != 0) { builder.append("+("); } builder.append(weight[i]); if (i == 1) { builder.append("*t"); } else if (i > 1) { builder.append("*t^"); builder.append(i); } if (i != 0) { builder.append(")"); } } builder.append("\""); } builder.append("}"); } return builder.toString(); } }
update type of max deg
plugins/ml/src/main/java/org/mwg/ml/algorithm/regression/PolynomialNode.java
update type of max deg
<ide><path>lugins/ml/src/main/java/org/mwg/ml/algorithm/regression/PolynomialNode.java <ide> super.setProperty(propertyName, propertyType, propertyValue); <ide> } else if (propertyName.equals(MAX_DEGREE)){ <ide> degenforcer.check(propertyName, propertyType, propertyValue); <del> super.setProperty(propertyName, propertyType, propertyValue); <add> super.setProperty(propertyName, Type.INT, (int) propertyValue); <ide> } <ide> else { <ide> throw new RuntimeException(NOT_MANAGED_ATT_ERROR);
Java
apache-2.0
869be6e35d1e499c209688860839b1fba81c8b3b
0
hvivani/bigdata,hvivani/bigdata,hvivani/bigdata
// This program aggregates by IP hits on apache access logs. // It can get the top ten of IP's // package com.amazonaws.vivanih.hadoop.cascading; import cascading.flow.Flow; import cascading.flow.FlowDef; import cascading.flow.hadoop.HadoopFlowConnector; import cascading.operation.aggregator.Count; import cascading.operation.filter.Sample; import cascading.operation.filter.Limit; import cascading.operation.regex.RegexParser; import cascading.operation.text.DateParser; import cascading.pipe.*; import cascading.property.AppProps; import cascading.scheme.hadoop.TextDelimited; import cascading.scheme.hadoop.TextLine; import cascading.tap.SinkMode; import cascading.tap.Tap; import cascading.tap.hadoop.Hfs; import cascading.tuple.Fields; import java.util.Properties; public class Main { public static void main(String[] args) { String inputPath = args[0]; //input will use default filesystem. HDFS or S3. String outputPath = args[1]; // String sortedTopTen = args[ 1 ] + "/top10/"; // sources and sinks Tap inTap = new Hfs(new TextLine(), inputPath); //input Tap outTap = new Hfs(new TextDelimited(true, ";"), outputPath, SinkMode.REPLACE); //output //Tap top10Tap = new Hfs( new TextDelimited(true, ";"), sortedTopTen, SinkMode.REPLACE); // Parse the line of input and break them into five fields RegexParser parser = new RegexParser(new Fields("ip", "time", "request", "response", "size"), "^([^ ]*) \\S+ \\S+ \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" (\\d{3}) ([^ ]*).*$", new int[]{1, 2, 3, 4, 5}); // "Each" pipe applies a Function or Filter Operation to each Tuple that passes through it. Pipe top10Pipe = new Each("top10Pipe", new Fields("line"), parser, Fields.RESULTS); // Grouping by 'ip' field: // "GroupBy" manages one input Tuple stream and, groups the stream on selected fields in the tuple stream. top10Pipe = new GroupBy(top10Pipe, new Fields("ip")); // Aggregate each "ip" group using Count function: // "Every" pipe applies an Aggregator (like count, or sum) or Buffer (a sliding window) Operation to every group of Tuples that pass through it. top10Pipe = new Every(top10Pipe, Fields.GROUP, new Count(new Fields("IPcount")), Fields.ALL); // After aggregation counter for each "ip," sort the counts. "true" is descending order Pipe top10CountPipe = new GroupBy(top10Pipe, new Fields("IPcount"), true); // Limit them to the first 10, in the descending order top10CountPipe = new Each(top10CountPipe, new Fields("IPcount"), new Limit(10)); // Join the pipe together in the flow, creating inputs and outputs (taps) FlowDef flowDef = FlowDef.flowDef() .addSource(top10Pipe, inTap) //.addTailSink(top10Pipe, outTap) // comment to use sorted top 10 //.addTailSink(top10CountPipe, top10Tap) //uncomment to use sorted top 10 .addTailSink(top10CountPipe, outTap) //uncomment to use sorted top 10 .setName("Top10IP"); Properties properties = AppProps.appProps() .setName("Top10IP") .buildProperties(); Flow parsedLogFlow = new HadoopFlowConnector(properties).connect(flowDef); //Finally, execute the flow. parsedLogFlow.complete(); } }
cascading/loganalysis/Main.java
// This program aggregates by IP hits on apache access logs. // It can get the top ten of IP's // package com.amazonaws.vivanih.hadoop.cascading; import cascading.flow.Flow; import cascading.flow.FlowDef; import cascading.flow.hadoop.HadoopFlowConnector; import cascading.operation.aggregator.Count; import cascading.operation.filter.Sample; import cascading.operation.filter.Limit; import cascading.operation.regex.RegexParser; import cascading.operation.text.DateParser; import cascading.pipe.*; import cascading.property.AppProps; import cascading.scheme.hadoop.TextDelimited; import cascading.scheme.hadoop.TextLine; import cascading.tap.SinkMode; import cascading.tap.Tap; import cascading.tap.hadoop.Hfs; import cascading.tuple.Fields; import java.util.Properties; public class Main { public static void main(String[] args) { String inputPath = args[0]; //input will use default filesystem. HDFS or S3. String outputPath = args[1]; // String sortedTopTen = args[ 1 ] + "/top10/"; // sources and sinks Tap inTap = new Hfs(new TextLine(), inputPath); //input Tap outTap = new Hfs(new TextDelimited(true, ";"), outputPath, SinkMode.REPLACE); //output //Tap top10Tap = new Hfs( new TextDelimited(true, ";"), sortedTopTen, SinkMode.REPLACE); // Parse the line of input and break them into five fields RegexParser parser = new RegexParser(new Fields("ip", "time", "request", "response", "size"), "^([^ ]*) \\S+ \\S+ \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" (\\d{3}) ([^ ]*).*$", new int[]{1, 2, 3, 4, 5}); // "Each" pipe applies a Function or Filter Operation to each Tuple that passes through it. Pipe top10Pipe = new Each("top10Pipe", new Fields("line"), parser, Fields.RESULTS); // Grouping by 'ip' field: // "GroupBy" manages one input Tuple stream and, groups the stream on selected fields in the tuple stream. top10Pipe = new GroupBy(top10Pipe, new Fields("ip")); // Aggregate each "ip" group using Count function: // "Every" pipe applies an Aggregator (like count, or sum) or Buffer (a sliding window) Operation to every group of Tuples that pass through it. top10Pipe = new Every(top10Pipe, Fields.GROUP, new Count(new Fields("IPcount")), Fields.ALL); // After aggregation counter for each "ip," sort the counts. "true" is descending order Pipe top10CountPipe = new GroupBy(top10Pipe, new Fields("IPcount"), true); // Limit them to the first 10, in the descending order top10CountPipe = new Each(top10CountPipe, new Fields("IPcount"), new Limit(10)); // Join the pipe together in the flow, creating inputs and outputs (taps) FlowDef flowDef = FlowDef.flowDef() .addSource(processPipe, inTap) //.addTailSink(top10Pipe, outTap) // comment to use sorted top 10 //.addTailSink(top10CountPipe, top10Tap) //uncomment to use sorted top 10 .addTailSink(top10CountPipe, outTap) //uncomment to use sorted top 10 .setName("Top10IP"); Properties properties = AppProps.appProps() .setName("Top10IP") .buildProperties(); Flow parsedLogFlow = new HadoopFlowConnector(properties).connect(flowDef); //Finally, execute the flow. parsedLogFlow.complete(); } }
Update Main.java
cascading/loganalysis/Main.java
Update Main.java
<ide><path>ascading/loganalysis/Main.java <ide> <ide> // Join the pipe together in the flow, creating inputs and outputs (taps) <ide> FlowDef flowDef = FlowDef.flowDef() <del> .addSource(processPipe, inTap) <add> .addSource(top10Pipe, inTap) <ide> //.addTailSink(top10Pipe, outTap) // comment to use sorted top 10 <ide> //.addTailSink(top10CountPipe, top10Tap) //uncomment to use sorted top 10 <ide> .addTailSink(top10CountPipe, outTap) //uncomment to use sorted top 10
Java
mit
865255579939382d66cef76a9e485264b8365291
0
njmube/OpERP,DevOpsDistilled/OpERP
package devopsdistilled.operp.client.party.panes; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import net.miginfocom.swing.MigLayout; import devopsdistilled.operp.client.abstracts.EntityOperation; import devopsdistilled.operp.client.abstracts.EntityPane; import devopsdistilled.operp.client.exceptions.EntityValidationException; import devopsdistilled.operp.client.party.panes.controllers.VendorPaneController; import devopsdistilled.operp.client.party.panes.models.observers.VendorPaneModelObserver; import devopsdistilled.operp.server.data.entity.party.Vendor; public class VendorPane extends EntityPane<VendorPaneController> implements VendorPaneModelObserver { private VendorPaneController controller; private final JPanel pane; private final JTextField nameField; private final JTextField panVatField; private final JButton btnCancel; private final JButton btnCreate; private final JLabel lblVendorId; private final JTextField vendorIdField; private JPanel contactInfoPanel; public VendorPane() { pane = new JPanel(); pane.setLayout(new MigLayout("", "[][grow]", "[][][][][]")); lblVendorId = new JLabel("Vendor ID"); pane.add(lblVendorId, "cell 0 0,alignx trailing"); vendorIdField = new JTextField(); pane.add(vendorIdField, "cell 1 0,growx"); vendorIdField.setColumns(10); JLabel lblVendorName = new JLabel("Vendor Name"); pane.add(lblVendorName, "cell 0 1,alignx trailing"); nameField = new JTextField(); nameField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getEntity() .setPartyName(nameField.getText().trim()); } }); pane.add(nameField, "cell 1 1,growx"); nameField.setColumns(10); JLabel lblPanvat = new JLabel("PAN/VAT"); pane.add(lblPanvat, "cell 0 2,alignx trailing"); panVatField = new JTextField(); panVatField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getEntity() .setPanVat(panVatField.getText().trim()); } }); pane.add(panVatField, "cell 1 2,growx"); panVatField.setColumns(10); btnCancel = new JButton("Cancel"); btnCancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getDialog().dispose(); } }); contactInfoPanel = new JPanel(); pane.add(contactInfoPanel, "cell 0 3,grow,span"); pane.add(btnCancel, "flowx,cell 1 4"); btnCreate = new JButton("Create"); btnCreate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { controller.validate(); controller.save(); getDialog().dispose(); } catch (EntityValidationException e1) { JOptionPane.showMessageDialog(getPane(), e1.getMessage()); } } }); pane.add(btnCreate, "cell 1 4"); } @Override public JComponent getPane() { return pane; } public void setContactInfopanel(JPanel contactInfoPanel) { MigLayout layout = (MigLayout) pane.getLayout(); Object constraints = layout .getComponentConstraints(this.contactInfoPanel); pane.remove(this.contactInfoPanel); pane.add(contactInfoPanel, constraints); this.contactInfoPanel = contactInfoPanel; pane.validate(); } @Override public void updateEntity(Vendor vendor, EntityOperation entityOperation) { if (EntityOperation.Create == entityOperation) { // XXX } } }
OpERP/src/main/java/devopsdistilled/operp/client/party/panes/VendorPane.java
package devopsdistilled.operp.client.party.panes; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import javax.inject.Inject; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import net.miginfocom.swing.MigLayout; import devopsdistilled.operp.client.abstracts.EntityOperation; import devopsdistilled.operp.client.abstracts.EntityPane; import devopsdistilled.operp.client.exceptions.EntityValidationException; import devopsdistilled.operp.client.party.panes.controllers.VendorPaneController; import devopsdistilled.operp.client.party.panes.models.observers.VendorPaneModelObserver; import devopsdistilled.operp.server.data.entity.party.Vendor; public class VendorPane extends EntityPane<VendorPaneController> implements VendorPaneModelObserver { @Inject private VendorPaneController controller; private final JPanel pane; private final JTextField nameField; private final JTextField panVatField; private final JButton btnCancel; private final JButton btnCreate; public VendorPane() { pane = new JPanel(); pane.setLayout(new MigLayout("", "[][grow]", "[][][][]")); JLabel lblVendorName = new JLabel("Vendor Name"); pane.add(lblVendorName, "cell 0 0,alignx trailing"); nameField = new JTextField(); nameField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getEntity() .setPartyName(nameField.getText().trim()); } }); pane.add(nameField, "cell 1 0,growx"); nameField.setColumns(10); JLabel lblPanvat = new JLabel("PAN/VAT"); pane.add(lblPanvat, "cell 0 1,alignx trailing"); panVatField = new JTextField(); panVatField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getEntity() .setPanVat(panVatField.getText().trim()); } }); pane.add(panVatField, "cell 1 1,growx"); panVatField.setColumns(10); btnCancel = new JButton("Cancel"); btnCancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getDialog().dispose(); } }); pane.add(btnCancel, "flowx,cell 1 3"); btnCreate = new JButton("Create"); btnCreate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { controller.validate(); controller.save(); getDialog().dispose(); } catch (EntityValidationException e1) { JOptionPane.showMessageDialog(getPane(), e1.getMessage()); } } }); pane.add(btnCreate, "cell 1 3"); } @Override public JComponent getPane() { return pane; } public void setContactInfopanel(JPanel contactInfopanel) { pane.add(contactInfopanel, "cell 0 2,grow,span"); pane.validate(); } @Override public void updateEntity(Vendor entity, EntityOperation entityOperation) { // TODO Auto-generated method stub } }
Manage UI Add Vendor ID Replace contactInfo with constraints dynamically retained
OpERP/src/main/java/devopsdistilled/operp/client/party/panes/VendorPane.java
Manage UI
<ide><path>pERP/src/main/java/devopsdistilled/operp/client/party/panes/VendorPane.java <ide> import java.awt.event.FocusAdapter; <ide> import java.awt.event.FocusEvent; <ide> <del>import javax.inject.Inject; <ide> import javax.swing.JButton; <ide> import javax.swing.JComponent; <ide> import javax.swing.JLabel; <ide> public class VendorPane extends EntityPane<VendorPaneController> implements <ide> VendorPaneModelObserver { <ide> <del> @Inject <ide> private VendorPaneController controller; <ide> <ide> private final JPanel pane; <ide> private final JTextField panVatField; <ide> private final JButton btnCancel; <ide> private final JButton btnCreate; <add> private final JLabel lblVendorId; <add> private final JTextField vendorIdField; <add> private JPanel contactInfoPanel; <ide> <ide> public VendorPane() { <ide> pane = new JPanel(); <del> pane.setLayout(new MigLayout("", "[][grow]", "[][][][]")); <add> pane.setLayout(new MigLayout("", "[][grow]", "[][][][][]")); <add> <add> lblVendorId = new JLabel("Vendor ID"); <add> pane.add(lblVendorId, "cell 0 0,alignx trailing"); <add> <add> vendorIdField = new JTextField(); <add> pane.add(vendorIdField, "cell 1 0,growx"); <add> vendorIdField.setColumns(10); <ide> <ide> JLabel lblVendorName = new JLabel("Vendor Name"); <del> pane.add(lblVendorName, "cell 0 0,alignx trailing"); <add> pane.add(lblVendorName, "cell 0 1,alignx trailing"); <ide> <ide> nameField = new JTextField(); <ide> nameField.addFocusListener(new FocusAdapter() { <ide> .setPartyName(nameField.getText().trim()); <ide> } <ide> }); <del> pane.add(nameField, "cell 1 0,growx"); <add> pane.add(nameField, "cell 1 1,growx"); <ide> nameField.setColumns(10); <ide> <ide> JLabel lblPanvat = new JLabel("PAN/VAT"); <del> pane.add(lblPanvat, "cell 0 1,alignx trailing"); <add> pane.add(lblPanvat, "cell 0 2,alignx trailing"); <ide> <ide> panVatField = new JTextField(); <ide> panVatField.addFocusListener(new FocusAdapter() { <ide> .setPanVat(panVatField.getText().trim()); <ide> } <ide> }); <del> pane.add(panVatField, "cell 1 1,growx"); <add> pane.add(panVatField, "cell 1 2,growx"); <ide> panVatField.setColumns(10); <ide> <ide> btnCancel = new JButton("Cancel"); <ide> getDialog().dispose(); <ide> } <ide> }); <del> pane.add(btnCancel, "flowx,cell 1 3"); <add> <add> contactInfoPanel = new JPanel(); <add> pane.add(contactInfoPanel, "cell 0 3,grow,span"); <add> pane.add(btnCancel, "flowx,cell 1 4"); <ide> <ide> btnCreate = new JButton("Create"); <ide> btnCreate.addActionListener(new ActionListener() { <ide> } <ide> } <ide> }); <del> pane.add(btnCreate, "cell 1 3"); <add> pane.add(btnCreate, "cell 1 4"); <ide> } <ide> <ide> @Override <ide> return pane; <ide> } <ide> <del> public void setContactInfopanel(JPanel contactInfopanel) { <del> pane.add(contactInfopanel, "cell 0 2,grow,span"); <add> public void setContactInfopanel(JPanel contactInfoPanel) { <add> MigLayout layout = (MigLayout) pane.getLayout(); <add> Object constraints = layout <add> .getComponentConstraints(this.contactInfoPanel); <add> <add> pane.remove(this.contactInfoPanel); <add> pane.add(contactInfoPanel, constraints); <add> this.contactInfoPanel = contactInfoPanel; <ide> pane.validate(); <ide> } <ide> <ide> @Override <del> public void updateEntity(Vendor entity, EntityOperation entityOperation) { <del> // TODO Auto-generated method stub <del> <add> public void updateEntity(Vendor vendor, EntityOperation entityOperation) { <add> if (EntityOperation.Create == entityOperation) { <add> // XXX <add> } <ide> } <ide> <ide> }
Java
apache-2.0
1e4a4906776f7300a9639a7599fccc545791583d
0
arbasha/commons-lang,weston100721/commons-lang,MarkDacek/commons-lang,MarkDacek/commons-lang,britter/commons-lang,MarkDacek/commons-lang,weston100721/commons-lang,arbasha/commons-lang,arbasha/commons-lang,britter/commons-lang,weston100721/commons-lang,apache/commons-lang,britter/commons-lang,apache/commons-lang,apache/commons-lang
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.builder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.ArrayUtils; /** * <p> * Assists in implementing {@link Diffable#diff(Object)} methods. * </p> * * <p> * To use this class, write code as follows: * </p> * * <pre> * public class Person implements Diffable&lt;Person&gt; { * String name; * int age; * boolean smoker; * * ... * * public DiffResult diff(Person obj) { * // No need for null check, as NullPointerException correct if obj is null * return new DiffBuilder(this, obj, ToStringStyle.SHORT_PREFIX_STYLE) * .append("name", this.name, obj.name) * .append("age", this.age, obj.age) * .append("smoker", this.smoker, obj.smoker) * .build(); * } * } * </pre> * * <p> * The {@code ToStringStyle} passed to the constructor is embedded in the * returned {@code DiffResult} and influences the style of the * {@code DiffResult.toString()} method. This style choice can be overridden by * calling {@link DiffResult#toString(ToStringStyle)}. * </p> * * @since 3.3 * @see Diffable * @see Diff * @see DiffResult * @see ToStringStyle */ public class DiffBuilder implements Builder<DiffResult> { private final List<Diff<?>> diffs; private final boolean objectsTriviallyEqual; private final Object left; private final Object right; private final ToStringStyle style; /** * <p> * Constructs a builder for the specified objects with the specified style. * </p> * * <p> * If {@code lhs == rhs} or {@code lhs.equals(rhs)} then the builder will * not evaluate any calls to {@code append(...)} and will return an empty * {@link DiffResult} when {@link #build()} is executed. * </p> * * @param lhs * {@code this} object * @param rhs * the object to diff against * @param style * the style will use when outputting the objects, {@code null} * uses the default * @param testTriviallyEqual * If true, this will test if lhs and rhs are the same or equal. * All of the append(fieldName, lhs, rhs) methods will abort * without creating a field {@link Diff} if the trivially equal * test is enabled and returns true. The result of this test * is never changed throughout the life of this {@link DiffBuilder}. * @throws IllegalArgumentException * if {@code lhs} or {@code rhs} is {@code null} * @since 3.4 */ public DiffBuilder(final Object lhs, final Object rhs, final ToStringStyle style, final boolean testTriviallyEqual) { if (lhs == null) { throw new IllegalArgumentException("lhs cannot be null"); } if (rhs == null) { throw new IllegalArgumentException("rhs cannot be null"); } this.diffs = new ArrayList<Diff<?>>(); this.left = lhs; this.right = rhs; this.style = style; // Don't compare any fields if objects equal this.objectsTriviallyEqual = testTriviallyEqual && (lhs == rhs || lhs.equals(rhs)); } /** * <p> * Constructs a builder for the specified objects with the specified style. * </p> * * <p> * If {@code lhs == rhs} or {@code lhs.equals(rhs)} then the builder will * not evaluate any calls to {@code append(...)} and will return an empty * {@link DiffResult} when {@link #build()} is executed. * </p> * * <p> * This delegates to {@link #DiffBuilder(Object, Object, ToStringStyle, boolean)} * with the testTriviallyEqual flag enabled. * </p> * * @param lhs * {@code this} object * @param rhs * the object to diff against * @param style * the style will use when outputting the objects, {@code null} * uses the default * @throws IllegalArgumentException * if {@code lhs} or {@code rhs} is {@code null} */ public DiffBuilder(final Object lhs, final Object rhs, final ToStringStyle style) { this(lhs, rhs, style, true); } /** * <p> * Test if two {@code boolean}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code boolean} * @param rhs * the right hand {@code boolean} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final boolean lhs, final boolean rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (lhs != rhs) { diffs.add(new Diff<Boolean>(fieldName) { private static final long serialVersionUID = 1L; @Override public Boolean getLeft() { return Boolean.valueOf(lhs); } @Override public Boolean getRight() { return Boolean.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code boolean[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code boolean[]} * @param rhs * the right hand {@code boolean[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final boolean[] lhs, final boolean[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Boolean[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Boolean[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Boolean[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code byte}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code byte} * @param rhs * the right hand {@code byte} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final byte lhs, final byte rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (lhs != rhs) { diffs.add(new Diff<Byte>(fieldName) { private static final long serialVersionUID = 1L; @Override public Byte getLeft() { return Byte.valueOf(lhs); } @Override public Byte getRight() { return Byte.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code byte[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code byte[]} * @param rhs * the right hand {@code byte[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final byte[] lhs, final byte[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Byte[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Byte[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Byte[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code char}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code char} * @param rhs * the right hand {@code char} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final char lhs, final char rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (lhs != rhs) { diffs.add(new Diff<Character>(fieldName) { private static final long serialVersionUID = 1L; @Override public Character getLeft() { return Character.valueOf(lhs); } @Override public Character getRight() { return Character.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code char[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code char[]} * @param rhs * the right hand {@code char[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final char[] lhs, final char[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Character[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Character[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Character[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code double}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code double} * @param rhs * the right hand {@code double} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final double lhs, final double rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (Double.doubleToLongBits(lhs) != Double.doubleToLongBits(rhs)) { diffs.add(new Diff<Double>(fieldName) { private static final long serialVersionUID = 1L; @Override public Double getLeft() { return Double.valueOf(lhs); } @Override public Double getRight() { return Double.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code double[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code double[]} * @param rhs * the right hand {@code double[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final double[] lhs, final double[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Double[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Double[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Double[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code float}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code float} * @param rhs * the right hand {@code float} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final float lhs, final float rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (Float.floatToIntBits(lhs) != Float.floatToIntBits(rhs)) { diffs.add(new Diff<Float>(fieldName) { private static final long serialVersionUID = 1L; @Override public Float getLeft() { return Float.valueOf(lhs); } @Override public Float getRight() { return Float.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code float[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code float[]} * @param rhs * the right hand {@code float[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final float[] lhs, final float[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Float[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Float[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Float[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code int}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code int} * @param rhs * the right hand {@code int} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final int lhs, final int rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (lhs != rhs) { diffs.add(new Diff<Integer>(fieldName) { private static final long serialVersionUID = 1L; @Override public Integer getLeft() { return Integer.valueOf(lhs); } @Override public Integer getRight() { return Integer.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code int[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code int[]} * @param rhs * the right hand {@code int[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final int[] lhs, final int[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Integer[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Integer[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Integer[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code long}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code long} * @param rhs * the right hand {@code long} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final long lhs, final long rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (lhs != rhs) { diffs.add(new Diff<Long>(fieldName) { private static final long serialVersionUID = 1L; @Override public Long getLeft() { return Long.valueOf(lhs); } @Override public Long getRight() { return Long.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code long[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code long[]} * @param rhs * the right hand {@code long[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final long[] lhs, final long[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Long[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Long[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Long[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code short}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code short} * @param rhs * the right hand {@code short} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final short lhs, final short rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (lhs != rhs) { diffs.add(new Diff<Short>(fieldName) { private static final long serialVersionUID = 1L; @Override public Short getLeft() { return Short.valueOf(lhs); } @Override public Short getRight() { return Short.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code short[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code short[]} * @param rhs * the right hand {@code short[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final short[] lhs, final short[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Short[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Short[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Short[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code Objects}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code Object} * @param rhs * the right hand {@code Object} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final Object lhs, final Object rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (lhs == rhs) { return this; } Object objectToTest; if (lhs != null) { objectToTest = lhs; } else { // rhs cannot be null, as lhs != rhs objectToTest = rhs; } if (objectToTest.getClass().isArray()) { if (objectToTest instanceof boolean[]) { return append(fieldName, (boolean[]) lhs, (boolean[]) rhs); } if (objectToTest instanceof byte[]) { return append(fieldName, (byte[]) lhs, (byte[]) rhs); } if (objectToTest instanceof char[]) { return append(fieldName, (char[]) lhs, (char[]) rhs); } if (objectToTest instanceof double[]) { return append(fieldName, (double[]) lhs, (double[]) rhs); } if (objectToTest instanceof float[]) { return append(fieldName, (float[]) lhs, (float[]) rhs); } if (objectToTest instanceof int[]) { return append(fieldName, (int[]) lhs, (int[]) rhs); } if (objectToTest instanceof long[]) { return append(fieldName, (long[]) lhs, (long[]) rhs); } if (objectToTest instanceof short[]) { return append(fieldName, (short[]) lhs, (short[]) rhs); } return append(fieldName, (Object[]) lhs, (Object[]) rhs); } // Not array type if (lhs != null && lhs.equals(rhs)) { return this; } diffs.add(new Diff<Object>(fieldName) { private static final long serialVersionUID = 1L; @Override public Object getLeft() { return lhs; } @Override public Object getRight() { return rhs; } }); return this; } /** * <p> * Test if two {@code Object[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code Object[]} * @param rhs * the right hand {@code Object[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final Object[] lhs, final Object[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Object[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Object[] getLeft() { return lhs; } @Override public Object[] getRight() { return rhs; } }); } return this; } /** * <p> * Builds a {@link DiffResult} based on the differences appended to this * builder. * </p> * * @return a {@code DiffResult} containing the differences between the two * objects. */ @Override public DiffResult build() { return new DiffResult(left, right, diffs, style); } }
src/main/java/org/apache/commons/lang3/builder/DiffBuilder.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.builder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.ArrayUtils; /** * <p> * Assists in implementing {@link Diffable#diff(Object)} methods. * </p> * * <p> * To use this class, write code as follows: * </p> * * <pre> * public class Person implements Diffable&lt;Person&gt; { * String name; * int age; * boolean smoker; * * ... * * public DiffResult diff(Person obj) { * // No need for null check, as NullPointerException correct if obj is null * return new DiffBuilder(this, obj, ToStringStyle.SHORT_PREFIX_STYLE) * .append("name", this.name, obj.name) * .append("age", this.age, obj.age) * .append("smoker", this.smoker, obj.smoker) * .build(); * } * } * </pre> * * <p> * The {@code ToStringStyle} passed to the constructor is embedded in the * returned {@code DiffResult} and influences the style of the * {@code DiffResult.toString()} method. This style choice can be overridden by * calling {@link DiffResult#toString(ToStringStyle)}. * </p> * * @since 3.3 * @see Diffable * @see Diff * @see DiffResult * @see ToStringStyle */ public class DiffBuilder implements Builder<DiffResult> { private final List<Diff<?>> diffs; private final boolean objectsTriviallyEqual; private final Object left; private final Object right; private final ToStringStyle style; /** * <p> * Constructs a builder for the specified objects with the specified style. * </p> * * <p> * If {@code lhs == rhs} or {@code lhs.equals(rhs)} then the builder will * not evaluate any calls to {@code append(...)} and will return an empty * {@link DiffResult} when {@link #build()} is executed. * </p> * * @param lhs * {@code this} object * @param rhs * the object to diff against * @param style * the style will use when outputting the objects, {@code null} * uses the default * @param testTriviallyEqual * If true, this will test if lhs and rhs are the same or equal. * All of the append(fieldName, lhs, rhs) methods will abort * without creating a field {@link Diff} if the trivially equal * test is enabled and returns true. The result of this test * is never changed throughout the life of this {@link DiffBuilder}. * @throws IllegalArgumentException * if {@code lhs} or {@code rhs} is {@code null} * @since 3.4 */ public DiffBuilder(final Object lhs, final Object rhs, final ToStringStyle style, final boolean testTriviallyEqual) { if (lhs == null) { throw new IllegalArgumentException("lhs cannot be null"); } if (rhs == null) { throw new IllegalArgumentException("rhs cannot be null"); } this.diffs = new ArrayList<Diff<?>>(); this.left = lhs; this.right = rhs; this.style = style; // Don't compare any fields if objects equal this.objectsTriviallyEqual = testTriviallyEqual && (lhs == rhs || lhs.equals(rhs)); } /** * <p> * Constructs a builder for the specified objects with the specified style. * </p> * * <p> * If {@code lhs == rhs} or {@code lhs.equals(rhs)} then the builder will * not evaluate any calls to {@code append(...)} and will return an empty * {@link DiffResult} when {@link #build()} is executed. * </p> * * <p> * This delegates to {@link #DiffBuilder(Object, Object, ToStringStyle, boolean)} * with the testTriviallyEqual flag enabled. * </p> * * @param lhs * {@code this} object * @param rhs * the object to diff against * @param style * the style will use when outputting the objects, {@code null} * uses the default * @throws IllegalArgumentException * if {@code lhs} or {@code rhs} is {@code null} */ public DiffBuilder(final Object lhs, final Object rhs, final ToStringStyle style) { this(lhs, rhs, style, true); } /** * <p> * Test if two {@code boolean}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code boolean} * @param rhs * the right hand {@code boolean} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final boolean lhs, final boolean rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (lhs != rhs) { diffs.add(new Diff<Boolean>(fieldName) { private static final long serialVersionUID = 1L; @Override public Boolean getLeft() { return Boolean.valueOf(lhs); } @Override public Boolean getRight() { return Boolean.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code boolean[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code boolean[]} * @param rhs * the right hand {@code boolean[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final boolean[] lhs, final boolean[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Boolean[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Boolean[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Boolean[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code byte}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code byte} * @param rhs * the right hand {@code byte} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final byte lhs, final byte rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (lhs != rhs) { diffs.add(new Diff<Byte>(fieldName) { private static final long serialVersionUID = 1L; @Override public Byte getLeft() { return Byte.valueOf(lhs); } @Override public Byte getRight() { return Byte.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code byte[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code byte[]} * @param rhs * the right hand {@code byte[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final byte[] lhs, final byte[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Byte[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Byte[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Byte[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code char}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code char} * @param rhs * the right hand {@code char} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final char lhs, final char rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (lhs != rhs) { diffs.add(new Diff<Character>(fieldName) { private static final long serialVersionUID = 1L; @Override public Character getLeft() { return Character.valueOf(lhs); } @Override public Character getRight() { return Character.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code char[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code char[]} * @param rhs * the right hand {@code char[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final char[] lhs, final char[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Character[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Character[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Character[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code double}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code double} * @param rhs * the right hand {@code double} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final double lhs, final double rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (Double.doubleToLongBits(lhs) != Double.doubleToLongBits(rhs)) { diffs.add(new Diff<Double>(fieldName) { private static final long serialVersionUID = 1L; @Override public Double getLeft() { return Double.valueOf(lhs); } @Override public Double getRight() { return Double.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code double[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code double[]} * @param rhs * the right hand {@code double[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final double[] lhs, final double[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Double[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Double[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Double[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code float}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code float} * @param rhs * the right hand {@code float} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final float lhs, final float rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (Float.floatToIntBits(lhs) != Float.floatToIntBits(rhs)) { diffs.add(new Diff<Float>(fieldName) { private static final long serialVersionUID = 1L; @Override public Float getLeft() { return Float.valueOf(lhs); } @Override public Float getRight() { return Float.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code float[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code float[]} * @param rhs * the right hand {@code float[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final float[] lhs, final float[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Float[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Float[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Float[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code int}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code int} * @param rhs * the right hand {@code int} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final int lhs, final int rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (lhs != rhs) { diffs.add(new Diff<Integer>(fieldName) { private static final long serialVersionUID = 1L; @Override public Integer getLeft() { return Integer.valueOf(lhs); } @Override public Integer getRight() { return Integer.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code int[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code int[]} * @param rhs * the right hand {@code int[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final int[] lhs, final int[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Integer[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Integer[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Integer[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code long}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code long} * @param rhs * the right hand {@code long} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final long lhs, final long rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (lhs != rhs) { diffs.add(new Diff<Long>(fieldName) { private static final long serialVersionUID = 1L; @Override public Long getLeft() { return Long.valueOf(lhs); } @Override public Long getRight() { return Long.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code long[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code long[]} * @param rhs * the right hand {@code long[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final long[] lhs, final long[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Long[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Long[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Long[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code short}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code short} * @param rhs * the right hand {@code short} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final short lhs, final short rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (lhs != rhs) { diffs.add(new Diff<Short>(fieldName) { private static final long serialVersionUID = 1L; @Override public Short getLeft() { return Short.valueOf(lhs); } @Override public Short getRight() { return Short.valueOf(rhs); } }); } return this; } /** * <p> * Test if two {@code short[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code short[]} * @param rhs * the right hand {@code short[]} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final short[] lhs, final short[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Short[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Short[] getLeft() { return ArrayUtils.toObject(lhs); } @Override public Short[] getRight() { return ArrayUtils.toObject(rhs); } }); } return this; } /** * <p> * Test if two {@code Objects}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code Object} * @param rhs * the right hand {@code Object} * @return this * @throws IllegalArgumentException * if field name is {@code null} */ public DiffBuilder append(final String fieldName, final Object lhs, final Object rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (lhs == rhs) { return this; } Object objectToTest; if (lhs != null) { objectToTest = lhs; } else { // rhs cannot be null, as lhs != rhs objectToTest = rhs; } if (objectToTest.getClass().isArray()) { if (objectToTest instanceof boolean[]) { return append(fieldName, (boolean[]) lhs, (boolean[]) rhs); } if (objectToTest instanceof byte[]) { return append(fieldName, (byte[]) lhs, (byte[]) rhs); } if (objectToTest instanceof char[]) { return append(fieldName, (char[]) lhs, (char[]) rhs); } if (objectToTest instanceof double[]) { return append(fieldName, (double[]) lhs, (double[]) rhs); } if (objectToTest instanceof float[]) { return append(fieldName, (float[]) lhs, (float[]) rhs); } if (objectToTest instanceof int[]) { return append(fieldName, (int[]) lhs, (int[]) rhs); } if (objectToTest instanceof long[]) { return append(fieldName, (long[]) lhs, (long[]) rhs); } if (objectToTest instanceof short[]) { return append(fieldName, (short[]) lhs, (short[]) rhs); } return append(fieldName, (Object[]) lhs, (Object[]) rhs); } // Not array type if (lhs != null && lhs.equals(rhs)) { return this; } diffs.add(new Diff<Object>(fieldName) { private static final long serialVersionUID = 1L; @Override public Object getLeft() { return lhs; } @Override public Object getRight() { return rhs; } }); return this; } /** * <p> * Test if two {@code Object[]}s are equal. * </p> * * @param fieldName * the field name * @param lhs * the left hand {@code Object[]} * @param rhs * the right hand {@code Object[]} * @throws IllegalArgumentException * if field name is {@code null} * @return this */ public DiffBuilder append(final String fieldName, final Object[] lhs, final Object[] rhs) { if (fieldName == null) { throw new IllegalArgumentException("Field name cannot be null"); } if (objectsTriviallyEqual) { return this; } if (!Arrays.equals(lhs, rhs)) { diffs.add(new Diff<Object[]>(fieldName) { private static final long serialVersionUID = 1L; @Override public Object[] getLeft() { return lhs; } @Override public Object[] getRight() { return rhs; } }); } return this; } /** * <p> * Builds a {@link DiffResult} based on the differences appended to this * builder. * </p> * * @return a {@code DiffResult} containing the differences between the two * objects. */ @Override public DiffResult build() { return new DiffResult(left, right, diffs, style); } }
LANG-1232: make javadoc tag order consistent with the rest of the DiffBuilder javadoc
src/main/java/org/apache/commons/lang3/builder/DiffBuilder.java
LANG-1232: make javadoc tag order consistent with the rest of the DiffBuilder javadoc
<ide><path>rc/main/java/org/apache/commons/lang3/builder/DiffBuilder.java <ide> * the left hand {@code Object[]} <ide> * @param rhs <ide> * the right hand {@code Object[]} <del> * @throws IllegalArgumentException <del> * if field name is {@code null} <del> * @return this <add> * @return this <add> * @throws IllegalArgumentException <add> * if field name is {@code null} <ide> */ <ide> public DiffBuilder append(final String fieldName, final Object[] lhs, <ide> final Object[] rhs) {
Java
apache-2.0
ddb0f1163b3bc0557ffe6d52e6f36c8c68aff108
0
nixplay/cordova-plugin-photo-browser,nixplay/cordova-plugin-photo-browser
package com.creedon.cordova.plugin.photobrowser; import android.Manifest; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.media.ExifInterface; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.support.annotation.NonNull; import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.text.InputType; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.GravityEnum; import com.afollestad.materialdialogs.MaterialDialog; import com.creedon.androidphotobrowser.PhotoBrowserActivity; import com.creedon.androidphotobrowser.PhotoBrowserBasicActivity; import com.creedon.androidphotobrowser.common.data.models.CustomImage; import com.creedon.androidphotobrowser.common.views.ImageOverlayView; import com.creedon.cordova.plugin.photobrowser.metadata.ActionSheet; import com.creedon.cordova.plugin.photobrowser.metadata.Datum; import com.creedon.cordova.plugin.photobrowser.metadata.PhotoDetail; import com.facebook.common.executors.CallerThreadExecutor; import com.facebook.common.references.CloseableReference; import com.facebook.datasource.BaseDataSubscriber; import com.facebook.datasource.DataSource; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.image.CloseableBitmap; import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; import com.stfalcon.frescoimageviewer.ImageViewer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import static com.creedon.cordova.plugin.photobrowser.PhotoBrowserPlugin.KEY_ACTION; import static com.creedon.cordova.plugin.photobrowser.PhotoBrowserPlugin.KEY_ACTION_SEND; import static com.creedon.cordova.plugin.photobrowser.PhotoBrowserPlugin.KEY_DESCRIPTION; import static com.creedon.cordova.plugin.photobrowser.PhotoBrowserPlugin.KEY_PHOTOS; import static com.creedon.cordova.plugin.photobrowser.PhotoBrowserPlugin.KEY_TYPE; public class PhotoBrowserPluginActivity extends PhotoBrowserActivity implements PhotoBrowserBasicActivity.PhotoBrowserListener, ImageOverlayView.ImageOverlayVieListener { public static final String TAG = PhotoBrowserPluginActivity.class.getSimpleName(); public static final float MAX = 100; public static final int SAVE_PHOTO = 0x11; public static final String KEY_ID = "id"; private static final String KEY_ALBUM = "album"; private static final String KEY_TYPE_NIXALBUM = "nixalbum"; private static final int TAG_SELECT_ALL = 0x501; private CallerThreadExecutor currentExecutor; private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE}; private ArrayList<String> pendingFetchDatas; PhotoDetail photoDetail; PhotoBrowserPluginActivity.PhotosDownloadListener photosDownloadListener = new PhotosDownloadListener() { @Override public void onPregress(final float progress) { runOnUiThread(new Runnable() { @Override public void run() { int v = (int) (progress * MAX); progressDialog.setProgress(v); } }); } @Override public void onComplete() { runOnUiThread(new Runnable() { @Override public void run() { progressDialog.dismiss(); } }); } @Override public void onFailed(Error err) { runOnUiThread(new Runnable() { @Override public void run() { progressDialog.dismiss(); } }); } }; private BottomSheetBehavior<View> mBottomSheetBehavior1; // private OkHttpClient globalOkHttpClient3; interface PhotosDownloadListener { void onPregress(float progress); void onComplete(); void onFailed(Error err); } private static final String KEY_ORIGINALURL = "originalUrl"; private FakeR f; private Context context; final private static String DEFAULT_ACTION_ADD = "add"; final private static String DEFAULT_ACTION_SELECT = "select"; final private static String DEFAULT_ACTION_ADDTOPLAYLIST = "addToPlaylist"; final private static String DEFAULT_ACTION_ADDTOFRAME = "addToFrame"; final private static String DEFAULT_ACTION_RENAME = "rename"; final private static String DEFAULT_ACTION_DELETE = "delete"; MaterialDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { if (!Fresco.hasBeenInitialized()) { Context context = this; // global 3 = new OkHttpClient(); // ImagePipelineConfig config = OkHttpImagePipelineConfigFactory // .newBuilder(context,globalOkHttpClient3) // .setNetworkFetcher(new OkHttp3NetworkFetcher(globalOkHttpClient3)) // .build(); // Fresco.initialize(context, config); Fresco.initialize(this); } super.onCreate(savedInstanceState); } @Override public boolean onCreatePanelMenu(int featureId, Menu menu) { if (!selectionMode) { //TODO build aaction menu from custom data int index = 0; for (ActionSheet actionSheet : photoDetail.getActionSheet()) { String label = actionSheet.getLabel(); String action = actionSheet.getAction(); if (action.equals(DEFAULT_ACTION_SELECT)) { MenuItem menuItem = menu.add(0, index, 1, label); //TODO any better way to create menu/menu icon? menuItem.setShowAsAction((index == 0 && label.toLowerCase().contains("add") || action.equals(DEFAULT_ACTION_SELECT)) ? MenuItem.SHOW_AS_ACTION_ALWAYS : MenuItem.SHOW_AS_ACTION_NEVER); if (index == 0 && label.toLowerCase().contains("add")) { menuItem.setIcon(f.getId("drawable", "ic_action_add")); } } index++; } setupToolBar(); } else { if(photoDetail.getType().equals(KEY_TYPE_NIXALBUM)){ MenuItem menuItem = menu.add(0, TAG_SELECT_ALL, 1, getString(f.getId("string", "SELECT_ALL"))); //TODO any better way to create menu/menu icon? menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); }else { MenuInflater inflater = getMenuInflater(); inflater.inflate(com.creedon.androidphotobrowser.R.menu.menu, menu); setupToolBar(); } } return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == SAVE_PHOTO) { for (int r : grantResults) { if (r == PackageManager.PERMISSION_GRANTED) { if (pendingFetchDatas != null) { downloadWithURLS(pendingFetchDatas, pendingFetchDatas.size(), this.photosDownloadListener); } } } } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection int id = item.getItemId(); if(id == TAG_SELECT_ALL){ if(item.getTitle().equals(getString(f.getId("string","SELECT_ALL")))) { item.setTitle(getString(f.getId("string", "DESELECT_ALL"))); for (int i = 0; i < selections.size(); i++) { selections.set(i, "1"); } rcAdapter.notifyDataSetChanged(); }else{ item.setTitle(getString(f.getId("string","SELECT_ALL"))); for (int i = 0; i < selections.size(); i++) { selections.set(i, "0"); } rcAdapter.notifyDataSetChanged(); } }else if (id == android.R.id.home) { if (!selectionMode || photoDetail.getType().equals(KEY_TYPE_NIXALBUM)) { finish(); } } else if (id == com.creedon.androidphotobrowser.R.id.delete) { try { deletePhotos(); } catch (JSONException e) { e.printStackTrace(); } //TODO delete item } // else if (id == com.creedon.androidphotobrowser.R.id.send) { //// addAlbumToPlaylist(); // try { // sendPhotos(); // } catch (JSONException e) { // e.printStackTrace(); // } // } else if (id == com.creedon.androidphotobrowser.R.id.download) { // try { // downloadPhotos(); // } catch (JSONException e) { // e.printStackTrace(); // } // } else if (item.getTitle() != null) { for (ActionSheet actionSheet : photoDetail.getActionSheet()) { String label = actionSheet.getLabel(); String action = actionSheet.getAction(); if (label.equals(item.getTitle())) { if (action.equals(DEFAULT_ACTION_ADD)) { try { addPhotos(); } catch (JSONException e) { e.printStackTrace(); } } else if (action.equals(DEFAULT_ACTION_RENAME)) { editAlbumName(); } else if (action.equals(DEFAULT_ACTION_ADDTOPLAYLIST)) { try { addAlbumToPlaylist(); } catch (JSONException e) { e.printStackTrace(); } } else if (action.equals(DEFAULT_ACTION_DELETE)) { deleteAlbum(); } else if (action.equals(DEFAULT_ACTION_SELECT)) { setupSelectionMode(!selectionMode); } else if (action.equals(DEFAULT_ACTION_ADDTOFRAME)) { try { addAlbumToFrame(); } catch (JSONException e) { e.printStackTrace(); } } break; } } } else { return super.onOptionsItemSelected(item); } return false; } private void addAlbumToFrame() throws JSONException { JSONObject res = new JSONObject(); res.put(KEY_ACTION, DEFAULT_ACTION_ADDTOFRAME); res.put(KEY_ID, photoDetail.getId()); res.put(KEY_TYPE, photoDetail.getType()); res.put(KEY_DESCRIPTION, "send photos to destination"); finishWithResult(res); } private void sendPhotos() throws JSONException { ArrayList<String> fetchedDatas = new ArrayList<String>(); for (int i = 0; i < selections.size(); i++) { //add to temp lsit if not selected if (selections.get(i).equals("1")) { JSONObject object = photoDetail.getData().get(i).toJSON(); String id = object.getString(KEY_ID); fetchedDatas.add(id); } } if (fetchedDatas.size() > 0) { JSONObject res = new JSONObject(); try { res.put(KEY_PHOTOS, new JSONArray(fetchedDatas)); res.put(KEY_ACTION, KEY_ACTION_SEND); res.put(KEY_ID, photoDetail.getId()); res.put(KEY_TYPE, photoDetail.getType()); res.put(KEY_DESCRIPTION, "send photos to destination"); finishWithResult(res); } catch (JSONException e) { e.printStackTrace(); } } } @Override protected void init() { f = new FakeR(getApplicationContext()); progressDialog = new MaterialDialog .Builder(this) .title(getString(f.getId("string", "DOWNLOADING"))) .neutralText(getString(f.getId("string", "CANCEL"))) .onAny(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { if (currentExecutor != null) { currentExecutor.shutdown(); } } }) .dismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (currentExecutor != null) { currentExecutor.shutdown(); } } }) .progress(false, 100, true) .build(); context = getApplicationContext(); listener = this; if (getIntent().getExtras() != null) { Bundle bundle = getIntent().getExtras(); String optionsJsonString = bundle.getString("options"); try { photoDetail = PhotoDetail.getInstance(new JSONObject(optionsJsonString)); } catch (JSONException e) { e.printStackTrace(); } // try { // JSONObject jsonObject = new JSONObject(optionsJsonString); // JSONArray images = jsonObject.getJSONArray("images"); // JSONArray thumbnails = jsonObject.getJSONArray("thumbnails"); // JSONArray data = jsonObject.getJSONArray("data"); // JSONArray captions = jsonObject.getJSONArray("captions"); // String id = jsonObject.getString("id"); // name = jsonObject.getString("name"); // int count = jsonObject.getInt("count"); // String type = jsonObject.getString("type"); // try { // actionSheet = jsonObject.getJSONArray("actionSheet"); // } catch (Exception e) { // e.printStackTrace(); // } // _previewUrls = new ArrayList<String>(); // _thumbnailUrls = new ArrayList<String>(); // _captions = new ArrayList<String>(); // _data = new ArrayList<JSONObject>(); // for (int i = 0; i < images.length(); i++) { // _previewUrls.add(images.getString(i)); // } // for (int i = 0; i < thumbnails.length(); i++) { // _thumbnailUrls.add(thumbnails.getString(i)); // } // for (int i = 0; i < captions.length(); i++) { // _captions.add(captions.getString(i)); // } // for (int i = 0; i < data.length(); i++) { // _data.add(data.getJSONObject(i)); // } // // // } catch (JSONException e) { // e.printStackTrace(); // } } super.init(); if(photoDetail.getType().equals(KEY_TYPE_NIXALBUM)) { setupSelectionMode(true); } View bottomSheet = findViewById(f.getId("id", "bottom_sheet1")); mBottomSheetBehavior1 = BottomSheetBehavior.from(bottomSheet); mBottomSheetBehavior1.setHideable(true); mBottomSheetBehavior1.setState(BottomSheetBehavior.STATE_HIDDEN); TextView titleTextView = (TextView) findViewById(f.getId("id", "titleTextView")); titleTextView.setText(getString(f.getId("string", "ADD_PHOTOS"))); FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(f.getId("id", "floatingButton")); if (floatingActionButton != null) { floatingActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(photoDetail.getType().equals(KEY_TYPE_NIXALBUM)) { try { sendPhotos(); } catch (JSONException e) { e.printStackTrace(); } }else{ if (mBottomSheetBehavior1.getState() != BottomSheetBehavior.STATE_EXPANDED) { mBottomSheetBehavior1.setState(BottomSheetBehavior.STATE_EXPANDED); } else { mBottomSheetBehavior1.setState(BottomSheetBehavior.STATE_HIDDEN); } } } }); } LinearLayout sheetLinearLayout = (LinearLayout) findViewById(f.getId("id", "sheetLinearLayout")); int index = 0; for (ActionSheet actionSheet : photoDetail.getActionSheet()) { try { String label = actionSheet.getLabel(); final String action = actionSheet.getAction(); Button imageButton = new Button(this, null, android.R.style.Widget_Button_Small);//@android:style/Widget.Button.Small Drawable drawable = null; if (index % 3 == 0) { drawable = getResources().getDrawable(com.creedon.androidphotobrowser.R.drawable.camera); } else if (index % 3 == 1) { drawable = getResources().getDrawable(com.creedon.androidphotobrowser.R.drawable.photolibrary); } else if (index % 3 == 2) { drawable = getResources().getDrawable(com.creedon.androidphotobrowser.R.drawable.nixplayalbum); } if (drawable != null) { int h = drawable.getIntrinsicHeight(); int w = drawable.getIntrinsicWidth(); drawable.setBounds(0, 0, w, h); imageButton.setBackgroundColor(0x00000000); imageButton.setCompoundDrawables(null, drawable, null, null); imageButton.setText(label); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { imageButton.setTextAppearance(f.getId("style", "AppTheme")); } else { imageButton.setTextAppearance(this, f.getId("style", "AppTheme")); } } LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1); layoutParams.setMargins(10,10,10,10); imageButton.setLayoutParams(layoutParams); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { JSONObject res = new JSONObject(); try { res.put(KEY_ACTION, action); res.put(KEY_ID, photoDetail.getId()); res.put(KEY_TYPE, photoDetail.getType()); res.put(KEY_DESCRIPTION, "add photo to album"); finishWithResult(res); } catch (JSONException e) { e.printStackTrace(); } mBottomSheetBehavior1.setState(BottomSheetBehavior.STATE_HIDDEN); } }); sheetLinearLayout.addView(imageButton); } catch (Exception e) { e.printStackTrace(); } index++; if (index == 3) break; } } @Override public List<String> photoBrowserPhotos(PhotoBrowserBasicActivity activity) { return photoDetail.getImages(); } @Override public List<String> photoBrowserThumbnails(PhotoBrowserBasicActivity activity) { return photoDetail.getThumbnails(); } @Override public String photoBrowserPhotoAtIndex(PhotoBrowserBasicActivity activity, int index) { return null; } @Override public List<String> photoBrowserPhotoCaptions(PhotoBrowserBasicActivity photoBrowserBasicActivity) { return photoDetail.getCaptions(); } @Override public String getActionBarTitle() { return photoDetail.getName(); } @Override public String getSubtitle() { if (photoDetail.getImages() == null) { return "0" + " " + context.getResources().getString(f.getId("string", "PHOTOS")); } else { return String.valueOf(this.photoDetail.getImages().size()) + " " + context.getResources().getString(f.getId("string", "PHOTOS")); } } @Override public List<CustomImage> getCustomImages(PhotoBrowserActivity photoBrowserActivity) { try { List<CustomImage> images = new ArrayList<CustomImage>(); ArrayList<String> previewUrls = (ArrayList<String>) listener.photoBrowserPhotos(this); ArrayList<String> captions = (ArrayList<String>) listener.photoBrowserPhotoCaptions(this); try { for (int i = 0; i < previewUrls.size(); i++) { images.add(new CustomImage(previewUrls.get(i), captions.get(i))); } } catch (Exception e) { e.printStackTrace(); } return images; } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected ImageViewer.OnImageChangeListener getImageChangeListener() { return new ImageViewer.OnImageChangeListener() { @Override public void onImageChange(int position) { setCurrentPosition(position); overlayView.setDescription(photoDetail.getCaptions().get(position)); try { overlayView.setData(photoDetail.getData().get(position).toJSON()); } catch (JSONException e) { e.printStackTrace(); } } }; } private void addPhotos() throws JSONException { //dismiss and send code JSONObject res = new JSONObject(); res.put(KEY_ACTION, DEFAULT_ACTION_ADD); res.put(KEY_ID, photoDetail.getId()); res.put(KEY_TYPE, photoDetail.getType()); res.put(KEY_DESCRIPTION, "add photo to album"); finishWithResult(res); } private void addAlbumToPlaylist() throws JSONException { JSONObject res = new JSONObject(); res.put(KEY_ACTION, DEFAULT_ACTION_ADDTOPLAYLIST); res.put(KEY_ID, photoDetail.getId()); res.put(KEY_TYPE, photoDetail.getType()); res.put(KEY_DESCRIPTION, "send photos to destination"); finishWithResult(res); } private void editAlbumName() { new MaterialDialog.Builder(this) .title(getString(f.getId("string", photoDetail.getType().toLowerCase().equals(KEY_ALBUM) ? "EDIT_ALBUM_NAME" : "EDIT_PLAYLIST_NAME"))) .inputType(InputType.TYPE_CLASS_TEXT) .input(getString(f.getId("string", "EDIT_ALBUM_NAME")), photoDetail.getName(), new MaterialDialog.InputCallback() { @Override public void onInput(@NonNull MaterialDialog dialog, @NonNull CharSequence input) { dialog.dismiss(); photoDetail.setName(input.toString()); android.support.v7.app.ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(input.toString()); } photoDetail.onSetName(input.toString()); } }).show(); } private void deleteAlbum() { String content = getString(f.getId("string", "ARE_YOU_SURE_YOU_WANT_TO_DELETE_THIS_ALBUM_THIS_WILL_ALSO_REMOVE_THE_PHOTOS_FROM_THE_PLAYLIST_IF_THEY_ARE_NOT_IN_ANY_OTHER_ALBUMS")); content.replace(KEY_ALBUM, photoDetail.getType()); new MaterialDialog.Builder(this) .title(getString(f.getId("string", "DELETE")) + photoDetail.getType()) .content(content) .positiveText(getString(f.getId("string", "CONFIRM"))) .negativeText(getString(f.getId("string", "CANCEL"))) .btnStackedGravity(GravityEnum.CENTER) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { dialog.dismiss(); try { JSONObject res = new JSONObject(); res.put(KEY_ACTION, DEFAULT_ACTION_DELETE); res.put(KEY_ID, photoDetail.getId()); res.put(KEY_TYPE, photoDetail.getType()); res.put(KEY_DESCRIPTION, "delete " + photoDetail.getType()); finishWithResult(res); } catch (JSONException e) { e.printStackTrace(); } } }) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { dialog.dismiss(); } }) .show(); } private void downloadPhotos() throws JSONException { //TODO download photos ArrayList<String> fetchedDatas = new ArrayList<String>(); for (int i = 0; i < selections.size(); i++) { //add to temp lsit if not selected if (selections.get(i).equals("1")) { JSONObject object = photoDetail.getData().get(i).toJSON(); String id = object.getString(KEY_ORIGINALURL); fetchedDatas.add(id); } } if (fetchedDatas.size() > 0) { progressDialog.setProgress(0); progressDialog.show(); downloadWithURLS(fetchedDatas, fetchedDatas.size(), this.photosDownloadListener); } } private void deletePhotos() throws JSONException { final ArrayList<String> fetchedDatas = new ArrayList<String>(); final ArrayList<Datum> tempDatas = new ArrayList<Datum >(); final ArrayList<String> tempPreviews = new ArrayList<String>(); final ArrayList<String> tempCations = new ArrayList<String>(); final ArrayList<String> tempThumbnails = new ArrayList<String>(); final ArrayList<String> tempSelection = new ArrayList<String>(); for (int i = 0; i < selections.size(); i++) { //add to temp lsit if not selected if (selections.get(i).equals("0")) { tempDatas.add(photoDetail.getData().get(i)); tempPreviews.add(photoDetail.getImages().get(i)); tempCations.add(photoDetail.getCaptions().get(i)); tempThumbnails.add(photoDetail.getThumbnails().get(i)); tempSelection.add(selections.get(i)); } else { Datum object = photoDetail.getData().get(i); String id = object.getId(); fetchedDatas.add(id); } } if (fetchedDatas.size() > 0) { new MaterialDialog.Builder(this) .title(getString(f.getId("string", "DELETE_PHOTOS"))) .content(getString(f.getId("string", "ARE_YOU_SURE_YOU_WANT_TO_DELETE_THE_SELECTED_PHOTOS"))) .positiveText(getString(f.getId("string", "CONFIRM"))) .negativeText(getString(f.getId("string", "CANCEL"))) .btnStackedGravity(GravityEnum.CENTER) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { dialog.dismiss(); photoDetail.onPhotoDeleted(fetchedDatas); photoDetail.setImages(tempPreviews); photoDetail.setData(tempDatas); photoDetail.setCaptions(tempCations); photoDetail.setThumbnails(tempThumbnails); selections = tempSelection; if (photoDetail.getImages().size() == 0) { finish(); } else { ArrayList<String> list = new ArrayList<String>(photoDetail.getThumbnails()); getRcAdapter().swap(list); } } }) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { dialog.dismiss(); } }) .show(); } // todo notify changed } private void deletePhoto(int position, JSONObject data) { try { Datum deletedData = photoDetail.getData().remove(position); photoDetail.getImages().remove(position); photoDetail.getCaptions().remove(position); photoDetail.getThumbnails().remove(position); selections.remove(position); ArrayList<String> deletedDatas = new ArrayList<String>(); deletedDatas.add(deletedData.getId()); photoDetail.onPhotoDeleted(deletedDatas); if (photoDetail.getImages().size() == 0) { finish(); } else { imageViewer.onDismiss(); super.refreshCustomImage(); showPicker(photoDetail.getImages().size() == 1 ? 0 : getCurrentPosition() > 0 ? getCurrentPosition() - 1 : getCurrentPosition()); ArrayList<String> list = new ArrayList<String>(photoDetail.getThumbnails()); getRcAdapter().swap(list); } } catch (Exception e) { e.printStackTrace(); } // todo notify changed } private void downloadWithURLS(final ArrayList<String> fetchedDatas, final int counts, final PhotosDownloadListener _photosDownloadListener) { Log.d(TAG, "going to download " + fetchedDatas.get(0)); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(permissions, SAVE_PHOTO); } pendingFetchDatas = fetchedDatas; return; } downloadPhotoWithURL(fetchedDatas.get(0), new PhotosDownloadListener() { @Override public void onPregress(float progress) { float particialProgress = ((1.0f / counts) * progress); Log.d(TAG, "particialProgress " + particialProgress); float curentsize = fetchedDatas.size(); float partition = (counts - curentsize); Log.d(TAG, "partition " + partition); float PROGRESS = (partition / counts) + particialProgress; Log.d(TAG, "Progress " + PROGRESS); _photosDownloadListener.onPregress(PROGRESS); } @Override public void onComplete() { fetchedDatas.remove(0); if (fetchedDatas.size() > 0) { downloadWithURLS(fetchedDatas, counts, _photosDownloadListener); } else { _photosDownloadListener.onComplete(); } } @Override public void onFailed(Error err) { _photosDownloadListener.onFailed(err); } }); } @Override public void onDownloadButtonPressed(JSONObject data) { //Save image to camera roll try { if (data.getString(KEY_ORIGINALURL) != null) { progressDialog.setProgress(0); progressDialog.show(); ArrayList<String> fetchedDatas = new ArrayList<String>(); fetchedDatas.add(data.getString(KEY_ORIGINALURL)); downloadWithURLS(fetchedDatas, fetchedDatas.size(), this.photosDownloadListener); } } catch (JSONException e) { e.printStackTrace(); } } private void downloadPhotoWithURL(String string, @NonNull final PhotosDownloadListener photosDownloadListener) { final Uri uri = Uri.parse(string); ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri) .build(); DataSource<CloseableReference<CloseableImage>> dataSource = Fresco.getImagePipeline() .fetchDecodedImage(request, this); CallerThreadExecutor executor = CallerThreadExecutor.getInstance(); currentExecutor = executor; dataSource.subscribe( new BaseDataSubscriber<CloseableReference<CloseableImage>>() { @Override protected void onNewResultImpl(DataSource<CloseableReference<CloseableImage>> dataSource) { currentExecutor = null; if (!dataSource.isFinished()) { return; } CloseableReference<CloseableImage> closeableImageRef = dataSource.getResult(); Bitmap bitmap = null; if (closeableImageRef != null && closeableImageRef.get() instanceof CloseableBitmap) { bitmap = ((CloseableBitmap) closeableImageRef.get()).getUnderlyingBitmap(); } try { String filePath = getPicturesPath(uri.toString()); File file = new File(filePath); OutputStream outStream = null; try { outStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream); } catch (FileNotFoundException e) { e.printStackTrace(); Error error = new Error(e.getMessage()); photosDownloadListener.onFailed(error); } finally { try { outStream.flush(); outStream.close(); } catch (IOException e) { Error error = new Error(e.getMessage()); photosDownloadListener.onFailed(error); e.printStackTrace(); } } photosDownloadListener.onComplete(); //TODO notify file saved } finally { CloseableReference.closeSafely(closeableImageRef); } } @Override protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) { //TODO notify failed download Error err = new Error("Failed to download"); photosDownloadListener.onFailed(err); currentExecutor = null; } @Override public void onProgressUpdate(DataSource<CloseableReference<CloseableImage>> dataSource) { boolean isFinished = dataSource.isFinished(); float progress = dataSource.getProgress(); photosDownloadListener.onPregress(progress); } } , executor); } private String getPicturesPath(String urlString) { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); //TODO dirty handle, may find bettery way handel data type int slashIndex = urlString.lastIndexOf("/"); int jpgIndex = urlString.indexOf("?"); String fileName = ""; if (slashIndex > 0 && jpgIndex > 0) { fileName = urlString.substring(slashIndex + 1, jpgIndex); } String imageFileName = (!fileName.equals("")) ? fileName : "IMG_" + timeStamp + (urlString.contains(".jpg") ? ".jpg" : ".png"); File storageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); String galleryPath = storageDir.getAbsolutePath() + "/" + imageFileName; return galleryPath; } @Override public void onTrashButtonPressed(final JSONObject data) { new MaterialDialog.Builder(this) .title(getString(f.getId("string", "DELETE_PHOTOS"))) .content(getString(f.getId("string", "ARE_YOU_SURE_YOU_WANT_TO_DELETE_THE_SELECTED_PHOTOS"))) .positiveText(getString(f.getId("string", "CONFIRM"))) .negativeText(getString(f.getId("string", "CANCEL"))) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { dialog.dismiss(); deletePhoto(getCurrentPosition(), data); } }) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { dialog.dismiss(); } }) .show(); } @Override public void onCaptionChanged(JSONObject data, String caption) { //TODO send caption photoDetail.setCaption(getCurrentPosition(), caption); overlayView.setDescription(caption); if (photoDetail.setCaption(getCurrentPosition(), caption)) { } else { Log.e(TAG, "Error failed to set caption"); } } @Override public void onCloseButtonClicked() { imageViewer.onDismiss(); } @Override public void onSendButtonClick(JSONObject data) { ArrayList<String> ids = new ArrayList<String>(); try { ids.add(data.getString("id")); } catch (JSONException e) { e.printStackTrace(); } JSONObject res = new JSONObject(); try { res.put(KEY_PHOTOS, new JSONArray(ids)); res.put(KEY_ACTION, KEY_ACTION_SEND); res.put(KEY_ID, photoDetail.getId()); res.put(KEY_TYPE, photoDetail.getType()); res.put(KEY_DESCRIPTION, "send photos to destination"); finishWithResult(res); } catch (JSONException e) { e.printStackTrace(); } } @Override public void didEndEditing(JSONObject data, String s) { photoDetail.setCaption(getCurrentPosition(), s); } void finishWithResult(JSONObject result) { Bundle conData = new Bundle(); conData.putString(Constants.RESULT, result.toString()); Intent intent = new Intent(); intent.putExtras(conData); setResult(RESULT_OK, intent); finish(); } @Override public int getOrientation(int currentPosition) { List<Datum> datums = photoDetail.getData(); int orientation = 0; if (datums != null) { if (datums.size() > currentPosition) { Datum datum = datums.get(currentPosition); orientation = datum.getOrientation(); } } return exifToDegrees(orientation); } @Override protected ImageViewer.OnOrientationListener getOrientationListener() { return new ImageViewer.OnOrientationListener() { @Override public int OnOrientaion(int currentPosition) { List<Datum> datums = photoDetail.getData(); int orientation = 0; if (datums != null) { if (datums.size() > currentPosition) { Datum datum = datums.get(currentPosition); orientation = datum.getOrientation(); } } return exifToDegrees(orientation); } }; } private int exifToDegrees(int exifOrientation) { if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { return 180; } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { return 270; } else { return 0; } } }
src/android/PhotoBrowserPluginActivity.java
package com.creedon.cordova.plugin.photobrowser; import android.Manifest; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.media.ExifInterface; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.support.annotation.NonNull; import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.text.InputType; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.GravityEnum; import com.afollestad.materialdialogs.MaterialDialog; import com.creedon.androidphotobrowser.PhotoBrowserActivity; import com.creedon.androidphotobrowser.PhotoBrowserBasicActivity; import com.creedon.androidphotobrowser.common.data.models.CustomImage; import com.creedon.androidphotobrowser.common.views.ImageOverlayView; import com.creedon.cordova.plugin.photobrowser.metadata.ActionSheet; import com.creedon.cordova.plugin.photobrowser.metadata.Datum; import com.creedon.cordova.plugin.photobrowser.metadata.PhotoDetail; import com.facebook.common.executors.CallerThreadExecutor; import com.facebook.common.references.CloseableReference; import com.facebook.datasource.BaseDataSubscriber; import com.facebook.datasource.DataSource; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.image.CloseableBitmap; import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; import com.stfalcon.frescoimageviewer.ImageViewer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import static com.creedon.cordova.plugin.photobrowser.PhotoBrowserPlugin.KEY_ACTION; import static com.creedon.cordova.plugin.photobrowser.PhotoBrowserPlugin.KEY_ACTION_SEND; import static com.creedon.cordova.plugin.photobrowser.PhotoBrowserPlugin.KEY_DESCRIPTION; import static com.creedon.cordova.plugin.photobrowser.PhotoBrowserPlugin.KEY_PHOTOS; import static com.creedon.cordova.plugin.photobrowser.PhotoBrowserPlugin.KEY_TYPE; public class PhotoBrowserPluginActivity extends PhotoBrowserActivity implements PhotoBrowserBasicActivity.PhotoBrowserListener, ImageOverlayView.ImageOverlayVieListener { public static final String TAG = PhotoBrowserPluginActivity.class.getSimpleName(); public static final float MAX = 100; public static final int SAVE_PHOTO = 0x11; public static final String KEY_ID = "id"; private static final String KEY_ALBUM = "album"; private static final String KEY_TYPE_NIXALBUM = "nixalbum"; private static final int TAG_SELECT_ALL = 0x501; private CallerThreadExecutor currentExecutor; private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE}; private ArrayList<String> pendingFetchDatas; PhotoDetail photoDetail; PhotoBrowserPluginActivity.PhotosDownloadListener photosDownloadListener = new PhotosDownloadListener() { @Override public void onPregress(final float progress) { runOnUiThread(new Runnable() { @Override public void run() { int v = (int) (progress * MAX); progressDialog.setProgress(v); } }); } @Override public void onComplete() { runOnUiThread(new Runnable() { @Override public void run() { progressDialog.dismiss(); } }); } @Override public void onFailed(Error err) { runOnUiThread(new Runnable() { @Override public void run() { progressDialog.dismiss(); } }); } }; private BottomSheetBehavior<View> mBottomSheetBehavior1; // private OkHttpClient globalOkHttpClient3; interface PhotosDownloadListener { void onPregress(float progress); void onComplete(); void onFailed(Error err); } private static final String KEY_ORIGINALURL = "originalUrl"; private FakeR f; private Context context; final private static String DEFAULT_ACTION_ADD = "add"; final private static String DEFAULT_ACTION_SELECT = "select"; final private static String DEFAULT_ACTION_ADDTOPLAYLIST = "addToPlaylist"; final private static String DEFAULT_ACTION_ADDTOFRAME = "addToFrame"; final private static String DEFAULT_ACTION_RENAME = "rename"; final private static String DEFAULT_ACTION_DELETE = "delete"; MaterialDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { if (!Fresco.hasBeenInitialized()) { Context context = this; // global 3 = new OkHttpClient(); // ImagePipelineConfig config = OkHttpImagePipelineConfigFactory // .newBuilder(context,globalOkHttpClient3) // .setNetworkFetcher(new OkHttp3NetworkFetcher(globalOkHttpClient3)) // .build(); // Fresco.initialize(context, config); Fresco.initialize(this); } super.onCreate(savedInstanceState); } @Override public boolean onCreatePanelMenu(int featureId, Menu menu) { if (!selectionMode) { //TODO build aaction menu from custom data int index = 0; for (ActionSheet actionSheet : photoDetail.getActionSheet()) { String label = actionSheet.getLabel(); String action = actionSheet.getAction(); if (action.equals(DEFAULT_ACTION_SELECT)) { MenuItem menuItem = menu.add(0, index, 1, label); //TODO any better way to create menu/menu icon? menuItem.setShowAsAction((index == 0 && label.toLowerCase().contains("add") || action.equals(DEFAULT_ACTION_SELECT)) ? MenuItem.SHOW_AS_ACTION_ALWAYS : MenuItem.SHOW_AS_ACTION_NEVER); if (index == 0 && label.toLowerCase().contains("add")) { menuItem.setIcon(f.getId("drawable", "ic_action_add")); } } index++; } setupToolBar(); } else { if(photoDetail.getType().equals(KEY_TYPE_NIXALBUM)){ MenuItem menuItem = menu.add(0, TAG_SELECT_ALL, 1, getString(f.getId("string", "SELECT_ALL"))); //TODO any better way to create menu/menu icon? menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); }else { MenuInflater inflater = getMenuInflater(); inflater.inflate(com.creedon.androidphotobrowser.R.menu.menu, menu); setupToolBar(); } } return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == SAVE_PHOTO) { for (int r : grantResults) { if (r == PackageManager.PERMISSION_GRANTED) { if (pendingFetchDatas != null) { downloadWithURLS(pendingFetchDatas, pendingFetchDatas.size(), this.photosDownloadListener); } } } } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection int id = item.getItemId(); if(id == TAG_SELECT_ALL){ if(item.getTitle().equals(getString(f.getId("string","SELECT_ALL")))) { item.setTitle(getString(f.getId("string", "DESELECT_ALL"))); for (int i = 0; i < selections.size(); i++) { selections.set(i, "1"); } rcAdapter.notifyDataSetChanged(); }else{ item.setTitle(getString(f.getId("string","SELECT_ALL"))); for (int i = 0; i < selections.size(); i++) { selections.set(i, "0"); } rcAdapter.notifyDataSetChanged(); } }else if (id == android.R.id.home) { if (!selectionMode) { finish(); } } else if (id == com.creedon.androidphotobrowser.R.id.delete) { try { deletePhotos(); } catch (JSONException e) { e.printStackTrace(); } //TODO delete item } // else if (id == com.creedon.androidphotobrowser.R.id.send) { //// addAlbumToPlaylist(); // try { // sendPhotos(); // } catch (JSONException e) { // e.printStackTrace(); // } // } else if (id == com.creedon.androidphotobrowser.R.id.download) { // try { // downloadPhotos(); // } catch (JSONException e) { // e.printStackTrace(); // } // } else if (item.getTitle() != null) { for (ActionSheet actionSheet : photoDetail.getActionSheet()) { String label = actionSheet.getLabel(); String action = actionSheet.getAction(); if (label.equals(item.getTitle())) { if (action.equals(DEFAULT_ACTION_ADD)) { try { addPhotos(); } catch (JSONException e) { e.printStackTrace(); } } else if (action.equals(DEFAULT_ACTION_RENAME)) { editAlbumName(); } else if (action.equals(DEFAULT_ACTION_ADDTOPLAYLIST)) { try { addAlbumToPlaylist(); } catch (JSONException e) { e.printStackTrace(); } } else if (action.equals(DEFAULT_ACTION_DELETE)) { deleteAlbum(); } else if (action.equals(DEFAULT_ACTION_SELECT)) { setupSelectionMode(!selectionMode); } else if (action.equals(DEFAULT_ACTION_ADDTOFRAME)) { try { addAlbumToFrame(); } catch (JSONException e) { e.printStackTrace(); } } break; } } } else { return super.onOptionsItemSelected(item); } return false; } private void addAlbumToFrame() throws JSONException { JSONObject res = new JSONObject(); res.put(KEY_ACTION, DEFAULT_ACTION_ADDTOFRAME); res.put(KEY_ID, photoDetail.getId()); res.put(KEY_TYPE, photoDetail.getType()); res.put(KEY_DESCRIPTION, "send photos to destination"); finishWithResult(res); } private void sendPhotos() throws JSONException { ArrayList<String> fetchedDatas = new ArrayList<String>(); for (int i = 0; i < selections.size(); i++) { //add to temp lsit if not selected if (selections.get(i).equals("1")) { JSONObject object = photoDetail.getData().get(i).toJSON(); String id = object.getString(KEY_ID); fetchedDatas.add(id); } } if (fetchedDatas.size() > 0) { JSONObject res = new JSONObject(); try { res.put(KEY_PHOTOS, new JSONArray(fetchedDatas)); res.put(KEY_ACTION, KEY_ACTION_SEND); res.put(KEY_ID, photoDetail.getId()); res.put(KEY_TYPE, photoDetail.getType()); res.put(KEY_DESCRIPTION, "send photos to destination"); finishWithResult(res); } catch (JSONException e) { e.printStackTrace(); } } } @Override protected void init() { f = new FakeR(getApplicationContext()); progressDialog = new MaterialDialog .Builder(this) .title(getString(f.getId("string", "DOWNLOADING"))) .neutralText(getString(f.getId("string", "CANCEL"))) .onAny(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { if (currentExecutor != null) { currentExecutor.shutdown(); } } }) .dismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (currentExecutor != null) { currentExecutor.shutdown(); } } }) .progress(false, 100, true) .build(); context = getApplicationContext(); listener = this; if (getIntent().getExtras() != null) { Bundle bundle = getIntent().getExtras(); String optionsJsonString = bundle.getString("options"); try { photoDetail = PhotoDetail.getInstance(new JSONObject(optionsJsonString)); } catch (JSONException e) { e.printStackTrace(); } // try { // JSONObject jsonObject = new JSONObject(optionsJsonString); // JSONArray images = jsonObject.getJSONArray("images"); // JSONArray thumbnails = jsonObject.getJSONArray("thumbnails"); // JSONArray data = jsonObject.getJSONArray("data"); // JSONArray captions = jsonObject.getJSONArray("captions"); // String id = jsonObject.getString("id"); // name = jsonObject.getString("name"); // int count = jsonObject.getInt("count"); // String type = jsonObject.getString("type"); // try { // actionSheet = jsonObject.getJSONArray("actionSheet"); // } catch (Exception e) { // e.printStackTrace(); // } // _previewUrls = new ArrayList<String>(); // _thumbnailUrls = new ArrayList<String>(); // _captions = new ArrayList<String>(); // _data = new ArrayList<JSONObject>(); // for (int i = 0; i < images.length(); i++) { // _previewUrls.add(images.getString(i)); // } // for (int i = 0; i < thumbnails.length(); i++) { // _thumbnailUrls.add(thumbnails.getString(i)); // } // for (int i = 0; i < captions.length(); i++) { // _captions.add(captions.getString(i)); // } // for (int i = 0; i < data.length(); i++) { // _data.add(data.getJSONObject(i)); // } // // // } catch (JSONException e) { // e.printStackTrace(); // } } super.init(); photoDetail.setType(KEY_TYPE_NIXALBUM); if(photoDetail.getType().equals(KEY_TYPE_NIXALBUM)) { setupSelectionMode(true); } View bottomSheet = findViewById(f.getId("id", "bottom_sheet1")); mBottomSheetBehavior1 = BottomSheetBehavior.from(bottomSheet); mBottomSheetBehavior1.setHideable(true); mBottomSheetBehavior1.setState(BottomSheetBehavior.STATE_HIDDEN); TextView titleTextView = (TextView) findViewById(f.getId("id", "titleTextView")); titleTextView.setText(getString(f.getId("string", "ADD_PHOTOS"))); FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(f.getId("id", "floatingButton")); if (floatingActionButton != null) { floatingActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(photoDetail.getType().equals(KEY_TYPE_NIXALBUM)) { try { sendPhotos(); } catch (JSONException e) { e.printStackTrace(); } }else{ if (mBottomSheetBehavior1.getState() != BottomSheetBehavior.STATE_EXPANDED) { mBottomSheetBehavior1.setState(BottomSheetBehavior.STATE_EXPANDED); } else { mBottomSheetBehavior1.setState(BottomSheetBehavior.STATE_HIDDEN); } } } }); } LinearLayout sheetLinearLayout = (LinearLayout) findViewById(f.getId("id", "sheetLinearLayout")); int index = 0; for (ActionSheet actionSheet : photoDetail.getActionSheet()) { try { String label = actionSheet.getLabel(); final String action = actionSheet.getAction(); Button imageButton = new Button(this, null, android.R.style.Widget_Button_Small);//@android:style/Widget.Button.Small Drawable drawable = null; if (index % 3 == 0) { drawable = getResources().getDrawable(com.creedon.androidphotobrowser.R.drawable.camera); } else if (index % 3 == 1) { drawable = getResources().getDrawable(com.creedon.androidphotobrowser.R.drawable.photolibrary); } else if (index % 3 == 2) { drawable = getResources().getDrawable(com.creedon.androidphotobrowser.R.drawable.nixplayalbum); } if (drawable != null) { int h = drawable.getIntrinsicHeight(); int w = drawable.getIntrinsicWidth(); drawable.setBounds(0, 0, w, h); imageButton.setBackgroundColor(0x00000000); imageButton.setCompoundDrawables(null, drawable, null, null); imageButton.setText(label); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { imageButton.setTextAppearance(f.getId("style", "AppTheme")); } else { imageButton.setTextAppearance(this, f.getId("style", "AppTheme")); } } LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1); layoutParams.setMargins(10,10,10,10); imageButton.setLayoutParams(layoutParams); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { JSONObject res = new JSONObject(); try { res.put(KEY_ACTION, action); res.put(KEY_ID, photoDetail.getId()); res.put(KEY_TYPE, photoDetail.getType()); res.put(KEY_DESCRIPTION, "add photo to album"); finishWithResult(res); } catch (JSONException e) { e.printStackTrace(); } mBottomSheetBehavior1.setState(BottomSheetBehavior.STATE_HIDDEN); } }); sheetLinearLayout.addView(imageButton); } catch (Exception e) { e.printStackTrace(); } index++; if (index == 3) break; } } @Override public List<String> photoBrowserPhotos(PhotoBrowserBasicActivity activity) { return photoDetail.getImages(); } @Override public List<String> photoBrowserThumbnails(PhotoBrowserBasicActivity activity) { return photoDetail.getThumbnails(); } @Override public String photoBrowserPhotoAtIndex(PhotoBrowserBasicActivity activity, int index) { return null; } @Override public List<String> photoBrowserPhotoCaptions(PhotoBrowserBasicActivity photoBrowserBasicActivity) { return photoDetail.getCaptions(); } @Override public String getActionBarTitle() { return photoDetail.getName(); } @Override public String getSubtitle() { if (photoDetail.getImages() == null) { return "0" + " " + context.getResources().getString(f.getId("string", "PHOTOS")); } else { return String.valueOf(this.photoDetail.getImages().size()) + " " + context.getResources().getString(f.getId("string", "PHOTOS")); } } @Override public List<CustomImage> getCustomImages(PhotoBrowserActivity photoBrowserActivity) { try { List<CustomImage> images = new ArrayList<CustomImage>(); ArrayList<String> previewUrls = (ArrayList<String>) listener.photoBrowserPhotos(this); ArrayList<String> captions = (ArrayList<String>) listener.photoBrowserPhotoCaptions(this); try { for (int i = 0; i < previewUrls.size(); i++) { images.add(new CustomImage(previewUrls.get(i), captions.get(i))); } } catch (Exception e) { e.printStackTrace(); } return images; } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected ImageViewer.OnImageChangeListener getImageChangeListener() { return new ImageViewer.OnImageChangeListener() { @Override public void onImageChange(int position) { setCurrentPosition(position); overlayView.setDescription(photoDetail.getCaptions().get(position)); try { overlayView.setData(photoDetail.getData().get(position).toJSON()); } catch (JSONException e) { e.printStackTrace(); } } }; } private void addPhotos() throws JSONException { //dismiss and send code JSONObject res = new JSONObject(); res.put(KEY_ACTION, DEFAULT_ACTION_ADD); res.put(KEY_ID, photoDetail.getId()); res.put(KEY_TYPE, photoDetail.getType()); res.put(KEY_DESCRIPTION, "add photo to album"); finishWithResult(res); } private void addAlbumToPlaylist() throws JSONException { JSONObject res = new JSONObject(); res.put(KEY_ACTION, DEFAULT_ACTION_ADDTOPLAYLIST); res.put(KEY_ID, photoDetail.getId()); res.put(KEY_TYPE, photoDetail.getType()); res.put(KEY_DESCRIPTION, "send photos to destination"); finishWithResult(res); } private void editAlbumName() { new MaterialDialog.Builder(this) .title(getString(f.getId("string", photoDetail.getType().toLowerCase().equals(KEY_ALBUM) ? "EDIT_ALBUM_NAME" : "EDIT_PLAYLIST_NAME"))) .inputType(InputType.TYPE_CLASS_TEXT) .input(getString(f.getId("string", "EDIT_ALBUM_NAME")), photoDetail.getName(), new MaterialDialog.InputCallback() { @Override public void onInput(@NonNull MaterialDialog dialog, @NonNull CharSequence input) { dialog.dismiss(); photoDetail.setName(input.toString()); android.support.v7.app.ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(input.toString()); } photoDetail.onSetName(input.toString()); } }).show(); } private void deleteAlbum() { String content = getString(f.getId("string", "ARE_YOU_SURE_YOU_WANT_TO_DELETE_THIS_ALBUM_THIS_WILL_ALSO_REMOVE_THE_PHOTOS_FROM_THE_PLAYLIST_IF_THEY_ARE_NOT_IN_ANY_OTHER_ALBUMS")); content.replace(KEY_ALBUM, photoDetail.getType()); new MaterialDialog.Builder(this) .title(getString(f.getId("string", "DELETE")) + photoDetail.getType()) .content(content) .positiveText(getString(f.getId("string", "CONFIRM"))) .negativeText(getString(f.getId("string", "CANCEL"))) .btnStackedGravity(GravityEnum.CENTER) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { dialog.dismiss(); try { JSONObject res = new JSONObject(); res.put(KEY_ACTION, DEFAULT_ACTION_DELETE); res.put(KEY_ID, photoDetail.getId()); res.put(KEY_TYPE, photoDetail.getType()); res.put(KEY_DESCRIPTION, "delete " + photoDetail.getType()); finishWithResult(res); } catch (JSONException e) { e.printStackTrace(); } } }) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { dialog.dismiss(); } }) .show(); } private void downloadPhotos() throws JSONException { //TODO download photos ArrayList<String> fetchedDatas = new ArrayList<String>(); for (int i = 0; i < selections.size(); i++) { //add to temp lsit if not selected if (selections.get(i).equals("1")) { JSONObject object = photoDetail.getData().get(i).toJSON(); String id = object.getString(KEY_ORIGINALURL); fetchedDatas.add(id); } } if (fetchedDatas.size() > 0) { progressDialog.setProgress(0); progressDialog.show(); downloadWithURLS(fetchedDatas, fetchedDatas.size(), this.photosDownloadListener); } } private void deletePhotos() throws JSONException { final ArrayList<String> fetchedDatas = new ArrayList<String>(); final ArrayList<Datum> tempDatas = new ArrayList<Datum >(); final ArrayList<String> tempPreviews = new ArrayList<String>(); final ArrayList<String> tempCations = new ArrayList<String>(); final ArrayList<String> tempThumbnails = new ArrayList<String>(); final ArrayList<String> tempSelection = new ArrayList<String>(); for (int i = 0; i < selections.size(); i++) { //add to temp lsit if not selected if (selections.get(i).equals("0")) { tempDatas.add(photoDetail.getData().get(i)); tempPreviews.add(photoDetail.getImages().get(i)); tempCations.add(photoDetail.getCaptions().get(i)); tempThumbnails.add(photoDetail.getThumbnails().get(i)); tempSelection.add(selections.get(i)); } else { Datum object = photoDetail.getData().get(i); String id = object.getId(); fetchedDatas.add(id); } } if (fetchedDatas.size() > 0) { new MaterialDialog.Builder(this) .title(getString(f.getId("string", "DELETE_PHOTOS"))) .content(getString(f.getId("string", "ARE_YOU_SURE_YOU_WANT_TO_DELETE_THE_SELECTED_PHOTOS"))) .positiveText(getString(f.getId("string", "CONFIRM"))) .negativeText(getString(f.getId("string", "CANCEL"))) .btnStackedGravity(GravityEnum.CENTER) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { dialog.dismiss(); photoDetail.onPhotoDeleted(fetchedDatas); photoDetail.setImages(tempPreviews); photoDetail.setData(tempDatas); photoDetail.setCaptions(tempCations); photoDetail.setThumbnails(tempThumbnails); selections = tempSelection; if (photoDetail.getImages().size() == 0) { finish(); } else { ArrayList<String> list = new ArrayList<String>(photoDetail.getThumbnails()); getRcAdapter().swap(list); } } }) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { dialog.dismiss(); } }) .show(); } // todo notify changed } private void deletePhoto(int position, JSONObject data) { try { Datum deletedData = photoDetail.getData().remove(position); photoDetail.getImages().remove(position); photoDetail.getCaptions().remove(position); photoDetail.getThumbnails().remove(position); selections.remove(position); ArrayList<String> deletedDatas = new ArrayList<String>(); deletedDatas.add(deletedData.getId()); photoDetail.onPhotoDeleted(deletedDatas); if (photoDetail.getImages().size() == 0) { finish(); } else { imageViewer.onDismiss(); super.refreshCustomImage(); showPicker(photoDetail.getImages().size() == 1 ? 0 : getCurrentPosition() > 0 ? getCurrentPosition() - 1 : getCurrentPosition()); ArrayList<String> list = new ArrayList<String>(photoDetail.getThumbnails()); getRcAdapter().swap(list); } } catch (Exception e) { e.printStackTrace(); } // todo notify changed } private void downloadWithURLS(final ArrayList<String> fetchedDatas, final int counts, final PhotosDownloadListener _photosDownloadListener) { Log.d(TAG, "going to download " + fetchedDatas.get(0)); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(permissions, SAVE_PHOTO); } pendingFetchDatas = fetchedDatas; return; } downloadPhotoWithURL(fetchedDatas.get(0), new PhotosDownloadListener() { @Override public void onPregress(float progress) { float particialProgress = ((1.0f / counts) * progress); Log.d(TAG, "particialProgress " + particialProgress); float curentsize = fetchedDatas.size(); float partition = (counts - curentsize); Log.d(TAG, "partition " + partition); float PROGRESS = (partition / counts) + particialProgress; Log.d(TAG, "Progress " + PROGRESS); _photosDownloadListener.onPregress(PROGRESS); } @Override public void onComplete() { fetchedDatas.remove(0); if (fetchedDatas.size() > 0) { downloadWithURLS(fetchedDatas, counts, _photosDownloadListener); } else { _photosDownloadListener.onComplete(); } } @Override public void onFailed(Error err) { _photosDownloadListener.onFailed(err); } }); } @Override public void onDownloadButtonPressed(JSONObject data) { //Save image to camera roll try { if (data.getString(KEY_ORIGINALURL) != null) { progressDialog.setProgress(0); progressDialog.show(); ArrayList<String> fetchedDatas = new ArrayList<String>(); fetchedDatas.add(data.getString(KEY_ORIGINALURL)); downloadWithURLS(fetchedDatas, fetchedDatas.size(), this.photosDownloadListener); } } catch (JSONException e) { e.printStackTrace(); } } private void downloadPhotoWithURL(String string, @NonNull final PhotosDownloadListener photosDownloadListener) { final Uri uri = Uri.parse(string); ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri) .build(); DataSource<CloseableReference<CloseableImage>> dataSource = Fresco.getImagePipeline() .fetchDecodedImage(request, this); CallerThreadExecutor executor = CallerThreadExecutor.getInstance(); currentExecutor = executor; dataSource.subscribe( new BaseDataSubscriber<CloseableReference<CloseableImage>>() { @Override protected void onNewResultImpl(DataSource<CloseableReference<CloseableImage>> dataSource) { currentExecutor = null; if (!dataSource.isFinished()) { return; } CloseableReference<CloseableImage> closeableImageRef = dataSource.getResult(); Bitmap bitmap = null; if (closeableImageRef != null && closeableImageRef.get() instanceof CloseableBitmap) { bitmap = ((CloseableBitmap) closeableImageRef.get()).getUnderlyingBitmap(); } try { String filePath = getPicturesPath(uri.toString()); File file = new File(filePath); OutputStream outStream = null; try { outStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream); } catch (FileNotFoundException e) { e.printStackTrace(); Error error = new Error(e.getMessage()); photosDownloadListener.onFailed(error); } finally { try { outStream.flush(); outStream.close(); } catch (IOException e) { Error error = new Error(e.getMessage()); photosDownloadListener.onFailed(error); e.printStackTrace(); } } photosDownloadListener.onComplete(); //TODO notify file saved } finally { CloseableReference.closeSafely(closeableImageRef); } } @Override protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) { //TODO notify failed download Error err = new Error("Failed to download"); photosDownloadListener.onFailed(err); currentExecutor = null; } @Override public void onProgressUpdate(DataSource<CloseableReference<CloseableImage>> dataSource) { boolean isFinished = dataSource.isFinished(); float progress = dataSource.getProgress(); photosDownloadListener.onPregress(progress); } } , executor); } private String getPicturesPath(String urlString) { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); //TODO dirty handle, may find bettery way handel data type int slashIndex = urlString.lastIndexOf("/"); int jpgIndex = urlString.indexOf("?"); String fileName = ""; if (slashIndex > 0 && jpgIndex > 0) { fileName = urlString.substring(slashIndex + 1, jpgIndex); } String imageFileName = (!fileName.equals("")) ? fileName : "IMG_" + timeStamp + (urlString.contains(".jpg") ? ".jpg" : ".png"); File storageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); String galleryPath = storageDir.getAbsolutePath() + "/" + imageFileName; return galleryPath; } @Override public void onTrashButtonPressed(final JSONObject data) { new MaterialDialog.Builder(this) .title(getString(f.getId("string", "DELETE_PHOTOS"))) .content(getString(f.getId("string", "ARE_YOU_SURE_YOU_WANT_TO_DELETE_THE_SELECTED_PHOTOS"))) .positiveText(getString(f.getId("string", "CONFIRM"))) .negativeText(getString(f.getId("string", "CANCEL"))) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { dialog.dismiss(); deletePhoto(getCurrentPosition(), data); } }) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { dialog.dismiss(); } }) .show(); } @Override public void onCaptionChanged(JSONObject data, String caption) { //TODO send caption photoDetail.setCaption(getCurrentPosition(), caption); overlayView.setDescription(caption); if (photoDetail.setCaption(getCurrentPosition(), caption)) { } else { Log.e(TAG, "Error failed to set caption"); } } @Override public void onCloseButtonClicked() { imageViewer.onDismiss(); } @Override public void onSendButtonClick(JSONObject data) { ArrayList<String> ids = new ArrayList<String>(); try { ids.add(data.getString("id")); } catch (JSONException e) { e.printStackTrace(); } JSONObject res = new JSONObject(); try { res.put(KEY_PHOTOS, new JSONArray(ids)); res.put(KEY_ACTION, KEY_ACTION_SEND); res.put(KEY_ID, photoDetail.getId()); res.put(KEY_TYPE, photoDetail.getType()); res.put(KEY_DESCRIPTION, "send photos to destination"); finishWithResult(res); } catch (JSONException e) { e.printStackTrace(); } } @Override public void didEndEditing(JSONObject data, String s) { photoDetail.setCaption(getCurrentPosition(), s); } void finishWithResult(JSONObject result) { Bundle conData = new Bundle(); conData.putString(Constants.RESULT, result.toString()); Intent intent = new Intent(); intent.putExtras(conData); setResult(RESULT_OK, intent); finish(); } @Override public int getOrientation(int currentPosition) { List<Datum> datums = photoDetail.getData(); int orientation = 0; if (datums != null) { if (datums.size() > currentPosition) { Datum datum = datums.get(currentPosition); orientation = datum.getOrientation(); } } return exifToDegrees(orientation); } @Override protected ImageViewer.OnOrientationListener getOrientationListener() { return new ImageViewer.OnOrientationListener() { @Override public int OnOrientaion(int currentPosition) { List<Datum> datums = photoDetail.getData(); int orientation = 0; if (datums != null) { if (datums.size() > currentPosition) { Datum datum = datums.get(currentPosition); orientation = datum.getOrientation(); } } return exifToDegrees(orientation); } }; } private int exifToDegrees(int exifOrientation) { if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { return 180; } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { return 270; } else { return 0; } } }
update layout
src/android/PhotoBrowserPluginActivity.java
update layout
<ide><path>rc/android/PhotoBrowserPluginActivity.java <ide> } <ide> <ide> }else if (id == android.R.id.home) { <del> if (!selectionMode) { <add> if (!selectionMode || photoDetail.getType().equals(KEY_TYPE_NIXALBUM)) { <ide> finish(); <ide> } <ide> <ide> } <ide> super.init(); <ide> <del> photoDetail.setType(KEY_TYPE_NIXALBUM); <ide> if(photoDetail.getType().equals(KEY_TYPE_NIXALBUM)) { <ide> setupSelectionMode(true); <ide> } <ide> imageButton.setTextAppearance(this, f.getId("style", "AppTheme")); <ide> } <ide> } <del> LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1); <add> LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1); <ide> layoutParams.setMargins(10,10,10,10); <ide> imageButton.setLayoutParams(layoutParams); <ide> imageButton.setOnClickListener(new View.OnClickListener() {
JavaScript
mit
948af76aaa10ca7601a1d262c1ca300ed152f466
0
kiettisak-angkanawin/guess_word_scoreboard,kiettisak-angkanawin/guess_word_scoreboard
/** * This file contains all necessary Angular controller definitions for 'frontend.examples.messages' module. * * Note that this file should only contain controllers and nothing else. */ (function() { 'use strict'; /** * Message controller that demonstrates boilerplate error handling and usage of MessageService. * * @todo * 1) Make example about $http / $sailsSocket usage where automatic message is disabled. * 2) Make example about invalid JWT */ angular.module('frontend.scoreboard') .controller('ScoreboardController', [ '$scope', '$http', '$sailsSocket', 'MessageService', 'BackendConfig', '_', function( $scope, $http, $sailsSocket, MessageService, BackendConfig, _ ) { // Initialize used scope variables $scope.guessWord = 'Taxi Driver Base'; var words = ['a','b','c','d','e','g']; $scope.team1Point = 0; $scope.team2Point = 0; $scope.point = 1; $scope.reset = function reset() { $scope.guessWord = 'Taxi Driver Base'; words = ['a','b','c','d','e','g']; $scope.team1Point = 0; $scope.team2Point = 0; $scope.point = 1; }; $scope.randomGuessWord = function randomGuessWord() { //var randomIndex = _.random(0, words.length-1); if(_.isEmpty(words)){ return MessageService['error']('Run out of Words in list'); } $scope.guessWord = words.splice(_.random(words.length - 1), 1)[0]; }; $scope.addTeam1Point = function addTeam1Point() { $scope.team1Point += _.parseInt($scope.point); }; $scope.addTeam2Point = function addTeam2Point() { $scope.team2Point += _.parseInt($scope.point); }; $scope.decreaseTeam1Point = function decreaseTeam1Point (){ $scope.team1Point -= 1; }; $scope.decreaseTeam2Point = function decreaseTeam2Point (){ $scope.team2Point -= 1; }; $('.pull-down').each(function() { $(this).css('margin-top', $(this).parent().height()-$(this).height()) }); } ]) ; }());
src/app/scoreboard/scoreboard-controllers.js
/** * This file contains all necessary Angular controller definitions for 'frontend.examples.messages' module. * * Note that this file should only contain controllers and nothing else. */ (function() { 'use strict'; /** * Message controller that demonstrates boilerplate error handling and usage of MessageService. * * @todo * 1) Make example about $http / $sailsSocket usage where automatic message is disabled. * 2) Make example about invalid JWT */ angular.module('frontend.scoreboard') .controller('ScoreboardController', [ '$scope', '$http', '$sailsSocket', 'MessageService', 'BackendConfig', function( $scope, $http, $sailsSocket, MessageService, BackendConfig ) { // Initialize used scope variables $scope.guessWord = 'Taxi Driver Base'; var words = ['a','b','c','d','e','g']; $scope.team1Point = 0; $scope.team2Point = 0; $scope.point = 1; $scope.reset = function reset() { $scope.guessWord = 'Taxi Driver Base'; words = ['a','b','c','d','e','g']; $scope.team1Point = 0; $scope.team2Point = 0; $scope.point = 1; }; $scope.randomGuessWord = function randomGuessWord() { //var randomIndex = _.random(0, words.length-1); if(_.isEmpty(words)){ return MessageService['error']('Run out of Words in list'); } $scope.guessWord = words.splice(_.random(words.length - 1), 1)[0]; }; $scope.addTeam1Point = function addTeam1Point() { $scope.team1Point += _.parseInt($scope.point); }; $scope.addTeam2Point = function addTeam2Point() { $scope.team2Point += _.parseInt($scope.point); }; $scope.decreaseTeam1Point = function decreaseTeam1Point (){ $scope.team1Point -= 1; }; $scope.decreaseTeam2Point = function decreaseTeam2Point (){ $scope.team2Point -= 1; }; $('.pull-down').each(function() { $(this).css('margin-top', $(this).parent().height()-$(this).height()) }); } ]) ; }());
fixed _ error on jshint
src/app/scoreboard/scoreboard-controllers.js
fixed _ error on jshint
<ide><path>rc/app/scoreboard/scoreboard-controllers.js <ide> .controller('ScoreboardController', [ <ide> '$scope', '$http', '$sailsSocket', <ide> 'MessageService', 'BackendConfig', <add> '_', <ide> function( <ide> $scope, $http, $sailsSocket, <del> MessageService, BackendConfig <add> MessageService, BackendConfig, <add> _ <ide> ) { <ide> // Initialize used scope variables <ide>
Java
bsd-3-clause
963a0c3d7c610092365c14caa606af471e503b05
0
abhinayagarwal/MyDevoxxGluon,tiainen/MyDevoxxGluon,erwin1/MyDevoxxGluon,devoxx/MyDevoxxGluon
/* * Copyright (c) 2016, 2018, Gluon Software * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.devoxx.views.cell; import com.devoxx.DevoxxView; import com.devoxx.model.Favorite; import com.devoxx.model.Session; import com.devoxx.model.TalkSpeaker; import com.devoxx.service.Service; import com.devoxx.util.DevoxxBundle; import com.devoxx.util.DevoxxSettings; import com.devoxx.views.SessionPresenter; import com.devoxx.views.helper.SessionVisuals; import com.gluonhq.charm.glisten.control.CharmListCell; import com.gluonhq.charm.glisten.control.ListTile; import com.gluonhq.charm.glisten.visual.MaterialDesignIcon; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.css.PseudoClass; import javafx.geometry.HPos; import javafx.geometry.Pos; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.Priority; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; public class ScheduleCell extends CharmListCell<Session> { private static final PseudoClass PSEUDO_CLASS_COLORED = PseudoClass.getPseudoClass("color"); private static Map<String, PseudoClass> trackPseudoClassMap = new HashMap<>(); private static List<String> pseudoClasses = Arrays.asList("track-color0", "track-color1", "track-color2", "track-color3", "track-color4", "track-color5", "track-color6", "track-color7", "track-color8", "track-color9" ); private static int index = 0; private final Service service; private final ListTile listTile; private final BorderPane borderPane; private final HBox sessionType; private final Label sessionTypeLabel; private final SecondaryGraphic secondaryGraphic; private final Label trackLabel; private Label startDateLabel; private Session session; private boolean showDate; private boolean showSessionType; private PseudoClass oldPseudoClass; public ScheduleCell(Service service) { this(service, false, false); } public ScheduleCell(Service service, boolean showDate, boolean showSessionType) { this.service = service; this.showDate = showDate; this.showSessionType = showSessionType; trackLabel = new Label(); secondaryGraphic = new SecondaryGraphic(); listTile = new ListTile(); listTile.setWrapText(true); listTile.setPrimaryGraphic(new Group(trackLabel)); listTile.setSecondaryGraphic(secondaryGraphic); sessionTypeLabel = new Label(); sessionType = new HBox(sessionTypeLabel); sessionType.getStyleClass().add("session-type"); borderPane = new BorderPane(listTile); setText(null); getStyleClass().add("schedule-cell"); } @Override public void updateItem(Session item, boolean empty) { super.updateItem(item, empty); session = item; if (item != null && !empty) { updateListTile(); secondaryGraphic.updateGraphic(session); if (showSessionType && item.isShowSessionType()) { sessionTypeLabel.setText(item.getTalk().getTalkType()); borderPane.setTop(sessionType); } else { borderPane.setTop(null); } setGraphic(borderPane); // FIX for OTN-568 listTile.setOnMouseReleased(event -> { DevoxxView.SESSION.switchView().ifPresent(presenter -> ((SessionPresenter) presenter).showSession(session)); }); } else { setGraphic(null); } } private void updateListTile() { if (session.getTalk() != null) { if (session.getTalk().getTrack() != null) { final String trackId = session.getTalk().getTrackId().toUpperCase(); trackLabel.setText(trackId); changePseudoClass(fetchPseudoClassForTrack(trackId)); } if (session.getTalk().getTitle() != null) { listTile.setTextLine(0, session.getTalk().getTitle()); } List<TalkSpeaker> speakers = session.getTalk().getSpeakers(); listTile.setTextLine(1, convertSpeakersToString(speakers)); } listTile.setTextLine(2, DevoxxBundle.getString("OTN.SCHEDULE.IN_AT", session.getRoomName(), DevoxxSettings.TIME_FORMATTER.format(session.getStartDate()), DevoxxSettings.TIME_FORMATTER.format(session.getEndDate()))); if (showDate) { initializeStartLabel(); startDateLabel.setText(DevoxxSettings.DATE_FORMATTER.format(session.getStartDate())); // Hacky Code as it uses internals of ListTile ((VBox) listTile.getChildren().get(0)).getChildren().add(startDateLabel); } Optional<Favorite> favorite = Optional.empty(); for (Favorite fav : service.retrieveFavorites()) { if (fav.getId().equals(session.getTalk().getId())) { favorite = Optional.of(fav); break; } } Favorite fav = favorite.orElseGet(() -> { Favorite emptyFavorite = new Favorite(); emptyFavorite.setId(session.getTalk().getId()); service.retrieveFavorites().add(emptyFavorite); return emptyFavorite; }); // Hacky Code as it uses internals of ListTile final VBox vBox = (VBox) listTile.getChildren().get(0); Label label = (Label) vBox.getChildren().get(vBox.getChildren().size() - 1); Label favLabel = new Label(); favLabel.textProperty().bind(fav.favsProperty().asString()); favLabel.visibleProperty().bind(fav.favsProperty().greaterThanOrEqualTo(10)); favLabel.getStyleClass().add("fav-label"); Node graphic = MaterialDesignIcon.FAVORITE.graphic(); graphic.getStyleClass().add("fav-graphic"); favLabel.setGraphic(graphic); label.setGraphic(favLabel); label.setContentDisplay(ContentDisplay.RIGHT); pseudoClassStateChanged(PSEUDO_CLASS_COLORED, session.isDecorated()); } private void initializeStartLabel() { if (startDateLabel == null) { startDateLabel = new Label(); startDateLabel.getStyleClass().add("extra-text"); } } private String convertSpeakersToString(List<TalkSpeaker> speakers) { if (speakers.size() > 0) { StringBuilder speakerTitle = new StringBuilder(); for (int index = 0; index < speakers.size(); index++) { if (index < speakers.size() - 1) { speakerTitle.append(speakers.get(index).getName()).append(", "); } else { speakerTitle.append(speakers.get(index).getName()); } } return speakerTitle.toString(); } return ""; } private PseudoClass fetchPseudoClassForTrack(String trackId) { PseudoClass pseudoClass = trackPseudoClassMap.get(trackId); if (pseudoClass == null) { if (index > pseudoClasses.size() - 1) { index = 0; // exhausted all colors, re-use } pseudoClass = PseudoClass.getPseudoClass(pseudoClasses.get(index++)); trackPseudoClassMap.put(trackId, pseudoClass); } return pseudoClass; } private void changePseudoClass(PseudoClass pseudoClass) { pseudoClassStateChanged(oldPseudoClass, false); pseudoClassStateChanged(pseudoClass, true); oldPseudoClass = pseudoClass; } private class SecondaryGraphic extends Pane { private final Node chevron; private StackPane indicator; private Session currentSession; public SecondaryGraphic() { chevron = MaterialDesignIcon.CHEVRON_RIGHT.graphic(); indicator = createIndicator(SessionVisuals.SessionListType.SCHEDULED, true); getChildren().addAll(chevron, indicator); InvalidationListener il = (Observable observable) -> { if (currentSession != null) { updateGraphic(currentSession); } }; if (service.isAuthenticated()) { service.retrieveScheduledSessions().addListener(il); service.retrieveFavoredSessions().addListener(il); } } @Override protected void layoutChildren() { final double w = getWidth(); final double h = getHeight(); double indicatorWidth = indicator.prefWidth(-1); double indicatorHeight = indicator.prefHeight(-1); indicator.resizeRelocate(w - indicatorWidth, 0, indicatorWidth, indicatorHeight); double chevronWidth = chevron.prefWidth(-1); double chevronHeight = chevron.prefHeight(-1); chevron.resizeRelocate(0, h / 2.0 - chevronHeight / 2.0, chevronWidth, chevronHeight); } public void updateGraphic(Session session) { // FIXME this doesn't work as the retrieve* calls return empty lists on first call, resulting in graphics // not being shown. currentSession = session; final boolean authenticated = service.isAuthenticated(); if ( authenticated && service.retrieveScheduledSessions().contains(session)) { resetIndicator( indicator, SessionVisuals.SessionListType.SCHEDULED); indicator.setVisible(true); } else if ( authenticated && service.retrieveFavoredSessions().contains(session)) { resetIndicator( indicator, SessionVisuals.SessionListType.FAVORITES); indicator.setVisible(true); } else { indicator.setVisible(false); } } private void resetIndicator(StackPane indicator, SessionVisuals.SessionListType style) { if (!indicator.getStyleClass().contains(style.getStyleClass()) ) { final Node graphic = style.getOnGraphic(); StackPane.setAlignment(graphic, Pos.TOP_RIGHT); indicator.getChildren().set(0, graphic); indicator.getStyleClass().remove( style.other().getStyleClass()); indicator.getStyleClass().add( style.getStyleClass()); } } private StackPane createIndicator(SessionVisuals.SessionListType style, boolean topRight) { Node graphic = style.getOnGraphic(); StackPane node = new StackPane(graphic); StackPane.setAlignment(graphic, topRight ? Pos.TOP_RIGHT : Pos.BOTTOM_RIGHT); node.setVisible(false); node.getStyleClass().addAll("indicator", style.getStyleClass()); GridPane.setVgrow(node, Priority.ALWAYS); GridPane.setHalignment(node, HPos.RIGHT); return node; } } }
DevoxxClientMobile/src/main/java/com/devoxx/views/cell/ScheduleCell.java
/* * Copyright (c) 2016, 2018, Gluon Software * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.devoxx.views.cell; import com.devoxx.DevoxxView; import com.devoxx.model.Favorite; import com.devoxx.model.Session; import com.devoxx.model.TalkSpeaker; import com.devoxx.service.Service; import com.devoxx.util.DevoxxBundle; import com.devoxx.util.DevoxxSettings; import com.devoxx.views.SessionPresenter; import com.devoxx.views.helper.SessionVisuals; import com.gluonhq.charm.glisten.control.CharmListCell; import com.gluonhq.charm.glisten.control.ListTile; import com.gluonhq.charm.glisten.visual.MaterialDesignIcon; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.css.PseudoClass; import javafx.geometry.HPos; import javafx.geometry.Pos; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.Priority; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; public class ScheduleCell extends CharmListCell<Session> { private static final PseudoClass PSEUDO_CLASS_COLORED = PseudoClass.getPseudoClass("color"); private static Map<String, PseudoClass> trackPseudoClassMap = new HashMap<>(); private static List<String> pseudoClasses = Arrays.asList("track-color0", "track-color1", "track-color2", "track-color3", "track-color4", "track-color5", "track-color6", "track-color7", "track-color8", "track-color9" ); private static int index = 0; private final Service service; private final ListTile listTile; private final SecondaryGraphic secondaryGraphic; private final Label trackLabel; private Label startDateLabel; private Session session; private boolean showDate; private boolean showSessionType; private PseudoClass oldPseudoClass; public ScheduleCell(Service service) { this(service, false, false); } public ScheduleCell(Service service, boolean showDate, boolean showSessionType) { this.service = service; this.showDate = showDate; this.showSessionType = showSessionType; trackLabel = new Label(); secondaryGraphic = new SecondaryGraphic(); listTile = new ListTile(); listTile.setWrapText(true); listTile.setPrimaryGraphic(new Group(trackLabel)); listTile.setSecondaryGraphic(secondaryGraphic); setText(null); getStyleClass().add("schedule-cell"); } @Override public void updateItem(Session item, boolean empty) { super.updateItem(item, empty); session = item; if (item != null && !empty) { updateListTile(); secondaryGraphic.updateGraphic(session); if (showSessionType && item.isShowSessionType()) { final BorderPane borderPane = new BorderPane(listTile); final HBox sessionType = new HBox(new Label(item.getTalk().getTalkType())); sessionType.getStyleClass().add("session-type"); borderPane.setTop(sessionType); setGraphic(borderPane); } else { setGraphic(listTile); } // FIX for OTN-568 listTile.setOnMouseReleased(event -> { DevoxxView.SESSION.switchView().ifPresent(presenter -> ((SessionPresenter) presenter).showSession(session)); }); } else { setGraphic(null); } } private void updateListTile() { if (session.getTalk() != null) { if (session.getTalk().getTrack() != null) { final String trackId = session.getTalk().getTrackId().toUpperCase(); trackLabel.setText(trackId); changePseudoClass(fetchPseudoClassForTrack(trackId)); } if (session.getTalk().getTitle() != null) { listTile.setTextLine(0, session.getTalk().getTitle()); } List<TalkSpeaker> speakers = session.getTalk().getSpeakers(); listTile.setTextLine(1, convertSpeakersToString(speakers)); } listTile.setTextLine(2, DevoxxBundle.getString("OTN.SCHEDULE.IN_AT", session.getRoomName(), DevoxxSettings.TIME_FORMATTER.format(session.getStartDate()), DevoxxSettings.TIME_FORMATTER.format(session.getEndDate()))); if (showDate) { initializeStartLabel(); startDateLabel.setText(DevoxxSettings.DATE_FORMATTER.format(session.getStartDate())); // Hacky Code as it uses internals of ListTile ((VBox) listTile.getChildren().get(0)).getChildren().add(startDateLabel); } Optional<Favorite> favorite = Optional.empty(); for (Favorite fav : service.retrieveFavorites()) { if (fav.getId().equals(session.getTalk().getId())) { favorite = Optional.of(fav); break; } } Favorite fav = favorite.orElseGet(() -> { Favorite emptyFavorite = new Favorite(); emptyFavorite.setId(session.getTalk().getId()); service.retrieveFavorites().add(emptyFavorite); return emptyFavorite; }); // Hacky Code as it uses internals of ListTile final VBox vBox = (VBox) listTile.getChildren().get(0); Label label = (Label) vBox.getChildren().get(vBox.getChildren().size() - 1); Label favLabel = new Label(); favLabel.textProperty().bind(fav.favsProperty().asString()); favLabel.visibleProperty().bind(fav.favsProperty().greaterThanOrEqualTo(10)); favLabel.getStyleClass().add("fav-label"); Node graphic = MaterialDesignIcon.FAVORITE.graphic(); graphic.getStyleClass().add("fav-graphic"); favLabel.setGraphic(graphic); label.setGraphic(favLabel); label.setContentDisplay(ContentDisplay.RIGHT); pseudoClassStateChanged(PSEUDO_CLASS_COLORED, session.isDecorated()); } private void initializeStartLabel() { if (startDateLabel == null) { startDateLabel = new Label(); startDateLabel.getStyleClass().add("extra-text"); } } private String convertSpeakersToString(List<TalkSpeaker> speakers) { if (speakers.size() > 0) { StringBuilder speakerTitle = new StringBuilder(); for (int index = 0; index < speakers.size(); index++) { if (index < speakers.size() - 1) { speakerTitle.append(speakers.get(index).getName()).append(", "); } else { speakerTitle.append(speakers.get(index).getName()); } } return speakerTitle.toString(); } return ""; } private PseudoClass fetchPseudoClassForTrack(String trackId) { PseudoClass pseudoClass = trackPseudoClassMap.get(trackId); if (pseudoClass == null) { if (index > pseudoClasses.size() - 1) { index = 0; // exhausted all colors, re-use } pseudoClass = PseudoClass.getPseudoClass(pseudoClasses.get(index++)); trackPseudoClassMap.put(trackId, pseudoClass); } return pseudoClass; } private void changePseudoClass(PseudoClass pseudoClass) { pseudoClassStateChanged(oldPseudoClass, false); pseudoClassStateChanged(pseudoClass, true); oldPseudoClass = pseudoClass; } private class SecondaryGraphic extends Pane { private final Node chevron; private StackPane indicator; private Session currentSession; public SecondaryGraphic() { chevron = MaterialDesignIcon.CHEVRON_RIGHT.graphic(); indicator = createIndicator(SessionVisuals.SessionListType.SCHEDULED, true); getChildren().addAll(chevron, indicator); InvalidationListener il = (Observable observable) -> { if (currentSession != null) { updateGraphic(currentSession); } }; if (service.isAuthenticated()) { service.retrieveScheduledSessions().addListener(il); service.retrieveFavoredSessions().addListener(il); } } @Override protected void layoutChildren() { final double w = getWidth(); final double h = getHeight(); double indicatorWidth = indicator.prefWidth(-1); double indicatorHeight = indicator.prefHeight(-1); indicator.resizeRelocate(w - indicatorWidth, 0, indicatorWidth, indicatorHeight); double chevronWidth = chevron.prefWidth(-1); double chevronHeight = chevron.prefHeight(-1); chevron.resizeRelocate(0, h / 2.0 - chevronHeight / 2.0, chevronWidth, chevronHeight); } public void updateGraphic(Session session) { // FIXME this doesn't work as the retrieve* calls return empty lists on first call, resulting in graphics // not being shown. currentSession = session; final boolean authenticated = service.isAuthenticated(); if ( authenticated && service.retrieveScheduledSessions().contains(session)) { resetIndicator( indicator, SessionVisuals.SessionListType.SCHEDULED); indicator.setVisible(true); } else if ( authenticated && service.retrieveFavoredSessions().contains(session)) { resetIndicator( indicator, SessionVisuals.SessionListType.FAVORITES); indicator.setVisible(true); } else { indicator.setVisible(false); } } private void resetIndicator(StackPane indicator, SessionVisuals.SessionListType style) { if (!indicator.getStyleClass().contains(style.getStyleClass()) ) { final Node graphic = style.getOnGraphic(); StackPane.setAlignment(graphic, Pos.TOP_RIGHT); indicator.getChildren().set(0, graphic); indicator.getStyleClass().remove( style.other().getStyleClass()); indicator.getStyleClass().add( style.getStyleClass()); } } private StackPane createIndicator(SessionVisuals.SessionListType style, boolean topRight) { Node graphic = style.getOnGraphic(); StackPane node = new StackPane(graphic); StackPane.setAlignment(graphic, topRight ? Pos.TOP_RIGHT : Pos.BOTTOM_RIGHT); node.setVisible(false); node.getStyleClass().addAll("indicator", style.getStyleClass()); GridPane.setVgrow(node, Priority.ALWAYS); GridPane.setHalignment(node, HPos.RIGHT); return node; } } }
#68 Do not recreate nodes inside updateItem()
DevoxxClientMobile/src/main/java/com/devoxx/views/cell/ScheduleCell.java
#68 Do not recreate nodes inside updateItem()
<ide><path>evoxxClientMobile/src/main/java/com/devoxx/views/cell/ScheduleCell.java <ide> <ide> private final Service service; <ide> private final ListTile listTile; <add> private final BorderPane borderPane; <add> private final HBox sessionType; <add> private final Label sessionTypeLabel; <ide> private final SecondaryGraphic secondaryGraphic; <ide> private final Label trackLabel; <ide> private Label startDateLabel; <ide> listTile.setWrapText(true); <ide> listTile.setPrimaryGraphic(new Group(trackLabel)); <ide> listTile.setSecondaryGraphic(secondaryGraphic); <add> <add> sessionTypeLabel = new Label(); <add> sessionType = new HBox(sessionTypeLabel); <add> sessionType.getStyleClass().add("session-type"); <add> borderPane = new BorderPane(listTile); <ide> <ide> setText(null); <ide> getStyleClass().add("schedule-cell"); <ide> updateListTile(); <ide> secondaryGraphic.updateGraphic(session); <ide> if (showSessionType && item.isShowSessionType()) { <del> final BorderPane borderPane = new BorderPane(listTile); <del> final HBox sessionType = new HBox(new Label(item.getTalk().getTalkType())); <del> sessionType.getStyleClass().add("session-type"); <add> sessionTypeLabel.setText(item.getTalk().getTalkType()); <ide> borderPane.setTop(sessionType); <del> setGraphic(borderPane); <ide> } else { <del> setGraphic(listTile); <del> } <add> borderPane.setTop(null); <add> } <add> <add> setGraphic(borderPane); <ide> <ide> // FIX for OTN-568 <ide> listTile.setOnMouseReleased(event -> {
Java
apache-2.0
f1fd467f3be08810f24a77823520d64dbb4b09e8
0
signed/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,semonte/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,xfournet/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,holmes/intellij-community,izonder/intellij-community,ryano144/intellij-community,adedayo/intellij-community,apixandru/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,supersven/intellij-community,allotria/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,ibinti/intellij-community,hurricup/intellij-community,retomerz/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,Distrotech/intellij-community,consulo/consulo,akosyakov/intellij-community,ryano144/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,blademainer/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,ernestp/consulo,retomerz/intellij-community,caot/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,caot/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,semonte/intellij-community,fnouama/intellij-community,caot/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,caot/intellij-community,izonder/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,orekyuu/intellij-community,allotria/intellij-community,xfournet/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,samthor/intellij-community,vladmm/intellij-community,slisson/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,allotria/intellij-community,ahb0327/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,izonder/intellij-community,petteyg/intellij-community,supersven/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,kool79/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,slisson/intellij-community,da1z/intellij-community,da1z/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,semonte/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,da1z/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,caot/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,jagguli/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,supersven/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,signed/intellij-community,amith01994/intellij-community,jagguli/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,signed/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,izonder/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,semonte/intellij-community,izonder/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,retomerz/intellij-community,asedunov/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,caot/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,holmes/intellij-community,kdwink/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,ernestp/consulo,gnuhub/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,allotria/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,hurricup/intellij-community,amith01994/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,supersven/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,samthor/intellij-community,apixandru/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,ernestp/consulo,idea4bsd/idea4bsd,ol-loginov/intellij-community,robovm/robovm-studio,FHannes/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,allotria/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,caot/intellij-community,gnuhub/intellij-community,kool79/intellij-community,robovm/robovm-studio,dslomov/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,asedunov/intellij-community,amith01994/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,caot/intellij-community,diorcety/intellij-community,adedayo/intellij-community,samthor/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,signed/intellij-community,diorcety/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,amith01994/intellij-community,semonte/intellij-community,petteyg/intellij-community,signed/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,signed/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,retomerz/intellij-community,kool79/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,ahb0327/intellij-community,izonder/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,kdwink/intellij-community,apixandru/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,diorcety/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,consulo/consulo,adedayo/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,supersven/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,izonder/intellij-community,samthor/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,signed/intellij-community,jagguli/intellij-community,dslomov/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,slisson/intellij-community,jagguli/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,ernestp/consulo,youdonghai/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,robovm/robovm-studio,apixandru/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,ernestp/consulo,orekyuu/intellij-community,kool79/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,samthor/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,ibinti/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,supersven/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,da1z/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,izonder/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,ibinti/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,asedunov/intellij-community,FHannes/intellij-community,supersven/intellij-community,robovm/robovm-studio,adedayo/intellij-community,kool79/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,holmes/intellij-community,vladmm/intellij-community,adedayo/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,consulo/consulo,TangHao1987/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,fnouama/intellij-community,ryano144/intellij-community,holmes/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,robovm/robovm-studio,blademainer/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,signed/intellij-community,semonte/intellij-community,ryano144/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,blademainer/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,dslomov/intellij-community,robovm/robovm-studio,FHannes/intellij-community,fitermay/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,slisson/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,xfournet/intellij-community,hurricup/intellij-community,samthor/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,hurricup/intellij-community,apixandru/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,consulo/consulo,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,clumsy/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,amith01994/intellij-community,fnouama/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,FHannes/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,slisson/intellij-community,clumsy/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,da1z/intellij-community,clumsy/intellij-community,kdwink/intellij-community,signed/intellij-community,xfournet/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,kool79/intellij-community,blademainer/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,signed/intellij-community,fitermay/intellij-community,slisson/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,adedayo/intellij-community,blademainer/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,consulo/consulo,MER-GROUP/intellij-community,petteyg/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,ibinti/intellij-community,hurricup/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,izonder/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,kool79/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community
/* * Copyright 2000-2012 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.idea; import com.intellij.ide.plugins.PluginManager; import com.intellij.ide.startupWizard.StartupWizard; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.Consumer; import org.jetbrains.annotations.NonNls; import javax.swing.*; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; /** * @author yole */ public class StartupUtil { static boolean isHeadless; private static SocketLock ourLock; private static String myDefaultLAF; @NonNls public static final String NOSPLASH = "nosplash"; private StartupUtil() { } public static void setDefaultLAF(String laf) { myDefaultLAF = laf; } public static String getDefaultLAF() { return myDefaultLAF; } public static boolean shouldShowSplash(final String[] args) { return !Arrays.asList(args).contains(NOSPLASH); } public static boolean isHeadless() { return isHeadless; } private static void showError(final String title, final String message) { if (isHeadless()) { //noinspection UseOfSystemOutOrSystemErr System.out.println(message); } else { JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), message, title, JOptionPane.ERROR_MESSAGE); } } /** * Checks if the program can run under the JDK it was started with. */ private static boolean checkJdkVersion() { if (!"true".equals(System.getProperty("idea.no.jre.check"))) { try { // try to find a class from tools.jar Class.forName("com.sun.jdi.Field"); } catch (ClassNotFoundException e) { showError("Error", "'tools.jar' is not in " + ApplicationNamesInfo.getInstance().getProductName() + " classpath.\n" + "Please ensure JAVA_HOME points to JDK rather than JRE."); return false; } } if (!"true".equals(System.getProperty("idea.no.jdk.check"))) { final String version = System.getProperty("java.version"); if (!version.startsWith("1.6") && !version.startsWith("1.7")) { showError("Java Version Mismatch", "The JDK version is " + version + "\n." + ApplicationNamesInfo.getInstance().getProductName() + " requires JDK 1.6 or 1.7."); return false; } } return true; } private synchronized static boolean lockSystemFolders(String[] args) { if (ourLock == null) { ourLock = new SocketLock(); } SocketLock.ActivateStatus activateStatus = ourLock.lock(PathManager.getConfigPath(false), true, args); if (activateStatus == SocketLock.ActivateStatus.NO_INSTANCE) { activateStatus = ourLock.lock(PathManager.getSystemPath(), false); } if (activateStatus != SocketLock.ActivateStatus.NO_INSTANCE) { if (isHeadless() || activateStatus == SocketLock.ActivateStatus.CANNOT_ACTIVATE) { showError("Error", "Only one instance of " + ApplicationNamesInfo.getInstance().getFullProductName() + " can be run at a time."); } return false; } return true; } private static boolean checkTmpIsAccessible() { if (!SystemInfo.isUnix || SystemInfo.isMac) return true; final File tmpDir = new File(System.getProperty("java.io.tmpdir")); if (!tmpDir.isDirectory()) { showError("Inaccessible Temp Directory", "Temp directory '" + tmpDir + "' does not exist.\n" + "Please set 'java.io.tmpdir' system property to point to an existing directory."); return false; } final File tmp; try { //noinspection SSBasedInspection tmp = File.createTempFile("idea_tmp_check_", ".sh", tmpDir); FileUtil.writeToFile(tmp, "#!/bin/sh\n" + "exit 0"); } catch (IOException e) { showError("Inaccessible Temp Directory", e.getMessage() + " (" + tmpDir + ").\n" + "Temp directory is not accessible.\n" + "Please set 'java.io.tmpdir' system property to point to a writable directory."); return false; } String message = null; try { if (!tmp.setExecutable(true, true) && !tmp.canExecute()) { message = "Cannot make '" + tmp.getAbsolutePath() + "' executable."; } else { final int rv = new ProcessBuilder(tmp.getAbsolutePath()).start().waitFor(); if (rv != 0) { message = "Cannot execute '" + tmp.getAbsolutePath() + "': " + rv; } } } catch (Exception e) { message = e.getMessage(); } if (!tmp.delete()) { tmp.deleteOnExit(); } if (message != null) { showError("Inaccessible Temp Directory", message + ".\nPossible reason: temp directory is mounted with a 'noexec' option.\n" + "Please set 'java.io.tmpdir' system property to point to an accessible directory."); return false; } return true; } static boolean checkStartupPossible(String[] args) { return checkJdkVersion() && lockSystemFolders(args) && checkTmpIsAccessible(); } static void runStartupWizard() { final List<ApplicationInfoEx.PluginChooserPage> pages = ApplicationInfoImpl.getShadowInstance().getPluginChooserPages(); if (!pages.isEmpty()) { final StartupWizard startupWizard = new StartupWizard(pages); startupWizard.setCancelText("Skip"); startupWizard.show(); PluginManager.invalidatePlugins(); } } public synchronized static void addExternalInstanceListener(Consumer<List<String>> consumer) { ourLock.setActivateListener(consumer); } }
platform/platform-impl/src/com/intellij/idea/StartupUtil.java
/* * Copyright 2000-2012 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.idea; import com.intellij.ide.plugins.PluginManager; import com.intellij.ide.startupWizard.StartupWizard; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.Consumer; import org.jetbrains.annotations.NonNls; import javax.swing.*; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; /** * @author yole */ public class StartupUtil { static boolean isHeadless; private static SocketLock ourLock; private static String myDefaultLAF; @NonNls public static final String NOSPLASH = "nosplash"; private StartupUtil() { } public static void setDefaultLAF(String laf) { myDefaultLAF = laf; } public static String getDefaultLAF() { return myDefaultLAF; } public static boolean shouldShowSplash(final String[] args) { return !Arrays.asList(args).contains(NOSPLASH); } public static boolean isHeadless() { return isHeadless; } private static void showError(final String title, final String message) { if (isHeadless()) { //noinspection UseOfSystemOutOrSystemErr System.out.println(message); } else { JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), message, title, JOptionPane.ERROR_MESSAGE); } } /** * Checks if the program can run under the JDK it was started with. */ private static boolean checkJdkVersion() { if (!"true".equals(System.getProperty("idea.no.jre.check"))) { try { // try to find a class from tools.jar Class.forName("com.sun.jdi.Field"); } catch (ClassNotFoundException e) { showError("Error", "'tools.jar' is not in " + ApplicationNamesInfo.getInstance().getProductName() + " classpath.\n" + "Please ensure JAVA_HOME points to JDK rather than JRE."); return false; } } if (!"true".equals(System.getProperty("idea.no.jdk.check"))) { final String version = System.getProperty("java.version"); if (!version.startsWith("1.6") && !version.startsWith("1.7")) { showError("Java Version Mismatch", "The JDK version is " + version + "\n." + ApplicationNamesInfo.getInstance().getProductName() + " requires JDK 1.6 or 1.7."); return false; } } return true; } private synchronized static boolean lockSystemFolders(String[] args) { if (ourLock == null) { ourLock = new SocketLock(); } SocketLock.ActivateStatus activateStatus = ourLock.lock(PathManager.getConfigPath(false), true, args); if (activateStatus == SocketLock.ActivateStatus.NO_INSTANCE) { activateStatus = ourLock.lock(PathManager.getSystemPath(), false); } if (activateStatus != SocketLock.ActivateStatus.NO_INSTANCE) { if (isHeadless() || activateStatus == SocketLock.ActivateStatus.CANNOT_ACTIVATE) { showError("Error", "Only one instance of " + ApplicationNamesInfo.getInstance().getFullProductName() + " can be run at a time."); } return false; } return true; } private static boolean checkTmpIsAccessible() { if (!SystemInfo.isUnix || SystemInfo.isMac) return true; final File tmp; try { tmp = FileUtil.createTempFile("idea_check_", ".tmp"); FileUtil.writeToFile(tmp, "#!/bin/sh\n" + "exit 0"); } catch (IOException e) { showError("Inaccessible Temp Directory", e.getMessage() + " (" + FileUtil.getTempDirectory() + ").\n" + "Temp directory is not accessible.\n" + "Please set 'java.io.tmpdir' system property to point to a writable directory."); return false; } String message = null; try { if (!tmp.setExecutable(true, true) && !tmp.canExecute()) { message = "Cannot make '" + tmp.getAbsolutePath() + "' executable."; } else { final int rv = new ProcessBuilder(tmp.getAbsolutePath()).start().waitFor(); if (rv != 0) { message = "Cannot execute '" + tmp.getAbsolutePath() + "': " + rv; } } } catch (Exception e) { message = e.getMessage(); } if (!tmp.delete()) { tmp.deleteOnExit(); } if (message != null) { showError("Inaccessible Temp Directory", message + ".\nPossible reason: temp directory is mounted with a 'noexec' option.\n" + "Please set 'java.io.tmpdir' system property to point to an accessible directory."); return false; } return true; } static boolean checkStartupPossible(String[] args) { return checkJdkVersion() && lockSystemFolders(args) && checkTmpIsAccessible(); } static void runStartupWizard() { final List<ApplicationInfoEx.PluginChooserPage> pages = ApplicationInfoImpl.getShadowInstance().getPluginChooserPages(); if (!pages.isEmpty()) { final StartupWizard startupWizard = new StartupWizard(pages); startupWizard.setCancelText("Skip"); startupWizard.show(); PluginManager.invalidatePlugins(); } } public synchronized static void addExternalInstanceListener(Consumer<List<String>> consumer) { ourLock.setActivateListener(consumer); } }
EA-34150 (examine temp. dir on startup just like JNA)
platform/platform-impl/src/com/intellij/idea/StartupUtil.java
EA-34150 (examine temp. dir on startup just like JNA)
<ide><path>latform/platform-impl/src/com/intellij/idea/StartupUtil.java <ide> private static boolean checkTmpIsAccessible() { <ide> if (!SystemInfo.isUnix || SystemInfo.isMac) return true; <ide> <add> final File tmpDir = new File(System.getProperty("java.io.tmpdir")); <add> if (!tmpDir.isDirectory()) { <add> showError("Inaccessible Temp Directory", "Temp directory '" + tmpDir + "' does not exist.\n" + <add> "Please set 'java.io.tmpdir' system property to point to an existing directory."); <add> return false; <add> } <add> <ide> final File tmp; <ide> try { <del> tmp = FileUtil.createTempFile("idea_check_", ".tmp"); <add> //noinspection SSBasedInspection <add> tmp = File.createTempFile("idea_tmp_check_", ".sh", tmpDir); <ide> FileUtil.writeToFile(tmp, "#!/bin/sh\n" + <ide> "exit 0"); <ide> } <ide> catch (IOException e) { <del> showError("Inaccessible Temp Directory", e.getMessage() + " (" + FileUtil.getTempDirectory() + ").\n" + <add> showError("Inaccessible Temp Directory", e.getMessage() + " (" + tmpDir + ").\n" + <ide> "Temp directory is not accessible.\n" + <ide> "Please set 'java.io.tmpdir' system property to point to a writable directory."); <ide> return false;
Java
mit
33c8b24a8d35f46830070179751478f437d18ffa
0
JCThePants/NucleusFramework,JCThePants/NucleusFramework
/* This file is part of GenericsLib for Bukkit, licensed under the MIT License (MIT). * * Copyright (c) JCThePants (www.jcwhatever.com) * * 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.jcwhatever.bukkit.generic.regions; import com.jcwhatever.bukkit.generic.GenericsLib; import com.jcwhatever.bukkit.generic.collections.EntryCounter; import com.jcwhatever.bukkit.generic.collections.EntryCounter.RemovalPolicy; import com.jcwhatever.bukkit.generic.messaging.Messenger; import com.jcwhatever.bukkit.generic.performance.SingleCache; import com.jcwhatever.bukkit.generic.player.collections.PlayerMap; import com.jcwhatever.bukkit.generic.utils.PreCon; import com.jcwhatever.bukkit.generic.utils.Scheduler; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; /** * Global Region Manager */ public class RegionManager { // String key is chunk coordinates private final Map<String, Set<ReadOnlyRegion>> _listenerRegionsMap = new HashMap<>(500); private final Map<String, Set<ReadOnlyRegion>> _allRegionsMap = new HashMap<>(500); private final Object _sync = new Object(); private EntryCounter<World> _listenerWorlds = new EntryCounter<>(RemovalPolicy.REMOVE); private Map<UUID, Set<ReadOnlyRegion>> _playerMap; private Map<UUID, LinkedList<Location>> _playerLocationCache; private SingleCache<UUID, LinkedList<Location>> _lastLocationCache = new SingleCache<>(); private Set<ReadOnlyRegion> _regions = new HashSet<>(500); /** * Constructor. Used by GenericsLib to initialize RegionEventManager. */ public RegionManager() { _playerMap = new PlayerMap<>(); _playerLocationCache = new PlayerMap<>(); PlayerWatcher _playerWatcher = new PlayerWatcher(); Scheduler.runTaskRepeat(GenericsLib.getPlugin(), 7, 7, _playerWatcher); } /** * Get number of regions registered. */ public int getRegionCount() { return _regions.size(); } /** * Get a set of regions that contain the specified location. * * @param location The location to check. */ public Set<ReadOnlyRegion> getRegions(Location location) { PreCon.notNull(location); return getRegion(location, _allRegionsMap); } /** * Get a set of regions that the specified location * is inside of and are player watchers/listeners. * * @param location The location to check. */ public Set<ReadOnlyRegion> getListenerRegions(Location location) { return getRegion(location, _listenerRegionsMap); } /** * Get all regions that intersect with the specified chunk. * * @param chunk The chunk to check. */ public Set<ReadOnlyRegion> getRegionsInChunk(Chunk chunk) { synchronized(_sync) { if (getRegionCount() == 0) return new HashSet<>(0); // TODO: Add Single Cache using chunk as key String key = getChunkKey(chunk.getWorld(), chunk.getX(), chunk.getZ()); Set<ReadOnlyRegion> regions = _allRegionsMap.get(key); if (regions == null) return new HashSet<>(0); _sync.notifyAll(); return new HashSet<>(regions); } } /** * Get all regions that player is currently in. * * @param p The player to check. */ public List<ReadOnlyRegion> getPlayerRegions(Player p) { PreCon.notNull(p); synchronized(_sync) { if (_playerMap == null) return new ArrayList<ReadOnlyRegion>(0); Set<ReadOnlyRegion> regions = _playerMap.get(p.getUniqueId()); if (regions == null) return new ArrayList<>(0); _sync.notifyAll(); return new ArrayList<>(regions); } } /** * Add a location that the player has moved to so it can be * cached and processed by the player watcher the next time it * runs. * * @param p The player. * @param location The location to cache. */ public void updatePlayerLocation(Player p, Location location) { PreCon.notNull(p); PreCon.notNull(location); if (!_listenerWorlds.contains(location.getWorld())) return; // ignore NPC's if (p.hasMetadata("NPC")) return; LinkedList<Location> locations = getPlayerLocations(p.getUniqueId()); locations.add(location); } /** * Causes a region to re-fire the onPlayerEnter event * if the player is already in it * . * @param p The player. * @param region The region. */ public void resetPlayerRegion(Player p, Region region) { PreCon.notNull(p); PreCon.notNull(region); synchronized(_sync) { if (_playerMap == null) return; Set<ReadOnlyRegion> regions = _playerMap.get(p.getUniqueId()); if (regions == null) return; regions.remove(new ReadOnlyRegion(region)); _sync.notifyAll(); } } /* * Get all regions contained in the specified location using * the supplied region map. */ private Set<ReadOnlyRegion> getRegion(Location location, Map<String, Set<ReadOnlyRegion>> map) { synchronized(_sync) { Set<ReadOnlyRegion> results = new HashSet<>(10); if (getRegionCount() == 0) return results; // calculate chunk location instead of getting it from chunk // to prevent asynchronous issues int chunkX = (int)Math.floor(location.getX() / 16); int chunkZ = (int)Math.floor(location.getZ() / 16); String key = getChunkKey(location.getWorld(), chunkX, chunkZ); Set<ReadOnlyRegion> regions = map.get(key); if (regions == null) return results; for (ReadOnlyRegion region : regions) { if (region.contains(location)) results.add(region); } _sync.notifyAll(); return results; } } /** * Register a region so it can be found in searches * and its events called if it is a player watcher. * * @param region The Region to register. */ void register(Region region) { PreCon.notNull(region); if (!region.isDefined()) { Messenger.debug(GenericsLib.getPlugin(), "Failed to register region '{0}' with RegionManager because it's coords are undefined.", region.getName()); return; } ReadOnlyRegion readOnlyRegion = new ReadOnlyRegion(region); _regions.add(readOnlyRegion); synchronized(_sync) { int xMax = region.getChunkX() + region.getChunkXWidth(); int zMax = region.getChunkZ() + region.getChunkZWidth(); boolean hasRegion = false; for (int x= region.getChunkX(); x < xMax; x++) { for (int z= region.getChunkZ(); z < zMax; z++) { //noinspection ConstantConditions String key = getChunkKey(region.getWorld(), x, z); if (region.isPlayerWatcher()) { addToMap(_listenerRegionsMap, key, readOnlyRegion); } else { hasRegion = removeFromMap(_listenerRegionsMap, key, readOnlyRegion); } addToMap(_allRegionsMap, key, readOnlyRegion); } } if (region.isPlayerWatcher()) { //noinspection ConstantConditions _listenerWorlds.add(region.getWorld()); } else if (hasRegion){ //noinspection ConstantConditions _listenerWorlds.subtract(region.getWorld()); } _sync.notifyAll(); } } /** * Unregister a region and its events completely. * * <p>Called when a region is disposed.</p> * * @param region The Region to unregister. */ void unregister(Region region) { PreCon.notNull(region); if (!region.isDefined()) return; ReadOnlyRegion readOnlyRegion = new ReadOnlyRegion(region); synchronized(_sync) { int xMax = region.getChunkX() + region.getChunkXWidth(); int zMax = region.getChunkZ() + region.getChunkZWidth(); for (int x= region.getChunkX(); x < xMax; x++) { for (int z= region.getChunkZ(); z < zMax; z++) { //noinspection ConstantConditions String key = getChunkKey(region.getWorld(), x, z); removeFromMap(_listenerRegionsMap, key, readOnlyRegion); removeFromMap(_allRegionsMap, key, readOnlyRegion); } } if (_regions.remove(readOnlyRegion) && region.isPlayerWatcher()) { //noinspection ConstantConditions _listenerWorlds.subtract(region.getWorld()); } _sync.notifyAll(); } } /* * Get the cached movement locations of a player that have not been processed * by the PlayerWatcher task yet. */ private LinkedList<Location> getPlayerLocations(UUID playerId) { if (_lastLocationCache.keyEquals(playerId)) { //noinspection ConstantConditions return _lastLocationCache.getValue(); } LinkedList<Location> locations = _playerLocationCache.get(playerId); if (locations == null) { locations = new LinkedList<Location>(); _playerLocationCache.put(playerId, locations); } _lastLocationCache.set(playerId, locations); return locations; } /* * Clear cached movement locations of a player */ private void clearPlayerLocations(UUID playerId) { LinkedList<Location> locations = getPlayerLocations(playerId); locations.clear(); } /* * Executes doPlayerLeave method in the specified region on the main thread. */ private void onPlayerLeave(final Region region, final Player p) { Scheduler.runTaskSync(GenericsLib.getPlugin(), new Runnable() { @Override public void run() { region.doPlayerLeave(p); } }); } /* * Executes doPlayerEnter method in the specified region on the main thread. */ private void onPlayerEnter(final Region region, final Player p) { Scheduler.runTaskSync(GenericsLib.getPlugin(), new Runnable() { @Override public void run() { region.doPlayerEnter(p); } }); } /* * Add a region to a region map. */ private void addToMap(Map<String, Set<ReadOnlyRegion>> map, String key, ReadOnlyRegion region) { Set<ReadOnlyRegion> regions = map.get(key); if (regions == null) { regions = new HashSet<>(10); map.put(key, regions); } regions.add(region); } /* * Remove a region from a region map. */ private boolean removeFromMap(Map<String, Set<ReadOnlyRegion>> map, String key, ReadOnlyRegion region) { Set<ReadOnlyRegion> regions = map.get(key); return regions != null && regions.remove(region); } /* * Get a regions chunk map key. */ private String getChunkKey(World world, int x, int z) { return world.getName() + '.' + String.valueOf(x) + '.' + String.valueOf(z); } /* * Repeating task that determines which regions need events fired. */ private final class PlayerWatcher implements Runnable { private boolean _isRunning = true; public void cancel() { _isRunning = false; } @Override public void run() { if (!_isRunning) return; List<World> worlds; synchronized (_sync) { worlds = new ArrayList<World>(_listenerWorlds.getTypesCounted()); } final List<WorldPlayers> worldPlayers = new ArrayList<WorldPlayers>(worlds.size()); for (World world : worlds) { if (world == null) continue; List<Player> players = world.getPlayers(); if (players == null || players.isEmpty()) continue; worldPlayers.add(new WorldPlayers(world, players)); } if (worldPlayers.isEmpty()) return; Scheduler.runTaskLaterAsync(GenericsLib.getPlugin(), 1, new Runnable() { @Override public void run() { for (WorldPlayers wp : worldPlayers) { synchronized (_sync) { // get players in world List<WorldPlayer> worldPlayers = wp.players; // iterate players for (WorldPlayer worldPlayer : worldPlayers) { UUID playerId = worldPlayer.player.getUniqueId(); // get regions the player is in (cached from previous check) Set<ReadOnlyRegion> cachedRegions = _playerMap.get(playerId); if (cachedRegions == null) { cachedRegions = new HashSet<>(10); _playerMap.put(playerId, cachedRegions); } // iterate cached locations while (!worldPlayer.locations.isEmpty()) { Location location = worldPlayer.locations.removeFirst(); // see which regions a player actually is in Set<ReadOnlyRegion> inRegions = getListenerRegions(location); // check for entered regions if (inRegions != null && !inRegions.isEmpty()) { for (ReadOnlyRegion region : inRegions) { if (!cachedRegions.contains(region)) { onPlayerEnter(region.getHandle(), worldPlayer.player); cachedRegions.add(region); } } } // check for regions player has left if (!cachedRegions.isEmpty()) { Iterator<ReadOnlyRegion> iterator = cachedRegions.iterator(); while(iterator.hasNext()) { ReadOnlyRegion region = iterator.next(); if (inRegions == null || !inRegions.contains(region)) { onPlayerLeave(region.getHandle(), worldPlayer.player); iterator.remove(); } } } } } // END for (Player _sync.notifyAll(); } // END synchronized } // END for (WorldPlayers } // END run() }); } } private class WorldPlayers { public final World world; public final List<WorldPlayer> players; public WorldPlayers (World world, List<Player> players) { this.world = world; List<WorldPlayer> worldPlayers = new ArrayList<WorldPlayer>(players.size()); for (Player p : players) { LinkedList<Location> locations = getPlayerLocations(p.getUniqueId()); if (locations.isEmpty()) continue; WorldPlayer worldPlayer = new WorldPlayer(p, new LinkedList<Location>(locations)); worldPlayers.add(worldPlayer); clearPlayerLocations(p.getUniqueId()); } this.players = worldPlayers; } } private static class WorldPlayer { public final Player player; public final LinkedList<Location> locations; public WorldPlayer(Player p, LinkedList<Location> locations) { this.player = p; this.locations = locations; } } }
src/com/jcwhatever/bukkit/generic/regions/RegionManager.java
/* This file is part of GenericsLib for Bukkit, licensed under the MIT License (MIT). * * Copyright (c) JCThePants (www.jcwhatever.com) * * 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.jcwhatever.bukkit.generic.regions; import com.jcwhatever.bukkit.generic.GenericsLib; import com.jcwhatever.bukkit.generic.collections.EntryCounter; import com.jcwhatever.bukkit.generic.collections.EntryCounter.RemovalPolicy; import com.jcwhatever.bukkit.generic.messaging.Messenger; import com.jcwhatever.bukkit.generic.performance.SingleCache; import com.jcwhatever.bukkit.generic.player.collections.PlayerMap; import com.jcwhatever.bukkit.generic.utils.PreCon; import com.jcwhatever.bukkit.generic.utils.Scheduler; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; /** * Global Region Manager */ public class RegionManager { // String key is chunk coordinates private final Map<String, Set<ReadOnlyRegion>> _listenerRegionsMap = new HashMap<>(500); private final Map<String, Set<ReadOnlyRegion>> _allRegionsMap = new HashMap<>(500); private final Object _sync = new Object(); private EntryCounter<World> _listenerWorlds = new EntryCounter<>(RemovalPolicy.REMOVE); private Map<UUID, Set<ReadOnlyRegion>> _playerMap; private Map<UUID, LinkedList<Location>> _playerLocationCache; private SingleCache<UUID, LinkedList<Location>> _lastLocationCache = new SingleCache<>(); private Set<ReadOnlyRegion> _regions = new HashSet<>(500); /** * Constructor. Used by GenericsLib to initialize RegionEventManager. */ public RegionManager() { _playerMap = new PlayerMap<>(); _playerLocationCache = new PlayerMap<>(); PlayerWatcher _playerWatcher = new PlayerWatcher(); Scheduler.runTaskRepeat(GenericsLib.getPlugin(), 7, 7, _playerWatcher); } /** * Get number of regions registered. */ public int getRegionCount() { return _regions.size(); } /** * Get a set of regions that contain the specified location. * * @param location The location to check. */ public Set<ReadOnlyRegion> getRegions(Location location) { PreCon.notNull(location); return getRegion(location, _allRegionsMap); } /** * Get a set of regions that the specified location * is inside of and are player watchers/listeners. * * @param location The location to check. */ public Set<ReadOnlyRegion> getListenerRegions(Location location) { return getRegion(location, _listenerRegionsMap); } /** * Get all regions that intersect with the specified chunk. * * @param chunk The chunk to check. */ public Set<ReadOnlyRegion> getRegionsInChunk(Chunk chunk) { synchronized(_sync) { if (getRegionCount() == 0) return new HashSet<>(0); // TODO: Add Single Cache using chunk as key String key = getChunkKey(chunk.getWorld(), chunk.getX(), chunk.getZ()); Set<ReadOnlyRegion> regions = _allRegionsMap.get(key); if (regions == null) return new HashSet<>(0); _sync.notifyAll(); return new HashSet<>(regions); } } /** * Get all regions that player is currently in. * * @param p The player to check. */ public List<ReadOnlyRegion> getPlayerRegions(Player p) { PreCon.notNull(p); synchronized(_sync) { if (_playerMap == null) return new ArrayList<ReadOnlyRegion>(0); Set<ReadOnlyRegion> regions = _playerMap.get(p.getUniqueId()); if (regions == null) return new ArrayList<>(0); _sync.notifyAll(); return new ArrayList<>(regions); } } /** * Add a location that the player has moved to so it can be * cached and processed by the player watcher the next time it * runs. * * @param p The player. * @param location The location to cache. */ public void updatePlayerLocation(Player p, Location location) { PreCon.notNull(p); PreCon.notNull(location); if (!_listenerWorlds.contains(location.getWorld())) return; // ignore NPC's if (p.hasMetadata("NPC")) return; LinkedList<Location> locations = getPlayerLocations(p.getUniqueId()); locations.add(location); } /** * Causes a region to re-fire the onPlayerEnter event * if the player is already in it * . * @param p The player. * @param region The region. */ public void resetPlayerRegion(Player p, Region region) { PreCon.notNull(p); PreCon.notNull(region); synchronized(_sync) { if (_playerMap == null) return; Set<ReadOnlyRegion> regions = _playerMap.get(p.getUniqueId()); if (regions == null) return; regions.remove(new ReadOnlyRegion(region)); _sync.notifyAll(); } } /* * Get all regions contained in the specified location using * the supplied region map. */ private Set<ReadOnlyRegion> getRegion(Location location, Map<String, Set<ReadOnlyRegion>> map) { synchronized(_sync) { Set<ReadOnlyRegion> results = new HashSet<>(10); if (getRegionCount() == 0) return results; // calculate chunk location instead of getting it from chunk // to prevent asynchronous issues int chunkX = (int)Math.floor(location.getX() / 16); int chunkZ = (int)Math.floor(location.getZ() / 16); String key = getChunkKey(location.getWorld(), chunkX, chunkZ); Set<ReadOnlyRegion> regions = map.get(key); if (regions == null) return results; for (ReadOnlyRegion region : regions) { if (region.contains(location)) results.add(region); } _sync.notifyAll(); return results; } } /** * Register a region so it can be found in searches * and its events called if it is a player watcher. * * @param region The Region to register. */ void register(Region region) { PreCon.notNull(region); if (!region.isDefined()) { Messenger.debug(GenericsLib.getPlugin(), "Failed to register region '{0}' with RegionManager because it's coords are undefined.", region.getName()); return; } ReadOnlyRegion readOnlyRegion = new ReadOnlyRegion(region); _regions.add(readOnlyRegion); synchronized(_sync) { int xMax = region.getChunkX() + region.getChunkXWidth(); int zMax = region.getChunkZ() + region.getChunkZWidth(); boolean hasRegion = false; for (int x= region.getChunkX(); x < xMax; x++) { for (int z= region.getChunkZ(); z < zMax; z++) { //noinspection ConstantConditions String key = getChunkKey(region.getWorld(), x, z); if (region.isPlayerWatcher()) { addToMap(_listenerRegionsMap, key, readOnlyRegion); } else { hasRegion = removeFromMap(_listenerRegionsMap, key, readOnlyRegion); } addToMap(_allRegionsMap, key, readOnlyRegion); } } if (region.isPlayerWatcher()) { //noinspection ConstantConditions _listenerWorlds.add(region.getWorld()); } else if (hasRegion){ //noinspection ConstantConditions _listenerWorlds.subtract(region.getWorld()); } _sync.notifyAll(); } } /** * Unregister a region and its events completely. * * <p>Called when a region is disposed.</p> * * @param region The Region to unregister. */ void unregister(Region region) { PreCon.notNull(region); if (!region.isDefined()) return; ReadOnlyRegion readOnlyRegion = new ReadOnlyRegion(region); synchronized(_sync) { int xMax = region.getChunkX() + region.getChunkXWidth(); int zMax = region.getChunkZ() + region.getChunkZWidth(); for (int x= region.getChunkX(); x < xMax; x++) { for (int z= region.getChunkZ(); z < zMax; z++) { //noinspection ConstantConditions String key = getChunkKey(region.getWorld(), x, z); removeFromMap(_listenerRegionsMap, key, readOnlyRegion); removeFromMap(_allRegionsMap, key, readOnlyRegion); } } if (_regions.remove(readOnlyRegion) && region.isPlayerWatcher()) { //noinspection ConstantConditions _listenerWorlds.subtract(region.getWorld()); } _sync.notifyAll(); } } /* * Get the cached movement locations of a player that have not been processed * by the PlayerWatcher task yet. */ private LinkedList<Location> getPlayerLocations(UUID playerId) { if (_lastLocationCache.keyEquals(playerId)) { //noinspection ConstantConditions return _lastLocationCache.getValue(); } LinkedList<Location> locations = _playerLocationCache.get(playerId); if (locations == null) { locations = new LinkedList<Location>(); _playerLocationCache.put(playerId, locations); } _lastLocationCache.set(playerId, locations); return locations; } /* * Clear cached movement locations of a player */ private void clearPlayerLocations(UUID playerId) { LinkedList<Location> locations = getPlayerLocations(playerId); locations.clear(); } /* * Executes doPlayerLeave method in the specified region on the main thread. */ private void onPlayerLeave(final Region region, final Player p) { Scheduler.runTaskSync(GenericsLib.getPlugin(), new Runnable() { @Override public void run() { region.doPlayerLeave(p); } }); } /* * Executes doPlayerEnter method in the specified region on the main thread. */ private void onPlayerEnter(final Region region, final Player p) { Scheduler.runTaskSync(GenericsLib.getPlugin(), new Runnable() { @Override public void run() { region.doPlayerEnter(p); } }); } /* * Add a region to a region map. */ private void addToMap(Map<String, Set<ReadOnlyRegion>> map, String key, ReadOnlyRegion region) { Set<ReadOnlyRegion> regions = map.get(key); if (regions == null) { regions = new HashSet<>(10); map.put(key, regions); } regions.add(region); } /* * Remove a region from a region map. */ private boolean removeFromMap(Map<String, Set<ReadOnlyRegion>> map, String key, ReadOnlyRegion region) { Set<ReadOnlyRegion> regions = map.get(key); return regions != null && regions.remove(region); } /* * Get a regions chunk map key. */ private String getChunkKey(World world, int x, int z) { return world.getName() + '.' + String.valueOf(x) + '.' + String.valueOf(z); } /* * Repeating task that determines which regions need events fired. */ private final class PlayerWatcher implements Runnable { private boolean _isRunning = true; public void cancel() { _isRunning = false; } @Override public void run() { if (!_isRunning) return; List<World> worlds; synchronized (_sync) { worlds = new ArrayList<World>(_listenerWorlds.getTypesCounted()); } final List<WorldPlayers> worldPlayers = new ArrayList<WorldPlayers>(worlds.size()); for (World world : worlds) { if (world == null) continue; List<Player> players = world.getPlayers(); if (players == null || players.isEmpty()) continue; worldPlayers.add(new WorldPlayers(world, players)); } if (worldPlayers.isEmpty()) return; Bukkit.getScheduler().runTaskAsynchronously(GenericsLib.getPlugin(), new Runnable() { @Override public void run() { for (WorldPlayers wp : worldPlayers) { synchronized (_sync) { // get players in world List<WorldPlayer> worldPlayers = wp.players; // iterate players for (WorldPlayer worldPlayer : worldPlayers) { UUID playerId = worldPlayer.player.getUniqueId(); // get regions the player is in (cached from previous check) Set<ReadOnlyRegion> cachedRegions = _playerMap.get(playerId); if (cachedRegions == null) { cachedRegions = new HashSet<>(10); _playerMap.put(playerId, cachedRegions); } // iterate cached locations while (!worldPlayer.locations.isEmpty()) { Location location = worldPlayer.locations.removeFirst(); // see which regions a player actually is in Set<ReadOnlyRegion> inRegions = getListenerRegions(location); // check for entered regions if (inRegions != null && !inRegions.isEmpty()) { for (ReadOnlyRegion region : inRegions) { if (!cachedRegions.contains(region)) { onPlayerEnter(region.getHandle(), worldPlayer.player); cachedRegions.add(region); } } } // check for regions player has left if (!cachedRegions.isEmpty()) { Iterator<ReadOnlyRegion> iterator = cachedRegions.iterator(); while(iterator.hasNext()) { ReadOnlyRegion region = iterator.next(); if (inRegions == null || !inRegions.contains(region)) { onPlayerLeave(region.getHandle(), worldPlayer.player); iterator.remove(); } } } } } // END for (Player _sync.notifyAll(); } // END synchronized } // END for (WorldPlayers } // END run() }); } } private class WorldPlayers { public final World world; public final List<WorldPlayer> players; public WorldPlayers (World world, List<Player> players) { this.world = world; List<WorldPlayer> worldPlayers = new ArrayList<WorldPlayer>(players.size()); for (Player p : players) { LinkedList<Location> locations = getPlayerLocations(p.getUniqueId()); if (locations.isEmpty()) continue; WorldPlayer worldPlayer = new WorldPlayer(p, new LinkedList<Location>(locations)); worldPlayers.add(worldPlayer); clearPlayerLocations(p.getUniqueId()); } this.players = worldPlayers; } } private static class WorldPlayer { public final Player player; public final LinkedList<Location> locations; public WorldPlayer(Player p, LinkedList<Location> locations) { this.player = p; this.locations = locations; } } }
remove bukkit scheduler
src/com/jcwhatever/bukkit/generic/regions/RegionManager.java
remove bukkit scheduler
<ide><path>rc/com/jcwhatever/bukkit/generic/regions/RegionManager.java <ide> import com.jcwhatever.bukkit.generic.player.collections.PlayerMap; <ide> import com.jcwhatever.bukkit.generic.utils.PreCon; <ide> import com.jcwhatever.bukkit.generic.utils.Scheduler; <del>import org.bukkit.Bukkit; <ide> import org.bukkit.Chunk; <ide> import org.bukkit.Location; <ide> import org.bukkit.World; <ide> if (worldPlayers.isEmpty()) <ide> return; <ide> <del> Bukkit.getScheduler().runTaskAsynchronously(GenericsLib.getPlugin(), new Runnable() { <add> Scheduler.runTaskLaterAsync(GenericsLib.getPlugin(), 1, new Runnable() { <ide> <ide> @Override <ide> public void run() {
Java
apache-2.0
d4301e17335e9a2fe54dfc4cc254c60a90030c11
0
GoogleCloudPlatform/grpc-gcp-java,GoogleCloudPlatform/grpc-gcp-java
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.grpc; import static com.google.cloud.grpc.GcpMultiEndpointChannel.ME_KEY; import static com.google.cloud.spanner.SpannerOptions.CALL_CONTEXT_CONFIGURATOR_KEY; import static com.google.common.base.Preconditions.checkState; import static com.google.common.truth.Truth.assertThat; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import com.google.api.client.util.Sleeper; import com.google.api.core.ApiFunction; import com.google.api.gax.grpc.GrpcCallContext; import com.google.api.gax.grpc.GrpcTransportChannel; import com.google.api.gax.longrunning.OperationFuture; import com.google.api.gax.rpc.ApiCallContext; import com.google.api.gax.rpc.FixedTransportChannelProvider; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.grpc.GcpManagedChannel.ChannelRef; import com.google.cloud.grpc.GcpManagedChannelOptions.GcpChannelPoolOptions; import com.google.cloud.grpc.GcpManagedChannelOptions.GcpMetricsOptions; import com.google.cloud.grpc.MetricRegistryTestUtils.FakeMetricRegistry; import com.google.cloud.grpc.MetricRegistryTestUtils.MetricsRecord; import com.google.cloud.grpc.MetricRegistryTestUtils.PointWithFunction; import com.google.cloud.grpc.proto.ApiConfig; import com.google.cloud.spanner.Database; import com.google.cloud.spanner.DatabaseAdminClient; import com.google.cloud.spanner.DatabaseClient; import com.google.cloud.spanner.DatabaseId; import com.google.cloud.spanner.Instance; import com.google.cloud.spanner.InstanceAdminClient; import com.google.cloud.spanner.InstanceConfig; import com.google.cloud.spanner.InstanceConfigId; import com.google.cloud.spanner.InstanceId; import com.google.cloud.spanner.InstanceInfo; import com.google.cloud.spanner.KeySet; import com.google.cloud.spanner.Mutation; import com.google.cloud.spanner.Spanner; import com.google.cloud.spanner.SpannerExceptionFactory; import com.google.cloud.spanner.SpannerOptions; import com.google.cloud.spanner.SpannerOptions.CallContextConfigurator; import com.google.common.collect.Iterators; import com.google.common.util.concurrent.ListenableFuture; import com.google.protobuf.Empty; import com.google.protobuf.util.JsonFormat; import com.google.protobuf.util.JsonFormat.Parser; import com.google.spanner.admin.database.v1.CreateDatabaseMetadata; import com.google.spanner.admin.instance.v1.CreateInstanceMetadata; import com.google.spanner.v1.BatchCreateSessionsRequest; import com.google.spanner.v1.BatchCreateSessionsResponse; import com.google.spanner.v1.CreateSessionRequest; import com.google.spanner.v1.DeleteSessionRequest; import com.google.spanner.v1.ExecuteBatchDmlRequest; import com.google.spanner.v1.ExecuteBatchDmlRequest.Statement; import com.google.spanner.v1.ExecuteBatchDmlResponse; import com.google.spanner.v1.ExecuteSqlRequest; import com.google.spanner.v1.GetSessionRequest; import com.google.spanner.v1.ListSessionsRequest; import com.google.spanner.v1.ListSessionsResponse; import com.google.spanner.v1.PartialResultSet; import com.google.spanner.v1.PartitionQueryRequest; import com.google.spanner.v1.PartitionResponse; import com.google.spanner.v1.ResultSet; import com.google.spanner.v1.Session; import com.google.spanner.v1.SpannerGrpc; import com.google.spanner.v1.SpannerGrpc.SpannerBlockingStub; import com.google.spanner.v1.SpannerGrpc.SpannerFutureStub; import com.google.spanner.v1.SpannerGrpc.SpannerStub; import com.google.spanner.v1.TransactionOptions; import com.google.spanner.v1.TransactionOptions.ReadOnly; import com.google.spanner.v1.TransactionOptions.ReadWrite; import com.google.spanner.v1.TransactionSelector; import io.grpc.CallOptions; import io.grpc.ConnectivityState; import io.grpc.Context; import io.grpc.ManagedChannelBuilder; import io.grpc.MethodDescriptor; import io.grpc.StatusRuntimeException; import io.grpc.auth.MoreCallCredentials; import io.grpc.stub.StreamObserver; import io.opencensus.metrics.LabelValue; import java.io.File; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.junit.After; import org.junit.AfterClass; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Integration tests for GcpManagedChannel with Spanner. */ @RunWith(JUnit4.class) public final class SpannerIntegrationTest { private static final Logger testLogger = Logger.getLogger(GcpManagedChannel.class.getName()); private final List<LogRecord> logRecords = new LinkedList<>(); private static final String GCP_PROJECT_ID = System.getenv("GCP_PROJECT_ID"); private static final String INSTANCE_ID = "grpc-gcp-test-instance"; private static final String DB_NAME = "grpc-gcp-test-db"; private static final String SPANNER_TARGET = "spanner.googleapis.com"; private static final String USERNAME = "test_user"; private static final String DATABASE_PATH = String.format("projects/%s/instances/%s/databases/%s", GCP_PROJECT_ID, INSTANCE_ID, DB_NAME); private static final String API_FILE = "spannertest.json"; private static final int MAX_CHANNEL = 3; private static final int MAX_STREAM = 2; private static final ManagedChannelBuilder<?> builder = ManagedChannelBuilder.forAddress(SPANNER_TARGET, 443); private GcpManagedChannel gcpChannel; private GcpManagedChannel gcpChannelBRR; private void sleep(long millis) throws InterruptedException { Sleeper.DEFAULT.sleep(millis); } @BeforeClass public static void beforeClass() { Assume.assumeTrue( "Need to provide GCP_PROJECT_ID for SpannerIntegrationTest", GCP_PROJECT_ID != null); SpannerOptions options = SpannerOptions.newBuilder().setProjectId(GCP_PROJECT_ID).build(); try (Spanner spanner = options.getService()) { InstanceAdminClient instanceAdminClient = spanner.getInstanceAdminClient(); InstanceId instanceId = InstanceId.of(GCP_PROJECT_ID, INSTANCE_ID); initializeInstance(instanceAdminClient, instanceId); DatabaseAdminClient databaseAdminClient = spanner.getDatabaseAdminClient(); DatabaseId databaseId = DatabaseId.of(instanceId, DB_NAME); initializeDatabase(databaseAdminClient, databaseId); DatabaseClient databaseClient = spanner.getDatabaseClient(databaseId); initializeTable(databaseClient); } } private String lastLogMessage() { return lastLogMessage(1); } private String lastLogMessage(int nthFromLast) { return logRecords.get(logRecords.size() - nthFromLast).getMessage(); } private Level lastLogLevel() { return logRecords.get(logRecords.size() - 1).getLevel(); } private final Handler testLogHandler = new Handler() { @Override public synchronized void publish(LogRecord record) { logRecords.add(record); } @Override public void flush() {} @Override public void close() throws SecurityException {} }; private static void initializeTable(DatabaseClient databaseClient) { List<Mutation> mutations = Arrays.asList( Mutation.newInsertBuilder("Users") .set("UserId") .to(1) .set("UserName") .to(USERNAME) .build()); databaseClient.write(mutations); } private static void initializeInstance( InstanceAdminClient instanceAdminClient, InstanceId instanceId) { InstanceConfig instanceConfig = Iterators.get(instanceAdminClient.listInstanceConfigs().iterateAll().iterator(), 0, null); checkState(instanceConfig != null, "No instance configs found"); InstanceConfigId configId = instanceConfig.getId(); InstanceInfo instance = InstanceInfo.newBuilder(instanceId) .setNodeCount(1) .setDisplayName("grpc-gcp test instance") .setInstanceConfigId(configId) .build(); OperationFuture<Instance, CreateInstanceMetadata> op = instanceAdminClient.createInstance(instance); try { op.get(); } catch (Exception e) { throw SpannerExceptionFactory.newSpannerException(e); } } private static void initializeDatabase( DatabaseAdminClient databaseAdminClient, DatabaseId databaseId) { OperationFuture<Database, CreateDatabaseMetadata> op = databaseAdminClient.createDatabase( databaseId.getInstanceId().getInstance(), databaseId.getDatabase(), Arrays.asList( "CREATE TABLE Users (" + " UserId INT64 NOT NULL," + " UserName STRING(1024)" + ") PRIMARY KEY (UserId)")); try { op.get(); } catch (Exception e) { throw SpannerExceptionFactory.newSpannerException(e); } } @AfterClass public static void afterClass() { SpannerOptions options = SpannerOptions.newBuilder().setProjectId(GCP_PROJECT_ID).build(); try (Spanner spanner = options.getService()) { InstanceAdminClient instanceAdminClient = spanner.getInstanceAdminClient(); InstanceId instanceId = InstanceId.of(GCP_PROJECT_ID, INSTANCE_ID); cleanUpInstance(instanceAdminClient, instanceId); } } private static void cleanUpInstance( InstanceAdminClient instanceAdminClient, InstanceId instanceId) { instanceAdminClient.deleteInstance(instanceId.getInstance()); } private static GoogleCredentials getCreds() { GoogleCredentials creds; try { creds = GoogleCredentials.getApplicationDefault(); } catch (Exception e) { return null; } return creds; } /** Helper functions for BlockingStub. */ private SpannerBlockingStub getSpannerBlockingStub() { GoogleCredentials creds = getCreds(); SpannerBlockingStub stub = SpannerGrpc.newBlockingStub(gcpChannel) .withCallCredentials(MoreCallCredentials.from(creds)); return stub; } private static void deleteSession(SpannerBlockingStub stub, Session session) { if (session != null) { stub.deleteSession(DeleteSessionRequest.newBuilder().setName(session.getName()).build()); } } /** Helper functions for Stub(async calls). */ private SpannerStub getSpannerStub() { GoogleCredentials creds = getCreds(); SpannerStub stub = SpannerGrpc.newStub(gcpChannel).withCallCredentials(MoreCallCredentials.from(creds)); return stub; } /** A wrapper of checking the status of each channelRef in the gcpChannel. */ private void checkChannelRefs(int channels, int streams, int affinities) { checkChannelRefs(gcpChannel, channels, streams, affinities); } private void checkChannelRefs(GcpManagedChannel gcpChannel, int channels, int streams, int affinities) { assertEquals("Channel pool size mismatch.", channels, gcpChannel.channelRefs.size()); for (int i = 0; i < channels; i++) { assertEquals( String.format("Channel %d streams mismatch.", i), streams, gcpChannel.channelRefs.get(i).getActiveStreamsCount() ); assertEquals( String.format("Channel %d affinities mismatch.", i), affinities, gcpChannel.channelRefs.get(i).getAffinityCount() ); } } private void checkChannelRefs(int[] streams, int[] affinities) { for (int i = 0; i < streams.length; i++) { assertEquals( String.format("Channel %d streams mismatch.", i), streams[i], gcpChannel.channelRefs.get(i).getActiveStreamsCount() ); assertEquals( String.format("Channel %d affinities mismatch.", i), affinities[i], gcpChannel.channelRefs.get(i).getAffinityCount() ); } } private List<String> createAsyncSessions(SpannerStub stub) throws Exception { List<AsyncResponseObserver<Session>> resps = new ArrayList<>(); List<String> respNames = new ArrayList<>(); // Check the state of the channel first. assertEquals(ConnectivityState.IDLE, gcpChannel.getState(false)); // Check CreateSession with multiple channels and streams, CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); for (int i = 0; i < MAX_CHANNEL * MAX_STREAM; i++) { AsyncResponseObserver<Session> resp = new AsyncResponseObserver<>(); stub.createSession(req, resp); resps.add(resp); } checkChannelRefs(MAX_CHANNEL, MAX_STREAM, 0); for (AsyncResponseObserver<Session> resp : resps) { respNames.add(resp.get().getName()); } // Since createSession will bind the key, check the number of keys bound with channels. assertEquals(ConnectivityState.READY, gcpChannel.getState(false)); assertEquals(MAX_CHANNEL * MAX_STREAM, gcpChannel.affinityKeyToChannelRef.size()); checkChannelRefs(MAX_CHANNEL, 0, MAX_STREAM); return respNames; } private void deleteAsyncSessions(SpannerStub stub, List<String> respNames) throws Exception { assertEquals(ConnectivityState.READY, gcpChannel.getState(false)); for (String respName : respNames) { AsyncResponseObserver<Empty> resp = new AsyncResponseObserver<>(); stub.deleteSession(DeleteSessionRequest.newBuilder().setName(respName).build(), resp); // The ChannelRef which is bound with the current affinity key. ChannelRef currentChannel = gcpChannel.affinityKeyToChannelRef.get(respName); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); resp.get(); assertEquals(0, currentChannel.getActiveStreamsCount()); } checkChannelRefs(MAX_CHANNEL, 0, 0); assertEquals(0, gcpChannel.affinityKeyToChannelRef.size()); } /** Helper Functions for FutureStub. */ private SpannerFutureStub getSpannerFutureStub() { return getSpannerFutureStub(gcpChannel); } private SpannerFutureStub getSpannerFutureStub(GcpManagedChannel gcpChannel) { GoogleCredentials creds = getCreds(); return SpannerGrpc.newFutureStub(gcpChannel).withCallCredentials(MoreCallCredentials.from(creds)); } private List<String> createFutureSessions(SpannerFutureStub stub) throws Exception { List<ListenableFuture<Session>> futures = new ArrayList<>(); List<String> futureNames = new ArrayList<>(); assertEquals(ConnectivityState.IDLE, gcpChannel.getState(false)); // Check CreateSession with multiple channels and streams, CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); for (int i = 0; i < MAX_CHANNEL * MAX_STREAM; i++) { ListenableFuture<Session> future = stub.createSession(req); futures.add(future); } checkChannelRefs(MAX_CHANNEL, MAX_STREAM, 0); for (ListenableFuture<Session> future : futures) { futureNames.add(future.get().getName()); } // Since createSession will bind the key, check the number of keys bound with channels. assertEquals(ConnectivityState.READY, gcpChannel.getState(false)); assertEquals(MAX_CHANNEL * MAX_STREAM, gcpChannel.affinityKeyToChannelRef.size()); checkChannelRefs(MAX_CHANNEL, 0, MAX_STREAM); return futureNames; } private void deleteFutureSessions(SpannerFutureStub stub, List<String> futureNames) throws Exception { assertEquals(ConnectivityState.READY, gcpChannel.getState(false)); for (String futureName : futureNames) { ListenableFuture<Empty> future = stub.deleteSession(DeleteSessionRequest.newBuilder().setName(futureName).build()); // The ChannelRef which is bound with the current affinity key. ChannelRef currentChannel = gcpChannel.affinityKeyToChannelRef.get(futureName); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); future.get(); assertEquals(0, currentChannel.getActiveStreamsCount()); } checkChannelRefs(MAX_CHANNEL, 0, 0); assertEquals(0, gcpChannel.affinityKeyToChannelRef.size()); } @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void setupChannels() { testLogger.addHandler(testLogHandler); File configFile = new File(SpannerIntegrationTest.class.getClassLoader().getResource(API_FILE).getFile()); gcpChannel = (GcpManagedChannel) GcpManagedChannelBuilder.forDelegateBuilder(builder) .withApiConfigJsonFile(configFile) .build(); gcpChannelBRR = (GcpManagedChannel) GcpManagedChannelBuilder.forDelegateBuilder(builder) .withApiConfigJsonFile(configFile) .withOptions(GcpManagedChannelOptions.newBuilder() .withChannelPoolOptions( GcpChannelPoolOptions.newBuilder() .setMaxSize(MAX_CHANNEL) .setConcurrentStreamsLowWatermark(MAX_STREAM) .setUseRoundRobinOnBind(true) .build()) .build()) .build(); } @After public void shutdownChannels() { testLogger.removeHandler(testLogHandler); testLogger.setLevel(Level.INFO); logRecords.clear(); gcpChannel.shutdownNow(); gcpChannelBRR.shutdownNow(); } private long getOkCallsCount( FakeMetricRegistry fakeRegistry, String endpoint) { MetricsRecord record = fakeRegistry.pollRecord(); List<PointWithFunction<?>> metric = record.getMetrics().get(GcpMetricsConstants.METRIC_NUM_CALLS_COMPLETED); for (PointWithFunction<?> m : metric) { assertThat(m.keys().get(0).getKey()).isEqualTo("result"); assertThat(m.keys().get(1).getKey()).isEqualTo("endpoint"); if (!m.values().get(0).equals(LabelValue.create(GcpMetricsConstants.RESULT_SUCCESS))) { continue; } if (!m.values().get(1).equals(LabelValue.create(endpoint))) { continue; } return m.value(); } fail("Success calls metric is not found for endpoint: " + endpoint); return 0; } private ApiConfig getApiConfig() throws IOException { File configFile = new File(SpannerIntegrationTest.class.getClassLoader().getResource(API_FILE).getFile()); Parser parser = JsonFormat.parser(); ApiConfig.Builder apiConfigBuilder = ApiConfig.newBuilder(); Reader reader = Files.newBufferedReader(configFile.toPath(), UTF_8); parser.merge(reader, apiConfigBuilder); return apiConfigBuilder.build(); } // For this test we'll create a Spanner client with gRPC-GCP MultiEndpoint feature. // // Imagine we have a multi-region Spanner instance with leader in the us-east4 and follower in the // us-east1 regions. // // We will provide two MultiEndpoint configs: "leader" (having leader region endpoint first and // follower second) and "follower" (having follower region endpoint first and leader second). // // Then we'll make sure the Spanner client uses leader MultiEndpoint as a default one and creates // its sessions there. Then we'll make sure a read request will also use the leader MultiEndpoint // by default. // // Then we'll verify we can use the follower MultiEndpoint when needed by specifying that in // the Spanner context. // // Then we'll update MultiEndpoints configuration by replacing the leader endpoint and renaming // the follower MultiEndpoint. And make sure the new leader endpoint and the previous follower // endpoint are still working as expected when using different MultiEndpoints. @Test public void testSpannerMultiEndpointClient() throws IOException, InterruptedException { // Watch debug messages. testLogger.setLevel(Level.FINEST); final FakeMetricRegistry fakeRegistry = new FakeMetricRegistry(); // Leader-first multi-endpoint endpoints. final List<String> leaderEndpoints = new ArrayList<>(); // Follower-first multi-endpoint endpoints. final List<String> followerEndpoints = new ArrayList<>(); final String leaderEndpoint = "us-east4.googleapis.com:443"; final String followerEndpoint = "us-east1.googleapis.com:443"; leaderEndpoints.add(leaderEndpoint); leaderEndpoints.add(followerEndpoint); followerEndpoints.add(followerEndpoint); followerEndpoints.add(leaderEndpoint); ApiFunction<ManagedChannelBuilder<?>, ManagedChannelBuilder<?>> configurator = input -> input.overrideAuthority(SPANNER_TARGET); GcpMultiEndpointOptions leaderOpts = GcpMultiEndpointOptions.newBuilder(leaderEndpoints) .withName("leader") .withChannelConfigurator(configurator) .withRecoveryTimeout(Duration.ofSeconds(3)) .build(); GcpMultiEndpointOptions followerOpts = GcpMultiEndpointOptions.newBuilder(followerEndpoints) .withName("follower") .withChannelConfigurator(configurator) .withRecoveryTimeout(Duration.ofSeconds(3)) .build(); List<GcpMultiEndpointOptions> opts = new ArrayList<>(); opts.add(leaderOpts); opts.add(followerOpts); GcpMultiEndpointChannel gcpMultiEndpointChannel = new GcpMultiEndpointChannel( opts, getApiConfig(), GcpManagedChannelOptions.newBuilder() .withChannelPoolOptions(GcpChannelPoolOptions.newBuilder() .setConcurrentStreamsLowWatermark(0) .setMaxSize(3) .build()) .withMetricsOptions(GcpMetricsOptions.newBuilder() .withMetricRegistry(fakeRegistry) .build()) .build()); final int currentIndex = GcpManagedChannel.channelPoolIndex.get(); final String followerPoolIndex = String.format("pool-%d", currentIndex); final String leaderPoolIndex = String.format("pool-%d", currentIndex - 1); // Make sure authorities are overridden by channel configurator. assertThat(gcpMultiEndpointChannel.authority()).isEqualTo(SPANNER_TARGET); assertThat(gcpMultiEndpointChannel.authorityFor("leader")) .isEqualTo(SPANNER_TARGET); assertThat(gcpMultiEndpointChannel.authorityFor("follower")) .isEqualTo(SPANNER_TARGET); assertThat(gcpMultiEndpointChannel.authorityFor("no-such-name")).isNull(); sleep(1000); List<String> logMessages = logRecords.stream() .map(LogRecord::getMessage).collect(Collectors.toList()); // Make sure min channels are created and connections are established right away in both pools. for (String poolIndex : Arrays.asList(leaderPoolIndex, followerPoolIndex)) { for (int i = 0; i < 2; i++) { assertThat(logMessages).contains( poolIndex + ": Channel " + i + " state change detected: null -> IDLE"); assertThat(logMessages).contains( poolIndex + ": Channel " + i + " state change detected: IDLE -> CONNECTING"); } } // Make sure endpoint is set as a metric label for each pool. assertThat(logRecords.stream().filter(logRecord -> logRecord.getMessage().matches( leaderPoolIndex + ": Metrics options: \\{namePrefix: \"\", labels: \\[endpoint: " + "\"" + leaderEndpoint + "\"], metricRegistry: .*" )).count()).isEqualTo(1); assertThat(logRecords.stream().filter(logRecord -> logRecord.getMessage().matches( followerPoolIndex + ": Metrics options: \\{namePrefix: \"\", labels: \\[endpoint: " + "\"" + followerEndpoint + "\"], metricRegistry: .*" )).count()).isEqualTo(1); logRecords.clear(); TransportChannelProvider channelProvider = FixedTransportChannelProvider.create( GrpcTransportChannel.create(gcpMultiEndpointChannel)); SpannerOptions.Builder options = SpannerOptions.newBuilder().setProjectId(GCP_PROJECT_ID); options.setChannelProvider(channelProvider); // Match channel pool size. options.setNumChannels(3); Spanner spanner = options.build().getService(); InstanceId instanceId = InstanceId.of(GCP_PROJECT_ID, INSTANCE_ID); DatabaseId databaseId = DatabaseId.of(instanceId, DB_NAME); DatabaseClient databaseClient = spanner.getDatabaseClient(databaseId); Runnable readQuery = () -> { try (com.google.cloud.spanner.ResultSet read = databaseClient.singleUse() .read("Users", KeySet.all(), Arrays.asList("UserId", "UserName"))) { int readRows = 0; while (read.next()) { readRows++; assertEquals(USERNAME, read.getCurrentRowAsStruct().getString("UserName")); } assertEquals(1, readRows); } }; // Make sure leader endpoint is used by default. assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(0); readQuery.run(); // Wait for sessions creation requests to be completed but no more than 10 seconds. for (int i = 0; i < 20; i++) { sleep(500); if (getOkCallsCount(fakeRegistry, leaderEndpoint) == 4) { break; } } // 3 session creation requests + 1 our read request to the leader endpoint. assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(4); // Make sure there were 3 session creation requests in the leader pool only. assertThat(logRecords.stream().filter(logRecord -> logRecord.getMessage().matches( leaderPoolIndex + ": Binding \\d+ key\\(s\\) to channel \\d:.*" )).count()).isEqualTo(3); assertThat(logRecords.stream().filter(logRecord -> logRecord.getMessage().matches( followerPoolIndex + ": Binding \\d+ key\\(s\\) to channel \\d:.*" )).count()).isEqualTo(0); // Create context for using follower-first multi-endpoint. Function<String, Context> contextFor = meName -> Context.current() .withValue(CALL_CONTEXT_CONFIGURATOR_KEY, new CallContextConfigurator() { @Nullable @Override public <ReqT, RespT> ApiCallContext configure(ApiCallContext context, ReqT request, MethodDescriptor<ReqT, RespT> method) { return context.merge(GrpcCallContext.createDefault().withCallOptions( CallOptions.DEFAULT.withOption(ME_KEY, meName))); } }); assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(0); // Use follower, make sure it is used. contextFor.apply("follower").run(readQuery); assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(1); // Replace leader endpoints. final String newLeaderEndpoint = "us-west1.googleapis.com:443"; leaderEndpoints.clear(); leaderEndpoints.add(newLeaderEndpoint); leaderEndpoints.add(followerEndpoint); leaderOpts = GcpMultiEndpointOptions.newBuilder(leaderEndpoints) .withName("leader") .withChannelConfigurator(configurator) .build(); followerEndpoints.clear(); followerEndpoints.add(followerEndpoint); followerEndpoints.add(newLeaderEndpoint); // Rename follower MultiEndpoint. followerOpts = GcpMultiEndpointOptions.newBuilder(followerEndpoints) .withName("follower-2") .withChannelConfigurator(configurator) .build(); opts.clear(); opts.add(leaderOpts); opts.add(followerOpts); gcpMultiEndpointChannel.setMultiEndpoints(opts); // As it takes some time to connect to the new leader endpoint, RPC will fall back to the // follower until we connect to leader. assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(1); readQuery.run(); assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(2); sleep(500); // Make sure the new leader endpoint is used by default after it is connected. assertThat(getOkCallsCount(fakeRegistry, newLeaderEndpoint)).isEqualTo(0); readQuery.run(); assertThat(getOkCallsCount(fakeRegistry, newLeaderEndpoint)).isEqualTo(1); // Make sure that the follower endpoint still works if specified. assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(2); // Use follower, make sure it is used. contextFor.apply("follower-2").run(readQuery); assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(3); gcpMultiEndpointChannel.shutdown(); spanner.close(); } @Test public void testSpannerMultiEndpointClientWithDelay() throws IOException, InterruptedException { // Watch debug messages. testLogger.setLevel(Level.FINEST); final int poolSize = 3; final long switchingDelayMs = 500; final long marginMs = 50; final FakeMetricRegistry fakeRegistry = new FakeMetricRegistry(); // Leader-first multi-endpoint endpoints. final List<String> leaderEndpoints = new ArrayList<>(); // Follower-first multi-endpoint endpoints. final List<String> followerEndpoints = new ArrayList<>(); final String leaderEndpoint = "us-east4.googleapis.com:443"; final String followerEndpoint = "us-east1.googleapis.com:443"; leaderEndpoints.add(leaderEndpoint); leaderEndpoints.add(followerEndpoint); followerEndpoints.add(followerEndpoint); followerEndpoints.add(leaderEndpoint); ApiFunction<ManagedChannelBuilder<?>, ManagedChannelBuilder<?>> configurator = input -> input.overrideAuthority(SPANNER_TARGET); GcpMultiEndpointOptions leaderOpts = GcpMultiEndpointOptions.newBuilder(leaderEndpoints) .withName("leader") .withChannelConfigurator(configurator) .withRecoveryTimeout(Duration.ofSeconds(3)) .withSwitchingDelay(Duration.ofMillis(switchingDelayMs)) .build(); GcpMultiEndpointOptions followerOpts = GcpMultiEndpointOptions.newBuilder(followerEndpoints) .withName("follower") .withChannelConfigurator(configurator) .withRecoveryTimeout(Duration.ofSeconds(3)) .withSwitchingDelay(Duration.ofMillis(switchingDelayMs)) .build(); List<GcpMultiEndpointOptions> opts = new ArrayList<>(); opts.add(leaderOpts); opts.add(followerOpts); GcpMultiEndpointChannel gcpMultiEndpointChannel = new GcpMultiEndpointChannel( opts, getApiConfig(), GcpManagedChannelOptions.newBuilder() .withChannelPoolOptions(GcpChannelPoolOptions.newBuilder() .setConcurrentStreamsLowWatermark(0) .setMaxSize(poolSize) .build()) .withMetricsOptions(GcpMetricsOptions.newBuilder() .withMetricRegistry(fakeRegistry) .build()) .build()); final int currentIndex = GcpManagedChannel.channelPoolIndex.get(); final String followerPoolIndex = String.format("pool-%d", currentIndex); final String leaderPoolIndex = String.format("pool-%d", currentIndex - 1); TransportChannelProvider channelProvider = FixedTransportChannelProvider.create( GrpcTransportChannel.create(gcpMultiEndpointChannel)); SpannerOptions.Builder options = SpannerOptions.newBuilder().setProjectId(GCP_PROJECT_ID); options.setChannelProvider(channelProvider); // Match channel pool size. options.setNumChannels(poolSize); Spanner spanner = options.build().getService(); InstanceId instanceId = InstanceId.of(GCP_PROJECT_ID, INSTANCE_ID); DatabaseId databaseId = DatabaseId.of(instanceId, DB_NAME); DatabaseClient databaseClient = spanner.getDatabaseClient(databaseId); Runnable readQuery = () -> { try (com.google.cloud.spanner.ResultSet read = databaseClient.singleUse() .read("Users", KeySet.all(), Arrays.asList("UserId", "UserName"))) { int readRows = 0; while (read.next()) { readRows++; assertEquals(USERNAME, read.getCurrentRowAsStruct().getString("UserName")); } assertEquals(1, readRows); } }; // Make sure leader endpoint is used by default. assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(0); readQuery.run(); // Wait for sessions creation requests to be completed but no more than 10 seconds. for (int i = 0; i < 20; i++) { sleep(500); if (getOkCallsCount(fakeRegistry, leaderEndpoint) == 4) { break; } } // 3 session creation requests + 1 our read request to the leader endpoint. assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(4); // Change the endpoints in the leader endpoint. east4, east1 -> east1, east4. leaderOpts = GcpMultiEndpointOptions.newBuilder(followerEndpoints) .withName("leader") .withChannelConfigurator(configurator) .withRecoveryTimeout(Duration.ofSeconds(3)) .withSwitchingDelay(Duration.ofMillis(switchingDelayMs)) .build(); opts = new ArrayList<>(); opts.add(leaderOpts); opts.add(followerOpts); gcpMultiEndpointChannel.setMultiEndpoints(opts); // Because of the delay the leader MultiEndpoint should still use leader endpoint. sleep(switchingDelayMs - marginMs); readQuery.run(); assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(5); assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(0); // But after the delay, it should switch to the follower endpoint. sleep(2 * marginMs); readQuery.run(); assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(5); assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(1); // Remove leader endpoint from the leader multi-endpoint. east1, east4 -> east1. leaderOpts = GcpMultiEndpointOptions.newBuilder(Collections.singletonList(followerEndpoint)) .withName("leader") .withChannelConfigurator(configurator) .withRecoveryTimeout(Duration.ofSeconds(3)) .withSwitchingDelay(Duration.ofMillis(switchingDelayMs)) .build(); opts = new ArrayList<>(); opts.add(leaderOpts); opts.add(followerOpts); gcpMultiEndpointChannel.setMultiEndpoints(opts); // Bring the leader endpoint back. east1 -> east4, east1. leaderOpts = GcpMultiEndpointOptions.newBuilder(leaderEndpoints) .withName("leader") .withChannelConfigurator(configurator) .withRecoveryTimeout(Duration.ofSeconds(3)) .withSwitchingDelay(Duration.ofMillis(switchingDelayMs)) .build(); opts = new ArrayList<>(); opts.add(leaderOpts); opts.add(followerOpts); gcpMultiEndpointChannel.setMultiEndpoints(opts); // Because of the delay the leader MultiEndpoint should still use follower endpoint. sleep(switchingDelayMs - marginMs); readQuery.run(); assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(5); assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(2); // But after the delay, it should switch back to the leader endpoint. sleep(2 * marginMs); readQuery.run(); assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(6); assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(2); gcpMultiEndpointChannel.shutdown(); spanner.close(); } @Test public void testCreateAndGetSessionBlocking() { SpannerBlockingStub stub = getSpannerBlockingStub(); CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); // The first MAX_CHANNEL requests (without affinity) should be distributed 1 per channel. List<Session> sessions = new ArrayList<>(); for (int i = 0; i < MAX_CHANNEL; i++) { Session session = stub.createSession(req); assertThat(session).isNotEqualTo(null); sessions.add(session); Session responseGet = stub.getSession(GetSessionRequest.newBuilder().setName(session.getName()).build()); assertEquals(responseGet.getName(), session.getName()); } checkChannelRefs(MAX_CHANNEL, 0, 1); for (Session session : sessions) { deleteSession(stub, session); } checkChannelRefs(MAX_CHANNEL, 0, 0); } @Test public void testBatchCreateSessionsBlocking() { int sessionCount = 10; SpannerBlockingStub stub = getSpannerBlockingStub(); BatchCreateSessionsRequest req = BatchCreateSessionsRequest.newBuilder() .setDatabase(DATABASE_PATH) .setSessionCount(sessionCount) .build(); List<Session> sessions = new ArrayList<>(); // The first MAX_CHANNEL requests (without affinity) should be distributed 1 per channel. for (int j = 0; j < MAX_CHANNEL; j++) { BatchCreateSessionsResponse resp = stub.batchCreateSessions(req); assertThat(resp.getSessionCount()).isEqualTo(sessionCount); sessions.addAll(resp.getSessionList()); } checkChannelRefs(MAX_CHANNEL, 0, sessionCount); for (Session session : sessions) { deleteSession(stub, session); } checkChannelRefs(MAX_CHANNEL, 0, 0); } @Test public void testSessionsCreatedUsingRoundRobin() throws Exception { SpannerFutureStub stub = getSpannerFutureStub(gcpChannelBRR); List<ListenableFuture<Session>> futures = new ArrayList<>(); assertEquals(ConnectivityState.IDLE, gcpChannelBRR.getState(false)); // Should create one session per channel. CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); for (int i = 0; i < MAX_CHANNEL; i++) { ListenableFuture<Session> future = stub.createSession(req); futures.add(future); } // If round-robin in use as expected, then each channel should have 1 active stream with the CreateSession request. checkChannelRefs(gcpChannelBRR, MAX_CHANNEL, 1, 0); // Collecting futures results. String lastSession = ""; for (ListenableFuture<Session> future : futures) { lastSession = future.get().getName(); } // Since createSession will bind the key, check the number of keys bound with channels. // Each channel should have 1 affinity key. assertEquals(MAX_CHANNEL, gcpChannelBRR.affinityKeyToChannelRef.size()); checkChannelRefs(gcpChannelBRR, MAX_CHANNEL, 0, 1); // Create a different request with the lastSession created. ListenableFuture<ResultSet> responseFuture = stub.executeSql( ExecuteSqlRequest.newBuilder() .setSession(lastSession) .setSql("select * FROM Users") .build()); // The ChannelRef which is bound with the lastSession. ChannelRef currentChannel = gcpChannelBRR.affinityKeyToChannelRef.get(lastSession); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); // Create another 1 session per channel sequentially. // Without the round-robin it won't use the currentChannel as it has more active streams (1) than other channels. // But with round-robin each channel should get one create session request. for (int i = 0; i < MAX_CHANNEL; i++) { ListenableFuture<Session> future = stub.createSession(req); future.get(); } ResultSet response = responseFuture.get(); // If round-robin in use, then each channel should now have 2 active stream with the CreateSession request. checkChannelRefs(gcpChannelBRR, MAX_CHANNEL, 0, 2); } @Test public void testSessionsCreatedWithoutRoundRobin() throws Exception { // Watch debug messages. testLogger.setLevel(Level.FINEST); final int currentIndex = GcpManagedChannel.channelPoolIndex.get() - 1; final String poolIndex = String.format("pool-%d", currentIndex); SpannerFutureStub stub = getSpannerFutureStub(); List<ListenableFuture<Session>> futures = new ArrayList<>(); assertEquals(ConnectivityState.IDLE, gcpChannel.getState(false)); // Initial log messages count. int logCount = logRecords.size(); // Should create one session per channel. CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); for (int i = 0; i < MAX_CHANNEL; i++) { ListenableFuture<Session> future = stub.createSession(req); futures.add(future); assertThat(lastLogMessage(3)).isEqualTo( poolIndex + ": Channel " + i + " state change detected: null -> IDLE"); assertThat(lastLogMessage(2)).isEqualTo( poolIndex + ": Channel " + i + " created."); assertThat(lastLogMessage()).isEqualTo( poolIndex + ": Channel " + i + " picked for bind operation."); logCount += 3; assertThat(logRecords.size()).isEqualTo(logCount); assertThat(lastLogLevel()).isEqualTo(Level.FINEST); } // Each channel should have 1 active stream with the CreateSession request because we create them concurrently. checkChannelRefs(gcpChannel, MAX_CHANNEL, 1, 0); // Collecting futures results. String lastSession = ""; for (ListenableFuture<Session> future : futures) { lastSession = future.get().getName(); } // Since createSession will bind the key, check the number of keys bound with channels. // Each channel should have 1 affinity key. assertEquals(MAX_CHANNEL, gcpChannel.affinityKeyToChannelRef.size()); checkChannelRefs(MAX_CHANNEL, 0, 1); // Create a different request with the lastSession created. ListenableFuture<ResultSet> responseFuture = stub.executeSql( ExecuteSqlRequest.newBuilder() .setSession(lastSession) .setSql("select * FROM Users") .build()); // The ChannelRef which is bound with the lastSession. ChannelRef currentChannel = gcpChannel.affinityKeyToChannelRef.get(lastSession); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); logCount = logRecords.size(); // Create another 1 session per channel sequentially. // Without the round-robin it won't use the currentChannel as it has more active streams (1) than other channels. for (int i = 0; i < MAX_CHANNEL; i++) { ListenableFuture<Session> future = stub.createSession(req); assertThat(lastLogMessage()).isEqualTo( poolIndex + ": Channel 0 picked for bind operation."); assertThat(logRecords.size()).isEqualTo(++logCount); future.get(); logCount++; // For session mapping log message. } ResultSet response = responseFuture.get(); // Without round-robin the first channel will get all additional 3 sessions. checkChannelRefs(new int[]{0, 0, 0}, new int[]{4, 1, 1}); } @Test public void testListSessionsFuture() throws Exception { SpannerFutureStub stub = getSpannerFutureStub(); List<String> futureNames = createFutureSessions(stub); ListSessionsResponse responseList = stub.listSessions(ListSessionsRequest.newBuilder().setDatabase(DATABASE_PATH).build()) .get(); Set<String> trueNames = new HashSet<>(); deleteFutureSessions(stub, futureNames); } @Test public void testListSessionsAsync() throws Exception { SpannerStub stub = getSpannerStub(); List<String> respNames = createAsyncSessions(stub); AsyncResponseObserver<ListSessionsResponse> respList = new AsyncResponseObserver<>(); stub.listSessions( ListSessionsRequest.newBuilder().setDatabase(DATABASE_PATH).build(), respList); ListSessionsResponse responseList = respList.get(); deleteAsyncSessions(stub, respNames); } @Test public void testExecuteSqlFuture() throws Exception { SpannerFutureStub stub = getSpannerFutureStub(); List<String> futureNames = createFutureSessions(stub); for (String futureName : futureNames) { ListenableFuture<ResultSet> responseFuture = stub.executeSql( ExecuteSqlRequest.newBuilder() .setSession(futureName) .setSql("select * FROM Users") .build()); // The ChannelRef which is bound with the current affinity key. ChannelRef currentChannel = gcpChannel.affinityKeyToChannelRef.get(futureName); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); ResultSet response = responseFuture.get(); assertEquals(1, response.getRowsCount()); assertEquals(USERNAME, response.getRows(0).getValuesList().get(1).getStringValue()); assertEquals(0, currentChannel.getActiveStreamsCount()); } deleteFutureSessions(stub, futureNames); } @Test public void testExecuteStreamingSqlAsync() throws Exception { SpannerStub stub = getSpannerStub(); List<String> respNames = createAsyncSessions(stub); for (String respName : respNames) { AsyncResponseObserver<PartialResultSet> resp = new AsyncResponseObserver<>(); stub.executeStreamingSql( ExecuteSqlRequest.newBuilder().setSession(respName).setSql("select * FROM Users").build(), resp); // The ChannelRef which is bound with the current affinity key. ChannelRef currentChannel = gcpChannel.affinityKeyToChannelRef.get(respName); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); PartialResultSet response = resp.get(); assertEquals(USERNAME, resp.get().getValues(1).getStringValue()); assertEquals(0, currentChannel.getActiveStreamsCount()); } deleteAsyncSessions(stub, respNames); } @Test public void testPartitionQueryAsync() throws Exception { SpannerStub stub = getSpannerStub(); List<String> respNames = createAsyncSessions(stub); for (String respName : respNames) { TransactionOptions options = TransactionOptions.newBuilder() .setReadOnly(ReadOnly.getDefaultInstance()) .build(); TransactionSelector selector = TransactionSelector.newBuilder().setBegin(options).build(); AsyncResponseObserver<PartitionResponse> resp = new AsyncResponseObserver<>(); stub.partitionQuery( PartitionQueryRequest.newBuilder() .setSession(respName) .setSql("select * FROM Users") .setTransaction(selector) .build(), resp); // The ChannelRef which is bound with the current affinity key. ChannelRef currentChannel = gcpChannel.affinityKeyToChannelRef.get(respName); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); PartitionResponse response = resp.get(); assertEquals(0, currentChannel.getActiveStreamsCount()); } deleteAsyncSessions(stub, respNames); } @Test public void testExecuteBatchDmlFuture() throws Exception { SpannerFutureStub stub = getSpannerFutureStub(); List<String> futureNames = createFutureSessions(stub); for (String futureName : futureNames) { TransactionOptions options = TransactionOptions.newBuilder() .setReadWrite(ReadWrite.getDefaultInstance()) .build(); TransactionSelector selector = TransactionSelector.newBuilder().setBegin(options).build(); // Will use only one session for the whole batch. ListenableFuture<ExecuteBatchDmlResponse> responseFuture = stub.executeBatchDml( ExecuteBatchDmlRequest.newBuilder() .setSession(futureName) .setTransaction(selector) .addStatements(Statement.newBuilder().setSql("select * FROM Users").build()) .build()); // The ChannelRef which is bound with the current affinity key. ChannelRef currentChannel = gcpChannel.affinityKeyToChannelRef.get(futureName); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); ExecuteBatchDmlResponse response = responseFuture.get(); assertEquals(0, currentChannel.getActiveStreamsCount()); } deleteFutureSessions(stub, futureNames); } @Test public void testBoundWithInvalidAffinityKey() { SpannerBlockingStub stub = getSpannerBlockingStub(); CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); Session session = stub.createSession(req); expectedEx.expect(StatusRuntimeException.class); expectedEx.expectMessage("INVALID_ARGUMENT: Invalid GetSession request."); // No channel bound with the key "invalid_session", will use the least busy one. stub.getSession(GetSessionRequest.newBuilder().setName("invalid_session").build()); } @Test public void testUnbindWithInvalidAffinityKey() { SpannerBlockingStub stub = getSpannerBlockingStub(); CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); Session session = stub.createSession(req); expectedEx.expect(StatusRuntimeException.class); expectedEx.expectMessage("INVALID_ARGUMENT: Invalid DeleteSession request."); // No channel bound with the key "invalid_session", will use the least busy one. stub.deleteSession(DeleteSessionRequest.newBuilder().setName("invalid_session").build()); } @Test public void testBoundAfterUnbind() { SpannerBlockingStub stub = getSpannerBlockingStub(); CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); Session session = stub.createSession(req); stub.deleteSession(DeleteSessionRequest.newBuilder().setName(session.getName()).build()); expectedEx.expect(StatusRuntimeException.class); expectedEx.expectMessage("NOT_FOUND: Session not found: " + session.getName()); stub.getSession(GetSessionRequest.newBuilder().setName(session.getName()).build()); } private static class AsyncResponseObserver<RespT> implements StreamObserver<RespT> { private final CountDownLatch finishLatch = new CountDownLatch(1); private RespT response = null; private AsyncResponseObserver() {} public RespT get() throws InterruptedException { finishLatch.await(1, TimeUnit.MINUTES); return response; } @Override public void onNext(RespT response) { this.response = response; } @Override public void onError(Throwable t) { finishLatch.countDown(); } @Override public void onCompleted() { finishLatch.countDown(); } } }
grpc-gcp/src/test/java/com/google/cloud/grpc/SpannerIntegrationTest.java
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.grpc; import static com.google.cloud.grpc.GcpMultiEndpointChannel.ME_KEY; import static com.google.cloud.spanner.SpannerOptions.CALL_CONTEXT_CONFIGURATOR_KEY; import static com.google.common.base.Preconditions.checkState; import static com.google.common.truth.Truth.assertThat; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import com.google.api.client.util.Sleeper; import com.google.api.core.ApiFunction; import com.google.api.gax.grpc.GrpcCallContext; import com.google.api.gax.grpc.GrpcTransportChannel; import com.google.api.gax.longrunning.OperationFuture; import com.google.api.gax.rpc.ApiCallContext; import com.google.api.gax.rpc.FixedTransportChannelProvider; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.grpc.GcpManagedChannel.ChannelRef; import com.google.cloud.grpc.GcpManagedChannelOptions.GcpChannelPoolOptions; import com.google.cloud.grpc.GcpManagedChannelOptions.GcpMetricsOptions; import com.google.cloud.grpc.MetricRegistryTestUtils.FakeMetricRegistry; import com.google.cloud.grpc.MetricRegistryTestUtils.MetricsRecord; import com.google.cloud.grpc.MetricRegistryTestUtils.PointWithFunction; import com.google.cloud.grpc.proto.ApiConfig; import com.google.cloud.spanner.Database; import com.google.cloud.spanner.DatabaseAdminClient; import com.google.cloud.spanner.DatabaseClient; import com.google.cloud.spanner.DatabaseId; import com.google.cloud.spanner.Instance; import com.google.cloud.spanner.InstanceAdminClient; import com.google.cloud.spanner.InstanceConfig; import com.google.cloud.spanner.InstanceConfigId; import com.google.cloud.spanner.InstanceId; import com.google.cloud.spanner.InstanceInfo; import com.google.cloud.spanner.KeySet; import com.google.cloud.spanner.Mutation; import com.google.cloud.spanner.Spanner; import com.google.cloud.spanner.SpannerExceptionFactory; import com.google.cloud.spanner.SpannerOptions; import com.google.cloud.spanner.SpannerOptions.CallContextConfigurator; import com.google.common.collect.Iterators; import com.google.common.util.concurrent.ListenableFuture; import com.google.protobuf.Empty; import com.google.protobuf.util.JsonFormat; import com.google.protobuf.util.JsonFormat.Parser; import com.google.spanner.admin.database.v1.CreateDatabaseMetadata; import com.google.spanner.admin.instance.v1.CreateInstanceMetadata; import com.google.spanner.v1.BatchCreateSessionsRequest; import com.google.spanner.v1.BatchCreateSessionsResponse; import com.google.spanner.v1.CreateSessionRequest; import com.google.spanner.v1.DeleteSessionRequest; import com.google.spanner.v1.ExecuteBatchDmlRequest; import com.google.spanner.v1.ExecuteBatchDmlRequest.Statement; import com.google.spanner.v1.ExecuteBatchDmlResponse; import com.google.spanner.v1.ExecuteSqlRequest; import com.google.spanner.v1.GetSessionRequest; import com.google.spanner.v1.ListSessionsRequest; import com.google.spanner.v1.ListSessionsResponse; import com.google.spanner.v1.PartialResultSet; import com.google.spanner.v1.PartitionQueryRequest; import com.google.spanner.v1.PartitionResponse; import com.google.spanner.v1.ResultSet; import com.google.spanner.v1.Session; import com.google.spanner.v1.SpannerGrpc; import com.google.spanner.v1.SpannerGrpc.SpannerBlockingStub; import com.google.spanner.v1.SpannerGrpc.SpannerFutureStub; import com.google.spanner.v1.SpannerGrpc.SpannerStub; import com.google.spanner.v1.TransactionOptions; import com.google.spanner.v1.TransactionOptions.ReadOnly; import com.google.spanner.v1.TransactionOptions.ReadWrite; import com.google.spanner.v1.TransactionSelector; import io.grpc.CallOptions; import io.grpc.ConnectivityState; import io.grpc.Context; import io.grpc.ManagedChannelBuilder; import io.grpc.MethodDescriptor; import io.grpc.StatusRuntimeException; import io.grpc.auth.MoreCallCredentials; import io.grpc.stub.StreamObserver; import io.opencensus.metrics.LabelValue; import java.io.File; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.junit.After; import org.junit.AfterClass; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Integration tests for GcpManagedChannel with Spanner. */ @RunWith(JUnit4.class) public final class SpannerIntegrationTest { private static final Logger testLogger = Logger.getLogger(GcpManagedChannel.class.getName()); private final List<LogRecord> logRecords = new LinkedList<>(); private static final String GCP_PROJECT_ID = System.getenv("GCP_PROJECT_ID"); private static final String INSTANCE_ID = "grpc-gcp-test-instance"; private static final String DB_NAME = "grpc-gcp-test-db"; private static final String SPANNER_TARGET = "spanner.googleapis.com"; private static final String USERNAME = "test_user"; private static final String DATABASE_PATH = String.format("projects/%s/instances/%s/databases/%s", GCP_PROJECT_ID, INSTANCE_ID, DB_NAME); private static final String API_FILE = "spannertest.json"; private static final int MAX_CHANNEL = 3; private static final int MAX_STREAM = 2; private static final ManagedChannelBuilder<?> builder = ManagedChannelBuilder.forAddress(SPANNER_TARGET, 443); private GcpManagedChannel gcpChannel; private GcpManagedChannel gcpChannelBRR; private void sleep(long millis) throws InterruptedException { Sleeper.DEFAULT.sleep(millis); } @BeforeClass public static void beforeClass() { Assume.assumeTrue( "Need to provide GCP_PROJECT_ID for SpannerIntegrationTest", GCP_PROJECT_ID != null); SpannerOptions options = SpannerOptions.newBuilder().setProjectId(GCP_PROJECT_ID).build(); try (Spanner spanner = options.getService()) { InstanceAdminClient instanceAdminClient = spanner.getInstanceAdminClient(); InstanceId instanceId = InstanceId.of(GCP_PROJECT_ID, INSTANCE_ID); initializeInstance(instanceAdminClient, instanceId); DatabaseAdminClient databaseAdminClient = spanner.getDatabaseAdminClient(); DatabaseId databaseId = DatabaseId.of(instanceId, DB_NAME); initializeDatabase(databaseAdminClient, databaseId); DatabaseClient databaseClient = spanner.getDatabaseClient(databaseId); initializeTable(databaseClient); } } private String lastLogMessage() { return lastLogMessage(1); } private String lastLogMessage(int nthFromLast) { return logRecords.get(logRecords.size() - nthFromLast).getMessage(); } private Level lastLogLevel() { return logRecords.get(logRecords.size() - 1).getLevel(); } private final Handler testLogHandler = new Handler() { @Override public synchronized void publish(LogRecord record) { logRecords.add(record); } @Override public void flush() {} @Override public void close() throws SecurityException {} }; private static void initializeTable(DatabaseClient databaseClient) { List<Mutation> mutations = Arrays.asList( Mutation.newInsertBuilder("Users") .set("UserId") .to(1) .set("UserName") .to(USERNAME) .build()); databaseClient.write(mutations); } private static void initializeInstance( InstanceAdminClient instanceAdminClient, InstanceId instanceId) { InstanceConfig instanceConfig = Iterators.get(instanceAdminClient.listInstanceConfigs().iterateAll().iterator(), 0, null); checkState(instanceConfig != null, "No instance configs found"); InstanceConfigId configId = instanceConfig.getId(); InstanceInfo instance = InstanceInfo.newBuilder(instanceId) .setNodeCount(1) .setDisplayName("grpc-gcp test instance") .setInstanceConfigId(configId) .build(); OperationFuture<Instance, CreateInstanceMetadata> op = instanceAdminClient.createInstance(instance); try { op.get(); } catch (Exception e) { throw SpannerExceptionFactory.newSpannerException(e); } } private static void initializeDatabase( DatabaseAdminClient databaseAdminClient, DatabaseId databaseId) { OperationFuture<Database, CreateDatabaseMetadata> op = databaseAdminClient.createDatabase( databaseId.getInstanceId().getInstance(), databaseId.getDatabase(), Arrays.asList( "CREATE TABLE Users (" + " UserId INT64 NOT NULL," + " UserName STRING(1024)" + ") PRIMARY KEY (UserId)")); try { op.get(); } catch (Exception e) { throw SpannerExceptionFactory.newSpannerException(e); } } @AfterClass public static void afterClass() { SpannerOptions options = SpannerOptions.newBuilder().setProjectId(GCP_PROJECT_ID).build(); try (Spanner spanner = options.getService()) { InstanceAdminClient instanceAdminClient = spanner.getInstanceAdminClient(); InstanceId instanceId = InstanceId.of(GCP_PROJECT_ID, INSTANCE_ID); cleanUpInstance(instanceAdminClient, instanceId); } } private static void cleanUpInstance( InstanceAdminClient instanceAdminClient, InstanceId instanceId) { instanceAdminClient.deleteInstance(instanceId.getInstance()); } private static GoogleCredentials getCreds() { GoogleCredentials creds; try { creds = GoogleCredentials.getApplicationDefault(); } catch (Exception e) { return null; } return creds; } /** Helper functions for BlockingStub. */ private SpannerBlockingStub getSpannerBlockingStub() { GoogleCredentials creds = getCreds(); SpannerBlockingStub stub = SpannerGrpc.newBlockingStub(gcpChannel) .withCallCredentials(MoreCallCredentials.from(creds)); return stub; } private static void deleteSession(SpannerBlockingStub stub, Session session) { if (session != null) { stub.deleteSession(DeleteSessionRequest.newBuilder().setName(session.getName()).build()); } } /** Helper functions for Stub(async calls). */ private SpannerStub getSpannerStub() { GoogleCredentials creds = getCreds(); SpannerStub stub = SpannerGrpc.newStub(gcpChannel).withCallCredentials(MoreCallCredentials.from(creds)); return stub; } /** A wrapper of checking the status of each channelRef in the gcpChannel. */ private void checkChannelRefs(int channels, int streams, int affinities) { checkChannelRefs(gcpChannel, channels, streams, affinities); } private void checkChannelRefs(GcpManagedChannel gcpChannel, int channels, int streams, int affinities) { assertEquals("Channel pool size mismatch.", channels, gcpChannel.channelRefs.size()); for (int i = 0; i < channels; i++) { assertEquals( String.format("Channel %d streams mismatch.", i), streams, gcpChannel.channelRefs.get(i).getActiveStreamsCount() ); assertEquals( String.format("Channel %d affinities mismatch.", i), affinities, gcpChannel.channelRefs.get(i).getAffinityCount() ); } } private void checkChannelRefs(int[] streams, int[] affinities) { for (int i = 0; i < streams.length; i++) { assertEquals( String.format("Channel %d streams mismatch.", i), streams[i], gcpChannel.channelRefs.get(i).getActiveStreamsCount() ); assertEquals( String.format("Channel %d affinities mismatch.", i), affinities[i], gcpChannel.channelRefs.get(i).getAffinityCount() ); } } private List<String> createAsyncSessions(SpannerStub stub) throws Exception { List<AsyncResponseObserver<Session>> resps = new ArrayList<>(); List<String> respNames = new ArrayList<>(); // Check the state of the channel first. assertEquals(ConnectivityState.IDLE, gcpChannel.getState(false)); // Check CreateSession with multiple channels and streams, CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); for (int i = 0; i < MAX_CHANNEL * MAX_STREAM; i++) { AsyncResponseObserver<Session> resp = new AsyncResponseObserver<>(); stub.createSession(req, resp); resps.add(resp); } checkChannelRefs(MAX_CHANNEL, MAX_STREAM, 0); for (AsyncResponseObserver<Session> resp : resps) { respNames.add(resp.get().getName()); } // Since createSession will bind the key, check the number of keys bound with channels. assertEquals(ConnectivityState.READY, gcpChannel.getState(false)); assertEquals(MAX_CHANNEL * MAX_STREAM, gcpChannel.affinityKeyToChannelRef.size()); checkChannelRefs(MAX_CHANNEL, 0, MAX_STREAM); return respNames; } private void deleteAsyncSessions(SpannerStub stub, List<String> respNames) throws Exception { assertEquals(ConnectivityState.READY, gcpChannel.getState(false)); for (String respName : respNames) { AsyncResponseObserver<Empty> resp = new AsyncResponseObserver<>(); stub.deleteSession(DeleteSessionRequest.newBuilder().setName(respName).build(), resp); // The ChannelRef which is bound with the current affinity key. ChannelRef currentChannel = gcpChannel.affinityKeyToChannelRef.get(respName); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); resp.get(); assertEquals(0, currentChannel.getActiveStreamsCount()); } checkChannelRefs(MAX_CHANNEL, 0, 0); assertEquals(0, gcpChannel.affinityKeyToChannelRef.size()); } /** Helper Functions for FutureStub. */ private SpannerFutureStub getSpannerFutureStub() { return getSpannerFutureStub(gcpChannel); } private SpannerFutureStub getSpannerFutureStub(GcpManagedChannel gcpChannel) { GoogleCredentials creds = getCreds(); return SpannerGrpc.newFutureStub(gcpChannel).withCallCredentials(MoreCallCredentials.from(creds)); } private List<String> createFutureSessions(SpannerFutureStub stub) throws Exception { List<ListenableFuture<Session>> futures = new ArrayList<>(); List<String> futureNames = new ArrayList<>(); assertEquals(ConnectivityState.IDLE, gcpChannel.getState(false)); // Check CreateSession with multiple channels and streams, CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); for (int i = 0; i < MAX_CHANNEL * MAX_STREAM; i++) { ListenableFuture<Session> future = stub.createSession(req); futures.add(future); } checkChannelRefs(MAX_CHANNEL, MAX_STREAM, 0); for (ListenableFuture<Session> future : futures) { futureNames.add(future.get().getName()); } // Since createSession will bind the key, check the number of keys bound with channels. assertEquals(ConnectivityState.READY, gcpChannel.getState(false)); assertEquals(MAX_CHANNEL * MAX_STREAM, gcpChannel.affinityKeyToChannelRef.size()); checkChannelRefs(MAX_CHANNEL, 0, MAX_STREAM); return futureNames; } private void deleteFutureSessions(SpannerFutureStub stub, List<String> futureNames) throws Exception { assertEquals(ConnectivityState.READY, gcpChannel.getState(false)); for (String futureName : futureNames) { ListenableFuture<Empty> future = stub.deleteSession(DeleteSessionRequest.newBuilder().setName(futureName).build()); // The ChannelRef which is bound with the current affinity key. ChannelRef currentChannel = gcpChannel.affinityKeyToChannelRef.get(futureName); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); future.get(); assertEquals(0, currentChannel.getActiveStreamsCount()); } checkChannelRefs(MAX_CHANNEL, 0, 0); assertEquals(0, gcpChannel.affinityKeyToChannelRef.size()); } @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void setupChannels() { testLogger.addHandler(testLogHandler); File configFile = new File(SpannerIntegrationTest.class.getClassLoader().getResource(API_FILE).getFile()); gcpChannel = (GcpManagedChannel) GcpManagedChannelBuilder.forDelegateBuilder(builder) .withApiConfigJsonFile(configFile) .build(); gcpChannelBRR = (GcpManagedChannel) GcpManagedChannelBuilder.forDelegateBuilder(builder) .withApiConfigJsonFile(configFile) .withOptions(GcpManagedChannelOptions.newBuilder() .withChannelPoolOptions( GcpChannelPoolOptions.newBuilder() .setMaxSize(MAX_CHANNEL) .setConcurrentStreamsLowWatermark(MAX_STREAM) .setUseRoundRobinOnBind(true) .build()) .build()) .build(); } @After public void shutdownChannels() { testLogger.removeHandler(testLogHandler); testLogger.setLevel(Level.INFO); logRecords.clear(); gcpChannel.shutdownNow(); gcpChannelBRR.shutdownNow(); } private long getOkCallsCount( FakeMetricRegistry fakeRegistry, String endpoint) { MetricsRecord record = fakeRegistry.pollRecord(); List<PointWithFunction<?>> metric = record.getMetrics().get(GcpMetricsConstants.METRIC_NUM_CALLS_COMPLETED); for (PointWithFunction<?> m : metric) { assertThat(m.keys().get(0).getKey()).isEqualTo("result"); assertThat(m.keys().get(1).getKey()).isEqualTo("endpoint"); if (!m.values().get(0).equals(LabelValue.create(GcpMetricsConstants.RESULT_SUCCESS))) { continue; } if (!m.values().get(1).equals(LabelValue.create(endpoint))) { continue; } return m.value(); } fail("Success calls metric is not found for endpoint: " + endpoint); return 0; } private ApiConfig getApiConfig() throws IOException { File configFile = new File(SpannerIntegrationTest.class.getClassLoader().getResource(API_FILE).getFile()); Parser parser = JsonFormat.parser(); ApiConfig.Builder apiConfigBuilder = ApiConfig.newBuilder(); Reader reader = Files.newBufferedReader(configFile.toPath(), UTF_8); parser.merge(reader, apiConfigBuilder); return apiConfigBuilder.build(); } // For this test we'll create a Spanner client with gRPC-GCP MultiEndpoint feature. // // Imagine we have a multi-region Spanner instance with leader in the us-east4 and follower in the // us-east1 regions. // // We will provide two MultiEndpoint configs: "leader" (having leader region endpoint first and // follower second) and "follower" (having follower region endpoint first and leader second). // // Then we'll make sure the Spanner client uses leader MultiEndpoint as a default one and creates // its sessions there. Then we'll make sure a read request will also use the leader MultiEndpoint // by default. // // Then we'll verify we can use the follower MultiEndpoint when needed by specifying that in // the Spanner context. // // Then we'll update MultiEndpoints configuration by replacing the leader endpoint and renaming // the follower MultiEndpoint. And make sure the new leader endpoint and the previous follower // endpoint are still working as expected when using different MultiEndpoints. @Test public void testSpannerMultiEndpointClient() throws IOException, InterruptedException { // Watch debug messages. testLogger.setLevel(Level.FINEST); final FakeMetricRegistry fakeRegistry = new FakeMetricRegistry(); // Leader-first multi-endpoint endpoints. final List<String> leaderEndpoints = new ArrayList<>(); // Follower-first multi-endpoint endpoints. final List<String> followerEndpoints = new ArrayList<>(); final String leaderEndpoint = "us-east4.googleapis.com:443"; final String followerEndpoint = "us-east1.googleapis.com:443"; leaderEndpoints.add(leaderEndpoint); leaderEndpoints.add(followerEndpoint); followerEndpoints.add(followerEndpoint); followerEndpoints.add(leaderEndpoint); ApiFunction<ManagedChannelBuilder<?>, ManagedChannelBuilder<?>> configurator = input -> input.overrideAuthority(SPANNER_TARGET); GcpMultiEndpointOptions leaderOpts = GcpMultiEndpointOptions.newBuilder(leaderEndpoints) .withName("leader") .withChannelConfigurator(configurator) .withRecoveryTimeout(Duration.ofSeconds(3)) .build(); GcpMultiEndpointOptions followerOpts = GcpMultiEndpointOptions.newBuilder(followerEndpoints) .withName("follower") .withChannelConfigurator(configurator) .withRecoveryTimeout(Duration.ofSeconds(3)) .build(); List<GcpMultiEndpointOptions> opts = new ArrayList<>(); opts.add(leaderOpts); opts.add(followerOpts); GcpMultiEndpointChannel gcpMultiEndpointChannel = new GcpMultiEndpointChannel( opts, getApiConfig(), GcpManagedChannelOptions.newBuilder() .withChannelPoolOptions(GcpChannelPoolOptions.newBuilder() .setConcurrentStreamsLowWatermark(0) .setMaxSize(3) .build()) .withMetricsOptions(GcpMetricsOptions.newBuilder() .withMetricRegistry(fakeRegistry) .build()) .build()); final int currentIndex = GcpManagedChannel.channelPoolIndex.get(); final String followerPoolIndex = String.format("pool-%d", currentIndex); final String leaderPoolIndex = String.format("pool-%d", currentIndex - 1); // Make sure authorities are overridden by channel configurator. assertThat(gcpMultiEndpointChannel.authority()).isEqualTo(SPANNER_TARGET); assertThat(gcpMultiEndpointChannel.authorityFor("leader")) .isEqualTo(SPANNER_TARGET); assertThat(gcpMultiEndpointChannel.authorityFor("follower")) .isEqualTo(SPANNER_TARGET); assertThat(gcpMultiEndpointChannel.authorityFor("no-such-name")).isNull(); sleep(1000); List<String> logMessages = logRecords.stream() .map(LogRecord::getMessage).collect(Collectors.toList()); // Make sure min channels are created and connections are established right away in both pools. for (String poolIndex : Arrays.asList(leaderPoolIndex, followerPoolIndex)) { for (int i = 0; i < 2; i++) { assertThat(logMessages).contains( poolIndex + ": Channel " + i + " state change detected: null -> IDLE"); assertThat(logMessages).contains( poolIndex + ": Channel " + i + " state change detected: IDLE -> CONNECTING"); } } // Make sure endpoint is set as a metric label for each pool. assertThat(logRecords.stream().filter(logRecord -> logRecord.getMessage().matches( leaderPoolIndex + ": Metrics options: \\{namePrefix: \"\", labels: \\[endpoint: " + "\"" + leaderEndpoint + "\"], metricRegistry: .*" )).count()).isEqualTo(1); assertThat(logRecords.stream().filter(logRecord -> logRecord.getMessage().matches( followerPoolIndex + ": Metrics options: \\{namePrefix: \"\", labels: \\[endpoint: " + "\"" + followerEndpoint + "\"], metricRegistry: .*" )).count()).isEqualTo(1); logRecords.clear(); TransportChannelProvider channelProvider = FixedTransportChannelProvider.create( GrpcTransportChannel.create(gcpMultiEndpointChannel)); SpannerOptions.Builder options = SpannerOptions.newBuilder().setProjectId(GCP_PROJECT_ID); options.setChannelProvider(channelProvider); // Match channel pool size. options.setNumChannels(3); Spanner spanner = options.build().getService(); InstanceId instanceId = InstanceId.of(GCP_PROJECT_ID, INSTANCE_ID); DatabaseId databaseId = DatabaseId.of(instanceId, DB_NAME); DatabaseClient databaseClient = spanner.getDatabaseClient(databaseId); Runnable readQuery = () -> { try (com.google.cloud.spanner.ResultSet read = databaseClient.singleUse() .read("Users", KeySet.all(), Arrays.asList("UserId", "UserName"))) { int readRows = 0; while (read.next()) { readRows++; assertEquals(USERNAME, read.getCurrentRowAsStruct().getString("UserName")); } assertEquals(1, readRows); } }; // Make sure leader endpoint is used by default. assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(0); readQuery.run(); // Wait for sessions creation requests to be completed but no more than 10 seconds. for (int i = 0; i < 20; i++) { sleep(500); if (getOkCallsCount(fakeRegistry, leaderEndpoint) == 4) { break; } } // 3 session creation requests + 1 our read request to the leader endpoint. assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(4); // Make sure there were 3 session creation requests in the leader pool only. assertThat(logRecords.stream().filter(logRecord -> logRecord.getMessage().matches( leaderPoolIndex + ": Binding \\d+ key\\(s\\) to channel \\d:.*" )).count()).isEqualTo(3); assertThat(logRecords.stream().filter(logRecord -> logRecord.getMessage().matches( followerPoolIndex + ": Binding \\d+ key\\(s\\) to channel \\d:.*" )).count()).isEqualTo(0); // Create context for using follower-first multi-endpoint. Function<String, Context> contextFor = meName -> Context.current() .withValue(CALL_CONTEXT_CONFIGURATOR_KEY, new CallContextConfigurator() { @Nullable @Override public <ReqT, RespT> ApiCallContext configure(ApiCallContext context, ReqT request, MethodDescriptor<ReqT, RespT> method) { return context.merge(GrpcCallContext.createDefault().withCallOptions( CallOptions.DEFAULT.withOption(ME_KEY, meName))); } }); assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(0); // Use follower, make sure it is used. contextFor.apply("follower").run(readQuery); assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(1); // Replace leader endpoints. final String newLeaderEndpoint = "us-west1.googleapis.com:443"; leaderEndpoints.clear(); leaderEndpoints.add(newLeaderEndpoint); leaderEndpoints.add(followerEndpoint); leaderOpts = GcpMultiEndpointOptions.newBuilder(leaderEndpoints) .withName("leader") .withChannelConfigurator(configurator) .build(); followerEndpoints.clear(); followerEndpoints.add(followerEndpoint); followerEndpoints.add(newLeaderEndpoint); // Rename follower MultiEndpoint. followerOpts = GcpMultiEndpointOptions.newBuilder(followerEndpoints) .withName("follower-2") .withChannelConfigurator(configurator) .build(); opts.clear(); opts.add(leaderOpts); opts.add(followerOpts); gcpMultiEndpointChannel.setMultiEndpoints(opts); // As it takes some time to connect to the new leader endpoint, RPC will fall back to the // follower until we connect to leader. assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(1); readQuery.run(); assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(2); sleep(500); // Make sure the new leader endpoint is used by default after it is connected. assertThat(getOkCallsCount(fakeRegistry, newLeaderEndpoint)).isEqualTo(0); readQuery.run(); assertThat(getOkCallsCount(fakeRegistry, newLeaderEndpoint)).isEqualTo(1); // Make sure that the follower endpoint still works if specified. assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(2); // Use follower, make sure it is used. contextFor.apply("follower-2").run(readQuery); assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(3); gcpMultiEndpointChannel.shutdown(); spanner.close(); } @Test public void testSpannerMultiEndpointClientWithDelay() throws IOException, InterruptedException { // Watch debug messages. testLogger.setLevel(Level.FINEST); final int poolSize = 3; final long switchingDelayMs = 500; final long marginMs = 50; final FakeMetricRegistry fakeRegistry = new FakeMetricRegistry(); // Leader-first multi-endpoint endpoints. final List<String> leaderEndpoints = new ArrayList<>(); // Follower-first multi-endpoint endpoints. final List<String> followerEndpoints = new ArrayList<>(); final String leaderEndpoint = "us-east4.googleapis.com:443"; final String followerEndpoint = "us-east1.googleapis.com:443"; leaderEndpoints.add(leaderEndpoint); leaderEndpoints.add(followerEndpoint); followerEndpoints.add(followerEndpoint); followerEndpoints.add(leaderEndpoint); ApiFunction<ManagedChannelBuilder<?>, ManagedChannelBuilder<?>> configurator = input -> input.overrideAuthority(SPANNER_TARGET); GcpMultiEndpointOptions leaderOpts = GcpMultiEndpointOptions.newBuilder(leaderEndpoints) .withName("leader") .withChannelConfigurator(configurator) .withRecoveryTimeout(Duration.ofSeconds(3)) .withSwitchingDelay(Duration.ofMillis(switchingDelayMs)) .build(); GcpMultiEndpointOptions followerOpts = GcpMultiEndpointOptions.newBuilder(followerEndpoints) .withName("follower") .withChannelConfigurator(configurator) .withRecoveryTimeout(Duration.ofSeconds(3)) .withSwitchingDelay(Duration.ofMillis(switchingDelayMs)) .build(); List<GcpMultiEndpointOptions> opts = new ArrayList<>(); opts.add(leaderOpts); opts.add(followerOpts); GcpMultiEndpointChannel gcpMultiEndpointChannel = new GcpMultiEndpointChannel( opts, getApiConfig(), GcpManagedChannelOptions.newBuilder() .withChannelPoolOptions(GcpChannelPoolOptions.newBuilder() .setConcurrentStreamsLowWatermark(0) .setMaxSize(poolSize) .build()) .withMetricsOptions(GcpMetricsOptions.newBuilder() .withMetricRegistry(fakeRegistry) .build()) .build()); final int currentIndex = GcpManagedChannel.channelPoolIndex.get(); final String followerPoolIndex = String.format("pool-%d", currentIndex); final String leaderPoolIndex = String.format("pool-%d", currentIndex - 1); TransportChannelProvider channelProvider = FixedTransportChannelProvider.create( GrpcTransportChannel.create(gcpMultiEndpointChannel)); SpannerOptions.Builder options = SpannerOptions.newBuilder().setProjectId(GCP_PROJECT_ID); options.setChannelProvider(channelProvider); // Match channel pool size. options.setNumChannels(poolSize); Spanner spanner = options.build().getService(); InstanceId instanceId = InstanceId.of(GCP_PROJECT_ID, INSTANCE_ID); DatabaseId databaseId = DatabaseId.of(instanceId, DB_NAME); DatabaseClient databaseClient = spanner.getDatabaseClient(databaseId); Runnable readQuery = () -> { try (com.google.cloud.spanner.ResultSet read = databaseClient.singleUse() .read("Users", KeySet.all(), Arrays.asList("UserId", "UserName"))) { int readRows = 0; while (read.next()) { readRows++; assertEquals(USERNAME, read.getCurrentRowAsStruct().getString("UserName")); } assertEquals(1, readRows); } }; // Make sure leader endpoint is used by default. assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(0); readQuery.run(); // Wait for sessions creation requests to be completed but no more than 10 seconds. for (int i = 0; i < 20; i++) { sleep(500); if (getOkCallsCount(fakeRegistry, leaderEndpoint) == 4) { break; } } // 3 session creation requests + 1 our read request to the leader endpoint. assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(4); // Change the endpoints in the leader endpoint. east4, east1 -> east1, east4. leaderOpts = GcpMultiEndpointOptions.newBuilder(followerEndpoints) .withName("leader") .withChannelConfigurator(configurator) .withRecoveryTimeout(Duration.ofSeconds(3)) .withSwitchingDelay(Duration.ofMillis(switchingDelayMs)) .build(); opts = new ArrayList<>(); opts.add(leaderOpts); opts.add(followerOpts); gcpMultiEndpointChannel.setMultiEndpoints(opts); // Because of the delay the leader MultiEndpoint should still use leader endpoint. sleep(switchingDelayMs - marginMs); readQuery.run(); assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(0); assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(5); // But after the delay, it should switch to the follower endpoint. sleep(2 * marginMs); readQuery.run(); assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(5); assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(1); gcpMultiEndpointChannel.shutdown(); spanner.close(); } @Test public void testCreateAndGetSessionBlocking() { SpannerBlockingStub stub = getSpannerBlockingStub(); CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); // The first MAX_CHANNEL requests (without affinity) should be distributed 1 per channel. List<Session> sessions = new ArrayList<>(); for (int i = 0; i < MAX_CHANNEL; i++) { Session session = stub.createSession(req); assertThat(session).isNotEqualTo(null); sessions.add(session); Session responseGet = stub.getSession(GetSessionRequest.newBuilder().setName(session.getName()).build()); assertEquals(responseGet.getName(), session.getName()); } checkChannelRefs(MAX_CHANNEL, 0, 1); for (Session session : sessions) { deleteSession(stub, session); } checkChannelRefs(MAX_CHANNEL, 0, 0); } @Test public void testBatchCreateSessionsBlocking() { int sessionCount = 10; SpannerBlockingStub stub = getSpannerBlockingStub(); BatchCreateSessionsRequest req = BatchCreateSessionsRequest.newBuilder() .setDatabase(DATABASE_PATH) .setSessionCount(sessionCount) .build(); List<Session> sessions = new ArrayList<>(); // The first MAX_CHANNEL requests (without affinity) should be distributed 1 per channel. for (int j = 0; j < MAX_CHANNEL; j++) { BatchCreateSessionsResponse resp = stub.batchCreateSessions(req); assertThat(resp.getSessionCount()).isEqualTo(sessionCount); sessions.addAll(resp.getSessionList()); } checkChannelRefs(MAX_CHANNEL, 0, sessionCount); for (Session session : sessions) { deleteSession(stub, session); } checkChannelRefs(MAX_CHANNEL, 0, 0); } @Test public void testSessionsCreatedUsingRoundRobin() throws Exception { SpannerFutureStub stub = getSpannerFutureStub(gcpChannelBRR); List<ListenableFuture<Session>> futures = new ArrayList<>(); assertEquals(ConnectivityState.IDLE, gcpChannelBRR.getState(false)); // Should create one session per channel. CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); for (int i = 0; i < MAX_CHANNEL; i++) { ListenableFuture<Session> future = stub.createSession(req); futures.add(future); } // If round-robin in use as expected, then each channel should have 1 active stream with the CreateSession request. checkChannelRefs(gcpChannelBRR, MAX_CHANNEL, 1, 0); // Collecting futures results. String lastSession = ""; for (ListenableFuture<Session> future : futures) { lastSession = future.get().getName(); } // Since createSession will bind the key, check the number of keys bound with channels. // Each channel should have 1 affinity key. assertEquals(MAX_CHANNEL, gcpChannelBRR.affinityKeyToChannelRef.size()); checkChannelRefs(gcpChannelBRR, MAX_CHANNEL, 0, 1); // Create a different request with the lastSession created. ListenableFuture<ResultSet> responseFuture = stub.executeSql( ExecuteSqlRequest.newBuilder() .setSession(lastSession) .setSql("select * FROM Users") .build()); // The ChannelRef which is bound with the lastSession. ChannelRef currentChannel = gcpChannelBRR.affinityKeyToChannelRef.get(lastSession); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); // Create another 1 session per channel sequentially. // Without the round-robin it won't use the currentChannel as it has more active streams (1) than other channels. // But with round-robin each channel should get one create session request. for (int i = 0; i < MAX_CHANNEL; i++) { ListenableFuture<Session> future = stub.createSession(req); future.get(); } ResultSet response = responseFuture.get(); // If round-robin in use, then each channel should now have 2 active stream with the CreateSession request. checkChannelRefs(gcpChannelBRR, MAX_CHANNEL, 0, 2); } @Test public void testSessionsCreatedWithoutRoundRobin() throws Exception { // Watch debug messages. testLogger.setLevel(Level.FINEST); final int currentIndex = GcpManagedChannel.channelPoolIndex.get() - 1; final String poolIndex = String.format("pool-%d", currentIndex); SpannerFutureStub stub = getSpannerFutureStub(); List<ListenableFuture<Session>> futures = new ArrayList<>(); assertEquals(ConnectivityState.IDLE, gcpChannel.getState(false)); // Initial log messages count. int logCount = logRecords.size(); // Should create one session per channel. CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); for (int i = 0; i < MAX_CHANNEL; i++) { ListenableFuture<Session> future = stub.createSession(req); futures.add(future); assertThat(lastLogMessage(3)).isEqualTo( poolIndex + ": Channel " + i + " state change detected: null -> IDLE"); assertThat(lastLogMessage(2)).isEqualTo( poolIndex + ": Channel " + i + " created."); assertThat(lastLogMessage()).isEqualTo( poolIndex + ": Channel " + i + " picked for bind operation."); logCount += 3; assertThat(logRecords.size()).isEqualTo(logCount); assertThat(lastLogLevel()).isEqualTo(Level.FINEST); } // Each channel should have 1 active stream with the CreateSession request because we create them concurrently. checkChannelRefs(gcpChannel, MAX_CHANNEL, 1, 0); // Collecting futures results. String lastSession = ""; for (ListenableFuture<Session> future : futures) { lastSession = future.get().getName(); } // Since createSession will bind the key, check the number of keys bound with channels. // Each channel should have 1 affinity key. assertEquals(MAX_CHANNEL, gcpChannel.affinityKeyToChannelRef.size()); checkChannelRefs(MAX_CHANNEL, 0, 1); // Create a different request with the lastSession created. ListenableFuture<ResultSet> responseFuture = stub.executeSql( ExecuteSqlRequest.newBuilder() .setSession(lastSession) .setSql("select * FROM Users") .build()); // The ChannelRef which is bound with the lastSession. ChannelRef currentChannel = gcpChannel.affinityKeyToChannelRef.get(lastSession); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); logCount = logRecords.size(); // Create another 1 session per channel sequentially. // Without the round-robin it won't use the currentChannel as it has more active streams (1) than other channels. for (int i = 0; i < MAX_CHANNEL; i++) { ListenableFuture<Session> future = stub.createSession(req); assertThat(lastLogMessage()).isEqualTo( poolIndex + ": Channel 0 picked for bind operation."); assertThat(logRecords.size()).isEqualTo(++logCount); future.get(); logCount++; // For session mapping log message. } ResultSet response = responseFuture.get(); // Without round-robin the first channel will get all additional 3 sessions. checkChannelRefs(new int[]{0, 0, 0}, new int[]{4, 1, 1}); } @Test public void testListSessionsFuture() throws Exception { SpannerFutureStub stub = getSpannerFutureStub(); List<String> futureNames = createFutureSessions(stub); ListSessionsResponse responseList = stub.listSessions(ListSessionsRequest.newBuilder().setDatabase(DATABASE_PATH).build()) .get(); Set<String> trueNames = new HashSet<>(); deleteFutureSessions(stub, futureNames); } @Test public void testListSessionsAsync() throws Exception { SpannerStub stub = getSpannerStub(); List<String> respNames = createAsyncSessions(stub); AsyncResponseObserver<ListSessionsResponse> respList = new AsyncResponseObserver<>(); stub.listSessions( ListSessionsRequest.newBuilder().setDatabase(DATABASE_PATH).build(), respList); ListSessionsResponse responseList = respList.get(); deleteAsyncSessions(stub, respNames); } @Test public void testExecuteSqlFuture() throws Exception { SpannerFutureStub stub = getSpannerFutureStub(); List<String> futureNames = createFutureSessions(stub); for (String futureName : futureNames) { ListenableFuture<ResultSet> responseFuture = stub.executeSql( ExecuteSqlRequest.newBuilder() .setSession(futureName) .setSql("select * FROM Users") .build()); // The ChannelRef which is bound with the current affinity key. ChannelRef currentChannel = gcpChannel.affinityKeyToChannelRef.get(futureName); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); ResultSet response = responseFuture.get(); assertEquals(1, response.getRowsCount()); assertEquals(USERNAME, response.getRows(0).getValuesList().get(1).getStringValue()); assertEquals(0, currentChannel.getActiveStreamsCount()); } deleteFutureSessions(stub, futureNames); } @Test public void testExecuteStreamingSqlAsync() throws Exception { SpannerStub stub = getSpannerStub(); List<String> respNames = createAsyncSessions(stub); for (String respName : respNames) { AsyncResponseObserver<PartialResultSet> resp = new AsyncResponseObserver<>(); stub.executeStreamingSql( ExecuteSqlRequest.newBuilder().setSession(respName).setSql("select * FROM Users").build(), resp); // The ChannelRef which is bound with the current affinity key. ChannelRef currentChannel = gcpChannel.affinityKeyToChannelRef.get(respName); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); PartialResultSet response = resp.get(); assertEquals(USERNAME, resp.get().getValues(1).getStringValue()); assertEquals(0, currentChannel.getActiveStreamsCount()); } deleteAsyncSessions(stub, respNames); } @Test public void testPartitionQueryAsync() throws Exception { SpannerStub stub = getSpannerStub(); List<String> respNames = createAsyncSessions(stub); for (String respName : respNames) { TransactionOptions options = TransactionOptions.newBuilder() .setReadOnly(ReadOnly.getDefaultInstance()) .build(); TransactionSelector selector = TransactionSelector.newBuilder().setBegin(options).build(); AsyncResponseObserver<PartitionResponse> resp = new AsyncResponseObserver<>(); stub.partitionQuery( PartitionQueryRequest.newBuilder() .setSession(respName) .setSql("select * FROM Users") .setTransaction(selector) .build(), resp); // The ChannelRef which is bound with the current affinity key. ChannelRef currentChannel = gcpChannel.affinityKeyToChannelRef.get(respName); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); PartitionResponse response = resp.get(); assertEquals(0, currentChannel.getActiveStreamsCount()); } deleteAsyncSessions(stub, respNames); } @Test public void testExecuteBatchDmlFuture() throws Exception { SpannerFutureStub stub = getSpannerFutureStub(); List<String> futureNames = createFutureSessions(stub); for (String futureName : futureNames) { TransactionOptions options = TransactionOptions.newBuilder() .setReadWrite(ReadWrite.getDefaultInstance()) .build(); TransactionSelector selector = TransactionSelector.newBuilder().setBegin(options).build(); // Will use only one session for the whole batch. ListenableFuture<ExecuteBatchDmlResponse> responseFuture = stub.executeBatchDml( ExecuteBatchDmlRequest.newBuilder() .setSession(futureName) .setTransaction(selector) .addStatements(Statement.newBuilder().setSql("select * FROM Users").build()) .build()); // The ChannelRef which is bound with the current affinity key. ChannelRef currentChannel = gcpChannel.affinityKeyToChannelRef.get(futureName); // Verify the channel is in use. assertEquals(1, currentChannel.getActiveStreamsCount()); ExecuteBatchDmlResponse response = responseFuture.get(); assertEquals(0, currentChannel.getActiveStreamsCount()); } deleteFutureSessions(stub, futureNames); } @Test public void testBoundWithInvalidAffinityKey() { SpannerBlockingStub stub = getSpannerBlockingStub(); CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); Session session = stub.createSession(req); expectedEx.expect(StatusRuntimeException.class); expectedEx.expectMessage("INVALID_ARGUMENT: Invalid GetSession request."); // No channel bound with the key "invalid_session", will use the least busy one. stub.getSession(GetSessionRequest.newBuilder().setName("invalid_session").build()); } @Test public void testUnbindWithInvalidAffinityKey() { SpannerBlockingStub stub = getSpannerBlockingStub(); CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); Session session = stub.createSession(req); expectedEx.expect(StatusRuntimeException.class); expectedEx.expectMessage("INVALID_ARGUMENT: Invalid DeleteSession request."); // No channel bound with the key "invalid_session", will use the least busy one. stub.deleteSession(DeleteSessionRequest.newBuilder().setName("invalid_session").build()); } @Test public void testBoundAfterUnbind() { SpannerBlockingStub stub = getSpannerBlockingStub(); CreateSessionRequest req = CreateSessionRequest.newBuilder().setDatabase(DATABASE_PATH).build(); Session session = stub.createSession(req); stub.deleteSession(DeleteSessionRequest.newBuilder().setName(session.getName()).build()); expectedEx.expect(StatusRuntimeException.class); expectedEx.expectMessage("NOT_FOUND: Session not found: " + session.getName()); stub.getSession(GetSessionRequest.newBuilder().setName(session.getName()).build()); } private static class AsyncResponseObserver<RespT> implements StreamObserver<RespT> { private final CountDownLatch finishLatch = new CountDownLatch(1); private RespT response = null; private AsyncResponseObserver() {} public RespT get() throws InterruptedException { finishLatch.await(1, TimeUnit.MINUTES); return response; } @Override public void onNext(RespT response) { this.response = response; } @Override public void onError(Throwable t) { finishLatch.countDown(); } @Override public void onCompleted() { finishLatch.countDown(); } } }
Add add/remove endpoint test case for switching delay.
grpc-gcp/src/test/java/com/google/cloud/grpc/SpannerIntegrationTest.java
Add add/remove endpoint test case for switching delay.
<ide><path>rpc-gcp/src/test/java/com/google/cloud/grpc/SpannerIntegrationTest.java <ide> import java.time.Duration; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <add>import java.util.Collections; <ide> import java.util.HashSet; <ide> import java.util.LinkedList; <ide> import java.util.List; <ide> // Because of the delay the leader MultiEndpoint should still use leader endpoint. <ide> sleep(switchingDelayMs - marginMs); <ide> readQuery.run(); <add> assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(5); <ide> assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(0); <del> assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(5); <ide> <ide> // But after the delay, it should switch to the follower endpoint. <ide> sleep(2 * marginMs); <ide> readQuery.run(); <ide> assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(5); <ide> assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(1); <add> <add> // Remove leader endpoint from the leader multi-endpoint. east1, east4 -> east1. <add> leaderOpts = GcpMultiEndpointOptions.newBuilder(Collections.singletonList(followerEndpoint)) <add> .withName("leader") <add> .withChannelConfigurator(configurator) <add> .withRecoveryTimeout(Duration.ofSeconds(3)) <add> .withSwitchingDelay(Duration.ofMillis(switchingDelayMs)) <add> .build(); <add> <add> opts = new ArrayList<>(); <add> opts.add(leaderOpts); <add> opts.add(followerOpts); <add> <add> gcpMultiEndpointChannel.setMultiEndpoints(opts); <add> <add> // Bring the leader endpoint back. east1 -> east4, east1. <add> leaderOpts = GcpMultiEndpointOptions.newBuilder(leaderEndpoints) <add> .withName("leader") <add> .withChannelConfigurator(configurator) <add> .withRecoveryTimeout(Duration.ofSeconds(3)) <add> .withSwitchingDelay(Duration.ofMillis(switchingDelayMs)) <add> .build(); <add> <add> opts = new ArrayList<>(); <add> opts.add(leaderOpts); <add> opts.add(followerOpts); <add> <add> gcpMultiEndpointChannel.setMultiEndpoints(opts); <add> <add> // Because of the delay the leader MultiEndpoint should still use follower endpoint. <add> sleep(switchingDelayMs - marginMs); <add> readQuery.run(); <add> assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(5); <add> assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(2); <add> <add> // But after the delay, it should switch back to the leader endpoint. <add> sleep(2 * marginMs); <add> readQuery.run(); <add> assertThat(getOkCallsCount(fakeRegistry, leaderEndpoint)).isEqualTo(6); <add> assertThat(getOkCallsCount(fakeRegistry, followerEndpoint)).isEqualTo(2); <ide> <ide> gcpMultiEndpointChannel.shutdown(); <ide> spanner.close();
JavaScript
mit
37f8dfe0080fa73a61cd16b3065cf133a3e74f8e
0
jjeffryes/openbazaar-desktop,jjeffryes/openbazaar-desktop,OpenBazaar/openbazaar-desktop,jashot7/openbazaar-desktop,jjeffryes/openbazaar-desktop,jashot7/openbazaar-desktop,OpenBazaar/openbazaar-desktop,jashot7/openbazaar-desktop,OpenBazaar/openbazaar-desktop
import $ from 'jquery'; import '../../../utils/velocity'; import '../../../lib/select2'; import Sortable from 'sortablejs'; import _ from 'underscore'; import path from 'path'; import '../../../utils/velocityUiPack.js'; import Backbone from 'backbone'; import { isScrolledIntoView } from '../../../utils/dom'; import { installRichEditor } from '../../../utils/trumbowyg'; import { getCurrenciesSortedByCode } from '../../../data/currencies'; import { formatPrice } from '../../../utils/currency'; import SimpleMessage from '../SimpleMessage'; import loadTemplate from '../../../utils/loadTemplate'; import ShippingOptionMd from '../../../models/listing/ShippingOption'; import Service from '../../../models/listing/Service'; import Image from '../../../models/listing/Image'; import Coupon from '../../../models/listing/Coupon'; import VariantOption from '../../../models/listing/VariantOption'; import app from '../../../app'; import BaseModal from '../BaseModal'; import ShippingOption from './ShippingOption'; import Coupons from './Coupons'; import Variants from './Variants'; import VariantInventory from './VariantInventory'; import InventoryManagement from './InventoryManagement'; import SkuField from './SkuField'; export default class extends BaseModal { constructor(options = {}) { if (!options.model) { throw new Error('Please provide a model.'); } const opts = { removeOnClose: true, ...options, }; super(opts); this.options = opts; // So the passed in modal does not get any un-saved data, // we'll clone and update it on sync this._origModel = this.model; this.model = this._origModel.clone(); this.listenTo(this.model, 'sync', () => { setTimeout(() => { if (this.createMode && !this.model.isNew()) { this.createMode = false; this.$('.js-listingHeading').text(app.polyglot.t('editListing.editListingLabel')); } const updatedData = this.model.toJSON(); // Will parse out some sku attributes that are specific to the variant // inventory view. updatedData.item.skus = updatedData.item.skus.map(sku => _.omit(sku, 'mappingId', 'choices')); if (updatedData.item.quantity === undefined) { this._origModel.get('item') .unset('quantity'); } if (updatedData.item.productID === undefined) { this._origModel.get('item') .unset('productID'); } this._origModel.set(updatedData); }); // A change event won't fire on a parent model if only nested attributes change. // The nested models would need to have change events manually bound to them // which is cumbersome with a model like this with so many levels of nesting. // If you are interested in any change on the model (as opposed to a sepcific // attribute), the simplest thing to do is use the 'saved' event from the // event emitter in models/listing/index.js. }); this.selectedNavTabIndex = 0; this.createMode = !(this.model.lastSyncedAttrs && this.model.lastSyncedAttrs.slug); this.photoUploads = []; this.images = this.model.get('item').get('images'); this.shippingOptions = this.model.get('shippingOptions'); this.shippingOptionViews = []; loadTemplate('modals/editListing/uploadPhoto.html', uploadT => (this.uploadPhotoT = uploadT)); this.listenTo(this.images, 'add', this.onAddImage); this.listenTo(this.images, 'remove', this.onRemoveImage); this.listenTo(this.shippingOptions, 'add', (shipOptMd) => { const shipOptVw = this.createShippingOptionView({ listPosition: this.shippingOptions.length, model: shipOptMd, }); this.shippingOptionViews.push(shipOptVw); this.$shippingOptionsWrap.append(shipOptVw.render().el); }); this.listenTo(this.shippingOptions, 'remove', (shipOptMd, shipOptCl, removeOpts) => { const [splicedVw] = this.shippingOptionViews.splice(removeOpts.index, 1); splicedVw.remove(); this.shippingOptionViews.slice(removeOpts.index) .forEach(shipOptVw => (shipOptVw.listPosition = shipOptVw.listPosition - 1)); }); this.listenTo(this.shippingOptions, 'update', (cl, updateOpts) => { if (!(updateOpts.changes.added.length || updateOpts.changes.removed.length)) { return; } this.$addShipOptSectionHeading .text(app.polyglot.t('editListing.shippingOptions.optionHeading', { listPosition: this.shippingOptions.length + 1 })); }); this.coupons = this.model.get('coupons'); this.listenTo(this.coupons, 'update', () => { if (this.coupons.length) { this.$couponsSection.addClass('expandedCouponView'); } else { this.$couponsSection.removeClass('expandedCouponView'); } }); this.variantOptionsCl = this.model.get('item') .get('options'); this.listenTo(this.variantOptionsCl, 'update', this.onUpdateVariantOptions); this.$el.on('scroll', () => { if (this.el.scrollTop > 57 && !this.$el.hasClass('fixedNav')) { this.$el.addClass('fixedNav'); } else if (this.el.scrollTop <= 57 && this.$el.hasClass('fixedNav')) { this.$el.removeClass('fixedNav'); } }); if (this.trackInventoryBy === 'DO_NOT_TRACK') { this.$el.addClass('notTrackingInventory'); } } className() { return `${super.className()} editListing tabbedModal modalScrollPage`; } events() { return { 'click .js-scrollLink': 'onScrollLinkClick', 'click .js-return': 'onClickReturn', 'click .js-save': 'onSaveClick', 'change #editContractType': 'onChangeContractType', 'change .js-price': 'onChangePrice', 'change #inputPhotoUpload': 'onChangePhotoUploadInput', 'click .js-addPhoto': 'onClickAddPhoto', 'click .js-removeImage': 'onClickRemoveImage', 'click .js-cancelPhotoUploads': 'onClickCancelPhotoUploads', 'click .js-addReturnPolicy': 'onClickAddReturnPolicy', 'click .js-addTermsAndConditions': 'onClickAddTermsAndConditions', 'click .js-addShippingOption': 'onClickAddShippingOption', 'click .js-btnAddCoupon': 'onClickAddCoupon', 'click .js-addFirstVariant': 'onClickAddFirstVariant', 'keyup .js-variantNameInput': 'onKeyUpVariantName', 'click .js-scrollToVariantInventory': 'onClickScrollToVariantInventory', ...super.events(), }; } get MAX_PHOTOS() { return this.model.get('item').max.images; } onClickReturn() { this.trigger('click-return', { view: this }); } onAddImage(image) { const imageHtml = this.uploadPhotoT({ closeIconClass: 'js-removeImage', ...image.toJSON(), }); this.$photoUploadItems.append(imageHtml); } onRemoveImage(image, images, options) { // 1 is added to the index to account for the .addElement this.$photoUploadItems.find('li') .eq(options.index + 1) .remove(); } onClickRemoveImage(e) { // since the first li is the .addElement, we need to subtract 1 from the index const removeIndex = $(e.target).parents('li').index() - 1; this.images.remove(this.images.at(removeIndex)); } onClickCancelPhotoUploads() { this.inProgressPhotoUploads.forEach(photoUpload => photoUpload.abort()); } onChangePrice(e) { const trimmedVal = $(e.target).val().trim(); const numericVal = Number(trimmedVal); if (!isNaN(numericVal) && trimmedVal) { $(e.target).val( formatPrice(numericVal, this.$currencySelect.val() === 'BTC') ); } else { $(e.target).val(trimmedVal); } this.variantInventory.render(); } onChangeContractType(e) { if (e.target.value !== 'PHYSICAL_GOOD') { this.$conditionWrap .add(this.$sectionShipping) .addClass('disabled'); } else { this.$conditionWrap .add(this.$sectionShipping) .removeClass('disabled'); } } getOrientation(file, callback) { const reader = new FileReader(); reader.onload = (e) => { const dataView = new DataView(e.target.result); // eslint-disable-line no-undef let offset = 2; if (dataView.getUint16(0, false) !== 0xFFD8) return callback(-2); while (offset < dataView.byteLength) { const marker = dataView.getUint16(offset, false); offset += 2; if (marker === 0xFFE1) { offset += 2; if (dataView.getUint32(offset, false) !== 0x45786966) { return callback(-1); } const little = dataView.getUint16(offset += 6, false) === 0x4949; offset += dataView.getUint32(offset + 4, little); const tags = dataView.getUint16(offset, little); offset += 2; for (let i = 0; i < tags; i++) { if (dataView.getUint16(offset + (i * 12), little) === 0x0112) { return callback(dataView.getUint16(offset + (i * 12) + 8, little)); } } } else if ((marker & 0xFF00) !== 0xFF00) { break; } else { offset += dataView.getUint16(offset, false); } } return callback(-1); }; reader.readAsArrayBuffer(file.slice(0, 64 * 1024)); } // todo: write a unit test for this truncateImageFilename(filename) { if (!filename || typeof filename !== 'string') { throw new Error('Please provide a filename as a string.'); } const truncated = filename; if (filename.length > Image.maxFilenameLength) { const parsed = path.parse(filename); const nameParseLen = Image.maxFilenameLength - parsed.ext.length; // acounting for rare edge case of the extension in and of itself // exceeding the max length return parsed.name.slice(0, nameParseLen < 0 ? 0 : nameParseLen) + parsed.ext.slice(0, Image.maxFilenameLength); } return truncated; } onChangePhotoUploadInput() { let photoFiles = Array.prototype.slice.call(this.$inputPhotoUpload[0].files, 0); // prune out any non-image files photoFiles = photoFiles.filter(file => file.type.startsWith('image')); this.$inputPhotoUpload.val(''); const currPhotoLength = this.model.get('item') .get('images') .length; if (currPhotoLength + photoFiles.length > this.MAX_PHOTOS) { photoFiles = photoFiles.slice(0, this.MAX_PHOTOS - currPhotoLength); new SimpleMessage({ title: app.polyglot.t('editListing.errors.tooManyPhotosTitle'), message: app.polyglot.t('editListing.errors.tooManyPhotosBody'), }) .render() .open(); } if (!photoFiles.length) return; this.$photoUploadingLabel.removeClass('hide'); const toUpload = []; let loaded = 0; let errored = 0; photoFiles.forEach(photoFile => { const newImage = document.createElement('img'); newImage.src = photoFile.path; newImage.onload = () => { const imgW = newImage.width; const imgH = newImage.height; const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); canvas.width = imgW; canvas.height = imgH; this.getOrientation(photoFile, (orientation) => { switch (orientation) { case 2: ctx.translate(imgW, 0); ctx.scale(-1, 1); break; case 3: ctx.translate(imgW, imgH); ctx.rotate(Math.PI); break; case 4: ctx.translate(0, imgH); ctx.scale(1, -1); break; case 5: ctx.rotate(0.5 * Math.PI); ctx.scale(1, -1); break; case 6: ctx.rotate(0.5 * Math.PI); ctx.translate(0, -imgH); break; case 7: ctx.rotate(0.5 * Math.PI); ctx.translate(imgW, -imgH); ctx.scale(-1, 1); break; case 8: ctx.rotate(-0.5 * Math.PI); ctx.translate(-imgW, 0); break; default: // do nothing } ctx.drawImage(newImage, 0, 0, imgW, imgH); toUpload.push({ filename: this.truncateImageFilename(photoFile.name), image: canvas.toDataURL('image/jpeg', 0.9) .replace(/^data:image\/(png|jpeg|webp);base64,/, ''), }); loaded += 1; if (loaded + errored === photoFiles.length) { this.uploadImages(toUpload); } }); }; newImage.onerror = () => { errored += 1; if (errored === photoFiles.length) { this.$photoUploadingLabel.addClass('hide'); new SimpleMessage({ title: app.polyglot.t('editListing.errors.unableToLoadImages', { smart_count: errored }), }) .render() .open(); } else if (loaded + errored === photoFiles.length) { this.uploadImages(toUpload); } }; }); } onClickAddReturnPolicy(e) { $(e.target).addClass('hide'); this.$editListingReturnPolicy.removeClass('hide') .focus(); this.expandedReturnPolicy = true; } onClickAddTermsAndConditions(e) { $(e.target).addClass('hide'); this.$editListingTermsAndConditions.removeClass('hide') .focus(); this.expandedTermsAndConditions = true; } onClickAddShippingOption() { this.shippingOptions .push(new ShippingOptionMd({ services: [ new Service(), ], })); } onClickAddCoupon() { this.coupons.add(new Coupon()); if (this.coupons.length === 1) { this.$couponsSection.find('.coupon input[name=title]') .focus(); } } onClickAddFirstVariant() { this.variantOptionsCl.add(new VariantOption()); if (this.variantOptionsCl.length === 1) { this.$variantsSection.find('.variant input[name=name]') .focus(); } } onKeyUpVariantName(e) { // wait until they stop typing if (this.variantNameKeyUpTimer) { clearTimeout(this.variantNameKeyUpTimer); } this.variantNameKeyUpTimer = setTimeout(() => { const index = $(e.target).closest('.variant') .index(); this.variantsView.setModelData(index); }, 150); } onVariantChoiceChange(e) { const index = this.variantsView.views .indexOf(e.view); this.variantsView.setModelData(index); } onUpdateVariantOptions() { if (this.variantOptionsCl.length) { this.$variantsSection.addClass('expandedVariantsView'); this.skuField.setState({ variantsPresent: true }); if (this.inventoryManagement.getState().trackBy !== 'DO_NOT_TRACK') { this.inventoryManagement.setState({ trackBy: 'TRACK_BY_VARIANT', }); } } else { this.$variantsSection.removeClass('expandedVariantsView'); this.skuField.setState({ variantsPresent: false }); if (this.inventoryManagement.getState().trackBy !== 'DO_NOT_TRACK') { this.inventoryManagement.setState({ trackBy: 'TRACK_BY_FIXED', }); } } this.$variantInventorySection.toggleClass('hide', !this.shouldShowVariantInventorySection); } onClickScrollToVariantInventory() { this.scrollTo(this.$variantInventorySection); } get shouldShowVariantInventorySection() { return !!this.variantOptionsCl.length; } /** * Will return true if we have at least one variant option with at least * one choice. */ get haveVariantOptionsWithChoice() { if (this.variantOptionsCl.length) { const atLeastOneHasChoice = this.variantOptionsCl.find(variantOption => { const choices = variantOption.get('variants'); return choices && choices.length; }); if (atLeastOneHasChoice) { return true; } } return false; } uploadImages(images) { let imagesToUpload = images; if (!images) { throw new Error('Please provide a list of images to upload.'); } if (typeof images === 'string') { imagesToUpload = [images]; } const upload = $.ajax({ url: app.getServerUrl('ob/images'), type: 'POST', data: JSON.stringify(imagesToUpload), dataType: 'json', contentType: 'application/json', }).always(() => { if (this.isRemoved()) return; if (!this.inProgressPhotoUploads.length) this.$photoUploadingLabel.addClass('hide'); }).done(uploadedImages => { if (this.isRemoved()) return; this.images.add(uploadedImages.map(image => ({ filename: image.filename, original: image.hashes.original, large: image.hashes.large, medium: image.hashes.medium, small: image.hashes.small, tiny: image.hashes.tiny, }))); }); this.photoUploads.push(upload); } get inProgressPhotoUploads() { return this.photoUploads .filter(upload => upload.state() === 'pending'); } onClickAddPhoto() { this.$inputPhotoUpload.trigger('click'); } scrollTo($el) { if (!$el) { throw new Error('Please provide a jQuery element to scroll to.'); } // Had this initially in Velocity, but after markup re-factor, it // doesn't work consistently, so we'll go old-school for now. this.$el .animate({ scrollTop: $el.position().top, }, { complete: () => { setTimeout( () => this.$el.on('scroll', this.throttledOnScroll), 100); }, }, 400); } onScrollLinkClick(e) { const index = $(e.target).index(); this.selectedNavTabIndex = index; this.$scrollLinks.removeClass('active'); $(e.target).addClass('active'); this.$el.off('scroll', this.throttledOnScroll); this.scrollTo(this.$scrollToSections.eq(index)); } onScroll() { let index = 0; let keepLooping = true; while (keepLooping) { if (isScrolledIntoView(this.$scrollToSections[index])) { this.$scrollLinks.removeClass('active'); this.$scrollLinks.eq(index).addClass('active'); this.selectedNavTabIndex = index; keepLooping = false; } else { if (index === this.$scrollToSections.length - 1) { keepLooping = false; } else { index += 1; } } } } onSaveClick() { const formData = this.getFormData(this.$formFields); const item = this.model.get('item'); this.$saveButton.addClass('disabled'); // set model / collection data for various child views this.shippingOptionViews.forEach((shipOptVw) => shipOptVw.setModelData()); this.variantsView.setCollectionData(); this.variantInventory.setCollectionData(); this.couponsView.setCollectionData(); if (item.get('options').length) { // If we have options, we shouldn't be providing a top-level quantity or // productID. item.unset('quantity'); item.unset('productID'); // If we have options and are not tracking inventory, we'll set the infiniteInventory // flag for any skus. if (this.trackInventoryBy === 'DO_NOT_TRACK') { item.get('skus') .forEach(sku => { sku.set('infiniteInventory', true); }); } } else if (this.trackInventoryBy === 'DO_NOT_TRACK') { // If we're not tracking inventory and don't have any variants, we should provide a top-level // quantity as -1, so it's considered infinite. formData.item.quantity = -1; } this.model.set(formData); // If the type is not 'PHYSICAL_GOOD', we'll clear out any shipping options. if (this.model.get('metadata').get('contractType') !== 'PHYSICAL_GOOD') { this.model.get('shippingOptions').reset(); } else { // If any shipping options have a type of 'LOCAL_PICKUP', we'll // clear out any services that may be there. this.model.get('shippingOptions').forEach(shipOpt => { if (shipOpt.get('type') === 'LOCAL_PICKUP') { shipOpt.set('services', []); } }); } const serverData = this.model.toJSON(); serverData.item.skus = serverData.item.skus.map(sku => ( // The variant inventory view adds some stuff to the skus collection that // shouldn't go to the server. We'll ensure the extraneous stuff isn't sent // with the save while still allowing it to stay in the collection. _.omit(sku, 'mappingId', 'choices') )); const save = this.model.save({}, { attrs: serverData, }); if (save) { const savingStatusMsg = app.statusBar.pushMessage({ msg: 'Saving listing...', type: 'message', duration: 99999999999999, }).on('clickViewListing', () => { const url = `#${app.profile.id}/store/${this.model.get('slug')}`; // This couldn't have been a simple href because that URL may already be the // page we're on, with the Listing Detail likely obscured by this modal. Since // the url wouldn't be changing, clicking that anchor would do nothing, hence // the use of loadUrl. Backbone.history.loadUrl(url); }); save.always(() => this.$saveButton.removeClass('disabled')) .fail((...args) => { savingStatusMsg.update({ msg: `Listing <em>${this.model.toJSON().item.title}</em> failed to save.`, type: 'warning', }); setTimeout(() => savingStatusMsg.remove(), 3000); new SimpleMessage({ title: app.polyglot.t('editListing.errors.saveErrorTitle'), message: args[0] && args[0].responseJSON && args[0].responseJSON.reason || '', }) .render() .open(); }).done(() => { savingStatusMsg.update(`Listing ${this.model.toJSON().item.title}` + ' saved. <a class="js-viewListing">view</a>'); setTimeout(() => savingStatusMsg.remove(), 6000); }); } else { // client side validation failed this.$saveButton.removeClass('disabled'); } // render so errrors are shown / cleared this.render(!!save); const $firstErr = this.$('.errorList:first'); if ($firstErr.length) $firstErr[0].scrollIntoViewIfNeeded(); } onChangeManagementType(e) { if (e.value === 'TRACK') { this.inventoryManagement.setState({ trackBy: this.model.get('item').get('options').length ? 'TRACK_BY_VARIANT' : 'TRACK_BY_FIXED', }); this.$el.removeClass('notTrackingInventory'); } else { this.inventoryManagement.setState({ trackBy: 'DO_NOT_TRACK', }); this.$el.addClass('notTrackingInventory'); } } get trackInventoryBy() { let trackBy; // If the inventoryManagement has been rendered, we'll let it's drop-down // determine whether we are tracking inventory. Otherwise, we'll get the info // form the model. if (this.inventoryManagement) { trackBy = this.inventoryManagement.getState().trackBy; } else { const item = this.model.get('item'); if (item.isInventoryTracked) { trackBy = item.get('options').length ? 'TRACK_BY_VARIANT' : 'TRACK_BY_FIXED'; } else { trackBy = 'DO_NOT_TRACK'; } } return trackBy; } get $scrollToSections() { return this._$scrollToSections || (this._$scrollToSections = this.$('.js-scrollToSection')); } get $scrollLinks() { return this._$scrollLinks || (this._$scrollLinks = this.$('.js-scrollLink')); } get $formFields() { const excludes = '.js-sectionShipping, .js-couponsSection, .js-variantsSection, ' + '.js-variantInventorySection'; return this._$formFields || (this._$formFields = this.$( `.js-formSectionsContainer > section:not(${excludes}) select[name],` + `.js-formSectionsContainer > section:not(${excludes}) input[name],` + `.js-formSectionsContainer > section:not(${excludes}) div[contenteditable][name],` + `.js-formSectionsContainer > section:not(${excludes}) ` + 'textarea[name]:not([class*="trumbowyg"])' )); } get $currencySelect() { return this._$currencySelect || (this._$currencySelect = this.$('#editListingCurrency')); } get $priceInput() { return this._$priceInput || (this._$priceInput = this.$('#editListingPrice')); } get $conditionWrap() { return this._$conditionWrap || (this._$conditionWrap = this.$('.js-conditionWrap')); } get $saveButton() { return this._$buttonSave || (this._$buttonSave = this.$('.js-save')); } get $inputPhotoUpload() { return this._$inputPhotoUpload || (this._$inputPhotoUpload = this.$('#inputPhotoUpload')); } get $photoUploadingLabel() { return this._$photoUploadingLabel || (this._$photoUploadingLabel = this.$('.js-photoUploadingLabel')); } get $editListingReturnPolicy() { return this._$editListingReturnPolicy || (this._$editListingReturnPolicy = this.$('#editListingReturnPolicy')); } get $editListingTermsAndConditions() { return this._$editListingTermsAndConditions || (this._$editListingTermsAndConditions = this.$('#editListingTermsAndConditions')); } get $sectionShipping() { return this._$sectionShipping || (this._$sectionShipping = this.$('.js-sectionShipping')); } get $maxCatsWarning() { return this._$maxCatsWarning || (this._$maxCatsWarning = this.$('.js-maxCatsWarning')); } get $maxTagsWarning() { return this._$maxTagsWarning || (this._$maxTagsWarning = this.$('.js-maxTagsWarning')); } get maxTagsWarning() { return `<div class="clrT2 tx5 row">${app.polyglot.t('editListing.maxTagsWarning')}</div>`; } get $addShipOptSectionHeading() { return this._$addShipOptSectionHeading || (this._$addShipOptSectionHeading = this.$('.js-addShipOptSectionHeading')); } get $variantInventorySection() { return this._$variantInventorySection || (this._$variantInventorySection = this.$('.js-variantInventorySection')); } get $itemPrice() { return this._$itemPrice || (this._$itemPrice = this.$('[name="item.price"]')); } showMaxTagsWarning() { this.$maxTagsWarning.empty() .append(this.maxTagsWarning); } hideMaxTagsWarning() { this.$maxTagsWarning.empty(); } get maxCatsWarning() { return `<div class="clrT2 tx5 row">${app.polyglot.t('editListing.maxCatsWarning')}</div>`; } showMaxCatsWarning() { this.$maxCatsWarning.empty() .append(this.maxCatsWarning); } hideMaxCatsWarning() { this.$maxCatsWarning.empty(); } // return the currency associated with this listing get currency() { return (this.$currencySelect.length ? this.$currencySelect.val() : this.model.get('metadata').get('pricingCurrency') || app.settings.get('localCurrency')); } createShippingOptionView(opts) { const options = { getCurrency: () => (this.$currencySelect.length ? this.$currencySelect.val() : this.model.get('metadata').pricingCurrency), ...opts || {}, }; const view = this.createChild(ShippingOption, options); this.listenTo(view, 'click-remove', e => { this.shippingOptions.remove( this.shippingOptions.at(this.shippingOptionViews.indexOf(e.view))); }); return view; } remove() { this.inProgressPhotoUploads.forEach(upload => upload.abort()); $(window).off('resize', this.throttledResizeWin); super.remove(); } render(restoreScrollPos = true) { let prevScrollPos = 0; const item = this.model.get('item'); if (restoreScrollPos) { prevScrollPos = this.el.scrollTop; } if (this.throttledOnScroll) this.$el.off('scroll', this.throttledOnScroll); this.currencies = this.currencies || getCurrenciesSortedByCode(); loadTemplate('modals/editListing/editListing.html', t => { this.$el.html(t({ createMode: this.createMode, selectedNavTabIndex: this.selectedNavTabIndex, returnText: this.options.returnText, currency: this.currency, currencies: this.currencies, contractTypes: this.model.get('metadata') .contractTypes .map((contractType) => ({ code: contractType, name: app.polyglot.t(`formats.${contractType}`) })), conditionTypes: this.model.get('item') .conditionTypes .map((conditionType) => ({ code: conditionType, name: app.polyglot.t(`conditionTypes.${conditionType}`) })), errors: this.model.validationError || {}, photoUploadInprogress: !!this.inProgressPhotoUploads.length, uploadPhotoT: this.uploadPhotoT, expandedReturnPolicy: this.expandedReturnPolicy || !!this.model.get('refundPolicy'), expandedTermsAndConditions: this.expandedTermsAndConditions || !!this.model.get('termsAndConditions'), formatPrice, maxCatsWarning: this.maxCatsWarning, maxTagsWarning: this.maxTagsWarning, max: { title: item.max.titleLength, cats: item.max.cats, tags: item.max.tags, photos: this.MAX_PHOTOS, }, shouldShowVariantInventorySection: this.shouldShowVariantInventorySection, ...this.model.toJSON(), })); super.render(); this.$editListingTags = this.$('#editListingTags'); this.$editListingTagsPlaceholder = this.$('#editListingTagsPlaceholder'); this.$editListingCategories = this.$('#editListingCategories'); this.$editListingCategoriesPlaceholder = this.$('#editListingCategoriesPlaceholder'); this.$editListingVariantsChoices = this.$('#editListingVariantsChoices'); this.$editListingVariantsChoicesPlaceholder = this.$('#editListingVariantsChoicesPlaceholder'); this.$shippingOptionsWrap = this.$('.js-shippingOptionsWrap'); this.$couponsSection = this.$('.js-couponsSection'); this.$variantsSection = this.$('.js-variantsSection'); this.$('#editContractType, #editListingVisibility, #editListingCondition').select2({ // disables the search box minimumResultsForSearch: Infinity, }); this.$('#editListingCurrency').select2() .on('change', () => this.variantInventory.render()); this.$editListingTags.select2({ multiple: true, tags: true, selectOnClose: true, tokenSeparators: [','], // *** // placeholder has issue where it won't show initially, will use // own element for this instead // placeholder: 'Enter tags... (and translate me)', // *** // dropdownParent needed to fully hide dropdown dropdownParent: this.$('#editListingTagsDropdown'), createTag: (params) => { let term = params.term; if (term === '') { return null; // don't add blank tags triggered by blur } // we'll make the tag all lowercase and // replace spaces with dashes. term = term.toLowerCase() .replace(/\s/g, '-') .replace('#', '') // replace consecutive dashes with one .replace(/-{2,}/g, '-'); return { id: term, text: term, }; }, // This is necessary, otherwise partial matches of existing tags are // prevented. E,G. If you have a tag of hello-world, hello would be prevented // as a tag because select2 would match hellow-world in the hidden dropdown // and think you are selecting that. matcher: () => false, }).on('change', () => { const tags = this.$editListingTags.val(); this.model.get('item').set('tags', tags); this.$editListingTagsPlaceholder[tags.length ? 'removeClass' : 'addClass']('emptyOfTags'); if (tags.length >= item.maxTags) { this.showMaxTagsWarning(); } else { this.hideMaxTagsWarning(); } }).on('select2:selecting', (e) => { if (this.$editListingTags.val().length >= item.maxTags) { this.$maxTagsWarning.velocity('callout.flash', { duration: 500 }); e.preventDefault(); } }) .next() .find('.select2-search__field') .attr('maxLength', item.max.tagLength); this.$editListingTagsPlaceholder[ this.$editListingTags.val().length ? 'removeClass' : 'addClass' ]('emptyOfTags'); this.$editListingCategories.select2({ multiple: true, tags: true, selectOnClose: true, tokenSeparators: [','], // dropdownParent needed to fully hide dropdown dropdownParent: this.$('#editListingCategoriesDropdown'), // This is necessary, see comment in select2 for tags above. matcher: () => false, }).on('change', () => { const count = this.$editListingCategories.val().length; this.$editListingCategoriesPlaceholder[ count ? 'removeClass' : 'addClass' ]('emptyOfTags'); if (count >= item.maxCategories) { this.showMaxCatsWarning(); } else { this.hideMaxCatsWarning(); } }).on('select2:selecting', (e) => { if (this.$editListingCategories.val().length >= item.maxCategories) { this.$maxCatsWarning.velocity('callout.flash', { duration: 500 }); e.preventDefault(); } }); this.$editListingCategoriesPlaceholder[ this.$editListingCategories.val().length ? 'removeClass' : 'addClass' ]('emptyOfTags'); // render shipping options this.shippingOptionViews.forEach((shipOptVw) => shipOptVw.remove()); this.shippingOptionViews = []; const shipOptsFrag = document.createDocumentFragment(); this.model.get('shippingOptions').forEach((shipOpt, shipOptIndex) => { const shipOptVw = this.createShippingOptionView({ model: shipOpt, listPosition: shipOptIndex + 1, }); this.shippingOptionViews.push(shipOptVw); shipOptVw.render().$el.appendTo(shipOptsFrag); }); this.$shippingOptionsWrap.append(shipOptsFrag); // render sku field if (this.skuField) this.skuField.remove(); this.skuField = this.createChild(SkuField, { model: item, initialState: { variantsPresent: !!item.get('options').length, }, }); this.$('.js-skuFieldContainer').html(this.skuField.render().el); // render variants if (this.variantsView) this.variantsView.remove(); const variantErrors = {}; Object.keys(item.validationError || {}) .forEach(errKey => { if (errKey.startsWith('options[')) { variantErrors[errKey] = item.validationError[errKey]; } }); this.variantsView = this.createChild(Variants, { collection: this.variantOptionsCl, maxVariantCount: item.max.optionCount, errors: variantErrors, }); this.variantsView.listenTo(this.variantsView, 'variantChoiceChange', this.onVariantChoiceChange.bind(this)); this.$variantsSection.find('.js-variantsContainer').append( this.variantsView.render().el ); // render inventory management section if (this.inventoryManagement) this.inventoryManagement.remove(); const inventoryManagementErrors = {}; if (this.model.validationError && this.model.validationError['item.quantity']) { inventoryManagementErrors.quantity = this.model.validationError['item.quantity']; } this.inventoryManagement = this.createChild(InventoryManagement, { initialState: { trackBy: this.trackInventoryBy, quantity: item.get('quantity'), errors: inventoryManagementErrors, }, }); this.$('.js-inventoryManagementSection').html(this.inventoryManagement.render().el); this.listenTo(this.inventoryManagement, 'changeManagementType', this.onChangeManagementType); // render variant inventory if (this.variantInventory) this.variantInventory.remove(); this.variantInventory = this.createChild(VariantInventory, { collection: item.get('skus'), optionsCl: item.get('options'), getPrice: () => this.getFormData(this.$itemPrice).item.price, getCurrency: () => this.currency, }); this.$('.js-variantInventoryTableContainer') .html(this.variantInventory.render().el); // render coupons if (this.couponsView) this.couponsView.remove(); const couponErrors = {}; Object.keys(this.model.validationError || {}) .forEach(errKey => { if (errKey.startsWith('coupons[')) { couponErrors[errKey] = this.model.validationError[errKey]; } }); this.couponsView = this.createChild(Coupons, { collection: this.coupons, maxCouponCount: this.model.max.couponCount, couponErrors, }); this.$couponsSection.find('.js-couponsContainer').append( this.couponsView.render().el ); this._$scrollLinks = null; this._$scrollToSections = null; this._$formFields = null; this._$currencySelect = null; this._$priceInput = null; this._$conditionWrap = null; this._$buttonSave = null; this._$inputPhotoUpload = null; this._$photoUploadingLabel = null; this._$editListingReturnPolicy = null; this._$editListingTermsAndConditions = null; this._$sectionShipping = null; this._$maxCatsWarning = null; this._$maxTagsWarning = null; this._$addShipOptSectionHeading = null; this._$variantInventorySection = null; this._$itemPrice = null; this.$photoUploadItems = this.$('.js-photoUploadItems'); this.$modalContent = this.$('.modalContent'); this.$tabControls = this.$('.tabControls'); this.$titleInput = this.$('#editListingTitle'); installRichEditor(this.$('#editListingDescription'), { topLevelClass: 'clrBr', }); if (this.sortablePhotos) this.sortablePhotos.destroy(); this.sortablePhotos = Sortable.create(this.$photoUploadItems[0], { filter: '.js-addPhotoWrap', onUpdate: (e) => { const imageModels = this.model .get('item') .get('images') .models; const movingModel = imageModels[e.oldIndex - 1]; imageModels.splice(e.oldIndex - 1, 1); imageModels.splice(e.newIndex - 1, 0, movingModel); }, onMove: (e) => ($(e.related).hasClass('js-addPhotoWrap') ? false : undefined), }); setTimeout(() => { if (!this.rendered) { this.rendered = true; this.$titleInput.focus(); } }); setTimeout(() => { // restore the scroll position if (restoreScrollPos) { this.el.scrollTop = prevScrollPos; } this.throttledOnScroll = _.bind(_.throttle(this.onScroll, 100), this); setTimeout(() => this.$el.on('scroll', this.throttledOnScroll), 100); }); }); return this; } }
js/views/modals/editListing/EditListing.js
import $ from 'jquery'; import '../../../utils/velocity'; import '../../../lib/select2'; import Sortable from 'sortablejs'; import _ from 'underscore'; import path from 'path'; import '../../../utils/velocityUiPack.js'; import Backbone from 'backbone'; import { isScrolledIntoView } from '../../../utils/dom'; import { installRichEditor } from '../../../utils/trumbowyg'; import { getCurrenciesSortedByCode } from '../../../data/currencies'; import { formatPrice } from '../../../utils/currency'; import SimpleMessage from '../SimpleMessage'; import loadTemplate from '../../../utils/loadTemplate'; import ShippingOptionMd from '../../../models/listing/ShippingOption'; import Service from '../../../models/listing/Service'; import Image from '../../../models/listing/Image'; import Coupon from '../../../models/listing/Coupon'; import VariantOption from '../../../models/listing/VariantOption'; import app from '../../../app'; import BaseModal from '../BaseModal'; import ShippingOption from './ShippingOption'; import Coupons from './Coupons'; import Variants from './Variants'; import VariantInventory from './VariantInventory'; import InventoryManagement from './InventoryManagement'; import SkuField from './SkuField'; export default class extends BaseModal { constructor(options = {}) { if (!options.model) { throw new Error('Please provide a model.'); } const opts = { removeOnClose: true, ...options, }; super(opts); this.options = opts; // So the passed in modal does not get any un-saved data, // we'll clone and update it on sync this._origModel = this.model; this.model = this._origModel.clone(); console.log('sugar'); window.sugar = this.model; this.listenTo(this.model, 'sync', () => { setTimeout(() => { if (this.createMode && !this.model.isNew()) { this.createMode = false; this.$('.js-listingHeading').text(app.polyglot.t('editListing.editListingLabel')); } const updatedData = this.model.toJSON(); // Will parse out some sku attributes that are specific to the variant // inventory view. updatedData.item.skus = updatedData.item.skus.map(sku => _.omit(sku, 'mappingId', 'choices')); if (updatedData.item.quantity === undefined) { this._origModel.get('item') .unset('quantity'); } if (updatedData.item.productID === undefined) { this._origModel.get('item') .unset('productID'); } this._origModel.set(updatedData); }); // A change event won't fire on a parent model if only nested attributes change. // The nested models would need to have change events manually bound to them // which is cumbersome with a model like this with so many levels of nesting. // If you are interested in any change on the model (as opposed to a sepcific // attribute), the simplest thing to do is use the 'saved' event from the // event emitter in models/listing/index.js. }); this.selectedNavTabIndex = 0; this.createMode = !(this.model.lastSyncedAttrs && this.model.lastSyncedAttrs.slug); this.photoUploads = []; this.images = this.model.get('item').get('images'); this.shippingOptions = this.model.get('shippingOptions'); this.shippingOptionViews = []; loadTemplate('modals/editListing/uploadPhoto.html', uploadT => (this.uploadPhotoT = uploadT)); this.listenTo(this.images, 'add', this.onAddImage); this.listenTo(this.images, 'remove', this.onRemoveImage); this.listenTo(this.shippingOptions, 'add', (shipOptMd) => { const shipOptVw = this.createShippingOptionView({ listPosition: this.shippingOptions.length, model: shipOptMd, }); this.shippingOptionViews.push(shipOptVw); this.$shippingOptionsWrap.append(shipOptVw.render().el); }); this.listenTo(this.shippingOptions, 'remove', (shipOptMd, shipOptCl, removeOpts) => { const [splicedVw] = this.shippingOptionViews.splice(removeOpts.index, 1); splicedVw.remove(); this.shippingOptionViews.slice(removeOpts.index) .forEach(shipOptVw => (shipOptVw.listPosition = shipOptVw.listPosition - 1)); }); this.listenTo(this.shippingOptions, 'update', (cl, updateOpts) => { if (!(updateOpts.changes.added.length || updateOpts.changes.removed.length)) { return; } this.$addShipOptSectionHeading .text(app.polyglot.t('editListing.shippingOptions.optionHeading', { listPosition: this.shippingOptions.length + 1 })); }); this.coupons = this.model.get('coupons'); this.listenTo(this.coupons, 'update', () => { if (this.coupons.length) { this.$couponsSection.addClass('expandedCouponView'); } else { this.$couponsSection.removeClass('expandedCouponView'); } }); this.variantOptionsCl = this.model.get('item') .get('options'); this.listenTo(this.variantOptionsCl, 'update', this.onUpdateVariantOptions); this.$el.on('scroll', () => { if (this.el.scrollTop > 57 && !this.$el.hasClass('fixedNav')) { this.$el.addClass('fixedNav'); } else if (this.el.scrollTop <= 57 && this.$el.hasClass('fixedNav')) { this.$el.removeClass('fixedNav'); } }); if (this.trackInventoryBy === 'DO_NOT_TRACK') { this.$el.addClass('notTrackingInventory'); } } className() { return `${super.className()} editListing tabbedModal modalScrollPage`; } events() { return { 'click .js-scrollLink': 'onScrollLinkClick', 'click .js-return': 'onClickReturn', 'click .js-save': 'onSaveClick', 'change #editContractType': 'onChangeContractType', 'change .js-price': 'onChangePrice', 'change #inputPhotoUpload': 'onChangePhotoUploadInput', 'click .js-addPhoto': 'onClickAddPhoto', 'click .js-removeImage': 'onClickRemoveImage', 'click .js-cancelPhotoUploads': 'onClickCancelPhotoUploads', 'click .js-addReturnPolicy': 'onClickAddReturnPolicy', 'click .js-addTermsAndConditions': 'onClickAddTermsAndConditions', 'click .js-addShippingOption': 'onClickAddShippingOption', 'click .js-btnAddCoupon': 'onClickAddCoupon', 'click .js-addFirstVariant': 'onClickAddFirstVariant', 'keyup .js-variantNameInput': 'onKeyUpVariantName', 'click .js-scrollToVariantInventory': 'onClickScrollToVariantInventory', ...super.events(), }; } get MAX_PHOTOS() { return this.model.get('item').max.images; } onClickReturn() { this.trigger('click-return', { view: this }); } onAddImage(image) { const imageHtml = this.uploadPhotoT({ closeIconClass: 'js-removeImage', ...image.toJSON(), }); this.$photoUploadItems.append(imageHtml); } onRemoveImage(image, images, options) { // 1 is added to the index to account for the .addElement this.$photoUploadItems.find('li') .eq(options.index + 1) .remove(); } onClickRemoveImage(e) { // since the first li is the .addElement, we need to subtract 1 from the index const removeIndex = $(e.target).parents('li').index() - 1; this.images.remove(this.images.at(removeIndex)); } onClickCancelPhotoUploads() { this.inProgressPhotoUploads.forEach(photoUpload => photoUpload.abort()); } onChangePrice(e) { const trimmedVal = $(e.target).val().trim(); const numericVal = Number(trimmedVal); if (!isNaN(numericVal) && trimmedVal) { $(e.target).val( formatPrice(numericVal, this.$currencySelect.val() === 'BTC') ); } else { $(e.target).val(trimmedVal); } this.variantInventory.render(); } onChangeContractType(e) { if (e.target.value !== 'PHYSICAL_GOOD') { this.$conditionWrap .add(this.$sectionShipping) .addClass('disabled'); } else { this.$conditionWrap .add(this.$sectionShipping) .removeClass('disabled'); } } getOrientation(file, callback) { const reader = new FileReader(); reader.onload = (e) => { const dataView = new DataView(e.target.result); // eslint-disable-line no-undef let offset = 2; if (dataView.getUint16(0, false) !== 0xFFD8) return callback(-2); while (offset < dataView.byteLength) { const marker = dataView.getUint16(offset, false); offset += 2; if (marker === 0xFFE1) { offset += 2; if (dataView.getUint32(offset, false) !== 0x45786966) { return callback(-1); } const little = dataView.getUint16(offset += 6, false) === 0x4949; offset += dataView.getUint32(offset + 4, little); const tags = dataView.getUint16(offset, little); offset += 2; for (let i = 0; i < tags; i++) { if (dataView.getUint16(offset + (i * 12), little) === 0x0112) { return callback(dataView.getUint16(offset + (i * 12) + 8, little)); } } } else if ((marker & 0xFF00) !== 0xFF00) { break; } else { offset += dataView.getUint16(offset, false); } } return callback(-1); }; reader.readAsArrayBuffer(file.slice(0, 64 * 1024)); } // todo: write a unit test for this truncateImageFilename(filename) { if (!filename || typeof filename !== 'string') { throw new Error('Please provide a filename as a string.'); } const truncated = filename; if (filename.length > Image.maxFilenameLength) { const parsed = path.parse(filename); const nameParseLen = Image.maxFilenameLength - parsed.ext.length; // acounting for rare edge case of the extension in and of itself // exceeding the max length return parsed.name.slice(0, nameParseLen < 0 ? 0 : nameParseLen) + parsed.ext.slice(0, Image.maxFilenameLength); } return truncated; } onChangePhotoUploadInput() { let photoFiles = Array.prototype.slice.call(this.$inputPhotoUpload[0].files, 0); // prune out any non-image files photoFiles = photoFiles.filter(file => file.type.startsWith('image')); this.$inputPhotoUpload.val(''); const currPhotoLength = this.model.get('item') .get('images') .length; if (currPhotoLength + photoFiles.length > this.MAX_PHOTOS) { photoFiles = photoFiles.slice(0, this.MAX_PHOTOS - currPhotoLength); new SimpleMessage({ title: app.polyglot.t('editListing.errors.tooManyPhotosTitle'), message: app.polyglot.t('editListing.errors.tooManyPhotosBody'), }) .render() .open(); } if (!photoFiles.length) return; this.$photoUploadingLabel.removeClass('hide'); const toUpload = []; let loaded = 0; let errored = 0; photoFiles.forEach(photoFile => { const newImage = document.createElement('img'); newImage.src = photoFile.path; newImage.onload = () => { const imgW = newImage.width; const imgH = newImage.height; const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); canvas.width = imgW; canvas.height = imgH; this.getOrientation(photoFile, (orientation) => { switch (orientation) { case 2: ctx.translate(imgW, 0); ctx.scale(-1, 1); break; case 3: ctx.translate(imgW, imgH); ctx.rotate(Math.PI); break; case 4: ctx.translate(0, imgH); ctx.scale(1, -1); break; case 5: ctx.rotate(0.5 * Math.PI); ctx.scale(1, -1); break; case 6: ctx.rotate(0.5 * Math.PI); ctx.translate(0, -imgH); break; case 7: ctx.rotate(0.5 * Math.PI); ctx.translate(imgW, -imgH); ctx.scale(-1, 1); break; case 8: ctx.rotate(-0.5 * Math.PI); ctx.translate(-imgW, 0); break; default: // do nothing } ctx.drawImage(newImage, 0, 0, imgW, imgH); toUpload.push({ filename: this.truncateImageFilename(photoFile.name), image: canvas.toDataURL('image/jpeg', 0.9) .replace(/^data:image\/(png|jpeg|webp);base64,/, ''), }); loaded += 1; if (loaded + errored === photoFiles.length) { this.uploadImages(toUpload); } }); }; newImage.onerror = () => { errored += 1; if (errored === photoFiles.length) { this.$photoUploadingLabel.addClass('hide'); new SimpleMessage({ title: app.polyglot.t('editListing.errors.unableToLoadImages', { smart_count: errored }), }) .render() .open(); } else if (loaded + errored === photoFiles.length) { this.uploadImages(toUpload); } }; }); } onClickAddReturnPolicy(e) { $(e.target).addClass('hide'); this.$editListingReturnPolicy.removeClass('hide') .focus(); this.expandedReturnPolicy = true; } onClickAddTermsAndConditions(e) { $(e.target).addClass('hide'); this.$editListingTermsAndConditions.removeClass('hide') .focus(); this.expandedTermsAndConditions = true; } onClickAddShippingOption() { this.shippingOptions .push(new ShippingOptionMd({ services: [ new Service(), ], })); } onClickAddCoupon() { this.coupons.add(new Coupon()); if (this.coupons.length === 1) { this.$couponsSection.find('.coupon input[name=title]') .focus(); } } onClickAddFirstVariant() { this.variantOptionsCl.add(new VariantOption()); if (this.variantOptionsCl.length === 1) { this.$variantsSection.find('.variant input[name=name]') .focus(); } } onKeyUpVariantName(e) { // wait until they stop typing if (this.variantNameKeyUpTimer) { clearTimeout(this.variantNameKeyUpTimer); } this.variantNameKeyUpTimer = setTimeout(() => { const index = $(e.target).closest('.variant') .index(); this.variantsView.setModelData(index); }, 150); } onVariantChoiceChange(e) { const index = this.variantsView.views .indexOf(e.view); this.variantsView.setModelData(index); } onUpdateVariantOptions() { if (this.variantOptionsCl.length) { this.$variantsSection.addClass('expandedVariantsView'); this.skuField.setState({ variantsPresent: true }); if (this.inventoryManagement.getState().trackBy !== 'DO_NOT_TRACK') { this.inventoryManagement.setState({ trackBy: 'TRACK_BY_VARIANT', }); } } else { this.$variantsSection.removeClass('expandedVariantsView'); this.skuField.setState({ variantsPresent: false }); if (this.inventoryManagement.getState().trackBy !== 'DO_NOT_TRACK') { this.inventoryManagement.setState({ trackBy: 'TRACK_BY_FIXED', }); } } this.$variantInventorySection.toggleClass('hide', !this.shouldShowVariantInventorySection); } onClickScrollToVariantInventory() { this.scrollTo(this.$variantInventorySection); } get shouldShowVariantInventorySection() { return !!this.variantOptionsCl.length; } /** * Will return true if we have at least one variant option with at least * one choice. */ get haveVariantOptionsWithChoice() { if (this.variantOptionsCl.length) { const atLeastOneHasChoice = this.variantOptionsCl.find(variantOption => { const choices = variantOption.get('variants'); return choices && choices.length; }); if (atLeastOneHasChoice) { return true; } } return false; } uploadImages(images) { let imagesToUpload = images; if (!images) { throw new Error('Please provide a list of images to upload.'); } if (typeof images === 'string') { imagesToUpload = [images]; } const upload = $.ajax({ url: app.getServerUrl('ob/images'), type: 'POST', data: JSON.stringify(imagesToUpload), dataType: 'json', contentType: 'application/json', }).always(() => { if (this.isRemoved()) return; if (!this.inProgressPhotoUploads.length) this.$photoUploadingLabel.addClass('hide'); }).done(uploadedImages => { if (this.isRemoved()) return; this.images.add(uploadedImages.map(image => ({ filename: image.filename, original: image.hashes.original, large: image.hashes.large, medium: image.hashes.medium, small: image.hashes.small, tiny: image.hashes.tiny, }))); }); this.photoUploads.push(upload); } get inProgressPhotoUploads() { return this.photoUploads .filter(upload => upload.state() === 'pending'); } onClickAddPhoto() { this.$inputPhotoUpload.trigger('click'); } scrollTo($el) { if (!$el) { throw new Error('Please provide a jQuery element to scroll to.'); } // Had this initially in Velocity, but after markup re-factor, it // doesn't work consistently, so we'll go old-school for now. this.$el .animate({ scrollTop: $el.position().top, }, { complete: () => { setTimeout( () => this.$el.on('scroll', this.throttledOnScroll), 100); }, }, 400); } onScrollLinkClick(e) { const index = $(e.target).index(); this.selectedNavTabIndex = index; this.$scrollLinks.removeClass('active'); $(e.target).addClass('active'); this.$el.off('scroll', this.throttledOnScroll); this.scrollTo(this.$scrollToSections.eq(index)); } onScroll() { let index = 0; let keepLooping = true; while (keepLooping) { if (isScrolledIntoView(this.$scrollToSections[index])) { this.$scrollLinks.removeClass('active'); this.$scrollLinks.eq(index).addClass('active'); this.selectedNavTabIndex = index; keepLooping = false; } else { if (index === this.$scrollToSections.length - 1) { keepLooping = false; } else { index += 1; } } } } onSaveClick() { const formData = this.getFormData(this.$formFields); const item = this.model.get('item'); this.$saveButton.addClass('disabled'); // set model / collection data for various child views this.shippingOptionViews.forEach((shipOptVw) => shipOptVw.setModelData()); this.variantsView.setCollectionData(); this.variantInventory.setCollectionData(); this.couponsView.setCollectionData(); if (item.get('options').length) { // If we have options, we shouldn't be providing a top-level quantity or // productID. item.unset('quantity'); item.unset('productID'); // If we have options and are not tracking inventory, we'll set the infiniteInventory // flag for any skus. if (this.trackInventoryBy === 'DO_NOT_TRACK') { item.get('skus') .forEach(sku => { sku.set('infiniteInventory', true); }); } } else if (this.trackInventoryBy === 'DO_NOT_TRACK') { // If we're not tracking inventory and don't have any variants, we should provide a top-level // quantity as -1, so it's considered infinite. formData.item.quantity = -1; } this.model.set(formData); // If the type is not 'PHYSICAL_GOOD', we'll clear out any shipping options. if (this.model.get('metadata').get('contractType') !== 'PHYSICAL_GOOD') { this.model.get('shippingOptions').reset(); } else { // If any shipping options have a type of 'LOCAL_PICKUP', we'll // clear out any services that may be there. this.model.get('shippingOptions').forEach(shipOpt => { if (shipOpt.get('type') === 'LOCAL_PICKUP') { shipOpt.set('services', []); } }); } const serverData = this.model.toJSON(); serverData.item.skus = serverData.item.skus.map(sku => ( // The variant inventory view adds some stuff to the skus collection that // shouldn't go to the server. We'll ensure the extraneous stuff isn't sent // with the save while still allowing it to stay in the collection. _.omit(sku, 'mappingId', 'choices') )); const save = this.model.save({}, { attrs: serverData, }); if (save) { const savingStatusMsg = app.statusBar.pushMessage({ msg: 'Saving listing...', type: 'message', duration: 99999999999999, }).on('clickViewListing', () => { const url = `#${app.profile.id}/store/${this.model.get('slug')}`; // This couldn't have been a simple href because that URL may already be the // page we're on, with the Listing Detail likely obscured by this modal. Since // the url wouldn't be changing, clicking that anchor would do nothing, hence // the use of loadUrl. Backbone.history.loadUrl(url); }); save.always(() => this.$saveButton.removeClass('disabled')) .fail((...args) => { savingStatusMsg.update({ msg: `Listing <em>${this.model.toJSON().item.title}</em> failed to save.`, type: 'warning', }); setTimeout(() => savingStatusMsg.remove(), 3000); new SimpleMessage({ title: app.polyglot.t('editListing.errors.saveErrorTitle'), message: args[0] && args[0].responseJSON && args[0].responseJSON.reason || '', }) .render() .open(); }).done(() => { savingStatusMsg.update(`Listing ${this.model.toJSON().item.title}` + ' saved. <a class="js-viewListing">view</a>'); setTimeout(() => savingStatusMsg.remove(), 6000); }); } else { // client side validation failed this.$saveButton.removeClass('disabled'); } // render so errrors are shown / cleared this.render(!!save); const $firstErr = this.$('.errorList:first'); if ($firstErr.length) $firstErr[0].scrollIntoViewIfNeeded(); } onChangeManagementType(e) { if (e.value === 'TRACK') { this.inventoryManagement.setState({ trackBy: this.model.get('item').get('options').length ? 'TRACK_BY_VARIANT' : 'TRACK_BY_FIXED', }); this.$el.removeClass('notTrackingInventory'); } else { this.inventoryManagement.setState({ trackBy: 'DO_NOT_TRACK', }); this.$el.addClass('notTrackingInventory'); } } get trackInventoryBy() { let trackBy; // If the inventoryManagement has been rendered, we'll let it's drop-down // determine whether we are tracking inventory. Otherwise, we'll get the info // form the model. if (this.inventoryManagement) { trackBy = this.inventoryManagement.getState().trackBy; } else { const item = this.model.get('item'); if (item.isInventoryTracked) { trackBy = item.get('options').length ? 'TRACK_BY_VARIANT' : 'TRACK_BY_FIXED'; } else { trackBy = 'DO_NOT_TRACK'; } } return trackBy; } get $scrollToSections() { return this._$scrollToSections || (this._$scrollToSections = this.$('.js-scrollToSection')); } get $scrollLinks() { return this._$scrollLinks || (this._$scrollLinks = this.$('.js-scrollLink')); } get $formFields() { const excludes = '.js-sectionShipping, .js-couponsSection, .js-variantsSection, ' + '.js-variantInventorySection'; return this._$formFields || (this._$formFields = this.$( `.js-formSectionsContainer > section:not(${excludes}) select[name],` + `.js-formSectionsContainer > section:not(${excludes}) input[name],` + `.js-formSectionsContainer > section:not(${excludes}) div[contenteditable][name],` + `.js-formSectionsContainer > section:not(${excludes}) ` + 'textarea[name]:not([class*="trumbowyg"])' )); } get $currencySelect() { return this._$currencySelect || (this._$currencySelect = this.$('#editListingCurrency')); } get $priceInput() { return this._$priceInput || (this._$priceInput = this.$('#editListingPrice')); } get $conditionWrap() { return this._$conditionWrap || (this._$conditionWrap = this.$('.js-conditionWrap')); } get $saveButton() { return this._$buttonSave || (this._$buttonSave = this.$('.js-save')); } get $inputPhotoUpload() { return this._$inputPhotoUpload || (this._$inputPhotoUpload = this.$('#inputPhotoUpload')); } get $photoUploadingLabel() { return this._$photoUploadingLabel || (this._$photoUploadingLabel = this.$('.js-photoUploadingLabel')); } get $editListingReturnPolicy() { return this._$editListingReturnPolicy || (this._$editListingReturnPolicy = this.$('#editListingReturnPolicy')); } get $editListingTermsAndConditions() { return this._$editListingTermsAndConditions || (this._$editListingTermsAndConditions = this.$('#editListingTermsAndConditions')); } get $sectionShipping() { return this._$sectionShipping || (this._$sectionShipping = this.$('.js-sectionShipping')); } get $maxCatsWarning() { return this._$maxCatsWarning || (this._$maxCatsWarning = this.$('.js-maxCatsWarning')); } get $maxTagsWarning() { return this._$maxTagsWarning || (this._$maxTagsWarning = this.$('.js-maxTagsWarning')); } get maxTagsWarning() { return `<div class="clrT2 tx5 row">${app.polyglot.t('editListing.maxTagsWarning')}</div>`; } get $addShipOptSectionHeading() { return this._$addShipOptSectionHeading || (this._$addShipOptSectionHeading = this.$('.js-addShipOptSectionHeading')); } get $variantInventorySection() { return this._$variantInventorySection || (this._$variantInventorySection = this.$('.js-variantInventorySection')); } get $itemPrice() { return this._$itemPrice || (this._$itemPrice = this.$('[name="item.price"]')); } showMaxTagsWarning() { this.$maxTagsWarning.empty() .append(this.maxTagsWarning); } hideMaxTagsWarning() { this.$maxTagsWarning.empty(); } get maxCatsWarning() { return `<div class="clrT2 tx5 row">${app.polyglot.t('editListing.maxCatsWarning')}</div>`; } showMaxCatsWarning() { this.$maxCatsWarning.empty() .append(this.maxCatsWarning); } hideMaxCatsWarning() { this.$maxCatsWarning.empty(); } // return the currency associated with this listing get currency() { return (this.$currencySelect.length ? this.$currencySelect.val() : this.model.get('metadata').get('pricingCurrency') || app.settings.get('localCurrency')); } createShippingOptionView(opts) { const options = { getCurrency: () => (this.$currencySelect.length ? this.$currencySelect.val() : this.model.get('metadata').pricingCurrency), ...opts || {}, }; const view = this.createChild(ShippingOption, options); this.listenTo(view, 'click-remove', e => { this.shippingOptions.remove( this.shippingOptions.at(this.shippingOptionViews.indexOf(e.view))); }); return view; } remove() { this.inProgressPhotoUploads.forEach(upload => upload.abort()); $(window).off('resize', this.throttledResizeWin); super.remove(); } render(restoreScrollPos = true) { let prevScrollPos = 0; const item = this.model.get('item'); if (restoreScrollPos) { prevScrollPos = this.el.scrollTop; } if (this.throttledOnScroll) this.$el.off('scroll', this.throttledOnScroll); this.currencies = this.currencies || getCurrenciesSortedByCode(); loadTemplate('modals/editListing/editListing.html', t => { this.$el.html(t({ createMode: this.createMode, selectedNavTabIndex: this.selectedNavTabIndex, returnText: this.options.returnText, currency: this.currency, currencies: this.currencies, contractTypes: this.model.get('metadata') .contractTypes .map((contractType) => ({ code: contractType, name: app.polyglot.t(`formats.${contractType}`) })), conditionTypes: this.model.get('item') .conditionTypes .map((conditionType) => ({ code: conditionType, name: app.polyglot.t(`conditionTypes.${conditionType}`) })), errors: this.model.validationError || {}, photoUploadInprogress: !!this.inProgressPhotoUploads.length, uploadPhotoT: this.uploadPhotoT, expandedReturnPolicy: this.expandedReturnPolicy || !!this.model.get('refundPolicy'), expandedTermsAndConditions: this.expandedTermsAndConditions || !!this.model.get('termsAndConditions'), formatPrice, maxCatsWarning: this.maxCatsWarning, maxTagsWarning: this.maxTagsWarning, max: { title: item.max.titleLength, cats: item.max.cats, tags: item.max.tags, photos: this.MAX_PHOTOS, }, shouldShowVariantInventorySection: this.shouldShowVariantInventorySection, ...this.model.toJSON(), })); super.render(); this.$editListingTags = this.$('#editListingTags'); this.$editListingTagsPlaceholder = this.$('#editListingTagsPlaceholder'); this.$editListingCategories = this.$('#editListingCategories'); this.$editListingCategoriesPlaceholder = this.$('#editListingCategoriesPlaceholder'); this.$editListingVariantsChoices = this.$('#editListingVariantsChoices'); this.$editListingVariantsChoicesPlaceholder = this.$('#editListingVariantsChoicesPlaceholder'); this.$shippingOptionsWrap = this.$('.js-shippingOptionsWrap'); this.$couponsSection = this.$('.js-couponsSection'); this.$variantsSection = this.$('.js-variantsSection'); this.$('#editContractType, #editListingVisibility, #editListingCondition').select2({ // disables the search box minimumResultsForSearch: Infinity, }); this.$('#editListingCurrency').select2() .on('change', () => this.variantInventory.render()); this.$editListingTags.select2({ multiple: true, tags: true, selectOnClose: true, tokenSeparators: [','], // *** // placeholder has issue where it won't show initially, will use // own element for this instead // placeholder: 'Enter tags... (and translate me)', // *** // dropdownParent needed to fully hide dropdown dropdownParent: this.$('#editListingTagsDropdown'), createTag: (params) => { let term = params.term; if (term === '') { return null; // don't add blank tags triggered by blur } // we'll make the tag all lowercase and // replace spaces with dashes. term = term.toLowerCase() .replace(/\s/g, '-') .replace('#', '') // replace consecutive dashes with one .replace(/-{2,}/g, '-'); return { id: term, text: term, }; }, // This is necessary, otherwise partial matches of existing tags are // prevented. E,G. If you have a tag of hello-world, hello would be prevented // as a tag because select2 would match hellow-world in the hidden dropdown // and think you are selecting that. matcher: () => false, }).on('change', () => { const tags = this.$editListingTags.val(); this.model.get('item').set('tags', tags); this.$editListingTagsPlaceholder[tags.length ? 'removeClass' : 'addClass']('emptyOfTags'); if (tags.length >= item.maxTags) { this.showMaxTagsWarning(); } else { this.hideMaxTagsWarning(); } }).on('select2:selecting', (e) => { if (this.$editListingTags.val().length >= item.maxTags) { this.$maxTagsWarning.velocity('callout.flash', { duration: 500 }); e.preventDefault(); } }) .next() .find('.select2-search__field') .attr('maxLength', item.max.tagLength); this.$editListingTagsPlaceholder[ this.$editListingTags.val().length ? 'removeClass' : 'addClass' ]('emptyOfTags'); this.$editListingCategories.select2({ multiple: true, tags: true, selectOnClose: true, tokenSeparators: [','], // dropdownParent needed to fully hide dropdown dropdownParent: this.$('#editListingCategoriesDropdown'), // This is necessary, see comment in select2 for tags above. matcher: () => false, }).on('change', () => { const count = this.$editListingCategories.val().length; this.$editListingCategoriesPlaceholder[ count ? 'removeClass' : 'addClass' ]('emptyOfTags'); if (count >= item.maxCategories) { this.showMaxCatsWarning(); } else { this.hideMaxCatsWarning(); } }).on('select2:selecting', (e) => { if (this.$editListingCategories.val().length >= item.maxCategories) { this.$maxCatsWarning.velocity('callout.flash', { duration: 500 }); e.preventDefault(); } }); this.$editListingCategoriesPlaceholder[ this.$editListingCategories.val().length ? 'removeClass' : 'addClass' ]('emptyOfTags'); // render shipping options this.shippingOptionViews.forEach((shipOptVw) => shipOptVw.remove()); this.shippingOptionViews = []; const shipOptsFrag = document.createDocumentFragment(); this.model.get('shippingOptions').forEach((shipOpt, shipOptIndex) => { const shipOptVw = this.createShippingOptionView({ model: shipOpt, listPosition: shipOptIndex + 1, }); this.shippingOptionViews.push(shipOptVw); shipOptVw.render().$el.appendTo(shipOptsFrag); }); this.$shippingOptionsWrap.append(shipOptsFrag); // render sku field if (this.skuField) this.skuField.remove(); this.skuField = this.createChild(SkuField, { model: item, initialState: { variantsPresent: !!item.get('options').length, }, }); this.$('.js-skuFieldContainer').html(this.skuField.render().el); // render variants if (this.variantsView) this.variantsView.remove(); const variantErrors = {}; Object.keys(item.validationError || {}) .forEach(errKey => { if (errKey.startsWith('options[')) { variantErrors[errKey] = item.validationError[errKey]; } }); this.variantsView = this.createChild(Variants, { collection: this.variantOptionsCl, maxVariantCount: item.max.optionCount, errors: variantErrors, }); this.variantsView.listenTo(this.variantsView, 'variantChoiceChange', this.onVariantChoiceChange.bind(this)); this.$variantsSection.find('.js-variantsContainer').append( this.variantsView.render().el ); // render inventory management section if (this.inventoryManagement) this.inventoryManagement.remove(); const inventoryManagementErrors = {}; if (this.model.validationError && this.model.validationError['item.quantity']) { inventoryManagementErrors.quantity = this.model.validationError['item.quantity']; } this.inventoryManagement = this.createChild(InventoryManagement, { initialState: { trackBy: this.trackInventoryBy, quantity: item.get('quantity'), errors: inventoryManagementErrors, }, }); this.$('.js-inventoryManagementSection').html(this.inventoryManagement.render().el); this.listenTo(this.inventoryManagement, 'changeManagementType', this.onChangeManagementType); // render variant inventory if (this.variantInventory) this.variantInventory.remove(); this.variantInventory = this.createChild(VariantInventory, { collection: item.get('skus'), optionsCl: item.get('options'), getPrice: () => this.getFormData(this.$itemPrice).item.price, getCurrency: () => this.currency, }); this.$('.js-variantInventoryTableContainer') .html(this.variantInventory.render().el); // render coupons if (this.couponsView) this.couponsView.remove(); const couponErrors = {}; Object.keys(this.model.validationError || {}) .forEach(errKey => { if (errKey.startsWith('coupons[')) { couponErrors[errKey] = this.model.validationError[errKey]; } }); this.couponsView = this.createChild(Coupons, { collection: this.coupons, maxCouponCount: this.model.max.couponCount, couponErrors, }); this.$couponsSection.find('.js-couponsContainer').append( this.couponsView.render().el ); this._$scrollLinks = null; this._$scrollToSections = null; this._$formFields = null; this._$currencySelect = null; this._$priceInput = null; this._$conditionWrap = null; this._$buttonSave = null; this._$inputPhotoUpload = null; this._$photoUploadingLabel = null; this._$editListingReturnPolicy = null; this._$editListingTermsAndConditions = null; this._$sectionShipping = null; this._$maxCatsWarning = null; this._$maxTagsWarning = null; this._$addShipOptSectionHeading = null; this._$variantInventorySection = null; this._$itemPrice = null; this.$photoUploadItems = this.$('.js-photoUploadItems'); this.$modalContent = this.$('.modalContent'); this.$tabControls = this.$('.tabControls'); this.$titleInput = this.$('#editListingTitle'); installRichEditor(this.$('#editListingDescription'), { topLevelClass: 'clrBr', }); if (this.sortablePhotos) this.sortablePhotos.destroy(); this.sortablePhotos = Sortable.create(this.$photoUploadItems[0], { filter: '.js-addPhotoWrap', onUpdate: (e) => { const imageModels = this.model .get('item') .get('images') .models; const movingModel = imageModels[e.oldIndex - 1]; imageModels.splice(e.oldIndex - 1, 1); imageModels.splice(e.newIndex - 1, 0, movingModel); }, onMove: (e) => ($(e.related).hasClass('js-addPhotoWrap') ? false : undefined), }); setTimeout(() => { if (!this.rendered) { this.rendered = true; this.$titleInput.focus(); } }); setTimeout(() => { // restore the scroll position if (restoreScrollPos) { this.el.scrollTop = prevScrollPos; } this.throttledOnScroll = _.bind(_.throttle(this.onScroll, 100), this); setTimeout(() => this.$el.on('scroll', this.throttledOnScroll), 100); }); }); return this; } }
some code cleanup
js/views/modals/editListing/EditListing.js
some code cleanup
<ide><path>s/views/modals/editListing/EditListing.js <ide> // we'll clone and update it on sync <ide> this._origModel = this.model; <ide> this.model = this._origModel.clone(); <del> <del> console.log('sugar'); <del> window.sugar = this.model; <ide> <ide> this.listenTo(this.model, 'sync', () => { <ide> setTimeout(() => {
Java
mit
c90eaae825c3a12323e52f8e4d8a8099b1648469
0
Mrbysco/MemeInABottle
package com.Mrbysco.MIAB.blocks; import java.util.ArrayList; import java.util.List; import com.Mrbysco.MIAB.MIAB; import com.Mrbysco.MIAB.Reference; import com.Mrbysco.MIAB.init.MIABItems; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BottleBlock extends Block{ protected static final AxisAlignedBB BOTTLE_AABB = new AxisAlignedBB(0.0F, 0.0F, 0.0F, 1.0F, 0.0625F, 1.0F); public BottleBlock(Material materialIn) { super(Material.GLASS); setUnlocalizedName(Reference.MIABBlocks.BOTTLEBLOCK.getUnlocalisedName()); setRegistryName(Reference.MIABBlocks.BOTTLEBLOCK.getRegistryName()); setCreativeTab(MIAB.tabMIAB); this.setSoundType(SoundType.GLASS); this.setTickRandomly(true); this.setHardness(0.2F); } @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override public boolean isFullCube(IBlockState state) { return false; } @Override public boolean canCollideCheck(IBlockState state, boolean hitIfLiquid) { return true; } @Override public boolean isPassable(IBlockAccess worldIn, BlockPos pos) { return true; } @Override @SideOnly(Side.CLIENT) public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.CUTOUT; } public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return BOTTLE_AABB; } /* @Override public AxisAlignedBB getCollisionBoundingBox(IBlockState worldIn, World pos, BlockPos state) { return worldIn.getBoundingBox(pos, state).offset(state); } */ @Override public List<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { ArrayList returnedStacks = new ArrayList(); returnedStacks.add(new ItemStack(MIABItems.meme_in_a_bottle)); return returnedStacks; } }
src/main/java/com/Mrbysco/MIAB/blocks/BottleBlock.java
package com.Mrbysco.MIAB.blocks; import java.util.ArrayList; import java.util.List; import com.Mrbysco.MIAB.MIAB; import com.Mrbysco.MIAB.Reference; import com.Mrbysco.MIAB.init.MIABItems; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BottleBlock extends Block{ protected static final AxisAlignedBB BOTTLE_AABB = new AxisAlignedBB(0.0F, 0.0F, 0.0F, 1.0F, 0.0625F, 1.0F); public BottleBlock(Material materialIn) { super(Material.GLASS); setUnlocalizedName(Reference.MIABBlocks.BOTTLEBLOCK.getUnlocalisedName()); setRegistryName(Reference.MIABBlocks.BOTTLEBLOCK.getRegistryName()); setCreativeTab(MIAB.tabMIAB); this.setSoundType(SoundType.GLASS); this.setTickRandomly(true); this.setHardness(0.2F); } @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override public boolean isFullCube(IBlockState state) { return false; } @Override public boolean canCollideCheck(IBlockState state, boolean hitIfLiquid) { return true; } @Override public boolean isPassable(IBlockAccess worldIn, BlockPos pos) { return true; } @Override @SideOnly(Side.CLIENT) public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.CUTOUT; } public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return BOTTLE_AABB; } /* @Override public AxisAlignedBB getCollisionBoundingBox(IBlockState worldIn, World pos, BlockPos state) { return worldIn.getBoundingBox(pos, state).offset(state); } */ @Override public List<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { ArrayList returnedStacks = new ArrayList(); returnedStacks.add(new ItemStack(MIABItems.meme_in_a_bottle)); return returnedStacks; } }
------ ---
src/main/java/com/Mrbysco/MIAB/blocks/BottleBlock.java
------
<ide><path>rc/main/java/com/Mrbysco/MIAB/blocks/BottleBlock.java <ide> public boolean isPassable(IBlockAccess worldIn, BlockPos pos) <ide> { <ide> return true; <del> } <add> } <ide> <ide> @Override <ide> @SideOnly(Side.CLIENT)
JavaScript
mit
ad4f9617a150003ec6f87030b8534a0d13a37cd6
0
c9/c9.ide.scm,c9/c9.ide.scm,c9/c9.ide.scm
define(function(require, exports, module) { main.consumes = [ "Panel", "Menu", "MenuItem", "Divider", "settings", "ui", "c9", "watcher", "panels", "util", "save", "preferences", "commands", "Tree", "tabManager", "layout", "preferences.experimental", "scm", "util" ]; main.provides = ["scm.branches"]; return main; function main(options, imports, register) { var Panel = imports.Panel; var Tree = imports.Tree; var Menu = imports.Menu; var MenuItem = imports.MenuItem; var Divider = imports.Divider; var settings = imports.settings; var ui = imports.ui; var c9 = imports.c9; var tabs = imports.tabManager; var watcher = imports.watcher; var util = imports.util; var panels = imports.panels; var util = imports.util; var save = imports.save; var layout = imports.layout; var scm = imports.scm; var prefs = imports.preferences; var commands = imports.commands; var experimental = imports["preferences.experimental"]; var timeago = require("timeago"); var escapeHTML = require("ace/lib/lang").escapeHTML; /* TODO: - Add support for remotes: - Auto open remotes section - Show url in remotes section git remote -v origin [email protected]:c9/newclient.git (fetch) origin [email protected]:c9/newclient.git (push) - Add button to add remote next to 'remotes' - Remove a remote using context menu - Variable rows: https://github.com/c9/newclient/blob/master/node_modules/ace_tree/lib/ace_tree/data_provider.js#L393 */ /***** Initialization *****/ var ENABLED = experimental.addExperiment("git", !c9.hosted, "Panels/Source Control Management") if (!ENABLED) return register(null, { "scm.branches": {} }); var plugin = new Panel("Ajax.org", main.consumes, { index: options.index || 350, caption: "Branches", minWidth: 130, autohide: true, where: options.where || "left" }); var emit = plugin.getEmitter(); var RECENT_THRESHOLD = 14 * 24 * 60 * 60 * 1000; // 2 weeks ago var ITEM_THRESHOLD_LOCAL = 5; var ITEM_THRESHOLD_REMOTE = 10; var ICON_BRANCH = require("text!./icons/git-branch.svg"); var ICON_PULLREQUEST = require("text!./icons/git-pull-request.svg"); var ICON_TAG = require("text!./icons/git-tag.svg"); var branchesTree, lastData; var displayMode = "branches"; var mnuSettings, btnSettings; var workspaceDir = c9.workspaceDir; // + "/plugins/c9.ide.scm/mock/git"; var loaded = false; function load(){ if (loaded) return false; loaded = true; plugin.setCommand({ name: "branches", hint: "Version Branches", bindKey: { mac: "", win: "" }, extra: function(editor, args, e) { } }); settings.on("read", function(){ settings.setDefaults("project/scm", [["primary", ["origin/master"]]]); settings.setDefaults("user/scm", [["showauthor", [false]]]); }); settings.on("user/scm/@showauthor", function(){ plugin.on("draw", function(){ var showAuthor = settings.getBool("user/scm/@showauthor"); branchesTree.container.className = branchesTree.container.className.replace(/ showAuthorName/, ""); if (showAuthor) branchesTree.container.className += " showAuthorName"; }); }); } var drawn = false; function draw(opts) { if (drawn) return; drawn = true; var mnuFilter = Menu({ items: [ new MenuItem({ type: "radio", caption: "Branches", value: "branches" }), new MenuItem({ type: "radio", caption: "Committer", value: "committer" }) ]}, plugin); mnuFilter.on("itemclick", function(e){ button.setCaption(e.item.caption); displayMode = e.item.value; if (displayMode == "branches") showBranches(); else showCommitters(); }); var codebox = new ui.codebox({ realtime: "true", skin: "codebox", "initial-message": "Filter Branches", clearbutton: "true", focusselect: "true", singleline: "true", left: 10, top: 10, right: 10 // class: "navigate-search" }); var container = new ui.bar({ anchors: "47 0 0 0" }); var button = new ui.button({ caption: "Branches", right: 10, top: 10, submenu: mnuFilter.aml }); opts.aml.appendChild(codebox); opts.aml.appendChild(button); opts.aml.appendChild(container); var mnuContext = new Menu({ items: [ new MenuItem({ caption: "Checkout" }), // new MenuItem({ caption: "Create Pull Request" }), new Divider(), new MenuItem({ caption: "Show In Version Log" }), new MenuItem({ caption: "Compare With Master" }), new Divider(), new MenuItem({ caption: "Delete Branch" }), new MenuItem({ caption: "Merge Into Current Branch" }) ]}, plugin); container.setAttribute("contextmenu", mnuContext.aml); branchesTree = new Tree({ container: container.$int, scrollMargin: [0, 10], theme: "filetree branches" + (settings.getBool("user/scm/@showauthor") ? " showAuthorName" : ""), isLoading: function() {}, getIconHTML: function(node) { if (node.isFolder || !node.path || !node.subject) return ""; var icon; if (node.path.indexOf("refs/tags/") === 0) icon = ICON_TAG; else if (node.parent.parent == pullRequests) icon = ICON_PULLREQUEST; else icon = ICON_BRANCH; // todo diff between local, remote, stash return icon; }, getCaptionHTML: function(node) { var name; if (branchesTree.filterKeyword && node.path && !node.parent.parent || node.path && displayMode == "committer") name = node.path.replace(/^refs\//, ""); else name = node.label || node.name; if (node.type == "user") return "<img src='" + util.getGravatarUrl(node.email.replace(/[<>]/g, ""), 32, "") + "' width='16' height='16' />" + escapeHTML(node.label) + " (" + node.items.length + ")"; if (node.authorname) { return escapeHTML(name) + "<span class='author'><img src='" + util.getGravatarUrl(node.authoremail.replace(/[<>]/g, ""), 32, "") + "' width='16' height='16' />" + escapeHTML(node.authorname) + "</span>" + "<span class='extrainfo'> - " + (node.date ? timeago(node.date) : "") + "</span>"; } return escapeHTML(name); }, getTooltipText: function(node){ return node.authorname ? "[" + node.hash + "] " + node.authorname + " - " + node.subject : ""; }, getRowIndent: function(node) { return branchesTree.filterKeyword || displayMode == "committer" ? node.$depth : node.$depth ? node.$depth - 1 : 0; }, getEmptyMessage: function(){ return branchesTree.filterKeyword ? "No branches found for '" + branchesTree.filterKeyword + "'" : "Loading..."; }, sort: function(children) { if (!children.length) return; var compare = branchesTree.model.alphanumCompare; if (children[0].type == "user") return children.sort(function(a, b){ if (a.label == "[None]") return 1; if (b.label == "[None]") return -1; return compare(a.label + "", b.label + ""); }); return children.sort(function(a, b) { if (a.isFolder) return 0; if (a.authorname && !b.authorname) return -1; if (b.authorname && !a.authorname) return 1; return compare(b.date + "", a.date + ""); }); } }, plugin); branchesTree.renderer.scrollBarV.$minWidth = 10; branchesTree.emptyMessage = "loading..." branchesTree.on("afterChoose", function(e){ var node = branchesTree.selectedNode; if (!node) return; if (node.showall) { var p = node.parent; p.items = p.children = p.cache; node.showall = false; node.label = "Show Less..." branchesTree.refresh(); } else if (node.showall === false) { var p = node.parent; p.items = p.children = p.cache.slice(0, p.limit); p.items.push(node); node.showall = true; node.label = "Show All (" + p.cache.length + ")..."; branchesTree.refresh(); } }); function forwardToTree() { branchesTree.execCommand(this.name); } codebox.ace.on("input", function(){ branchesTree.filterKeyword = codebox.ace.getValue(); }); codebox.ace.commands.addCommands([ "centerselection", "goToStart", "goToEnd", "pageup", "gotopageup", "pagedown", "gotopageDown", "scrollup", "scrolldown", "goUp", "goDown", "selectUp", "selectDown", "selectMoreUp", "selectMoreDown" ].map(function(name) { var command = branchesTree.commands.byName[name]; return { name: command.name, bindKey: command.editorKey || command.bindKey, exec: forwardToTree }; })); refresh(); mnuSettings = new Menu({ items: [ new MenuItem({ caption: "Refresh", onclick: refresh }, plugin), new Divider(), new MenuItem({ caption: "Remove All Local Merged Branches", onclick: refresh }, plugin), new MenuItem({ caption: "Remove All Remote Merged Branches", onclick: refresh }, plugin), // https://gist.github.com/schacon/942899 new Divider(), new MenuItem({ caption: "Show Author Name", type: "check", checked: "user/scm/@showauthor" }, plugin) ]}, plugin); btnSettings = opts.aml.appendChild(new ui.button({ skin: "header-btn", class: "panel-settings changes", submenu: mnuSettings.aml })); // Mark Dirty // plugin.on("show", function() { // save.on("afterSave", markDirty); // watcher.on("change", markDirty); // }); // plugin.on("hide", function() { // clearTimeout(timer); // save.off("afterSave", markDirty); // watcher.off("change", markDirty); // }); // watcher.watch(util.normalizePath(workspaceDir) + "/.git"); // var timer = null; // function markDirty(e) { // clearTimeout(timer); // timer = setTimeout(function() { // if (tree && tree.meta.options && !tree.meta.options.hash) { // tree.meta.options.force = true; // emit("reload", tree.meta.options); // } // }, 800); // } } /***** Methods *****/ var recentLocal = { label: "recent local branches", className: "heading", items: [], isOpen: true, isFolder: true, noSelect: true, $sorted: true }; var primaryRemote = { label: "primary remote branches", className: "heading", items: [], isOpen: true, isFolder: true, noSelect: true, $sorted: true }; var pullRequests = { label: "pull requests", className: "heading", isPR: true, items: [ { label: "Open", items: [], isOpen: true, isFolder: true }, { label: "Closed", items: [], isOpen: false, isFolder: true } ], isOpen: true, isFolder: true, map: {}, noSelect: true, $sorted: true }; var recentActive = { label: "recently active", className: "heading", items: [], isOpen: true, isFolder: true, map: {}, noSelect: true, $sorted: true }; var all = { label: "all", className: "heading", items: [], isOpen: true, isFolder: true, noSelect: true, $sorted: true }; var branchesRoot = { path: "", items: [recentLocal, primaryRemote, pullRequests, recentActive, all] }; var committersRoot = { path: "", items: [] } function loadBranches(data){ var root = branchesRoot; root.items.forEach(function(n){ if (n.isPR) { n.items[0].items.length = 0; n.items[1].items.length = 0; } else n.items.length = 0; }); var primary = settings.getJson("project/scm/@primary"); function isPrimary(path){ return ~primary.indexOf(path.replace(/^refs\/remotes\//, "")); } function copyNode(x){ var y = util.extend({ className: "root-branch" }, x); y.name = x.path.replace(/^refs\/(?:(?:remotes|tags|heads)\/)?/, ""); return y; } // Store all branches in all data.forEach(function(x) { x.date = parseInt(x.committerdate) * 1000; x.path = x.name; var parts = x.path.replace(/^refs\//, "").split("/"); x.name = parts.pop(); // disregard the name if (parts[0] == "remotes") { if (isPrimary(x.path)) primaryRemote.items.push(copyNode(x)); } var node = all; parts.forEach(function(p) { var items = node.items || (node.items = []); var map = node.map || (node.map = {}); if (map[p]) node = map[p]; else { node = map[p] = { label: p, path: (node.path || "") + p + "/" }; items.push(node); } }); var items = node.items || (node.items = []); var map = node.map || (node.map = {}); map[x.name] = x; items.push(x); }); // Sort by date data.sort(function(a, b){ if (a.date == b.date) return 0; if (a.date < b.date) return 1; if (a.date > b.date) return -1; }); var local = [], remote = [], threshold = Date.now() - RECENT_THRESHOLD; for (var i = 0, l = data.length; i < l; i++) { var x = data[i]; if (x.date < threshold) continue; if (x.path.indexOf("refs/remotes") === 0 && !isPrimary(x.path)) remote.push(copyNode(x)); else if (x.path.indexOf("refs/heads") === 0) local.push(copyNode(x)); } // TODO add current branch to top of recent local and make bold recentLocal.limit = ITEM_THRESHOLD_LOCAL; recentLocal.cache = local; recentLocal.items = local.slice(0, ITEM_THRESHOLD_LOCAL); if (local.length > ITEM_THRESHOLD_LOCAL) { var n = { showall: true, label: "Show All (" + local.length + ")..." }; recentLocal.items.push(n); local.push(n); } recentActive.limit = ITEM_THRESHOLD_REMOTE; recentActive.cache = remote; recentActive.children = recentActive.items = remote.slice(0, ITEM_THRESHOLD_REMOTE); if (remote.length > ITEM_THRESHOLD_REMOTE) { var n = { showall: true, label: "Show All (" + remote.length + ")..." }; recentActive.items.push(n); remote.push(n); } // Remove empty blocks root.items = root.items.filter(function(n){ if (n == all) return true; if (n.isPR) return n.items[0].length + n.items[1].length; return n.items.length; }); // Reset committers root committersRoot.items.length = 0; // branchesTree.filterRoot = data; // branchesTree.setRoot(root.items); // branchesTree.resize(); } function showBranches(){ branchesTree.filterProperty = "path"; branchesTree.filterRoot = lastData; branchesTree.setRoot(branchesRoot.items); } function showCommitters(){ if (!committersRoot.items.length) { var data = lastData; var users = {}, emails = {}; data.forEach(function(x) { var user = x.authorname || "[None]"; if (!emails[user]) emails[user] = x.authoremail; (users[user] || (users[user] = [])).push(x); }); for (var user in users) { committersRoot.items.push({ label: user, authorname: user, email: emails[user], type: "user", items: users[user], clone: function(){ var x = function(){}; x.prototype = this; var y = new x(); y.keepChildren = true; y.isOpen = true; return y; } }); } } branchesTree.filterProperty = "authorname"; branchesTree.filterRoot = committersRoot; branchesTree.setRoot(committersRoot.items); } function refresh(){ scm.listAllRefs(function(err, data) { if (err) { branchesTree.emptyMessage = "Error while loading\n" + escapeHTML(err.message); branchesTree.setRoot(null); return console.error(err); } lastData = data; loadBranches(data); if (displayMode == "branches") showBranches(); else showCommitters(); }); } /***** Lifecycle *****/ plugin.on("load", function(){ load(); }); plugin.on("draw", function(e) { draw(e); }); plugin.on("enable", function(){ }); plugin.on("disable", function(){ }); plugin.on("show", function onShow(e) { }); plugin.on("hide", function(e) { }); plugin.on("unload", function(){ loaded = false; drawn = false; }); /***** Register and define API *****/ plugin.freezePublicAPI({ get tree(){ return branchesTree; } }); register(null, { "scm.branches": plugin }); } });
scm.branches.js
define(function(require, exports, module) { main.consumes = [ "Panel", "Menu", "MenuItem", "Divider", "settings", "ui", "c9", "watcher", "panels", "util", "save", "preferences", "commands", "Tree", "tabManager", "layout", "preferences.experimental", "scm", "util" ]; main.provides = ["scm.branches"]; return main; function main(options, imports, register) { var Panel = imports.Panel; var Tree = imports.Tree; var Menu = imports.Menu; var MenuItem = imports.MenuItem; var Divider = imports.Divider; var settings = imports.settings; var ui = imports.ui; var c9 = imports.c9; var tabs = imports.tabManager; var watcher = imports.watcher; var util = imports.util; var panels = imports.panels; var util = imports.util; var save = imports.save; var layout = imports.layout; var scm = imports.scm; var prefs = imports.preferences; var commands = imports.commands; var experimental = imports["preferences.experimental"]; var timeago = require("timeago"); var escapeHTML = require("ace/lib/lang").escapeHTML; /***** Initialization *****/ var ENABLED = experimental.addExperiment("git", !c9.hosted, "Panels/Source Control Management") if (!ENABLED) return register(null, { "scm.branches": {} }); var plugin = new Panel("Ajax.org", main.consumes, { index: options.index || 350, caption: "Branches", minWidth: 130, autohide: true, where: options.where || "left" }); var emit = plugin.getEmitter(); var RECENT_THRESHOLD = 14 * 24 * 60 * 60 * 1000; // 2 weeks ago var ITEM_THRESHOLD_LOCAL = 5; var ITEM_THRESHOLD_REMOTE = 10; var ICON_BRANCH = require("text!./icons/git-branch.svg"); var ICON_PULLREQUEST = require("text!./icons/git-pull-request.svg"); var ICON_TAG = require("text!./icons/git-tag.svg"); var branchesTree; var mnuSettings, btnSettings var workspaceDir = c9.workspaceDir; // + "/plugins/c9.ide.scm/mock/git"; var loaded = false; function load(){ if (loaded) return false; loaded = true; plugin.setCommand({ name: "branches", hint: "Version Branches", bindKey: { mac: "", win: "" }, extra: function(editor, args, e) { } }); settings.on("read", function(){ settings.setDefaults("project/scm", [["primary", ["origin/master"]]]); settings.setDefaults("user/scm", [["showauthor", [false]]]); }); settings.on("user/scm/@showauthor", function(){ plugin.on("draw", function(){ var showAuthor = settings.getBool("user/scm/@showauthor"); branchesTree.container.className = branchesTree.container.className.replace(/ showAuthorName/, ""); if (showAuthor) branchesTree.container.className += " showAuthorName"; }); }); } var drawn = false; function draw(opts) { if (drawn) return; drawn = true; var codebox = new ui.codebox({ realtime: "true", skin: "codebox", "initial-message": "Filter Branches", clearbutton: "true", focusselect: "true", singleline: "true", left: 10, top: 10, right: 10 // class: "navigate-search" }); var container = new ui.bar({ anchors: "47 0 0 0" }); opts.aml.appendChild(codebox); opts.aml.appendChild(container); var mnuContext = new Menu({ items: [ new MenuItem({ caption: "Checkout" }), // new MenuItem({ caption: "Create Pull Request" }), new Divider(), new MenuItem({ caption: "Show In Version Log" }), new MenuItem({ caption: "Compare With Master" }), new Divider(), new MenuItem({ caption: "Delete Branch" }), new MenuItem({ caption: "Merge Into Current Branch" }) ]}, plugin); container.setAttribute("contextmenu", mnuContext.aml); branchesTree = new Tree({ container: container.$int, scrollMargin: [0, 10], filterProperty: "path", filterRoot: all, theme: "filetree branches" + (settings.getBool("user/scm/@showauthor") ? " showAuthorName" : ""), isLoading: function() {}, getIconHTML: function(node) { if (node.isFolder || !node.path || !node.subject) return ""; var icon; if (node.path.indexOf("refs/tags/") === 0) icon = ICON_TAG; else if (node.parent.parent == pullRequests) icon = ICON_PULLREQUEST; else icon = ICON_BRANCH; // todo diff between local, remote, stash return icon; }, getCaptionHTML: function(node) { var name; if (branchesTree.filterKeyword && node.path && !node.parent.parent) name = node.path.replace(/^refs\//, ""); else name = node.label || node.name; if (node.authorname) { return escapeHTML(name) + "<span class='author'><img src='" + util.getGravatarUrl(node.authoremail.replace(/[<>]/g, ""), 32, "") + "' width='16' height='16' />" + node.authorname + "</span>" + "<span class='extrainfo'> - " + (node.date ? timeago(node.date) : "") + "</span>"; } return escapeHTML(name); }, getTooltipText: function(node){ return node.authorname ? "[" + node.hash + "] " + node.authorname + " - " + node.subject : ""; }, getRowIndent: function(node) { return branchesTree.filterKeyword ? node.$depth : node.$depth ? node.$depth - 1 : 0; }, getEmptyMessage: function(){ return branchesTree.filterKeyword ? "No branches found for '" + branchesTree.filterKeyword + "'" : "Loading..."; }, sort: function(children) { if (!children.length) return; var compare = branchesTree.model.alphanumCompare; return children.sort(function(a, b) { if (a.isFolder) return 0; if (a.authorname && !b.authorname) return 1; if (b.authorname && !a.authorname) return -1; return compare(b.date + "", a.date + ""); }); } }, plugin); // var idMixin = function () { // this.expandedList = Object.create(null); // this.selectedList = Object.create(null); // this.setOpen = function(node, val) { // if (val) // this.expandedList[node.path] = val; // else // delete this.expandedList[node.path]; // }; // this.isOpen = function(node) { // return this.expandedList[node.path]; // }; // this.isSelected = function(node) { // return this.selectedList[node.path]; // }; // this.setSelected = function(node, val) { // if (val) // this.selectedList[node.path] = !!val; // else // delete this.selectedList[node.path]; // }; // }; // idMixin.call(branchesTree.model); // branchesTree.model.expandedList["refs/remotes/"] = true; branchesTree.renderer.scrollBarV.$minWidth = 10; // branchesTree.container.style.margin = "0 0px 0 0"; // branchesTree.minLines = 3; // branchesTree.maxLines = Math.floor((window.innerHeight - 100) / branchesTree.rowHeight); branchesTree.emptyMessage = "loading..." branchesTree.on("afterChoose", function(e){ var node = branchesTree.selectedNode; if (!node) return; if (node.showall) { var p = node.parent; p.items = p.children = p.cache; node.showall = false; node.label = "Show Less..." branchesTree.refresh(); } else if (node.showall === false) { var p = node.parent; p.items = p.children = p.cache.slice(0, p.limit); p.items.push(node); node.showall = true; node.label = "Show All (" + p.cache.length + ")..."; branchesTree.refresh(); } }); function forwardToTree() { branchesTree.execCommand(this.name); } codebox.ace.on("input", function(){ branchesTree.filterKeyword = codebox.ace.getValue(); }); codebox.ace.commands.addCommands([ "centerselection", "goToStart", "goToEnd", "pageup", "gotopageup", "pagedown", "gotopageDown", "scrollup", "scrolldown", "goUp", "goDown", "selectUp", "selectDown", "selectMoreUp", "selectMoreDown" ].map(function(name) { var command = branchesTree.commands.byName[name]; return { name: command.name, bindKey: command.editorKey || command.bindKey, exec: forwardToTree }; })); scm.listAllRefs(function(err, data) { if (err) { branchesTree.emptyMessage = "Error while loading\n" + escapeHTML(err.message); return console.error(err); } loadBranches(data); }); mnuSettings = new Menu({ items: [ new MenuItem({ caption: "Refresh", onclick: refresh }, plugin), new Divider(), new MenuItem({ caption: "Remove All Local Merged Branches", onclick: refresh }, plugin), new MenuItem({ caption: "Remove All Remote Merged Branches", onclick: refresh }, plugin), // https://gist.github.com/schacon/942899 new Divider(), new MenuItem({ caption: "Show Author Name", type: "check", checked: "user/scm/@showauthor" }, plugin) ]}, plugin); btnSettings = opts.aml.appendChild(new ui.button({ skin: "header-btn", class: "panel-settings changes", submenu: mnuSettings.aml })); // Mark Dirty // plugin.on("show", function() { // save.on("afterSave", markDirty); // watcher.on("change", markDirty); // }); // plugin.on("hide", function() { // clearTimeout(timer); // save.off("afterSave", markDirty); // watcher.off("change", markDirty); // }); // watcher.watch(util.normalizePath(workspaceDir) + "/.git"); // var timer = null; // function markDirty(e) { // clearTimeout(timer); // timer = setTimeout(function() { // if (tree && tree.meta.options && !tree.meta.options.hash) { // tree.meta.options.force = true; // emit("reload", tree.meta.options); // } // }, 800); // } } /***** Methods *****/ var recentLocal = { label: "recent local branches", className: "heading", items: [], isOpen: true, isFolder: true, noSelect: true, $sorted: true }; var primaryRemote = { label: "primary remote branches", className: "heading", items: [], isOpen: true, isFolder: true, noSelect: true, $sorted: true }; var pullRequests = { label: "pull requests", className: "heading", isPR: true, items: [ { label: "Open", items: [], isOpen: true, isFolder: true }, { label: "Closed", items: [], isOpen: false, isFolder: true } ], isOpen: true, isFolder: true, map: {}, noSelect: true, $sorted: true }; var recentActive = { label: "recently active", className: "heading", items: [], isOpen: true, isFolder: true, map: {}, noSelect: true, $sorted: true }; var all = { label: "all", className: "heading", items: [], isOpen: true, isFolder: true, noSelect: true, $sorted: true }; function loadBranches(data){ var root = { path: "", items: [recentLocal, primaryRemote, pullRequests, recentActive, all] }; root.items.forEach(function(n){ if (n.isPR) { n.items[0].items.length = 0; n.items[1].items.length = 0; } else n.items.length = 0; }); var primary = settings.getJson("project/scm/@primary"); function isPrimary(path){ return ~primary.indexOf(path.replace(/^refs\/remotes\//, "")); } function copyNode(x){ var y = util.extend({ className: "root-branch" }, x); y.name = x.path.replace(/^refs\/(?:(?:remotes|tags|heads)\/)?/, ""); return y; } // Store all branches in all data.forEach(function(x) { x.date = parseInt(x.committerdate) * 1000; x.path = x.name; var parts = x.path.replace(/^refs\//, "").split("/"); x.name = parts.pop(); // disregard the name if (parts[0] == "remotes") { if (isPrimary(x.path)) primaryRemote.items.push(copyNode(x)); } var node = all; parts.forEach(function(p) { var items = node.items || (node.items = []); var map = node.map || (node.map = {}); if (map[p]) node = map[p]; else { node = map[p] = { label: p, path: (node.path || "") + p + "/" }; items.push(node); } }); var items = node.items || (node.items = []); var map = node.map || (node.map = {}); map[x.name] = x; items.push(x); }); // Sort by date data.sort(function(a, b){ if (a.date == b.date) return 0; if (a.date < b.date) return 1; if (a.date > b.date) return -1; }); var local = [], remote = [], threshold = Date.now() - RECENT_THRESHOLD; for (var i = 0, l = data.length; i < l; i++) { var x = data[i]; if (x.date < threshold) continue; if (x.path.indexOf("refs/remotes") === 0 && !isPrimary(x.path)) remote.push(copyNode(x)); else if (x.path.indexOf("refs/heads") === 0) local.push(copyNode(x)); } // TODO add current branch to top of recent local and make bold recentLocal.limit = ITEM_THRESHOLD_LOCAL; recentLocal.cache = local; recentLocal.items = local.slice(0, ITEM_THRESHOLD_LOCAL); if (local.length > ITEM_THRESHOLD_LOCAL) { var n = { showall: true, label: "Show All (" + local.length + ")..." }; recentLocal.items.push(n); local.push(n); } recentActive.limit = ITEM_THRESHOLD_REMOTE; recentActive.cache = remote; recentActive.children = recentActive.items = remote.slice(0, ITEM_THRESHOLD_REMOTE); if (remote.length > ITEM_THRESHOLD_REMOTE) { var n = { showall: true, label: "Show All (" + remote.length + ")..." }; recentActive.items.push(n); remote.push(n); } // Remove empty blocks root.items = root.items.filter(function(n){ if (n == all) return true; if (n.isPR) return n.items[0].length + n.items[1].length; return n.items.length; }); branchesTree.setRoot(root.items); branchesTree.resize(); } function refresh(){ } /***** Lifecycle *****/ plugin.on("load", function(){ load(); }); plugin.on("draw", function(e) { draw(e); }); plugin.on("enable", function(){ }); plugin.on("disable", function(){ }); plugin.on("show", function onShow(e) { }); plugin.on("hide", function(e) { }); plugin.on("unload", function(){ loaded = false; drawn = false; }); /***** Register and define API *****/ plugin.freezePublicAPI({ get tree(){ return branchesTree; } }); register(null, { "scm.branches": plugin }); } });
Committer mode with filtering
scm.branches.js
Committer mode with filtering
<ide><path>cm.branches.js <ide> var timeago = require("timeago"); <ide> var escapeHTML = require("ace/lib/lang").escapeHTML; <ide> <add> /* <add> TODO: <add> - Add support for remotes: <add> - Auto open remotes section <add> - Show url in remotes section <add> git remote -v <add> origin [email protected]:c9/newclient.git (fetch) <add> origin [email protected]:c9/newclient.git (push) <add> - Add button to add remote next to 'remotes' <add> - Remove a remote using context menu <add> - Variable rows: <add> https://github.com/c9/newclient/blob/master/node_modules/ace_tree/lib/ace_tree/data_provider.js#L393 <add> */ <add> <ide> /***** Initialization *****/ <ide> <ide> var ENABLED = experimental.addExperiment("git", !c9.hosted, "Panels/Source Control Management") <ide> var ICON_PULLREQUEST = require("text!./icons/git-pull-request.svg"); <ide> var ICON_TAG = require("text!./icons/git-tag.svg"); <ide> <del> var branchesTree; <del> var mnuSettings, btnSettings <add> var branchesTree, lastData; <add> var displayMode = "branches"; <add> var mnuSettings, btnSettings; <ide> var workspaceDir = c9.workspaceDir; // + "/plugins/c9.ide.scm/mock/git"; <ide> <ide> var loaded = false; <ide> function draw(opts) { <ide> if (drawn) return; <ide> drawn = true; <add> <add> var mnuFilter = Menu({ items: [ <add> new MenuItem({ type: "radio", caption: "Branches", value: "branches" }), <add> new MenuItem({ type: "radio", caption: "Committer", value: "committer" }) <add> ]}, plugin); <add> mnuFilter.on("itemclick", function(e){ <add> button.setCaption(e.item.caption); <add> displayMode = e.item.value; <add> <add> if (displayMode == "branches") <add> showBranches(); <add> else <add> showCommitters(); <add> }); <ide> <ide> var codebox = new ui.codebox({ <ide> realtime: "true", <ide> // class: "navigate-search" <ide> }); <ide> var container = new ui.bar({ anchors: "47 0 0 0" }); <add> var button = new ui.button({ <add> caption: "Branches", <add> right: 10, <add> top: 10, <add> submenu: mnuFilter.aml <add> }); <ide> <ide> opts.aml.appendChild(codebox); <add> opts.aml.appendChild(button); <ide> opts.aml.appendChild(container); <ide> <ide> var mnuContext = new Menu({ items: [ <ide> branchesTree = new Tree({ <ide> container: container.$int, <ide> scrollMargin: [0, 10], <del> filterProperty: "path", <del> filterRoot: all, <ide> theme: "filetree branches" <ide> + (settings.getBool("user/scm/@showauthor") ? " showAuthorName" : ""), <ide> <ide> <ide> getCaptionHTML: function(node) { <ide> var name; <del> if (branchesTree.filterKeyword && node.path && !node.parent.parent) <add> if (branchesTree.filterKeyword && node.path && !node.parent.parent <add> || node.path && displayMode == "committer") <ide> name = node.path.replace(/^refs\//, ""); <ide> else <ide> name = node.label || node.name; <add> <add> if (node.type == "user") <add> return "<img src='" <add> + util.getGravatarUrl(node.email.replace(/[<>]/g, ""), 32, "") <add> + "' width='16' height='16' />" <add> + escapeHTML(node.label) <add> + " (" + node.items.length + ")"; <ide> <ide> if (node.authorname) { <ide> return escapeHTML(name) <ide> + "<span class='author'><img src='" <ide> + util.getGravatarUrl(node.authoremail.replace(/[<>]/g, ""), 32, "") <ide> + "' width='16' height='16' />" <del> + node.authorname + "</span>" <add> + escapeHTML(node.authorname) + "</span>" <ide> + "<span class='extrainfo'> - " <ide> + (node.date ? timeago(node.date) : "") + "</span>"; <ide> } <ide> }, <ide> <ide> getRowIndent: function(node) { <del> return branchesTree.filterKeyword <add> return branchesTree.filterKeyword || displayMode == "committer" <ide> ? node.$depth <ide> : node.$depth ? node.$depth - 1 : 0; <ide> }, <del> <add> <ide> getEmptyMessage: function(){ <ide> return branchesTree.filterKeyword <ide> ? "No branches found for '" + branchesTree.filterKeyword + "'" <ide> return; <ide> <ide> var compare = branchesTree.model.alphanumCompare; <add> <add> if (children[0].type == "user") <add> return children.sort(function(a, b){ <add> if (a.label == "[None]") return 1; <add> if (b.label == "[None]") return -1; <add> return compare(a.label + "", b.label + ""); <add> }); <add> <ide> return children.sort(function(a, b) { <ide> if (a.isFolder) return 0; <ide> <ide> if (a.authorname && !b.authorname) <add> return -1; <add> if (b.authorname && !a.authorname) <ide> return 1; <del> if (b.authorname && !a.authorname) <del> return -1; <ide> <ide> return compare(b.date + "", a.date + ""); <ide> }); <ide> } <ide> }, plugin); <ide> <del> // var idMixin = function () { <del> // this.expandedList = Object.create(null); <del> // this.selectedList = Object.create(null); <del> // this.setOpen = function(node, val) { <del> // if (val) <del> // this.expandedList[node.path] = val; <del> // else <del> // delete this.expandedList[node.path]; <del> // }; <del> // this.isOpen = function(node) { <del> // return this.expandedList[node.path]; <del> // }; <del> // this.isSelected = function(node) { <del> // return this.selectedList[node.path]; <del> // }; <del> // this.setSelected = function(node, val) { <del> // if (val) <del> // this.selectedList[node.path] = !!val; <del> // else <del> // delete this.selectedList[node.path]; <del> // }; <del> // }; <del> // idMixin.call(branchesTree.model); <del> // branchesTree.model.expandedList["refs/remotes/"] = true; <del> <ide> branchesTree.renderer.scrollBarV.$minWidth = 10; <del> // branchesTree.container.style.margin = "0 0px 0 0"; <del> <del> // branchesTree.minLines = 3; <del> // branchesTree.maxLines = Math.floor((window.innerHeight - 100) / branchesTree.rowHeight); <add> <ide> branchesTree.emptyMessage = "loading..." <ide> <ide> branchesTree.on("afterChoose", function(e){ <ide> }; <ide> })); <ide> <del> scm.listAllRefs(function(err, data) { <del> if (err) { <del> branchesTree.emptyMessage = "Error while loading\n" + escapeHTML(err.message); <del> return console.error(err); <del> } <del> <del> loadBranches(data); <del> }); <add> refresh(); <ide> <ide> mnuSettings = new Menu({ items: [ <ide> new MenuItem({ caption: "Refresh", onclick: refresh }, plugin), <ide> noSelect: true, <ide> $sorted: true <ide> }; <add> var branchesRoot = { <add> path: "", <add> items: [recentLocal, primaryRemote, pullRequests, recentActive, all] <add> }; <add> var committersRoot = { <add> path: "", <add> items: [] <add> } <ide> <ide> function loadBranches(data){ <del> var root = { <del> path: "", <del> items: [recentLocal, primaryRemote, pullRequests, recentActive, all] <del> }; <add> var root = branchesRoot; <ide> root.items.forEach(function(n){ <ide> if (n.isPR) { <ide> n.items[0].items.length = 0; <ide> return n.items.length; <ide> }); <ide> <del> branchesTree.setRoot(root.items); <del> branchesTree.resize(); <add> // Reset committers root <add> committersRoot.items.length = 0; <add> <add> // branchesTree.filterRoot = data; <add> // branchesTree.setRoot(root.items); <add> // branchesTree.resize(); <ide> } <ide> <add> function showBranches(){ <add> branchesTree.filterProperty = "path"; <add> branchesTree.filterRoot = lastData; <add> branchesTree.setRoot(branchesRoot.items); <add> } <add> function showCommitters(){ <add> if (!committersRoot.items.length) { <add> var data = lastData; <add> var users = {}, emails = {}; <add> data.forEach(function(x) { <add> var user = x.authorname || "[None]"; <add> if (!emails[user]) emails[user] = x.authoremail; <add> (users[user] || (users[user] = [])).push(x); <add> }); <add> for (var user in users) { <add> committersRoot.items.push({ <add> label: user, <add> authorname: user, <add> email: emails[user], <add> type: "user", <add> items: users[user], <add> clone: function(){ <add> var x = function(){}; <add> x.prototype = this; <add> var y = new x(); <add> y.keepChildren = true; <add> y.isOpen = true; <add> return y; <add> } <add> }); <add> } <add> } <add> <add> branchesTree.filterProperty = "authorname"; <add> branchesTree.filterRoot = committersRoot; <add> branchesTree.setRoot(committersRoot.items); <add> } <add> <ide> function refresh(){ <del> <add> scm.listAllRefs(function(err, data) { <add> if (err) { <add> branchesTree.emptyMessage = "Error while loading\n" + escapeHTML(err.message); <add> branchesTree.setRoot(null); <add> return console.error(err); <add> } <add> <add> lastData = data; <add> loadBranches(data); <add> <add> if (displayMode == "branches") <add> showBranches(); <add> else <add> showCommitters(); <add> }); <ide> } <ide> <ide> /***** Lifecycle *****/
JavaScript
mit
18fbd9866a1a305c7cf825887c5521e436537dd3
0
AlexLeoTW/myBus_Server,AlexLeoTW/myBus_Server,AlexLeoTW/myBus_Server
module/cronJobs_test.js
/*jshint esversion: 6 */ var cronJobs = require('./cronJobs'); var mysql = require('promise-mysql'); var sql_config = require('../sql_config'); var db = mysql.createPool(sql_config.db); /*returnPlus123().then((x) => { console.log(x); return x + '123'; }).then((x) => { console.log(x); returnPlus123(x); }); function returnPlus123(x) { return new Promise((resolve, reject) => { resolve(x + '123'); }); }*/ /*var arr = []; for (var i=0; i<138; i++) { arr.push(i); } function recursivePrint(arr) { if (arr.length > 0) { return promisePrint(arr.pop()).then(recursivePrint(arr)); } } recursivePrint(arr); function promisePrint(x) { return new Promise((resolve, reject) => { if (x) { console.log(x); resolve(); } else { reject('No x'); } }); }*/ //cronJobs.updateBusTable(160); //cronJobs.updateBusArrival(); var timetable = JSON.parse('[".weekday.reverse.05.45.+8",".weekday.reverse.06.10.+8",".weekday.reverse.06.30.+8",".weekday.reverse.06.50.+8",".weekday.reverse.07.10.+8",".weekday.reverse.07.30.+8",".weekday.reverse.07.50.+8",".weekday.reverse.08.20.+8",".weekday.reverse.08.50.+8",".weekday.reverse.09.10.+8",".weekday.reverse.09.30.+8",".weekday.reverse.09.50.+8",".weekday.reverse.10.00.+8",".weekday.reverse.10.20.+8",".weekday.reverse.10.40.+8",".weekday.reverse.11.00.+8",".weekday.reverse.11.30.+8",".weekday.reverse.12.00.+8",".weekday.reverse.12.30.+8",".weekday.reverse.13.00.+8",".weekday.reverse.13.30.+8",".weekday.reverse.14.00.+8",".weekday.reverse.14.30.+8",".weekday.reverse.15.00.+8",".weekday.reverse.15.20.+8",".weekday.reverse.15.40.+8",".weekday.reverse.16.00.+8",".weekday.reverse.16.20.+8",".weekday.reverse.16.40.+8",".weekday.reverse.17.00.+8",".weekday.reverse.17.20.+8",".weekday.reverse.17.40.+8",".weekday.reverse.18.00.+8",".weekday.reverse.18.20.+8",".weekday.reverse.18.40.+8",".weekday.reverse.19.00.+8",".weekday.reverse.19.20.+8",".weekday.reverse.19.40.+8",".weekday.reverse.20.00.+8",".weekday.reverse.20.20.+8",".weekday.reverse.20.40.+8",".weekday.reverse.21.00.+8",".weekday.reverse.21.20.+8",".weekday.reverse.21.40.+8",".weekday.reverse.22.00.+8",".weekday.reverse.22.20.+8",".weekend.foward.00.10.+8",".weekend.foward.06.50.+8",".weekend.foward.07.10.+8",".weekend.foward.07.30.+8",".weekend.foward.07.40.+8",".weekend.foward.08.10.+8",".weekend.foward.08.30.+8",".weekend.foward.08.50.+8",".weekend.foward.09.20.+8",".weekend.foward.09.50.+8",".weekend.foward.10.00.+8",".weekend.foward.10.20.+8",".weekend.foward.10.40.+8",".weekend.foward.11.00.+8",".weekend.foward.11.20.+8",".weekend.foward.11.40.+8",".weekend.foward.12.00.+8",".weekend.foward.12.30.+8",".weekend.foward.13.00.+8",".weekend.foward.13.30.+8",".weekend.foward.14.00.+8",".weekend.foward.14.30.+8",".weekend.foward.14.45.+8",".weekend.foward.15.00.+8",".weekend.foward.15.30.+8",".weekend.foward.15.45.+8",".weekend.foward.16.00.+8",".weekend.foward.16.15.+8",".weekend.foward.16.30.+8",".weekend.foward.16.45.+8",".weekend.foward.17.00.+8",".weekend.foward.17.15.+8",".weekend.foward.17.30.+8",".weekend.foward.17.45.+8",".weekend.foward.18.00.+8",".weekend.foward.18.15.+8",".weekend.foward.18.30.+8",".weekend.foward.18.45.+8",".weekend.foward.19.00.+8",".weekend.foward.19.15.+8",".weekend.foward.19.30.+8",".weekend.foward.19.45.+8",".weekend.foward.20.00.+8",".weekend.foward.20.15.+8",".weekend.foward.20.30.+8",".weekend.foward.20.45.+8",".weekend.foward.21.00.+8",".weekend.foward.21.15.+8",".weekend.foward.21.30.+8",".weekend.foward.21.45.+8",".weekend.foward.22.10.+8",".weekend.foward.22.35.+8",".weekend.foward.23.00.+8",".weekend.foward.23.30.+8",".weekend.reverse.05.45.+8",".weekend.reverse.06.10.+8",".weekend.reverse.06.30.+8",".weekend.reverse.06.50.+8",".weekend.reverse.07.10.+8",".weekend.reverse.07.30.+8",".weekend.reverse.07.50.+8",".weekend.reverse.08.20.+8",".weekend.reverse.08.50.+8",".weekend.reverse.09.10.+8",".weekend.reverse.09.30.+8",".weekend.reverse.09.50.+8",".weekend.reverse.10.00.+8",".weekend.reverse.10.20.+8",".weekend.reverse.10.40.+8",".weekend.reverse.11.00.+8",".weekend.reverse.11.30.+8",".weekend.reverse.12.00.+8",".weekend.reverse.12.30.+8",".weekend.reverse.13.00.+8",".weekend.reverse.13.30.+8",".weekend.reverse.13.45.+8",".weekend.reverse.14.00.+8",".weekend.reverse.14.30.+8",".weekend.reverse.14.45.+8",".weekend.reverse.15.00.+8",".weekend.reverse.15.15.+8",".weekend.reverse.15.30.+8",".weekend.reverse.15.45.+8",".weekend.reverse.16.00.+8",".weekend.reverse.16.15.+8",".weekend.reverse.16.30.+8",".weekend.reverse.16.45.+8",".weekend.reverse.17.00.+8",".weekend.reverse.17.15.+8",".weekend.reverse.17.30.+8",".weekend.reverse.17.45.+8",".weekend.reverse.18.00.+8",".weekend.reverse.18.15.+8",".weekend.reverse.18.30.+8",".weekend.reverse.18.45.+8",".weekend.reverse.19.00.+8",".weekend.reverse.19.15.+8",".weekend.reverse.19.30.+8",".weekend.reverse.19.45.+8",".weekend.reverse.20.00.+8",".weekend.reverse.20.15.+8",".weekend.reverse.20.30.+8",".weekend.reverse.20.45.+8",".weekend.reverse.21.00.+8",".weekend.reverse.21.20.+8",".weekend.reverse.21.40.+8",".weekend.reverse.22.00.+8",".weekend.reverse.22.20.+8"]'); cronJobs.saveTimeList(timetable, 160); /*var timetable = { route: 160, descritpion: '高鐵臺中站 - 僑光科技大學', operator: '和欣客運', timeList: { weekday: { foward: [ {hour: 0, minute: 10, local: '+8'}, {hour: 06, minute: 50, local: '+8'} ], reverse: [ {hour: 05, minute: 45, local: "+8"}, {hour: 06, minute: 10, local: "+8"} ] }, weekend: { foward: [ {hour: 0, minute: 10, local: "+8"}, {hour: 06, minute: 50, local: "+8"} ], reverse: [ {hour: 05, minute: 45, local: "+8"}, {hour: 06, minute: 10, local: "+8"} ] } } };*/ //console.log(cronJobs.walkThroughTimetable(timetable.timeList, '')); /*function testSql () { var query = `SELECT * FROM \`Bus_arrival\``; console.log(query); return db.getConnection().then((connection) => { connection.query(query).then((rows) => { console.log(rows); }).catch((err) => { console.log('\t' + err.code); }).finally(() => { db.releaseConnection(connection); }); }); }*/
remove unused test case
module/cronJobs_test.js
remove unused test case
<ide><path>odule/cronJobs_test.js <del>/*jshint esversion: 6 */ <del> <del>var cronJobs = require('./cronJobs'); <del>var mysql = require('promise-mysql'); <del>var sql_config = require('../sql_config'); <del>var db = mysql.createPool(sql_config.db); <del> <del>/*returnPlus123().then((x) => { <del> console.log(x); <del> return x + '123'; <del>}).then((x) => { <del> console.log(x); <del> returnPlus123(x); <del>}); <del> <del>function returnPlus123(x) { <del> return new Promise((resolve, reject) => { <del> resolve(x + '123'); <del> }); <del>}*/ <del> <del>/*var arr = []; <del> <del>for (var i=0; i<138; i++) { <del> arr.push(i); <del>} <del> <del>function recursivePrint(arr) { <del> if (arr.length > 0) { <del> return promisePrint(arr.pop()).then(recursivePrint(arr)); <del> } <del>} <del> <del>recursivePrint(arr); <del> <del>function promisePrint(x) { <del> return new Promise((resolve, reject) => { <del> if (x) { <del> console.log(x); <del> resolve(); <del> } else { <del> reject('No x'); <del> } <del> }); <del>}*/ <del> <del>//cronJobs.updateBusTable(160); <del>//cronJobs.updateBusArrival(); <del>var timetable = JSON.parse('[".weekday.reverse.05.45.+8",".weekday.reverse.06.10.+8",".weekday.reverse.06.30.+8",".weekday.reverse.06.50.+8",".weekday.reverse.07.10.+8",".weekday.reverse.07.30.+8",".weekday.reverse.07.50.+8",".weekday.reverse.08.20.+8",".weekday.reverse.08.50.+8",".weekday.reverse.09.10.+8",".weekday.reverse.09.30.+8",".weekday.reverse.09.50.+8",".weekday.reverse.10.00.+8",".weekday.reverse.10.20.+8",".weekday.reverse.10.40.+8",".weekday.reverse.11.00.+8",".weekday.reverse.11.30.+8",".weekday.reverse.12.00.+8",".weekday.reverse.12.30.+8",".weekday.reverse.13.00.+8",".weekday.reverse.13.30.+8",".weekday.reverse.14.00.+8",".weekday.reverse.14.30.+8",".weekday.reverse.15.00.+8",".weekday.reverse.15.20.+8",".weekday.reverse.15.40.+8",".weekday.reverse.16.00.+8",".weekday.reverse.16.20.+8",".weekday.reverse.16.40.+8",".weekday.reverse.17.00.+8",".weekday.reverse.17.20.+8",".weekday.reverse.17.40.+8",".weekday.reverse.18.00.+8",".weekday.reverse.18.20.+8",".weekday.reverse.18.40.+8",".weekday.reverse.19.00.+8",".weekday.reverse.19.20.+8",".weekday.reverse.19.40.+8",".weekday.reverse.20.00.+8",".weekday.reverse.20.20.+8",".weekday.reverse.20.40.+8",".weekday.reverse.21.00.+8",".weekday.reverse.21.20.+8",".weekday.reverse.21.40.+8",".weekday.reverse.22.00.+8",".weekday.reverse.22.20.+8",".weekend.foward.00.10.+8",".weekend.foward.06.50.+8",".weekend.foward.07.10.+8",".weekend.foward.07.30.+8",".weekend.foward.07.40.+8",".weekend.foward.08.10.+8",".weekend.foward.08.30.+8",".weekend.foward.08.50.+8",".weekend.foward.09.20.+8",".weekend.foward.09.50.+8",".weekend.foward.10.00.+8",".weekend.foward.10.20.+8",".weekend.foward.10.40.+8",".weekend.foward.11.00.+8",".weekend.foward.11.20.+8",".weekend.foward.11.40.+8",".weekend.foward.12.00.+8",".weekend.foward.12.30.+8",".weekend.foward.13.00.+8",".weekend.foward.13.30.+8",".weekend.foward.14.00.+8",".weekend.foward.14.30.+8",".weekend.foward.14.45.+8",".weekend.foward.15.00.+8",".weekend.foward.15.30.+8",".weekend.foward.15.45.+8",".weekend.foward.16.00.+8",".weekend.foward.16.15.+8",".weekend.foward.16.30.+8",".weekend.foward.16.45.+8",".weekend.foward.17.00.+8",".weekend.foward.17.15.+8",".weekend.foward.17.30.+8",".weekend.foward.17.45.+8",".weekend.foward.18.00.+8",".weekend.foward.18.15.+8",".weekend.foward.18.30.+8",".weekend.foward.18.45.+8",".weekend.foward.19.00.+8",".weekend.foward.19.15.+8",".weekend.foward.19.30.+8",".weekend.foward.19.45.+8",".weekend.foward.20.00.+8",".weekend.foward.20.15.+8",".weekend.foward.20.30.+8",".weekend.foward.20.45.+8",".weekend.foward.21.00.+8",".weekend.foward.21.15.+8",".weekend.foward.21.30.+8",".weekend.foward.21.45.+8",".weekend.foward.22.10.+8",".weekend.foward.22.35.+8",".weekend.foward.23.00.+8",".weekend.foward.23.30.+8",".weekend.reverse.05.45.+8",".weekend.reverse.06.10.+8",".weekend.reverse.06.30.+8",".weekend.reverse.06.50.+8",".weekend.reverse.07.10.+8",".weekend.reverse.07.30.+8",".weekend.reverse.07.50.+8",".weekend.reverse.08.20.+8",".weekend.reverse.08.50.+8",".weekend.reverse.09.10.+8",".weekend.reverse.09.30.+8",".weekend.reverse.09.50.+8",".weekend.reverse.10.00.+8",".weekend.reverse.10.20.+8",".weekend.reverse.10.40.+8",".weekend.reverse.11.00.+8",".weekend.reverse.11.30.+8",".weekend.reverse.12.00.+8",".weekend.reverse.12.30.+8",".weekend.reverse.13.00.+8",".weekend.reverse.13.30.+8",".weekend.reverse.13.45.+8",".weekend.reverse.14.00.+8",".weekend.reverse.14.30.+8",".weekend.reverse.14.45.+8",".weekend.reverse.15.00.+8",".weekend.reverse.15.15.+8",".weekend.reverse.15.30.+8",".weekend.reverse.15.45.+8",".weekend.reverse.16.00.+8",".weekend.reverse.16.15.+8",".weekend.reverse.16.30.+8",".weekend.reverse.16.45.+8",".weekend.reverse.17.00.+8",".weekend.reverse.17.15.+8",".weekend.reverse.17.30.+8",".weekend.reverse.17.45.+8",".weekend.reverse.18.00.+8",".weekend.reverse.18.15.+8",".weekend.reverse.18.30.+8",".weekend.reverse.18.45.+8",".weekend.reverse.19.00.+8",".weekend.reverse.19.15.+8",".weekend.reverse.19.30.+8",".weekend.reverse.19.45.+8",".weekend.reverse.20.00.+8",".weekend.reverse.20.15.+8",".weekend.reverse.20.30.+8",".weekend.reverse.20.45.+8",".weekend.reverse.21.00.+8",".weekend.reverse.21.20.+8",".weekend.reverse.21.40.+8",".weekend.reverse.22.00.+8",".weekend.reverse.22.20.+8"]'); <del>cronJobs.saveTimeList(timetable, 160); <del> <del>/*var timetable = { route: 160, <del> descritpion: '高鐵臺中站 - 僑光科技大學', <del> operator: '和欣客運', <del> timeList: { <del> weekday: { <del> foward: [ <del> {hour: 0, minute: 10, local: '+8'}, <del> {hour: 06, minute: 50, local: '+8'} <del> ], <del> reverse: [ <del> {hour: 05, minute: 45, local: "+8"}, <del> {hour: 06, minute: 10, local: "+8"} <del> ] <del> }, <del> weekend: { <del> foward: [ <del> {hour: 0, minute: 10, local: "+8"}, <del> {hour: 06, minute: 50, local: "+8"} <del> ], <del> reverse: [ <del> {hour: 05, minute: 45, local: "+8"}, <del> {hour: 06, minute: 10, local: "+8"} <del> ] <del> } <del> } <del>};*/ <del>//console.log(cronJobs.walkThroughTimetable(timetable.timeList, '')); <del> <del>/*function testSql () { <del> var query = `SELECT * FROM \`Bus_arrival\``; <del> console.log(query); <del> return db.getConnection().then((connection) => { <del> connection.query(query).then((rows) => { <del> console.log(rows); <del> }).catch((err) => { <del> console.log('\t' + err.code); <del> }).finally(() => { <del> db.releaseConnection(connection); <del> }); <del> }); <del>}*/
Java
lgpl-2.1
ed2f92fc8f2234eb00f0af17da44e86adb436414
0
phoenixctms/ctsms,phoenixctms/ctsms,phoenixctms/ctsms,phoenixctms/ctsms
package org.phoenixctms.ctsms.executable; import java.io.UnsupportedEncodingException; import java.sql.Timestamp; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.TimeZone; import java.util.TreeMap; import java.util.regex.Pattern; import org.apache.commons.lang3.RandomStringUtils; import org.phoenixctms.ctsms.Search; import org.phoenixctms.ctsms.SearchParameter; import org.phoenixctms.ctsms.domain.CourseCategory; import org.phoenixctms.ctsms.domain.CourseCategoryDao; import org.phoenixctms.ctsms.domain.CourseParticipationStatusType; import org.phoenixctms.ctsms.domain.CourseParticipationStatusTypeDao; import org.phoenixctms.ctsms.domain.Criteria; import org.phoenixctms.ctsms.domain.CriteriaDao; import org.phoenixctms.ctsms.domain.CriterionProperty; import org.phoenixctms.ctsms.domain.CriterionPropertyDao; import org.phoenixctms.ctsms.domain.CriterionRestrictionDao; import org.phoenixctms.ctsms.domain.CriterionTieDao; import org.phoenixctms.ctsms.domain.Department; import org.phoenixctms.ctsms.domain.DepartmentDao; import org.phoenixctms.ctsms.domain.InputField; import org.phoenixctms.ctsms.domain.InputFieldDao; import org.phoenixctms.ctsms.domain.InputFieldSelectionSetValue; import org.phoenixctms.ctsms.domain.InputFieldSelectionSetValueDao; import org.phoenixctms.ctsms.domain.Proband; import org.phoenixctms.ctsms.domain.ProbandCategory; import org.phoenixctms.ctsms.domain.ProbandCategoryDao; import org.phoenixctms.ctsms.domain.ProbandDao; import org.phoenixctms.ctsms.domain.ProbandListStatusEntry; import org.phoenixctms.ctsms.domain.ProbandListStatusEntryDao; import org.phoenixctms.ctsms.domain.SponsoringTypeDao; import org.phoenixctms.ctsms.domain.Staff; import org.phoenixctms.ctsms.domain.StaffDao; import org.phoenixctms.ctsms.domain.TeamMemberRole; import org.phoenixctms.ctsms.domain.TeamMemberRoleDao; import org.phoenixctms.ctsms.domain.TimelineEventType; import org.phoenixctms.ctsms.domain.TimelineEventTypeDao; import org.phoenixctms.ctsms.domain.TrialStatusTypeDao; import org.phoenixctms.ctsms.domain.TrialTypeDao; import org.phoenixctms.ctsms.domain.User; import org.phoenixctms.ctsms.domain.UserDao; import org.phoenixctms.ctsms.domain.UserPermissionProfile; import org.phoenixctms.ctsms.domain.UserPermissionProfileDao; import org.phoenixctms.ctsms.domain.VisitTypeDao; import org.phoenixctms.ctsms.enumeration.AuthenticationType; import org.phoenixctms.ctsms.enumeration.CriterionRestriction; import org.phoenixctms.ctsms.enumeration.CriterionTie; import org.phoenixctms.ctsms.enumeration.CriterionValueType; import org.phoenixctms.ctsms.enumeration.DBModule; import org.phoenixctms.ctsms.enumeration.EventImportance; import org.phoenixctms.ctsms.enumeration.FileModule; import org.phoenixctms.ctsms.enumeration.InputFieldType; import org.phoenixctms.ctsms.enumeration.PermissionProfile; import org.phoenixctms.ctsms.enumeration.RandomizationMode; import org.phoenixctms.ctsms.enumeration.Sex; import org.phoenixctms.ctsms.enumeration.VariablePeriod; import org.phoenixctms.ctsms.exception.ServiceException; import org.phoenixctms.ctsms.pdf.PDFImprinter; import org.phoenixctms.ctsms.pdf.PDFStream; import org.phoenixctms.ctsms.security.CryptoUtil; import org.phoenixctms.ctsms.service.course.CourseService; import org.phoenixctms.ctsms.service.inventory.InventoryService; import org.phoenixctms.ctsms.service.proband.ProbandService; import org.phoenixctms.ctsms.service.shared.FileService; import org.phoenixctms.ctsms.service.shared.InputFieldService; import org.phoenixctms.ctsms.service.shared.SearchService; import org.phoenixctms.ctsms.service.shared.SelectionSetService; import org.phoenixctms.ctsms.service.shared.ToolsService; import org.phoenixctms.ctsms.service.staff.StaffService; import org.phoenixctms.ctsms.service.trial.TrialService; import org.phoenixctms.ctsms.service.user.UserService; import org.phoenixctms.ctsms.util.CommonUtil; import org.phoenixctms.ctsms.util.CoreUtil; import org.phoenixctms.ctsms.util.ExecUtil; import org.phoenixctms.ctsms.util.GermanPersonNames; import org.phoenixctms.ctsms.util.JobOutput; import org.phoenixctms.ctsms.util.ServiceUtil; import org.phoenixctms.ctsms.util.date.DateCalc; import org.phoenixctms.ctsms.util.xeger.Xeger; import org.phoenixctms.ctsms.vo.AuthenticationVO; import org.phoenixctms.ctsms.vo.CourseInVO; import org.phoenixctms.ctsms.vo.CourseOutVO; import org.phoenixctms.ctsms.vo.CourseParticipationStatusEntryInVO; import org.phoenixctms.ctsms.vo.CourseParticipationStatusEntryOutVO; import org.phoenixctms.ctsms.vo.CriteriaInVO; import org.phoenixctms.ctsms.vo.CriteriaOutVO; import org.phoenixctms.ctsms.vo.CriterionInVO; import org.phoenixctms.ctsms.vo.DepartmentVO; import org.phoenixctms.ctsms.vo.DutyRosterTurnInVO; import org.phoenixctms.ctsms.vo.DutyRosterTurnOutVO; import org.phoenixctms.ctsms.vo.ECRFFieldInVO; import org.phoenixctms.ctsms.vo.ECRFFieldOutVO; import org.phoenixctms.ctsms.vo.ECRFInVO; import org.phoenixctms.ctsms.vo.ECRFOutVO; import org.phoenixctms.ctsms.vo.FileInVO; import org.phoenixctms.ctsms.vo.FileOutVO; import org.phoenixctms.ctsms.vo.FileStreamInVO; import org.phoenixctms.ctsms.vo.InputFieldInVO; import org.phoenixctms.ctsms.vo.InputFieldOutVO; import org.phoenixctms.ctsms.vo.InputFieldSelectionSetValueInVO; import org.phoenixctms.ctsms.vo.InputFieldSelectionSetValueOutVO; import org.phoenixctms.ctsms.vo.InquiryInVO; import org.phoenixctms.ctsms.vo.InquiryOutVO; import org.phoenixctms.ctsms.vo.InquiryValueInVO; import org.phoenixctms.ctsms.vo.InventoryInVO; import org.phoenixctms.ctsms.vo.InventoryOutVO; import org.phoenixctms.ctsms.vo.PSFVO; import org.phoenixctms.ctsms.vo.PasswordInVO; import org.phoenixctms.ctsms.vo.ProbandGroupInVO; import org.phoenixctms.ctsms.vo.ProbandGroupOutVO; import org.phoenixctms.ctsms.vo.ProbandInVO; import org.phoenixctms.ctsms.vo.ProbandListEntryInVO; import org.phoenixctms.ctsms.vo.ProbandListEntryOutVO; import org.phoenixctms.ctsms.vo.ProbandListEntryTagInVO; import org.phoenixctms.ctsms.vo.ProbandListEntryTagOutVO; import org.phoenixctms.ctsms.vo.ProbandListEntryTagValueInVO; import org.phoenixctms.ctsms.vo.ProbandListStatusEntryInVO; import org.phoenixctms.ctsms.vo.ProbandListStatusEntryOutVO; import org.phoenixctms.ctsms.vo.ProbandListStatusTypeVO; import org.phoenixctms.ctsms.vo.ProbandOutVO; import org.phoenixctms.ctsms.vo.StaffInVO; import org.phoenixctms.ctsms.vo.StaffOutVO; import org.phoenixctms.ctsms.vo.TeamMemberInVO; import org.phoenixctms.ctsms.vo.TeamMemberOutVO; import org.phoenixctms.ctsms.vo.TimelineEventInVO; import org.phoenixctms.ctsms.vo.TimelineEventOutVO; import org.phoenixctms.ctsms.vo.TrialInVO; import org.phoenixctms.ctsms.vo.TrialOutVO; import org.phoenixctms.ctsms.vo.UserInVO; import org.phoenixctms.ctsms.vo.UserOutVO; import org.phoenixctms.ctsms.vo.VisitInVO; import org.phoenixctms.ctsms.vo.VisitOutVO; import org.phoenixctms.ctsms.vo.VisitScheduleItemInVO; import org.phoenixctms.ctsms.vo.VisitScheduleItemOutVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.io.ClassPathResource; public class DemoDataProvider { private enum InputFields { HEIGHT("Körpergröße"), WEIGHT("Körpergewicht"), BMI("Body Mass Index"), DIABETES_YN("Diabetes J/N"), DIABETES_TYPE("Diabetes Typ"), DIABETES_SINCE("Diabetes seit"), DIABETES_HBA1C_MMOLPERMOL("HbA1C in mmol/mol"), DIABETES_HBA1C_PERCENT("HbA1C in prozent"), DIABETES_HBA1C_DATE("HbA1C Datum"), DIABETES_C_PEPTIDE("C-Peptid"), // µg/l DIABETES_ATTENDING_PHYSICIAN("Arzt in Behandlung"), DIABETES_METHOD_OF_TREATMENT("Diabetes Behandlungsmethode"), // Diät sport insulintherapie orale Antidiabetika DIABETES_MEDICATION("Diabetes Medikamente"), CLINICAL_TRIAL_EXPERIENCE_YN("Erfahrung mit klin. Studien J/N"), SMOKER_YN("Raucher J/N"), CIGARETTES_PER_DAY("Zigaretten pro Tag"), CHRONIC_DISEASE_YN("Chronische Erkrankung J/N"), CHRONIC_DISEASE("Chronische Erkrankung"), EPILEPSY_YN("Epilepsie J/N"), EPILEPSY("Epilepsie"), CARDIAC_PROBLEMS_YN("Herzprobleme J/N"), CARDIAC_PROBLEMS("Herzprobleme"), HYPERTENSION_YN("Bluthochdruck J/N"), HYPERTENSION("Bluthochdruck"), RENAL_INSUFFICIENCY_YN("Niereninsuffizienz/-erkrankung J/N"), // renal RENAL_INSUFFICIENCY("Niereninsuffizienz/-erkrankung"), LIVER_DISEASE_YN("Lebererkrankung J/N"), // liver diseaseYN LIVER_DISEASE("Lebererkrankung"), ANEMIA_YN("Anemie J/N"), // anemiaYN ANEMIA("Anemie"), IMMUNE_MEDAITED_DISEASE_YN("Autoimmunerkrankung J/N"), // immune mediated diseaseYN IMMUNE_MEDAITED_DISEASE("Autoimmunerkrankung"), GESTATION_YN("schwanger, stillen etc. J/N"), // gestationYN GESTATION("schwanger, stillen etc."), GESTATION_TYPE("schwanger, stillen etc. Auswahl"), CONTRACEPTION_YN("Empfängnisverhütung J/N"), // contraceptionYN CONTRACEPTION("Empfängnisverhütung"), CONTRACEPTION_TYPE("Empfängnisverhütung Auswahl"), ALCOHOL_DRUG_ABUSE_YN("Missbrauch von Alkohol/Drogen J/N"), // alcohol_drug_abuseYN ALCOHOL_DRUG_ABUSE("Missbrauch von Alkohol/Drogen"), PSYCHIATRIC_CONDITION_YN("Psychiatrische Erkrankung J/N"), // psychiatric_conditionYN PSYCHIATRIC_CONDITION("Psychiatrische Erkrankung"), ALLERGY_YN("Allergien J/N"), // allergyYN ALLERGY("Allergien"), MEDICATION_YN("Medikamente J/N"), // medicationYN MEDICATION("Medikamente"), EYE_PROBLEMS_YN("Probleme mit den Augen J/N"), // eye_probalemsYN EYE_PROBLEMS("Probleme mit den Augen"), FEET_PROBLEMS_YN("Probleme mit den Füßen J/N"), // feet_probalemsYN FEET_PROBLEMS("Probleme mit den Füßen"), DIAGNOSTIC_FINDINGS_AVAILABLE_YN("Befunde zuhause J/N"), DIAGNOSTIC_FINDINGS_AVAILABLE("Befunde zuhause"), GENERAL_STATE_OF_HEALTH("Allgemeiner Gesundheitszustand"), NOTE("Anmerkung"), SUBJECT_NUMBER("Subject Number"), IC_DATE("Informed Consent Date"), SCREENING_DATE("Screening Date"), LAB_NUMBER("Lab Number"), RANDOM_NUMBER("Random Number"), LETTER_TO_PHYSICIAN_SENT("Letter to physician sent"), PARTICIPATION_LETTER_IN_MEDOCS("Participation letter in MR/Medocs"), LETTER_TO_SUBJECT_AT_END_OF_STUDY("Letter to subject at end of study"), COMPLETION_LETTER_IN_MEDOCS("Completion letter in MR/Medocs"), BODY_HEIGHT("Body Height"), BODY_WEIGHT("Body Weight"), BODY_MASS_INDEX("BMI"), OBESITY("Obesity"), EGFR("eGFR"), SERUM_CREATININ_CONCENTRATION("Serum Creatinin Concentration"), ETHNICITY("Ethnicity"), HBA1C_PERCENT("HbA1C (percent)"), HBA1C_MMOLPERMOL("HbA1C (mmol/mol)"), MANNEQUIN("Mannequin"), ESR("ESR"), VAS("VAS"), DAS28("DAS28"), DISTANCE("Distance"), ALPHA_ID("Alpha-ID"), STRING_SINGLELINE("singleline text"), STRING_MULTILINE("multiline text"), FLOAT("decimal"), INTEGER("integer"), DIAGNOSIS_START("diagnosis from"), DIAGNOSIS_END("diagnosis to"), DIAGNOSIS_COUNT("diagnosis count"); private final String value; private InputFields(final String value) { this.value = value; } @Override public String toString() { return value; } } private enum InputFieldValues { TYP_1_DIABETES("Typ 1 Diabetes"), TYP_2_DIABETES_MIT_INSULINEIGENPRODUKTION("Typ 2 Diabetes mit Insulineigenproduktion"), TYP_2_DIABETES_OHNE_INSULINEIGENPRODUKTION("Typ 2 Diabetes ohne Insulineigenproduktion"), DIAET("Diät"), SPORTLICHE_BETAETIGUNG("Sportliche Betätigung"), ORALE_ANTIDIABETIKA("Orale Antidiabetika"), INSULINTHERAPIE("Insulintherapie"), CIGARETTES_UNTER_5("Unter 5"), CIGARETTES_5_20("5-20"), CIGARETTES_20_40("20-40"), CIGARETTES_UEBER_40("über 40"), SCHWANGER("schwanger"), STILLEN("stillen"), HORMONELL("hormonell"), MECHANISCH("mechanisch"), INTRAUTERINPESSARE("Intrauterinpessare"), CHEMISCH("chemisch"), OPERATIV("operativ"), SHORTWEIGHT("shortweight"), NORMAL_WEIGHT("normal weight"), OVERWEIGHT("overweight"), ADIPOSITY_DEGREE_I("adiposity degree I"), ADIPOSITY_DEGREE_II("adiposity degree II"), ADIPOSITY_DEGREE_III("adiposity degree III"), AMERICAN_INDIAN_OR_ALASKA_NATIVE("American Indian or Alaska Native"), ASIAN("Asian"), BLACK("Black"), NATIVE_HAWAIIAN_OR_OTHER_PACIFIC_ISLANDER("Native Hawaiian or Other Pacific Islander"), WHITE("White"), SHOULDER_RIGHT("shoulder right"), SHOULDER_LEFT("shoulder left"), ELLBOW_RIGHT("ellbow right"), ELLBOW_LEFT("ellbow left"), WRIST_RIGHT("wrist right"), WRIST_LEFT("wrist left"), THUMB_BASE_RIGHT("thumb base right"), THUMB_MIDDLE_RIGHT("thumb middle right"), THUMB_BASE_LEFT("thumb base left"), THUMB_MIDDLE_LEFT("thumb middle left"), INDEX_FINGER_BASE_RIGHT("index finger base right"), INDEX_FINGER_MIDDLE_RIGHT("index finger middle right"), MIDDLE_FINGER_BASE_RIGHT("middle finger base right"), MIDDLE_FINGER_MIDDLE_RIGHT("middle finger middle right"), RING_FINGER_BASE_RIGHT("ring finger base right"), RING_FINGER_MIDDLE_RIGHT("ring finger middle right"), LITTLE_FINGER_BASE_RIGHT("little finger base right"), LITTLE_FINGER_MIDDLE_RIGHT("little finger middle right"), INDEX_FINGER_BASE_LEFT("index finger base left"), INDEX_FINGER_MIDDLE_LEFT("index finger middle left"), MIDDLE_FINGER_BASE_LEFT("middle finger base left"), MIDDLE_FINGER_MIDDLE_LEFT("middle finger middle left"), RING_FINGER_BASE_LEFT("ring finger base left"), RING_FINGER_MIDDLE_LEFT("ring finger middle left"), LITTLE_FINGER_BASE_LEFT("little finger base left"), LITTLE_FINGER_MIDDLE_LEFT("little finger middle left"), KNEE_RIGHT("knee right"), KNEE_LEFT("knee left"), VAS_1("vas-1"), VAS_2("vas-2"), VAS_3("vas-3"), VAS_4("vas-4"), VAS_5("vas-5"), VAS_6("vas-6"), VAS_7("vas-7"), VAS_8("vas-8"), VAS_9("vas-9"), VAS_10("vas-10"); private final String value; private InputFieldValues(final String value) { this.value = value; } @Override public String toString() { return value; } } public enum SearchCriteria { ALL_INVENTORY("all inventory"), ALL_STAFF("all staff"), ALL_COURSES("all courses"), ALL_TRIALS("all trials"), ALL_PROBANDS("all probands"), ALL_INPUTFIELDS("all inputfields"), ALL_MASSMAILS("all_massmails"), ALL_USERS("all users"), SUBJECTS_1("subjects_1"); private final String value; private SearchCriteria(final String value) { this.value = value; } @Override public String toString() { return value; } } private final class SearchCriterion { private CriterionTie junction; private String property; private CriterionRestriction operator; private boolean booleanValue; private Date dateValue; private Float floatValue; private Long longValue; private String stringValue; private SearchCriterion(CriterionTie junction, String property, CriterionRestriction operator) { this.junction = junction; this.property = property; this.operator = operator; booleanValue = false; dateValue = null; floatValue = null; longValue = null; stringValue = null; } private SearchCriterion(CriterionTie junction, String property, CriterionRestriction operator, boolean value) { this(junction, property, operator); booleanValue = value; } private SearchCriterion(CriterionTie junction, String property, CriterionRestriction operator, Date value) { this(junction, property, operator); dateValue = value; } private SearchCriterion(CriterionTie junction, String property, CriterionRestriction operator, Float value) { this(junction, property, operator); floatValue = value; } private SearchCriterion(CriterionTie junction, String property, CriterionRestriction operator, Long value) { this(junction, property, operator); longValue = value; } private SearchCriterion(CriterionTie junction, String property, CriterionRestriction operator, String value) { this(junction, property, operator); stringValue = value; } public CriterionInVO buildCriterionInVO(DemoDataProvider d, DBModule module, int position) { CriterionInVO newCriterion = new CriterionInVO(); newCriterion.setTieId(junction != null ? d.criterionTieDao.searchUniqueTie(junction).getId() : null); CriterionProperty p = CommonUtil.isEmptyString(property) ? null : (new ArrayList<CriterionProperty>(criterionPropertyDao.search(new Search(new SearchParameter[] { new SearchParameter("module", module, SearchParameter.EQUAL_COMPARATOR), new SearchParameter("property", property, SearchParameter.EQUAL_COMPARATOR), })))).iterator().next(); newCriterion.setPropertyId(p != null ? p.getId() : null); newCriterion.setRestrictionId(operator != null ? d.criterionRestrictionDao.searchUniqueRestriction(operator).getId() : null); newCriterion.setPosition((long) position); newCriterion.setBooleanValue(booleanValue); newCriterion.setFloatValue(floatValue); newCriterion.setLongValue(longValue); newCriterion.setStringValue(stringValue); if (p != null && (p.getValueType() == CriterionValueType.DATE || p.getValueType() == CriterionValueType.DATE_HASH)) { newCriterion.setDateValue(dateValue); newCriterion.setTimeValue(null); newCriterion.setTimestampValue(null); } else if (p != null && (p.getValueType() == CriterionValueType.TIME || p.getValueType() == CriterionValueType.TIME_HASH)) { newCriterion.setDateValue(null); newCriterion.setTimeValue(dateValue); newCriterion.setTimestampValue(null); } else if (p != null && (p.getValueType() == CriterionValueType.TIMESTAMP || p.getValueType() == CriterionValueType.TIMESTAMP_HASH)) { newCriterion.setDateValue(null); newCriterion.setTimeValue(null); newCriterion.setTimestampValue(dateValue); } else { newCriterion.setDateValue(null); newCriterion.setTimeValue(null); newCriterion.setTimestampValue(null); } return newCriterion; } } private final class Stroke { private final static String INK_VALUE_CHARSET = "UTF8"; public String color; public String path; public String strokesId; public String value; public boolean valueSet; private Stroke() { color = null; path = null; strokesId = CommonUtil.generateUUID(); value = null; valueSet = false; } public Stroke(String path) { this(); this.color = "#00ff00"; this.path = path; } public Stroke(String path, String value) { this(path); setValue(value); } public Stroke(String color, String path, String value) { this(); this.color = color; this.path = path; setValue(value); } public byte[] getBytes() throws UnsupportedEncodingException { return toString().getBytes(INK_VALUE_CHARSET); } private void setValue(String value) { this.value = value; valueSet = true; } @Override public String toString() { return String.format("[{" + "\"fill\": \"%s\"," + "\"stroke\": \"%s\"," + "\"path\": \"%s\"," + "\"stroke-opacity\": 0.4," + "\"stroke-width\": 2," + "\"stroke-linecap\": \"round\"," + "\"stroke-linejoin\": \"round\"," + "\"transform\": []," + "\"type\": \"path\"," + "\"fill-opacity\": 0.2," + "\"strokes-id\": \"%s\"}]", color, color, path, strokesId); } } private static final int FILE_COUNT_PER_STAFF = 5; private static final int FILE_COUNT_PER_ORGANISATION = 5; private static final int FILE_COUNT_PER_COURSE = 10; private static final int FILE_COUNT_PER_INVENTORY = 10; private static final int FILE_COUNT_PER_PROBAND = 3; private static final int FILE_COUNT_PER_TRIAL = 500; private static final boolean CREATE_FILES = false; @Autowired private DepartmentDao departmentDao; @Autowired private UserDao userDao; @Autowired private UserPermissionProfileDao userPermissionProfileDao; @Autowired private StaffDao staffDao; @Autowired private ToolsService toolsService; @Autowired private StaffService staffService; @Autowired private UserService userService; @Autowired private CourseService courseService; @Autowired private SelectionSetService selectionSetService; @Autowired private InventoryService inventoryService; @Autowired private ProbandService probandService; @Autowired private ProbandDao probandDao; @Autowired private ProbandCategoryDao probandCategoryDao; @Autowired private CourseCategoryDao courseCategoryDao; @Autowired private TrialStatusTypeDao trialStatusTypeDao; @Autowired private SponsoringTypeDao sponsoringTypeDao; @Autowired private TrialTypeDao trialTypeDao; @Autowired private VisitTypeDao visitTypeDao; @Autowired private TrialService trialService; @Autowired private FileService fileService; @Autowired private InputFieldService inputFieldService; @Autowired private SearchService searchService; @Autowired private InputFieldDao inputFieldDao; @Autowired private InputFieldSelectionSetValueDao inputFieldSelectionSetValueDao; @Autowired private TeamMemberRoleDao teamMemberRoleDao; @Autowired private TimelineEventTypeDao timelineEventTypeDao; @Autowired private CourseParticipationStatusTypeDao courseParticipationStatusTypeDao; @Autowired private ProbandListStatusEntryDao probandListStatusEntryDao; @Autowired private CriteriaDao criteriaDao; @Autowired private CriterionTieDao criterionTieDao; @Autowired private CriterionPropertyDao criterionPropertyDao; @Autowired private CriterionRestrictionDao criterionRestrictionDao; private Random random; private String prefix; private int year; private int departmentCount; private int usersPerDepartmentCount; // more users than persons intended private JobOutput jobOutput; private ApplicationContext context; public DemoDataProvider() { random = new Random(); prefix = RandomStringUtils.randomAlphanumeric(4).toLowerCase(); year = Calendar.getInstance().get(Calendar.YEAR); } private void addInkRegions(AuthenticationVO auth, InputFieldOutVO inputField, TreeMap<InputFieldValues, Stroke> inkRegions) throws Exception { auth = (auth == null ? getRandomAuth() : auth); Iterator<Entry<InputFieldValues, Stroke>> it = inkRegions.entrySet().iterator(); while (it.hasNext()) { Entry<InputFieldValues, Stroke> inkRegion = it.next(); Stroke stroke = inkRegion.getValue(); InputFieldSelectionSetValueInVO newSelectionSetValue = new InputFieldSelectionSetValueInVO(); newSelectionSetValue.setFieldId(inputField.getId()); newSelectionSetValue.setName(inkRegion.getKey().toString()); newSelectionSetValue.setPreset(false); newSelectionSetValue.setValue(stroke.valueSet ? stroke.value : inkRegion.getKey().toString()); newSelectionSetValue.setInkRegions(stroke.getBytes()); newSelectionSetValue.setStrokesId(stroke.strokesId); InputFieldSelectionSetValueOutVO out = inputFieldService.addSelectionSetValue(auth, newSelectionSetValue); jobOutput.println("ink region created: " + out.getName()); } } private void addSelectionSetValues(AuthenticationVO auth, InputFieldOutVO inputField, TreeMap<InputFieldValues, Boolean> selectionSetValues) throws Exception { auth = (auth == null ? getRandomAuth() : auth); Iterator<Entry<InputFieldValues, Boolean>> it = selectionSetValues.entrySet().iterator(); while (it.hasNext()) { Entry<InputFieldValues, Boolean> selectionSetValue = it.next(); InputFieldSelectionSetValueInVO newSelectionSetValue = new InputFieldSelectionSetValueInVO(); newSelectionSetValue.setFieldId(inputField.getId()); newSelectionSetValue.setName(selectionSetValue.getKey().toString()); newSelectionSetValue.setPreset(selectionSetValue.getValue()); newSelectionSetValue.setValue(selectionSetValue.getKey().toString()); InputFieldSelectionSetValueOutVO out = inputFieldService.addSelectionSetValue(auth, newSelectionSetValue); jobOutput.println("selection set value created: " + out.getName()); } } private ArrayList<UserPermissionProfile> addUserPermissionProfiles(UserOutVO userVO, ArrayList<PermissionProfile> profiles) throws Exception { User user = userDao.load(userVO.getId()); Timestamp now = new Timestamp(System.currentTimeMillis()); ArrayList<UserPermissionProfile> result = new ArrayList<UserPermissionProfile>(profiles.size()); Iterator<PermissionProfile> profilesIt = profiles.iterator(); while (profilesIt.hasNext()) { PermissionProfile profile = profilesIt.next(); UserPermissionProfile userPermissionProfile = UserPermissionProfile.Factory.newInstance(); userPermissionProfile.setActive(true); userPermissionProfile.setProfile(profile); userPermissionProfile.setUser(user); CoreUtil.modifyVersion(userPermissionProfile, now, null); result.add(userPermissionProfileDao.create(userPermissionProfile)); jobOutput.println("permission profile " + profile.toString() + " added"); } return result; } private UserOutVO assignUser(StaffOutVO staff) throws Exception { Set<User> unassignedUsers = userDao.search(new Search(new SearchParameter[] { new SearchParameter("identity", SearchParameter.NULL_COMPARATOR), new SearchParameter("department.id", getDepartmentIds(), SearchParameter.IN_COMPARATOR) })); User user = getRandomElement(unassignedUsers); UserOutVO userVO = null; if (user != null) { UserInVO modifiedUser = new UserInVO(); modifiedUser.setDepartmentId(user.getDepartment().getId()); modifiedUser.setId(user.getId()); modifiedUser.setIdentityId(staff.getId()); modifiedUser.setName(user.getName()); modifiedUser.setLocale(user.getLocale()); modifiedUser.setTimeZone(user.getTimeZone()); modifiedUser.setDateFormat(user.getDateFormat()); modifiedUser.setDecimalSeparator(user.getDecimalSeparator()); modifiedUser.setTheme(user.getTheme()); modifiedUser.setLocked(user.isLocked()); modifiedUser.setShowTooltips(user.isShowTooltips()); modifiedUser.setDecrypt(user.isDecrypt()); modifiedUser.setDecryptUntrusted(user.isDecryptUntrusted()); modifiedUser.setEnableInventoryModule(true); modifiedUser.setEnableStaffModule(true); modifiedUser.setEnableCourseModule(true); modifiedUser.setEnableTrialModule(true); modifiedUser.setEnableInputFieldModule(true); modifiedUser.setEnableProbandModule(true); modifiedUser.setEnableMassMailModule(true); modifiedUser.setEnableUserModule(true); modifiedUser.setAuthMethod(user.getAuthMethod()); modifiedUser.setVersion(user.getVersion()); userVO = userService.updateUser(getRandomAuth(user.getDepartment().getId()), modifiedUser, null, null, null); jobOutput.println("user " + userVO.getName() + " assigned to " + staff.getName()); } return userVO; } private InputFieldOutVO createCheckBoxField(AuthenticationVO auth, String name, String category, String title, String comment, boolean booleanPreset) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.CHECKBOX); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setBooleanPreset(booleanPreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("check box input field created: " + out.getName()); return out; } private CourseOutVO createCourse(AuthenticationVO auth, int courseNum, int departmentNum, Collection<Long> precedingCourseIds, Collection<Staff> institutions, int maxParticipants) throws Exception { auth = (auth == null ? getRandomAuth() : auth); CourseInVO newCourse = new CourseInVO(); Date stop; VariablePeriod validityPeriod = getRandomElement(new VariablePeriod[] { VariablePeriod.MONTH, VariablePeriod.SIX_MONTHS, VariablePeriod.YEAR }); Long validityPeriodDays = (validityPeriod == VariablePeriod.EXPLICIT ? getRandomElement(new Long[] { 7L, 14L, 21L }) : null); if (precedingCourseIds != null && precedingCourseIds.size() > 0) { stop = null; Iterator<Long> it = precedingCourseIds.iterator(); while (it.hasNext()) { Long precedingCourseId = it.next(); CourseOutVO precedingCourse = courseService.getCourse(auth, precedingCourseId, 1, null, null); if (precedingCourse.isExpires()) { Date precedingExpiration = DateCalc.addInterval(precedingCourse.getStop(), precedingCourse.getValidityPeriod().getPeriod(), precedingCourse.getValidityPeriodDays()); if (stop == null || precedingExpiration.compareTo(stop) < 0) { stop = precedingExpiration; } } } stop = stop == null ? getRandomCourseStop() : DateCalc.subInterval(stop, VariablePeriod.EXPLICIT, new Long(random.nextInt(8))); newCourse.setPrecedingCourseIds(precedingCourseIds); } else { stop = getRandomCourseStop(); } if (getRandomBoolean(50)) { newCourse.setExpires(true); newCourse.setValidityPeriod(validityPeriod); newCourse.setValidityPeriodDays(validityPeriodDays); } else { newCourse.setExpires(false); } Date start; if (getRandomBoolean(50)) { start = null; } else { VariablePeriod courseDurationPeriod = getRandomElement(new VariablePeriod[] { VariablePeriod.EXPLICIT, VariablePeriod.MONTH, VariablePeriod.SIX_MONTHS, VariablePeriod.YEAR }); Long courseDurationPeriodDays = (courseDurationPeriod == VariablePeriod.EXPLICIT ? getRandomElement(new Long[] { 7L, 14L, 21L }) : null); start = DateCalc.subInterval(stop, courseDurationPeriod, courseDurationPeriodDays); } if (getRandomBoolean(50)) { newCourse.setSelfRegistration(false); } else { newCourse.setSelfRegistration(true); newCourse.setMaxNumberOfParticipants(1L + random.nextInt(maxParticipants)); Date participationDeadline; if (getRandomBoolean(50)) { if (start != null) { participationDeadline = DateCalc.subInterval(start, VariablePeriod.EXPLICIT, new Long(random.nextInt(8))); } else { participationDeadline = DateCalc.subInterval(stop, VariablePeriod.EXPLICIT, new Long(random.nextInt(8))); } } else { participationDeadline = null; } newCourse.setParticipationDeadline(participationDeadline); } newCourse.setDepartmentId(getDepartmentId(departmentNum)); Collection<CourseCategory> categories = courseCategoryDao.search(new Search(new SearchParameter[] { new SearchParameter("trialRequired", false, SearchParameter.EQUAL_COMPARATOR) })); newCourse.setCategoryId(getRandomElement(categories).getId()); newCourse.setInstitutionId(getRandomBoolean(50) ? getRandomElement(institutions).getId() : null); newCourse.setName("course_" + (departmentNum + 1) + "_" + (courseNum + 1)); newCourse.setDescription("description for " + newCourse.getName()); newCourse.setStart(start); newCourse.setStop(stop); if (getRandomBoolean(50)) { newCourse.setShowCvPreset(true); newCourse.setCvTitle("Course " + (departmentNum + 1) + "-" + (courseNum + 1)); if (getRandomBoolean(50)) { newCourse.setShowCommentCvPreset(true); newCourse.setCvCommentPreset("CV comment for " + newCourse.getCvTitle()); } else { newCourse.setShowCommentCvPreset(false); } newCourse.setCvSectionPresetId(getRandomElement(selectionSetService.getCvSections(auth, null)).getId()); } else { newCourse.setShowCvPreset(false); } if (getRandomBoolean(50)) { newCourse.setShowTrainingRecordPreset(true); //newCourse.setCvTitle(cvTitle); newCourse.setTrainingRecordSectionPresetId(getRandomElement(selectionSetService.getTrainingRecordSections(auth, null)).getId()); } else { newCourse.setShowTrainingRecordPreset(false); } newCourse.setCertificate(false); CourseOutVO course = courseService.addCourse(auth, newCourse, null, null, null); jobOutput.println("course created: " + course.getName()); ArrayList<Staff> persons = new ArrayList<Staff>(staffDao.search(new Search(new SearchParameter[] { new SearchParameter("person", true, SearchParameter.EQUAL_COMPARATOR) }))); Iterator<Staff> participantStaffIt; if (course.getMaxNumberOfParticipants() != null) { participantStaffIt = getUniqueRandomElements(persons, CommonUtil.safeLongToInt(course.getMaxNumberOfParticipants())).iterator(); } else { participantStaffIt = getUniqueRandomElements(persons, 1 + random.nextInt(maxParticipants)).iterator(); } Collection<CourseParticipationStatusType> initialStates = courseParticipationStatusTypeDao.findInitialStates(true, course.isSelfRegistration()); while (participantStaffIt.hasNext()) { CourseParticipationStatusEntryInVO newCourseParticipationStatusEntry = new CourseParticipationStatusEntryInVO(); newCourseParticipationStatusEntry.setComment(course.getCvCommentPreset()); newCourseParticipationStatusEntry.setCourseId(course.getId()); newCourseParticipationStatusEntry.setCvSectionId(course.getCvSectionPreset() == null ? null : course.getCvSectionPreset().getId()); newCourseParticipationStatusEntry.setShowCommentCv(course.getShowCommentCvPreset()); newCourseParticipationStatusEntry.setShowCv(course.getShowCvPreset()); newCourseParticipationStatusEntry.setTrainingRecordSectionId(course.getTrainingRecordSectionPreset() == null ? null : course.getTrainingRecordSectionPreset().getId()); newCourseParticipationStatusEntry.setShowTrainingRecord(course.isShowTrainingRecordPreset()); newCourseParticipationStatusEntry.setStaffId(participantStaffIt.next().getId()); newCourseParticipationStatusEntry.setStatusId(getRandomElement(initialStates).getId()); CourseParticipationStatusEntryOutVO participation = courseService.addCourseParticipationStatusEntry(auth, newCourseParticipationStatusEntry); jobOutput.println("participant " + participation.getStatus().getName() + ": " + participation.getStaff().getName()); } return course; } public void createCourses(int courseCountPerDepartment) throws Exception { int newestCourseCount = (int) (0.5 * courseCountPerDepartment); for (int departmentNum = 0; departmentNum < departmentCount; departmentNum++) { Collection<Staff> institutions = staffDao.search(new Search(new SearchParameter[] { new SearchParameter("department.id", getDepartmentId(departmentNum), SearchParameter.EQUAL_COMPARATOR), new SearchParameter("person", false, SearchParameter.EQUAL_COMPARATOR) })); Collection<Staff> persons = staffDao.search(new Search(new SearchParameter[] { new SearchParameter("department.id", getDepartmentId(departmentNum), SearchParameter.EQUAL_COMPARATOR), new SearchParameter("person", true, SearchParameter.EQUAL_COMPARATOR) })); ArrayList<Long> createdIds = new ArrayList<Long>(); for (int i = 0; i < newestCourseCount; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); CourseOutVO course = createCourse(auth, i, departmentNum, null, institutions, persons.size()); createdIds.add(course.getId()); createFiles(auth, FileModule.COURSE_DOCUMENT, course.getId(), FILE_COUNT_PER_COURSE); } for (int i = 0; i < (courseCountPerDepartment - newestCourseCount); i++) { AuthenticationVO auth = getRandomAuth(departmentNum); CourseOutVO course = createCourse(auth, newestCourseCount + i, departmentNum, getUniqueRandomElements(createdIds, random.nextInt(5)), institutions, persons.size()); createdIds.add(course.getId()); createFiles(auth, FileModule.COURSE_DOCUMENT, course.getId(), FILE_COUNT_PER_COURSE); } } } private CriteriaOutVO createCriteria(AuthenticationVO auth, DBModule module, List<SearchCriterion> criterions, String label, String comment, boolean loadByDefault) throws Exception { auth = (auth == null ? getRandomAuth() : auth); CriteriaInVO newCriteria = new CriteriaInVO(); newCriteria.setCategory("test_" + prefix); newCriteria.setComment(comment); newCriteria.setLabel(label); newCriteria.setLoadByDefault(loadByDefault); newCriteria.setModule(module); HashSet<CriterionInVO> newCriterions = new HashSet<CriterionInVO>(criterions.size()); Iterator<SearchCriterion> it = criterions.iterator(); int position = 1; while (it.hasNext()) { SearchCriterion criterion = it.next(); newCriterions.add(criterion.buildCriterionInVO(this, module, position)); position++; } CriteriaOutVO out = searchService.addCriteria(auth, newCriteria, newCriterions); jobOutput.println("criteria created: " + out.getLabel()); return out; } public ArrayList<CriteriaOutVO> createCriterias() throws Throwable { AuthenticationVO auth = getRandomAuth(); ArrayList<CriteriaOutVO> criterias = new ArrayList<CriteriaOutVO>(); for (int i = 0; i < SearchCriteria.values().length; i++) { criterias.add(getCriteria(auth, SearchCriteria.values()[i])); } return criterias; } private InputFieldOutVO createDateField(AuthenticationVO auth, String name, String category, String title, String comment, Date datePreset, Date minDate, Date maxDate, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.DATE); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setMinDate(minDate); newInputField.setMaxDate(maxDate); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setDatePreset(datePreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("date input field created: " + out.getName()); return out; } private Long createDemoEcrfIncrement() { return null; } private ArrayList<ECRFFieldOutVO> createDemoEcrfMedicalHistory(AuthenticationVO auth, TrialOutVO trial, Long probandGroupId, int position, Long visitId) throws Throwable { ECRFOutVO ecrf = createEcrf(auth, trial, "medical history", "eCRF to capture ICD-10 coded medical history", probandGroupId, position, visitId, true, false, true, 0.0f, null); ArrayList<ECRFFieldOutVO> ecrfFields = new ArrayList<ECRFFieldOutVO>(); ecrfFields.add(createEcrfField(auth, InputFields.DIAGNOSIS_COUNT, ecrf, "summary", 1, false, false, false, true, true, null, null, "count", "function(alphaid) {\n" + " return alphaid.length - 1;\n" + "}", "function() {\n" + " return sprintf('medical history: %d entries',$value);\n" + "}")); ecrfFields.add(createEcrfField(auth, InputFields.DIAGNOSIS_START, ecrf, "medical history", 1, true, true, false, true, true, null, "date when disease started, if known/applicable", null, null, null)); ecrfFields.add( createEcrfField(auth, InputFields.DIAGNOSIS_END, ecrf, "medical history", 2, true, true, false, true, true, null, "date when disease ended, if known/applicable", null, null, null)); ecrfFields.add(createEcrfField(auth, InputFields.ALPHA_ID, ecrf, "medical history", 3, true, false, false, true, true, null, "disease name", "alphaid", null, "function() {\n" + " if ($enteredValue != $oldValue) {\n" + " var output = 'Matching AlphaID synonyms: ';\n" + " var request = RestApi.createRequest('GET', 'tools/complete/alphaidtext');\n" + " request.data = 'textInfix=' + $enteredValue;\n" + " request.success = function(data, code, jqXHR) {\n" + " if (data.length > 0) {\n" + " output += '<select onchange=\"FieldCalculation.setVariable([\\'alphaid\\',' + $index + '],';\n" + " output += 'this.options[this.selectedIndex].text,true);\">';\n" + " for (var i = 0; i < data.length; i++) {\n" + " output += '<option>' + data[i] + '</option>';\n" + " }\n" + " output += '</select>';\n" + " } else {\n" + " output += 'no hits';\n" + " }\n" + " setOutput(['alphaid',$index],output);\n" + " };\n" + " RestApi.executeRequest(request);\n" + " return output;\n" + " } else {\n" + " return $output;\n" + " }\n" + "}")); return ecrfFields; } private ArrayList<ECRFFieldOutVO> createDemoEcrfSum(AuthenticationVO auth, TrialOutVO trial, Long probandGroupId, int position, Long visitId) throws Throwable { ECRFOutVO ecrf = createEcrf(auth, trial, "some eCRF", "demo eCRF to show field calculations with series sections", probandGroupId, position, visitId, true, false, true, 0.0f, null); ArrayList<ECRFFieldOutVO> ecrfFields = new ArrayList<ECRFFieldOutVO>(); ecrfFields.add(createEcrfField(auth, InputFields.STRING_SINGLELINE, ecrf, "series #1", 1, true, false, false, true, true, null, "some name", null, null, null)); ecrfFields.add(createEcrfField(auth, InputFields.INTEGER, ecrf, "series #1", 2, true, false, false, true, true, null, "some repeatable value 1", "value1", null, null)); ecrfFields.add(createEcrfField(auth, InputFields.INTEGER, ecrf, "series #1", 3, true, false, false, true, true, null, "some repeatable value 2", "value2", null, null)); ecrfFields.add(createEcrfField(auth, InputFields.STRING_MULTILINE, ecrf, "series #1", 4, true, false, false, true, true, null, "some description", null, null, null)); ecrfFields.add(createEcrfField(auth, InputFields.FLOAT, ecrf, "series #1", 5, true, false, false, true, true, null, "some repeatable value 3", "value3", "function(value1, value2) {\n" + " return value1 + value2;\n" + "}", "function(value3) {\n" + " return sprintf(\"value3 = value1 + value2 = %.3f\",value3);\n" + "}")); ecrfFields.add(createEcrfField(auth, InputFields.STRING_SINGLELINE, ecrf, "series #2", 1, true, false, false, true, true, null, "some name", null, null, null)); ecrfFields.add(createEcrfField(auth, InputFields.INTEGER, ecrf, "series #2", 2, true, false, false, true, true, null, "some repeatable value 4", "value4", null, null)); ecrfFields.add(createEcrfField(auth, InputFields.INTEGER, ecrf, "series #2", 3, true, false, false, true, true, null, "some repeatable value 5", "value5", null, null)); ecrfFields.add(createEcrfField(auth, InputFields.STRING_MULTILINE, ecrf, "series #2", 4, true, false, false, true, true, null, "some description", null, null, null)); ecrfFields.add(createEcrfField(auth, InputFields.FLOAT, ecrf, "series #2", 5, true, false, false, true, true, null, "some repeatable value 6", "value6", "function(value4, value5) {\n" + " return value4 + value5;\n" + "}", "function(value6) {\n" + " return sprintf(\"value6 = value4 + value5 = %.3f\",value6);\n" + "}")); ecrfFields.add(createEcrfField(auth, InputFields.STRING_SINGLELINE, ecrf, "totals section", 1, false, false, false, true, true, null, "some name", null, null, null)); ecrfFields.add(createEcrfField(auth, InputFields.INTEGER, ecrf, "totals section", 2, false, false, false, true, true, null, "some total value 1", "total1", "function(value1, value4) {\n" + " var sum = 0;\n" + " var i;\n" + " for (i = 0; i < value1.length; i++) {\n" + " sum += value1[i];\n" + " }\n" + " for (i = 0; i < value4.length; i++) {\n" + " sum += value4[i];\n" + " }\n" + " return sum;\n" + "}", "function(total1) {\n" + " return sprintf(\"total1 = sum(value1) + sum(value4) = %.3f\",total1);\n" + "}")); ecrfFields.add(createEcrfField(auth, InputFields.INTEGER, ecrf, "totals section", 3, false, false, false, true, true, null, "some total value 2", "total2", "function(value2, value5) {\n" + " var sum = 0;\n" + " var i;\n" + " for (i = 0; i < value2.length; i++) {\n" + " sum += value2[i];\n" + " }\n" + " for (i = 0; i < value5.length; i++) {\n" + " sum += value5[i];\n" + " }\n" + " return sum;\n" + "}", "function(total2) {\n" + " return sprintf(\"total2 = sum(value2) + sum(value5) = %.3f\",total2);\n" + "}")); ecrfFields.add(createEcrfField(auth, InputFields.STRING_MULTILINE, ecrf, "totals section", 4, false, false, false, true, true, null, "some description", null, null, null)); ecrfFields.add(createEcrfField(auth, InputFields.FLOAT, ecrf, "totals section", 5, false, false, false, true, true, null, "some total value 3", "total3", "function(total1, total2) {\n" + " return total1 + total2;\n" + "}", "function(total3,value3,value6) {\n" + " var sum = 0;\n" + " var i;\n" + " for (i = 0; i < value3.length; i++) {\n" + " sum += value3[i];\n" + " }\n" + " for (i = 0; i < value6.length; i++) {\n" + " sum += value6[i];\n" + " }\n" + " return sprintf(\"total3 = total1 + total2 = %.3f = sum(value3) + sum(value6) = %.3f\",total3,sum);\n" + "}")); return ecrfFields; } private DepartmentVO createDepartment(String nameL10nKey, boolean visible, String plainDepartmentPassword) throws Exception { Department department = Department.Factory.newInstance(); department.setNameL10nKey(nameL10nKey); department.setVisible(visible); CryptoUtil.encryptDepartmentKey(department, CryptoUtil.createRandomKey().getEncoded(), plainDepartmentPassword); DepartmentVO out = departmentDao.toDepartmentVO(departmentDao.create(department)); jobOutput.println("department created: " + out.getName()); return out; } public void createDepartmentsAndUsers(int departmentCount, int usersPerDepartmentCount) throws Exception { this.usersPerDepartmentCount = usersPerDepartmentCount; for (int i = 0; i < departmentCount; i++) { DepartmentVO department = createDepartment(getDepartmentName(i), true, getDepartmentPassword(i)); this.departmentCount++; for (int j = 0; j < usersPerDepartmentCount; j++) { createUser(getUsername(i, j), getUserPassword(i, j), department.getId(), getDepartmentPassword(i)); } } } private Collection<DutyRosterTurnOutVO> createDuty(AuthenticationVO auth, ArrayList<Staff> staff, TrialOutVO trial, Date start, Date stop, String title) throws Exception { auth = (auth == null ? getRandomAuth() : auth); Collection<VisitScheduleItemOutVO> visitScheduleItems = trialService.getVisitScheduleItems(auth, trial.getId(), null, start, stop, null, false); DutyRosterTurnInVO newDutyRosterTurn = new DutyRosterTurnInVO(); newDutyRosterTurn.setSelfAllocatable(staff.size() > 0); newDutyRosterTurn.setStart(start); newDutyRosterTurn.setStop(stop); newDutyRosterTurn.setTrialId(trial.getId()); ArrayList<DutyRosterTurnOutVO> out = new ArrayList<DutyRosterTurnOutVO>(); if (title == null && visitScheduleItems.size() > 0) { Iterator<Staff> staffIt = getUniqueRandomElements(staff, visitScheduleItems.size()).iterator(); Iterator<VisitScheduleItemOutVO> visitScheduleItemsIt = visitScheduleItems.iterator(); int dutyCount = 0; while (staffIt.hasNext() && visitScheduleItemsIt.hasNext()) { VisitScheduleItemOutVO visitScheduleItem = visitScheduleItemsIt.next(); newDutyRosterTurn.setStaffId(staffIt.next().getId()); newDutyRosterTurn.setTitle(null); newDutyRosterTurn.setComment(null); newDutyRosterTurn.setVisitScheduleItemId(visitScheduleItem.getId()); try { out.add(staffService.addDutyRosterTurn(auth, newDutyRosterTurn)); dutyCount++; } catch (ServiceException e) { jobOutput.println(e.getMessage()); } } jobOutput.println(dutyCount + " duty roster turns for " + visitScheduleItems.size() + " visit schedule items created"); return out; } else { newDutyRosterTurn.setStaffId(staff.size() == 0 ? null : getRandomElement(staff).getId()); newDutyRosterTurn.setTitle(title); newDutyRosterTurn.setComment(null); newDutyRosterTurn.setVisitScheduleItemId(visitScheduleItems.size() > 0 ? visitScheduleItems.iterator().next().getId() : null); try { out.add(staffService.addDutyRosterTurn(auth, newDutyRosterTurn)); jobOutput.println("duty roster turn created: " + title); } catch (ServiceException e) { jobOutput.println(e.getMessage()); } } return out; } private ECRFOutVO createEcrf(AuthenticationVO auth, TrialOutVO trial, String name, String title, Long probandGroupId, int position, Long visitId, boolean active, boolean disabled, boolean enableBrowserFieldCalculation, float charge, String description) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); ECRFInVO newEcrf = new ECRFInVO(); newEcrf.setName(name); newEcrf.setTitle(title); newEcrf.setPosition(new Long(position)); newEcrf.setTrialId(trial.getId()); newEcrf.setActive(active); newEcrf.setDescription(description); newEcrf.setDisabled(disabled); newEcrf.setEnableBrowserFieldCalculation(enableBrowserFieldCalculation); newEcrf.setCharge(charge); newEcrf.setGroupId(probandGroupId); newEcrf.setVisitId(visitId); ECRFOutVO out = trialService.addEcrf(auth, newEcrf); jobOutput.println("eCRF created: " + out.getUniqueName()); return out; } private ECRFFieldOutVO createEcrfField(AuthenticationVO auth, InputFields inputField, ECRFOutVO ecrf, String section, int position, boolean series, boolean optional, boolean disabled, boolean auditTrail, boolean reasonForChangeRequired, String title, String comment, String jsVariableName, String jsValueExpression, String jsOutputExpression) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); ECRFFieldInVO newEcrfField = new ECRFFieldInVO(); newEcrfField.setAuditTrail(auditTrail); newEcrfField.setComment(comment); newEcrfField.setTitle(title); newEcrfField.setDisabled(disabled); newEcrfField.setEcrfId(ecrf.getId()); newEcrfField.setFieldId(getInputField(auth, inputField).getId()); newEcrfField.setOptional(optional); newEcrfField.setPosition(new Long(position)); newEcrfField.setReasonForChangeRequired(reasonForChangeRequired); newEcrfField.setNotify(false); newEcrfField.setSection(section); newEcrfField.setSeries(series); newEcrfField.setTrialId(ecrf.getTrial().getId()); newEcrfField.setJsVariableName(jsVariableName); newEcrfField.setJsValueExpression(jsValueExpression); newEcrfField.setJsOutputExpression(jsOutputExpression); ECRFFieldOutVO out = trialService.addEcrfField(auth, newEcrfField); jobOutput.println("eCRF field created: " + out.getUniqueName()); return out; } private FileOutVO createFile(AuthenticationVO auth, FileModule module, Long id, ArrayList<String> folders) throws Exception { auth = (auth == null ? getRandomAuth() : auth); FileInVO newFile = new FileInVO(); newFile.setActive(getRandomBoolean(50)); newFile.setPublicFile(true); switch (module) { case INVENTORY_DOCUMENT: newFile.setInventoryId(id); break; case STAFF_DOCUMENT: newFile.setStaffId(id); break; case COURSE_DOCUMENT: newFile.setCourseId(id); break; case TRIAL_DOCUMENT: newFile.setTrialId(id); break; case PROBAND_DOCUMENT: newFile.setProbandId(id); break; case MASS_MAIL_DOCUMENT: newFile.setMassMailId(id); break; default: } newFile.setModule(module); if (folders.size() == 0) { folders.add(CommonUtil.LOGICAL_PATH_SEPARATOR); folders.addAll(fileService.getFileFolders(auth, module, id, CommonUtil.LOGICAL_PATH_SEPARATOR, false, null, null, null)); } StringBuilder logicalPath = new StringBuilder(getRandomElement(folders)); if (getRandomBoolean(50)) { logicalPath.append(CommonUtil.generateUUID()); logicalPath.append(CommonUtil.LOGICAL_PATH_SEPARATOR); folders.add(logicalPath.toString()); } newFile.setLogicalPath(logicalPath.toString()); PDFImprinter blankPDF = new PDFImprinter(); PDFStream pdfStream = new PDFStream(); blankPDF.setOutput(pdfStream); blankPDF.render(); FileStreamInVO newFileStream = new FileStreamInVO(); StringBuilder fileName = new StringBuilder(CommonUtil.generateUUID()); fileName.append("."); fileName.append(CoreUtil.PDF_FILENAME_EXTENSION); newFileStream.setFileName(fileName.toString()); newFileStream.setMimeType(CoreUtil.PDF_MIMETYPE_STRING); newFileStream.setSize((long) pdfStream.getSize()); newFileStream.setStream(pdfStream.getInputStream()); newFile.setComment("test file"); newFile.setTitle(fileName.toString()); return fileService.addFile(auth, newFile, newFileStream); } private void createFiles(AuthenticationVO auth, FileModule module, Long id, int fileCount) throws Exception { if (CREATE_FILES) { auth = (auth == null ? getRandomAuth() : auth); ArrayList<String> folders = new ArrayList<String>(); for (int i = 0; i < fileCount; i++) { createFile(auth, module, id, folders); } jobOutput.println(fileCount + " files created for " + module + " enitity " + id); } } private InputFieldOutVO createFloatField(AuthenticationVO auth, String name, String category, String title, String comment, Float floatPreset, Float lowerLimit, Float upperLimit, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.FLOAT); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setFloatLowerLimit(lowerLimit); newInputField.setFloatUpperLimit(upperLimit); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setFloatPreset(floatPreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("float input field created: " + out.getName()); return out; } public TrialOutVO createFormScriptingTrial() throws Throwable { int departmentNum = 0; AuthenticationVO auth = getRandomAuth(departmentNum); TrialInVO newTrial = new TrialInVO(); newTrial.setStatusId(trialStatusTypeDao.searchUniqueNameL10nKey("migration_started").getId()); newTrial.setDepartmentId(getDepartmentId(departmentNum)); newTrial.setName("demo:form-scripting"); newTrial.setTitle("Inquiry form showing various form field calculation examples."); newTrial.setDescription(""); newTrial.setSignupProbandList(false); newTrial.setSignupInquiries(false); newTrial.setSignupRandomize(false); newTrial.setSignupDescription(""); newTrial.setExclusiveProbands(false); newTrial.setProbandAliasFormat(""); newTrial.setDutySelfAllocationLocked(false); newTrial.setTypeId(trialTypeDao.searchUniqueNameL10nKey("na").getId()); newTrial.setSponsoringId(sponsoringTypeDao.searchUniqueNameL10nKey("na").getId()); newTrial.setSurveyStatusId(getRandomElement(selectionSetService.getSurveyStatusTypes(auth, null)).getId()); TrialOutVO trial = trialService.addTrial(auth, newTrial, null); jobOutput.println("trial created: " + trial.getName()); ArrayList<InquiryOutVO> inquiries = new ArrayList<InquiryOutVO>(); inquiries.add(createInquiry(auth, InputFields.BODY_HEIGHT, trial, "01 - BMI", 1, true, true, false, false, false, false, null, null, "size", null, null)); inquiries.add(createInquiry(auth, InputFields.BODY_WEIGHT, trial, "01 - BMI", 2, true, true, false, false, false, false, null, null, "weight", null, null)); inquiries.add(createInquiry(auth, InputFields.BODY_MASS_INDEX, trial, "01 - BMI", 3, true, true, false, false, false, false, null, null, "bmi", "function(weight,size) {\n" + " return weight / (size * size / 10000.0);\n" + "}", "function(bmi) {\n" + " return sprintf(\"BMI entered: %.6f<br>\" +\n" + " \"BMI calculated: %.6f\",\n" + " $enteredValue + 0.0,\n" + " bmi);\n" + "}")); inquiries.add(createInquiry(auth, InputFields.OBESITY, trial, "01 - BMI", 4, true, true, false, false, false, false, null, null, "obesity", "function(bmi) {\n" + " var selection;\n" + " if (bmi < 18.5) {\n" + " selection = \"shortweight\";\n" + " } else if (bmi < 25) {\n" + " selection = \"normal weight\";\n" + " } else if (bmi < 30) {\n" + " selection = \"overweight\"; \n" + " } else if (bmi < 35) {\n" + " selection = \"adiposity degree I\";\n" + " } else if (bmi < 40) { \n" + " selection = \"adiposity degree II\";\n" + " } else {\n" + " selection = \"adiposity degree III\";\n" + " }\n" + " return findSelectionSetValueIds(function(option){\n" + " return option.name == selection;});\n" + "}", "function(obesity) {\n" + " return \"entered: \" +\n" + " printSelectionSetValues($enteredValue) + \"<br>\" +\n" + " \"calculated: <em>\" +\n" + " printSelectionSetValues(obesity) + \"</em>\";\n" + "}")); inquiries.add(createInquiry(auth, InputFields.ETHNICITY, trial, "02 - eGFR", 1, true, true, false, false, false, false, null, null, "ethnicity", "", "function() {\n" + " return sprintf(\"<a href=\\\"http://www.fda.gov/RegulatoryInformation/Guidances/ucm126340.htm\\\" target=\\\"new\\\">FDA Information</a>\");\n" + "}")); inquiries.add(createInquiry(auth, InputFields.SERUM_CREATININ_CONCENTRATION, trial, "02 - eGFR", 2, true, true, false, false, false, false, null, null, "s_cr", "", "")); inquiries.add(createInquiry(auth, InputFields.EGFR, trial, "02 - eGFR", 3, true, true, false, false, false, false, null, null, "egfr", "function(s_cr, ethnicity) { // s_cr: serum creatinin concentration (decimal), skin_color (single selection)\n" + " var result = 175.0 * Math.pow(s_cr, -1.154) * Math.pow($proband.age, -0.203);\n" + " if (getInputFieldSelectionSetValue(\'ethnicity\', ethnicity[0]).value == \'Black\') {\n" + " result *= 1.210;\n" + " }\n" + " if ($proband.gender.sex == \'FEMALE\') {\n" + " result *= 0.742;\n" + " }\n" + " return result;\n" + "}", "function(egfr) {\n" + " return sprintf(\"eGFR entered: %.6f<br>\" + \n" + " \"eGFR calculated: %.6f\",\n" + " $enteredValue + 0.0,\n" + " egfr);\n" + "}")); inquiries.add(createInquiry(auth, InputFields.HBA1C_PERCENT, trial, "03 - HbA1C", 1, true, true, false, false, false, false, null, null, "hba1c_percent", "//function(hba1c_mmol_per_mol) {\n" + "// return hba1c_mmol_per_mol * 0.0915 + 2.15;\n" + "//}", "function() {\n" + " return sprintf(\"HbA1c (%%): %.1f<br/>\" +\n" + " \"HbA1c (mmol/mol): %.2f\",\n" + " $enteredValue + 0.0,\n" + " ($enteredValue - 2.15) * 10.929);\n" + "}")); inquiries.add(createInquiry(auth, InputFields.HBA1C_MMOLPERMOL, trial, "03 - HbA1C", 2, true, true, false, false, false, false, null, null, "hba1c_mmol_per_mol", "function(hba1c_percent) {\n" + " return (hba1c_percent - 2.15) * 10.929;\n" + "}", "//function() {\n" + "// return sprintf(\"HbA1c (mmol/mol): %.2f<br/>\" +\n" + "// \"HbA1c (%%): %.1f\",\n" + "// $enteredValue + 0.0,\n" + "// $enteredValue * 0.0915 + 2.15);\n" + "//}\n" + "function(hba1c_mmol_per_mol) {\n" + " return sprintf(\"HbA1c entered (mmol/mol): %.6f<br/>\" +\n" + " \"HbA1c calculated (mmol/mol): %.6f\",\n" + " $enteredValue + 0.0,\n" + " hba1c_mmol_per_mol);\n" + "}")); inquiries.add(createInquiry(auth, InputFields.MANNEQUIN, trial, "04 - DAS28", 1, true, true, false, false, false, false, null, "tender joints", "tender", null, null)); inquiries.add(createInquiry(auth, InputFields.MANNEQUIN, trial, "04 - DAS28", 2, true, true, false, false, false, false, null, "swollen joints", "swollen", null, null)); inquiries.add(createInquiry(auth, InputFields.ESR, trial, "04 - DAS28", 3, true, true, false, false, false, false, null, null, "esr", null, null)); inquiries.add(createInquiry(auth, InputFields.VAS, trial, "04 - DAS28", 4, true, true, false, false, false, false, null, "The patient's general health condition (subjective)", "vas", null, null)); inquiries.add(createInquiry(auth, InputFields.DAS28, trial, "04 - DAS28", 5, true, true, false, false, false, false, null, null, "das28", "function (tender, swollen, esr, vas) { //das (28 joints) computation:\n" + " return 0.56 * Math.sqrt(tender.ids.length) + //tender joint count (0-28)\n" + " 0.28 * Math.sqrt(swollen.ids.length) + //swollen joint count (0-28)\n" + " 0.7 * Math.log(esr) + //erythrocyte sedimentation rate reading (5-30 mm/h)\n" + " 0.014 * getInputFieldSelectionSetValue(\"vas\",vas.ids[0]).value; //the proband\'s\n" + " //subjective assessment of recent disease activity (visual analog scale, 0-100 mm)\n" + "}", "function(das28) {\n" + " return sprintf(\"entered: %.2f<br/>\" +\n" + " \"calculated: %.2f\", $enteredValue + 0.0,das28 + 0.0);\n" + "}")); inquiries.add(createInquiry(auth, InputFields.DISTANCE, trial, "05 - Google Maps", 1, true, true, false, false, false, false, null, null, "distance", "function() {\n" + " if ($enteredValue) {\n" + " return $enteredValue; \n" + " }\n" + " if ($probandAddresses) {\n" + " for (var i in $probandAddresses) {\n" + " if ($probandAddresses[i].wireTransfer) {\n" + " LocationDistance.calcRouteDistance(null,$probandAddresses[i].civicName,function(d,j){\n" + " setVariable(\"distance\",Math.round(d/1000.0));\n" + " },i);\n" + " return;\n" + " }\n" + " }\n" + " }\n" + " return;\n" + "}", "function(distance){\n" + " if ($enteredValue) {\n" + " return \"\"; \n" + " }\n" + " if ($probandAddresses) {\n" + " for (var i in $probandAddresses) {\n" + " if ($probandAddresses[i].wireTransfer) {\n" + " if (distance != null) {\n" + " return sprintf(\"Distance from %s to %s: %d km\",LocationDistance.currentSubLocality,$probandAddresses[i].name,distance);\n" + " } else {\n" + " return \"querying Google Maps ...\"; \n" + " }\n" + " }\n" + " }\n" + " }\n" + " return \"No subject address.\"; \n" + "}")); inquiries.add(createInquiry(auth, InputFields.ALPHA_ID, trial, "06 - Rest API", 1, true, true, false, false, false, false, null, "(Medical Coding example ...)", "alphaid", null, "function() {\n" + " if ($enteredValue != $oldValue) {\n" + " var output = 'Matching AlphaID synonyms: ';\n" + " var request = RestApi.createRequest('GET', 'tools/complete/alphaidtext');\n" + " request.data = 'textInfix=' + $enteredValue;\n" + " request.success = function(data, code, jqXHR) {\n" + " if (data.length > 0) {\n" + " output += '<select onchange=\"FieldCalculation.setVariable(\\'alphaid\\',';\n" + " output += 'this.options[this.selectedIndex].text,true);\">';\n" + " for (var i = 0; i < data.length; i++) {\n" + " output += '<option>' + data[i] + '</option>';\n" + " }\n" + " output += '</select>';\n" + " } else {\n" + " output += 'no hits';\n" + " }\n" + " setOutput('alphaid',output);\n" + " };\n" + " RestApi.executeRequest(request);\n" + " return output;\n" + " } else {\n" + " return $output;\n" + " }\n" + "}")); createDemoEcrfSum(auth, trial, null, 1, null); createDemoEcrfMedicalHistory(auth, trial, null, 2, null); return trial; } public TrialOutVO createGroupCoinRandomizationTrial(int probandGroupCount, int probandCount) throws Throwable { int departmentNum = 0; AuthenticationVO auth = getRandomAuth(departmentNum); TrialInVO newTrial = new TrialInVO(); newTrial.setStatusId(trialStatusTypeDao.searchUniqueNameL10nKey("migration_started").getId()); newTrial.setDepartmentId(getDepartmentId(departmentNum)); newTrial.setName("demo:group coin randomization"); newTrial.setTitle("Group coin randomization testcase."); newTrial.setDescription(""); newTrial.setRandomization(RandomizationMode.GROUP_COIN); newTrial.setSignupProbandList(false); newTrial.setSignupInquiries(false); newTrial.setSignupRandomize(false); newTrial.setSignupDescription(""); newTrial.setExclusiveProbands(false); newTrial.setProbandAliasFormat(""); newTrial.setDutySelfAllocationLocked(false); newTrial.setTypeId(trialTypeDao.searchUniqueNameL10nKey("na").getId()); newTrial.setSponsoringId(sponsoringTypeDao.searchUniqueNameL10nKey("na").getId()); newTrial.setSurveyStatusId(getRandomElement(selectionSetService.getSurveyStatusTypes(auth, null)).getId()); TrialOutVO trial = trialService.addTrial(auth, newTrial, null); jobOutput.println("trial created: " + trial.getName()); ProbandGroupInVO newProbandGroup = new ProbandGroupInVO(); newProbandGroup.setTitle("Screeninggruppe"); newProbandGroup.setToken("SG"); newProbandGroup.setTrialId(trial.getId()); newProbandGroup.setRandomize(false); ProbandGroupOutVO screeningGroup = trialService.addProbandGroup(auth, newProbandGroup); jobOutput.println("proband group created: " + screeningGroup.getTitle()); LinkedHashMap<Long, ProbandGroupOutVO> probandGroupMap = new LinkedHashMap<Long, ProbandGroupOutVO>(); for (int i = 0; i < probandGroupCount; i++) { newProbandGroup = new ProbandGroupInVO(); newProbandGroup.setTitle("Gruppe " + (i + 1)); newProbandGroup.setToken("G" + (i + 1)); newProbandGroup.setTrialId(trial.getId()); newProbandGroup.setRandomize(true); ProbandGroupOutVO probandGroup = trialService.addProbandGroup(auth, newProbandGroup); jobOutput.println("proband group created: " + probandGroup.getTitle()); probandGroupMap.put(probandGroup.getId(), probandGroup); } ProbandCategory probandCategory = probandCategoryDao.search(new Search(new SearchParameter[] { new SearchParameter("nameL10nKey", "test", SearchParameter.EQUAL_COMPARATOR) })).iterator().next(); HashMap<Long, Long> groupSizes = new HashMap<Long, Long>(); for (int i = 0; i < probandCount; i++) { ProbandInVO newProband = new ProbandInVO(); newProband.setDepartmentId(getDepartmentId(departmentNum)); newProband.setCategoryId(probandCategory.getId()); newProband.setPerson(true); newProband.setBlinded(true); newProband.setAlias(MessageFormat.format("{0} {1}", trial.getName(), i + 1)); newProband.setGender(getRandomBoolean(50) ? Sex.MALE : Sex.FEMALE); newProband.setDateOfBirth(getRandomDateOfBirth()); ProbandOutVO proband = probandService.addProband(auth, newProband, null, null, null); jobOutput.println("proband created: " + proband.getName()); ProbandListEntryInVO newProbandListEntry = new ProbandListEntryInVO(); newProbandListEntry.setPosition(i + 1l); newProbandListEntry.setTrialId(trial.getId()); newProbandListEntry.setProbandId(proband.getId()); ProbandListEntryOutVO probandListEntry = trialService.addProbandListEntry(auth, false, false, true, newProbandListEntry); jobOutput.println("proband list entry created - trial: " + probandListEntry.getTrial().getName() + " position: " + probandListEntry.getPosition() + " proband: " + probandListEntry.getProband().getName()); if (groupSizes.containsKey(probandListEntry.getGroup().getId())) { groupSizes.put(probandListEntry.getGroup().getId(), groupSizes.get(probandListEntry.getGroup().getId()) + 1l); } else { groupSizes.put(probandListEntry.getGroup().getId(), 1l); } } Iterator<Long> probandGroupIdsIt = probandGroupMap.keySet().iterator(); while (probandGroupIdsIt.hasNext()) { Long probandGroupId = probandGroupIdsIt.next(); jobOutput.println(probandGroupMap.get(probandGroupId).getToken() + ": " + groupSizes.get(probandGroupId) + " probands"); } return trial; } public ArrayList<InputFieldOutVO> createInputFields() throws Throwable { AuthenticationVO auth = getRandomAuth(); ArrayList<InputFieldOutVO> inputFields = new ArrayList<InputFieldOutVO>(); for (int i = 0; i < InputFields.values().length; i++) { inputFields.add(getInputField(auth, InputFields.values()[i])); } return inputFields; } private InquiryOutVO createInquiry(AuthenticationVO auth, InputFields inputField, TrialOutVO trial, String category, int position, boolean active, boolean activeSignup, boolean optional, boolean disabled, boolean excelValue, boolean excelDate, String title, String comment, String jsVariableName, String jsValueExpression, String jsOutputExpression) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); InquiryInVO newInquiry = new InquiryInVO(); newInquiry.setCategory(category); newInquiry.setActive(active); newInquiry.setActiveSignup(activeSignup); newInquiry.setOptional(optional); newInquiry.setDisabled(disabled); newInquiry.setExcelValue(excelValue); newInquiry.setExcelDate(excelDate); newInquiry.setFieldId(getInputField(auth, inputField).getId()); newInquiry.setTrialId(trial.getId()); newInquiry.setPosition(new Long(position)); newInquiry.setComment(comment); newInquiry.setTitle(title); newInquiry.setJsVariableName(jsVariableName); newInquiry.setJsValueExpression(jsValueExpression); newInquiry.setJsOutputExpression(jsOutputExpression); InquiryOutVO out = trialService.addInquiry(auth, newInquiry); jobOutput.println("inquiry created: " + out.getUniqueName()); return out; } private InputFieldOutVO createIntegerField(AuthenticationVO auth, String name, String category, String title, String comment, Long longPreset, Long lowerLimit, Long upperLimit, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.INTEGER); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setLongLowerLimit(lowerLimit); newInputField.setLongUpperLimit(upperLimit); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setLongPreset(longPreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("integer input field created: " + out.getName()); return out; } private InventoryOutVO createInventory(AuthenticationVO auth, int inventoryNum, int departmentNum, Long parentId, Collection<Staff> owners) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InventoryInVO newInventory = new InventoryInVO(); newInventory.setBookable(getRandomBoolean(50)); if (newInventory.getBookable()) { newInventory.setMaxOverlappingBookings(1l); } else { newInventory.setMaxOverlappingBookings(0l); } newInventory.setOwnerId(getRandomBoolean(50) ? getRandomElement(owners).getId() : null); newInventory.setParentId(parentId); newInventory.setDepartmentId(getDepartmentId(departmentNum)); newInventory.setCategoryId(getRandomElement(selectionSetService.getInventoryCategories(auth, null)).getId()); newInventory.setName("inventory_" + (departmentNum + 1) + "_" + (inventoryNum + 1)); newInventory.setPieces(random.nextInt(5) + 1L); InventoryOutVO out = inventoryService.addInventory(auth, newInventory, null, null, null); jobOutput.println("inventory created: " + out.getName()); return out; } public void createInventory(int inventoryCountPerDepartment) throws Exception { int inventoryRootCount = (int) (0.1 * inventoryCountPerDepartment); for (int departmentNum = 0; departmentNum < departmentCount; departmentNum++) { Collection<Staff> owners = staffDao.search(new Search(new SearchParameter[] { new SearchParameter("department.id", getDepartmentId(departmentNum), SearchParameter.EQUAL_COMPARATOR), new SearchParameter("person", false, SearchParameter.EQUAL_COMPARATOR) })); ArrayList<Long> createdIds = new ArrayList<Long>(); for (int i = 0; i < inventoryRootCount; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); InventoryOutVO inventory = createInventory(auth, i, departmentNum, null, owners); createdIds.add(inventory.getId()); createFiles(auth, FileModule.INVENTORY_DOCUMENT, inventory.getId(), FILE_COUNT_PER_INVENTORY); } for (int i = 0; i < (inventoryCountPerDepartment - inventoryRootCount); i++) { AuthenticationVO auth = getRandomAuth(departmentNum); InventoryOutVO inventory = createInventory(auth, inventoryRootCount + i, departmentNum, getRandomElement(createdIds), owners); createdIds.add(inventory.getId()); createFiles(auth, FileModule.INVENTORY_DOCUMENT, inventory.getId(), FILE_COUNT_PER_INVENTORY); } } } private InputFieldOutVO createMultiLineTextField(AuthenticationVO auth, String name, String category, String title, String comment, String textPreset, String regExp, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.MULTI_LINE_TEXT); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setRegExp(regExp); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setTextPreset(textPreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("multi line text input field created: " + out.getName()); return out; } private ProbandOutVO createProband(AuthenticationVO auth, int departmentNum, Sex sex, Collection<Long> childIds, Collection<ProbandCategory> categories, Collection<String> titles) throws Exception { // todo: relatives graph auth = (auth == null ? getRandomAuth() : auth); ProbandInVO newProband = new ProbandInVO(); newProband.setDepartmentId(getDepartmentId(departmentNum)); newProband.setCategoryId(getRandomElement(categories).getId()); if (getRandomBoolean(25)) { newProband.setPrefixedTitle1(getRandomElement(titles)); if (getRandomBoolean(20)) { newProband.setPrefixedTitle2(getRandomElement(titles)); } } if (sex == null) { if (getRandomBoolean(50)) { sex = Sex.MALE; } else { sex = Sex.FEMALE; } } newProband.setGender(sex); newProband.setFirstName(Sex.MALE == sex ? getRandomElement(GermanPersonNames.MALE_FIRST_NAMES) : getRandomElement(GermanPersonNames.FEMALE_FIRST_NAMES)); newProband.setPerson(true); newProband.setBlinded(false); newProband.setLastName(getRandomElement(GermanPersonNames.LAST_NAMES)); newProband.setCitizenship(getRandomBoolean(5) ? "Deutschland" : "österreich"); Long oldestChildDoBTime = null; if (childIds != null && childIds.size() > 0) { newProband.setChildIds(childIds); Iterator<Long> it = childIds.iterator(); while (it.hasNext()) { Long childId = it.next(); ProbandOutVO child = probandService.getProband(auth, childId, 1, null, null); if (oldestChildDoBTime == null || oldestChildDoBTime > child.getDateOfBirth().getTime()) { oldestChildDoBTime = child.getDateOfBirth().getTime(); } } } Date dOb; if (oldestChildDoBTime != null) { dOb = new Date(); dOb.setTime(oldestChildDoBTime); dOb = DateCalc.subIntervals(dOb, VariablePeriod.YEAR, null, CommonUtil.safeLongToInt(getRandomLong(15l, 40l))); } else { dOb = getRandomDateOfBirth(); } newProband.setDateOfBirth(dOb); ProbandOutVO out = probandService.addProband(auth, newProband, null, null, null); jobOutput.println("proband created: " + out.getName()); return out; } private ProbandListEntryTagOutVO createProbandListEntryTag(AuthenticationVO auth, InputFields inputField, TrialOutVO trial, int position, boolean optional, boolean disabled, boolean excelValue, boolean excelDate, boolean ecrfValue, boolean stratification, boolean randomize, String title, String comment, String jsVariableName, String jsValueExpression, String jsOutputExpression) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); ProbandListEntryTagInVO newProbandListEntryTag = new ProbandListEntryTagInVO(); newProbandListEntryTag.setOptional(optional); newProbandListEntryTag.setDisabled(disabled); newProbandListEntryTag.setExcelValue(excelValue); newProbandListEntryTag.setEcrfValue(ecrfValue); newProbandListEntryTag.setStratification(stratification); newProbandListEntryTag.setRandomize(randomize); newProbandListEntryTag.setExcelDate(excelDate); newProbandListEntryTag.setFieldId(getInputField(auth, inputField).getId()); newProbandListEntryTag.setTrialId(trial.getId()); newProbandListEntryTag.setPosition(new Long(position)); newProbandListEntryTag.setComment(comment); newProbandListEntryTag.setTitle(title); newProbandListEntryTag.setJsVariableName(jsVariableName); newProbandListEntryTag.setJsValueExpression(jsValueExpression); newProbandListEntryTag.setJsOutputExpression(jsOutputExpression); ProbandListEntryTagOutVO out = trialService.addProbandListEntryTag(auth, newProbandListEntryTag); jobOutput.println("proband list entry tag created: " + out.getUniqueName()); return out; } public void createProbands(int probandCountPerDepartment) throws Exception { int grandChildrenCount = (int) (0.5 * probandCountPerDepartment); int childrenCount = (int) (0.5 * (probandCountPerDepartment - grandChildrenCount)); Collection<String> titles = toolsService.completeTitle(null, null, -1); ArrayList<ProbandCategory> categories = new ArrayList<ProbandCategory>(probandCategoryDao.search(new Search(new SearchParameter[] { new SearchParameter("locked", false, SearchParameter.EQUAL_COMPARATOR), new SearchParameter("signup", false, SearchParameter.EQUAL_COMPARATOR), new SearchParameter("person", true, SearchParameter.EQUAL_COMPARATOR) }))); for (int departmentNum = 0; departmentNum < departmentCount; departmentNum++) { ArrayList<Long> grandChildrentIds = new ArrayList<Long>(); ArrayList<Long> childrentIds = new ArrayList<Long>(); for (int i = 0; i < grandChildrenCount; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); ProbandOutVO proband = createProband(auth, departmentNum, null, null, categories, titles); grandChildrentIds.add(proband.getId()); createFiles(auth, FileModule.PROBAND_DOCUMENT, proband.getId(), FILE_COUNT_PER_PROBAND); } HashSet<Long> childWoMaleParentIds = new HashSet<Long>(grandChildrentIds); HashSet<Long> childWoFemaleParentIds = new HashSet<Long>(grandChildrentIds); for (int i = 0; i < childrenCount; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); boolean isMale = getRandomBoolean(50); ArrayList<Long> childIds; if (isMale) { childIds = getUniqueRandomElements(new ArrayList<Long>(childWoMaleParentIds), random.nextInt(5)); childWoMaleParentIds.removeAll(childIds); } else { childIds = getUniqueRandomElements(new ArrayList<Long>(childWoFemaleParentIds), random.nextInt(5)); childWoFemaleParentIds.removeAll(childIds); } ProbandOutVO proband = createProband(auth, departmentNum, isMale ? Sex.MALE : Sex.FEMALE, childIds, categories, titles); childrentIds.add(proband.getId()); createFiles(auth, FileModule.PROBAND_DOCUMENT, proband.getId(), FILE_COUNT_PER_PROBAND); } childWoMaleParentIds = new HashSet<Long>(childrentIds); childWoFemaleParentIds = new HashSet<Long>(childrentIds); for (int i = 0; i < probandCountPerDepartment - grandChildrenCount - childrenCount; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); boolean isMale = getRandomBoolean(50); ArrayList<Long> childIds; if (isMale) { childIds = getUniqueRandomElements(new ArrayList<Long>(childWoMaleParentIds), random.nextInt(5)); childWoMaleParentIds.removeAll(childIds); } else { childIds = getUniqueRandomElements(new ArrayList<Long>(childWoFemaleParentIds), random.nextInt(5)); childWoFemaleParentIds.removeAll(childIds); } ProbandOutVO proband = createProband(auth, departmentNum, isMale ? Sex.MALE : Sex.FEMALE, childIds, categories, titles); createFiles(auth, FileModule.PROBAND_DOCUMENT, proband.getId(), FILE_COUNT_PER_PROBAND); } } } private InputFieldOutVO createSelectManyField(AuthenticationVO auth, String name, String category, String title, String comment, boolean vertical, TreeMap<InputFieldValues, Boolean> selectionSetValues, Integer minSelections, Integer maxSelections, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(vertical ? InputFieldType.SELECT_MANY_V : InputFieldType.SELECT_MANY_H); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setMinSelections(minSelections); newInputField.setMaxSelections(maxSelections); newInputField.setValidationErrorMsg(validationErrorMessage); InputFieldOutVO inputField = inputFieldService.addInputField(auth, newInputField); jobOutput.println("select many input field created: " + inputField.getName()); addSelectionSetValues(auth, inputField, selectionSetValues); return inputField; } private InputFieldOutVO createSelectOneDropdownField(AuthenticationVO auth, String name, String category, String title, String comment, TreeMap<InputFieldValues, Boolean> selectionSetValues) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.SELECT_ONE_DROPDOWN); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); InputFieldOutVO inputField = inputFieldService.addInputField(auth, newInputField); jobOutput.println("select one dropdown input field created: " + inputField.getName()); addSelectionSetValues(auth, inputField, selectionSetValues); return inputField; } private InputFieldOutVO createSelectOneRadioField(AuthenticationVO auth, String name, String category, String title, String comment, boolean vertical, TreeMap<InputFieldValues, Boolean> selectionSetValues) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(vertical ? InputFieldType.SELECT_ONE_RADIO_V : InputFieldType.SELECT_ONE_RADIO_H); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); InputFieldOutVO inputField = inputFieldService.addInputField(auth, newInputField); jobOutput.println("select one radio input field created: " + inputField.getName()); addSelectionSetValues(auth, inputField, selectionSetValues); return inputField; } private InputFieldOutVO createSingleLineTextField(AuthenticationVO auth, String name, String category, String title, String comment, String textPreset, String regExp, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.SINGLE_LINE_TEXT); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setRegExp(regExp); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setTextPreset(textPreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("single line text input field created: " + out.getName()); return out; } private InputFieldOutVO createSketchField(AuthenticationVO auth, String name, String category, String title, String comment, String resourceFileName, TreeMap<InputFieldValues, Stroke> inkRegions, Integer minSelections, Integer maxSelections, String validationErrorMessage) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); ClassPathResource resource = new ClassPathResource("/" + resourceFileName); byte[] data = CommonUtil.inputStreamToByteArray(resource.getInputStream()); newInputField.setFieldType(InputFieldType.SKETCH); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setMinSelections(minSelections); newInputField.setMaxSelections(maxSelections); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setDatas(data); newInputField.setMimeType(ExecUtil.getMimeType(data, resource.getFilename())); newInputField.setFileName(resource.getFilename()); InputFieldOutVO inputField = inputFieldService.addInputField(auth, newInputField); jobOutput.println("select many input field created: " + inputField.getName()); addInkRegions(auth, inputField, inkRegions); return inputField; } public void createStaff(int staffCountPerDepartment) throws Exception { Collection<String> titles = toolsService.completeTitle(null, null, -1); int personCount = (int) (0.6 * staffCountPerDepartment); int personRootCount = (int) (0.1 * personCount); int externalCount = (int) (0.05 * personCount); int organisationCount = staffCountPerDepartment - personCount; int organisationRootCount = (int) (0.1 * organisationCount); for (int departmentNum = 0; departmentNum < departmentCount; departmentNum++) { for (int i = 0; i < externalCount; i++) { createStaffPerson(getRandomAuth(departmentNum), departmentNum, false, null, titles).getId(); } ArrayList<Long> createdIds = new ArrayList<Long>(); for (int i = 0; i < personRootCount; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); StaffOutVO staff = createStaffPerson(auth, departmentNum, true, null, titles); createdIds.add(staff.getId()); createFiles(auth, FileModule.STAFF_DOCUMENT, staff.getId(), FILE_COUNT_PER_STAFF); } for (int i = 0; i < (personCount - externalCount - personRootCount); i++) { AuthenticationVO auth = getRandomAuth(departmentNum); StaffOutVO staff = createStaffPerson(auth, departmentNum, true, getRandomElement(createdIds), titles); createdIds.add(staff.getId()); createFiles(auth, FileModule.STAFF_DOCUMENT, staff.getId(), FILE_COUNT_PER_STAFF); } createdIds.clear(); for (int i = 0; i < organisationRootCount; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); StaffOutVO organisation = createStaffOrganisation(auth, i, departmentNum, null); createdIds.add(organisation.getId()); createFiles(auth, FileModule.STAFF_DOCUMENT, organisation.getId(), FILE_COUNT_PER_ORGANISATION); } for (int i = 0; i < (organisationCount - organisationRootCount); i++) { AuthenticationVO auth = getRandomAuth(departmentNum); StaffOutVO organisation = createStaffOrganisation(auth, organisationRootCount + i, departmentNum, getRandomElement(createdIds)); createdIds.add(organisation.getId()); createFiles(auth, FileModule.STAFF_DOCUMENT, organisation.getId(), FILE_COUNT_PER_ORGANISATION); } } } private StaffOutVO createStaffOrganisation(AuthenticationVO auth, int organisationNum, int departmentNum, Long parentId) throws Exception { auth = (auth == null ? getRandomAuth() : auth); StaffInVO newStaff = new StaffInVO(); newStaff.setPerson(false); newStaff.setAllocatable(false); newStaff.setMaxOverlappingShifts(0l); newStaff.setParentId(parentId); newStaff.setDepartmentId(getDepartmentId(departmentNum)); newStaff.setCategoryId(getRandomElement(selectionSetService.getStaffCategories(auth, false, true, null)).getId()); newStaff.setOrganisationName("organisation_" + (departmentNum + 1) + "_" + (organisationNum + 1)); StaffOutVO staff = staffService.addStaff(auth, newStaff, null, null, null); jobOutput.println("organisation created: " + staff.getName()); assignUser(staff); return staff; } private StaffOutVO createStaffPerson(AuthenticationVO auth, int departmentNum, Boolean employee, Long parentId, Collection<String> titles) throws Exception { auth = (auth == null ? getRandomAuth() : auth); StaffInVO newStaff = new StaffInVO(); newStaff.setPerson(true); newStaff.setEmployee(employee == null ? getRandomBoolean(80) : employee); newStaff.setAllocatable(newStaff.getEmployee() && getRandomBoolean(50)); if (newStaff.getAllocatable()) { newStaff.setMaxOverlappingShifts(1l); } else { newStaff.setMaxOverlappingShifts(0l); } newStaff.setParentId(parentId); newStaff.setDepartmentId(getDepartmentId(departmentNum)); newStaff.setCategoryId(getRandomElement(selectionSetService.getStaffCategories(auth, true, false, null)).getId()); if (getRandomBoolean(25)) { newStaff.setPrefixedTitle1(getRandomElement(titles)); if (getRandomBoolean(20)) { newStaff.setPrefixedTitle2(getRandomElement(titles)); } } if (getRandomBoolean(50)) { newStaff.setGender(Sex.MALE); newStaff.setFirstName(getRandomElement(GermanPersonNames.MALE_FIRST_NAMES)); } else { newStaff.setGender(Sex.FEMALE); newStaff.setFirstName(getRandomElement(GermanPersonNames.FEMALE_FIRST_NAMES)); } newStaff.setLastName(getRandomElement(GermanPersonNames.LAST_NAMES)); newStaff.setCitizenship(getRandomBoolean(5) ? "Deutschland" : "österreich"); newStaff.setDateOfBirth(getRandomDateOfBirth()); StaffOutVO staff = staffService.addStaff(auth, newStaff, null, null, null); jobOutput.println("person created: " + staff.getName()); assignUser(staff); return staff; } private InputFieldOutVO createTimeField(AuthenticationVO auth, String name, String category, String title, String comment, Date timePreset, Date minTime, Date maxTime, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.TIME); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setMinTime(minTime); newInputField.setMaxTime(maxTime); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setTimePreset(timePreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("time input field created: " + out.getName()); return out; } private TimelineEventOutVO createTimelineEvent(AuthenticationVO auth, Long trialId, String title, String typeNameL10nKey, Date start, Date stop) throws Exception { auth = (auth == null ? getRandomAuth() : auth); TimelineEventInVO newTimelineEvent = new TimelineEventInVO(); TimelineEventType eventType = typeNameL10nKey != null ? timelineEventTypeDao.searchUniqueNameL10nKey(typeNameL10nKey) : getRandomElement(timelineEventTypeDao.loadAll()); newTimelineEvent.setTrialId(trialId); newTimelineEvent.setTypeId(eventType.getId()); newTimelineEvent.setImportance(getRandomElement(EventImportance.values())); newTimelineEvent.setNotify(eventType.isNotifyPreset()); newTimelineEvent.setReminderPeriod(VariablePeriod.EXPLICIT); newTimelineEvent.setReminderPeriodDays(getRandomElement(new Long[] { 7L, 14L, 21L })); newTimelineEvent.setShow(eventType.isShowPreset()); newTimelineEvent.setStart(start); newTimelineEvent.setStop(stop); newTimelineEvent.setParentId(null); newTimelineEvent.setTitle(title == null ? eventType.getNameL10nKey() : title); newTimelineEvent.setDescription("details eines weiteren " + eventType.getNameL10nKey() + " ereignisses"); TimelineEventOutVO out = trialService.addTimelineEvent(auth, newTimelineEvent, null, null, null); jobOutput.println("timeline event created: " + out.getTitle()); return out; } private InputFieldOutVO createTimestampField(AuthenticationVO auth, String name, String category, String title, String comment, Date timestampPreset, Date minTimestamp, Date maxTimestamp, boolean isUserTimeZone, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.TIMESTAMP); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setMinTimestamp(minTimestamp); newInputField.setMaxTimestamp(maxTimestamp); newInputField.setUserTimeZone(isUserTimeZone); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setTimestampPreset(timestampPreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("timestamp input field created: " + out.getName()); return out; } private TrialOutVO createTrial(AuthenticationVO auth, int departmentNum, int trialNum, int visitCount, int probandGroupCount, int avgGroupSize, SearchCriteria criteria) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); TrialInVO newTrial = new TrialInVO(); newTrial.setStatusId(getRandomElement(selectionSetService.getInitialTrialStatusTypes(auth)).getId()); newTrial.setDepartmentId(getDepartmentId(departmentNum)); newTrial.setName("TEST TRIAL " + (departmentNum + 1) + "-" + (trialNum + 1)); newTrial.setTitle(newTrial.getName()); newTrial.setDescription(""); newTrial.setSignupProbandList(false); newTrial.setSignupInquiries(false); newTrial.setSignupRandomize(false); newTrial.setSignupDescription(""); newTrial.setExclusiveProbands(false); newTrial.setProbandAliasFormat(""); newTrial.setDutySelfAllocationLocked(false); newTrial.setTypeId(getRandomElement(selectionSetService.getTrialTypes(auth, null)).getId()); newTrial.setSponsoringId(getRandomElement(selectionSetService.getSponsoringTypes(auth, null)).getId()); newTrial.setSurveyStatusId(getRandomElement(selectionSetService.getSurveyStatusTypes(auth, null)).getId()); TrialOutVO trial = trialService.addTrial(auth, newTrial, null); jobOutput.println("trial created: " + trial.getName()); ArrayList<Staff> departmentStaff = new ArrayList<Staff>(staffDao.search(new Search(new SearchParameter[] { new SearchParameter("department.id", trial.getDepartment().getId(), SearchParameter.EQUAL_COMPARATOR), new SearchParameter("person", true, SearchParameter.EQUAL_COMPARATOR), new SearchParameter("employee", true, SearchParameter.EQUAL_COMPARATOR), new SearchParameter("allocatable", true, SearchParameter.EQUAL_COMPARATOR) }))); Collection<TeamMemberRole> roles = teamMemberRoleDao.loadAll(); ArrayList<TeamMemberOutVO> teamMembers = new ArrayList<TeamMemberOutVO>(); Iterator<Staff> teamMemberStaffIt = getUniqueRandomElements(departmentStaff, 3 + random.nextInt(8)).iterator(); while (teamMemberStaffIt.hasNext()) { Staff teamMemberStaff = teamMemberStaffIt.next(); TeamMemberInVO newTeamMember = new TeamMemberInVO(); newTeamMember.setStaffId(teamMemberStaff.getId()); newTeamMember.setTrialId(trial.getId()); newTeamMember.setAccess(true); newTeamMember.setNotifyTimelineEvent(true); newTeamMember.setNotifyEcrfValidatedStatus(true); newTeamMember.setNotifyEcrfReviewStatus(true); newTeamMember.setNotifyEcrfVerifiedStatus(true); newTeamMember.setNotifyEcrfFieldStatus(true); newTeamMember.setNotifyOther(true); boolean created = false; TeamMemberRole role; while (!created) { try { role = getRandomElement(roles); newTeamMember.setRoleId(role.getId()); TeamMemberOutVO out = trialService.addTeamMember(auth, newTeamMember); jobOutput.println("team member created: " + out.getStaff().getName() + " (" + out.getRole().getName() + ")"); teamMembers.add(out); created = true; } catch (ServiceException e) { jobOutput.println(e.getMessage()); } } } VisitInVO newVisit = new VisitInVO(); newVisit.setTitle("Screeningvisite"); newVisit.setToken("SV"); newVisit.setReimbursement(0.0f); newVisit.setTypeId(visitTypeDao.searchUniqueNameL10nKey("screening").getId()); newVisit.setTrialId(trial.getId()); VisitOutVO screeningVisit = trialService.addVisit(auth, newVisit); jobOutput.println("visit created: " + screeningVisit.getTitle()); ArrayList<VisitOutVO> visits = new ArrayList<VisitOutVO>(); for (int i = 0; i < visitCount; i++) { newVisit = new VisitInVO(); newVisit.setTitle("Visite " + (i + 1)); newVisit.setToken("V" + (i + 1)); newVisit.setReimbursement(0.0f); newVisit.setTypeId(visitTypeDao.searchUniqueNameL10nKey("inpatient").getId()); newVisit.setTrialId(trial.getId()); VisitOutVO visit = trialService.addVisit(auth, newVisit); jobOutput.println("visit created: " + visit.getTitle()); visits.add(visit); } newVisit = new VisitInVO(); newVisit.setTitle("Abschlussvisite"); newVisit.setToken("AV"); newVisit.setReimbursement(0.0f); newVisit.setTypeId(visitTypeDao.searchUniqueNameL10nKey("final").getId()); newVisit.setTrialId(trial.getId()); VisitOutVO finalVisit = trialService.addVisit(auth, newVisit); jobOutput.println("visit created: " + finalVisit.getTitle()); visits.add(finalVisit); ProbandGroupInVO newProbandGroup = new ProbandGroupInVO(); newProbandGroup.setTitle("Screeninggruppe"); newProbandGroup.setToken("SG"); newProbandGroup.setTrialId(trial.getId()); ProbandGroupOutVO screeningGroup = trialService.addProbandGroup(auth, newProbandGroup); jobOutput.println("proband group created: " + screeningGroup.getTitle()); ArrayList<ProbandGroupOutVO> probandGroups = new ArrayList<ProbandGroupOutVO>(); for (int i = 0; i < probandGroupCount; i++) { newProbandGroup = new ProbandGroupInVO(); newProbandGroup.setTitle("Gruppe " + (i + 1)); newProbandGroup.setToken("G" + (i + 1)); newProbandGroup.setTrialId(trial.getId()); ProbandGroupOutVO probandGroup = trialService.addProbandGroup(auth, newProbandGroup); jobOutput.println("proband group created: " + probandGroup.getTitle()); probandGroups.add(probandGroup); } Date screeningDate = getRandomScreeningDate(); Date visitDate = new Date(); visitDate.setTime(screeningDate.getTime()); HashMap<Long, ArrayList<VisitScheduleItemOutVO>> visitScheduleItemPerGroupMap = new HashMap<Long, ArrayList<VisitScheduleItemOutVO>>(); long screeningDays = getRandomLong(2l, 14l); VisitScheduleItemInVO newVisitScheduleItem = new VisitScheduleItemInVO(); newVisitScheduleItem.setVisitId(screeningVisit.getId()); newVisitScheduleItem.setGroupId(screeningGroup.getId()); newVisitScheduleItem.setToken("D1"); newVisitScheduleItem.setTrialId(trial.getId()); newVisitScheduleItem.setNotify(false); Date[] startStop = getFromTo(visitDate, 9, 0, 16, 0); newVisitScheduleItem.setStart(startStop[0]); newVisitScheduleItem.setStop(startStop[1]); VisitScheduleItemOutVO visitScheduleItem = trialService.addVisitScheduleItem(auth, newVisitScheduleItem); ArrayList<VisitScheduleItemOutVO> groupVisitScheduleItems = new ArrayList<VisitScheduleItemOutVO>((int) screeningDays); groupVisitScheduleItems.add(visitScheduleItem); jobOutput.println("visit schedule item created: " + visitScheduleItem.getName()); createDuty(auth, departmentStaff, trial, startStop[0], startStop[1], "Dienst für Screening Tag 1"); for (int i = 2; i <= screeningDays; i++) { newVisitScheduleItem = new VisitScheduleItemInVO(); newVisitScheduleItem.setVisitId(screeningVisit.getId()); newVisitScheduleItem.setGroupId(screeningGroup.getId()); newVisitScheduleItem.setToken("D" + i); newVisitScheduleItem.setTrialId(trial.getId()); newVisitScheduleItem.setNotify(false); startStop = getFromTo(DateCalc.addInterval(visitDate, VariablePeriod.EXPLICIT, i - 1l), 9, 0, 16, 0); newVisitScheduleItem.setStart(startStop[0]); newVisitScheduleItem.setStop(startStop[1]); visitScheduleItem = trialService.addVisitScheduleItem(auth, newVisitScheduleItem); groupVisitScheduleItems.add(visitScheduleItem); visitScheduleItemPerGroupMap.put(screeningGroup.getId(), groupVisitScheduleItems); jobOutput.println("visit schedule item created: " + visitScheduleItem.getName()); createDuty(auth, departmentStaff, trial, startStop[0], startStop[1], "Dienst für Screening Tag " + i); } visitDate = DateCalc.addInterval(visitDate, VariablePeriod.EXPLICIT, getRandomElement(new Long[] { 2l, 3l, 7l }) + screeningDays - 1l); Iterator<VisitOutVO> visitIt = visits.iterator(); while (visitIt.hasNext()) { VisitOutVO visit = visitIt.next(); Iterator<ProbandGroupOutVO> probandGroupIt = probandGroups.iterator(); int groupCount = 0; while (probandGroupIt.hasNext()) { ProbandGroupOutVO probandGroup = probandGroupIt.next(); newVisitScheduleItem = new VisitScheduleItemInVO(); newVisitScheduleItem.setVisitId(visit.getId()); newVisitScheduleItem.setGroupId(probandGroup.getId()); newVisitScheduleItem.setToken(null); newVisitScheduleItem.setTrialId(trial.getId()); newVisitScheduleItem.setNotify(false); startStop = getFromTo(visitDate, 9, 0, 16, 0); newVisitScheduleItem.setStart(startStop[0]); newVisitScheduleItem.setStop(startStop[1]); if (!visitScheduleItemPerGroupMap.containsKey(probandGroup.getId())) { groupVisitScheduleItems = new ArrayList<VisitScheduleItemOutVO>(visits.size()); visitScheduleItemPerGroupMap.put(probandGroup.getId(), groupVisitScheduleItems); } else { groupVisitScheduleItems = visitScheduleItemPerGroupMap.get(probandGroup.getId()); } visitScheduleItem = trialService.addVisitScheduleItem(auth, newVisitScheduleItem); groupVisitScheduleItems.add(visitScheduleItem); jobOutput.println("visit schedule item created: " + visitScheduleItem.getName()); if (groupCount % 2 == 1) { createDuty(auth, departmentStaff, trial, startStop[0], startStop[1], null); visitDate = DateCalc.addInterval(visitDate, VariablePeriod.EXPLICIT, 1L); } groupCount++; } visitDate = DateCalc.addInterval(visitDate, VariablePeriod.EXPLICIT, getRandomElement(new Long[] { 1l, 2l, 3l, 7L, 14L, 21L })); } Date finalVisitDate = new Date(); finalVisitDate.setTime(visitDate.getTime()); createTimelineEvent(auth, trial.getId(), "Screening", "deadline", screeningDate, null); createTimelineEvent(auth, trial.getId(), "Abschlussvisite", "deadline", finalVisitDate, null); createTimelineEvent(auth, trial.getId(), "Studienvisiten", "phase", screeningDate, finalVisitDate); Date screeningDatePlanned = getRandomDateAround(screeningDate, 5, 5); createTimelineEvent(auth, trial.getId(), "Screening geplant", "phase", screeningDatePlanned, DateCalc.addInterval(screeningDatePlanned, VariablePeriod.EXPLICIT, (long) DateCalc.dateDeltaDays(screeningDate, finalVisitDate))); int screeningDelay = random.nextInt(15); Date recruitmentStop = DateCalc.subInterval(screeningDate, VariablePeriod.EXPLICIT, (long) screeningDelay); VariablePeriod recruitmentDuration = getRandomElement(new VariablePeriod[] { VariablePeriod.EXPLICIT, VariablePeriod.MONTH, VariablePeriod.TWO_MONTHS, VariablePeriod.THREE_MONTHS }); Date recruitmentStart = DateCalc.subInterval(recruitmentStop, recruitmentDuration, (recruitmentDuration == VariablePeriod.EXPLICIT ? getRandomElement(new Long[] { 21L, 42L, 70L }) : null)); createTimelineEvent(auth, trial.getId(), "Rekrutierung", "phase", recruitmentStart, recruitmentStop); Date trialStart = DateCalc.subInterval(recruitmentStart, VariablePeriod.EXPLICIT, getRandomElement(new Long[] { 14L, 21L, 28L, 42L })); Date trialEnd = getRandomDate(DateCalc.addInterval(finalVisitDate, VariablePeriod.EXPLICIT, 14L), DateCalc.addInterval(finalVisitDate, VariablePeriod.EXPLICIT, 60L)); createTimelineEvent(auth, trial.getId(), "Studie", "trial", trialStart, trialEnd); for (int i = 0; i < 3 + random.nextInt(8); i++) { createTimelineEvent(auth, trial.getId(), "Einreichfrist " + (i + 1), "deadline", getRandomDate(trialStart, screeningDate), null); } for (int i = 0; i < 1 + random.nextInt(3); i++) { createTimelineEvent(auth, trial.getId(), "Audit " + (i + 1), "deadline", getRandomDate(screeningDate, trialEnd), null); } for (int i = 0; i < 1 + random.nextInt(3); i++) { createTimelineEvent(auth, trial.getId(), "Abgabefrist " + (i + 1), "deadline", getRandomDate(finalVisitDate, trialEnd), null); } ArrayList<InquiryOutVO> inquiries = new ArrayList<InquiryOutVO>(); ArrayList<ProbandListEntryTagOutVO> probandListEntryTags = new ArrayList<ProbandListEntryTagOutVO>(); if (criteria != null) { inquiries.add(createInquiry(auth, InputFields.HEIGHT, trial, "01 - Allgemeine information", 1, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.WEIGHT, trial, "01 - Allgemeine information", 2, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.BMI, trial, "01 - Allgemeine information", 3, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.CLINICAL_TRIAL_EXPERIENCE_YN, trial, "01 - Allgemeine information", 4, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.SMOKER_YN, trial, "01 - Allgemeine information", 5, true, true, false, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.CIGARETTES_PER_DAY, trial, "01 - Allgemeine information", 6, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.DIABETES_YN, trial, "02 - Diabetes", 1, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.DIABETES_TYPE, trial, "02 - Diabetes", 2, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.DIABETES_SINCE, trial, "02 - Diabetes", 3, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.DIABETES_HBA1C_MMOLPERMOL, trial, "02 - Diabetes", 4, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.DIABETES_HBA1C_DATE, trial, "02 - Diabetes", 5, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.DIABETES_ATTENDING_PHYSICIAN, trial, "02 - Diabetes", 6, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.DIABETES_METHOD_OF_TREATMENT, trial, "02 - Diabetes", 7, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.DIABETES_MEDICATION, trial, "02 - Diabetes", 8, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.CHRONIC_DISEASE_YN, trial, "03 - Krankheitsgeschichte", 1, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.CHRONIC_DISEASE, trial, "03 - Krankheitsgeschichte", 2, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.EPILEPSY_YN, trial, "03 - Krankheitsgeschichte", 3, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.EPILEPSY, trial, "03 - Krankheitsgeschichte", 4, true, true, true, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.CARDIAC_PROBLEMS_YN, trial, "03 - Krankheitsgeschichte", 5, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.CARDIAC_PROBLEMS, trial, "03 - Krankheitsgeschichte", 6, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.HYPERTENSION_YN, trial, "03 - Krankheitsgeschichte", 7, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.HYPERTENSION, trial, "03 - Krankheitsgeschichte", 8, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.RENAL_INSUFFICIENCY_YN, trial, "03 - Krankheitsgeschichte", 9, true, true, false, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.RENAL_INSUFFICIENCY, trial, "03 - Krankheitsgeschichte", 10, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.LIVER_DISEASE_YN, trial, "03 - Krankheitsgeschichte", 11, true, true, false, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.LIVER_DISEASE, trial, "03 - Krankheitsgeschichte", 12, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.ANEMIA_YN, trial, "03 - Krankheitsgeschichte", 13, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.ANEMIA, trial, "03 - Krankheitsgeschichte", 14, true, true, true, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.IMMUNE_MEDAITED_DISEASE_YN, trial, "03 - Krankheitsgeschichte", 15, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.IMMUNE_MEDAITED_DISEASE, trial, "03 - Krankheitsgeschichte", 16, true, true, true, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.GESTATION_YN, trial, "03 - Krankheitsgeschichte", 17, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.GESTATION_TYPE, trial, "03 - Krankheitsgeschichte", 18, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.CONTRACEPTION_YN, trial, "03 - Krankheitsgeschichte", 19, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.CONTRACEPTION_TYPE, trial, "03 - Krankheitsgeschichte", 20, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.ALCOHOL_DRUG_ABUSE_YN, trial, "03 - Krankheitsgeschichte", 21, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.ALCOHOL_DRUG_ABUSE, trial, "03 - Krankheitsgeschichte", 22, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.ALLERGY_YN, trial, "03 - Krankheitsgeschichte", 23, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.ALLERGY, trial, "03 - Krankheitsgeschichte", 24, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.MEDICATION_YN, trial, "03 - Krankheitsgeschichte", 25, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.MEDICATION, trial, "03 - Krankheitsgeschichte", 26, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.EYE_PROBLEMS_YN, trial, "03 - Krankheitsgeschichte", 27, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.EYE_PROBLEMS, trial, "03 - Krankheitsgeschichte", 28, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.FEET_PROBLEMS_YN, trial, "03 - Krankheitsgeschichte", 29, true, true, false, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.FEET_PROBLEMS, trial, "03 - Krankheitsgeschichte", 30, true, true, true, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.DIAGNOSTIC_FINDINGS_AVAILABLE_YN, trial, "03 - Krankheitsgeschichte", 31, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.DIAGNOSTIC_FINDINGS_AVAILABLE, trial, "03 - Krankheitsgeschichte", 32, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.GENERAL_STATE_OF_HEALTH, trial, "03 - Krankheitsgeschichte", 33, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.NOTE, trial, "03 - Krankheitsgeschichte", 34, true, true, true, false, true, true, null, null, null, null, null)); } probandListEntryTags.add(createProbandListEntryTag(auth, InputFields.SUBJECT_NUMBER, trial, 1, false, false, true, true, true, false, false, null, null, null, null, null)); probandListEntryTags.add(createProbandListEntryTag(auth, InputFields.IC_DATE, trial, 2, false, false, true, true, true, false, false, null, null, null, null, null)); probandListEntryTags.add(createProbandListEntryTag(auth, InputFields.SCREENING_DATE, trial, 3, false, false, true, true, true, false, false, null, null, null, null, null)); probandListEntryTags.add(createProbandListEntryTag(auth, InputFields.LAB_NUMBER, trial, 4, false, false, true, true, true, false, false, null, null, null, null, null)); probandListEntryTags.add(createProbandListEntryTag(auth, InputFields.RANDOM_NUMBER, trial, 5, false, false, true, true, true, false, false, null, null, null, null, null)); probandListEntryTags .add(createProbandListEntryTag(auth, InputFields.LETTER_TO_PHYSICIAN_SENT, trial, 6, false, false, true, true, true, false, false, null, null, null, null, null)); probandListEntryTags .add(createProbandListEntryTag(auth, InputFields.PARTICIPATION_LETTER_IN_MEDOCS, trial, 7, false, false, true, true, true, false, false, null, null, null, null, null)); probandListEntryTags .add(createProbandListEntryTag(auth, InputFields.COMPLETION_LETTER_IN_MEDOCS, trial, 8, false, false, true, true, true, false, false, null, null, null, null, null)); if (!"migration_started".equals(trial.getStatus().getNameL10nKey())) { newTrial.setId(trial.getId()); newTrial.setVersion(trial.getVersion()); newTrial.setStatusId(trialStatusTypeDao.searchUniqueNameL10nKey("started").getId()); trial = trialService.updateTrial(auth, newTrial, null, false); jobOutput.println("trial " + trial.getName() + " updated: " + trial.getStatus().getName()); } Collection allProbands = probandDao.search(new Search(new SearchParameter[] { new SearchParameter("department.id", getDepartmentId(departmentNum), SearchParameter.EQUAL_COMPARATOR) })); ArrayList<ProbandOutVO> probands; if (criteria != null) { Iterator<Proband> probandsIt = allProbands.iterator(); while (probandsIt.hasNext()) { Proband proband = probandsIt.next(); ProbandOutVO probandVO = probandService.getProband(auth, proband.getId(), null, null, null); HashSet<InquiryValueInVO> inquiryValuesIns = new HashSet<InquiryValueInVO>(); Iterator<InquiryOutVO> inquiriesIt = inquiries.iterator(); while (inquiriesIt.hasNext()) { InquiryOutVO inquiry = inquiriesIt.next(); if (inquiry.isActive()) { InquiryValueInVO newInquiryValue = new InquiryValueInVO(); newInquiryValue.setProbandId(proband.getId()); newInquiryValue.setInquiryId(inquiry.getId()); setRandomInquiryValue(inquiry, newInquiryValue); inquiryValuesIns.add(newInquiryValue); } } jobOutput.println(probandVO.getName() + ": " + probandService.setInquiryValues(getRandomAuth(departmentNum), inquiryValuesIns, true).getPageValues().size() + " inquiry values set/created"); } probands = new ArrayList<ProbandOutVO>(performSearch(auth, criteria, null, null)); } else { probands = new ArrayList<ProbandOutVO>(allProbands.size()); Iterator<Proband> probandsIt = allProbands.iterator(); while (probandsIt.hasNext()) { probands.add(probandService.getProband(auth, probandsIt.next().getId(), null, null, null)); } } Collections.shuffle(probands, random); ArrayList<ProbandListEntryOutVO> probandListEntries = new ArrayList<ProbandListEntryOutVO>(); for (int i = 0; i < probands.size() && i < (probandGroupCount * avgGroupSize); i++) { ProbandListEntryInVO newProbandListEntry = new ProbandListEntryInVO(); newProbandListEntry.setGroupId(getRandomElement(probandGroups).getId()); newProbandListEntry.setPosition(i + 1l); newProbandListEntry.setTrialId(trial.getId()); newProbandListEntry.setProbandId(probands.get(i).getId()); ProbandListEntryOutVO probandListEntry = trialService.addProbandListEntry(auth, false, false, false, newProbandListEntry); jobOutput.println("proband list entry created - trial: " + probandListEntry.getTrial().getName() + " position: " + probandListEntry.getPosition() + " proband: " + probandListEntry.getProband().getName()); updateProbandListStatusEntryRealTimestamp(probandListEntry.getLastStatus(), screeningGroup, visitScheduleItemPerGroupMap, 0); probandListEntry = trialService.getProbandListEntry(auth, probandListEntry.getId()); // valid laststatus probandListEntries.add(probandListEntry); } HashMap<String, ProbandListStatusTypeVO> probandListStatusTypeMap = new HashMap<String, ProbandListStatusTypeVO>(); Iterator<ProbandListStatusTypeVO> probandListStatusTypeIt = selectionSetService.getAllProbandListStatusTypes(auth, true).iterator(); while (probandListStatusTypeIt.hasNext()) { ProbandListStatusTypeVO probandListStatusType = probandListStatusTypeIt.next(); probandListStatusTypeMap.put(probandListStatusType.getNameL10nKey(), probandListStatusType); } Iterator<ProbandListEntryOutVO> probandListEntryIt = probandListEntries.iterator(); while (probandListEntryIt.hasNext()) { ProbandListEntryOutVO probandListEntry = probandListEntryIt.next(); HashSet<ProbandListEntryTagValueInVO> probandListEntryTagValuesIns = new HashSet<ProbandListEntryTagValueInVO>(); Iterator<ProbandListEntryTagOutVO> probandListEntryTagsIt = probandListEntryTags.iterator(); while (probandListEntryTagsIt.hasNext()) { ProbandListEntryTagOutVO probandListEntryTag = probandListEntryTagsIt.next(); ProbandListEntryTagValueInVO newProbandListEntryTagValue = new ProbandListEntryTagValueInVO(); newProbandListEntryTagValue.setListEntryId(probandListEntry.getId()); newProbandListEntryTagValue.setTagId(probandListEntryTag.getId()); setRandomProbandListEntryTagValue(probandListEntryTag, newProbandListEntryTagValue); probandListEntryTagValuesIns.add(newProbandListEntryTagValue); } jobOutput.println(probandListEntry.getPosition() + ". " + probandListEntry.getProband().getName() + ": " + trialService.setProbandListEntryTagValues(getRandomAuth(departmentNum), probandListEntryTagValuesIns, true).getPageValues().size() + " proband list entry tag values set/created"); HashSet<ProbandListStatusTypeVO> passedProbandListStatus = new HashSet<ProbandListStatusTypeVO>(); passedProbandListStatus.add(probandListEntry.getLastStatus().getStatus()); boolean allowPassed = false; int statusHistoryLength = 0; ProbandListStatusTypeVO newStatus; while ((newStatus = getNextProbandListStatusType(auth, probandListEntry, allowPassed, passedProbandListStatus, probandListStatusTypeMap)) != null) { passedProbandListStatus.add(newStatus); ProbandListStatusEntryInVO newProbandListStatusEntry = new ProbandListStatusEntryInVO(); newProbandListStatusEntry.setListEntryId(probandListEntry.getId()); newProbandListStatusEntry.setStatusId(newStatus.getId()); newProbandListStatusEntry.setReason(newStatus.isReasonRequired() ? "eine erforderliche Begründung" : null); newProbandListStatusEntry.setRealTimestamp(new Date(probandListEntry.getLastStatus().getRealTimestamp().getTime() + 60000l)); if (!updateProbandListStatusEntryRealTimestamp(trialService.addProbandListStatusEntry(auth, false, newProbandListStatusEntry), screeningGroup, visitScheduleItemPerGroupMap, statusHistoryLength)) { break; } probandListEntry = trialService.getProbandListEntry(auth, probandListEntry.getId()); // valid laststatus statusHistoryLength++; } jobOutput.println(probandListEntry.getPosition() + ". " + probandListEntry.getProband().getName() + ": " + statusHistoryLength + " enrollment status entries added - final state: " + probandListEntry.getLastStatus().getStatus().getName()); } return trial; } public void createTrials(int trialCountPerDepartment, SearchCriteria[] eligibilityCriterias, Integer[] visitCounts, Integer[] probandGroupCounts, Integer[] avgProbandGroupSizes) throws Throwable { for (int departmentNum = 0; departmentNum < departmentCount; departmentNum++) { for (int i = 0; i < trialCountPerDepartment; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); SearchCriteria eligibilityCriteria = null; if (eligibilityCriterias != null && i < eligibilityCriterias.length) { eligibilityCriteria = eligibilityCriterias[i]; } TrialOutVO trial = createTrial(auth, departmentNum, i, getRandomElement(visitCounts), getRandomElement(probandGroupCounts), getRandomElement(avgProbandGroupSizes), eligibilityCriteria); createFiles(auth, FileModule.TRIAL_DOCUMENT, trial.getId(), FILE_COUNT_PER_TRIAL); } } } private UserOutVO createUser(String name, String password, long departmentId, String departmentPassword) throws Exception { UserInVO newUser = new UserInVO(); newUser.setLocale(CommonUtil.localeToString(Locale.getDefault())); newUser.setTimeZone(CommonUtil.timeZoneToString(TimeZone.getDefault())); newUser.setDateFormat(null); newUser.setDecimalSeparator(null); newUser.setLocked(false); newUser.setShowTooltips(false); newUser.setDecrypt(true); newUser.setDecryptUntrusted(false); newUser.setEnableInventoryModule(true); newUser.setEnableStaffModule(true); newUser.setEnableCourseModule(true); newUser.setEnableTrialModule(true); newUser.setEnableInputFieldModule(true); newUser.setEnableProbandModule(true); newUser.setEnableMassMailModule(true); newUser.setEnableUserModule(true); newUser.setAuthMethod(AuthenticationType.LOCAL); PasswordInVO newPassword = new PasswordInVO(); ServiceUtil.applyLogonLimitations(newPassword); newUser.setDepartmentId(departmentId); newUser.setName(name); newPassword.setPassword(password); UserOutVO user = toolsService.addUser(newUser, newPassword, departmentPassword); jobOutput.println("user created: " + user.getName()); addUserPermissionProfiles(user, new ArrayList<PermissionProfile>() { { add(PermissionProfile.INVENTORY_MASTER_ALL_DEPARTMENTS); add(PermissionProfile.STAFF_MASTER_ALL_DEPARTMENTS); add(PermissionProfile.COURSE_MASTER_ALL_DEPARTMENTS); add(PermissionProfile.TRIAL_MASTER_ALL_DEPARTMENTS); add(PermissionProfile.PROBAND_MASTER_ALL_DEPARTMENTS); add(PermissionProfile.USER_ALL_DEPARTMENTS); add(PermissionProfile.INPUT_FIELD_MASTER); add(PermissionProfile.MASS_MAIL_DETAIL_ALL_DEPARTMENTS); add(PermissionProfile.INVENTORY_MASTER_SEARCH); add(PermissionProfile.STAFF_MASTER_SEARCH); add(PermissionProfile.COURSE_MASTER_SEARCH); add(PermissionProfile.TRIAL_MASTER_SEARCH); add(PermissionProfile.PROBAND_MASTER_SEARCH); add(PermissionProfile.USER_MASTER_SEARCH); add(PermissionProfile.INPUT_FIELD_MASTER_SEARCH); add(PermissionProfile.MASS_MAIL_MASTER_SEARCH); } }); return user; } private AuthenticationVO getAuth(int departmentNum, int userNum) { return new AuthenticationVO(getUsername(departmentNum, userNum), getUserPassword(departmentNum, userNum), null, "localhost"); } private CriteriaOutVO getCriteria(AuthenticationVO auth, SearchCriteria criteria) throws Throwable { final AuthenticationVO a = (auth == null ? getRandomAuth() : auth); String name = criteria.toString(); Iterator<Criteria> it = (new ArrayList<Criteria>(criteriaDao.search(new Search(new SearchParameter[] { new SearchParameter("category", "test_" + prefix, SearchParameter.EQUAL_COMPARATOR), new SearchParameter("label", name, SearchParameter.EQUAL_COMPARATOR) })))).iterator(); if (it.hasNext()) { return searchService.getCriteria(a, it.next().getId()); } else { switch (criteria) { case ALL_INVENTORY: return createCriteria(a, DBModule.INVENTORY_DB, new ArrayList<SearchCriterion>(), name, "This query lists all inventory items.", true); case ALL_STAFF: return createCriteria(a, DBModule.STAFF_DB, new ArrayList<SearchCriterion>(), name, "This query lists all person and organisation records.", true); case ALL_COURSES: return createCriteria(a, DBModule.COURSE_DB, new ArrayList<SearchCriterion>(), name, "This query lists all courses.", true); case ALL_TRIALS: return createCriteria(a, DBModule.TRIAL_DB, new ArrayList<SearchCriterion>(), name, "This query lists all trials.", true); case ALL_PROBANDS: return createCriteria(a, DBModule.PROBAND_DB, new ArrayList<SearchCriterion>(), name, "This query lists all probands.", true); case ALL_INPUTFIELDS: return createCriteria(a, DBModule.INPUT_FIELD_DB, new ArrayList<SearchCriterion>(), name, "This query lists all input fields.", true); case ALL_USERS: return createCriteria(a, DBModule.USER_DB, new ArrayList<SearchCriterion>(), name, "This query lists all users.", true); case ALL_MASSMAILS: return createCriteria(a, DBModule.MASS_MAIL_DB, new ArrayList<SearchCriterion>(), name, "This query lists all mass mails.", true); case SUBJECTS_1: return createCriteria(a, DBModule.PROBAND_DB, new ArrayList<SearchCriterion>() { { InputFieldOutVO field1 = getInputField(a, InputFields.DIABETES_TYPE); InputFieldSelectionSetValue value1 = getInputFieldValue(field1.getId(), InputFieldValues.TYP_2_DIABETES_OHNE_INSULINEIGENPRODUKTION); add(new SearchCriterion(null, "proband.inquiryValues.inquiry.field.id", CriterionRestriction.EQ, field1.getId())); add(new SearchCriterion(CriterionTie.AND, "proband.inquiryValues.value.selectionValues.id", CriterionRestriction.EQ, value1.getId())); } }, name, "", true); default: return null; } } } private Long getDepartmentId(int departmentNum) throws Exception { return ExecUtil.departmentL10nKeyToId(getDepartmentName(departmentNum), departmentDao, jobOutput); } private Object[] getDepartmentIds() { ArrayList<Long> result = new ArrayList<Long>(); Pattern departmentNameRegExp = Pattern.compile("^department " + Pattern.quote(prefix) + " [0-9]+$"); Iterator<Department> departmentIt = departmentDao.loadAll().iterator(); while (departmentIt.hasNext()) { Department department = departmentIt.next(); if (departmentNameRegExp.matcher(department.getNameL10nKey()).find()) { result.add(department.getId()); } } return result.toArray(); } private String getDepartmentName(int num) { return String.format("department %s %d", prefix, num + 1); } private String getDepartmentPassword(int num) { return getDepartmentName(num); } private Date[] getFromTo(Date date, int hourStart, int minuteStart, int hourEnd, int minuteEnd) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); Date[] result = new Date[2]; result[0] = (new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), hourStart, minuteStart, 0)) .getTime(); result[1] = (new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), hourEnd, minuteEnd, 0)) .getTime(); return result; } private InputFieldOutVO getInputField(AuthenticationVO auth, InputFields inputField) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); String name = inputField.toString(); Iterator<InputField> it = inputFieldDao.findByNameL10nKeyLocalized(name, false).iterator(); if (it.hasNext()) { return inputFieldService.getInputField(auth, it.next().getId()); } else { String inquiryQuestionsCategory = "Erhebungsfragen"; String probandListEntryTagCategory = "Probandenlistenspalten"; String ecrfFieldCategory = "eCRF Felder"; switch (inputField) { case HEIGHT: return createIntegerField(auth, name, inquiryQuestionsCategory, "Körpergröße (cm):", "", null, 50l, 300l, "Die Körpergröße erfordert einen Ganzzahlwert zwischen 50 und 300 cm."); case WEIGHT: return createIntegerField(auth, name, inquiryQuestionsCategory, "Körpergewicht (kg):", "", null, 3l, 500l, "Das Körpergewicht erfordert einen Ganzzahlwert zwischen 3 und 500 kg."); case BMI: return createFloatField(auth, name, inquiryQuestionsCategory, "BMI (kg/m²):", "", null, 5f, 60f, "Der BMI erfordert eine Fließkommazahl zwischen 5.0 und 200.0 kg/m²."); case DIABETES_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Diabetes:", null, false); case DIABETES_TYPE: return createSelectOneRadioField(auth, name, inquiryQuestionsCategory, "Diabetes Typ:", null, false, new TreeMap<InputFieldValues, Boolean>() { { put(InputFieldValues.TYP_1_DIABETES, false); put(InputFieldValues.TYP_2_DIABETES_MIT_INSULINEIGENPRODUKTION, false); put(InputFieldValues.TYP_2_DIABETES_OHNE_INSULINEIGENPRODUKTION, false); } }); case DIABETES_SINCE: return createIntegerField(auth, name, inquiryQuestionsCategory, "Diabetes seit (Jahr):", null, null, 1930l, null, "Diabetes seit erfordert eine Jahreszahl größer gleich 1930."); case DIABETES_HBA1C_MMOLPERMOL: return createFloatField(auth, name, inquiryQuestionsCategory, "HbA1C-Wert (mmol/mol):", null, null, 20f, 130f, "Der HbA1C-Wert erfordert eine Fließkommazahl zwischen 20.0 und 130.0 mmol/mol"); case DIABETES_HBA1C_PERCENT: return createFloatField(auth, name, inquiryQuestionsCategory, "HbA1C-Wert (Prozent):", null, null, 2.5f, 15f, "Der HbA1C-Wert erfordert eine Fließkommazahl zwischen 2.5 und 15.0 %"); case DIABETES_HBA1C_DATE: return createDateField(auth, name, inquiryQuestionsCategory, "HbA1C zuletzt bestimmt:", null, null, (new GregorianCalendar(1980, 0, 1)).getTime(), null, "HbA1C zuletzt bestimmt muss nach 1980-01-01 liegen"); case DIABETES_C_PEPTIDE: return createFloatField(auth, name, inquiryQuestionsCategory, "C-Peptid (µg/l):", null, null, 0.5f, 7.0f, "Die C-Peptid Konzentration erfordert eine Fließkommazahl zwischen 0.5 und 7.0 µg/l"); case DIABETES_ATTENDING_PHYSICIAN: return createSingleLineTextField(auth, name, inquiryQuestionsCategory, "Arzt in Behandlung:", "Name/Anschrift des Arztes", null, null, null); case DIABETES_METHOD_OF_TREATMENT: return createSelectManyField(auth, name, inquiryQuestionsCategory, "Behandlungsmethode:", null, true, new TreeMap<InputFieldValues, Boolean>() { { put(InputFieldValues.DIAET, false); put(InputFieldValues.SPORTLICHE_BETAETIGUNG, false); put(InputFieldValues.ORALE_ANTIDIABETIKA, false); put(InputFieldValues.INSULINTHERAPIE, false); } }, null, null, null); case DIABETES_MEDICATION: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Medikamente:", null, null, null, null); case CLINICAL_TRIAL_EXPERIENCE_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Haben Sie Erfahrung mit klinischen Studien?", null, false); case SMOKER_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Raucher:", null, false); case CIGARETTES_PER_DAY: return createSelectOneDropdownField(auth, name, inquiryQuestionsCategory, "Zigaretten/Tag:", null, new TreeMap<InputFieldValues, Boolean>() { { put(InputFieldValues.CIGARETTES_UNTER_5, false); put(InputFieldValues.CIGARETTES_5_20, false); put(InputFieldValues.CIGARETTES_20_40, false); put(InputFieldValues.CIGARETTES_UEBER_40, false); } }); case CHRONIC_DISEASE_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Chronische Erkrankung:", null, false); case CHRONIC_DISEASE: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Chronische Erkrankung:", null, null, null, null); case EPILEPSY_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Epilepsie:", null, false); case EPILEPSY: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Epilepsie:", null, null, null, null); case CARDIAC_PROBLEMS_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Herzprobleme:", null, false); case CARDIAC_PROBLEMS: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "herzprobleme:", null, null, null, null); case HYPERTENSION_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Bluthochdruck:", null, false); case HYPERTENSION: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Bluthochdruck:", null, null, null, null); case RENAL_INSUFFICIENCY_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Niereninsuffizienz/-erkrankung:", null, false); case RENAL_INSUFFICIENCY: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Niereninsuffizienz/-erkrankung:", null, null, null, null); case LIVER_DISEASE_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Lebererkrankung:", null, false); case LIVER_DISEASE: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Lebererkrankung:", null, null, null, null); case ANEMIA_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Anämie (Blutarmut):", null, false); case ANEMIA: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Anämie (Blutarmut):", null, null, null, null); case IMMUNE_MEDAITED_DISEASE_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Autoimmunerkrankung:", null, false); case IMMUNE_MEDAITED_DISEASE: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Autoimmunerkrankung:", null, null, null, null); case GESTATION_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "schwanger, stillen etc.", null, false); case GESTATION: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "schwanger, stillen etc.", null, null, null, null); case GESTATION_TYPE: return createSelectManyField(auth, name, inquiryQuestionsCategory, "schwanger, stillen etc.", null, false, new TreeMap<InputFieldValues, Boolean>() { { put(InputFieldValues.SCHWANGER, false); put(InputFieldValues.STILLEN, false); } }, null, null, null); case CONTRACEPTION_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Empfängnisverhütung:", null, false); case CONTRACEPTION: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Empfängnisverhütung:", null, null, null, null); case CONTRACEPTION_TYPE: return createSelectManyField(auth, name, inquiryQuestionsCategory, "Empfängnisverhütung:", null, true, new TreeMap<InputFieldValues, Boolean>() { { put(InputFieldValues.HORMONELL, false); put(InputFieldValues.MECHANISCH, false); put(InputFieldValues.INTRAUTERINPESSARE, false); put(InputFieldValues.CHEMISCH, false); put(InputFieldValues.OPERATIV, false); } }, null, null, null); case ALCOHOL_DRUG_ABUSE_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Missbrauch von Alkohol/Drogen:", null, false); case ALCOHOL_DRUG_ABUSE: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Missbrauch von Alkohol/Drogen:", null, null, null, null); case PSYCHIATRIC_CONDITION_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Psychiatrische Erkrankung:", null, false); case PSYCHIATRIC_CONDITION: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Psychiatrische Erkrankung:", null, null, null, null); case ALLERGY_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Allergien:", null, false); case ALLERGY: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Allergien:", null, null, null, null); case MEDICATION_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Medikamente:", null, false); case MEDICATION: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Medikamente:", null, null, null, null); case EYE_PROBLEMS_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Probleme mit den Augen:", null, false); case EYE_PROBLEMS: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Probleme mit den Augen:", null, null, null, null); case FEET_PROBLEMS_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Probleme mit den Füßen:", null, false); case FEET_PROBLEMS: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Probleme mit den Füßen:", null, null, null, null); case DIAGNOSTIC_FINDINGS_AVAILABLE_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Haben Sie eventuell Befunde zu Hause?", null, false); case DIAGNOSTIC_FINDINGS_AVAILABLE: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Haben Sie eventuell Befunde zu Hause?", null, null, null, null); case GENERAL_STATE_OF_HEALTH: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Allgemeiner Gesundheitszustand:", null, null, null, null); case NOTE: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Anmerkungen:", null, null, null, null); case SUBJECT_NUMBER: // [0-9]{4}: omit ^ and $ here for xeger return createSingleLineTextField(auth, name, probandListEntryTagCategory, "Subject Number:", null, null, "[0-9]{4}", "Vierstellige Zahl (mit führenden Nullen) erforderlich."); case IC_DATE: return createDateField(auth, name, probandListEntryTagCategory, "Informed Consent Date:", null, null, null, null, null); case SCREENING_DATE: return createDateField(auth, name, probandListEntryTagCategory, "Screening Date:", null, null, null, null, null); case LAB_NUMBER: return createSingleLineTextField(auth, name, probandListEntryTagCategory, "Lab Nummer:", null, null, "[0-9]{4}", "Vierstellige Zahl (mit führenden Nullen) erforderlich."); case RANDOM_NUMBER: return createSingleLineTextField(auth, name, probandListEntryTagCategory, "Random Number:", null, null, "[0-9]{3}", "Dreistellige Nummber (mit führenden Nullen) erforderlich."); case LETTER_TO_PHYSICIAN_SENT: return createCheckBoxField(auth, name, probandListEntryTagCategory, "Letter to physician sent:", null, false); case PARTICIPATION_LETTER_IN_MEDOCS: return createCheckBoxField(auth, name, probandListEntryTagCategory, "Participation letter in MR/Medocs:", null, false); case LETTER_TO_SUBJECT_AT_END_OF_STUDY: return createCheckBoxField(auth, name, probandListEntryTagCategory, "Letter to subject at end of study:", null, false); case COMPLETION_LETTER_IN_MEDOCS: return createCheckBoxField(auth, name, probandListEntryTagCategory, "Completion letter in MR/Medocs:", null, false); case BODY_HEIGHT: return createIntegerField(auth, name, inquiryQuestionsCategory, "Body Height (cm):", "", null, 50l, 300l, "Body height requires an integer value between 50 and 300 cm."); case BODY_WEIGHT: return createIntegerField(auth, name, inquiryQuestionsCategory, "Body Weight (kg):", "", null, 3l, 500l, "Body weight requires an integer value between 3 and 500 kg."); case BODY_MASS_INDEX: return createFloatField(auth, name, inquiryQuestionsCategory, "BMI (kg/m²):", "", null, 5f, 60f, "Body mass index requires a decimal value between 5.0 and 200.0 kg/m²."); case OBESITY: return createSelectOneRadioField(auth, name, inquiryQuestionsCategory, "Obesity:", "BMI < 18.5: shortweight\n" + "18.5-24.9: normal weight\n" + "25-29.9: overweight\n" + "30-34.9: adiposity degree I\n" + "35-39.9: adiposity degree II\n" + ">= 40: adiposity degree III (morbid)", true, new TreeMap<InputFieldValues, Boolean>() { { put(InputFieldValues.SHORTWEIGHT, false); put(InputFieldValues.NORMAL_WEIGHT, false); put(InputFieldValues.OVERWEIGHT, false); put(InputFieldValues.ADIPOSITY_DEGREE_I, false); put(InputFieldValues.ADIPOSITY_DEGREE_II, false); put(InputFieldValues.ADIPOSITY_DEGREE_III, false); } }); case EGFR: return createFloatField(auth, name, inquiryQuestionsCategory, "Estimated Glomerular Filtration Rate (ml/min):", "", null, 1f, 50f, "Estimated glomerular filtration rate requires a decimal value between 1.0 and 50.0 ml/min."); case ETHNICITY: return createSelectOneDropdownField(auth, name, inquiryQuestionsCategory, "Ethnicity:", null, new TreeMap<InputFieldValues, Boolean>() { { put(InputFieldValues.AMERICAN_INDIAN_OR_ALASKA_NATIVE, false); put(InputFieldValues.ASIAN, false); put(InputFieldValues.BLACK, false); put(InputFieldValues.NATIVE_HAWAIIAN_OR_OTHER_PACIFIC_ISLANDER, false); put(InputFieldValues.WHITE, false); } }); case SERUM_CREATININ_CONCENTRATION: return createFloatField(auth, name, inquiryQuestionsCategory, "Serum Creatinin Concentration (mg/dl):", "", null, 1f, 50f, "Serum creatinin concentration requires a decimal value between 1.0 and 50.0 mg/dl."); // range? case HBA1C_PERCENT: return createFloatField(auth, name, inquiryQuestionsCategory, "HbA1C (%):", "", null, 2.5f, 15.0f, "HbA1C in percent requires a decimal value between 2.5 and 15.0 %."); case HBA1C_MMOLPERMOL: return createFloatField(auth, name, inquiryQuestionsCategory, "HbA1C (mmol/mol):", "", null, 20.0f, 130.0f, "HbA1C in mmol/mol requires a decimal value between 20.0 and 130.0 mmol/mol."); case MANNEQUIN: return createSketchField(auth, name, inquiryQuestionsCategory, "Joints:", "", "mannequin.png", new TreeMap<InputFieldValues, Stroke>() { { put(InputFieldValues.SHOULDER_RIGHT, new Stroke("M111.91619,64.773336L134.22667,64.773336L134.22667,86.512383L111.91619,86.512383Z")); put(InputFieldValues.SHOULDER_LEFT, new Stroke("M196.2019,66.916193L218.51238,66.916193L218.51238,88.65524L196.2019,88.65524Z")); put(InputFieldValues.ELLBOW_RIGHT, new Stroke("M114.05904,111.20191L136.36952,111.20191L136.36952,132.94095L114.05904,132.94095Z")); put(InputFieldValues.ELLBOW_LEFT, new Stroke("M197.63047,113.34477L219.94095,113.34477L219.94095,135.08381L197.63047,135.08381Z")); put(InputFieldValues.WRIST_RIGHT, new Stroke("M94.773327,156.9162L117.08381,156.9162L117.08381,178.65524L94.773327,178.65524Z")); put(InputFieldValues.WRIST_LEFT, new Stroke("M215.48761,161.20191L237.7981,161.20191L237.7981,182.94095L215.48761,182.94095Z")); put(InputFieldValues.THUMB_BASE_RIGHT, new Stroke("M29.891238,214.89125L49.823043,214.89125L49.823043,254.9659L29.891238,254.9659Z")); put(InputFieldValues.THUMB_MIDDLE_RIGHT, new Stroke("M9.0200169,246.16289L29.265697,246.16289L29.265697,265.83713L9.0200169,265.83713Z")); put(InputFieldValues.THUMB_BASE_LEFT, new Stroke("M282.0341,217.03411L301.9659,217.03411L301.9659,257.10876L282.0341,257.10876Z")); put(InputFieldValues.THUMB_MIDDLE_LEFT, new Stroke("M301.87716,250.4486L322.12284,250.4486L322.12284,270.12284L301.87716,270.12284Z")); put(InputFieldValues.INDEX_FINGER_BASE_RIGHT, new Stroke("M28.305731,271.87717L48.551411,271.87717L48.551411,291.55141L28.305731,291.55141Z")); put(InputFieldValues.INDEX_FINGER_MIDDLE_RIGHT, new Stroke("M22.591445,294.73431L42.837125,294.73431L42.837125,314.40855L22.591445,314.40855Z")); put(InputFieldValues.MIDDLE_FINGER_BASE_RIGHT, new Stroke("M48.305731,276.16288L68.551411,276.16288L68.551411,295.83712L48.305731,295.83712Z")); put(InputFieldValues.MIDDLE_FINGER_MIDDLE_RIGHT, new Stroke("M44.734302,298.30574L64.979982,298.30574L64.979982,317.97998L44.734302,317.97998Z")); put(InputFieldValues.RING_FINGER_BASE_RIGHT, new Stroke("M66.162873,279.02003L86.408553,279.02003L86.408553,298.69427L66.162873,298.69427Z")); put(InputFieldValues.RING_FINGER_MIDDLE_RIGHT, new Stroke("M65.448587,302.59146L85.694267,302.59146L85.694267,322.2657L65.448587,322.2657Z")); put(InputFieldValues.LITTLE_FINGER_BASE_RIGHT, new Stroke("M85.448587,276.16289L105.69427,276.16289L105.69427,295.83713L85.448587,295.83713Z")); put(InputFieldValues.LITTLE_FINGER_MIDDLE_RIGHT, new Stroke("M87.591444,299.02003L107.83713,299.02003L107.83713,318.69427L87.591444,318.69427Z")); put(InputFieldValues.INDEX_FINGER_BASE_LEFT, new Stroke("M281.16287,274.73432L301.40856,274.73432L301.40856,294.40856L281.16287,294.40856Z")); put(InputFieldValues.INDEX_FINGER_MIDDLE_LEFT, new Stroke("M286.16287,296.16289L306.40856,296.16289L306.40856,315.83713L286.16287,315.83713Z")); put(InputFieldValues.MIDDLE_FINGER_BASE_LEFT, new Stroke("M262.59144,279.73432L282.83713,279.73432L282.83713,299.40856L262.59144,299.40856Z")); put(InputFieldValues.MIDDLE_FINGER_MIDDLE_LEFT, new Stroke("M264.02001,301.87718L284.2657,301.87718L284.2657,321.55142L264.02001,321.55142Z")); put(InputFieldValues.RING_FINGER_BASE_LEFT, new Stroke("M244.7343,282.59147L264.97999,282.59147L264.97999,302.26571L244.7343,302.26571Z")); put(InputFieldValues.RING_FINGER_MIDDLE_LEFT, new Stroke("M244.02001,304.02004L264.2657,304.02004L264.2657,323.69428L244.02001,323.69428Z")); put(InputFieldValues.LITTLE_FINGER_BASE_LEFT, new Stroke("M224.7343,279.02004L244.97999,279.02004L244.97999,298.69428L224.7343,298.69428Z")); put(InputFieldValues.LITTLE_FINGER_MIDDLE_LEFT, new Stroke("M224.02001,301.1629L244.2657,301.1629L244.2657,320.83714L224.02001,320.83714Z")); put(InputFieldValues.KNEE_RIGHT, new Stroke("M133.4355,241.29267L161.27879,241.29267L161.27879,267.13594L133.4355,267.13594Z")); put(InputFieldValues.KNEE_LEFT, new Stroke("M166.29264,242.00696L194.13593,242.00696L194.13593,267.85023L166.29264,267.85023Z")); } }, 0, 28, "Mark up to 28 joints."); case VAS: return createSketchField(auth, name, inquiryQuestionsCategory, "Visual Analogue Scale:", "", "vas.png", new TreeMap<InputFieldValues, Stroke>() { { final int VAS_STEPS = 10; final float VAS_MAX_VALUE = 100.0f; final float VAS_X_OFFSET = 10.0f; final float VAS_LENGTH = 382.0f; final String[] VAS_COLORS = new String[] { "#24FF00", "#58FF00", "#8DFF00", "#C2FF00", "#F7FF00", "#FFD300", "#FF9E00", "#FF6900", "#FF3400", "#FF0000" }; for (int i = 0; i < VAS_STEPS; i++) { float valueFrom = i * VAS_MAX_VALUE / VAS_STEPS; float valueTo = (i + 1) * VAS_MAX_VALUE / VAS_STEPS; float value = (valueFrom + valueTo) / 2; float x1 = VAS_X_OFFSET + i * VAS_LENGTH / VAS_STEPS; float x2 = VAS_X_OFFSET + (i + 1) * VAS_LENGTH / VAS_STEPS; int colorIndex = i * VAS_COLORS.length / VAS_STEPS; put(InputFieldValues.valueOf(String.format("VAS_%d", i + 1)), new Stroke(VAS_COLORS[colorIndex], "M" + x1 + ",10L" + x2 + ",10L" + x2 + ",50L" + x1 + ",50Z", Float.toString(value))); } } }, 1, 1, "Mark exactly one position."); case ESR: return createFloatField(auth, name, inquiryQuestionsCategory, "Erythrocyte Sedimentation Rate (mm/h):", "", null, 1.0f, 30.0f, "Erythrocyte sedimentation rate requires a decimal value between 1.0 and 30.0 mm/h."); case DAS28: return createFloatField(auth, name, inquiryQuestionsCategory, "Disease Activity Score 28:", "", null, 2.0f, 10.0f, "Disease activity score 28 requires a decimal value between 2.0 and 10.0."); case DISTANCE: return createFloatField(auth, name, inquiryQuestionsCategory, "Distance (km):", "Travel distance from trial site to subject home address according to Google Maps.", null, 0.1f, 21000.0f, "Distance requires a decimal value between 0.1 and 21000.0 km."); case ALPHA_ID: return createSingleLineTextField(auth, name, inquiryQuestionsCategory, "Diagnosis Alpha ID Synonym:", null, null, null, null); case STRING_SINGLELINE: return createSingleLineTextField(auth, name, ecrfFieldCategory, "singleline text:", null, null, null, null); case STRING_MULTILINE: return createMultiLineTextField(auth, name, ecrfFieldCategory, "multiline text:", null, null, null, null); case FLOAT: return createFloatField(auth, name, ecrfFieldCategory, "decimal value:", "some decimal value", null, null, null, null); case INTEGER: return createIntegerField(auth, name, ecrfFieldCategory, "integer value:", "some integer value", null, null, null, null); case DIAGNOSIS_START: return createDateField(auth, name, inquiryQuestionsCategory, "Diagnosis Start:", null, null, null, null, null); case DIAGNOSIS_END: return createDateField(auth, name, inquiryQuestionsCategory, "Diagnosis End:", null, null, null, null, null); case DIAGNOSIS_COUNT: return createIntegerField(auth, name, ecrfFieldCategory, "Number of diagnoses:", null, null, 1l, null, "at least one diagnosis required"); default: return null; } } } private InputFieldSelectionSetValue getInputFieldValue(Long fieldId, InputFieldValues value) { return inputFieldSelectionSetValueDao.findByFieldNameL10nKeyLocalized(fieldId, value.toString(), false).iterator().next(); } private ProbandListStatusTypeVO getNextProbandListStatusType(AuthenticationVO auth, ProbandListEntryOutVO probandListEntry, boolean allowPassed, HashSet<ProbandListStatusTypeVO> passedProbandListStatus, HashMap<String, ProbandListStatusTypeVO> probandListStatusTypeMap) throws Exception { ProbandListStatusTypeVO newState = null; Collection<ProbandListStatusTypeVO> newStates = selectionSetService.getProbandListStatusTypeTransitions(auth, probandListEntry.getLastStatus().getStatus().getId()); if (newStates != null && newStates.size() > 0) { HashSet<Long> newStateIds = new HashSet<Long>(newStates.size()); Iterator<ProbandListStatusTypeVO> it = newStates.iterator(); while (it.hasNext()) { newStateIds.add(it.next().getId()); } if (!allowPassed) { while (newState == null) { newState = getRandomElement(newStates); newState = probandListStatusMarkov(newState, probandListStatusTypeMap); if (!newStateIds.contains(newState.getId())) { newState = null; } else if (passedProbandListStatus.contains(newState)) { newState = null; } } } else { while (newState == null) { newState = getRandomElement(newStates); newState = probandListStatusMarkov(newState, probandListStatusTypeMap); if (!newStateIds.contains(newState.getId())) { newState = null; } } } } return newState; } private AuthenticationVO getRandomAuth() { return getRandomAuth(random.nextInt(departmentCount)); } private AuthenticationVO getRandomAuth(int departmentNum) { int userNum = random.nextInt(usersPerDepartmentCount); return new AuthenticationVO(getUsername(departmentNum, userNum), getUserPassword(departmentNum, userNum), null, "localhost"); } private AuthenticationVO getRandomAuth(long departmentId) { String departmentL10nKey = departmentDao.load(departmentId).getNameL10nKey(); int departmentNum = Integer.parseInt(departmentL10nKey.replaceFirst("department " + Pattern.quote(prefix) + " ", "")) - 1; return getRandomAuth(departmentNum); } private Date getRandomAutoDeleteDeadline() { return getRandomDate((new GregorianCalendar(year, 0, 1)).getTime(), (new GregorianCalendar(year, 11, 31)).getTime()); } private boolean getRandomBoolean() { return random.nextBoolean(); } private boolean getRandomBoolean(int p) { if (p <= 0) { return false; } else if (p >= 100) { return true; } else { return random.nextDouble() < ((p) / 100.0d); } } private Date getRandomCourseStop() { return getRandomDate((new GregorianCalendar(year, 0, 1)).getTime(), (new GregorianCalendar(year, 11, 31)).getTime()); } private Date getRandomDate(Date minDate, Date maxDate) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(minDate == null ? (new GregorianCalendar(1900, 0, 1)).getTime() : minDate); cal = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0); cal.add(Calendar.DAY_OF_YEAR, random.nextInt(DateCalc.dateDeltaDays(minDate == null ? (new GregorianCalendar(1900, 0, 1)).getTime() : minDate, maxDate == null ? (new GregorianCalendar(year, 11, 31)).getTime() : maxDate))); return cal.getTime(); } private Date getRandomDateAround(Date date, int maxDaysBefore, int maxDaysAfter) { return DateCalc.addInterval(date, VariablePeriod.EXPLICIT, (long) (getRandomBoolean() ? random.nextInt(maxDaysAfter + 1) : (-1 * random.nextInt(maxDaysBefore + 1)))); } private Date getRandomDateOfBirth() { return getRandomDate((new GregorianCalendar(year - 90, 0, 1)).getTime(), (new GregorianCalendar(year - 20, 0, 1)).getTime()); } private Long getRandomDepartmentId() throws Exception { return getDepartmentId(random.nextInt(departmentCount)); } private <E> E getRandomElement(ArrayList<E> list) { if (list != null && list.size() > 0) { return list.get(random.nextInt(list.size())); } return null; } private <E> E getRandomElement(Collection<E> collection) { E result = null; if (collection != null && collection.size() > 0) { int index = random.nextInt(collection.size()); Iterator<E> it = collection.iterator(); for (int i = 0; i <= index; i++) { result = it.next(); } } return result; } private <E> E getRandomElement(E[] array) { if (array != null && array.length > 0) { return array[random.nextInt(array.length)]; } return null; } private float getRandomFloat(Float lowerLimit, Float upperLimit) { float lower = (lowerLimit == null ? 0f : lowerLimit.floatValue()); return lower + random.nextFloat() * ((upperLimit == null ? Float.MAX_VALUE : upperLimit.longValue()) - lower); } private long getRandomLong(Long lowerLimit, Long upperLimit) { long lower = (lowerLimit == null ? 0l : lowerLimit.longValue()); return lower + nextLong(random, (upperLimit == null ? Integer.MAX_VALUE : upperLimit.longValue()) - lower); } private Date getRandomScreeningDate() { return getRandomDate((new GregorianCalendar(year, 0, 1)).getTime(), (new GregorianCalendar(year, 11, 31)).getTime()); } private Date getRandomTime(Date minTime, Date maxTime) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(minTime == null ? (new GregorianCalendar(1970, 0, 1, 0, 0, 0)).getTime() : minTime); cal.setTimeInMillis(cal.getTimeInMillis() + nextLong(random, (maxTime == null ? (new GregorianCalendar(1970, 0, 1, 23, 59, 59)).getTime() : maxTime).getTime() - cal.getTimeInMillis())); return cal.getTime(); } private Date getRandomTimestamp(Date minTimestamp, Date maxTimestamp) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(minTimestamp == null ? (new GregorianCalendar(1900, 0, 1, 0, 0, 0)).getTime() : minTimestamp); cal.setTimeInMillis(cal.getTimeInMillis() + nextLong(random, (maxTimestamp == null ? (new GregorianCalendar(year, 11, 31)).getTime() : maxTimestamp).getTime() - cal.getTimeInMillis())); return cal.getTime(); } private Long getRandomUserId() { return getRandomUserId(random.nextInt(departmentCount)); } private Long getRandomUserId(int departmentNum) { return getUserId(departmentNum, random.nextInt(usersPerDepartmentCount)); } private <E> ArrayList<E> getUniqueRandomElements(ArrayList<E> list, int n) { if (list != null) { int listSize = list.size(); if (listSize > 0 && n > 0) { if (listSize <= n) { return new ArrayList<E>(list); } else { HashSet<E> result = new HashSet<E>(n); while (result.size() < n && result.size() < listSize) { result.add(list.get(random.nextInt(listSize))); } return new ArrayList<E>(result); } } else { return new ArrayList<E>(); } } return null; } private Long getUserId(int departmentNum, int userNum) { return userDao.searchUniqueName(getUsername(departmentNum, userNum)).getId(); } private String getUsername(int departmentNum, int num) { return String.format("user_%s_%d_%d", prefix, departmentNum + 1, num + 1); } private String getUserPassword(int departmentNum, int num) { return getUsername(departmentNum, num); } private long nextLong(Random rng, long n) { // error checking and 2^x checking removed for simplicity. if (n <= 0) { throw new IllegalArgumentException("n must be positive"); } // if ((n & -n) == n) // i.e., n is a power of 2 // return (int)((n * (long)next(31)) >> 31); long bits, val; do { bits = (rng.nextLong() << 1) >>> 1; val = bits % n; } while (bits - val + (n - 1) < 0L); return val; } private Collection performSearch(AuthenticationVO auth, SearchCriteria criteria, PSFVO psf, Integer maxInstances) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); CriteriaInVO newCriteria = new CriteriaInVO(); HashSet<CriterionInVO> newCriterions = new HashSet<CriterionInVO>(); ExecUtil.criteriaOutToIn(newCriteria, newCriterions, getCriteria(auth, criteria)); Collection result; String type; switch (newCriteria.getModule()) { case INVENTORY_DB: result = searchService.searchInventory(auth, newCriteria, newCriterions, maxInstances, psf); type = "inventory"; break; case STAFF_DB: result = searchService.searchStaff(auth, newCriteria, newCriterions, maxInstances, psf); type = "staff"; break; case COURSE_DB: result = searchService.searchCourse(auth, newCriteria, newCriterions, maxInstances, psf); type = "course"; break; case TRIAL_DB: result = searchService.searchTrial(auth, newCriteria, newCriterions, psf); type = "trial"; break; case PROBAND_DB: result = searchService.searchProband(auth, newCriteria, newCriterions, maxInstances, psf); type = "proband"; break; case INPUT_FIELD_DB: result = searchService.searchInputField(auth, newCriteria, newCriterions, psf); type = "inputfield"; break; case USER_DB: result = searchService.searchUser(auth, newCriteria, newCriterions, maxInstances, psf); type = "user"; break; case MASS_MAIL_DB: result = searchService.searchMassMail(auth, newCriteria, newCriterions, psf); type = "massmail"; break; default: result = null; type = null; } jobOutput.println("search '" + criteria.toString() + "' returned " + result.size() + (psf != null ? " of " + psf.getRowCount() : "") + " " + type + " items"); return result; } private ProbandListStatusTypeVO probandListStatusMarkov(ProbandListStatusTypeVO state, HashMap<String, ProbandListStatusTypeVO> probandListStatusTypeMap) throws Exception { boolean negative = getRandomBoolean(10); if ("cancelled".equals(state.getNameL10nKey())) { return negative ? state : probandListStatusTypeMap.get("acceptance"); } else if ("screening_failure".equals(state.getNameL10nKey())) { return negative ? state : probandListStatusTypeMap.get("screening_ok"); } else if ("dropped_out".equals(state.getNameL10nKey())) { return negative ? state : probandListStatusTypeMap.get("completed"); } return state; } public void setContext(ApplicationContext context) { this.context = context; } public void setJobOutput(JobOutput jobOutput) { this.jobOutput = jobOutput; } private void setRandomInquiryValue(InquiryOutVO inquiry, InquiryValueInVO inquiryValue) { if (!inquiry.isOptional() || getRandomBoolean()) { HashSet<Long> selectionSetValues = new HashSet<Long>(); switch (inquiry.getField().getFieldType().getType()) { case CHECKBOX: inquiryValue.setBooleanValue(inquiry.isDisabled() ? inquiry.getField().getBooleanPreset() : getRandomBoolean()); break; case SELECT_ONE_DROPDOWN: case SELECT_ONE_RADIO_H: case SELECT_ONE_RADIO_V: if (inquiry.isDisabled()) { Iterator<InputFieldSelectionSetValueOutVO> selectionSetValueIt = inquiry.getField().getSelectionSetValues().iterator(); while (selectionSetValueIt.hasNext()) { InputFieldSelectionSetValueOutVO selectionSetValue = selectionSetValueIt.next(); if (selectionSetValue.isPreset()) { selectionSetValues.add(selectionSetValue.getId()); break; } } } else { selectionSetValues.add(getRandomElement(inquiry.getField().getSelectionSetValues()).getId()); } inquiryValue.setSelectionValueIds(new ArrayList<Long>(selectionSetValues)); break; case SELECT_MANY_H: case SELECT_MANY_V: if (inquiry.isDisabled()) { Iterator<InputFieldSelectionSetValueOutVO> selectionSetValueIt = inquiry.getField().getSelectionSetValues().iterator(); while (selectionSetValueIt.hasNext()) { InputFieldSelectionSetValueOutVO selectionSetValue = selectionSetValueIt.next(); if (selectionSetValue.isPreset()) { selectionSetValues.add(selectionSetValue.getId()); } } } else { for (int i = 0; i <= random.nextInt(inquiry.getField().getSelectionSetValues().size()); i++) { selectionSetValues.add(getRandomElement(inquiry.getField().getSelectionSetValues()).getId()); } } inquiryValue.setSelectionValueIds(new ArrayList<Long>(selectionSetValues)); break; case SINGLE_LINE_TEXT: case MULTI_LINE_TEXT: if (inquiry.isDisabled()) { inquiryValue.setTextValue(inquiry.getField().getTextPreset()); } else { String regExp = inquiry.getField().getRegExp(); if (regExp != null && regExp.length() > 0) { Xeger generator = new Xeger(regExp); inquiryValue.setTextValue(generator.generate()); } else { inquiryValue.setTextValue("random text"); } } break; case INTEGER: inquiryValue.setLongValue(inquiry.isDisabled() ? inquiry.getField().getLongPreset() : getRandomLong(inquiry.getField().getLongLowerLimit(), inquiry.getField() .getLongUpperLimit())); break; case FLOAT: inquiryValue.setFloatValue(inquiry.isDisabled() ? inquiry.getField().getFloatPreset() : getRandomFloat(inquiry.getField().getFloatLowerLimit(), inquiry .getField().getFloatUpperLimit())); break; case DATE: inquiryValue.setDateValue(inquiry.isDisabled() ? inquiry.getField().getDatePreset() : getRandomDate(inquiry.getField().getMinDate(), inquiry.getField() .getMaxDate())); break; case TIME: inquiryValue.setTimeValue(inquiry.isDisabled() ? inquiry.getField().getTimePreset() : getRandomTime(inquiry.getField().getMinTime(), inquiry.getField() .getMaxTime())); break; case TIMESTAMP: inquiryValue.setTimestampValue(inquiry.isDisabled() ? inquiry.getField().getTimestampPreset() : getRandomTimestamp(inquiry.getField().getMinTimestamp(), inquiry.getField().getMaxTimestamp())); break; default: } } } private void setRandomProbandListEntryTagValue(ProbandListEntryTagOutVO probandListEntryTag, ProbandListEntryTagValueInVO probandListEntryTagValue) { if (!probandListEntryTag.isOptional() || getRandomBoolean()) { HashSet<Long> selectionSetValues = new HashSet<Long>(); switch (probandListEntryTag.getField().getFieldType().getType()) { case CHECKBOX: probandListEntryTagValue.setBooleanValue(probandListEntryTag.isDisabled() ? probandListEntryTag.getField().getBooleanPreset() : getRandomBoolean()); break; case SELECT_ONE_DROPDOWN: case SELECT_ONE_RADIO_H: case SELECT_ONE_RADIO_V: if (probandListEntryTag.isDisabled()) { Iterator<InputFieldSelectionSetValueOutVO> selectionSetValueIt = probandListEntryTag.getField().getSelectionSetValues().iterator(); while (selectionSetValueIt.hasNext()) { InputFieldSelectionSetValueOutVO selectionSetValue = selectionSetValueIt.next(); if (selectionSetValue.isPreset()) { selectionSetValues.add(selectionSetValue.getId()); break; } } } else { selectionSetValues.add(getRandomElement(probandListEntryTag.getField().getSelectionSetValues()).getId()); } probandListEntryTagValue.setSelectionValueIds(new ArrayList<Long>(selectionSetValues)); break; case SELECT_MANY_H: case SELECT_MANY_V: if (probandListEntryTag.isDisabled()) { Iterator<InputFieldSelectionSetValueOutVO> selectionSetValueIt = probandListEntryTag.getField().getSelectionSetValues().iterator(); while (selectionSetValueIt.hasNext()) { InputFieldSelectionSetValueOutVO selectionSetValue = selectionSetValueIt.next(); if (selectionSetValue.isPreset()) { selectionSetValues.add(selectionSetValue.getId()); } } } else { for (int i = 0; i <= random.nextInt(probandListEntryTag.getField().getSelectionSetValues().size()); i++) { selectionSetValues.add(getRandomElement(probandListEntryTag.getField().getSelectionSetValues()).getId()); } } probandListEntryTagValue.setSelectionValueIds(new ArrayList<Long>(selectionSetValues)); break; case SINGLE_LINE_TEXT: case MULTI_LINE_TEXT: if (probandListEntryTag.isDisabled()) { probandListEntryTagValue.setTextValue(probandListEntryTag.getField().getTextPreset()); } else { String regExp = probandListEntryTag.getField().getRegExp(); if (regExp != null && regExp.length() > 0) { Xeger generator = new Xeger(regExp); probandListEntryTagValue.setTextValue(generator.generate()); } else { probandListEntryTagValue.setTextValue("random text"); } } break; case INTEGER: probandListEntryTagValue.setLongValue(probandListEntryTag.isDisabled() ? probandListEntryTag.getField().getLongPreset() : getRandomLong(probandListEntryTag .getField().getLongLowerLimit(), probandListEntryTag.getField().getLongUpperLimit())); break; case FLOAT: probandListEntryTagValue.setFloatValue(probandListEntryTag.isDisabled() ? probandListEntryTag.getField().getFloatPreset() : getRandomFloat(probandListEntryTag .getField().getFloatLowerLimit(), probandListEntryTag.getField().getFloatUpperLimit())); break; case DATE: probandListEntryTagValue.setDateValue(probandListEntryTag.isDisabled() ? probandListEntryTag.getField().getDatePreset() : getRandomDate(probandListEntryTag .getField().getMinDate(), probandListEntryTag.getField().getMaxDate())); break; case TIME: probandListEntryTagValue.setTimeValue(probandListEntryTag.isDisabled() ? probandListEntryTag.getField().getTimePreset() : getRandomTime(probandListEntryTag .getField().getMinTime(), probandListEntryTag.getField().getMaxTime())); break; case TIMESTAMP: probandListEntryTagValue.setTimestampValue(probandListEntryTag.isDisabled() ? probandListEntryTag.getField().getTimestampPreset() : getRandomTimestamp( probandListEntryTag.getField().getMinTimestamp(), probandListEntryTag.getField().getMaxTimestamp())); break; default: } } } private boolean updateProbandListStatusEntryRealTimestamp(ProbandListStatusEntryOutVO probandListStatusEntryVO, ProbandGroupOutVO screeningGroup, HashMap<Long, ArrayList<VisitScheduleItemOutVO>> visitScheduleItemPerGroupMap, int statusHistoryLength) throws Exception { boolean result = true; VisitScheduleItemOutVO visitScheduleItem; if (probandListStatusEntryVO.getStatus().isInitial()) { visitScheduleItem = getRandomElement(visitScheduleItemPerGroupMap.get(screeningGroup.getId())); } else { ArrayList<VisitScheduleItemOutVO> visitScheduleItems = visitScheduleItemPerGroupMap.get(probandListStatusEntryVO.getListEntry().getGroup().getId()); if (statusHistoryLength >= visitScheduleItems.size()) { result = false; visitScheduleItem = visitScheduleItems.get(visitScheduleItems.size() - 1); } else { visitScheduleItem = visitScheduleItems.get(statusHistoryLength); } } ProbandListStatusEntry probandListStatusEntry = probandListStatusEntryDao.load(probandListStatusEntryVO.getId()); probandListStatusEntry.setRealTimestamp(new Timestamp(visitScheduleItem.getStop().getTime())); probandListStatusEntryDao.update(probandListStatusEntry); return result; } }
core/src/exec/java/org/phoenixctms/ctsms/executable/DemoDataProvider.java
package org.phoenixctms.ctsms.executable; import java.io.UnsupportedEncodingException; import java.sql.Timestamp; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.TimeZone; import java.util.TreeMap; import java.util.regex.Pattern; import org.apache.commons.lang3.RandomStringUtils; import org.phoenixctms.ctsms.Search; import org.phoenixctms.ctsms.SearchParameter; import org.phoenixctms.ctsms.domain.CourseCategory; import org.phoenixctms.ctsms.domain.CourseCategoryDao; import org.phoenixctms.ctsms.domain.CourseParticipationStatusType; import org.phoenixctms.ctsms.domain.CourseParticipationStatusTypeDao; import org.phoenixctms.ctsms.domain.Criteria; import org.phoenixctms.ctsms.domain.CriteriaDao; import org.phoenixctms.ctsms.domain.CriterionProperty; import org.phoenixctms.ctsms.domain.CriterionPropertyDao; import org.phoenixctms.ctsms.domain.CriterionRestrictionDao; import org.phoenixctms.ctsms.domain.CriterionTieDao; import org.phoenixctms.ctsms.domain.Department; import org.phoenixctms.ctsms.domain.DepartmentDao; import org.phoenixctms.ctsms.domain.InputField; import org.phoenixctms.ctsms.domain.InputFieldDao; import org.phoenixctms.ctsms.domain.InputFieldSelectionSetValue; import org.phoenixctms.ctsms.domain.InputFieldSelectionSetValueDao; import org.phoenixctms.ctsms.domain.Proband; import org.phoenixctms.ctsms.domain.ProbandCategory; import org.phoenixctms.ctsms.domain.ProbandCategoryDao; import org.phoenixctms.ctsms.domain.ProbandDao; import org.phoenixctms.ctsms.domain.ProbandListStatusEntry; import org.phoenixctms.ctsms.domain.ProbandListStatusEntryDao; import org.phoenixctms.ctsms.domain.SponsoringTypeDao; import org.phoenixctms.ctsms.domain.Staff; import org.phoenixctms.ctsms.domain.StaffDao; import org.phoenixctms.ctsms.domain.TeamMemberRole; import org.phoenixctms.ctsms.domain.TeamMemberRoleDao; import org.phoenixctms.ctsms.domain.TimelineEventType; import org.phoenixctms.ctsms.domain.TimelineEventTypeDao; import org.phoenixctms.ctsms.domain.TrialStatusTypeDao; import org.phoenixctms.ctsms.domain.TrialTypeDao; import org.phoenixctms.ctsms.domain.User; import org.phoenixctms.ctsms.domain.UserDao; import org.phoenixctms.ctsms.domain.UserPermissionProfile; import org.phoenixctms.ctsms.domain.UserPermissionProfileDao; import org.phoenixctms.ctsms.domain.VisitTypeDao; import org.phoenixctms.ctsms.enumeration.AuthenticationType; import org.phoenixctms.ctsms.enumeration.CriterionRestriction; import org.phoenixctms.ctsms.enumeration.CriterionTie; import org.phoenixctms.ctsms.enumeration.CriterionValueType; import org.phoenixctms.ctsms.enumeration.DBModule; import org.phoenixctms.ctsms.enumeration.EventImportance; import org.phoenixctms.ctsms.enumeration.FileModule; import org.phoenixctms.ctsms.enumeration.InputFieldType; import org.phoenixctms.ctsms.enumeration.PermissionProfile; import org.phoenixctms.ctsms.enumeration.RandomizationMode; import org.phoenixctms.ctsms.enumeration.Sex; import org.phoenixctms.ctsms.enumeration.VariablePeriod; import org.phoenixctms.ctsms.exception.ServiceException; import org.phoenixctms.ctsms.pdf.PDFImprinter; import org.phoenixctms.ctsms.pdf.PDFStream; import org.phoenixctms.ctsms.security.CryptoUtil; import org.phoenixctms.ctsms.service.course.CourseService; import org.phoenixctms.ctsms.service.inventory.InventoryService; import org.phoenixctms.ctsms.service.proband.ProbandService; import org.phoenixctms.ctsms.service.shared.FileService; import org.phoenixctms.ctsms.service.shared.InputFieldService; import org.phoenixctms.ctsms.service.shared.SearchService; import org.phoenixctms.ctsms.service.shared.SelectionSetService; import org.phoenixctms.ctsms.service.shared.ToolsService; import org.phoenixctms.ctsms.service.staff.StaffService; import org.phoenixctms.ctsms.service.trial.TrialService; import org.phoenixctms.ctsms.service.user.UserService; import org.phoenixctms.ctsms.util.CommonUtil; import org.phoenixctms.ctsms.util.CoreUtil; import org.phoenixctms.ctsms.util.ExecUtil; import org.phoenixctms.ctsms.util.GermanPersonNames; import org.phoenixctms.ctsms.util.JobOutput; import org.phoenixctms.ctsms.util.ServiceUtil; import org.phoenixctms.ctsms.util.date.DateCalc; import org.phoenixctms.ctsms.util.xeger.Xeger; import org.phoenixctms.ctsms.vo.AuthenticationVO; import org.phoenixctms.ctsms.vo.CourseInVO; import org.phoenixctms.ctsms.vo.CourseOutVO; import org.phoenixctms.ctsms.vo.CourseParticipationStatusEntryInVO; import org.phoenixctms.ctsms.vo.CourseParticipationStatusEntryOutVO; import org.phoenixctms.ctsms.vo.CriteriaInVO; import org.phoenixctms.ctsms.vo.CriteriaOutVO; import org.phoenixctms.ctsms.vo.CriterionInVO; import org.phoenixctms.ctsms.vo.DepartmentVO; import org.phoenixctms.ctsms.vo.DutyRosterTurnInVO; import org.phoenixctms.ctsms.vo.DutyRosterTurnOutVO; import org.phoenixctms.ctsms.vo.ECRFFieldInVO; import org.phoenixctms.ctsms.vo.ECRFFieldOutVO; import org.phoenixctms.ctsms.vo.ECRFInVO; import org.phoenixctms.ctsms.vo.ECRFOutVO; import org.phoenixctms.ctsms.vo.FileInVO; import org.phoenixctms.ctsms.vo.FileOutVO; import org.phoenixctms.ctsms.vo.FileStreamInVO; import org.phoenixctms.ctsms.vo.InputFieldInVO; import org.phoenixctms.ctsms.vo.InputFieldOutVO; import org.phoenixctms.ctsms.vo.InputFieldSelectionSetValueInVO; import org.phoenixctms.ctsms.vo.InputFieldSelectionSetValueOutVO; import org.phoenixctms.ctsms.vo.InquiryInVO; import org.phoenixctms.ctsms.vo.InquiryOutVO; import org.phoenixctms.ctsms.vo.InquiryValueInVO; import org.phoenixctms.ctsms.vo.InventoryInVO; import org.phoenixctms.ctsms.vo.InventoryOutVO; import org.phoenixctms.ctsms.vo.PSFVO; import org.phoenixctms.ctsms.vo.PasswordInVO; import org.phoenixctms.ctsms.vo.ProbandGroupInVO; import org.phoenixctms.ctsms.vo.ProbandGroupOutVO; import org.phoenixctms.ctsms.vo.ProbandInVO; import org.phoenixctms.ctsms.vo.ProbandListEntryInVO; import org.phoenixctms.ctsms.vo.ProbandListEntryOutVO; import org.phoenixctms.ctsms.vo.ProbandListEntryTagInVO; import org.phoenixctms.ctsms.vo.ProbandListEntryTagOutVO; import org.phoenixctms.ctsms.vo.ProbandListEntryTagValueInVO; import org.phoenixctms.ctsms.vo.ProbandListStatusEntryInVO; import org.phoenixctms.ctsms.vo.ProbandListStatusEntryOutVO; import org.phoenixctms.ctsms.vo.ProbandListStatusTypeVO; import org.phoenixctms.ctsms.vo.ProbandOutVO; import org.phoenixctms.ctsms.vo.StaffInVO; import org.phoenixctms.ctsms.vo.StaffOutVO; import org.phoenixctms.ctsms.vo.TeamMemberInVO; import org.phoenixctms.ctsms.vo.TeamMemberOutVO; import org.phoenixctms.ctsms.vo.TimelineEventInVO; import org.phoenixctms.ctsms.vo.TimelineEventOutVO; import org.phoenixctms.ctsms.vo.TrialInVO; import org.phoenixctms.ctsms.vo.TrialOutVO; import org.phoenixctms.ctsms.vo.UserInVO; import org.phoenixctms.ctsms.vo.UserOutVO; import org.phoenixctms.ctsms.vo.VisitInVO; import org.phoenixctms.ctsms.vo.VisitOutVO; import org.phoenixctms.ctsms.vo.VisitScheduleItemInVO; import org.phoenixctms.ctsms.vo.VisitScheduleItemOutVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.io.ClassPathResource; public class DemoDataProvider { private enum InputFields { HEIGHT("Körpergröße"), WEIGHT("Körpergewicht"), BMI("Body Mass Index"), DIABETES_YN("Diabetes J/N"), DIABETES_TYPE("Diabetes Typ"), DIABETES_SINCE("Diabetes seit"), DIABETES_HBA1C_MMOLPERMOL("HbA1C in mmol/mol"), DIABETES_HBA1C_PERCENT("HbA1C in prozent"), DIABETES_HBA1C_DATE("HbA1C Datum"), DIABETES_C_PEPTIDE("C-Peptid"), // µg/l DIABETES_ATTENDING_PHYSICIAN("Arzt in Behandlung"), DIABETES_METHOD_OF_TREATMENT("Diabetes Behandlungsmethode"), // Diät sport insulintherapie orale Antidiabetika DIABETES_MEDICATION("Diabetes Medikamente"), CLINICAL_TRIAL_EXPERIENCE_YN("Erfahrung mit klin. Studien J/N"), SMOKER_YN("Raucher J/N"), CIGARETTES_PER_DAY("Zigaretten pro Tag"), CHRONIC_DISEASE_YN("Chronische Erkrankung J/N"), CHRONIC_DISEASE("Chronische Erkrankung"), EPILEPSY_YN("Epilepsie J/N"), EPILEPSY("Epilepsie"), CARDIAC_PROBLEMS_YN("Herzprobleme J/N"), CARDIAC_PROBLEMS("Herzprobleme"), HYPERTENSION_YN("Bluthochdruck J/N"), HYPERTENSION("Bluthochdruck"), RENAL_INSUFFICIENCY_YN("Niereninsuffizienz/-erkrankung J/N"), // renal RENAL_INSUFFICIENCY("Niereninsuffizienz/-erkrankung"), LIVER_DISEASE_YN("Lebererkrankung J/N"), // liver diseaseYN LIVER_DISEASE("Lebererkrankung"), ANEMIA_YN("Anemie J/N"), // anemiaYN ANEMIA("Anemie"), IMMUNE_MEDAITED_DISEASE_YN("Autoimmunerkrankung J/N"), // immune mediated diseaseYN IMMUNE_MEDAITED_DISEASE("Autoimmunerkrankung"), GESTATION_YN("schwanger, stillen etc. J/N"), // gestationYN GESTATION("schwanger, stillen etc."), GESTATION_TYPE("schwanger, stillen etc. Auswahl"), CONTRACEPTION_YN("Empfängnisverhütung J/N"), // contraceptionYN CONTRACEPTION("Empfängnisverhütung"), CONTRACEPTION_TYPE("Empfängnisverhütung Auswahl"), ALCOHOL_DRUG_ABUSE_YN("Missbrauch von Alkohol/Drogen J/N"), // alcohol_drug_abuseYN ALCOHOL_DRUG_ABUSE("Missbrauch von Alkohol/Drogen"), PSYCHIATRIC_CONDITION_YN("Psychiatrische Erkrankung J/N"), // psychiatric_conditionYN PSYCHIATRIC_CONDITION("Psychiatrische Erkrankung"), ALLERGY_YN("Allergien J/N"), // allergyYN ALLERGY("Allergien"), MEDICATION_YN("Medikamente J/N"), // medicationYN MEDICATION("Medikamente"), EYE_PROBLEMS_YN("Probleme mit den Augen J/N"), // eye_probalemsYN EYE_PROBLEMS("Probleme mit den Augen"), FEET_PROBLEMS_YN("Probleme mit den Füßen J/N"), // feet_probalemsYN FEET_PROBLEMS("Probleme mit den Füßen"), DIAGNOSTIC_FINDINGS_AVAILABLE_YN("Befunde zuhause J/N"), DIAGNOSTIC_FINDINGS_AVAILABLE("Befunde zuhause"), GENERAL_STATE_OF_HEALTH("Allgemeiner Gesundheitszustand"), NOTE("Anmerkung"), SUBJECT_NUMBER("Subject Number"), IC_DATE("Informed Consent Date"), SCREENING_DATE("Screening Date"), LAB_NUMBER("Lab Number"), RANDOM_NUMBER("Random Number"), LETTER_TO_PHYSICIAN_SENT("Letter to physician sent"), PARTICIPATION_LETTER_IN_MEDOCS("Participation letter in MR/Medocs"), LETTER_TO_SUBJECT_AT_END_OF_STUDY("Letter to subject at end of study"), COMPLETION_LETTER_IN_MEDOCS("Completion letter in MR/Medocs"), BODY_HEIGHT("Body Height"), BODY_WEIGHT("Body Weight"), BODY_MASS_INDEX("BMI"), OBESITY("Obesity"), EGFR("eGFR"), SERUM_CREATININ_CONCENTRATION("Serum Creatinin Concentration"), ETHNICITY("Ethnicity"), HBA1C_PERCENT("HbA1C (percent)"), HBA1C_MMOLPERMOL("HbA1C (mmol/mol)"), MANNEQUIN("Mannequin"), ESR("ESR"), VAS("VAS"), DAS28("DAS28"), DISTANCE("Distance"), ALPHA_ID("Alpha-ID"), STRING_SINGLELINE("singleline text"), STRING_MULTILINE("multiline text"), FLOAT("decimal"), INTEGER("integer"), DIAGNOSIS_START("diagnosis from"), DIAGNOSIS_END("diagnosis to"), DIAGNOSIS_COUNT("diagnosis count"); private final String value; private InputFields(final String value) { this.value = value; } @Override public String toString() { return value; } } private enum InputFieldValues { TYP_1_DIABETES("Typ 1 Diabetes"), TYP_2_DIABETES_MIT_INSULINEIGENPRODUKTION("Typ 2 Diabetes mit Insulineigenproduktion"), TYP_2_DIABETES_OHNE_INSULINEIGENPRODUKTION("Typ 2 Diabetes ohne Insulineigenproduktion"), DIAET("Diät"), SPORTLICHE_BETAETIGUNG("Sportliche Betätigung"), ORALE_ANTIDIABETIKA("Orale Antidiabetika"), INSULINTHERAPIE("Insulintherapie"), CIGARETTES_UNTER_5("Unter 5"), CIGARETTES_5_20("5-20"), CIGARETTES_20_40("20-40"), CIGARETTES_UEBER_40("über 40"), SCHWANGER("schwanger"), STILLEN("stillen"), HORMONELL("hormonell"), MECHANISCH("mechanisch"), INTRAUTERINPESSARE("Intrauterinpessare"), CHEMISCH("chemisch"), OPERATIV("operativ"), SHORTWEIGHT("shortweight"), NORMAL_WEIGHT("normal weight"), OVERWEIGHT("overweight"), ADIPOSITY_DEGREE_I("adiposity degree I"), ADIPOSITY_DEGREE_II("adiposity degree II"), ADIPOSITY_DEGREE_III("adiposity degree III"), AMERICAN_INDIAN_OR_ALASKA_NATIVE("American Indian or Alaska Native"), ASIAN("Asian"), BLACK("Black"), NATIVE_HAWAIIAN_OR_OTHER_PACIFIC_ISLANDER("Native Hawaiian or Other Pacific Islander"), WHITE("White"), SHOULDER_RIGHT("shoulder right"), SHOULDER_LEFT("shoulder left"), ELLBOW_RIGHT("ellbow right"), ELLBOW_LEFT("ellbow left"), WRIST_RIGHT("wrist right"), WRIST_LEFT("wrist left"), THUMB_BASE_RIGHT("thumb base right"), THUMB_MIDDLE_RIGHT("thumb middle right"), THUMB_BASE_LEFT("thumb base left"), THUMB_MIDDLE_LEFT("thumb middle left"), INDEX_FINGER_BASE_RIGHT("index finger base right"), INDEX_FINGER_MIDDLE_RIGHT("index finger middle right"), MIDDLE_FINGER_BASE_RIGHT("middle finger base right"), MIDDLE_FINGER_MIDDLE_RIGHT("middle finger middle right"), RING_FINGER_BASE_RIGHT("ring finger base right"), RING_FINGER_MIDDLE_RIGHT("ring finger middle right"), LITTLE_FINGER_BASE_RIGHT("little finger base right"), LITTLE_FINGER_MIDDLE_RIGHT("little finger middle right"), INDEX_FINGER_BASE_LEFT("index finger base left"), INDEX_FINGER_MIDDLE_LEFT("index finger middle left"), MIDDLE_FINGER_BASE_LEFT("middle finger base left"), MIDDLE_FINGER_MIDDLE_LEFT("middle finger middle left"), RING_FINGER_BASE_LEFT("ring finger base left"), RING_FINGER_MIDDLE_LEFT("ring finger middle left"), LITTLE_FINGER_BASE_LEFT("little finger base left"), LITTLE_FINGER_MIDDLE_LEFT("little finger middle left"), KNEE_RIGHT("knee right"), KNEE_LEFT("knee left"), VAS_1("vas-1"), VAS_2("vas-2"), VAS_3("vas-3"), VAS_4("vas-4"), VAS_5("vas-5"), VAS_6("vas-6"), VAS_7("vas-7"), VAS_8("vas-8"), VAS_9("vas-9"), VAS_10("vas-10"); private final String value; private InputFieldValues(final String value) { this.value = value; } @Override public String toString() { return value; } } public enum SearchCriteria { ALL_INVENTORY("all inventory"), ALL_STAFF("all staff"), ALL_COURSES("all courses"), ALL_TRIALS("all trials"), ALL_PROBANDS("all probands"), ALL_INPUTFIELDS("all inputfields"), ALL_MASSMAILS("all_massmails"), ALL_USERS("all users"), SUBJECTS_1("subjects_1"); private final String value; private SearchCriteria(final String value) { this.value = value; } @Override public String toString() { return value; } } private final class SearchCriterion { private CriterionTie junction; private String property; private CriterionRestriction operator; private boolean booleanValue; private Date dateValue; private Float floatValue; private Long longValue; private String stringValue; private SearchCriterion(CriterionTie junction, String property, CriterionRestriction operator) { this.junction = junction; this.property = property; this.operator = operator; booleanValue = false; dateValue = null; floatValue = null; longValue = null; stringValue = null; } private SearchCriterion(CriterionTie junction, String property, CriterionRestriction operator, boolean value) { this(junction, property, operator); booleanValue = value; } private SearchCriterion(CriterionTie junction, String property, CriterionRestriction operator, Date value) { this(junction, property, operator); dateValue = value; } private SearchCriterion(CriterionTie junction, String property, CriterionRestriction operator, Float value) { this(junction, property, operator); floatValue = value; } private SearchCriterion(CriterionTie junction, String property, CriterionRestriction operator, Long value) { this(junction, property, operator); longValue = value; } private SearchCriterion(CriterionTie junction, String property, CriterionRestriction operator, String value) { this(junction, property, operator); stringValue = value; } public CriterionInVO buildCriterionInVO(DemoDataProvider d, DBModule module, int position) { CriterionInVO newCriterion = new CriterionInVO(); newCriterion.setTieId(junction != null ? d.criterionTieDao.searchUniqueTie(junction).getId() : null); CriterionProperty p = CommonUtil.isEmptyString(property) ? null : (new ArrayList<CriterionProperty>(criterionPropertyDao.search(new Search(new SearchParameter[] { new SearchParameter("module", module, SearchParameter.EQUAL_COMPARATOR), new SearchParameter("property", property, SearchParameter.EQUAL_COMPARATOR), })))).iterator().next(); newCriterion.setPropertyId(p != null ? p.getId() : null); newCriterion.setRestrictionId(operator != null ? d.criterionRestrictionDao.searchUniqueRestriction(operator).getId() : null); newCriterion.setPosition((long) position); newCriterion.setBooleanValue(booleanValue); newCriterion.setFloatValue(floatValue); newCriterion.setLongValue(longValue); newCriterion.setStringValue(stringValue); if (p != null && (p.getValueType() == CriterionValueType.DATE || p.getValueType() == CriterionValueType.DATE_HASH)) { newCriterion.setDateValue(dateValue); newCriterion.setTimeValue(null); newCriterion.setTimestampValue(null); } else if (p != null && (p.getValueType() == CriterionValueType.TIME || p.getValueType() == CriterionValueType.TIME_HASH)) { newCriterion.setDateValue(null); newCriterion.setTimeValue(dateValue); newCriterion.setTimestampValue(null); } else if (p != null && (p.getValueType() == CriterionValueType.TIMESTAMP || p.getValueType() == CriterionValueType.TIMESTAMP_HASH)) { newCriterion.setDateValue(null); newCriterion.setTimeValue(null); newCriterion.setTimestampValue(dateValue); } else { newCriterion.setDateValue(null); newCriterion.setTimeValue(null); newCriterion.setTimestampValue(null); } return newCriterion; } } private final class Stroke { private final static String INK_VALUE_CHARSET = "UTF8"; public String color; public String path; public String strokesId; public String value; public boolean valueSet; private Stroke() { color = null; path = null; strokesId = CommonUtil.generateUUID(); value = null; valueSet = false; } public Stroke(String path) { this(); this.color = "#00ff00"; this.path = path; } public Stroke(String path, String value) { this(path); setValue(value); } public Stroke(String color, String path, String value) { this(); this.color = color; this.path = path; setValue(value); } public byte[] getBytes() throws UnsupportedEncodingException { return toString().getBytes(INK_VALUE_CHARSET); } private void setValue(String value) { this.value = value; valueSet = true; } @Override public String toString() { return String.format("[{" + "\"fill\": \"%s\"," + "\"stroke\": \"%s\"," + "\"path\": \"%s\"," + "\"stroke-opacity\": 0.4," + "\"stroke-width\": 2," + "\"stroke-linecap\": \"round\"," + "\"stroke-linejoin\": \"round\"," + "\"transform\": []," + "\"type\": \"path\"," + "\"fill-opacity\": 0.2," + "\"strokes-id\": \"%s\"}]", color, color, path, strokesId); } } private static final int FILE_COUNT_PER_STAFF = 5; private static final int FILE_COUNT_PER_ORGANISATION = 5; private static final int FILE_COUNT_PER_COURSE = 10; private static final int FILE_COUNT_PER_INVENTORY = 10; private static final int FILE_COUNT_PER_PROBAND = 3; private static final int FILE_COUNT_PER_TRIAL = 500; private static final boolean CREATE_FILES = false; @Autowired private DepartmentDao departmentDao; @Autowired private UserDao userDao; @Autowired private UserPermissionProfileDao userPermissionProfileDao; @Autowired private StaffDao staffDao; @Autowired private ToolsService toolsService; @Autowired private StaffService staffService; @Autowired private UserService userService; @Autowired private CourseService courseService; @Autowired private SelectionSetService selectionSetService; @Autowired private InventoryService inventoryService; @Autowired private ProbandService probandService; @Autowired private ProbandDao probandDao; @Autowired private ProbandCategoryDao probandCategoryDao; @Autowired private CourseCategoryDao courseCategoryDao; @Autowired private TrialStatusTypeDao trialStatusTypeDao; @Autowired private SponsoringTypeDao sponsoringTypeDao; @Autowired private TrialTypeDao trialTypeDao; @Autowired private VisitTypeDao visitTypeDao; @Autowired private TrialService trialService; @Autowired private FileService fileService; @Autowired private InputFieldService inputFieldService; @Autowired private SearchService searchService; @Autowired private InputFieldDao inputFieldDao; @Autowired private InputFieldSelectionSetValueDao inputFieldSelectionSetValueDao; @Autowired private TeamMemberRoleDao teamMemberRoleDao; @Autowired private TimelineEventTypeDao timelineEventTypeDao; @Autowired private CourseParticipationStatusTypeDao courseParticipationStatusTypeDao; @Autowired private ProbandListStatusEntryDao probandListStatusEntryDao; @Autowired private CriteriaDao criteriaDao; @Autowired private CriterionTieDao criterionTieDao; @Autowired private CriterionPropertyDao criterionPropertyDao; @Autowired private CriterionRestrictionDao criterionRestrictionDao; private Random random; private String prefix; private int year; private int departmentCount; private int usersPerDepartmentCount; // more users than persons intended private JobOutput jobOutput; private ApplicationContext context; public DemoDataProvider() { random = new Random(); prefix = RandomStringUtils.randomAlphanumeric(4).toLowerCase(); year = Calendar.getInstance().get(Calendar.YEAR); } private void addInkRegions(AuthenticationVO auth, InputFieldOutVO inputField, TreeMap<InputFieldValues, Stroke> inkRegions) throws Exception { auth = (auth == null ? getRandomAuth() : auth); Iterator<Entry<InputFieldValues, Stroke>> it = inkRegions.entrySet().iterator(); while (it.hasNext()) { Entry<InputFieldValues, Stroke> inkRegion = it.next(); Stroke stroke = inkRegion.getValue(); InputFieldSelectionSetValueInVO newSelectionSetValue = new InputFieldSelectionSetValueInVO(); newSelectionSetValue.setFieldId(inputField.getId()); newSelectionSetValue.setName(inkRegion.getKey().toString()); newSelectionSetValue.setPreset(false); newSelectionSetValue.setValue(stroke.valueSet ? stroke.value : inkRegion.getKey().toString()); newSelectionSetValue.setInkRegions(stroke.getBytes()); newSelectionSetValue.setStrokesId(stroke.strokesId); InputFieldSelectionSetValueOutVO out = inputFieldService.addSelectionSetValue(auth, newSelectionSetValue); jobOutput.println("ink region created: " + out.getName()); } } private void addSelectionSetValues(AuthenticationVO auth, InputFieldOutVO inputField, TreeMap<InputFieldValues, Boolean> selectionSetValues) throws Exception { auth = (auth == null ? getRandomAuth() : auth); Iterator<Entry<InputFieldValues, Boolean>> it = selectionSetValues.entrySet().iterator(); while (it.hasNext()) { Entry<InputFieldValues, Boolean> selectionSetValue = it.next(); InputFieldSelectionSetValueInVO newSelectionSetValue = new InputFieldSelectionSetValueInVO(); newSelectionSetValue.setFieldId(inputField.getId()); newSelectionSetValue.setName(selectionSetValue.getKey().toString()); newSelectionSetValue.setPreset(selectionSetValue.getValue()); newSelectionSetValue.setValue(selectionSetValue.getKey().toString()); InputFieldSelectionSetValueOutVO out = inputFieldService.addSelectionSetValue(auth, newSelectionSetValue); jobOutput.println("selection set value created: " + out.getName()); } } private ArrayList<UserPermissionProfile> addUserPermissionProfiles(UserOutVO userVO, ArrayList<PermissionProfile> profiles) throws Exception { User user = userDao.load(userVO.getId()); Timestamp now = new Timestamp(System.currentTimeMillis()); ArrayList<UserPermissionProfile> result = new ArrayList<UserPermissionProfile>(profiles.size()); Iterator<PermissionProfile> profilesIt = profiles.iterator(); while (profilesIt.hasNext()) { PermissionProfile profile = profilesIt.next(); UserPermissionProfile userPermissionProfile = UserPermissionProfile.Factory.newInstance(); userPermissionProfile.setActive(true); userPermissionProfile.setProfile(profile); userPermissionProfile.setUser(user); CoreUtil.modifyVersion(userPermissionProfile, now, null); result.add(userPermissionProfileDao.create(userPermissionProfile)); jobOutput.println("permission profile " + profile.toString() + " added"); } return result; } private UserOutVO assignUser(StaffOutVO staff) throws Exception { Set<User> unassignedUsers = userDao.search(new Search(new SearchParameter[] { new SearchParameter("identity", SearchParameter.NULL_COMPARATOR), new SearchParameter("department.id", getDepartmentIds(), SearchParameter.IN_COMPARATOR) })); User user = getRandomElement(unassignedUsers); UserOutVO userVO = null; if (user != null) { UserInVO modifiedUser = new UserInVO(); modifiedUser.setDepartmentId(user.getDepartment().getId()); modifiedUser.setId(user.getId()); modifiedUser.setIdentityId(staff.getId()); modifiedUser.setName(user.getName()); modifiedUser.setLocale(user.getLocale()); modifiedUser.setTimeZone(user.getTimeZone()); modifiedUser.setDateFormat(user.getDateFormat()); modifiedUser.setDecimalSeparator(user.getDecimalSeparator()); modifiedUser.setTheme(user.getTheme()); modifiedUser.setLocked(user.isLocked()); modifiedUser.setShowTooltips(user.isShowTooltips()); modifiedUser.setDecrypt(user.isDecrypt()); modifiedUser.setDecryptUntrusted(user.isDecryptUntrusted()); modifiedUser.setEnableInventoryModule(true); modifiedUser.setEnableStaffModule(true); modifiedUser.setEnableCourseModule(true); modifiedUser.setEnableTrialModule(true); modifiedUser.setEnableInputFieldModule(true); modifiedUser.setEnableProbandModule(true); modifiedUser.setEnableMassMailModule(true); modifiedUser.setEnableUserModule(true); modifiedUser.setAuthMethod(user.getAuthMethod()); modifiedUser.setVersion(user.getVersion()); userVO = userService.updateUser(getRandomAuth(user.getDepartment().getId()), modifiedUser, null, null, null); jobOutput.println("user " + userVO.getName() + " assigned to " + staff.getName()); } return userVO; } private InputFieldOutVO createCheckBoxField(AuthenticationVO auth, String name, String category, String title, String comment, boolean booleanPreset) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.CHECKBOX); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setBooleanPreset(booleanPreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("check box input field created: " + out.getName()); return out; } private CourseOutVO createCourse(AuthenticationVO auth, int courseNum, int departmentNum, Collection<Long> precedingCourseIds, Collection<Staff> institutions, int maxParticipants) throws Exception { auth = (auth == null ? getRandomAuth() : auth); CourseInVO newCourse = new CourseInVO(); Date stop; VariablePeriod validityPeriod = getRandomElement(new VariablePeriod[] { VariablePeriod.MONTH, VariablePeriod.SIX_MONTHS, VariablePeriod.YEAR }); Long validityPeriodDays = (validityPeriod == VariablePeriod.EXPLICIT ? getRandomElement(new Long[] { 7L, 14L, 21L }) : null); if (precedingCourseIds != null && precedingCourseIds.size() > 0) { stop = null; Iterator<Long> it = precedingCourseIds.iterator(); while (it.hasNext()) { Long precedingCourseId = it.next(); CourseOutVO precedingCourse = courseService.getCourse(auth, precedingCourseId, 1, null, null); if (precedingCourse.isExpires()) { Date precedingExpiration = DateCalc.addInterval(precedingCourse.getStop(), precedingCourse.getValidityPeriod().getPeriod(), precedingCourse.getValidityPeriodDays()); if (stop == null || precedingExpiration.compareTo(stop) < 0) { stop = precedingExpiration; } } } stop = stop == null ? getRandomCourseStop() : DateCalc.subInterval(stop, VariablePeriod.EXPLICIT, new Long(random.nextInt(8))); newCourse.setPrecedingCourseIds(precedingCourseIds); } else { stop = getRandomCourseStop(); } if (getRandomBoolean(50)) { newCourse.setExpires(true); newCourse.setValidityPeriod(validityPeriod); newCourse.setValidityPeriodDays(validityPeriodDays); } else { newCourse.setExpires(false); } Date start; if (getRandomBoolean(50)) { start = null; } else { VariablePeriod courseDurationPeriod = getRandomElement(new VariablePeriod[] { VariablePeriod.EXPLICIT, VariablePeriod.MONTH, VariablePeriod.SIX_MONTHS, VariablePeriod.YEAR }); Long courseDurationPeriodDays = (courseDurationPeriod == VariablePeriod.EXPLICIT ? getRandomElement(new Long[] { 7L, 14L, 21L }) : null); start = DateCalc.subInterval(stop, courseDurationPeriod, courseDurationPeriodDays); } if (getRandomBoolean(50)) { newCourse.setSelfRegistration(false); } else { newCourse.setSelfRegistration(true); newCourse.setMaxNumberOfParticipants(1L + random.nextInt(maxParticipants)); Date participationDeadline; if (getRandomBoolean(50)) { if (start != null) { participationDeadline = DateCalc.subInterval(start, VariablePeriod.EXPLICIT, new Long(random.nextInt(8))); } else { participationDeadline = DateCalc.subInterval(stop, VariablePeriod.EXPLICIT, new Long(random.nextInt(8))); } } else { participationDeadline = null; } newCourse.setParticipationDeadline(participationDeadline); } newCourse.setDepartmentId(getDepartmentId(departmentNum)); Collection<CourseCategory> categories = courseCategoryDao.search(new Search(new SearchParameter[] { new SearchParameter("trialRequired", false, SearchParameter.EQUAL_COMPARATOR) })); newCourse.setCategoryId(getRandomElement(categories).getId()); newCourse.setInstitutionId(getRandomBoolean(50) ? getRandomElement(institutions).getId() : null); newCourse.setName("course_" + (departmentNum + 1) + "_" + (courseNum + 1)); newCourse.setDescription("description for " + newCourse.getName()); newCourse.setStart(start); newCourse.setStop(stop); if (getRandomBoolean(50)) { newCourse.setShowCvPreset(true); newCourse.setCvTitle("Course " + (departmentNum + 1) + "-" + (courseNum + 1)); if (getRandomBoolean(50)) { newCourse.setShowCommentCvPreset(true); newCourse.setCvCommentPreset("CV comment for " + newCourse.getCvTitle()); } else { newCourse.setShowCommentCvPreset(false); } newCourse.setCvSectionPresetId(getRandomElement(selectionSetService.getCvSections(auth, null)).getId()); } else { newCourse.setShowCvPreset(false); } if (getRandomBoolean(50)) { newCourse.setShowTrainingRecordPreset(true); //newCourse.setCvTitle(cvTitle); newCourse.setTrainingRecordSectionPresetId(getRandomElement(selectionSetService.getTrainingRecordSections(auth, null)).getId()); } else { newCourse.setShowTrainingRecordPreset(false); } newCourse.setCertificate(false); CourseOutVO course = courseService.addCourse(auth, newCourse, null, null, null); jobOutput.println("course created: " + course.getName()); ArrayList<Staff> persons = new ArrayList<Staff>(staffDao.search(new Search(new SearchParameter[] { new SearchParameter("person", true, SearchParameter.EQUAL_COMPARATOR) }))); Iterator<Staff> participantStaffIt; if (course.getMaxNumberOfParticipants() != null) { participantStaffIt = getUniqueRandomElements(persons, CommonUtil.safeLongToInt(course.getMaxNumberOfParticipants())).iterator(); } else { participantStaffIt = getUniqueRandomElements(persons, 1 + random.nextInt(maxParticipants)).iterator(); } Collection<CourseParticipationStatusType> initialStates = courseParticipationStatusTypeDao.findInitialStates(true, course.isSelfRegistration()); while (participantStaffIt.hasNext()) { CourseParticipationStatusEntryInVO newCourseParticipationStatusEntry = new CourseParticipationStatusEntryInVO(); newCourseParticipationStatusEntry.setComment(course.getCvCommentPreset()); newCourseParticipationStatusEntry.setCourseId(course.getId()); newCourseParticipationStatusEntry.setCvSectionId(course.getCvSectionPreset() == null ? null : course.getCvSectionPreset().getId()); newCourseParticipationStatusEntry.setShowCommentCv(course.getShowCommentCvPreset()); newCourseParticipationStatusEntry.setShowCv(course.getShowCvPreset()); newCourseParticipationStatusEntry.setTrainingRecordSectionId(course.getTrainingRecordSectionPreset() == null ? null : course.getTrainingRecordSectionPreset().getId()); newCourseParticipationStatusEntry.setShowTrainingRecord(course.isShowTrainingRecordPreset()); newCourseParticipationStatusEntry.setStaffId(participantStaffIt.next().getId()); newCourseParticipationStatusEntry.setStatusId(getRandomElement(initialStates).getId()); CourseParticipationStatusEntryOutVO participation = courseService.addCourseParticipationStatusEntry(auth, newCourseParticipationStatusEntry); jobOutput.println("participant " + participation.getStatus().getName() + ": " + participation.getStaff().getName()); } return course; } public void createCourses(int courseCountPerDepartment) throws Exception { int newestCourseCount = (int) (0.5 * courseCountPerDepartment); for (int departmentNum = 0; departmentNum < departmentCount; departmentNum++) { Collection<Staff> institutions = staffDao.search(new Search(new SearchParameter[] { new SearchParameter("department.id", getDepartmentId(departmentNum), SearchParameter.EQUAL_COMPARATOR), new SearchParameter("person", false, SearchParameter.EQUAL_COMPARATOR) })); Collection<Staff> persons = staffDao.search(new Search(new SearchParameter[] { new SearchParameter("department.id", getDepartmentId(departmentNum), SearchParameter.EQUAL_COMPARATOR), new SearchParameter("person", true, SearchParameter.EQUAL_COMPARATOR) })); ArrayList<Long> createdIds = new ArrayList<Long>(); for (int i = 0; i < newestCourseCount; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); CourseOutVO course = createCourse(auth, i, departmentNum, null, institutions, persons.size()); createdIds.add(course.getId()); createFiles(auth, FileModule.COURSE_DOCUMENT, course.getId(), FILE_COUNT_PER_COURSE); } for (int i = 0; i < (courseCountPerDepartment - newestCourseCount); i++) { AuthenticationVO auth = getRandomAuth(departmentNum); CourseOutVO course = createCourse(auth, newestCourseCount + i, departmentNum, getUniqueRandomElements(createdIds, random.nextInt(5)), institutions, persons.size()); createdIds.add(course.getId()); createFiles(auth, FileModule.COURSE_DOCUMENT, course.getId(), FILE_COUNT_PER_COURSE); } } } private CriteriaOutVO createCriteria(AuthenticationVO auth, DBModule module, List<SearchCriterion> criterions, String label, String comment, boolean loadByDefault) throws Exception { auth = (auth == null ? getRandomAuth() : auth); CriteriaInVO newCriteria = new CriteriaInVO(); newCriteria.setCategory("test_" + prefix); newCriteria.setComment(comment); newCriteria.setLabel(label); newCriteria.setLoadByDefault(loadByDefault); newCriteria.setModule(module); HashSet<CriterionInVO> newCriterions = new HashSet<CriterionInVO>(criterions.size()); Iterator<SearchCriterion> it = criterions.iterator(); int position = 1; while (it.hasNext()) { SearchCriterion criterion = it.next(); newCriterions.add(criterion.buildCriterionInVO(this, module, position)); position++; } CriteriaOutVO out = searchService.addCriteria(auth, newCriteria, newCriterions); jobOutput.println("criteria created: " + out.getLabel()); return out; } public ArrayList<CriteriaOutVO> createCriterias() throws Throwable { AuthenticationVO auth = getRandomAuth(); ArrayList<CriteriaOutVO> criterias = new ArrayList<CriteriaOutVO>(); for (int i = 0; i < SearchCriteria.values().length; i++) { criterias.add(getCriteria(auth, SearchCriteria.values()[i])); } return criterias; } private InputFieldOutVO createDateField(AuthenticationVO auth, String name, String category, String title, String comment, Date datePreset, Date minDate, Date maxDate, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.DATE); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setMinDate(minDate); newInputField.setMaxDate(maxDate); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setDatePreset(datePreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("date input field created: " + out.getName()); return out; } private Long createDemoEcrfIncrement() { return null; } private ArrayList<ECRFFieldOutVO> createDemoEcrfMedicalHistory(AuthenticationVO auth, TrialOutVO trial, Long probandGroupId, int position, Long visitId) throws Throwable { ECRFOutVO ecrf = createEcrf(auth, trial, "medical history", "eCRF to capture ICD-10 coded medical history", probandGroupId, position, visitId, true, false, true, 0.0f, null); ArrayList<ECRFFieldOutVO> ecrfFields = new ArrayList<ECRFFieldOutVO>(); ecrfFields.add(createEcrfField(auth, InputFields.DIAGNOSIS_COUNT, ecrf, "summary", 1, false, false, false, true, true, null, null, "count", "function(alphaid) {\n" + " return alphaid.length - 1;\n" + "}", "function() {\n" + " return sprintf('medical history: %d entries',$value);\n" + "}")); ecrfFields.add(createEcrfField(auth, InputFields.DIAGNOSIS_START, ecrf, "medical history", 1, true, true, false, true, true, null, "date when disease started, if known/applicable", null, null, null)); ecrfFields.add( createEcrfField(auth, InputFields.DIAGNOSIS_END, ecrf, "medical history", 2, true, true, false, true, true, null, "date when disease ended, if known/applicable", null, null, null)); ecrfFields.add(createEcrfField(auth, InputFields.ALPHA_ID, ecrf, "medical history", 3, true, false, false, true, true, null, "disease name", "alphaid", null, "function() {\n" + " if ($enteredValue != $oldValue) {\n" + " var output = 'Matching AlphaID synonyms: ';\n" + " var request = RestApi.createRequest('GET', 'tools/complete/alphaidtext');\n" + " request.data = 'textInfix=' + $enteredValue;\n" + " request.success = function(data, code, jqXHR) {\n" + " if (data.length > 0) {\n" + " output += '<select onchange=\"FieldCalculation.setVariable([\\'alphaid\\',' + $index + '],';\n" + " output += 'this.options[this.selectedIndex].text,true);\">';\n" + " for (var i = 0; i < data.length; i++) {\n" + " output += '<option>' + data[i] + '</option>';\n" + " }\n" + " output += '</select>';\n" + " } else {\n" + " output += 'no hits';\n" + " }\n" + " setOutput(['alphaid',$index],output);\n" + " };\n" + " RestApi.executeRequest(request);\n" + " return output;\n" + " } else {\n" + " return $output;\n" + " }\n" + "}")); return ecrfFields; } private ArrayList<ECRFFieldOutVO> createDemoEcrfSum(AuthenticationVO auth, TrialOutVO trial, Long probandGroupId, int position, Long visitId) throws Throwable { ECRFOutVO ecrf = createEcrf(auth, trial, "some eCRF", "demo eCRF to show field calculations with series sections", probandGroupId, position, visitId, true, false, true, 0.0f, null); ArrayList<ECRFFieldOutVO> ecrfFields = new ArrayList<ECRFFieldOutVO>(); ecrfFields.add(createEcrfField(auth, InputFields.STRING_SINGLELINE, ecrf, "series #1", 1, true, false, false, true, true, null, "some name", null, null, null)); ecrfFields.add(createEcrfField(auth, InputFields.INTEGER, ecrf, "series #1", 2, true, false, false, true, true, null, "some repeatable value 1", "value1", null, null)); ecrfFields.add(createEcrfField(auth, InputFields.INTEGER, ecrf, "series #1", 3, true, false, false, true, true, null, "some repeatable value 2", "value2", null, null)); ecrfFields.add(createEcrfField(auth, InputFields.STRING_MULTILINE, ecrf, "series #1", 4, true, false, false, true, true, null, "some description", null, null, null)); ecrfFields.add(createEcrfField(auth, InputFields.FLOAT, ecrf, "series #1", 5, true, false, false, true, true, null, "some repeatable value 3", "value3", "function(value1, value2) {\n" + " return value1 + value2;\n" + "}", "function(value3) {\n" + " return sprintf(\"value3 = value1 + value2 = %.3f\",value3);\n" + "}")); ecrfFields.add(createEcrfField(auth, InputFields.STRING_SINGLELINE, ecrf, "series #2", 1, true, false, false, true, true, null, "some name", null, null, null)); ecrfFields.add(createEcrfField(auth, InputFields.INTEGER, ecrf, "series #2", 2, true, false, false, true, true, null, "some repeatable value 4", "value4", null, null)); ecrfFields.add(createEcrfField(auth, InputFields.INTEGER, ecrf, "series #2", 3, true, false, false, true, true, null, "some repeatable value 5", "value5", null, null)); ecrfFields.add(createEcrfField(auth, InputFields.STRING_MULTILINE, ecrf, "series #2", 4, true, false, false, true, true, null, "some description", null, null, null)); ecrfFields.add(createEcrfField(auth, InputFields.FLOAT, ecrf, "series #2", 5, true, false, false, true, true, null, "some repeatable value 6", "value6", "function(value4, value5) {\n" + " return value4 + value5;\n" + "}", "function(value6) {\n" + " return sprintf(\"value6 = value4 + value5 = %.3f\",value6);\n" + "}")); ecrfFields.add(createEcrfField(auth, InputFields.STRING_SINGLELINE, ecrf, "totals section", 1, false, false, false, true, true, null, "some name", null, null, null)); ecrfFields.add(createEcrfField(auth, InputFields.INTEGER, ecrf, "totals section", 2, false, false, false, true, true, null, "some total value 1", "total1", "function(value1, value4) {\n" + " var sum = 0;\n" + " var i;\n" + " for (i = 0; i < value1.length; i++) {\n" + " sum += value1[i];\n" + " }\n" + " for (i = 0; i < value4.length; i++) {\n" + " sum += value4[i];\n" + " }\n" + " return sum;\n" + "}", "function(total1) {\n" + " return sprintf(\"total1 = sum(value1) + sum(value4) = %.3f\",total1);\n" + "}")); ecrfFields.add(createEcrfField(auth, InputFields.INTEGER, ecrf, "totals section", 3, false, false, false, true, true, null, "some total value 2", "total2", "function(value2, value5) {\n" + " var sum = 0;\n" + " var i;\n" + " for (i = 0; i < value2.length; i++) {\n" + " sum += value2[i];\n" + " }\n" + " for (i = 0; i < value5.length; i++) {\n" + " sum += value5[i];\n" + " }\n" + " return sum;\n" + "}", "function(total2) {\n" + " return sprintf(\"total2 = sum(value2) + sum(value5) = %.3f\",total2);\n" + "}")); ecrfFields.add(createEcrfField(auth, InputFields.STRING_MULTILINE, ecrf, "totals section", 4, false, false, false, true, true, null, "some description", null, null, null)); ecrfFields.add(createEcrfField(auth, InputFields.FLOAT, ecrf, "totals section", 5, false, false, false, true, true, null, "some total value 3", "total3", "function(total1, total2) {\n" + " return total1 + total2;\n" + "}", "function(total3,value3,value6) {\n" + " var sum = 0;\n" + " var i;\n" + " for (i = 0; i < value3.length; i++) {\n" + " sum += value3[i];\n" + " }\n" + " for (i = 0; i < value6.length; i++) {\n" + " sum += value6[i];\n" + " }\n" + " return sprintf(\"total3 = total1 + total2 = %.3f = sum(value3) + sum(value6) = %.3f\",total3,sum);\n" + "}")); return ecrfFields; } private DepartmentVO createDepartment(String nameL10nKey, boolean visible, String plainDepartmentPassword) throws Exception { Department department = Department.Factory.newInstance(); department.setNameL10nKey(nameL10nKey); department.setVisible(visible); CryptoUtil.encryptDepartmentKey(department, CryptoUtil.createRandomKey().getEncoded(), plainDepartmentPassword); DepartmentVO out = departmentDao.toDepartmentVO(departmentDao.create(department)); jobOutput.println("department created: " + out.getName()); return out; } public void createDepartmentsAndUsers(int departmentCount, int usersPerDepartmentCount) throws Exception { this.usersPerDepartmentCount = usersPerDepartmentCount; for (int i = 0; i < departmentCount; i++) { DepartmentVO department = createDepartment(getDepartmentName(i), true, getDepartmentPassword(i)); this.departmentCount++; for (int j = 0; j < usersPerDepartmentCount; j++) { createUser(getUsername(i, j), getUserPassword(i, j), department.getId(), getDepartmentPassword(i)); } } } private Collection<DutyRosterTurnOutVO> createDuty(AuthenticationVO auth, ArrayList<Staff> staff, TrialOutVO trial, Date start, Date stop, String title) throws Exception { auth = (auth == null ? getRandomAuth() : auth); Collection<VisitScheduleItemOutVO> visitScheduleItems = trialService.getVisitScheduleItemInterval(auth, trial.getId(), null, null, null, start, stop, null, false); DutyRosterTurnInVO newDutyRosterTurn = new DutyRosterTurnInVO(); newDutyRosterTurn.setSelfAllocatable(staff.size() > 0); newDutyRosterTurn.setStart(start); newDutyRosterTurn.setStop(stop); newDutyRosterTurn.setTrialId(trial.getId()); ArrayList<DutyRosterTurnOutVO> out = new ArrayList<DutyRosterTurnOutVO>(); if (title == null && visitScheduleItems.size() > 0) { Iterator<Staff> staffIt = getUniqueRandomElements(staff, visitScheduleItems.size()).iterator(); Iterator<VisitScheduleItemOutVO> visitScheduleItemsIt = visitScheduleItems.iterator(); int dutyCount = 0; while (staffIt.hasNext() && visitScheduleItemsIt.hasNext()) { VisitScheduleItemOutVO visitScheduleItem = visitScheduleItemsIt.next(); newDutyRosterTurn.setStaffId(staffIt.next().getId()); newDutyRosterTurn.setTitle(null); newDutyRosterTurn.setComment(null); newDutyRosterTurn.setVisitScheduleItemId(visitScheduleItem.getId()); try { out.add(staffService.addDutyRosterTurn(auth, newDutyRosterTurn)); dutyCount++; } catch (ServiceException e) { jobOutput.println(e.getMessage()); } } jobOutput.println(dutyCount + " duty roster turns for " + visitScheduleItems.size() + " visit schedule items created"); return out; } else { newDutyRosterTurn.setStaffId(staff.size() == 0 ? null : getRandomElement(staff).getId()); newDutyRosterTurn.setTitle(title); newDutyRosterTurn.setComment(null); newDutyRosterTurn.setVisitScheduleItemId(visitScheduleItems.size() > 0 ? visitScheduleItems.iterator().next().getId() : null); try { out.add(staffService.addDutyRosterTurn(auth, newDutyRosterTurn)); jobOutput.println("duty roster turn created: " + title); } catch (ServiceException e) { jobOutput.println(e.getMessage()); } } return out; } private ECRFOutVO createEcrf(AuthenticationVO auth, TrialOutVO trial, String name, String title, Long probandGroupId, int position, Long visitId, boolean active, boolean disabled, boolean enableBrowserFieldCalculation, float charge, String description) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); ECRFInVO newEcrf = new ECRFInVO(); newEcrf.setName(name); newEcrf.setTitle(title); newEcrf.setPosition(new Long(position)); newEcrf.setTrialId(trial.getId()); newEcrf.setActive(active); newEcrf.setDescription(description); newEcrf.setDisabled(disabled); newEcrf.setEnableBrowserFieldCalculation(enableBrowserFieldCalculation); newEcrf.setCharge(charge); newEcrf.setGroupId(probandGroupId); newEcrf.setVisitId(visitId); ECRFOutVO out = trialService.addEcrf(auth, newEcrf); jobOutput.println("eCRF created: " + out.getUniqueName()); return out; } private ECRFFieldOutVO createEcrfField(AuthenticationVO auth, InputFields inputField, ECRFOutVO ecrf, String section, int position, boolean series, boolean optional, boolean disabled, boolean auditTrail, boolean reasonForChangeRequired, String title, String comment, String jsVariableName, String jsValueExpression, String jsOutputExpression) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); ECRFFieldInVO newEcrfField = new ECRFFieldInVO(); newEcrfField.setAuditTrail(auditTrail); newEcrfField.setComment(comment); newEcrfField.setTitle(title); newEcrfField.setDisabled(disabled); newEcrfField.setEcrfId(ecrf.getId()); newEcrfField.setFieldId(getInputField(auth, inputField).getId()); newEcrfField.setOptional(optional); newEcrfField.setPosition(new Long(position)); newEcrfField.setReasonForChangeRequired(reasonForChangeRequired); newEcrfField.setNotify(false); newEcrfField.setSection(section); newEcrfField.setSeries(series); newEcrfField.setTrialId(ecrf.getTrial().getId()); newEcrfField.setJsVariableName(jsVariableName); newEcrfField.setJsValueExpression(jsValueExpression); newEcrfField.setJsOutputExpression(jsOutputExpression); ECRFFieldOutVO out = trialService.addEcrfField(auth, newEcrfField); jobOutput.println("eCRF field created: " + out.getUniqueName()); return out; } private FileOutVO createFile(AuthenticationVO auth, FileModule module, Long id, ArrayList<String> folders) throws Exception { auth = (auth == null ? getRandomAuth() : auth); FileInVO newFile = new FileInVO(); newFile.setActive(getRandomBoolean(50)); newFile.setPublicFile(true); switch (module) { case INVENTORY_DOCUMENT: newFile.setInventoryId(id); break; case STAFF_DOCUMENT: newFile.setStaffId(id); break; case COURSE_DOCUMENT: newFile.setCourseId(id); break; case TRIAL_DOCUMENT: newFile.setTrialId(id); break; case PROBAND_DOCUMENT: newFile.setProbandId(id); break; case MASS_MAIL_DOCUMENT: newFile.setMassMailId(id); break; default: } newFile.setModule(module); if (folders.size() == 0) { folders.add(CommonUtil.LOGICAL_PATH_SEPARATOR); folders.addAll(fileService.getFileFolders(auth, module, id, CommonUtil.LOGICAL_PATH_SEPARATOR, false, null, null, null)); } StringBuilder logicalPath = new StringBuilder(getRandomElement(folders)); if (getRandomBoolean(50)) { logicalPath.append(CommonUtil.generateUUID()); logicalPath.append(CommonUtil.LOGICAL_PATH_SEPARATOR); folders.add(logicalPath.toString()); } newFile.setLogicalPath(logicalPath.toString()); PDFImprinter blankPDF = new PDFImprinter(); PDFStream pdfStream = new PDFStream(); blankPDF.setOutput(pdfStream); blankPDF.render(); FileStreamInVO newFileStream = new FileStreamInVO(); StringBuilder fileName = new StringBuilder(CommonUtil.generateUUID()); fileName.append("."); fileName.append(CoreUtil.PDF_FILENAME_EXTENSION); newFileStream.setFileName(fileName.toString()); newFileStream.setMimeType(CoreUtil.PDF_MIMETYPE_STRING); newFileStream.setSize((long) pdfStream.getSize()); newFileStream.setStream(pdfStream.getInputStream()); newFile.setComment("test file"); newFile.setTitle(fileName.toString()); return fileService.addFile(auth, newFile, newFileStream); } private void createFiles(AuthenticationVO auth, FileModule module, Long id, int fileCount) throws Exception { if (CREATE_FILES) { auth = (auth == null ? getRandomAuth() : auth); ArrayList<String> folders = new ArrayList<String>(); for (int i = 0; i < fileCount; i++) { createFile(auth, module, id, folders); } jobOutput.println(fileCount + " files created for " + module + " enitity " + id); } } private InputFieldOutVO createFloatField(AuthenticationVO auth, String name, String category, String title, String comment, Float floatPreset, Float lowerLimit, Float upperLimit, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.FLOAT); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setFloatLowerLimit(lowerLimit); newInputField.setFloatUpperLimit(upperLimit); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setFloatPreset(floatPreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("float input field created: " + out.getName()); return out; } public TrialOutVO createFormScriptingTrial() throws Throwable { int departmentNum = 0; AuthenticationVO auth = getRandomAuth(departmentNum); TrialInVO newTrial = new TrialInVO(); newTrial.setStatusId(trialStatusTypeDao.searchUniqueNameL10nKey("migration_started").getId()); newTrial.setDepartmentId(getDepartmentId(departmentNum)); newTrial.setName("demo:form-scripting"); newTrial.setTitle("Inquiry form showing various form field calculation examples."); newTrial.setDescription(""); newTrial.setSignupProbandList(false); newTrial.setSignupInquiries(false); newTrial.setSignupRandomize(false); newTrial.setSignupDescription(""); newTrial.setExclusiveProbands(false); newTrial.setProbandAliasFormat(""); newTrial.setDutySelfAllocationLocked(false); newTrial.setTypeId(trialTypeDao.searchUniqueNameL10nKey("na").getId()); newTrial.setSponsoringId(sponsoringTypeDao.searchUniqueNameL10nKey("na").getId()); newTrial.setSurveyStatusId(getRandomElement(selectionSetService.getSurveyStatusTypes(auth, null)).getId()); TrialOutVO trial = trialService.addTrial(auth, newTrial, null); jobOutput.println("trial created: " + trial.getName()); ArrayList<InquiryOutVO> inquiries = new ArrayList<InquiryOutVO>(); inquiries.add(createInquiry(auth, InputFields.BODY_HEIGHT, trial, "01 - BMI", 1, true, true, false, false, false, false, null, null, "size", null, null)); inquiries.add(createInquiry(auth, InputFields.BODY_WEIGHT, trial, "01 - BMI", 2, true, true, false, false, false, false, null, null, "weight", null, null)); inquiries.add(createInquiry(auth, InputFields.BODY_MASS_INDEX, trial, "01 - BMI", 3, true, true, false, false, false, false, null, null, "bmi", "function(weight,size) {\n" + " return weight / (size * size / 10000.0);\n" + "}", "function(bmi) {\n" + " return sprintf(\"BMI entered: %.6f<br>\" +\n" + " \"BMI calculated: %.6f\",\n" + " $enteredValue + 0.0,\n" + " bmi);\n" + "}")); inquiries.add(createInquiry(auth, InputFields.OBESITY, trial, "01 - BMI", 4, true, true, false, false, false, false, null, null, "obesity", "function(bmi) {\n" + " var selection;\n" + " if (bmi < 18.5) {\n" + " selection = \"shortweight\";\n" + " } else if (bmi < 25) {\n" + " selection = \"normal weight\";\n" + " } else if (bmi < 30) {\n" + " selection = \"overweight\"; \n" + " } else if (bmi < 35) {\n" + " selection = \"adiposity degree I\";\n" + " } else if (bmi < 40) { \n" + " selection = \"adiposity degree II\";\n" + " } else {\n" + " selection = \"adiposity degree III\";\n" + " }\n" + " return findSelectionSetValueIds(function(option){\n" + " return option.name == selection;});\n" + "}", "function(obesity) {\n" + " return \"entered: \" +\n" + " printSelectionSetValues($enteredValue) + \"<br>\" +\n" + " \"calculated: <em>\" +\n" + " printSelectionSetValues(obesity) + \"</em>\";\n" + "}")); inquiries.add(createInquiry(auth, InputFields.ETHNICITY, trial, "02 - eGFR", 1, true, true, false, false, false, false, null, null, "ethnicity", "", "function() {\n" + " return sprintf(\"<a href=\\\"http://www.fda.gov/RegulatoryInformation/Guidances/ucm126340.htm\\\" target=\\\"new\\\">FDA Information</a>\");\n" + "}")); inquiries.add(createInquiry(auth, InputFields.SERUM_CREATININ_CONCENTRATION, trial, "02 - eGFR", 2, true, true, false, false, false, false, null, null, "s_cr", "", "")); inquiries.add(createInquiry(auth, InputFields.EGFR, trial, "02 - eGFR", 3, true, true, false, false, false, false, null, null, "egfr", "function(s_cr, ethnicity) { // s_cr: serum creatinin concentration (decimal), skin_color (single selection)\n" + " var result = 175.0 * Math.pow(s_cr, -1.154) * Math.pow($proband.age, -0.203);\n" + " if (getInputFieldSelectionSetValue(\'ethnicity\', ethnicity[0]).value == \'Black\') {\n" + " result *= 1.210;\n" + " }\n" + " if ($proband.gender.sex == \'FEMALE\') {\n" + " result *= 0.742;\n" + " }\n" + " return result;\n" + "}", "function(egfr) {\n" + " return sprintf(\"eGFR entered: %.6f<br>\" + \n" + " \"eGFR calculated: %.6f\",\n" + " $enteredValue + 0.0,\n" + " egfr);\n" + "}")); inquiries.add(createInquiry(auth, InputFields.HBA1C_PERCENT, trial, "03 - HbA1C", 1, true, true, false, false, false, false, null, null, "hba1c_percent", "//function(hba1c_mmol_per_mol) {\n" + "// return hba1c_mmol_per_mol * 0.0915 + 2.15;\n" + "//}", "function() {\n" + " return sprintf(\"HbA1c (%%): %.1f<br/>\" +\n" + " \"HbA1c (mmol/mol): %.2f\",\n" + " $enteredValue + 0.0,\n" + " ($enteredValue - 2.15) * 10.929);\n" + "}")); inquiries.add(createInquiry(auth, InputFields.HBA1C_MMOLPERMOL, trial, "03 - HbA1C", 2, true, true, false, false, false, false, null, null, "hba1c_mmol_per_mol", "function(hba1c_percent) {\n" + " return (hba1c_percent - 2.15) * 10.929;\n" + "}", "//function() {\n" + "// return sprintf(\"HbA1c (mmol/mol): %.2f<br/>\" +\n" + "// \"HbA1c (%%): %.1f\",\n" + "// $enteredValue + 0.0,\n" + "// $enteredValue * 0.0915 + 2.15);\n" + "//}\n" + "function(hba1c_mmol_per_mol) {\n" + " return sprintf(\"HbA1c entered (mmol/mol): %.6f<br/>\" +\n" + " \"HbA1c calculated (mmol/mol): %.6f\",\n" + " $enteredValue + 0.0,\n" + " hba1c_mmol_per_mol);\n" + "}")); inquiries.add(createInquiry(auth, InputFields.MANNEQUIN, trial, "04 - DAS28", 1, true, true, false, false, false, false, null, "tender joints", "tender", null, null)); inquiries.add(createInquiry(auth, InputFields.MANNEQUIN, trial, "04 - DAS28", 2, true, true, false, false, false, false, null, "swollen joints", "swollen", null, null)); inquiries.add(createInquiry(auth, InputFields.ESR, trial, "04 - DAS28", 3, true, true, false, false, false, false, null, null, "esr", null, null)); inquiries.add(createInquiry(auth, InputFields.VAS, trial, "04 - DAS28", 4, true, true, false, false, false, false, null, "The patient's general health condition (subjective)", "vas", null, null)); inquiries.add(createInquiry(auth, InputFields.DAS28, trial, "04 - DAS28", 5, true, true, false, false, false, false, null, null, "das28", "function (tender, swollen, esr, vas) { //das (28 joints) computation:\n" + " return 0.56 * Math.sqrt(tender.ids.length) + //tender joint count (0-28)\n" + " 0.28 * Math.sqrt(swollen.ids.length) + //swollen joint count (0-28)\n" + " 0.7 * Math.log(esr) + //erythrocyte sedimentation rate reading (5-30 mm/h)\n" + " 0.014 * getInputFieldSelectionSetValue(\"vas\",vas.ids[0]).value; //the proband\'s\n" + " //subjective assessment of recent disease activity (visual analog scale, 0-100 mm)\n" + "}", "function(das28) {\n" + " return sprintf(\"entered: %.2f<br/>\" +\n" + " \"calculated: %.2f\", $enteredValue + 0.0,das28 + 0.0);\n" + "}")); inquiries.add(createInquiry(auth, InputFields.DISTANCE, trial, "05 - Google Maps", 1, true, true, false, false, false, false, null, null, "distance", "function() {\n" + " if ($enteredValue) {\n" + " return $enteredValue; \n" + " }\n" + " if ($probandAddresses) {\n" + " for (var i in $probandAddresses) {\n" + " if ($probandAddresses[i].wireTransfer) {\n" + " LocationDistance.calcRouteDistance(null,$probandAddresses[i].civicName,function(d,j){\n" + " setVariable(\"distance\",Math.round(d/1000.0));\n" + " },i);\n" + " return;\n" + " }\n" + " }\n" + " }\n" + " return;\n" + "}", "function(distance){\n" + " if ($enteredValue) {\n" + " return \"\"; \n" + " }\n" + " if ($probandAddresses) {\n" + " for (var i in $probandAddresses) {\n" + " if ($probandAddresses[i].wireTransfer) {\n" + " if (distance != null) {\n" + " return sprintf(\"Distance from %s to %s: %d km\",LocationDistance.currentSubLocality,$probandAddresses[i].name,distance);\n" + " } else {\n" + " return \"querying Google Maps ...\"; \n" + " }\n" + " }\n" + " }\n" + " }\n" + " return \"No subject address.\"; \n" + "}")); inquiries.add(createInquiry(auth, InputFields.ALPHA_ID, trial, "06 - Rest API", 1, true, true, false, false, false, false, null, "(Medical Coding example ...)", "alphaid", null, "function() {\n" + " if ($enteredValue != $oldValue) {\n" + " var output = 'Matching AlphaID synonyms: ';\n" + " var request = RestApi.createRequest('GET', 'tools/complete/alphaidtext');\n" + " request.data = 'textInfix=' + $enteredValue;\n" + " request.success = function(data, code, jqXHR) {\n" + " if (data.length > 0) {\n" + " output += '<select onchange=\"FieldCalculation.setVariable(\\'alphaid\\',';\n" + " output += 'this.options[this.selectedIndex].text,true);\">';\n" + " for (var i = 0; i < data.length; i++) {\n" + " output += '<option>' + data[i] + '</option>';\n" + " }\n" + " output += '</select>';\n" + " } else {\n" + " output += 'no hits';\n" + " }\n" + " setOutput('alphaid',output);\n" + " };\n" + " RestApi.executeRequest(request);\n" + " return output;\n" + " } else {\n" + " return $output;\n" + " }\n" + "}")); createDemoEcrfSum(auth, trial, null, 1, null); createDemoEcrfMedicalHistory(auth, trial, null, 2, null); return trial; } public TrialOutVO createGroupCoinRandomizationTrial(int probandGroupCount, int probandCount) throws Throwable { int departmentNum = 0; AuthenticationVO auth = getRandomAuth(departmentNum); TrialInVO newTrial = new TrialInVO(); newTrial.setStatusId(trialStatusTypeDao.searchUniqueNameL10nKey("migration_started").getId()); newTrial.setDepartmentId(getDepartmentId(departmentNum)); newTrial.setName("demo:group coin randomization"); newTrial.setTitle("Group coin randomization testcase."); newTrial.setDescription(""); newTrial.setRandomization(RandomizationMode.GROUP_COIN); newTrial.setSignupProbandList(false); newTrial.setSignupInquiries(false); newTrial.setSignupRandomize(false); newTrial.setSignupDescription(""); newTrial.setExclusiveProbands(false); newTrial.setProbandAliasFormat(""); newTrial.setDutySelfAllocationLocked(false); newTrial.setTypeId(trialTypeDao.searchUniqueNameL10nKey("na").getId()); newTrial.setSponsoringId(sponsoringTypeDao.searchUniqueNameL10nKey("na").getId()); newTrial.setSurveyStatusId(getRandomElement(selectionSetService.getSurveyStatusTypes(auth, null)).getId()); TrialOutVO trial = trialService.addTrial(auth, newTrial, null); jobOutput.println("trial created: " + trial.getName()); ProbandGroupInVO newProbandGroup = new ProbandGroupInVO(); newProbandGroup.setTitle("Screeninggruppe"); newProbandGroup.setToken("SG"); newProbandGroup.setTrialId(trial.getId()); newProbandGroup.setRandomize(false); ProbandGroupOutVO screeningGroup = trialService.addProbandGroup(auth, newProbandGroup); jobOutput.println("proband group created: " + screeningGroup.getTitle()); LinkedHashMap<Long, ProbandGroupOutVO> probandGroupMap = new LinkedHashMap<Long, ProbandGroupOutVO>(); for (int i = 0; i < probandGroupCount; i++) { newProbandGroup = new ProbandGroupInVO(); newProbandGroup.setTitle("Gruppe " + (i + 1)); newProbandGroup.setToken("G" + (i + 1)); newProbandGroup.setTrialId(trial.getId()); newProbandGroup.setRandomize(true); ProbandGroupOutVO probandGroup = trialService.addProbandGroup(auth, newProbandGroup); jobOutput.println("proband group created: " + probandGroup.getTitle()); probandGroupMap.put(probandGroup.getId(), probandGroup); } ProbandCategory probandCategory = probandCategoryDao.search(new Search(new SearchParameter[] { new SearchParameter("nameL10nKey", "test", SearchParameter.EQUAL_COMPARATOR) })).iterator().next(); HashMap<Long, Long> groupSizes = new HashMap<Long, Long>(); for (int i = 0; i < probandCount; i++) { ProbandInVO newProband = new ProbandInVO(); newProband.setDepartmentId(getDepartmentId(departmentNum)); newProband.setCategoryId(probandCategory.getId()); newProband.setPerson(true); newProband.setBlinded(true); newProband.setAlias(MessageFormat.format("{0} {1}", trial.getName(), i + 1)); newProband.setGender(getRandomBoolean(50) ? Sex.MALE : Sex.FEMALE); newProband.setDateOfBirth(getRandomDateOfBirth()); ProbandOutVO proband = probandService.addProband(auth, newProband, null, null, null); jobOutput.println("proband created: " + proband.getName()); ProbandListEntryInVO newProbandListEntry = new ProbandListEntryInVO(); newProbandListEntry.setPosition(i + 1l); newProbandListEntry.setTrialId(trial.getId()); newProbandListEntry.setProbandId(proband.getId()); ProbandListEntryOutVO probandListEntry = trialService.addProbandListEntry(auth, false, false, true, newProbandListEntry); jobOutput.println("proband list entry created - trial: " + probandListEntry.getTrial().getName() + " position: " + probandListEntry.getPosition() + " proband: " + probandListEntry.getProband().getName()); if (groupSizes.containsKey(probandListEntry.getGroup().getId())) { groupSizes.put(probandListEntry.getGroup().getId(), groupSizes.get(probandListEntry.getGroup().getId()) + 1l); } else { groupSizes.put(probandListEntry.getGroup().getId(), 1l); } } Iterator<Long> probandGroupIdsIt = probandGroupMap.keySet().iterator(); while (probandGroupIdsIt.hasNext()) { Long probandGroupId = probandGroupIdsIt.next(); jobOutput.println(probandGroupMap.get(probandGroupId).getToken() + ": " + groupSizes.get(probandGroupId) + " probands"); } return trial; } public ArrayList<InputFieldOutVO> createInputFields() throws Throwable { AuthenticationVO auth = getRandomAuth(); ArrayList<InputFieldOutVO> inputFields = new ArrayList<InputFieldOutVO>(); for (int i = 0; i < InputFields.values().length; i++) { inputFields.add(getInputField(auth, InputFields.values()[i])); } return inputFields; } private InquiryOutVO createInquiry(AuthenticationVO auth, InputFields inputField, TrialOutVO trial, String category, int position, boolean active, boolean activeSignup, boolean optional, boolean disabled, boolean excelValue, boolean excelDate, String title, String comment, String jsVariableName, String jsValueExpression, String jsOutputExpression) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); InquiryInVO newInquiry = new InquiryInVO(); newInquiry.setCategory(category); newInquiry.setActive(active); newInquiry.setActiveSignup(activeSignup); newInquiry.setOptional(optional); newInquiry.setDisabled(disabled); newInquiry.setExcelValue(excelValue); newInquiry.setExcelDate(excelDate); newInquiry.setFieldId(getInputField(auth, inputField).getId()); newInquiry.setTrialId(trial.getId()); newInquiry.setPosition(new Long(position)); newInquiry.setComment(comment); newInquiry.setTitle(title); newInquiry.setJsVariableName(jsVariableName); newInquiry.setJsValueExpression(jsValueExpression); newInquiry.setJsOutputExpression(jsOutputExpression); InquiryOutVO out = trialService.addInquiry(auth, newInquiry); jobOutput.println("inquiry created: " + out.getUniqueName()); return out; } private InputFieldOutVO createIntegerField(AuthenticationVO auth, String name, String category, String title, String comment, Long longPreset, Long lowerLimit, Long upperLimit, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.INTEGER); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setLongLowerLimit(lowerLimit); newInputField.setLongUpperLimit(upperLimit); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setLongPreset(longPreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("integer input field created: " + out.getName()); return out; } private InventoryOutVO createInventory(AuthenticationVO auth, int inventoryNum, int departmentNum, Long parentId, Collection<Staff> owners) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InventoryInVO newInventory = new InventoryInVO(); newInventory.setBookable(getRandomBoolean(50)); if (newInventory.getBookable()) { newInventory.setMaxOverlappingBookings(1l); } else { newInventory.setMaxOverlappingBookings(0l); } newInventory.setOwnerId(getRandomBoolean(50) ? getRandomElement(owners).getId() : null); newInventory.setParentId(parentId); newInventory.setDepartmentId(getDepartmentId(departmentNum)); newInventory.setCategoryId(getRandomElement(selectionSetService.getInventoryCategories(auth, null)).getId()); newInventory.setName("inventory_" + (departmentNum + 1) + "_" + (inventoryNum + 1)); newInventory.setPieces(random.nextInt(5) + 1L); InventoryOutVO out = inventoryService.addInventory(auth, newInventory, null, null, null); jobOutput.println("inventory created: " + out.getName()); return out; } public void createInventory(int inventoryCountPerDepartment) throws Exception { int inventoryRootCount = (int) (0.1 * inventoryCountPerDepartment); for (int departmentNum = 0; departmentNum < departmentCount; departmentNum++) { Collection<Staff> owners = staffDao.search(new Search(new SearchParameter[] { new SearchParameter("department.id", getDepartmentId(departmentNum), SearchParameter.EQUAL_COMPARATOR), new SearchParameter("person", false, SearchParameter.EQUAL_COMPARATOR) })); ArrayList<Long> createdIds = new ArrayList<Long>(); for (int i = 0; i < inventoryRootCount; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); InventoryOutVO inventory = createInventory(auth, i, departmentNum, null, owners); createdIds.add(inventory.getId()); createFiles(auth, FileModule.INVENTORY_DOCUMENT, inventory.getId(), FILE_COUNT_PER_INVENTORY); } for (int i = 0; i < (inventoryCountPerDepartment - inventoryRootCount); i++) { AuthenticationVO auth = getRandomAuth(departmentNum); InventoryOutVO inventory = createInventory(auth, inventoryRootCount + i, departmentNum, getRandomElement(createdIds), owners); createdIds.add(inventory.getId()); createFiles(auth, FileModule.INVENTORY_DOCUMENT, inventory.getId(), FILE_COUNT_PER_INVENTORY); } } } private InputFieldOutVO createMultiLineTextField(AuthenticationVO auth, String name, String category, String title, String comment, String textPreset, String regExp, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.MULTI_LINE_TEXT); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setRegExp(regExp); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setTextPreset(textPreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("multi line text input field created: " + out.getName()); return out; } private ProbandOutVO createProband(AuthenticationVO auth, int departmentNum, Sex sex, Collection<Long> childIds, Collection<ProbandCategory> categories, Collection<String> titles) throws Exception { // todo: relatives graph auth = (auth == null ? getRandomAuth() : auth); ProbandInVO newProband = new ProbandInVO(); newProband.setDepartmentId(getDepartmentId(departmentNum)); newProband.setCategoryId(getRandomElement(categories).getId()); if (getRandomBoolean(25)) { newProband.setPrefixedTitle1(getRandomElement(titles)); if (getRandomBoolean(20)) { newProband.setPrefixedTitle2(getRandomElement(titles)); } } if (sex == null) { if (getRandomBoolean(50)) { sex = Sex.MALE; } else { sex = Sex.FEMALE; } } newProband.setGender(sex); newProband.setFirstName(Sex.MALE == sex ? getRandomElement(GermanPersonNames.MALE_FIRST_NAMES) : getRandomElement(GermanPersonNames.FEMALE_FIRST_NAMES)); newProband.setPerson(true); newProband.setBlinded(false); newProband.setLastName(getRandomElement(GermanPersonNames.LAST_NAMES)); newProband.setCitizenship(getRandomBoolean(5) ? "Deutschland" : "österreich"); Long oldestChildDoBTime = null; if (childIds != null && childIds.size() > 0) { newProband.setChildIds(childIds); Iterator<Long> it = childIds.iterator(); while (it.hasNext()) { Long childId = it.next(); ProbandOutVO child = probandService.getProband(auth, childId, 1, null, null); if (oldestChildDoBTime == null || oldestChildDoBTime > child.getDateOfBirth().getTime()) { oldestChildDoBTime = child.getDateOfBirth().getTime(); } } } Date dOb; if (oldestChildDoBTime != null) { dOb = new Date(); dOb.setTime(oldestChildDoBTime); dOb = DateCalc.subIntervals(dOb, VariablePeriod.YEAR, null, CommonUtil.safeLongToInt(getRandomLong(15l, 40l))); } else { dOb = getRandomDateOfBirth(); } newProband.setDateOfBirth(dOb); ProbandOutVO out = probandService.addProband(auth, newProband, null, null, null); jobOutput.println("proband created: " + out.getName()); return out; } private ProbandListEntryTagOutVO createProbandListEntryTag(AuthenticationVO auth, InputFields inputField, TrialOutVO trial, int position, boolean optional, boolean disabled, boolean excelValue, boolean excelDate, boolean ecrfValue, boolean stratification, boolean randomize, String title, String comment, String jsVariableName, String jsValueExpression, String jsOutputExpression) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); ProbandListEntryTagInVO newProbandListEntryTag = new ProbandListEntryTagInVO(); newProbandListEntryTag.setOptional(optional); newProbandListEntryTag.setDisabled(disabled); newProbandListEntryTag.setExcelValue(excelValue); newProbandListEntryTag.setEcrfValue(ecrfValue); newProbandListEntryTag.setStratification(stratification); newProbandListEntryTag.setRandomize(randomize); newProbandListEntryTag.setExcelDate(excelDate); newProbandListEntryTag.setFieldId(getInputField(auth, inputField).getId()); newProbandListEntryTag.setTrialId(trial.getId()); newProbandListEntryTag.setPosition(new Long(position)); newProbandListEntryTag.setComment(comment); newProbandListEntryTag.setTitle(title); newProbandListEntryTag.setJsVariableName(jsVariableName); newProbandListEntryTag.setJsValueExpression(jsValueExpression); newProbandListEntryTag.setJsOutputExpression(jsOutputExpression); ProbandListEntryTagOutVO out = trialService.addProbandListEntryTag(auth, newProbandListEntryTag); jobOutput.println("proband list entry tag created: " + out.getUniqueName()); return out; } public void createProbands(int probandCountPerDepartment) throws Exception { int grandChildrenCount = (int) (0.5 * probandCountPerDepartment); int childrenCount = (int) (0.5 * (probandCountPerDepartment - grandChildrenCount)); Collection<String> titles = toolsService.completeTitle(null, null, -1); ArrayList<ProbandCategory> categories = new ArrayList<ProbandCategory>(probandCategoryDao.search(new Search(new SearchParameter[] { new SearchParameter("locked", false, SearchParameter.EQUAL_COMPARATOR), new SearchParameter("signup", false, SearchParameter.EQUAL_COMPARATOR), new SearchParameter("person", true, SearchParameter.EQUAL_COMPARATOR) }))); for (int departmentNum = 0; departmentNum < departmentCount; departmentNum++) { ArrayList<Long> grandChildrentIds = new ArrayList<Long>(); ArrayList<Long> childrentIds = new ArrayList<Long>(); for (int i = 0; i < grandChildrenCount; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); ProbandOutVO proband = createProband(auth, departmentNum, null, null, categories, titles); grandChildrentIds.add(proband.getId()); createFiles(auth, FileModule.PROBAND_DOCUMENT, proband.getId(), FILE_COUNT_PER_PROBAND); } HashSet<Long> childWoMaleParentIds = new HashSet<Long>(grandChildrentIds); HashSet<Long> childWoFemaleParentIds = new HashSet<Long>(grandChildrentIds); for (int i = 0; i < childrenCount; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); boolean isMale = getRandomBoolean(50); ArrayList<Long> childIds; if (isMale) { childIds = getUniqueRandomElements(new ArrayList<Long>(childWoMaleParentIds), random.nextInt(5)); childWoMaleParentIds.removeAll(childIds); } else { childIds = getUniqueRandomElements(new ArrayList<Long>(childWoFemaleParentIds), random.nextInt(5)); childWoFemaleParentIds.removeAll(childIds); } ProbandOutVO proband = createProband(auth, departmentNum, isMale ? Sex.MALE : Sex.FEMALE, childIds, categories, titles); childrentIds.add(proband.getId()); createFiles(auth, FileModule.PROBAND_DOCUMENT, proband.getId(), FILE_COUNT_PER_PROBAND); } childWoMaleParentIds = new HashSet<Long>(childrentIds); childWoFemaleParentIds = new HashSet<Long>(childrentIds); for (int i = 0; i < probandCountPerDepartment - grandChildrenCount - childrenCount; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); boolean isMale = getRandomBoolean(50); ArrayList<Long> childIds; if (isMale) { childIds = getUniqueRandomElements(new ArrayList<Long>(childWoMaleParentIds), random.nextInt(5)); childWoMaleParentIds.removeAll(childIds); } else { childIds = getUniqueRandomElements(new ArrayList<Long>(childWoFemaleParentIds), random.nextInt(5)); childWoFemaleParentIds.removeAll(childIds); } ProbandOutVO proband = createProband(auth, departmentNum, isMale ? Sex.MALE : Sex.FEMALE, childIds, categories, titles); createFiles(auth, FileModule.PROBAND_DOCUMENT, proband.getId(), FILE_COUNT_PER_PROBAND); } } } private InputFieldOutVO createSelectManyField(AuthenticationVO auth, String name, String category, String title, String comment, boolean vertical, TreeMap<InputFieldValues, Boolean> selectionSetValues, Integer minSelections, Integer maxSelections, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(vertical ? InputFieldType.SELECT_MANY_V : InputFieldType.SELECT_MANY_H); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setMinSelections(minSelections); newInputField.setMaxSelections(maxSelections); newInputField.setValidationErrorMsg(validationErrorMessage); InputFieldOutVO inputField = inputFieldService.addInputField(auth, newInputField); jobOutput.println("select many input field created: " + inputField.getName()); addSelectionSetValues(auth, inputField, selectionSetValues); return inputField; } private InputFieldOutVO createSelectOneDropdownField(AuthenticationVO auth, String name, String category, String title, String comment, TreeMap<InputFieldValues, Boolean> selectionSetValues) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.SELECT_ONE_DROPDOWN); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); InputFieldOutVO inputField = inputFieldService.addInputField(auth, newInputField); jobOutput.println("select one dropdown input field created: " + inputField.getName()); addSelectionSetValues(auth, inputField, selectionSetValues); return inputField; } private InputFieldOutVO createSelectOneRadioField(AuthenticationVO auth, String name, String category, String title, String comment, boolean vertical, TreeMap<InputFieldValues, Boolean> selectionSetValues) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(vertical ? InputFieldType.SELECT_ONE_RADIO_V : InputFieldType.SELECT_ONE_RADIO_H); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); InputFieldOutVO inputField = inputFieldService.addInputField(auth, newInputField); jobOutput.println("select one radio input field created: " + inputField.getName()); addSelectionSetValues(auth, inputField, selectionSetValues); return inputField; } private InputFieldOutVO createSingleLineTextField(AuthenticationVO auth, String name, String category, String title, String comment, String textPreset, String regExp, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.SINGLE_LINE_TEXT); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setRegExp(regExp); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setTextPreset(textPreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("single line text input field created: " + out.getName()); return out; } private InputFieldOutVO createSketchField(AuthenticationVO auth, String name, String category, String title, String comment, String resourceFileName, TreeMap<InputFieldValues, Stroke> inkRegions, Integer minSelections, Integer maxSelections, String validationErrorMessage) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); ClassPathResource resource = new ClassPathResource("/" + resourceFileName); byte[] data = CommonUtil.inputStreamToByteArray(resource.getInputStream()); newInputField.setFieldType(InputFieldType.SKETCH); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setMinSelections(minSelections); newInputField.setMaxSelections(maxSelections); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setDatas(data); newInputField.setMimeType(ExecUtil.getMimeType(data, resource.getFilename())); newInputField.setFileName(resource.getFilename()); InputFieldOutVO inputField = inputFieldService.addInputField(auth, newInputField); jobOutput.println("select many input field created: " + inputField.getName()); addInkRegions(auth, inputField, inkRegions); return inputField; } public void createStaff(int staffCountPerDepartment) throws Exception { Collection<String> titles = toolsService.completeTitle(null, null, -1); int personCount = (int) (0.6 * staffCountPerDepartment); int personRootCount = (int) (0.1 * personCount); int externalCount = (int) (0.05 * personCount); int organisationCount = staffCountPerDepartment - personCount; int organisationRootCount = (int) (0.1 * organisationCount); for (int departmentNum = 0; departmentNum < departmentCount; departmentNum++) { for (int i = 0; i < externalCount; i++) { createStaffPerson(getRandomAuth(departmentNum), departmentNum, false, null, titles).getId(); } ArrayList<Long> createdIds = new ArrayList<Long>(); for (int i = 0; i < personRootCount; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); StaffOutVO staff = createStaffPerson(auth, departmentNum, true, null, titles); createdIds.add(staff.getId()); createFiles(auth, FileModule.STAFF_DOCUMENT, staff.getId(), FILE_COUNT_PER_STAFF); } for (int i = 0; i < (personCount - externalCount - personRootCount); i++) { AuthenticationVO auth = getRandomAuth(departmentNum); StaffOutVO staff = createStaffPerson(auth, departmentNum, true, getRandomElement(createdIds), titles); createdIds.add(staff.getId()); createFiles(auth, FileModule.STAFF_DOCUMENT, staff.getId(), FILE_COUNT_PER_STAFF); } createdIds.clear(); for (int i = 0; i < organisationRootCount; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); StaffOutVO organisation = createStaffOrganisation(auth, i, departmentNum, null); createdIds.add(organisation.getId()); createFiles(auth, FileModule.STAFF_DOCUMENT, organisation.getId(), FILE_COUNT_PER_ORGANISATION); } for (int i = 0; i < (organisationCount - organisationRootCount); i++) { AuthenticationVO auth = getRandomAuth(departmentNum); StaffOutVO organisation = createStaffOrganisation(auth, organisationRootCount + i, departmentNum, getRandomElement(createdIds)); createdIds.add(organisation.getId()); createFiles(auth, FileModule.STAFF_DOCUMENT, organisation.getId(), FILE_COUNT_PER_ORGANISATION); } } } private StaffOutVO createStaffOrganisation(AuthenticationVO auth, int organisationNum, int departmentNum, Long parentId) throws Exception { auth = (auth == null ? getRandomAuth() : auth); StaffInVO newStaff = new StaffInVO(); newStaff.setPerson(false); newStaff.setAllocatable(false); newStaff.setMaxOverlappingShifts(0l); newStaff.setParentId(parentId); newStaff.setDepartmentId(getDepartmentId(departmentNum)); newStaff.setCategoryId(getRandomElement(selectionSetService.getStaffCategories(auth, false, true, null)).getId()); newStaff.setOrganisationName("organisation_" + (departmentNum + 1) + "_" + (organisationNum + 1)); StaffOutVO staff = staffService.addStaff(auth, newStaff, null, null, null); jobOutput.println("organisation created: " + staff.getName()); assignUser(staff); return staff; } private StaffOutVO createStaffPerson(AuthenticationVO auth, int departmentNum, Boolean employee, Long parentId, Collection<String> titles) throws Exception { auth = (auth == null ? getRandomAuth() : auth); StaffInVO newStaff = new StaffInVO(); newStaff.setPerson(true); newStaff.setEmployee(employee == null ? getRandomBoolean(80) : employee); newStaff.setAllocatable(newStaff.getEmployee() && getRandomBoolean(50)); if (newStaff.getAllocatable()) { newStaff.setMaxOverlappingShifts(1l); } else { newStaff.setMaxOverlappingShifts(0l); } newStaff.setParentId(parentId); newStaff.setDepartmentId(getDepartmentId(departmentNum)); newStaff.setCategoryId(getRandomElement(selectionSetService.getStaffCategories(auth, true, false, null)).getId()); if (getRandomBoolean(25)) { newStaff.setPrefixedTitle1(getRandomElement(titles)); if (getRandomBoolean(20)) { newStaff.setPrefixedTitle2(getRandomElement(titles)); } } if (getRandomBoolean(50)) { newStaff.setGender(Sex.MALE); newStaff.setFirstName(getRandomElement(GermanPersonNames.MALE_FIRST_NAMES)); } else { newStaff.setGender(Sex.FEMALE); newStaff.setFirstName(getRandomElement(GermanPersonNames.FEMALE_FIRST_NAMES)); } newStaff.setLastName(getRandomElement(GermanPersonNames.LAST_NAMES)); newStaff.setCitizenship(getRandomBoolean(5) ? "Deutschland" : "österreich"); newStaff.setDateOfBirth(getRandomDateOfBirth()); StaffOutVO staff = staffService.addStaff(auth, newStaff, null, null, null); jobOutput.println("person created: " + staff.getName()); assignUser(staff); return staff; } private InputFieldOutVO createTimeField(AuthenticationVO auth, String name, String category, String title, String comment, Date timePreset, Date minTime, Date maxTime, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.TIME); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setMinTime(minTime); newInputField.setMaxTime(maxTime); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setTimePreset(timePreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("time input field created: " + out.getName()); return out; } private TimelineEventOutVO createTimelineEvent(AuthenticationVO auth, Long trialId, String title, String typeNameL10nKey, Date start, Date stop) throws Exception { auth = (auth == null ? getRandomAuth() : auth); TimelineEventInVO newTimelineEvent = new TimelineEventInVO(); TimelineEventType eventType = typeNameL10nKey != null ? timelineEventTypeDao.searchUniqueNameL10nKey(typeNameL10nKey) : getRandomElement(timelineEventTypeDao.loadAll()); newTimelineEvent.setTrialId(trialId); newTimelineEvent.setTypeId(eventType.getId()); newTimelineEvent.setImportance(getRandomElement(EventImportance.values())); newTimelineEvent.setNotify(eventType.isNotifyPreset()); newTimelineEvent.setReminderPeriod(VariablePeriod.EXPLICIT); newTimelineEvent.setReminderPeriodDays(getRandomElement(new Long[] { 7L, 14L, 21L })); newTimelineEvent.setShow(eventType.isShowPreset()); newTimelineEvent.setStart(start); newTimelineEvent.setStop(stop); newTimelineEvent.setParentId(null); newTimelineEvent.setTitle(title == null ? eventType.getNameL10nKey() : title); newTimelineEvent.setDescription("details eines weiteren " + eventType.getNameL10nKey() + " ereignisses"); TimelineEventOutVO out = trialService.addTimelineEvent(auth, newTimelineEvent, null, null, null); jobOutput.println("timeline event created: " + out.getTitle()); return out; } private InputFieldOutVO createTimestampField(AuthenticationVO auth, String name, String category, String title, String comment, Date timestampPreset, Date minTimestamp, Date maxTimestamp, boolean isUserTimeZone, String validationErrorMessage) throws Exception { auth = (auth == null ? getRandomAuth() : auth); InputFieldInVO newInputField = new InputFieldInVO(); newInputField.setFieldType(InputFieldType.TIMESTAMP); newInputField.setName(name); newInputField.setTitle(title); newInputField.setCategory(category); newInputField.setComment(comment); newInputField.setMinTimestamp(minTimestamp); newInputField.setMaxTimestamp(maxTimestamp); newInputField.setUserTimeZone(isUserTimeZone); newInputField.setValidationErrorMsg(validationErrorMessage); newInputField.setTimestampPreset(timestampPreset); InputFieldOutVO out = inputFieldService.addInputField(auth, newInputField); jobOutput.println("timestamp input field created: " + out.getName()); return out; } private TrialOutVO createTrial(AuthenticationVO auth, int departmentNum, int trialNum, int visitCount, int probandGroupCount, int avgGroupSize, SearchCriteria criteria) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); TrialInVO newTrial = new TrialInVO(); newTrial.setStatusId(getRandomElement(selectionSetService.getInitialTrialStatusTypes(auth)).getId()); newTrial.setDepartmentId(getDepartmentId(departmentNum)); newTrial.setName("TEST TRIAL " + (departmentNum + 1) + "-" + (trialNum + 1)); newTrial.setTitle(newTrial.getName()); newTrial.setDescription(""); newTrial.setSignupProbandList(false); newTrial.setSignupInquiries(false); newTrial.setSignupRandomize(false); newTrial.setSignupDescription(""); newTrial.setExclusiveProbands(false); newTrial.setProbandAliasFormat(""); newTrial.setDutySelfAllocationLocked(false); newTrial.setTypeId(getRandomElement(selectionSetService.getTrialTypes(auth, null)).getId()); newTrial.setSponsoringId(getRandomElement(selectionSetService.getSponsoringTypes(auth, null)).getId()); newTrial.setSurveyStatusId(getRandomElement(selectionSetService.getSurveyStatusTypes(auth, null)).getId()); TrialOutVO trial = trialService.addTrial(auth, newTrial, null); jobOutput.println("trial created: " + trial.getName()); ArrayList<Staff> departmentStaff = new ArrayList<Staff>(staffDao.search(new Search(new SearchParameter[] { new SearchParameter("department.id", trial.getDepartment().getId(), SearchParameter.EQUAL_COMPARATOR), new SearchParameter("person", true, SearchParameter.EQUAL_COMPARATOR), new SearchParameter("employee", true, SearchParameter.EQUAL_COMPARATOR), new SearchParameter("allocatable", true, SearchParameter.EQUAL_COMPARATOR) }))); Collection<TeamMemberRole> roles = teamMemberRoleDao.loadAll(); ArrayList<TeamMemberOutVO> teamMembers = new ArrayList<TeamMemberOutVO>(); Iterator<Staff> teamMemberStaffIt = getUniqueRandomElements(departmentStaff, 3 + random.nextInt(8)).iterator(); while (teamMemberStaffIt.hasNext()) { Staff teamMemberStaff = teamMemberStaffIt.next(); TeamMemberInVO newTeamMember = new TeamMemberInVO(); newTeamMember.setStaffId(teamMemberStaff.getId()); newTeamMember.setTrialId(trial.getId()); newTeamMember.setAccess(true); newTeamMember.setNotifyTimelineEvent(true); newTeamMember.setNotifyEcrfValidatedStatus(true); newTeamMember.setNotifyEcrfReviewStatus(true); newTeamMember.setNotifyEcrfVerifiedStatus(true); newTeamMember.setNotifyEcrfFieldStatus(true); newTeamMember.setNotifyOther(true); boolean created = false; TeamMemberRole role; while (!created) { try { role = getRandomElement(roles); newTeamMember.setRoleId(role.getId()); TeamMemberOutVO out = trialService.addTeamMember(auth, newTeamMember); jobOutput.println("team member created: " + out.getStaff().getName() + " (" + out.getRole().getName() + ")"); teamMembers.add(out); created = true; } catch (ServiceException e) { jobOutput.println(e.getMessage()); } } } VisitInVO newVisit = new VisitInVO(); newVisit.setTitle("Screeningvisite"); newVisit.setToken("SV"); newVisit.setReimbursement(0.0f); newVisit.setTypeId(visitTypeDao.searchUniqueNameL10nKey("screening").getId()); newVisit.setTrialId(trial.getId()); VisitOutVO screeningVisit = trialService.addVisit(auth, newVisit); jobOutput.println("visit created: " + screeningVisit.getTitle()); ArrayList<VisitOutVO> visits = new ArrayList<VisitOutVO>(); for (int i = 0; i < visitCount; i++) { newVisit = new VisitInVO(); newVisit.setTitle("Visite " + (i + 1)); newVisit.setToken("V" + (i + 1)); newVisit.setReimbursement(0.0f); newVisit.setTypeId(visitTypeDao.searchUniqueNameL10nKey("inpatient").getId()); newVisit.setTrialId(trial.getId()); VisitOutVO visit = trialService.addVisit(auth, newVisit); jobOutput.println("visit created: " + visit.getTitle()); visits.add(visit); } newVisit = new VisitInVO(); newVisit.setTitle("Abschlussvisite"); newVisit.setToken("AV"); newVisit.setReimbursement(0.0f); newVisit.setTypeId(visitTypeDao.searchUniqueNameL10nKey("final").getId()); newVisit.setTrialId(trial.getId()); VisitOutVO finalVisit = trialService.addVisit(auth, newVisit); jobOutput.println("visit created: " + finalVisit.getTitle()); visits.add(finalVisit); ProbandGroupInVO newProbandGroup = new ProbandGroupInVO(); newProbandGroup.setTitle("Screeninggruppe"); newProbandGroup.setToken("SG"); newProbandGroup.setTrialId(trial.getId()); ProbandGroupOutVO screeningGroup = trialService.addProbandGroup(auth, newProbandGroup); jobOutput.println("proband group created: " + screeningGroup.getTitle()); ArrayList<ProbandGroupOutVO> probandGroups = new ArrayList<ProbandGroupOutVO>(); for (int i = 0; i < probandGroupCount; i++) { newProbandGroup = new ProbandGroupInVO(); newProbandGroup.setTitle("Gruppe " + (i + 1)); newProbandGroup.setToken("G" + (i + 1)); newProbandGroup.setTrialId(trial.getId()); ProbandGroupOutVO probandGroup = trialService.addProbandGroup(auth, newProbandGroup); jobOutput.println("proband group created: " + probandGroup.getTitle()); probandGroups.add(probandGroup); } Date screeningDate = getRandomScreeningDate(); Date visitDate = new Date(); visitDate.setTime(screeningDate.getTime()); HashMap<Long, ArrayList<VisitScheduleItemOutVO>> visitScheduleItemPerGroupMap = new HashMap<Long, ArrayList<VisitScheduleItemOutVO>>(); long screeningDays = getRandomLong(2l, 14l); VisitScheduleItemInVO newVisitScheduleItem = new VisitScheduleItemInVO(); newVisitScheduleItem.setVisitId(screeningVisit.getId()); newVisitScheduleItem.setGroupId(screeningGroup.getId()); newVisitScheduleItem.setToken("D1"); newVisitScheduleItem.setTrialId(trial.getId()); newVisitScheduleItem.setNotify(false); Date[] startStop = getFromTo(visitDate, 9, 0, 16, 0); newVisitScheduleItem.setStart(startStop[0]); newVisitScheduleItem.setStop(startStop[1]); VisitScheduleItemOutVO visitScheduleItem = trialService.addVisitScheduleItem(auth, newVisitScheduleItem); ArrayList<VisitScheduleItemOutVO> groupVisitScheduleItems = new ArrayList<VisitScheduleItemOutVO>((int) screeningDays); groupVisitScheduleItems.add(visitScheduleItem); jobOutput.println("visit schedule item created: " + visitScheduleItem.getName()); createDuty(auth, departmentStaff, trial, startStop[0], startStop[1], "Dienst für Screening Tag 1"); for (int i = 2; i <= screeningDays; i++) { newVisitScheduleItem = new VisitScheduleItemInVO(); newVisitScheduleItem.setVisitId(screeningVisit.getId()); newVisitScheduleItem.setGroupId(screeningGroup.getId()); newVisitScheduleItem.setToken("D" + i); newVisitScheduleItem.setTrialId(trial.getId()); newVisitScheduleItem.setNotify(false); startStop = getFromTo(DateCalc.addInterval(visitDate, VariablePeriod.EXPLICIT, i - 1l), 9, 0, 16, 0); newVisitScheduleItem.setStart(startStop[0]); newVisitScheduleItem.setStop(startStop[1]); visitScheduleItem = trialService.addVisitScheduleItem(auth, newVisitScheduleItem); groupVisitScheduleItems.add(visitScheduleItem); visitScheduleItemPerGroupMap.put(screeningGroup.getId(), groupVisitScheduleItems); jobOutput.println("visit schedule item created: " + visitScheduleItem.getName()); createDuty(auth, departmentStaff, trial, startStop[0], startStop[1], "Dienst für Screening Tag " + i); } visitDate = DateCalc.addInterval(visitDate, VariablePeriod.EXPLICIT, getRandomElement(new Long[] { 2l, 3l, 7l }) + screeningDays - 1l); Iterator<VisitOutVO> visitIt = visits.iterator(); while (visitIt.hasNext()) { VisitOutVO visit = visitIt.next(); Iterator<ProbandGroupOutVO> probandGroupIt = probandGroups.iterator(); int groupCount = 0; while (probandGroupIt.hasNext()) { ProbandGroupOutVO probandGroup = probandGroupIt.next(); newVisitScheduleItem = new VisitScheduleItemInVO(); newVisitScheduleItem.setVisitId(visit.getId()); newVisitScheduleItem.setGroupId(probandGroup.getId()); newVisitScheduleItem.setToken(null); newVisitScheduleItem.setTrialId(trial.getId()); newVisitScheduleItem.setNotify(false); startStop = getFromTo(visitDate, 9, 0, 16, 0); newVisitScheduleItem.setStart(startStop[0]); newVisitScheduleItem.setStop(startStop[1]); if (!visitScheduleItemPerGroupMap.containsKey(probandGroup.getId())) { groupVisitScheduleItems = new ArrayList<VisitScheduleItemOutVO>(visits.size()); visitScheduleItemPerGroupMap.put(probandGroup.getId(), groupVisitScheduleItems); } else { groupVisitScheduleItems = visitScheduleItemPerGroupMap.get(probandGroup.getId()); } visitScheduleItem = trialService.addVisitScheduleItem(auth, newVisitScheduleItem); groupVisitScheduleItems.add(visitScheduleItem); jobOutput.println("visit schedule item created: " + visitScheduleItem.getName()); if (groupCount % 2 == 1) { createDuty(auth, departmentStaff, trial, startStop[0], startStop[1], null); visitDate = DateCalc.addInterval(visitDate, VariablePeriod.EXPLICIT, 1L); } groupCount++; } visitDate = DateCalc.addInterval(visitDate, VariablePeriod.EXPLICIT, getRandomElement(new Long[] { 1l, 2l, 3l, 7L, 14L, 21L })); } Date finalVisitDate = new Date(); finalVisitDate.setTime(visitDate.getTime()); createTimelineEvent(auth, trial.getId(), "Screening", "deadline", screeningDate, null); createTimelineEvent(auth, trial.getId(), "Abschlussvisite", "deadline", finalVisitDate, null); createTimelineEvent(auth, trial.getId(), "Studienvisiten", "phase", screeningDate, finalVisitDate); Date screeningDatePlanned = getRandomDateAround(screeningDate, 5, 5); createTimelineEvent(auth, trial.getId(), "Screening geplant", "phase", screeningDatePlanned, DateCalc.addInterval(screeningDatePlanned, VariablePeriod.EXPLICIT, (long) DateCalc.dateDeltaDays(screeningDate, finalVisitDate))); int screeningDelay = random.nextInt(15); Date recruitmentStop = DateCalc.subInterval(screeningDate, VariablePeriod.EXPLICIT, (long) screeningDelay); VariablePeriod recruitmentDuration = getRandomElement(new VariablePeriod[] { VariablePeriod.EXPLICIT, VariablePeriod.MONTH, VariablePeriod.TWO_MONTHS, VariablePeriod.THREE_MONTHS }); Date recruitmentStart = DateCalc.subInterval(recruitmentStop, recruitmentDuration, (recruitmentDuration == VariablePeriod.EXPLICIT ? getRandomElement(new Long[] { 21L, 42L, 70L }) : null)); createTimelineEvent(auth, trial.getId(), "Rekrutierung", "phase", recruitmentStart, recruitmentStop); Date trialStart = DateCalc.subInterval(recruitmentStart, VariablePeriod.EXPLICIT, getRandomElement(new Long[] { 14L, 21L, 28L, 42L })); Date trialEnd = getRandomDate(DateCalc.addInterval(finalVisitDate, VariablePeriod.EXPLICIT, 14L), DateCalc.addInterval(finalVisitDate, VariablePeriod.EXPLICIT, 60L)); createTimelineEvent(auth, trial.getId(), "Studie", "trial", trialStart, trialEnd); for (int i = 0; i < 3 + random.nextInt(8); i++) { createTimelineEvent(auth, trial.getId(), "Einreichfrist " + (i + 1), "deadline", getRandomDate(trialStart, screeningDate), null); } for (int i = 0; i < 1 + random.nextInt(3); i++) { createTimelineEvent(auth, trial.getId(), "Audit " + (i + 1), "deadline", getRandomDate(screeningDate, trialEnd), null); } for (int i = 0; i < 1 + random.nextInt(3); i++) { createTimelineEvent(auth, trial.getId(), "Abgabefrist " + (i + 1), "deadline", getRandomDate(finalVisitDate, trialEnd), null); } ArrayList<InquiryOutVO> inquiries = new ArrayList<InquiryOutVO>(); ArrayList<ProbandListEntryTagOutVO> probandListEntryTags = new ArrayList<ProbandListEntryTagOutVO>(); if (criteria != null) { inquiries.add(createInquiry(auth, InputFields.HEIGHT, trial, "01 - Allgemeine information", 1, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.WEIGHT, trial, "01 - Allgemeine information", 2, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.BMI, trial, "01 - Allgemeine information", 3, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.CLINICAL_TRIAL_EXPERIENCE_YN, trial, "01 - Allgemeine information", 4, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.SMOKER_YN, trial, "01 - Allgemeine information", 5, true, true, false, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.CIGARETTES_PER_DAY, trial, "01 - Allgemeine information", 6, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.DIABETES_YN, trial, "02 - Diabetes", 1, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.DIABETES_TYPE, trial, "02 - Diabetes", 2, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.DIABETES_SINCE, trial, "02 - Diabetes", 3, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.DIABETES_HBA1C_MMOLPERMOL, trial, "02 - Diabetes", 4, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.DIABETES_HBA1C_DATE, trial, "02 - Diabetes", 5, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.DIABETES_ATTENDING_PHYSICIAN, trial, "02 - Diabetes", 6, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.DIABETES_METHOD_OF_TREATMENT, trial, "02 - Diabetes", 7, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.DIABETES_MEDICATION, trial, "02 - Diabetes", 8, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.CHRONIC_DISEASE_YN, trial, "03 - Krankheitsgeschichte", 1, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.CHRONIC_DISEASE, trial, "03 - Krankheitsgeschichte", 2, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.EPILEPSY_YN, trial, "03 - Krankheitsgeschichte", 3, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.EPILEPSY, trial, "03 - Krankheitsgeschichte", 4, true, true, true, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.CARDIAC_PROBLEMS_YN, trial, "03 - Krankheitsgeschichte", 5, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.CARDIAC_PROBLEMS, trial, "03 - Krankheitsgeschichte", 6, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.HYPERTENSION_YN, trial, "03 - Krankheitsgeschichte", 7, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.HYPERTENSION, trial, "03 - Krankheitsgeschichte", 8, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.RENAL_INSUFFICIENCY_YN, trial, "03 - Krankheitsgeschichte", 9, true, true, false, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.RENAL_INSUFFICIENCY, trial, "03 - Krankheitsgeschichte", 10, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.LIVER_DISEASE_YN, trial, "03 - Krankheitsgeschichte", 11, true, true, false, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.LIVER_DISEASE, trial, "03 - Krankheitsgeschichte", 12, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.ANEMIA_YN, trial, "03 - Krankheitsgeschichte", 13, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.ANEMIA, trial, "03 - Krankheitsgeschichte", 14, true, true, true, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.IMMUNE_MEDAITED_DISEASE_YN, trial, "03 - Krankheitsgeschichte", 15, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.IMMUNE_MEDAITED_DISEASE, trial, "03 - Krankheitsgeschichte", 16, true, true, true, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.GESTATION_YN, trial, "03 - Krankheitsgeschichte", 17, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.GESTATION_TYPE, trial, "03 - Krankheitsgeschichte", 18, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.CONTRACEPTION_YN, trial, "03 - Krankheitsgeschichte", 19, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.CONTRACEPTION_TYPE, trial, "03 - Krankheitsgeschichte", 20, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.ALCOHOL_DRUG_ABUSE_YN, trial, "03 - Krankheitsgeschichte", 21, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.ALCOHOL_DRUG_ABUSE, trial, "03 - Krankheitsgeschichte", 22, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.ALLERGY_YN, trial, "03 - Krankheitsgeschichte", 23, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.ALLERGY, trial, "03 - Krankheitsgeschichte", 24, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.MEDICATION_YN, trial, "03 - Krankheitsgeschichte", 25, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.MEDICATION, trial, "03 - Krankheitsgeschichte", 26, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.EYE_PROBLEMS_YN, trial, "03 - Krankheitsgeschichte", 27, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.EYE_PROBLEMS, trial, "03 - Krankheitsgeschichte", 28, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.FEET_PROBLEMS_YN, trial, "03 - Krankheitsgeschichte", 29, true, true, false, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.FEET_PROBLEMS, trial, "03 - Krankheitsgeschichte", 30, true, true, true, false, true, true, null, null, null, null, null)); inquiries .add(createInquiry(auth, InputFields.DIAGNOSTIC_FINDINGS_AVAILABLE_YN, trial, "03 - Krankheitsgeschichte", 31, true, true, false, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.DIAGNOSTIC_FINDINGS_AVAILABLE, trial, "03 - Krankheitsgeschichte", 32, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add( createInquiry(auth, InputFields.GENERAL_STATE_OF_HEALTH, trial, "03 - Krankheitsgeschichte", 33, true, true, true, false, true, true, null, null, null, null, null)); inquiries.add(createInquiry(auth, InputFields.NOTE, trial, "03 - Krankheitsgeschichte", 34, true, true, true, false, true, true, null, null, null, null, null)); } probandListEntryTags.add(createProbandListEntryTag(auth, InputFields.SUBJECT_NUMBER, trial, 1, false, false, true, true, true, false, false, null, null, null, null, null)); probandListEntryTags.add(createProbandListEntryTag(auth, InputFields.IC_DATE, trial, 2, false, false, true, true, true, false, false, null, null, null, null, null)); probandListEntryTags.add(createProbandListEntryTag(auth, InputFields.SCREENING_DATE, trial, 3, false, false, true, true, true, false, false, null, null, null, null, null)); probandListEntryTags.add(createProbandListEntryTag(auth, InputFields.LAB_NUMBER, trial, 4, false, false, true, true, true, false, false, null, null, null, null, null)); probandListEntryTags.add(createProbandListEntryTag(auth, InputFields.RANDOM_NUMBER, trial, 5, false, false, true, true, true, false, false, null, null, null, null, null)); probandListEntryTags .add(createProbandListEntryTag(auth, InputFields.LETTER_TO_PHYSICIAN_SENT, trial, 6, false, false, true, true, true, false, false, null, null, null, null, null)); probandListEntryTags .add(createProbandListEntryTag(auth, InputFields.PARTICIPATION_LETTER_IN_MEDOCS, trial, 7, false, false, true, true, true, false, false, null, null, null, null, null)); probandListEntryTags .add(createProbandListEntryTag(auth, InputFields.COMPLETION_LETTER_IN_MEDOCS, trial, 8, false, false, true, true, true, false, false, null, null, null, null, null)); if (!"migration_started".equals(trial.getStatus().getNameL10nKey())) { newTrial.setId(trial.getId()); newTrial.setVersion(trial.getVersion()); newTrial.setStatusId(trialStatusTypeDao.searchUniqueNameL10nKey("started").getId()); trial = trialService.updateTrial(auth, newTrial, null, false); jobOutput.println("trial " + trial.getName() + " updated: " + trial.getStatus().getName()); } Collection allProbands = probandDao.search(new Search(new SearchParameter[] { new SearchParameter("department.id", getDepartmentId(departmentNum), SearchParameter.EQUAL_COMPARATOR) })); ArrayList<ProbandOutVO> probands; if (criteria != null) { Iterator<Proband> probandsIt = allProbands.iterator(); while (probandsIt.hasNext()) { Proband proband = probandsIt.next(); ProbandOutVO probandVO = probandService.getProband(auth, proband.getId(), null, null, null); HashSet<InquiryValueInVO> inquiryValuesIns = new HashSet<InquiryValueInVO>(); Iterator<InquiryOutVO> inquiriesIt = inquiries.iterator(); while (inquiriesIt.hasNext()) { InquiryOutVO inquiry = inquiriesIt.next(); if (inquiry.isActive()) { InquiryValueInVO newInquiryValue = new InquiryValueInVO(); newInquiryValue.setProbandId(proband.getId()); newInquiryValue.setInquiryId(inquiry.getId()); setRandomInquiryValue(inquiry, newInquiryValue); inquiryValuesIns.add(newInquiryValue); } } jobOutput.println(probandVO.getName() + ": " + probandService.setInquiryValues(getRandomAuth(departmentNum), inquiryValuesIns, true).getPageValues().size() + " inquiry values set/created"); } probands = new ArrayList<ProbandOutVO>(performSearch(auth, criteria, null, null)); } else { probands = new ArrayList<ProbandOutVO>(allProbands.size()); Iterator<Proband> probandsIt = allProbands.iterator(); while (probandsIt.hasNext()) { probands.add(probandService.getProband(auth, probandsIt.next().getId(), null, null, null)); } } Collections.shuffle(probands, random); ArrayList<ProbandListEntryOutVO> probandListEntries = new ArrayList<ProbandListEntryOutVO>(); for (int i = 0; i < probands.size() && i < (probandGroupCount * avgGroupSize); i++) { ProbandListEntryInVO newProbandListEntry = new ProbandListEntryInVO(); newProbandListEntry.setGroupId(getRandomElement(probandGroups).getId()); newProbandListEntry.setPosition(i + 1l); newProbandListEntry.setTrialId(trial.getId()); newProbandListEntry.setProbandId(probands.get(i).getId()); ProbandListEntryOutVO probandListEntry = trialService.addProbandListEntry(auth, false, false, false, newProbandListEntry); jobOutput.println("proband list entry created - trial: " + probandListEntry.getTrial().getName() + " position: " + probandListEntry.getPosition() + " proband: " + probandListEntry.getProband().getName()); updateProbandListStatusEntryRealTimestamp(probandListEntry.getLastStatus(), screeningGroup, visitScheduleItemPerGroupMap, 0); probandListEntry = trialService.getProbandListEntry(auth, probandListEntry.getId()); // valid laststatus probandListEntries.add(probandListEntry); } HashMap<String, ProbandListStatusTypeVO> probandListStatusTypeMap = new HashMap<String, ProbandListStatusTypeVO>(); Iterator<ProbandListStatusTypeVO> probandListStatusTypeIt = selectionSetService.getAllProbandListStatusTypes(auth, true).iterator(); while (probandListStatusTypeIt.hasNext()) { ProbandListStatusTypeVO probandListStatusType = probandListStatusTypeIt.next(); probandListStatusTypeMap.put(probandListStatusType.getNameL10nKey(), probandListStatusType); } Iterator<ProbandListEntryOutVO> probandListEntryIt = probandListEntries.iterator(); while (probandListEntryIt.hasNext()) { ProbandListEntryOutVO probandListEntry = probandListEntryIt.next(); HashSet<ProbandListEntryTagValueInVO> probandListEntryTagValuesIns = new HashSet<ProbandListEntryTagValueInVO>(); Iterator<ProbandListEntryTagOutVO> probandListEntryTagsIt = probandListEntryTags.iterator(); while (probandListEntryTagsIt.hasNext()) { ProbandListEntryTagOutVO probandListEntryTag = probandListEntryTagsIt.next(); ProbandListEntryTagValueInVO newProbandListEntryTagValue = new ProbandListEntryTagValueInVO(); newProbandListEntryTagValue.setListEntryId(probandListEntry.getId()); newProbandListEntryTagValue.setTagId(probandListEntryTag.getId()); setRandomProbandListEntryTagValue(probandListEntryTag, newProbandListEntryTagValue); probandListEntryTagValuesIns.add(newProbandListEntryTagValue); } jobOutput.println(probandListEntry.getPosition() + ". " + probandListEntry.getProband().getName() + ": " + trialService.setProbandListEntryTagValues(getRandomAuth(departmentNum), probandListEntryTagValuesIns, true).getPageValues().size() + " proband list entry tag values set/created"); HashSet<ProbandListStatusTypeVO> passedProbandListStatus = new HashSet<ProbandListStatusTypeVO>(); passedProbandListStatus.add(probandListEntry.getLastStatus().getStatus()); boolean allowPassed = false; int statusHistoryLength = 0; ProbandListStatusTypeVO newStatus; while ((newStatus = getNextProbandListStatusType(auth, probandListEntry, allowPassed, passedProbandListStatus, probandListStatusTypeMap)) != null) { passedProbandListStatus.add(newStatus); ProbandListStatusEntryInVO newProbandListStatusEntry = new ProbandListStatusEntryInVO(); newProbandListStatusEntry.setListEntryId(probandListEntry.getId()); newProbandListStatusEntry.setStatusId(newStatus.getId()); newProbandListStatusEntry.setReason(newStatus.isReasonRequired() ? "eine erforderliche Begründung" : null); newProbandListStatusEntry.setRealTimestamp(new Date(probandListEntry.getLastStatus().getRealTimestamp().getTime() + 60000l)); if (!updateProbandListStatusEntryRealTimestamp(trialService.addProbandListStatusEntry(auth, false, newProbandListStatusEntry), screeningGroup, visitScheduleItemPerGroupMap, statusHistoryLength)) { break; } probandListEntry = trialService.getProbandListEntry(auth, probandListEntry.getId()); // valid laststatus statusHistoryLength++; } jobOutput.println(probandListEntry.getPosition() + ". " + probandListEntry.getProband().getName() + ": " + statusHistoryLength + " enrollment status entries added - final state: " + probandListEntry.getLastStatus().getStatus().getName()); } return trial; } public void createTrials(int trialCountPerDepartment, SearchCriteria[] eligibilityCriterias, Integer[] visitCounts, Integer[] probandGroupCounts, Integer[] avgProbandGroupSizes) throws Throwable { for (int departmentNum = 0; departmentNum < departmentCount; departmentNum++) { for (int i = 0; i < trialCountPerDepartment; i++) { AuthenticationVO auth = getRandomAuth(departmentNum); SearchCriteria eligibilityCriteria = null; if (eligibilityCriterias != null && i < eligibilityCriterias.length) { eligibilityCriteria = eligibilityCriterias[i]; } TrialOutVO trial = createTrial(auth, departmentNum, i, getRandomElement(visitCounts), getRandomElement(probandGroupCounts), getRandomElement(avgProbandGroupSizes), eligibilityCriteria); createFiles(auth, FileModule.TRIAL_DOCUMENT, trial.getId(), FILE_COUNT_PER_TRIAL); } } } private UserOutVO createUser(String name, String password, long departmentId, String departmentPassword) throws Exception { UserInVO newUser = new UserInVO(); newUser.setLocale(CommonUtil.localeToString(Locale.getDefault())); newUser.setTimeZone(CommonUtil.timeZoneToString(TimeZone.getDefault())); newUser.setDateFormat(null); newUser.setDecimalSeparator(null); newUser.setLocked(false); newUser.setShowTooltips(false); newUser.setDecrypt(true); newUser.setDecryptUntrusted(false); newUser.setEnableInventoryModule(true); newUser.setEnableStaffModule(true); newUser.setEnableCourseModule(true); newUser.setEnableTrialModule(true); newUser.setEnableInputFieldModule(true); newUser.setEnableProbandModule(true); newUser.setEnableMassMailModule(true); newUser.setEnableUserModule(true); newUser.setAuthMethod(AuthenticationType.LOCAL); PasswordInVO newPassword = new PasswordInVO(); ServiceUtil.applyLogonLimitations(newPassword); newUser.setDepartmentId(departmentId); newUser.setName(name); newPassword.setPassword(password); UserOutVO user = toolsService.addUser(newUser, newPassword, departmentPassword); jobOutput.println("user created: " + user.getName()); addUserPermissionProfiles(user, new ArrayList<PermissionProfile>() { { add(PermissionProfile.INVENTORY_MASTER_ALL_DEPARTMENTS); add(PermissionProfile.STAFF_MASTER_ALL_DEPARTMENTS); add(PermissionProfile.COURSE_MASTER_ALL_DEPARTMENTS); add(PermissionProfile.TRIAL_MASTER_ALL_DEPARTMENTS); add(PermissionProfile.PROBAND_MASTER_ALL_DEPARTMENTS); add(PermissionProfile.USER_ALL_DEPARTMENTS); add(PermissionProfile.INPUT_FIELD_MASTER); add(PermissionProfile.MASS_MAIL_DETAIL_ALL_DEPARTMENTS); add(PermissionProfile.INVENTORY_MASTER_SEARCH); add(PermissionProfile.STAFF_MASTER_SEARCH); add(PermissionProfile.COURSE_MASTER_SEARCH); add(PermissionProfile.TRIAL_MASTER_SEARCH); add(PermissionProfile.PROBAND_MASTER_SEARCH); add(PermissionProfile.USER_MASTER_SEARCH); add(PermissionProfile.INPUT_FIELD_MASTER_SEARCH); add(PermissionProfile.MASS_MAIL_MASTER_SEARCH); } }); return user; } private AuthenticationVO getAuth(int departmentNum, int userNum) { return new AuthenticationVO(getUsername(departmentNum, userNum), getUserPassword(departmentNum, userNum), null, "localhost"); } private CriteriaOutVO getCriteria(AuthenticationVO auth, SearchCriteria criteria) throws Throwable { final AuthenticationVO a = (auth == null ? getRandomAuth() : auth); String name = criteria.toString(); Iterator<Criteria> it = (new ArrayList<Criteria>(criteriaDao.search(new Search(new SearchParameter[] { new SearchParameter("category", "test_" + prefix, SearchParameter.EQUAL_COMPARATOR), new SearchParameter("label", name, SearchParameter.EQUAL_COMPARATOR) })))).iterator(); if (it.hasNext()) { return searchService.getCriteria(a, it.next().getId()); } else { switch (criteria) { case ALL_INVENTORY: return createCriteria(a, DBModule.INVENTORY_DB, new ArrayList<SearchCriterion>(), name, "This query lists all inventory items.", true); case ALL_STAFF: return createCriteria(a, DBModule.STAFF_DB, new ArrayList<SearchCriterion>(), name, "This query lists all person and organisation records.", true); case ALL_COURSES: return createCriteria(a, DBModule.COURSE_DB, new ArrayList<SearchCriterion>(), name, "This query lists all courses.", true); case ALL_TRIALS: return createCriteria(a, DBModule.TRIAL_DB, new ArrayList<SearchCriterion>(), name, "This query lists all trials.", true); case ALL_PROBANDS: return createCriteria(a, DBModule.PROBAND_DB, new ArrayList<SearchCriterion>(), name, "This query lists all probands.", true); case ALL_INPUTFIELDS: return createCriteria(a, DBModule.INPUT_FIELD_DB, new ArrayList<SearchCriterion>(), name, "This query lists all input fields.", true); case ALL_USERS: return createCriteria(a, DBModule.USER_DB, new ArrayList<SearchCriterion>(), name, "This query lists all users.", true); case ALL_MASSMAILS: return createCriteria(a, DBModule.MASS_MAIL_DB, new ArrayList<SearchCriterion>(), name, "This query lists all mass mails.", true); case SUBJECTS_1: return createCriteria(a, DBModule.PROBAND_DB, new ArrayList<SearchCriterion>() { { InputFieldOutVO field1 = getInputField(a, InputFields.DIABETES_TYPE); InputFieldSelectionSetValue value1 = getInputFieldValue(field1.getId(), InputFieldValues.TYP_2_DIABETES_OHNE_INSULINEIGENPRODUKTION); add(new SearchCriterion(null, "proband.inquiryValues.inquiry.field.id", CriterionRestriction.EQ, field1.getId())); add(new SearchCriterion(CriterionTie.AND, "proband.inquiryValues.value.selectionValues.id", CriterionRestriction.EQ, value1.getId())); } }, name, "", true); default: return null; } } } private Long getDepartmentId(int departmentNum) throws Exception { return ExecUtil.departmentL10nKeyToId(getDepartmentName(departmentNum), departmentDao, jobOutput); } private Object[] getDepartmentIds() { ArrayList<Long> result = new ArrayList<Long>(); Pattern departmentNameRegExp = Pattern.compile("^department " + Pattern.quote(prefix) + " [0-9]+$"); Iterator<Department> departmentIt = departmentDao.loadAll().iterator(); while (departmentIt.hasNext()) { Department department = departmentIt.next(); if (departmentNameRegExp.matcher(department.getNameL10nKey()).find()) { result.add(department.getId()); } } return result.toArray(); } private String getDepartmentName(int num) { return String.format("department %s %d", prefix, num + 1); } private String getDepartmentPassword(int num) { return getDepartmentName(num); } private Date[] getFromTo(Date date, int hourStart, int minuteStart, int hourEnd, int minuteEnd) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); Date[] result = new Date[2]; result[0] = (new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), hourStart, minuteStart, 0)) .getTime(); result[1] = (new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), hourEnd, minuteEnd, 0)) .getTime(); return result; } private InputFieldOutVO getInputField(AuthenticationVO auth, InputFields inputField) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); String name = inputField.toString(); Iterator<InputField> it = inputFieldDao.findByNameL10nKeyLocalized(name, false).iterator(); if (it.hasNext()) { return inputFieldService.getInputField(auth, it.next().getId()); } else { String inquiryQuestionsCategory = "Erhebungsfragen"; String probandListEntryTagCategory = "Probandenlistenspalten"; String ecrfFieldCategory = "eCRF Felder"; switch (inputField) { case HEIGHT: return createIntegerField(auth, name, inquiryQuestionsCategory, "Körpergröße (cm):", "", null, 50l, 300l, "Die Körpergröße erfordert einen Ganzzahlwert zwischen 50 und 300 cm."); case WEIGHT: return createIntegerField(auth, name, inquiryQuestionsCategory, "Körpergewicht (kg):", "", null, 3l, 500l, "Das Körpergewicht erfordert einen Ganzzahlwert zwischen 3 und 500 kg."); case BMI: return createFloatField(auth, name, inquiryQuestionsCategory, "BMI (kg/m²):", "", null, 5f, 60f, "Der BMI erfordert eine Fließkommazahl zwischen 5.0 und 200.0 kg/m²."); case DIABETES_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Diabetes:", null, false); case DIABETES_TYPE: return createSelectOneRadioField(auth, name, inquiryQuestionsCategory, "Diabetes Typ:", null, false, new TreeMap<InputFieldValues, Boolean>() { { put(InputFieldValues.TYP_1_DIABETES, false); put(InputFieldValues.TYP_2_DIABETES_MIT_INSULINEIGENPRODUKTION, false); put(InputFieldValues.TYP_2_DIABETES_OHNE_INSULINEIGENPRODUKTION, false); } }); case DIABETES_SINCE: return createIntegerField(auth, name, inquiryQuestionsCategory, "Diabetes seit (Jahr):", null, null, 1930l, null, "Diabetes seit erfordert eine Jahreszahl größer gleich 1930."); case DIABETES_HBA1C_MMOLPERMOL: return createFloatField(auth, name, inquiryQuestionsCategory, "HbA1C-Wert (mmol/mol):", null, null, 20f, 130f, "Der HbA1C-Wert erfordert eine Fließkommazahl zwischen 20.0 und 130.0 mmol/mol"); case DIABETES_HBA1C_PERCENT: return createFloatField(auth, name, inquiryQuestionsCategory, "HbA1C-Wert (Prozent):", null, null, 2.5f, 15f, "Der HbA1C-Wert erfordert eine Fließkommazahl zwischen 2.5 und 15.0 %"); case DIABETES_HBA1C_DATE: return createDateField(auth, name, inquiryQuestionsCategory, "HbA1C zuletzt bestimmt:", null, null, (new GregorianCalendar(1980, 0, 1)).getTime(), null, "HbA1C zuletzt bestimmt muss nach 1980-01-01 liegen"); case DIABETES_C_PEPTIDE: return createFloatField(auth, name, inquiryQuestionsCategory, "C-Peptid (µg/l):", null, null, 0.5f, 7.0f, "Die C-Peptid Konzentration erfordert eine Fließkommazahl zwischen 0.5 und 7.0 µg/l"); case DIABETES_ATTENDING_PHYSICIAN: return createSingleLineTextField(auth, name, inquiryQuestionsCategory, "Arzt in Behandlung:", "Name/Anschrift des Arztes", null, null, null); case DIABETES_METHOD_OF_TREATMENT: return createSelectManyField(auth, name, inquiryQuestionsCategory, "Behandlungsmethode:", null, true, new TreeMap<InputFieldValues, Boolean>() { { put(InputFieldValues.DIAET, false); put(InputFieldValues.SPORTLICHE_BETAETIGUNG, false); put(InputFieldValues.ORALE_ANTIDIABETIKA, false); put(InputFieldValues.INSULINTHERAPIE, false); } }, null, null, null); case DIABETES_MEDICATION: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Medikamente:", null, null, null, null); case CLINICAL_TRIAL_EXPERIENCE_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Haben Sie Erfahrung mit klinischen Studien?", null, false); case SMOKER_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Raucher:", null, false); case CIGARETTES_PER_DAY: return createSelectOneDropdownField(auth, name, inquiryQuestionsCategory, "Zigaretten/Tag:", null, new TreeMap<InputFieldValues, Boolean>() { { put(InputFieldValues.CIGARETTES_UNTER_5, false); put(InputFieldValues.CIGARETTES_5_20, false); put(InputFieldValues.CIGARETTES_20_40, false); put(InputFieldValues.CIGARETTES_UEBER_40, false); } }); case CHRONIC_DISEASE_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Chronische Erkrankung:", null, false); case CHRONIC_DISEASE: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Chronische Erkrankung:", null, null, null, null); case EPILEPSY_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Epilepsie:", null, false); case EPILEPSY: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Epilepsie:", null, null, null, null); case CARDIAC_PROBLEMS_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Herzprobleme:", null, false); case CARDIAC_PROBLEMS: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "herzprobleme:", null, null, null, null); case HYPERTENSION_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Bluthochdruck:", null, false); case HYPERTENSION: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Bluthochdruck:", null, null, null, null); case RENAL_INSUFFICIENCY_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Niereninsuffizienz/-erkrankung:", null, false); case RENAL_INSUFFICIENCY: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Niereninsuffizienz/-erkrankung:", null, null, null, null); case LIVER_DISEASE_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Lebererkrankung:", null, false); case LIVER_DISEASE: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Lebererkrankung:", null, null, null, null); case ANEMIA_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Anämie (Blutarmut):", null, false); case ANEMIA: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Anämie (Blutarmut):", null, null, null, null); case IMMUNE_MEDAITED_DISEASE_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Autoimmunerkrankung:", null, false); case IMMUNE_MEDAITED_DISEASE: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Autoimmunerkrankung:", null, null, null, null); case GESTATION_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "schwanger, stillen etc.", null, false); case GESTATION: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "schwanger, stillen etc.", null, null, null, null); case GESTATION_TYPE: return createSelectManyField(auth, name, inquiryQuestionsCategory, "schwanger, stillen etc.", null, false, new TreeMap<InputFieldValues, Boolean>() { { put(InputFieldValues.SCHWANGER, false); put(InputFieldValues.STILLEN, false); } }, null, null, null); case CONTRACEPTION_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Empfängnisverhütung:", null, false); case CONTRACEPTION: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Empfängnisverhütung:", null, null, null, null); case CONTRACEPTION_TYPE: return createSelectManyField(auth, name, inquiryQuestionsCategory, "Empfängnisverhütung:", null, true, new TreeMap<InputFieldValues, Boolean>() { { put(InputFieldValues.HORMONELL, false); put(InputFieldValues.MECHANISCH, false); put(InputFieldValues.INTRAUTERINPESSARE, false); put(InputFieldValues.CHEMISCH, false); put(InputFieldValues.OPERATIV, false); } }, null, null, null); case ALCOHOL_DRUG_ABUSE_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Missbrauch von Alkohol/Drogen:", null, false); case ALCOHOL_DRUG_ABUSE: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Missbrauch von Alkohol/Drogen:", null, null, null, null); case PSYCHIATRIC_CONDITION_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Psychiatrische Erkrankung:", null, false); case PSYCHIATRIC_CONDITION: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Psychiatrische Erkrankung:", null, null, null, null); case ALLERGY_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Allergien:", null, false); case ALLERGY: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Allergien:", null, null, null, null); case MEDICATION_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Medikamente:", null, false); case MEDICATION: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Medikamente:", null, null, null, null); case EYE_PROBLEMS_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Probleme mit den Augen:", null, false); case EYE_PROBLEMS: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Probleme mit den Augen:", null, null, null, null); case FEET_PROBLEMS_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Probleme mit den Füßen:", null, false); case FEET_PROBLEMS: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Probleme mit den Füßen:", null, null, null, null); case DIAGNOSTIC_FINDINGS_AVAILABLE_YN: return createCheckBoxField(auth, name, inquiryQuestionsCategory, "Haben Sie eventuell Befunde zu Hause?", null, false); case DIAGNOSTIC_FINDINGS_AVAILABLE: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Haben Sie eventuell Befunde zu Hause?", null, null, null, null); case GENERAL_STATE_OF_HEALTH: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Allgemeiner Gesundheitszustand:", null, null, null, null); case NOTE: return createMultiLineTextField(auth, name, inquiryQuestionsCategory, "Anmerkungen:", null, null, null, null); case SUBJECT_NUMBER: // [0-9]{4}: omit ^ and $ here for xeger return createSingleLineTextField(auth, name, probandListEntryTagCategory, "Subject Number:", null, null, "[0-9]{4}", "Vierstellige Zahl (mit führenden Nullen) erforderlich."); case IC_DATE: return createDateField(auth, name, probandListEntryTagCategory, "Informed Consent Date:", null, null, null, null, null); case SCREENING_DATE: return createDateField(auth, name, probandListEntryTagCategory, "Screening Date:", null, null, null, null, null); case LAB_NUMBER: return createSingleLineTextField(auth, name, probandListEntryTagCategory, "Lab Nummer:", null, null, "[0-9]{4}", "Vierstellige Zahl (mit führenden Nullen) erforderlich."); case RANDOM_NUMBER: return createSingleLineTextField(auth, name, probandListEntryTagCategory, "Random Number:", null, null, "[0-9]{3}", "Dreistellige Nummber (mit führenden Nullen) erforderlich."); case LETTER_TO_PHYSICIAN_SENT: return createCheckBoxField(auth, name, probandListEntryTagCategory, "Letter to physician sent:", null, false); case PARTICIPATION_LETTER_IN_MEDOCS: return createCheckBoxField(auth, name, probandListEntryTagCategory, "Participation letter in MR/Medocs:", null, false); case LETTER_TO_SUBJECT_AT_END_OF_STUDY: return createCheckBoxField(auth, name, probandListEntryTagCategory, "Letter to subject at end of study:", null, false); case COMPLETION_LETTER_IN_MEDOCS: return createCheckBoxField(auth, name, probandListEntryTagCategory, "Completion letter in MR/Medocs:", null, false); case BODY_HEIGHT: return createIntegerField(auth, name, inquiryQuestionsCategory, "Body Height (cm):", "", null, 50l, 300l, "Body height requires an integer value between 50 and 300 cm."); case BODY_WEIGHT: return createIntegerField(auth, name, inquiryQuestionsCategory, "Body Weight (kg):", "", null, 3l, 500l, "Body weight requires an integer value between 3 and 500 kg."); case BODY_MASS_INDEX: return createFloatField(auth, name, inquiryQuestionsCategory, "BMI (kg/m²):", "", null, 5f, 60f, "Body mass index requires a decimal value between 5.0 and 200.0 kg/m²."); case OBESITY: return createSelectOneRadioField(auth, name, inquiryQuestionsCategory, "Obesity:", "BMI < 18.5: shortweight\n" + "18.5-24.9: normal weight\n" + "25-29.9: overweight\n" + "30-34.9: adiposity degree I\n" + "35-39.9: adiposity degree II\n" + ">= 40: adiposity degree III (morbid)", true, new TreeMap<InputFieldValues, Boolean>() { { put(InputFieldValues.SHORTWEIGHT, false); put(InputFieldValues.NORMAL_WEIGHT, false); put(InputFieldValues.OVERWEIGHT, false); put(InputFieldValues.ADIPOSITY_DEGREE_I, false); put(InputFieldValues.ADIPOSITY_DEGREE_II, false); put(InputFieldValues.ADIPOSITY_DEGREE_III, false); } }); case EGFR: return createFloatField(auth, name, inquiryQuestionsCategory, "Estimated Glomerular Filtration Rate (ml/min):", "", null, 1f, 50f, "Estimated glomerular filtration rate requires a decimal value between 1.0 and 50.0 ml/min."); case ETHNICITY: return createSelectOneDropdownField(auth, name, inquiryQuestionsCategory, "Ethnicity:", null, new TreeMap<InputFieldValues, Boolean>() { { put(InputFieldValues.AMERICAN_INDIAN_OR_ALASKA_NATIVE, false); put(InputFieldValues.ASIAN, false); put(InputFieldValues.BLACK, false); put(InputFieldValues.NATIVE_HAWAIIAN_OR_OTHER_PACIFIC_ISLANDER, false); put(InputFieldValues.WHITE, false); } }); case SERUM_CREATININ_CONCENTRATION: return createFloatField(auth, name, inquiryQuestionsCategory, "Serum Creatinin Concentration (mg/dl):", "", null, 1f, 50f, "Serum creatinin concentration requires a decimal value between 1.0 and 50.0 mg/dl."); // range? case HBA1C_PERCENT: return createFloatField(auth, name, inquiryQuestionsCategory, "HbA1C (%):", "", null, 2.5f, 15.0f, "HbA1C in percent requires a decimal value between 2.5 and 15.0 %."); case HBA1C_MMOLPERMOL: return createFloatField(auth, name, inquiryQuestionsCategory, "HbA1C (mmol/mol):", "", null, 20.0f, 130.0f, "HbA1C in mmol/mol requires a decimal value between 20.0 and 130.0 mmol/mol."); case MANNEQUIN: return createSketchField(auth, name, inquiryQuestionsCategory, "Joints:", "", "mannequin.png", new TreeMap<InputFieldValues, Stroke>() { { put(InputFieldValues.SHOULDER_RIGHT, new Stroke("M111.91619,64.773336L134.22667,64.773336L134.22667,86.512383L111.91619,86.512383Z")); put(InputFieldValues.SHOULDER_LEFT, new Stroke("M196.2019,66.916193L218.51238,66.916193L218.51238,88.65524L196.2019,88.65524Z")); put(InputFieldValues.ELLBOW_RIGHT, new Stroke("M114.05904,111.20191L136.36952,111.20191L136.36952,132.94095L114.05904,132.94095Z")); put(InputFieldValues.ELLBOW_LEFT, new Stroke("M197.63047,113.34477L219.94095,113.34477L219.94095,135.08381L197.63047,135.08381Z")); put(InputFieldValues.WRIST_RIGHT, new Stroke("M94.773327,156.9162L117.08381,156.9162L117.08381,178.65524L94.773327,178.65524Z")); put(InputFieldValues.WRIST_LEFT, new Stroke("M215.48761,161.20191L237.7981,161.20191L237.7981,182.94095L215.48761,182.94095Z")); put(InputFieldValues.THUMB_BASE_RIGHT, new Stroke("M29.891238,214.89125L49.823043,214.89125L49.823043,254.9659L29.891238,254.9659Z")); put(InputFieldValues.THUMB_MIDDLE_RIGHT, new Stroke("M9.0200169,246.16289L29.265697,246.16289L29.265697,265.83713L9.0200169,265.83713Z")); put(InputFieldValues.THUMB_BASE_LEFT, new Stroke("M282.0341,217.03411L301.9659,217.03411L301.9659,257.10876L282.0341,257.10876Z")); put(InputFieldValues.THUMB_MIDDLE_LEFT, new Stroke("M301.87716,250.4486L322.12284,250.4486L322.12284,270.12284L301.87716,270.12284Z")); put(InputFieldValues.INDEX_FINGER_BASE_RIGHT, new Stroke("M28.305731,271.87717L48.551411,271.87717L48.551411,291.55141L28.305731,291.55141Z")); put(InputFieldValues.INDEX_FINGER_MIDDLE_RIGHT, new Stroke("M22.591445,294.73431L42.837125,294.73431L42.837125,314.40855L22.591445,314.40855Z")); put(InputFieldValues.MIDDLE_FINGER_BASE_RIGHT, new Stroke("M48.305731,276.16288L68.551411,276.16288L68.551411,295.83712L48.305731,295.83712Z")); put(InputFieldValues.MIDDLE_FINGER_MIDDLE_RIGHT, new Stroke("M44.734302,298.30574L64.979982,298.30574L64.979982,317.97998L44.734302,317.97998Z")); put(InputFieldValues.RING_FINGER_BASE_RIGHT, new Stroke("M66.162873,279.02003L86.408553,279.02003L86.408553,298.69427L66.162873,298.69427Z")); put(InputFieldValues.RING_FINGER_MIDDLE_RIGHT, new Stroke("M65.448587,302.59146L85.694267,302.59146L85.694267,322.2657L65.448587,322.2657Z")); put(InputFieldValues.LITTLE_FINGER_BASE_RIGHT, new Stroke("M85.448587,276.16289L105.69427,276.16289L105.69427,295.83713L85.448587,295.83713Z")); put(InputFieldValues.LITTLE_FINGER_MIDDLE_RIGHT, new Stroke("M87.591444,299.02003L107.83713,299.02003L107.83713,318.69427L87.591444,318.69427Z")); put(InputFieldValues.INDEX_FINGER_BASE_LEFT, new Stroke("M281.16287,274.73432L301.40856,274.73432L301.40856,294.40856L281.16287,294.40856Z")); put(InputFieldValues.INDEX_FINGER_MIDDLE_LEFT, new Stroke("M286.16287,296.16289L306.40856,296.16289L306.40856,315.83713L286.16287,315.83713Z")); put(InputFieldValues.MIDDLE_FINGER_BASE_LEFT, new Stroke("M262.59144,279.73432L282.83713,279.73432L282.83713,299.40856L262.59144,299.40856Z")); put(InputFieldValues.MIDDLE_FINGER_MIDDLE_LEFT, new Stroke("M264.02001,301.87718L284.2657,301.87718L284.2657,321.55142L264.02001,321.55142Z")); put(InputFieldValues.RING_FINGER_BASE_LEFT, new Stroke("M244.7343,282.59147L264.97999,282.59147L264.97999,302.26571L244.7343,302.26571Z")); put(InputFieldValues.RING_FINGER_MIDDLE_LEFT, new Stroke("M244.02001,304.02004L264.2657,304.02004L264.2657,323.69428L244.02001,323.69428Z")); put(InputFieldValues.LITTLE_FINGER_BASE_LEFT, new Stroke("M224.7343,279.02004L244.97999,279.02004L244.97999,298.69428L224.7343,298.69428Z")); put(InputFieldValues.LITTLE_FINGER_MIDDLE_LEFT, new Stroke("M224.02001,301.1629L244.2657,301.1629L244.2657,320.83714L224.02001,320.83714Z")); put(InputFieldValues.KNEE_RIGHT, new Stroke("M133.4355,241.29267L161.27879,241.29267L161.27879,267.13594L133.4355,267.13594Z")); put(InputFieldValues.KNEE_LEFT, new Stroke("M166.29264,242.00696L194.13593,242.00696L194.13593,267.85023L166.29264,267.85023Z")); } }, 0, 28, "Mark up to 28 joints."); case VAS: return createSketchField(auth, name, inquiryQuestionsCategory, "Visual Analogue Scale:", "", "vas.png", new TreeMap<InputFieldValues, Stroke>() { { final int VAS_STEPS = 10; final float VAS_MAX_VALUE = 100.0f; final float VAS_X_OFFSET = 10.0f; final float VAS_LENGTH = 382.0f; final String[] VAS_COLORS = new String[] { "#24FF00", "#58FF00", "#8DFF00", "#C2FF00", "#F7FF00", "#FFD300", "#FF9E00", "#FF6900", "#FF3400", "#FF0000" }; for (int i = 0; i < VAS_STEPS; i++) { float valueFrom = i * VAS_MAX_VALUE / VAS_STEPS; float valueTo = (i + 1) * VAS_MAX_VALUE / VAS_STEPS; float value = (valueFrom + valueTo) / 2; float x1 = VAS_X_OFFSET + i * VAS_LENGTH / VAS_STEPS; float x2 = VAS_X_OFFSET + (i + 1) * VAS_LENGTH / VAS_STEPS; int colorIndex = i * VAS_COLORS.length / VAS_STEPS; put(InputFieldValues.valueOf(String.format("VAS_%d", i + 1)), new Stroke(VAS_COLORS[colorIndex], "M" + x1 + ",10L" + x2 + ",10L" + x2 + ",50L" + x1 + ",50Z", Float.toString(value))); } } }, 1, 1, "Mark exactly one position."); case ESR: return createFloatField(auth, name, inquiryQuestionsCategory, "Erythrocyte Sedimentation Rate (mm/h):", "", null, 1.0f, 30.0f, "Erythrocyte sedimentation rate requires a decimal value between 1.0 and 30.0 mm/h."); case DAS28: return createFloatField(auth, name, inquiryQuestionsCategory, "Disease Activity Score 28:", "", null, 2.0f, 10.0f, "Disease activity score 28 requires a decimal value between 2.0 and 10.0."); case DISTANCE: return createFloatField(auth, name, inquiryQuestionsCategory, "Distance (km):", "Travel distance from trial site to subject home address according to Google Maps.", null, 0.1f, 21000.0f, "Distance requires a decimal value between 0.1 and 21000.0 km."); case ALPHA_ID: return createSingleLineTextField(auth, name, inquiryQuestionsCategory, "Diagnosis Alpha ID Synonym:", null, null, null, null); case STRING_SINGLELINE: return createSingleLineTextField(auth, name, ecrfFieldCategory, "singleline text:", null, null, null, null); case STRING_MULTILINE: return createMultiLineTextField(auth, name, ecrfFieldCategory, "multiline text:", null, null, null, null); case FLOAT: return createFloatField(auth, name, ecrfFieldCategory, "decimal value:", "some decimal value", null, null, null, null); case INTEGER: return createIntegerField(auth, name, ecrfFieldCategory, "integer value:", "some integer value", null, null, null, null); case DIAGNOSIS_START: return createDateField(auth, name, inquiryQuestionsCategory, "Diagnosis Start:", null, null, null, null, null); case DIAGNOSIS_END: return createDateField(auth, name, inquiryQuestionsCategory, "Diagnosis End:", null, null, null, null, null); case DIAGNOSIS_COUNT: return createIntegerField(auth, name, ecrfFieldCategory, "Number of diagnoses:", null, null, 1l, null, "at least one diagnosis required"); default: return null; } } } private InputFieldSelectionSetValue getInputFieldValue(Long fieldId, InputFieldValues value) { return inputFieldSelectionSetValueDao.findByFieldNameL10nKeyLocalized(fieldId, value.toString(), false).iterator().next(); } private ProbandListStatusTypeVO getNextProbandListStatusType(AuthenticationVO auth, ProbandListEntryOutVO probandListEntry, boolean allowPassed, HashSet<ProbandListStatusTypeVO> passedProbandListStatus, HashMap<String, ProbandListStatusTypeVO> probandListStatusTypeMap) throws Exception { ProbandListStatusTypeVO newState = null; Collection<ProbandListStatusTypeVO> newStates = selectionSetService.getProbandListStatusTypeTransitions(auth, probandListEntry.getLastStatus().getStatus().getId()); if (newStates != null && newStates.size() > 0) { HashSet<Long> newStateIds = new HashSet<Long>(newStates.size()); Iterator<ProbandListStatusTypeVO> it = newStates.iterator(); while (it.hasNext()) { newStateIds.add(it.next().getId()); } if (!allowPassed) { while (newState == null) { newState = getRandomElement(newStates); newState = probandListStatusMarkov(newState, probandListStatusTypeMap); if (!newStateIds.contains(newState.getId())) { newState = null; } else if (passedProbandListStatus.contains(newState)) { newState = null; } } } else { while (newState == null) { newState = getRandomElement(newStates); newState = probandListStatusMarkov(newState, probandListStatusTypeMap); if (!newStateIds.contains(newState.getId())) { newState = null; } } } } return newState; } private AuthenticationVO getRandomAuth() { return getRandomAuth(random.nextInt(departmentCount)); } private AuthenticationVO getRandomAuth(int departmentNum) { int userNum = random.nextInt(usersPerDepartmentCount); return new AuthenticationVO(getUsername(departmentNum, userNum), getUserPassword(departmentNum, userNum), null, "localhost"); } private AuthenticationVO getRandomAuth(long departmentId) { String departmentL10nKey = departmentDao.load(departmentId).getNameL10nKey(); int departmentNum = Integer.parseInt(departmentL10nKey.replaceFirst("department " + Pattern.quote(prefix) + " ", "")) - 1; return getRandomAuth(departmentNum); } private Date getRandomAutoDeleteDeadline() { return getRandomDate((new GregorianCalendar(year, 0, 1)).getTime(), (new GregorianCalendar(year, 11, 31)).getTime()); } private boolean getRandomBoolean() { return random.nextBoolean(); } private boolean getRandomBoolean(int p) { if (p <= 0) { return false; } else if (p >= 100) { return true; } else { return random.nextDouble() < ((p) / 100.0d); } } private Date getRandomCourseStop() { return getRandomDate((new GregorianCalendar(year, 0, 1)).getTime(), (new GregorianCalendar(year, 11, 31)).getTime()); } private Date getRandomDate(Date minDate, Date maxDate) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(minDate == null ? (new GregorianCalendar(1900, 0, 1)).getTime() : minDate); cal = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0); cal.add(Calendar.DAY_OF_YEAR, random.nextInt(DateCalc.dateDeltaDays(minDate == null ? (new GregorianCalendar(1900, 0, 1)).getTime() : minDate, maxDate == null ? (new GregorianCalendar(year, 11, 31)).getTime() : maxDate))); return cal.getTime(); } private Date getRandomDateAround(Date date, int maxDaysBefore, int maxDaysAfter) { return DateCalc.addInterval(date, VariablePeriod.EXPLICIT, (long) (getRandomBoolean() ? random.nextInt(maxDaysAfter + 1) : (-1 * random.nextInt(maxDaysBefore + 1)))); } private Date getRandomDateOfBirth() { return getRandomDate((new GregorianCalendar(year - 90, 0, 1)).getTime(), (new GregorianCalendar(year - 20, 0, 1)).getTime()); } private Long getRandomDepartmentId() throws Exception { return getDepartmentId(random.nextInt(departmentCount)); } private <E> E getRandomElement(ArrayList<E> list) { if (list != null && list.size() > 0) { return list.get(random.nextInt(list.size())); } return null; } private <E> E getRandomElement(Collection<E> collection) { E result = null; if (collection != null && collection.size() > 0) { int index = random.nextInt(collection.size()); Iterator<E> it = collection.iterator(); for (int i = 0; i <= index; i++) { result = it.next(); } } return result; } private <E> E getRandomElement(E[] array) { if (array != null && array.length > 0) { return array[random.nextInt(array.length)]; } return null; } private float getRandomFloat(Float lowerLimit, Float upperLimit) { float lower = (lowerLimit == null ? 0f : lowerLimit.floatValue()); return lower + random.nextFloat() * ((upperLimit == null ? Float.MAX_VALUE : upperLimit.longValue()) - lower); } private long getRandomLong(Long lowerLimit, Long upperLimit) { long lower = (lowerLimit == null ? 0l : lowerLimit.longValue()); return lower + nextLong(random, (upperLimit == null ? Integer.MAX_VALUE : upperLimit.longValue()) - lower); } private Date getRandomScreeningDate() { return getRandomDate((new GregorianCalendar(year, 0, 1)).getTime(), (new GregorianCalendar(year, 11, 31)).getTime()); } private Date getRandomTime(Date minTime, Date maxTime) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(minTime == null ? (new GregorianCalendar(1970, 0, 1, 0, 0, 0)).getTime() : minTime); cal.setTimeInMillis(cal.getTimeInMillis() + nextLong(random, (maxTime == null ? (new GregorianCalendar(1970, 0, 1, 23, 59, 59)).getTime() : maxTime).getTime() - cal.getTimeInMillis())); return cal.getTime(); } private Date getRandomTimestamp(Date minTimestamp, Date maxTimestamp) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(minTimestamp == null ? (new GregorianCalendar(1900, 0, 1, 0, 0, 0)).getTime() : minTimestamp); cal.setTimeInMillis(cal.getTimeInMillis() + nextLong(random, (maxTimestamp == null ? (new GregorianCalendar(year, 11, 31)).getTime() : maxTimestamp).getTime() - cal.getTimeInMillis())); return cal.getTime(); } private Long getRandomUserId() { return getRandomUserId(random.nextInt(departmentCount)); } private Long getRandomUserId(int departmentNum) { return getUserId(departmentNum, random.nextInt(usersPerDepartmentCount)); } private <E> ArrayList<E> getUniqueRandomElements(ArrayList<E> list, int n) { if (list != null) { int listSize = list.size(); if (listSize > 0 && n > 0) { if (listSize <= n) { return new ArrayList<E>(list); } else { HashSet<E> result = new HashSet<E>(n); while (result.size() < n && result.size() < listSize) { result.add(list.get(random.nextInt(listSize))); } return new ArrayList<E>(result); } } else { return new ArrayList<E>(); } } return null; } private Long getUserId(int departmentNum, int userNum) { return userDao.searchUniqueName(getUsername(departmentNum, userNum)).getId(); } private String getUsername(int departmentNum, int num) { return String.format("user_%s_%d_%d", prefix, departmentNum + 1, num + 1); } private String getUserPassword(int departmentNum, int num) { return getUsername(departmentNum, num); } private long nextLong(Random rng, long n) { // error checking and 2^x checking removed for simplicity. if (n <= 0) { throw new IllegalArgumentException("n must be positive"); } // if ((n & -n) == n) // i.e., n is a power of 2 // return (int)((n * (long)next(31)) >> 31); long bits, val; do { bits = (rng.nextLong() << 1) >>> 1; val = bits % n; } while (bits - val + (n - 1) < 0L); return val; } private Collection performSearch(AuthenticationVO auth, SearchCriteria criteria, PSFVO psf, Integer maxInstances) throws Throwable { auth = (auth == null ? getRandomAuth() : auth); CriteriaInVO newCriteria = new CriteriaInVO(); HashSet<CriterionInVO> newCriterions = new HashSet<CriterionInVO>(); ExecUtil.criteriaOutToIn(newCriteria, newCriterions, getCriteria(auth, criteria)); Collection result; String type; switch (newCriteria.getModule()) { case INVENTORY_DB: result = searchService.searchInventory(auth, newCriteria, newCriterions, maxInstances, psf); type = "inventory"; break; case STAFF_DB: result = searchService.searchStaff(auth, newCriteria, newCriterions, maxInstances, psf); type = "staff"; break; case COURSE_DB: result = searchService.searchCourse(auth, newCriteria, newCriterions, maxInstances, psf); type = "course"; break; case TRIAL_DB: result = searchService.searchTrial(auth, newCriteria, newCriterions, psf); type = "trial"; break; case PROBAND_DB: result = searchService.searchProband(auth, newCriteria, newCriterions, maxInstances, psf); type = "proband"; break; case INPUT_FIELD_DB: result = searchService.searchInputField(auth, newCriteria, newCriterions, psf); type = "inputfield"; break; case USER_DB: result = searchService.searchUser(auth, newCriteria, newCriterions, maxInstances, psf); type = "user"; break; case MASS_MAIL_DB: result = searchService.searchMassMail(auth, newCriteria, newCriterions, psf); type = "massmail"; break; default: result = null; type = null; } jobOutput.println("search '" + criteria.toString() + "' returned " + result.size() + (psf != null ? " of " + psf.getRowCount() : "") + " " + type + " items"); return result; } private ProbandListStatusTypeVO probandListStatusMarkov(ProbandListStatusTypeVO state, HashMap<String, ProbandListStatusTypeVO> probandListStatusTypeMap) throws Exception { boolean negative = getRandomBoolean(10); if ("cancelled".equals(state.getNameL10nKey())) { return negative ? state : probandListStatusTypeMap.get("acceptance"); } else if ("screening_failure".equals(state.getNameL10nKey())) { return negative ? state : probandListStatusTypeMap.get("screening_ok"); } else if ("dropped_out".equals(state.getNameL10nKey())) { return negative ? state : probandListStatusTypeMap.get("completed"); } return state; } public void setContext(ApplicationContext context) { this.context = context; } public void setJobOutput(JobOutput jobOutput) { this.jobOutput = jobOutput; } private void setRandomInquiryValue(InquiryOutVO inquiry, InquiryValueInVO inquiryValue) { if (!inquiry.isOptional() || getRandomBoolean()) { HashSet<Long> selectionSetValues = new HashSet<Long>(); switch (inquiry.getField().getFieldType().getType()) { case CHECKBOX: inquiryValue.setBooleanValue(inquiry.isDisabled() ? inquiry.getField().getBooleanPreset() : getRandomBoolean()); break; case SELECT_ONE_DROPDOWN: case SELECT_ONE_RADIO_H: case SELECT_ONE_RADIO_V: if (inquiry.isDisabled()) { Iterator<InputFieldSelectionSetValueOutVO> selectionSetValueIt = inquiry.getField().getSelectionSetValues().iterator(); while (selectionSetValueIt.hasNext()) { InputFieldSelectionSetValueOutVO selectionSetValue = selectionSetValueIt.next(); if (selectionSetValue.isPreset()) { selectionSetValues.add(selectionSetValue.getId()); break; } } } else { selectionSetValues.add(getRandomElement(inquiry.getField().getSelectionSetValues()).getId()); } inquiryValue.setSelectionValueIds(new ArrayList<Long>(selectionSetValues)); break; case SELECT_MANY_H: case SELECT_MANY_V: if (inquiry.isDisabled()) { Iterator<InputFieldSelectionSetValueOutVO> selectionSetValueIt = inquiry.getField().getSelectionSetValues().iterator(); while (selectionSetValueIt.hasNext()) { InputFieldSelectionSetValueOutVO selectionSetValue = selectionSetValueIt.next(); if (selectionSetValue.isPreset()) { selectionSetValues.add(selectionSetValue.getId()); } } } else { for (int i = 0; i <= random.nextInt(inquiry.getField().getSelectionSetValues().size()); i++) { selectionSetValues.add(getRandomElement(inquiry.getField().getSelectionSetValues()).getId()); } } inquiryValue.setSelectionValueIds(new ArrayList<Long>(selectionSetValues)); break; case SINGLE_LINE_TEXT: case MULTI_LINE_TEXT: if (inquiry.isDisabled()) { inquiryValue.setTextValue(inquiry.getField().getTextPreset()); } else { String regExp = inquiry.getField().getRegExp(); if (regExp != null && regExp.length() > 0) { Xeger generator = new Xeger(regExp); inquiryValue.setTextValue(generator.generate()); } else { inquiryValue.setTextValue("random text"); } } break; case INTEGER: inquiryValue.setLongValue(inquiry.isDisabled() ? inquiry.getField().getLongPreset() : getRandomLong(inquiry.getField().getLongLowerLimit(), inquiry.getField() .getLongUpperLimit())); break; case FLOAT: inquiryValue.setFloatValue(inquiry.isDisabled() ? inquiry.getField().getFloatPreset() : getRandomFloat(inquiry.getField().getFloatLowerLimit(), inquiry .getField().getFloatUpperLimit())); break; case DATE: inquiryValue.setDateValue(inquiry.isDisabled() ? inquiry.getField().getDatePreset() : getRandomDate(inquiry.getField().getMinDate(), inquiry.getField() .getMaxDate())); break; case TIME: inquiryValue.setTimeValue(inquiry.isDisabled() ? inquiry.getField().getTimePreset() : getRandomTime(inquiry.getField().getMinTime(), inquiry.getField() .getMaxTime())); break; case TIMESTAMP: inquiryValue.setTimestampValue(inquiry.isDisabled() ? inquiry.getField().getTimestampPreset() : getRandomTimestamp(inquiry.getField().getMinTimestamp(), inquiry.getField().getMaxTimestamp())); break; default: } } } private void setRandomProbandListEntryTagValue(ProbandListEntryTagOutVO probandListEntryTag, ProbandListEntryTagValueInVO probandListEntryTagValue) { if (!probandListEntryTag.isOptional() || getRandomBoolean()) { HashSet<Long> selectionSetValues = new HashSet<Long>(); switch (probandListEntryTag.getField().getFieldType().getType()) { case CHECKBOX: probandListEntryTagValue.setBooleanValue(probandListEntryTag.isDisabled() ? probandListEntryTag.getField().getBooleanPreset() : getRandomBoolean()); break; case SELECT_ONE_DROPDOWN: case SELECT_ONE_RADIO_H: case SELECT_ONE_RADIO_V: if (probandListEntryTag.isDisabled()) { Iterator<InputFieldSelectionSetValueOutVO> selectionSetValueIt = probandListEntryTag.getField().getSelectionSetValues().iterator(); while (selectionSetValueIt.hasNext()) { InputFieldSelectionSetValueOutVO selectionSetValue = selectionSetValueIt.next(); if (selectionSetValue.isPreset()) { selectionSetValues.add(selectionSetValue.getId()); break; } } } else { selectionSetValues.add(getRandomElement(probandListEntryTag.getField().getSelectionSetValues()).getId()); } probandListEntryTagValue.setSelectionValueIds(new ArrayList<Long>(selectionSetValues)); break; case SELECT_MANY_H: case SELECT_MANY_V: if (probandListEntryTag.isDisabled()) { Iterator<InputFieldSelectionSetValueOutVO> selectionSetValueIt = probandListEntryTag.getField().getSelectionSetValues().iterator(); while (selectionSetValueIt.hasNext()) { InputFieldSelectionSetValueOutVO selectionSetValue = selectionSetValueIt.next(); if (selectionSetValue.isPreset()) { selectionSetValues.add(selectionSetValue.getId()); } } } else { for (int i = 0; i <= random.nextInt(probandListEntryTag.getField().getSelectionSetValues().size()); i++) { selectionSetValues.add(getRandomElement(probandListEntryTag.getField().getSelectionSetValues()).getId()); } } probandListEntryTagValue.setSelectionValueIds(new ArrayList<Long>(selectionSetValues)); break; case SINGLE_LINE_TEXT: case MULTI_LINE_TEXT: if (probandListEntryTag.isDisabled()) { probandListEntryTagValue.setTextValue(probandListEntryTag.getField().getTextPreset()); } else { String regExp = probandListEntryTag.getField().getRegExp(); if (regExp != null && regExp.length() > 0) { Xeger generator = new Xeger(regExp); probandListEntryTagValue.setTextValue(generator.generate()); } else { probandListEntryTagValue.setTextValue("random text"); } } break; case INTEGER: probandListEntryTagValue.setLongValue(probandListEntryTag.isDisabled() ? probandListEntryTag.getField().getLongPreset() : getRandomLong(probandListEntryTag .getField().getLongLowerLimit(), probandListEntryTag.getField().getLongUpperLimit())); break; case FLOAT: probandListEntryTagValue.setFloatValue(probandListEntryTag.isDisabled() ? probandListEntryTag.getField().getFloatPreset() : getRandomFloat(probandListEntryTag .getField().getFloatLowerLimit(), probandListEntryTag.getField().getFloatUpperLimit())); break; case DATE: probandListEntryTagValue.setDateValue(probandListEntryTag.isDisabled() ? probandListEntryTag.getField().getDatePreset() : getRandomDate(probandListEntryTag .getField().getMinDate(), probandListEntryTag.getField().getMaxDate())); break; case TIME: probandListEntryTagValue.setTimeValue(probandListEntryTag.isDisabled() ? probandListEntryTag.getField().getTimePreset() : getRandomTime(probandListEntryTag .getField().getMinTime(), probandListEntryTag.getField().getMaxTime())); break; case TIMESTAMP: probandListEntryTagValue.setTimestampValue(probandListEntryTag.isDisabled() ? probandListEntryTag.getField().getTimestampPreset() : getRandomTimestamp( probandListEntryTag.getField().getMinTimestamp(), probandListEntryTag.getField().getMaxTimestamp())); break; default: } } } private boolean updateProbandListStatusEntryRealTimestamp(ProbandListStatusEntryOutVO probandListStatusEntryVO, ProbandGroupOutVO screeningGroup, HashMap<Long, ArrayList<VisitScheduleItemOutVO>> visitScheduleItemPerGroupMap, int statusHistoryLength) throws Exception { boolean result = true; VisitScheduleItemOutVO visitScheduleItem; if (probandListStatusEntryVO.getStatus().isInitial()) { visitScheduleItem = getRandomElement(visitScheduleItemPerGroupMap.get(screeningGroup.getId())); } else { ArrayList<VisitScheduleItemOutVO> visitScheduleItems = visitScheduleItemPerGroupMap.get(probandListStatusEntryVO.getListEntry().getGroup().getId()); if (statusHistoryLength >= visitScheduleItems.size()) { result = false; visitScheduleItem = visitScheduleItems.get(visitScheduleItems.size() - 1); } else { visitScheduleItem = visitScheduleItems.get(statusHistoryLength); } } ProbandListStatusEntry probandListStatusEntry = probandListStatusEntryDao.load(probandListStatusEntryVO.getId()); probandListStatusEntry.setRealTimestamp(new Timestamp(visitScheduleItem.getStop().getTime())); probandListStatusEntryDao.update(probandListStatusEntry); return result; } }
show visit appointments in calendar - adopt demo data generator
core/src/exec/java/org/phoenixctms/ctsms/executable/DemoDataProvider.java
show visit appointments in calendar - adopt demo data generator
<ide><path>ore/src/exec/java/org/phoenixctms/ctsms/executable/DemoDataProvider.java <ide> <ide> private Collection<DutyRosterTurnOutVO> createDuty(AuthenticationVO auth, ArrayList<Staff> staff, TrialOutVO trial, Date start, Date stop, String title) throws Exception { <ide> auth = (auth == null ? getRandomAuth() : auth); <del> Collection<VisitScheduleItemOutVO> visitScheduleItems = trialService.getVisitScheduleItemInterval(auth, trial.getId(), null, null, null, start, stop, null, false); <add> Collection<VisitScheduleItemOutVO> visitScheduleItems = trialService.getVisitScheduleItems(auth, trial.getId(), null, start, stop, null, false); <ide> DutyRosterTurnInVO newDutyRosterTurn = new DutyRosterTurnInVO(); <ide> newDutyRosterTurn.setSelfAllocatable(staff.size() > 0); <ide> newDutyRosterTurn.setStart(start);
Java
mit
5bfcaf4832971a01f10610dd3cddcdc897342cbe
0
PaulKlinger/Sprog-App
package com.almoturg.sprog; import android.app.DownloadManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.IntentFilter; import android.content.SharedPreferences; import android.net.Uri; import android.os.Environment; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.content.Intent; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import android.util.Log; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.TimeZone; import static com.almoturg.sprog.SprogApplication.poems; public class MainActivity extends AppCompatActivity { public static final String TAG = "Sprog"; private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; public String sort_order = "Date"; private BroadcastReceiver onComplete; public TextView statusView; private Tracker mTracker; private boolean updating = false; // after processing set last update time if this is true private boolean processing = false; // These are the times when an update should be available on the server static int FIRST_UPDATE_HOUR = 2; static int SECOND_UPDATE_HOUR = 14; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SprogApplication application = (SprogApplication) getApplication(); mTracker = application.getDefaultTracker(); Toolbar myToolbar = (Toolbar) findViewById(R.id.main_toolbar); setSupportActionBar(myToolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); myToolbar.setTitle(null); statusView = (TextView) findViewById(R.id.update_status); Spinner sortSpinner = (Spinner) findViewById(R.id.sort_spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.sort_orders, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sortSpinner.setAdapter(adapter); sortSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (!processing) { String selectedItem = parent.getItemAtPosition(position).toString(); sort_order = selectedItem; sortPoems(); } } public void onNothingSelected(AdapterView<?> parent) { } }); mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view); // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView mRecyclerView.setHasFixedSize(true); // use a linear layout manager mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); } @Override protected void onStart() { super.onStart(); mTracker.setScreenName("PoemsList"); mTracker.send(new HitBuilders.ScreenViewBuilder().build()); autoUpdate(); } private void autoUpdate() { SharedPreferences prefs = getPreferences(MODE_PRIVATE); long last_update_tstamp = prefs.getLong("LAST_UPDATE_TIME", -1); File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "poems.json"); if (last_update_tstamp == -1 || !file.exists()) { updatePoems(null); } else { Log.i(TAG, "Checking if it's time to update"); Log.i(TAG, String.format("last update time %d", last_update_tstamp)); Calendar last_update_cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC")); last_update_cal.setTimeInMillis(last_update_tstamp); long diff_in_ms = now.getTimeInMillis() - last_update_tstamp; long ms_today = now.get(Calendar.HOUR_OF_DAY) * 60 * 60 * 1000 + now.get(Calendar.MINUTE) * 60 * 1000 + now.get(Calendar.SECOND) * 1000 + now.get(Calendar.MILLISECOND); if ( (now.get(Calendar.HOUR_OF_DAY) >= FIRST_UPDATE_HOUR && diff_in_ms > ms_today - FIRST_UPDATE_HOUR * 60 * 60 * 1000 ) || (now.get(Calendar.HOUR_OF_DAY) >= SECOND_UPDATE_HOUR && diff_in_ms > ms_today - SECOND_UPDATE_HOUR * 60 * 60 * 1000) ) { updatePoems(null); } else if (poems == null) { processPoems(); } else { // TODO: This really has nothing to do with autoupdate, should put somewhere else... mAdapter = new MyAdapter(poems, this); mRecyclerView.setAdapter(mAdapter); statusView.setText(String.format("%d poems", poems.size())); } } } private void sortPoems() { if (sort_order.equals("Date")) { Collections.sort(poems, new Comparator<Poem>() { @Override public int compare(Poem p1, Poem p2) { return (int) (p2.timestamp - p1.timestamp); } }); } else if (sort_order.equals("Score")) { Collections.sort(poems, new Comparator<Poem>() { @Override public int compare(Poem p1, Poem p2) { return (p2.score - p1.score); } }); } else if (sort_order.equals("Gold")) { Collections.sort(poems, new Comparator<Poem>() { @Override public int compare(Poem p1, Poem p2) { return (p2.gold - p1.gold); } }); } mAdapter.notifyDataSetChanged(); } public void processPoems() { processing = true; sort_order = "Date"; ((Spinner) findViewById(R.id.sort_spinner)).setSelection(0); // 0 is Date (is there a better way to do this??) statusView.setText("processing"); poems = new ArrayList<>(); mAdapter = new MyAdapter(poems, this); mRecyclerView.setAdapter(mAdapter); new ParsePoemsTask(this).execute(this); } public void addPoems(List<Poem> poems_set) { poems.addAll(poems_set); statusView.setText(String.format("%d poems", poems.size())); mAdapter.notifyDataSetChanged(); } public void finishedProcessing(boolean status) { if (updating) { updating = false; if (poems.size() > 1000) { SharedPreferences prefs = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC")); editor.putLong("LAST_UPDATE_TIME", now.getTimeInMillis()); editor.apply(); } } if (!status) { statusView.setText("error"); } processing = false; } public void updatePoems(View view) { if (onComplete != null) { return; } updating = true; File poems_file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "poems.json"); File poems_old_file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "poems_old.json"); if (poems_file.exists()) { poems_file.renameTo(poems_old_file); } String url = "https://almoturg.com/poems.json"; DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setDescription("Sprog poems"); request.setTitle("Sprog"); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, "poems.json"); // get download service and enqueue file DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); onComplete = new BroadcastReceiver() { public void onReceive(Context ctxt, Intent intent) { statusView.setText("poems downloaded"); processPoems(); unregisterReceiver(onComplete); onComplete = null; } }; registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); statusView.setText("loading poems"); manager.enqueue(request); } } class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements FastScrollRecyclerView.SectionedAdapter { private Context context; private List<Poem> poems; private Calendar cal; // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public int position; public TextView poem_content; public CardView view; public ViewHolder(View v) { super(v); v.setOnClickListener(this); this.poem_content = (TextView) v.findViewById(R.id.content); this.view = (CardView) v; } @Override public void onClick(View v) { if (poem_content.getEllipsize() == null) { Intent intent = new Intent(context, PoemActivity.class); intent.putExtra("POEM_ID", position); context.startActivity(intent); } else { poem_content.setEllipsize(null); poem_content.setMaxLines(Integer.MAX_VALUE); } } } // Provide a suitable constructor (depends on the kind of dataset) MyAdapter(List<Poem> poems, Context context) { this.poems = poems; this.context = context; this.cal = Calendar.getInstance(Locale.ENGLISH); } // Create new views (invoked by the layout manager) @Override public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.poem_row, parent, false); // set the view's size, margins, paddings and layout parameters ViewHolder vh = new ViewHolder(v); return vh; } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(ViewHolder holder, int position) { // - get element from your dataset at this position // - replace the contents of the view with that element Poem poem = (poems.get(position)); holder.position = position; holder.poem_content.setEllipsize(TextUtils.TruncateAt.END); holder.poem_content.setMaxLines(1); Util.update_poem_row(poem, holder.view, false, true, context); } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return poems.size(); } @NonNull @Override public String getSectionName(int position) { if (((MainActivity) context).sort_order.equals("Date")) { cal.setTimeInMillis((long) poems.get(position).timestamp * 1000); return DateFormat.format("yyyy-MM", cal).toString(); } else if (((MainActivity) context).sort_order.equals("Score")) { return Integer.toString(poems.get(position).score); } else if (((MainActivity) context).sort_order.equals("Gold")) { return Integer.toString(poems.get(position).gold); } return ""; } }
app/src/main/java/com/almoturg/sprog/MainActivity.java
package com.almoturg.sprog; import android.app.DownloadManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.IntentFilter; import android.content.SharedPreferences; import android.net.Uri; import android.os.Environment; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.content.Intent; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import android.util.Log; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.TimeZone; import static com.almoturg.sprog.SprogApplication.poems; public class MainActivity extends AppCompatActivity { public static final String TAG = "Sprog"; private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; public String sort_order = "Date"; private BroadcastReceiver onComplete; public TextView statusView; private Tracker mTracker; private boolean updating = false; // after processing set last update time if this is true private boolean processing = false; // These are the times when an update should be available on the server static int FIRST_UPDATE_HOUR = 2; static int SECOND_UPDATE_HOUR = 14; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SprogApplication application = (SprogApplication) getApplication(); mTracker = application.getDefaultTracker(); Toolbar myToolbar = (Toolbar) findViewById(R.id.main_toolbar); setSupportActionBar(myToolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); myToolbar.setTitle(null); statusView = (TextView) findViewById(R.id.update_status); Spinner sortSpinner = (Spinner) findViewById(R.id.sort_spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.sort_orders, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sortSpinner.setAdapter(adapter); sortSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (! processing) { String selectedItem = parent.getItemAtPosition(position).toString(); sort_order = selectedItem; sortPoems(); } } public void onNothingSelected(AdapterView<?> parent) { } }); mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view); // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView mRecyclerView.setHasFixedSize(true); // use a linear layout manager mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); } @Override protected void onStart() { super.onStart(); mTracker.setScreenName("PoemsList"); mTracker.send(new HitBuilders.ScreenViewBuilder().build()); autoUpdate(); } private void autoUpdate() { SharedPreferences prefs = getPreferences(MODE_PRIVATE); long last_update_tstamp = prefs.getLong("LAST_UPDATE_TIME", -1); File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "poems.json"); if (last_update_tstamp == -1 || !file.exists()) { updatePoems(null); } else { Log.i(TAG, "Checking if it's time to update"); Log.i(TAG, String.format("last update time %d", last_update_tstamp)); Calendar last_update_cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC")); last_update_cal.setTimeInMillis(last_update_tstamp); long diff_in_ms = now.getTimeInMillis() - last_update_tstamp; long ms_today = now.get(Calendar.HOUR_OF_DAY) * 60 * 60 * 1000 + now.get(Calendar.MINUTE) * 60 * 1000 + now.get(Calendar.SECOND) * 1000 + now.get(Calendar.MILLISECOND); if ( (now.get(Calendar.HOUR_OF_DAY) >= FIRST_UPDATE_HOUR && diff_in_ms > ms_today - FIRST_UPDATE_HOUR * 60 * 60 * 1000 ) || (now.get(Calendar.HOUR_OF_DAY) >= SECOND_UPDATE_HOUR && diff_in_ms > ms_today - SECOND_UPDATE_HOUR * 60 * 60 * 1000) ) { updatePoems(null); } else if (poems == null){ processPoems(); } else { // TODO: This really has nothing to do with autoupdate, should put somewhere else... mAdapter = new MyAdapter(poems, this); mRecyclerView.setAdapter(mAdapter); } } } private void sortPoems() { if (sort_order.equals("Date")) { Collections.sort(poems, new Comparator<Poem>() { @Override public int compare(Poem p1, Poem p2) { return (int) (p2.timestamp - p1.timestamp); } }); } else if (sort_order.equals("Score")) { Collections.sort(poems, new Comparator<Poem>() { @Override public int compare(Poem p1, Poem p2) { return (p2.score - p1.score); } }); } else if (sort_order.equals("Gold")) { Collections.sort(poems, new Comparator<Poem>() { @Override public int compare(Poem p1, Poem p2) { return (p2.gold - p1.gold); } }); } mAdapter.notifyDataSetChanged(); } public void processPoems() { processing = true; sort_order = "Date"; ((Spinner) findViewById(R.id.sort_spinner)).setSelection(0); // 0 is Date (is there a better way to do this??) statusView.setText("processing"); poems = new ArrayList<>(); mAdapter = new MyAdapter(poems, this); mRecyclerView.setAdapter(mAdapter); new ParsePoemsTask(this).execute(this); } public void addPoems(List<Poem> poems_set){ poems.addAll(poems_set); statusView.setText(String.format("%d poems", poems.size())); mAdapter.notifyDataSetChanged(); } public void finishedProcessing(boolean status){ if (updating){ updating = false; if (poems.size() > 1000){ SharedPreferences prefs = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC")); editor.putLong("LAST_UPDATE_TIME", now.getTimeInMillis()); editor.apply(); } } if (!status) { statusView.setText("error"); } processing = false; } public void updatePoems(View view) { if (onComplete != null) { return; } updating = true; File poems_file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "poems.json"); File poems_old_file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "poems_old.json"); if (poems_file.exists()) { poems_file.renameTo(poems_old_file); } String url = "https://almoturg.com/poems.json"; DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setDescription("Sprog poems"); request.setTitle("Sprog"); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, "poems.json"); // get download service and enqueue file DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); onComplete = new BroadcastReceiver() { public void onReceive(Context ctxt, Intent intent) { statusView.setText("poems downloaded"); processPoems(); unregisterReceiver(onComplete); onComplete = null; } }; registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); statusView.setText("loading poems"); manager.enqueue(request); } } class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements FastScrollRecyclerView.SectionedAdapter { private Context context; private List<Poem> poems; private Calendar cal; // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public int position; public TextView poem_content; public CardView view; public ViewHolder(View v) { super(v); v.setOnClickListener(this); this.poem_content = (TextView) v.findViewById(R.id.content); this.view = (CardView) v; } @Override public void onClick(View v) { if (poem_content.getEllipsize() == null) { Intent intent = new Intent(context, PoemActivity.class); intent.putExtra("POEM_ID", position); context.startActivity(intent); } else { poem_content.setEllipsize(null); poem_content.setMaxLines(Integer.MAX_VALUE); } } } // Provide a suitable constructor (depends on the kind of dataset) MyAdapter(List<Poem> poems, Context context) { this.poems = poems; this.context = context; this.cal = Calendar.getInstance(Locale.ENGLISH); } // Create new views (invoked by the layout manager) @Override public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.poem_row, parent, false); // set the view's size, margins, paddings and layout parameters ViewHolder vh = new ViewHolder(v); return vh; } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(ViewHolder holder, int position) { // - get element from your dataset at this position // - replace the contents of the view with that element Poem poem = (poems.get(position)); holder.position = position; holder.poem_content.setEllipsize(TextUtils.TruncateAt.END); holder.poem_content.setMaxLines(1); Util.update_poem_row(poem, holder.view, false, true, context); } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return poems.size(); } @NonNull @Override public String getSectionName(int position) { if (((MainActivity) context).sort_order.equals("Date")) { cal.setTimeInMillis((long) poems.get(position).timestamp * 1000); return DateFormat.format("yyyy-MM", cal).toString(); } else if (((MainActivity) context).sort_order.equals("Score")) { return Integer.toString(poems.get(position).score); } else if (((MainActivity) context).sort_order.equals("Gold")) { return Integer.toString(poems.get(position).gold); } return ""; } }
set number of poems when resuming
app/src/main/java/com/almoturg/sprog/MainActivity.java
set number of poems when resuming
<ide><path>pp/src/main/java/com/almoturg/sprog/MainActivity.java <ide> <ide> sortSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { <ide> public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { <del> if (! processing) { <add> if (!processing) { <ide> String selectedItem = parent.getItemAtPosition(position).toString(); <ide> sort_order = selectedItem; <ide> sortPoems(); <ide> && diff_in_ms > ms_today - SECOND_UPDATE_HOUR * 60 * 60 * 1000) <ide> ) { <ide> updatePoems(null); <del> } else if (poems == null){ <add> } else if (poems == null) { <ide> processPoems(); <ide> } else { <ide> // TODO: This really has nothing to do with autoupdate, should put somewhere else... <ide> mAdapter = new MyAdapter(poems, this); <ide> mRecyclerView.setAdapter(mAdapter); <add> statusView.setText(String.format("%d poems", poems.size())); <ide> } <ide> } <ide> } <ide> new ParsePoemsTask(this).execute(this); <ide> } <ide> <del> public void addPoems(List<Poem> poems_set){ <add> public void addPoems(List<Poem> poems_set) { <ide> poems.addAll(poems_set); <ide> statusView.setText(String.format("%d poems", poems.size())); <ide> mAdapter.notifyDataSetChanged(); <ide> } <del> public void finishedProcessing(boolean status){ <del> if (updating){ <add> <add> public void finishedProcessing(boolean status) { <add> if (updating) { <ide> updating = false; <del> if (poems.size() > 1000){ <add> if (poems.size() > 1000) { <ide> SharedPreferences prefs = getPreferences(MODE_PRIVATE); <ide> SharedPreferences.Editor editor = prefs.edit(); <ide>
Java
mit
7a9a2b1fc70aaea2fbf13fe94d212ade145a38a4
0
rossdrew/emuRox,rossdrew/emuRox
package com.rox.emu.p6502; import com.pholser.junit.quickcheck.Property; import com.pholser.junit.quickcheck.generator.InRange; import com.pholser.junit.quickcheck.runner.JUnitQuickcheck; import com.rox.emu.UnknownOpCodeException; import com.rox.emu.p6502.op.AddressingMode; import com.rox.emu.p6502.op.OpCode; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Arrays; import static org.junit.Assert.*; @RunWith(JUnitQuickcheck.class) public class CompilerTest { @Test public void testPrefixExtraction(){ try { assertEquals("$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "$10", "LDA")); assertEquals("#$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "#$10", "ADC")); assertEquals("$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "$AA", "LDA")); assertEquals("#$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "#$AA", "ADC")); assertEquals("($", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "($AA,X)", "ADC")); }catch (UnknownOpCodeException e){ fail(e.getMessage()); } } @Test public void testValueExtraction(){ try { assertEquals("10", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "$10", "LDA")); assertEquals("10", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "#$10", "LDA")); assertEquals("AA", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "$AA", "LDA")); assertEquals("AA", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "#$AA", "LDA")); assertEquals("AA", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "($AA,X)", "ADC")); }catch (UnknownOpCodeException e){ fail(e.getMessage()); } } @Test public void testPostfixExtraction(){ try { assertEquals(",X", Compiler.extractFirstOccurrence(Compiler.POSTFIX_REGEX, "$10,X", "LDA")); assertEquals(",Y", Compiler.extractFirstOccurrence(Compiler.POSTFIX_REGEX, "$AA,Y", "LDA")); assertEquals(",X)", Compiler.extractFirstOccurrence(Compiler.POSTFIX_REGEX, "($AA,X)", "ADC")); }catch (UnknownOpCodeException e){ fail(e.getMessage()); } } @Test public void testImpliedInstructions(){ OpCode.streamOf(AddressingMode.IMPLIED).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName()); int[] bytes = compiler.getBytes(); assertEquals("Wrong byte value for " + opcode.getOpCodeName() + "(" + opcode.getByteValue() + ")", opcode.getByteValue(), bytes[0]); }); } @Property public void testImmediateInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.IMMEDIATE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.IMMEDIATE_VALUE_PREFIX + hexByte); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testAccumulatorInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ACCUMULATOR).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.IMMEDIATE_PREFIX + hexByte); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testZeroPageInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ZERO_PAGE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexByte); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testZeroPageXInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ZERO_PAGE_X).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexByte+ ",X"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testZeroPageYInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ZERO_PAGE_Y).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexByte + ",Y"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testAbsoluteInstructions(@InRange(min = "256", max = "65535") int wordValue){ final String hexWord = Integer.toHexString(wordValue); OpCode.streamOf(AddressingMode.ABSOLUTE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexWord); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), wordValue}, bytes); }); } @Property public void testAbsoluteXInstructions(@InRange(min = "256", max = "65535") int wordValue){ final String hexWord = Integer.toHexString(wordValue); OpCode.streamOf(AddressingMode.ABSOLUTE_X).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexWord + ",X"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + " 0x" + hexWord + "' was wrong.", new int[] {opcode.getByteValue(), wordValue}, bytes); }); } @Property public void testAbsoluteYInstructions(@InRange(min = "256", max = "65535") int wordValue){ final String hexWord = Integer.toHexString(wordValue); OpCode.streamOf(AddressingMode.ABSOLUTE_Y).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexWord + ",Y"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + " 0x" + hexWord + "' was wrong.", new int[] {opcode.getByteValue(), wordValue}, bytes); }); } @Property public void testIndirectXInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.INDIRECT_X).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " (" + Compiler.VALUE_PREFIX + hexByte + ",X)"); int[] bytes = compiler.getBytes(); assertArrayEquals(new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testIndirectYInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.INDIRECT_Y).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " (" + Compiler.VALUE_PREFIX + hexByte + "),Y"); int[] bytes = compiler.getBytes(); assertArrayEquals(new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Test public void testChainedInstruction(){ Compiler compiler = new Compiler("SEC LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "47"); final int[] bytes = compiler.getBytes(); int[] expected = new int[] {OpCode.OP_SEC.getByteValue(), OpCode.OP_LDA_I.getByteValue(), 0x47}; assertArrayEquals("Expected: " + Arrays.toString(expected) + ", Got: " + Arrays.toString(bytes), expected, bytes); } @Test public void testChainedTwoByteInstruction(){ Compiler compiler = new Compiler("LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "47 SEC"); final int[] bytes = compiler.getBytes(); int[] expected = new int[] {OpCode.OP_LDA_I.getByteValue(), 0x47, OpCode.OP_SEC.getByteValue()}; assertArrayEquals("Expected: " + Arrays.toString(expected) + ", Got: " + Arrays.toString(bytes), expected, bytes); } @Test public void testChainedTwoByteInstructions(){ Compiler compiler = new Compiler("LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "47 CLC LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "10 SEC"); final int[] bytes = compiler.getBytes(); int[] expected = new int[] {OpCode.OP_LDA_I.getByteValue(), 0x47, OpCode.OP_CLC.getByteValue(), OpCode.OP_LDA_I.getByteValue(), 0x10, OpCode.OP_SEC.getByteValue()}; assertArrayEquals("Expected: " + Arrays.toString(expected) + ", Got: " + Arrays.toString(bytes), expected, bytes); } @Test public void firstInvalidOpcode(){ Compiler compiler = new Compiler("ROX"); try { compiler.getBytes(); fail("Exception expected, 'ROX' is an invalid OpCode"); }catch(UnknownOpCodeException e){ assertNotNull(e); } } @Test public void testInvalidValuePrefix(){ try { Compiler compiler = new Compiler("ADC @$10"); int[] bytes = compiler.getBytes(); fail("Invalid argument structure should throw an exception but was " + Arrays.toString(bytes)); }catch (UnknownOpCodeException e){ assertFalse(e.getMessage().isEmpty()); assertFalse(e.getOpCode() == null); } } }
src/test/java/com/rox/emu/p6502/CompilerTest.java
package com.rox.emu.p6502; import com.pholser.junit.quickcheck.Property; import com.pholser.junit.quickcheck.generator.InRange; import com.pholser.junit.quickcheck.runner.JUnitQuickcheck; import com.rox.emu.UnknownOpCodeException; import com.rox.emu.p6502.op.AddressingMode; import com.rox.emu.p6502.op.OpCode; import jdk.nashorn.internal.runtime.regexp.joni.constants.OPCode; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Arrays; import static org.junit.Assert.*; @RunWith(JUnitQuickcheck.class) public class CompilerTest { @Test public void testPrefixExtraction(){ try { assertEquals("$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "$10", "LDA")); assertEquals("#$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "#$10", "ADC")); assertEquals("$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "$AA", "LDA")); assertEquals("#$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "#$AA", "ADC")); assertEquals("($", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "($AA,X)", "ADC")); }catch (UnknownOpCodeException e){ fail(e.getMessage()); } } @Test public void testValueExtraction(){ try { assertEquals("10", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "$10", "LDA")); assertEquals("10", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "#$10", "LDA")); assertEquals("AA", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "$AA", "LDA")); assertEquals("AA", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "#$AA", "LDA")); assertEquals("AA", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "($AA,X)", "ADC")); }catch (UnknownOpCodeException e){ fail(e.getMessage()); } } @Test public void testPostfixExtraction(){ try { assertEquals(",X", Compiler.extractFirstOccurrence(Compiler.POSTFIX_REGEX, "$10,X", "LDA")); assertEquals(",Y", Compiler.extractFirstOccurrence(Compiler.POSTFIX_REGEX, "$AA,Y", "LDA")); assertEquals(",X)", Compiler.extractFirstOccurrence(Compiler.POSTFIX_REGEX, "($AA,X)", "ADC")); }catch (UnknownOpCodeException e){ fail(e.getMessage()); } } @Test public void testImpliedInstructions(){ OpCode.streamOf(AddressingMode.IMPLIED).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName()); int[] bytes = compiler.getBytes(); assertEquals("Wrong byte value for " + opcode.getOpCodeName() + "(" + opcode.getByteValue() + ")", opcode.getByteValue(), bytes[0]); }); } @Property public void testImmediateInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.IMMEDIATE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.IMMEDIATE_VALUE_PREFIX + hexByte); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testAccumulatorInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ACCUMULATOR).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.IMMEDIATE_PREFIX + hexByte); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testZeroPageInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ZERO_PAGE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexByte); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testZeroPageXInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ZERO_PAGE_X).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexByte+ ",X"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testZeroPageYInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ZERO_PAGE_Y).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexByte + ",Y"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testAbsoluteInstructions(@InRange(min = "256", max = "65535") int wordValue){ final String hexWord = Integer.toHexString(wordValue); OpCode.streamOf(AddressingMode.ABSOLUTE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexWord); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), wordValue}, bytes); }); } @Property public void testAbsoluteXInstructions(@InRange(min = "256", max = "65535") int wordValue){ final String hexWord = Integer.toHexString(wordValue); OpCode.streamOf(AddressingMode.ABSOLUTE_X).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexWord + ",X"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + " 0x" + hexWord + "' was wrong.", new int[] {opcode.getByteValue(), wordValue}, bytes); }); } @Property public void testAbsoluteYInstructions(@InRange(min = "256", max = "65535") int wordValue){ final String hexWord = Integer.toHexString(wordValue); OpCode.streamOf(AddressingMode.ABSOLUTE_Y).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexWord + ",Y"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + " 0x" + hexWord + "' was wrong.", new int[] {opcode.getByteValue(), wordValue}, bytes); }); } @Property public void testIndirectXInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.INDIRECT_X).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " (" + Compiler.VALUE_PREFIX + hexByte + ",X)"); int[] bytes = compiler.getBytes(); assertArrayEquals(new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testIndirectYInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.INDIRECT_Y).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " (" + Compiler.VALUE_PREFIX + hexByte + "),Y"); int[] bytes = compiler.getBytes(); assertArrayEquals(new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Test public void testChainedInstruction(){ Compiler compiler = new Compiler("SEC LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "47"); final int[] bytes = compiler.getBytes(); int[] expected = new int[] {OpCode.OP_SEC.getByteValue(), OpCode.OP_LDA_I.getByteValue(), 0x47}; assertArrayEquals("Expected: " + Arrays.toString(expected) + ", Got: " + Arrays.toString(bytes), expected, bytes); } @Test public void testChainedTwoByteInstruction(){ Compiler compiler = new Compiler("LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "47 SEC"); final int[] bytes = compiler.getBytes(); int[] expected = new int[] {OpCode.OP_LDA_I.getByteValue(), 0x47, OpCode.OP_SEC.getByteValue()}; assertArrayEquals("Expected: " + Arrays.toString(expected) + ", Got: " + Arrays.toString(bytes), expected, bytes); } @Test public void testChainedTwoByteInstructions(){ Compiler compiler = new Compiler("LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "47 SEC LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "10 SEC"); final int[] bytes = compiler.getBytes(); int[] expected = new int[] {OpCode.OP_LDA_I.getByteValue(), 0x47, OpCode.OP_LDA_I.getByteValue(), 0x10, OpCode.OP_SEC.getByteValue()}; assertArrayEquals("Expected: " + Arrays.toString(expected) + ", Got: " + Arrays.toString(bytes), expected, bytes); } @Test public void firstInvalidOpcode(){ Compiler compiler = new Compiler("ROX"); try { compiler.getBytes(); fail("Exception expected, 'ROX' is an invalid OpCode"); }catch(UnknownOpCodeException e){ assertNotNull(e); } } @Test public void testInvalidValuePrefix(){ try { Compiler compiler = new Compiler("ADC @$10"); int[] bytes = compiler.getBytes(); fail("Invalid argument structure should throw an exception but was " + Arrays.toString(bytes)); }catch (UnknownOpCodeException e){ assertFalse(e.getMessage().isEmpty()); assertFalse(e.getOpCode() == null); } } }
Fixing broken test
src/test/java/com/rox/emu/p6502/CompilerTest.java
Fixing broken test
<ide><path>rc/test/java/com/rox/emu/p6502/CompilerTest.java <ide> import com.rox.emu.UnknownOpCodeException; <ide> import com.rox.emu.p6502.op.AddressingMode; <ide> import com.rox.emu.p6502.op.OpCode; <del>import jdk.nashorn.internal.runtime.regexp.joni.constants.OPCode; <ide> import org.junit.Test; <ide> import org.junit.runner.RunWith; <ide> <ide> <ide> @Test <ide> public void testChainedTwoByteInstructions(){ <del> Compiler compiler = new Compiler("LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "47 SEC LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "10 SEC"); <add> Compiler compiler = new Compiler("LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "47 CLC LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "10 SEC"); <ide> final int[] bytes = compiler.getBytes(); <ide> <del> int[] expected = new int[] {OpCode.OP_LDA_I.getByteValue(), 0x47, OpCode.OP_LDA_I.getByteValue(), 0x10, OpCode.OP_SEC.getByteValue()}; <add> int[] expected = new int[] {OpCode.OP_LDA_I.getByteValue(), 0x47, OpCode.OP_CLC.getByteValue(), OpCode.OP_LDA_I.getByteValue(), 0x10, OpCode.OP_SEC.getByteValue()}; <ide> assertArrayEquals("Expected: " + Arrays.toString(expected) + ", Got: " + Arrays.toString(bytes), expected, bytes); <ide> } <ide>
Java
apache-2.0
7556eb87b0e91dda668dd99b105ad9cbf4ae4472
0
topicusonderwijs/wicket,apache/wicket,topicusonderwijs/wicket,klopfdreh/wicket,selckin/wicket,topicusonderwijs/wicket,mosoft521/wicket,apache/wicket,Servoy/wicket,mafulafunk/wicket,mosoft521/wicket,selckin/wicket,bitstorm/wicket,dashorst/wicket,selckin/wicket,mafulafunk/wicket,freiheit-com/wicket,martin-g/wicket-osgi,martin-g/wicket-osgi,klopfdreh/wicket,aldaris/wicket,dashorst/wicket,klopfdreh/wicket,Servoy/wicket,mosoft521/wicket,astrapi69/wicket,Servoy/wicket,astrapi69/wicket,topicusonderwijs/wicket,bitstorm/wicket,bitstorm/wicket,freiheit-com/wicket,AlienQueen/wicket,topicusonderwijs/wicket,selckin/wicket,AlienQueen/wicket,bitstorm/wicket,freiheit-com/wicket,klopfdreh/wicket,dashorst/wicket,Servoy/wicket,dashorst/wicket,astrapi69/wicket,mosoft521/wicket,Servoy/wicket,astrapi69/wicket,apache/wicket,mosoft521/wicket,aldaris/wicket,AlienQueen/wicket,selckin/wicket,aldaris/wicket,AlienQueen/wicket,martin-g/wicket-osgi,mafulafunk/wicket,zwsong/wicket,zwsong/wicket,apache/wicket,zwsong/wicket,zwsong/wicket,freiheit-com/wicket,bitstorm/wicket,AlienQueen/wicket,freiheit-com/wicket,klopfdreh/wicket,aldaris/wicket,dashorst/wicket,aldaris/wicket,apache/wicket
/* * 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.wicket.extensions.markup.html.tabs; import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.list.Loop; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.AbstractReadOnlyModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; /** * TabbedPanel component represets a panel with tabs that are used to switch * between different content panels inside the TabbedPanel panel. * <p> * Example: * * <pre> * * List tabs=new ArrayList(); * * tabs.add(new AbstractTab(new Model(&quot;first tab&quot;)) { * * public Panel getPanel(String panelId) * { * return new TabPanel1(panelId); * } * * }); * * tabs.add(new AbstractTab(new Model(&quot;second tab&quot;)) { * * public Panel getPanel(String panelId) * { * return new TabPanel2(panelId); * } * * }); * * add(new TabbedPanel(&quot;tabs&quot;, tabs)); * * * &lt;span wicket:id=&quot;tabs&quot; class=&quot;tabpanel&quot;&gt;[tabbed panel will be here]&lt;/span&gt; * * </pre> * * </p> * * <p> * For a complete example see the component references in wicket-examples * project * </p> * * @see org.apache.wicket.extensions.markup.html.tabs.ITab * * @author Igor Vaynberg (ivaynberg at apache dot org) * */ public class TabbedPanel extends Panel { private static final long serialVersionUID = 1L; /** * id used for child panels */ public static final String TAB_PANEL_ID = "panel"; private List tabs; /** * Constructor * * @param id * component id * @param tabs * list of ITab objects used to represent tabs */ public TabbedPanel(String id, List tabs) { super(id, new Model(new Integer(-1))); if (tabs == null) { throw new IllegalArgumentException("argument [tabs] cannot be null"); } if (tabs.size() < 1) { throw new IllegalArgumentException( "argument [tabs] must contain a list of at least one tab"); } this.tabs = tabs; final IModel tabCount = new AbstractReadOnlyModel() { private static final long serialVersionUID = 1L; public Object getObject() { return new Integer(TabbedPanel.this.tabs.size()); } }; WebMarkupContainer tabsContainer = new WebMarkupContainer("tabs-container") { private static final long serialVersionUID = 1L; protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); tag.put("class", getTabContainerCssClass()); } }; add(tabsContainer); // add the loop used to generate tab names tabsContainer.add(new Loop("tabs", tabCount) { private static final long serialVersionUID = 1L; protected void populateItem(LoopItem item) { final int index = item.getIteration(); final ITab tab = ((ITab)TabbedPanel.this.tabs.get(index)); final int selected = getSelectedTab(); final WebMarkupContainer titleLink = newLink("link", index); titleLink.add(newTitle("title", tab.getTitle(), index)); item.add(titleLink); } protected LoopItem newItem(int iteration) { return new LoopItem(iteration) { private static final long serialVersionUID = 1L; protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); String cssClass = (String)tag.getString("class"); if (cssClass == null) { cssClass = " "; } cssClass += " tab" + getIteration(); if (getIteration() == getSelectedTab()) { cssClass += " selected"; } if (getIteration() == getIterations() - 1) { cssClass += " last"; } tag.put("class", cssClass.trim()); } }; } }); // select the first tab by default setSelectedTab(0); } /** * @return the value of css class attribute that will be added to a div * containing the tabs. The default value is <code>tab-row</code> */ protected String getTabContainerCssClass() { return "tab-row"; } /** * @return list of tabs that can be used by the user to add/remove/reorder * tabs in the panel */ public final List getTabs() { return tabs; } /** * Factory method for tab titles. Returned component can be anything that * can attach to span tags such as a fragment, panel, or a label * * @param titleId * id of title component * @param titleModel * model containing tab title * @param index * index of tab * @return title component */ protected Component newTitle(String titleId, IModel titleModel, int index) { return new Label(titleId, titleModel); } /** * Factory method for links used to switch between tabs. * * The created component is attached to the following markup. Label * component with id: title will be added for you by the tabbed panel. * * <pre> * &lt;a href=&quot;#&quot; wicket:id=&quot;link&quot;&gt;&lt;span wicket:id=&quot;title&quot;&gt;[[tab title]]&lt;/span&gt;&lt;/a&gt; * </pre> * * Example implementation: * * <pre> * protected WebMarkupContainer newLink(String linkId, final int index) * { * return new Link(linkId) * { * private static final long serialVersionUID = 1L; * * public void onClick() * { * setSelectedTab(index); * } * }; * } * </pre> * * @param linkId * component id with which the link should be created * @param index * index of the tab that should be activated when this link is * clicked. See {@link #setSelectedTab(int)}. * @return created link component */ protected WebMarkupContainer newLink(String linkId, final int index) { return new Link(linkId) { private static final long serialVersionUID = 1L; public void onClick() { setSelectedTab(index); } }; } /** * sets the selected tab * * @param index * index of the tab to select * */ public final void setSelectedTab(int index) { if (index < 0 || index >= tabs.size()) { throw new IndexOutOfBoundsException(); } setModelObject(new Integer(index)); ITab tab = (ITab)tabs.get(index); Panel panel = tab.getPanel(TAB_PANEL_ID); if (panel == null) { throw new WicketRuntimeException("ITab.getPanel() returned null. TabbedPanel [" + getPath() + "] ITab index [" + index + "]"); } if (!panel.getId().equals(TAB_PANEL_ID)) { throw new WicketRuntimeException( "ITab.getPanel() returned a panel with invalid id [" + panel.getId() + "]. You must always return a panel with id equal to the provided panelId parameter. TabbedPanel [" + getPath() + "] ITab index [" + index + "]"); } if (get(TAB_PANEL_ID) == null) { add(panel); } else { replace(panel); } } /** * @return index of the selected tab */ public final int getSelectedTab() { return ((Integer)getModelObject()).intValue(); } }
jdk-1.4/wicket-extensions/src/main/java/org/apache/wicket/extensions/markup/html/tabs/TabbedPanel.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.wicket.extensions.markup.html.tabs; import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.behavior.SimpleAttributeModifier; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.list.Loop; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.AbstractReadOnlyModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; /** * TabbedPanel component represets a panel with tabs that are used to switch * between different content panels inside the TabbedPanel panel. * <p> * Example: * * <pre> * * List tabs=new ArrayList(); * * tabs.add(new AbstractTab(new Model(&quot;first tab&quot;)) { * * public Panel getPanel(String panelId) * { * return new TabPanel1(panelId); * } * * }); * * tabs.add(new AbstractTab(new Model(&quot;second tab&quot;)) { * * public Panel getPanel(String panelId) * { * return new TabPanel2(panelId); * } * * }); * * add(new TabbedPanel(&quot;tabs&quot;, tabs)); * * * &lt;span wicket:id=&quot;tabs&quot; class=&quot;tabpanel&quot;&gt;[tabbed panel will be here]&lt;/span&gt; * * </pre> * * </p> * * <p> * For a complete example see the component references in wicket-examples * project * </p> * * @see org.apache.wicket.extensions.markup.html.tabs.ITab * * @author Igor Vaynberg (ivaynberg) * */ public class TabbedPanel extends Panel { private static final long serialVersionUID = 1L; /** * id used for child panels */ public static final String TAB_PANEL_ID = "panel"; private List tabs; /** * Constructor * * @param id * component id * @param tabs * list of ITab objects used to represent tabs */ public TabbedPanel(String id, List tabs) { super(id, new Model(new Integer(-1))); if (tabs == null) { throw new IllegalArgumentException("argument [tabs] cannot be null"); } if (tabs.size() < 1) { throw new IllegalArgumentException( "argument [tabs] must contain a list of at least one tab"); } this.tabs = tabs; final IModel tabCount = new AbstractReadOnlyModel() { private static final long serialVersionUID = 1L; public Object getObject() { return new Integer(TabbedPanel.this.tabs.size()); } }; WebMarkupContainer tabsContainer = new WebMarkupContainer("tabs-container") { private static final long serialVersionUID = 1L; protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); tag.put("class", getTabContainerCssClass()); } }; add(tabsContainer); // add the loop used to generate tab names tabsContainer.add(new Loop("tabs", tabCount) { private static final long serialVersionUID = 1L; protected void populateItem(LoopItem item) { final int index = item.getIteration(); final ITab tab = ((ITab)TabbedPanel.this.tabs.get(index)); final int selected = getSelectedTab(); final WebMarkupContainer titleLink = newLink("link", index); titleLink.add(newTitle("title", tab.getTitle(), index)); item.add(titleLink); item.add(new SimpleAttributeModifier("class", "selected") { private static final long serialVersionUID = 1L; public boolean isEnabled(Component component) { return index == selected; } }); if (item.getIteration() == getIterations() - 1) { item.add(new AttributeAppender("class", true, new Model("last"), " ")); } } }); // select the first tab by default setSelectedTab(0); } /** * @return the value of css class attribute that will be added to a div * containing the tabs. The default value is <code>tab-row</code> */ protected String getTabContainerCssClass() { return "tab-row"; } /** * @return list of tabs that can be used by the user to add/remove/reorder * tabs in the panel */ public final List getTabs() { return tabs; } /** * Factory method for tab titles. Returned component can be anything that * can attach to span tags such as a fragment, panel, or a label * * @param titleId * id of title component * @param titleModel * model containing tab title * @param index * index of tab * @return title component */ protected Component newTitle(String titleId, IModel titleModel, int index) { return new Label(titleId, titleModel); } /** * Factory method for links used to switch between tabs. * * The created component is attached to the following markup. Label * component with id: title will be added for you by the tabbed panel. * * <pre> * &lt;a href=&quot;#&quot; wicket:id=&quot;link&quot;&gt;&lt;span wicket:id=&quot;title&quot;&gt;[[tab title]]&lt;/span&gt;&lt;/a&gt; * </pre> * * Example implementation: * * <pre> * protected WebMarkupContainer newLink(String linkId, final int index) * { * return new Link(linkId) * { * private static final long serialVersionUID = 1L; * * public void onClick() * { * setSelectedTab(index); * } * }; * } * </pre> * * @param linkId * component id with which the link should be created * @param index * index of the tab that should be activated when this link is * clicked. See {@link #setSelectedTab(int)}. * @return created link component */ protected WebMarkupContainer newLink(String linkId, final int index) { return new Link(linkId) { private static final long serialVersionUID = 1L; public void onClick() { setSelectedTab(index); } }; } /** * sets the selected tab * * @param index * index of the tab to select * */ public final void setSelectedTab(int index) { if (index < 0 || index >= tabs.size()) { throw new IndexOutOfBoundsException(); } setModelObject(new Integer(index)); ITab tab = (ITab)tabs.get(index); Panel panel = tab.getPanel(TAB_PANEL_ID); if (panel == null) { throw new WicketRuntimeException("ITab.getPanel() returned null. TabbedPanel [" + getPath() + "] ITab index [" + index + "]"); } if (!panel.getId().equals(TAB_PANEL_ID)) { throw new WicketRuntimeException( "ITab.getPanel() returned a panel with invalid id [" + panel.getId() + "]. You must always return a panel with id equal to the provided panelId parameter. TabbedPanel [" + getPath() + "] ITab index [" + index + "]"); } if (get(TAB_PANEL_ID) == null) { add(panel); } else { replace(panel); } } /** * @return index of the selected tab */ public final int getSelectedTab() { return ((Integer)getModelObject()).intValue(); } }
patch to add tab0, tab1 css classes. optimized state by not using attribute modifiers. git-svn-id: ac804e38dcddf5e42ac850d29d9218b7df6087b7@555051 13f79535-47bb-0310-9956-ffa450edef68
jdk-1.4/wicket-extensions/src/main/java/org/apache/wicket/extensions/markup/html/tabs/TabbedPanel.java
patch to add tab0, tab1 css classes. optimized state by not using attribute modifiers.
<ide><path>dk-1.4/wicket-extensions/src/main/java/org/apache/wicket/extensions/markup/html/tabs/TabbedPanel.java <ide> <ide> import org.apache.wicket.Component; <ide> import org.apache.wicket.WicketRuntimeException; <del>import org.apache.wicket.behavior.AttributeAppender; <del>import org.apache.wicket.behavior.SimpleAttributeModifier; <ide> import org.apache.wicket.markup.ComponentTag; <ide> import org.apache.wicket.markup.html.WebMarkupContainer; <ide> import org.apache.wicket.markup.html.basic.Label; <ide> * <ide> * <pre> <ide> * <del> * List tabs=new ArrayList(); <add> * List tabs=new ArrayList(); <ide> * <del> * tabs.add(new AbstractTab(new Model(&quot;first tab&quot;)) { <add> * tabs.add(new AbstractTab(new Model(&quot;first tab&quot;)) { <add> * <add> * public Panel getPanel(String panelId) <add> * { <add> * return new TabPanel1(panelId); <add> * } <add> * <add> * }); <ide> * <del> * public Panel getPanel(String panelId) <del> * { <del> * return new TabPanel1(panelId); <del> * } <add> * tabs.add(new AbstractTab(new Model(&quot;second tab&quot;)) { <add> * <add> * public Panel getPanel(String panelId) <add> * { <add> * return new TabPanel2(panelId); <add> * } <ide> * <del> * }); <add> * }); <ide> * <del> * tabs.add(new AbstractTab(new Model(&quot;second tab&quot;)) { <del> * <del> * public Panel getPanel(String panelId) <del> * { <del> * return new TabPanel2(panelId); <del> * } <del> * <del> * }); <del> * <del> * add(new TabbedPanel(&quot;tabs&quot;, tabs)); <del> * <del> * <del> * &lt;span wicket:id=&quot;tabs&quot; class=&quot;tabpanel&quot;&gt;[tabbed panel will be here]&lt;/span&gt; <add> * add(new TabbedPanel(&quot;tabs&quot;, tabs)); <add> * <add> * <add> * &lt;span wicket:id=&quot;tabs&quot; class=&quot;tabpanel&quot;&gt;[tabbed panel will be here]&lt;/span&gt; <ide> * <ide> * </pre> <ide> * <ide> * <ide> * @see org.apache.wicket.extensions.markup.html.tabs.ITab <ide> * <del> * @author Igor Vaynberg (ivaynberg) <add> * @author Igor Vaynberg (ivaynberg at apache dot org) <ide> * <ide> */ <ide> public class TabbedPanel extends Panel <ide> <ide> titleLink.add(newTitle("title", tab.getTitle(), index)); <ide> item.add(titleLink); <del> <del> item.add(new SimpleAttributeModifier("class", "selected") <add> } <add> <add> protected LoopItem newItem(int iteration) <add> { <add> return new LoopItem(iteration) <ide> { <ide> private static final long serialVersionUID = 1L; <ide> <del> public boolean isEnabled(Component component) <add> protected void onComponentTag(ComponentTag tag) <ide> { <del> return index == selected; <add> super.onComponentTag(tag); <add> String cssClass = (String)tag.getString("class"); <add> if (cssClass == null) <add> { <add> cssClass = " "; <add> } <add> cssClass += " tab" + getIteration(); <add> <add> if (getIteration() == getSelectedTab()) <add> { <add> cssClass += " selected"; <add> } <add> if (getIteration() == getIterations() - 1) <add> { <add> cssClass += " last"; <add> } <add> tag.put("class", cssClass.trim()); <ide> } <ide> <del> }); <del> if (item.getIteration() == getIterations() - 1) <del> { <del> item.add(new AttributeAppender("class", true, new Model("last"), " ")); <del> } <del> <add> }; <ide> } <ide> <ide> });
Java
apache-2.0
ad3d91d30305088684c07d6302a94944986b1091
0
mtransitapps/ca-toronto-ttc-light-rail-parser,mtransitapps/ca-toronto-ttc-light-rail-parser
package org.mtransit.parser.ca_toronto_ttc_light_rail; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import org.mtransit.parser.CleanUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.Pair; import org.mtransit.parser.SplitUtils; import org.mtransit.parser.Utils; import org.mtransit.parser.SplitUtils.RouteTripSpec; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.gtfs.data.GTripStop; import org.mtransit.parser.mt.data.MAgency; import org.mtransit.parser.mt.data.MDirectionType; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.mt.data.MTrip; import org.mtransit.parser.mt.data.MTripStop; // http://www1.toronto.ca/wps/portal/contentonly?vgnextoid=96f236899e02b210VgnVCM1000003dd60f89RCRD // http://opendata.toronto.ca/TTC/routes/OpenData_TTC_Schedules.zip public class TorontoTTCLightRailAgencyTools extends DefaultAgencyTools { public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-toronto-ttc-light-rail-android/res/raw/"; args[2] = ""; // files-prefix } new TorontoTTCLightRailAgencyTools().start(args); } private HashSet<String> serviceIds; @Override public void start(String[] args) { System.out.printf("\nGenerating TTC light rail data..."); long start = System.currentTimeMillis(); this.serviceIds = extractUsefulServiceIds(args, this); super.start(args); System.out.printf("\nGenerating TTC light rail data... DONE in %s.", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludingAll() { return this.serviceIds != null && this.serviceIds.isEmpty(); } @Override public boolean excludeCalendar(GCalendar gCalendar) { if (this.serviceIds != null) { return excludeUselessCalendar(gCalendar, this.serviceIds); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { if (this.serviceIds != null) { return excludeUselessCalendarDate(gCalendarDates, this.serviceIds); } return super.excludeCalendarDate(gCalendarDates); } @Override public boolean excludeRoute(GRoute gRoute) { return super.excludeRoute(gRoute); } @Override public boolean excludeTrip(GTrip gTrip) { if (this.serviceIds != null) { return excludeUselessTrip(gTrip, this.serviceIds); } return super.excludeTrip(gTrip); } @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_LIGHT_RAIL; } @Override public long getRouteId(GRoute gRoute) { return Long.parseLong(gRoute.getRouteShortName()); // using route short name as route ID } @Override public String getRouteLongName(GRoute gRoute) { return cleanRouteLongName(gRoute); } private String cleanRouteLongName(GRoute gRoute) { String routeLongName = gRoute.getRouteLongName(); routeLongName = routeLongName.toLowerCase(Locale.ENGLISH); return CleanUtils.cleanLabel(routeLongName); } private static final String AGENCY_COLOR = "B80000"; // RED (AGENCY WEB SITE CSS) @Override public String getAgencyColor() { return AGENCY_COLOR; } private static final String COLOR_00529F = "00529F"; // BLUE (NIGHT BUSES) @Override public String getRouteColor(GRoute gRoute) { int rsn = Integer.parseInt(gRoute.getRouteShortName()); if (rsn >= 300 && rsn <= 399) { // Night Network return COLOR_00529F; } return null; // use agency color instead of provided colors (like web site) } private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2; static { HashMap<Long, RouteTripSpec> map2 = new HashMap<Long, RouteTripSpec>(); map2.put(506L, new RouteTripSpec(506L, // MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_DIRECTION, MDirectionType.EAST.getId(), // MAIN STREET STATION MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_DIRECTION, MDirectionType.WEST.getId()) // HIGH PARK LOOP .addTripSort(MDirectionType.EAST.intValue(), // Arrays.asList(new String[] { // "5292", // HIGH PARK LOOP <= "8673", // HOWARD PARK AVE AT PARKSIDE DR EAST SIDE {43.649054,-79.457394} "8763", // HOWARD PARK AVE AT RONCESVALLES AVE "8999", // != HOWARD PARK AVE AT DUNDAS ST WEST "9132", // != HOWARD PARK AVE AT RONCESVALLES AVE <= "2954", // != DUNDAS ST WEST AT HOWARD PARK AVE "2243", // == DUNDAS ST WEST AT SORAUREN AVE "7506", // DUNDAS ST WEST AT STERLING RD "3368", // == "3797", // != GERRARD ST EAST AT COXWELL AVE "8980", // == COXWELL AVE AT UPPER GERRARD ST EAST "549", // == "14260", // MAIN STREET STATION })) // .addTripSort(MDirectionType.WEST.intValue(), // Arrays.asList(new String[] { // "14260", // MAIN STREET STATION "10283", // COXWELL AVE AT LOWER GERRARD ST EAST "2048", // GERRARD ST EAST AT ASHDALE AVE "8135", // COLLEGE ST AT LANSDOWNE AVE "9132", // HOWARD PARK AVE AT RONCESVALLES AVE "4538", // HOWARD PARK AVE AT PARKSIDE DR "5292", // HIGH PARK LOOP })) // .compileBothTripSort()); map2.put(510L, new RouteTripSpec(510L, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_DIRECTION, MDirectionType.NORTH.getId(), // SPADINA STATION MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_DIRECTION, MDirectionType.SOUTH.getId()) // UNION STATION .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "9227", // UNION STATION <= "6075", // != SPADINA AVE AT QUEENS QUAY WEST NORTH SIDE "478", // != <> QUEENS QUAY LOOP AT LOWER SPADINA AVE <= "9243", // == SPADINA AVE AT BREMNER BLVD NORTH SIDE "5275", // == != SPADINA AVE AT KING ST WEST NORTH SIDE "10089", // != <> CHARLOTTE ST AT OXLEY ST => "8346", // != SPADINA AVE AT RICHMOND ST WEST "7582", // SPADINA AVE AT QUEEN ST WEST NORTH SIDE "14339", // SPADINA STATION => })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // "14339", // SPADINA STATION "9203", // == != SPADINA AVE AT QUEEN ST WEST SOUTH SIDE "10089", // != <> CHARLOTTE ST AT OXLEY ST => "10138", // != SPADINA AVE AT KING ST WEST "6639", // SPADINA AVE AT BREMNER BLVD "2125", // == != QUEENS QUAY WEST AT LOWER SPADINA AVE EAST SIDE "478", // != <> QUEENS QUAY LOOP AT LOWER SPADINA AVE => "15122", // != QUEENS QUAY W AT REES ST "9227", // UNION STATION => })) // .compileBothTripSort()); ALL_ROUTE_TRIPS2 = map2; } @Override public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { if (ALL_ROUTE_TRIPS2.containsKey(routeId)) { return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this); } return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop); } @Override public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips(); } return super.splitTrip(mRoute, gTrip, gtfs); } @Override public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this); } return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS); } private static final String WEST = "west"; private static final String EAST = "east"; private static final String SOUTH = "south"; private static final String NORTH = "north"; @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return; // split } String gTripHeadsignLC = gTrip.getTripHeadsign().toLowerCase(Locale.ENGLISH); if (gTripHeadsignLC.startsWith(EAST)) { mTrip.setHeadsignDirection(MDirectionType.EAST); return; } else if (gTripHeadsignLC.startsWith(WEST)) { mTrip.setHeadsignDirection(MDirectionType.WEST); return; } else if (gTripHeadsignLC.startsWith(NORTH)) { mTrip.setHeadsignDirection(MDirectionType.NORTH); return; } else if (gTripHeadsignLC.startsWith(SOUTH)) { mTrip.setHeadsignDirection(MDirectionType.SOUTH); return; } System.out.printf("\n%s: Unexpected trip %s!\n", mRoute.getId(), gTrip); System.exit(-1); } @Override public String cleanTripHeadsign(String tripHeadsign) { tripHeadsign = tripHeadsign.toLowerCase(Locale.ENGLISH); tripHeadsign = CleanUtils.CLEAN_AT.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } @Override public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) { System.out.printf("\nUnexptected trips to merge %s & %s!\n", mTrip, mTripToMerge); System.exit(-1); return false; } private static final Pattern SIDE = Pattern.compile("((^|\\W){1}(side)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String SIDE_REPLACEMENT = "$2$4"; private static final Pattern EAST_ = Pattern.compile("((^|\\W){1}(east)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String EAST_REPLACEMENT = "$2E$4"; private static final Pattern WEST_ = Pattern.compile("((^|\\W){1}(west)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String WEST_REPLACEMENT = "$2W$4"; private static final Pattern NORTH_ = Pattern.compile("((^|\\W){1}(north)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String NORTH_REPLACEMENT = "$2N$4"; private static final Pattern SOUTH_ = Pattern.compile("((^|\\W){1}(south)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String SOUTH_REPLACEMENT = "$2S$4"; @Override public String cleanStopName(String gStopName) { gStopName = gStopName.toLowerCase(Locale.ENGLISH); gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); gStopName = SIDE.matcher(gStopName).replaceAll(SIDE_REPLACEMENT); gStopName = EAST_.matcher(gStopName).replaceAll(EAST_REPLACEMENT); gStopName = WEST_.matcher(gStopName).replaceAll(WEST_REPLACEMENT); gStopName = NORTH_.matcher(gStopName).replaceAll(NORTH_REPLACEMENT); gStopName = SOUTH_.matcher(gStopName).replaceAll(SOUTH_REPLACEMENT); gStopName = CleanUtils.removePoints(gStopName); gStopName = CleanUtils.cleanStreetTypes(gStopName); gStopName = CleanUtils.cleanNumbers(gStopName); return CleanUtils.cleanLabel(gStopName); } }
src/org/mtransit/parser/ca_toronto_ttc_light_rail/TorontoTTCLightRailAgencyTools.java
package org.mtransit.parser.ca_toronto_ttc_light_rail; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import org.mtransit.parser.CleanUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.Pair; import org.mtransit.parser.SplitUtils; import org.mtransit.parser.Utils; import org.mtransit.parser.SplitUtils.RouteTripSpec; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.gtfs.data.GTripStop; import org.mtransit.parser.mt.data.MAgency; import org.mtransit.parser.mt.data.MDirectionType; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.mt.data.MTrip; import org.mtransit.parser.mt.data.MTripStop; // http://www1.toronto.ca/wps/portal/contentonly?vgnextoid=96f236899e02b210VgnVCM1000003dd60f89RCRD // http://opendata.toronto.ca/TTC/routes/OpenData_TTC_Schedules.zip public class TorontoTTCLightRailAgencyTools extends DefaultAgencyTools { public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-toronto-ttc-light-rail-android/res/raw/"; args[2] = ""; // files-prefix } new TorontoTTCLightRailAgencyTools().start(args); } private HashSet<String> serviceIds; @Override public void start(String[] args) { System.out.printf("\nGenerating TTC light rail data..."); long start = System.currentTimeMillis(); this.serviceIds = extractUsefulServiceIds(args, this); super.start(args); System.out.printf("\nGenerating TTC light rail data... DONE in %s.", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludingAll() { return this.serviceIds != null && this.serviceIds.isEmpty(); } @Override public boolean excludeCalendar(GCalendar gCalendar) { if (this.serviceIds != null) { return excludeUselessCalendar(gCalendar, this.serviceIds); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { if (this.serviceIds != null) { return excludeUselessCalendarDate(gCalendarDates, this.serviceIds); } return super.excludeCalendarDate(gCalendarDates); } @Override public boolean excludeRoute(GRoute gRoute) { return super.excludeRoute(gRoute); } @Override public boolean excludeTrip(GTrip gTrip) { if (this.serviceIds != null) { return excludeUselessTrip(gTrip, this.serviceIds); } return super.excludeTrip(gTrip); } @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_LIGHT_RAIL; } @Override public long getRouteId(GRoute gRoute) { return Long.parseLong(gRoute.getRouteShortName()); // using route short name as route ID } @Override public String getRouteLongName(GRoute gRoute) { return cleanRouteLongName(gRoute); } private String cleanRouteLongName(GRoute gRoute) { String routeLongName = gRoute.getRouteLongName(); routeLongName = routeLongName.toLowerCase(Locale.ENGLISH); return CleanUtils.cleanLabel(routeLongName); } private static final String AGENCY_COLOR = "B80000"; // RED (AGENCY WEB SITE CSS) @Override public String getAgencyColor() { return AGENCY_COLOR; } private static final String COLOR_00529F = "00529F"; // BLUE (NIGHT BUSES) @Override public String getRouteColor(GRoute gRoute) { int rsn = Integer.parseInt(gRoute.getRouteShortName()); if (rsn >= 300 && rsn <= 399) { // Night Network return COLOR_00529F; } return null; // use agency color instead of provided colors (like web site) } private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2; static { HashMap<Long, RouteTripSpec> map2 = new HashMap<Long, RouteTripSpec>(); map2.put(506L, new RouteTripSpec(506L, // MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_DIRECTION, MDirectionType.EAST.getId(), // MAIN STREET STATION MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_DIRECTION, MDirectionType.WEST.getId()) // HIGH PARK LOOP .addTripSort(MDirectionType.EAST.intValue(), // Arrays.asList(new String[] { // "5292", // HIGH PARK LOOP <= "8763", // HOWARD PARK AVE AT RONCESVALLES AVE "8999", // != HOWARD PARK AVE AT DUNDAS ST WEST "9132", // != HOWARD PARK AVE AT RONCESVALLES AVE <= "2954", // != DUNDAS ST WEST AT HOWARD PARK AVE "2243", // == DUNDAS ST WEST AT SORAUREN AVE "7506", // DUNDAS ST WEST AT STERLING RD "3797", // GERRARD ST EAST AT COXWELL AVE "8980", // COXWELL AVE AT UPPER GERRARD ST EAST "14260", // MAIN STREET STATION })) // .addTripSort(MDirectionType.WEST.intValue(), // Arrays.asList(new String[] { // "14260", // MAIN STREET STATION "10283", // COXWELL AVE AT LOWER GERRARD ST EAST "2048", // GERRARD ST EAST AT ASHDALE AVE "8135", // COLLEGE ST AT LANSDOWNE AVE "9132", // HOWARD PARK AVE AT RONCESVALLES AVE "5292", // HIGH PARK LOOP })) // .compileBothTripSort()); map2.put(510L, new RouteTripSpec(510L, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_DIRECTION, MDirectionType.NORTH.getId(), // SPADINA STATION MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_DIRECTION, MDirectionType.SOUTH.getId()) // UNION STATION .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "9227", // UNION STATION <= "6075", // != SPADINA AVE AT QUEENS QUAY WEST NORTH SIDE "478", // != <> QUEENS QUAY LOOP AT LOWER SPADINA AVE <= "9243", // == SPADINA AVE AT BREMNER BLVD NORTH SIDE "5275", // == != SPADINA AVE AT KING ST WEST NORTH SIDE "10089", // != <> CHARLOTTE ST AT OXLEY ST => "8346", // != SPADINA AVE AT RICHMOND ST WEST "7582", // SPADINA AVE AT QUEEN ST WEST NORTH SIDE "14339", // SPADINA STATION => })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // "14339", // SPADINA STATION "9203", // == != SPADINA AVE AT QUEEN ST WEST SOUTH SIDE "10089", // != <> CHARLOTTE ST AT OXLEY ST => "10138", // != SPADINA AVE AT KING ST WEST "6639", // SPADINA AVE AT BREMNER BLVD "2125", // == != QUEENS QUAY WEST AT LOWER SPADINA AVE EAST SIDE "478", // != <> QUEENS QUAY LOOP AT LOWER SPADINA AVE => "15122", // != QUEENS QUAY W AT REES ST "9227", // UNION STATION => })) // .compileBothTripSort()); ALL_ROUTE_TRIPS2 = map2; } @Override public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { if (ALL_ROUTE_TRIPS2.containsKey(routeId)) { return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this); } return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop); } @Override public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips(); } return super.splitTrip(mRoute, gTrip, gtfs); } @Override public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this); } return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS); } private static final String WEST = "west"; private static final String EAST = "east"; private static final String SOUTH = "south"; private static final String NORTH = "north"; @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return; // split } String gTripHeadsignLC = gTrip.getTripHeadsign().toLowerCase(Locale.ENGLISH); if (gTripHeadsignLC.startsWith(EAST)) { mTrip.setHeadsignDirection(MDirectionType.EAST); return; } else if (gTripHeadsignLC.startsWith(WEST)) { mTrip.setHeadsignDirection(MDirectionType.WEST); return; } else if (gTripHeadsignLC.startsWith(NORTH)) { mTrip.setHeadsignDirection(MDirectionType.NORTH); return; } else if (gTripHeadsignLC.startsWith(SOUTH)) { mTrip.setHeadsignDirection(MDirectionType.SOUTH); return; } System.out.printf("\n%s: Unexpected trip %s!\n", mRoute.getId(), gTrip); System.exit(-1); } @Override public String cleanTripHeadsign(String tripHeadsign) { tripHeadsign = tripHeadsign.toLowerCase(Locale.ENGLISH); tripHeadsign = CleanUtils.CLEAN_AT.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } @Override public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) { System.out.printf("\nUnexptected trips to merge %s & %s!\n", mTrip, mTripToMerge); System.exit(-1); return false; } private static final Pattern SIDE = Pattern.compile("((^|\\W){1}(side)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String SIDE_REPLACEMENT = "$2$4"; private static final Pattern EAST_ = Pattern.compile("((^|\\W){1}(east)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String EAST_REPLACEMENT = "$2E$4"; private static final Pattern WEST_ = Pattern.compile("((^|\\W){1}(west)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String WEST_REPLACEMENT = "$2W$4"; private static final Pattern NORTH_ = Pattern.compile("((^|\\W){1}(north)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String NORTH_REPLACEMENT = "$2N$4"; private static final Pattern SOUTH_ = Pattern.compile("((^|\\W){1}(south)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String SOUTH_REPLACEMENT = "$2S$4"; @Override public String cleanStopName(String gStopName) { gStopName = gStopName.toLowerCase(Locale.ENGLISH); gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); gStopName = SIDE.matcher(gStopName).replaceAll(SIDE_REPLACEMENT); gStopName = EAST_.matcher(gStopName).replaceAll(EAST_REPLACEMENT); gStopName = WEST_.matcher(gStopName).replaceAll(WEST_REPLACEMENT); gStopName = NORTH_.matcher(gStopName).replaceAll(NORTH_REPLACEMENT); gStopName = SOUTH_.matcher(gStopName).replaceAll(SOUTH_REPLACEMENT); gStopName = CleanUtils.removePoints(gStopName); gStopName = CleanUtils.cleanStreetTypes(gStopName); gStopName = CleanUtils.cleanNumbers(gStopName); return CleanUtils.cleanLabel(gStopName); } }
Compatibility with latest update
src/org/mtransit/parser/ca_toronto_ttc_light_rail/TorontoTTCLightRailAgencyTools.java
Compatibility with latest update
<ide><path>rc/org/mtransit/parser/ca_toronto_ttc_light_rail/TorontoTTCLightRailAgencyTools.java <ide> .addTripSort(MDirectionType.EAST.intValue(), // <ide> Arrays.asList(new String[] { // <ide> "5292", // HIGH PARK LOOP <= <add> "8673", // HOWARD PARK AVE AT PARKSIDE DR EAST SIDE {43.649054,-79.457394} <ide> "8763", // HOWARD PARK AVE AT RONCESVALLES AVE <ide> "8999", // != HOWARD PARK AVE AT DUNDAS ST WEST <ide> "9132", // != HOWARD PARK AVE AT RONCESVALLES AVE <= <ide> "2954", // != DUNDAS ST WEST AT HOWARD PARK AVE <ide> "2243", // == DUNDAS ST WEST AT SORAUREN AVE <ide> "7506", // DUNDAS ST WEST AT STERLING RD <del> "3797", // GERRARD ST EAST AT COXWELL AVE <del> "8980", // COXWELL AVE AT UPPER GERRARD ST EAST <add> "3368", // == <add> "3797", // != GERRARD ST EAST AT COXWELL AVE <add> "8980", // == COXWELL AVE AT UPPER GERRARD ST EAST <add> "549", // == <ide> "14260", // MAIN STREET STATION <ide> })) // <ide> .addTripSort(MDirectionType.WEST.intValue(), // <ide> "2048", // GERRARD ST EAST AT ASHDALE AVE <ide> "8135", // COLLEGE ST AT LANSDOWNE AVE <ide> "9132", // HOWARD PARK AVE AT RONCESVALLES AVE <add> "4538", // HOWARD PARK AVE AT PARKSIDE DR <ide> "5292", // HIGH PARK LOOP <ide> })) // <ide> .compileBothTripSort());
Java
apache-2.0
573f8c22b0be894649598ee6c842a8aefbbd41c0
0
reportportal/service-api,reportportal/service-api,reportportal/service-api,reportportal/service-api,reportportal/service-api
/* * Copyright 2019 EPAM Systems * * 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.epam.ta.reportportal.auth.basic; import com.epam.ta.reportportal.dao.UserRepository; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.core.userdetails.UsernameNotFoundException; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; /** * @author <a href="mailto:[email protected]">Ihar Kahadouski</a> */ @ExtendWith(MockitoExtension.class) class DatabaseUserDetailsServiceTest { @Mock private UserRepository userRepository; @InjectMocks private DatabaseUserDetailsService userDetailsService; @Test void userNotFoundTest() { when(userRepository.findUserDetails("not_exist")).thenReturn(Optional.empty()); UsernameNotFoundException exception = assertThrows(UsernameNotFoundException.class, () -> userDetailsService.loadUserByUsername("not_exist") ); assertEquals("User not found", exception.getMessage()); } }
src/test/java/com/epam/ta/reportportal/auth/basic/DatabaseUserDetailsServiceTest.java
/* * Copyright 2019 EPAM Systems * * 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.epam.ta.reportportal.auth.basic; import com.epam.ta.reportportal.dao.UserRepository; import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.entity.user.UserType; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; /** * @author <a href="mailto:[email protected]">Ihar Kahadouski</a> */ @ExtendWith(MockitoExtension.class) class DatabaseUserDetailsServiceTest { @Mock private UserRepository userRepository; @InjectMocks private DatabaseUserDetailsService userDetailsService; @Test void userNotFoundTest() { when(userRepository.findByLogin("not_exist")).thenReturn(Optional.empty()); UsernameNotFoundException exception = assertThrows(UsernameNotFoundException.class, () -> userDetailsService.loadUserByUsername("not_exist") ); assertEquals("User not found", exception.getMessage()); } @Test void loadUserWithEmptyPassword() { User user = new User(); user.setLogin("user"); user.setId(1L); user.setEmail("[email protected]"); user.setExpired(false); user.setUserType(UserType.INTERNAL); user.setRole(UserRole.USER); when(userRepository.findByLogin("user")).thenReturn(Optional.of(user)); UserDetails userDetails = userDetailsService.loadUserByUsername("user"); assertEquals(user.getLogin(), userDetails.getUsername()); assertTrue(userDetails.getPassword().isEmpty()); assertEquals(!user.isExpired(), userDetails.isAccountNonExpired()); } }
fix tests
src/test/java/com/epam/ta/reportportal/auth/basic/DatabaseUserDetailsServiceTest.java
fix tests
<ide><path>rc/test/java/com/epam/ta/reportportal/auth/basic/DatabaseUserDetailsServiceTest.java <ide> package com.epam.ta.reportportal.auth.basic; <ide> <ide> import com.epam.ta.reportportal.dao.UserRepository; <del>import com.epam.ta.reportportal.entity.user.User; <del>import com.epam.ta.reportportal.entity.user.UserRole; <del>import com.epam.ta.reportportal.entity.user.UserType; <ide> import org.junit.jupiter.api.Test; <ide> import org.junit.jupiter.api.extension.ExtendWith; <ide> import org.mockito.InjectMocks; <ide> import org.mockito.Mock; <ide> import org.mockito.junit.jupiter.MockitoExtension; <del>import org.springframework.security.core.userdetails.UserDetails; <ide> import org.springframework.security.core.userdetails.UsernameNotFoundException; <ide> <ide> import java.util.Optional; <ide> <del>import static org.junit.jupiter.api.Assertions.*; <add>import static org.junit.jupiter.api.Assertions.assertEquals; <add>import static org.junit.jupiter.api.Assertions.assertThrows; <ide> import static org.mockito.Mockito.when; <ide> <ide> /** <ide> <ide> @Test <ide> void userNotFoundTest() { <del> when(userRepository.findByLogin("not_exist")).thenReturn(Optional.empty()); <add> when(userRepository.findUserDetails("not_exist")).thenReturn(Optional.empty()); <ide> <ide> UsernameNotFoundException exception = assertThrows(UsernameNotFoundException.class, <ide> () -> userDetailsService.loadUserByUsername("not_exist") <ide> <ide> assertEquals("User not found", exception.getMessage()); <ide> } <del> <del> @Test <del> void loadUserWithEmptyPassword() { <del> User user = new User(); <del> user.setLogin("user"); <del> user.setId(1L); <del> user.setEmail("[email protected]"); <del> user.setExpired(false); <del> user.setUserType(UserType.INTERNAL); <del> user.setRole(UserRole.USER); <del> when(userRepository.findByLogin("user")).thenReturn(Optional.of(user)); <del> <del> UserDetails userDetails = userDetailsService.loadUserByUsername("user"); <del> <del> assertEquals(user.getLogin(), userDetails.getUsername()); <del> assertTrue(userDetails.getPassword().isEmpty()); <del> assertEquals(!user.isExpired(), userDetails.isAccountNonExpired()); <del> } <ide> }
JavaScript
mit
d6e72f9d292eb7078403626464a737edf7c073c8
0
bigpipe/bigpipe,tonybo2006/bigpipe,tonybo2006/bigpipe,PatidarWeb/bigpipe,PatidarWeb/bigpipe,bigpipe/bigpipe
/*globals Primus */ 'use strict'; var collection = require('./collection') , Pagelet = require('./pagelet') , loader = require('./loader'); /** * Pipe. * * @constructor * @param {String} server The server address we need to connect to. * @param {Object} options Pipe configuration * @api public */ function Pipe(server, options) { options = options || {}; this.stream = null; // Reference to the connected Primus socket. this.pagelets = {}; // Collection of different pagelets. this.freelist = []; // Collection of unused Pagelet instances. this.maximum = 20; // Max Pagelet instances we can reuse. this.assets = {}; // Asset cache. this.root = document.documentElement; // The <html> element. Primus.EventEmitter.call(this); this.configure(options); this.connect(server, options.primus); } // // Inherit from Primus's EventEmitter. // Pipe.prototype = new Primus.EventEmitter(); Pipe.prototype.constructor = Pipe; /** * Configure the Pipe. * * @api private */ Pipe.prototype.configure = function configure() { if (this.root.className.indexOf('no_js')) { this.root.className = this.root.className.replace('no_js', ''); } }; /** * Horrible hack, but needed to prevent memory leaks while maintaing sublime * performance. See Pagelet.prototype.IEV for more information. * * @type {Number} * @private */ Pipe.prototype.IEV = Pagelet.prototype.IEV; /** * A new Pagelet is flushed by the server. We should register it and update the * content. * * @param {String} name The name of the pagelet. * @param {Object} data Pagelet data. * @api public */ Pipe.prototype.arrive = function arrive(name, data) { if (!this.has(name)) this.create(name, data); return this; }; /** * Create a new Pagelet instance. * * @api private */ Pipe.prototype.create = function create(name, data) { var pagelet = this.pagelets[name] = this.alloc(); pagelet.configure(name, data); }; /** * Check if the pagelet has already been loaded. * * @param {String} name The name of the pagelet. * @returns {Boolean} * @api public */ Pipe.prototype.has = function has(name) { return name in this.pagelets; }; /** * Remove the pagelet. * * @param {String} name The name of the pagelet that needs to be removed. * @api public */ Pipe.prototype.remove = function remove(name) { if (this.has(name)) { this.pagelets[name].destroy(); delete this.pagelets[name]; } return this; }; /** * Load a new resource. * * @param {Element} root The root node where we should insert stuff in. * @param {String} url The location of the asset. * @param {Function} fn Completion callback. * @api private */ Pipe.prototype.load = loader.load; /** * Unload a new resource. * * @param {String} url The location of the asset. * @api private */ Pipe.prototype.unload = loader.unload; /** * Allocate a new Pagelet instance. * * @returns {Pagelet} */ Pipe.prototype.alloc = function alloc() { return this.freelist.length ? this.freelist.shift() : new Pagelet(this); }; /** * Free an allocated Pagelet instance which can be re-used again to reduce * garbage collection. * * @param {Pagelet} pagelet The pagelet instance. * @api private */ Pipe.prototype.free = function free(pagelet) { if (this.freelist.length < this.maximum) this.freelist.push(pagelet); }; /** * Setup a real-time connection to the pagelet server. * * @param {String} url The server address. * @param {Object} options The primus configuration. * @api private */ Pipe.prototype.connect = function connect(url, options) { this.stream = new Primus(url, options); };
pipe/index.js
/*globals Primus */ 'use strict'; var collection = require('./collection') , Pagelet = require('./pagelet') , loader = require('./loader'); /** * Pipe. * * @constructor * @param {String} server The server address we need to connect to. * @param {Object} options Pipe configuration * @api public */ function Pipe(server, options) { options = options || {}; this.stream = null; // Reference to the connected Primus socket. this.pagelets = {}; // Collection of different pagelets. this.freelist = []; // Collection of unused Pagelet instances. this.maximum = 20; // Max Pagelet instances we can reuse. this.assets = {}; // Asset cache. this.root = document.documentElement; // The <html> element. Primus.EventEmitter.call(this); this.configure(options); this.connect(server, options.primus); } // // Inherit from Primus's EventEmitter. // Pipe.prototype = new Primus.EventEmitter(); Pipe.prototype.constructor = Pipe; /** * Configure the Pipe. * * @api private */ Pipe.prototype.configure = function configure() { if (this.root.className.indexOf('no_js')) { this.root.className = this.root.className.replace('no_js', ''); } }; /** * A new Pagelet is flushed by the server. We should register it and update the * content. * * @param {String} name The name of the pagelet. * @param {Object} data Pagelet data. * @api public */ Pipe.prototype.arrive = function arrive(name, data) { var pagelet = this.pagelets[name] = this.alloc(); pagelet.configure(name, data); return this; }; /** * Load a new resource. * * @param {Element} root The root node where we should insert stuff in. * @param {String} url The location of the asset. * @param {Function} fn Completion callback. * @api private */ Pipe.prototype.load = loader.load; /** * Unload a new resource. * * @param {String} url The location of the asset. * @api private */ Pipe.prototype.unload = loader.unload; /** * Allocate a new Pagelet instance. * * @returns {Pagelet} */ Pipe.prototype.alloc = function alloc() { return this.freelist.length ? this.freelist.shift() : new Pagelet(this); }; /** * Free an allocated Pagelet instance which can be re-used again to reduce * garbage collection. * * @param {Pagelet} pagelet The pagelet instance. * @api private */ Pipe.prototype.free = function free(pagelet) { if (this.freelist.length < this.maximum) this.freelist.push(pagelet); }; /** * Setup a real-time connection to the pagelet server. * * @param {String} url The server address. * @param {Object} options The primus configuration. * @api private */ Pipe.prototype.connect = function connect(url, options) { this.stream = new Primus(url, options); };
[minor] Added create/has/remove API for pagelets
pipe/index.js
[minor] Added create/has/remove API for pagelets
<ide><path>ipe/index.js <ide> } <ide> }; <ide> <add>/** <add> * Horrible hack, but needed to prevent memory leaks while maintaing sublime <add> * performance. See Pagelet.prototype.IEV for more information. <add> * <add> * @type {Number} <add> * @private <add> */ <add>Pipe.prototype.IEV = Pagelet.prototype.IEV; <ide> <ide> /** <ide> * A new Pagelet is flushed by the server. We should register it and update the <ide> * @api public <ide> */ <ide> Pipe.prototype.arrive = function arrive(name, data) { <add> if (!this.has(name)) this.create(name, data); <add> return this; <add>}; <add> <add>/** <add> * Create a new Pagelet instance. <add> * <add> * @api private <add> */ <add>Pipe.prototype.create = function create(name, data) { <ide> var pagelet = this.pagelets[name] = this.alloc(); <ide> pagelet.configure(name, data); <add>}; <add> <add>/** <add> * Check if the pagelet has already been loaded. <add> * <add> * @param {String} name The name of the pagelet. <add> * @returns {Boolean} <add> * @api public <add> */ <add>Pipe.prototype.has = function has(name) { <add> return name in this.pagelets; <add>}; <add> <add>/** <add> * Remove the pagelet. <add> * <add> * @param {String} name The name of the pagelet that needs to be removed. <add> * @api public <add> */ <add>Pipe.prototype.remove = function remove(name) { <add> if (this.has(name)) { <add> this.pagelets[name].destroy(); <add> delete this.pagelets[name]; <add> } <ide> <ide> return this; <ide> };
Java
apache-2.0
e87a1625830741bcd0a21658ca51e09251b392d8
0
CMPUT301F14T03/lotsofcodingkitty,CMPUT301F14T03/lotsofcodingkitty
package ca.ualberta.cs.cmput301t03app; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; public class ViewComment extends Activity { int commentType; String questionID; String answerID; ArrayList<Comment> comments = new ArrayList<Comment>(); PostController pc = new PostController(this); private static ArrayList<String> commentBodyList = new ArrayList<String>(); ArrayAdapter<String> cla; ListView commentListView; Button commentButton; TextView commentCount; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_comment); Bundle extras = getIntent().getExtras(); commentType = extras.getInt(ViewQuestion.SET_COMMENT_TYPE); // This is used to find which mode this is set to. Either Answer // comments // or Question comments. Log.d("click", "Comment type: " + commentType); questionID = extras.getString(ViewQuestion.QUESTION_ID_KEY); switch (commentType) { case 1: comments = pc.getCommentsToQuestion(questionID); case 2: answerID = extras.getString(ViewQuestion.ANSWER_ID_KEY); comments = pc.getCommentsToAnswer(questionID, answerID); } // Set the Title (question or answer) TextView commentTitle = (TextView) findViewById(R.id.comment_title); if (commentType == 1) { commentTitle.setText(pc.getQuestion(questionID).getSubject()); } else if (commentType == 2) { commentTitle.setText(pc.getAnswer(answerID, questionID).getAnswer()); } instantiateViews(); setListeners(); setCommentAdapter(); updateCommentCount(); } public void instantiateViews() { commentButton = (Button) findViewById(R.id.comment_button); commentCount = (TextView) findViewById(R.id.comment_count); commentListView = (ListView) findViewById(R.id.commentListView); cla = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, commentBodyList); } public void setListeners() { commentButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub addComment(); } }); } public void setCommentAdapter() { getCommentBodiesFromComment(); commentListView.setAdapter(cla); } public void getCommentBodiesFromComment() { if (comments != null) { commentBodyList.clear(); for (int i = 0; i < comments.size(); i++) commentBodyList.add(comments.get(i).getCommentBody()); } } public void updateCommentCount() { if(commentType == 1){ commentCount.setText("Comments: " + String.valueOf(pc.getQuestion(questionID).countComments())); } else if(commentType == 2) { commentCount.setText("Comments: " + String.valueOf(pc.getQuestion(questionID).getAnswerByID(answerID).countAnswerComments())); } } public void addComment() { LayoutInflater li = LayoutInflater.from(this); // Get XML file to view View promptsView = li.inflate(R.layout.activity_post_dialog, null); final EditText postBody = (EditText) promptsView .findViewById(R.id.postBody); final EditText userName = (EditText) promptsView .findViewById(R.id.UsernameRespondTextView); // Create a new AlertDialog AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); // Link the alertdialog to the XML alertDialogBuilder.setView(promptsView); // Building the dialog for adding alertDialogBuilder.setPositiveButton("Comment", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String commentBodyString = (String) postBody.getText() .toString(); String userNameString = (String) userName.getText() .toString(); Comment c = new Comment(commentBodyString, userNameString); if (commentType == 1) { pc.addCommentToQuestion(c, questionID); comments = pc.getCommentsToQuestion(questionID); } else if (commentType == 2) { pc.addCommentToAnswer(c, questionID, answerID); comments = pc.getCommentsToAnswer(questionID, answerID); } //setCommentAdapter(); commentBodyList.add(commentBodyString); cla.notifyDataSetChanged(); updateCommentCount(); //<-- MIGHT NOT USE THIS } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Do nothing dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } }
cmput301t03app/src/ca/ualberta/cs/cmput301t03app/ViewComment.java
package ca.ualberta.cs.cmput301t03app; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; public class ViewComment extends Activity { int commentType; String questionID; String answerID; ArrayList<Comment> comments = new ArrayList<Comment>(); PostController pc = new PostController(this); private static ArrayList<String> commentBodyList = new ArrayList<String>(); ArrayAdapter<String> cla; ListView commentListView; Button commentButton; TextView commentCount; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_comment); Bundle extras = getIntent().getExtras(); commentType = extras.getInt(ViewQuestion.SET_COMMENT_TYPE); // This is used to find which mode this is set to. Either Answer // comments // or Question comments. Log.d("click", "Comment type: " + commentType); questionID = extras.getString(ViewQuestion.QUESTION_ID_KEY); switch (commentType) { case 1: comments = pc.getCommentsToQuestion(questionID); case 2: answerID = extras.getString(ViewQuestion.ANSWER_ID_KEY); comments = pc.getCommentsToAnswer(questionID, answerID); } // Set the Title (question or answer) TextView commentTitle = (TextView) findViewById(R.id.comment_title); if (commentType == 1) { commentTitle.setText(pc.getQuestion(questionID).getSubject()); } else if (commentType == 2) { commentTitle.setText(pc.getAnswer(answerID, questionID).getAnswer()); } instantiateViews(); setListeners(); setCommentAdapter(); updateCommentCount(); } public void instantiateViews() { commentButton = (Button) findViewById(R.id.comment_button); commentCount = (TextView) findViewById(R.id.comment_count); commentListView = (ListView) findViewById(R.id.commentListView); cla = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, commentBodyList); } public void setListeners() { commentButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub addComment(); } }); } public void setCommentAdapter() { getCommentBodiesFromComment(); commentListView.setAdapter(cla); } public void getCommentBodiesFromComment() { if (comments != null) { commentBodyList.clear(); for (int i = 0; i < comments.size(); i++) commentBodyList.add(comments.get(i).getCommentBody()); } } public void updateCommentCount() { if(commentType == 1){ commentCount.setText("Comments: " + String.valueOf(pc.getQuestion(questionID).countComments())); } // else if(commentType == 2) { // commentCount.setText("Comments: " // + String.valueOf(pc.getQuestion(questionID).getAnswers().get)); // } } public void addComment() { LayoutInflater li = LayoutInflater.from(this); // Get XML file to view View promptsView = li.inflate(R.layout.activity_post_dialog, null); final EditText postBody = (EditText) promptsView .findViewById(R.id.postBody); final EditText userName = (EditText) promptsView .findViewById(R.id.UsernameRespondTextView); // Create a new AlertDialog AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); // Link the alertdialog to the XML alertDialogBuilder.setView(promptsView); // Building the dialog for adding alertDialogBuilder.setPositiveButton("Comment", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String commentBodyString = (String) postBody.getText() .toString(); String userNameString = (String) userName.getText() .toString(); Comment c = new Comment(commentBodyString, userNameString); if (commentType == 1) { pc.addCommentToQuestion(c, questionID); comments = pc.getCommentsToQuestion(questionID); } else if (commentType == 2) { pc.addCommentToAnswer(c, questionID, answerID); comments = pc.getCommentsToAnswer(questionID, answerID); } //setCommentAdapter(); commentBodyList.add(commentBodyString); cla.notifyDataSetChanged(); updateCommentCount(); //<-- MIGHT NOT USE THIS } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Do nothing dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } }
got counts to work for both answers and questions
cmput301t03app/src/ca/ualberta/cs/cmput301t03app/ViewComment.java
got counts to work for both answers and questions
<ide><path>mput301t03app/src/ca/ualberta/cs/cmput301t03app/ViewComment.java <ide> commentCount.setText("Comments: " <ide> + String.valueOf(pc.getQuestion(questionID).countComments())); <ide> } <del>// else if(commentType == 2) { <del>// commentCount.setText("Comments: " <del>// + String.valueOf(pc.getQuestion(questionID).getAnswers().get)); <del>// } <add> else if(commentType == 2) { <add> commentCount.setText("Comments: " <add> + String.valueOf(pc.getQuestion(questionID).getAnswerByID(answerID).countAnswerComments())); <add> } <ide> } <ide> <ide>
Java
apache-2.0
98a6fbb2ad1dbb71a63a0b295813a0ad5c4bfb76
0
cwenao/DSAA
/** * Company * Copyright (C) 2014-2017 All Rights Reserved. */ package com.cwenao.datastructure; /** * 求一个最大子数组 * 假设:数组下标 中值为mid,左边元素最小下标为low,右边最大下标为high * mid = (low + high) /2 * 那么使用分治法的思想可以对任意长度>1的数组进行f分解 * 针对一个数组最大的非空连续元素的和 * 要么存在与 A[low...mid]中 要么存在 A[mid...high] * 或者存在与以mid为起点进行左右两边取最大然后求和: A[...mid...] * @author cwenao * @version $Id MaxSubArray.java, v 0.1 2017-05-03 21:07 cwenao Exp $$ */ public class MaxSubArray { /** * 求中间最大字数组 * @param sub */ public static int maxCrossingSubArray(int[] sub,int low,int mid,int high) { Integer leftSum = null; int temp = 0; for (int i = mid; i >= low; i--) { if (null == leftSum) { leftSum = sub[i]; temp = leftSum; continue; } temp = temp + sub[i]; if (temp > leftSum) { leftSum = temp; } } Integer rightSum = null; temp = 0; for(int i= mid+1; i<=high ;i++) { if (null == rightSum) { rightSum = sub[i]; temp = rightSum; continue; } temp = temp + sub[i]; if (temp > rightSum) { rightSum = temp; } } return leftSum + rightSum; } /** * 分治思想进行分解、解决、合并 * 用递归方法进行分解合并: * 因为没有限制所以递推最后一层的时候是单个元素 * 然后递归的时候进行解决合并 * * @param sub * @param low * @param high * @return */ public static int maxSubArray(int[] sub, int low, int high) { if (low == high) { return sub[low]; } int mid = (low + high) / 2; int leftSum = maxSubArray(sub, low, mid); int rightSum = maxSubArray(sub, mid + 1, high); int midSum = maxCrossingSubArray(sub, low, mid, high); int max = leftSum; if(rightSum > max) { max = rightSum; } if (midSum > max) { max = midSum; } return max; } public static void main(String[] args) { int[] maxSubArrays = new int[]{13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7}; System.out.println(maxSubArray(maxSubArrays, 0, maxSubArrays.length - 1)); } }
data-structure/src/main/java/com/cwenao/datastructure/MaxSubArray.java
/** * Company * Copyright (C) 2014-2017 All Rights Reserved. */ package com.cwenao.datastructure; /** * 求一个最大子数组 * 假设:数组下标 中值为mid,左边元素最小下标为low,右边最大下标为high * mid = (low + high) /2 * 那么使用分治法的思想可以对任意长度>1的数组进行f分解 * 针对一个数组最大的非空连续元素的和 * 要么存在与 A[low...mid]中 要么存在 A[mid...high] * 或者存在与以mid为起点进行左右两边取最大然后求和: A[...mid...] * @author cwenao * @version $Id MaxSubArray.java, v 0.1 2017-05-03 21:07 cwenao Exp $$ */ public class MaxSubArray { /** * 求中间最大字数组 * @param sub */ public static int maxCrossingSubArray(int[] sub,int low,int mid,int high) { Integer leftSum = null; int temp = 0; for (int i = mid; i >= low; i--) { if (null == leftSum) { leftSum = sub[i]; temp = leftSum; continue; } temp = temp + sub[i]; if (temp > leftSum) { leftSum = temp; } } Integer rightSum = null; temp = 0; for(int i= mid+1; i<=high ;i++) { if (null == rightSum) { rightSum = sub[i]; temp = rightSum; continue; } temp = temp + sub[i]; if (temp > rightSum) { rightSum = temp; } } return leftSum + rightSum; } /** * 分治思想进行分解、解决、合并 * 用递归方法进行分解合并: * 因为没有限制所以递推最后一层的时候是单个元素 * 然后递归的时候进行解决合并 * @param sub * @param low * @param high * @return */ public static int maxSubArray(int[] sub, int low, int high) { if (low == high) { return sub[low]; } int mid = (low + high) / 2; int leftSum = maxSubArray(sub, low, mid); int rightSum = maxSubArray(sub, mid + 1, high); int midSum = maxCrossingSubArray(sub, low, mid, high); int max = leftSum; if(rightSum > max) { max = rightSum; } if (midSum > max) { max = midSum; } return max; } public static void main(String[] args) { int[] maxSubArrays = new int[]{13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7}; System.out.println(maxSubArray(maxSubArrays, 0, maxSubArrays.length - 1)); } }
test the commit
data-structure/src/main/java/com/cwenao/datastructure/MaxSubArray.java
test the commit
<ide><path>ata-structure/src/main/java/com/cwenao/datastructure/MaxSubArray.java <ide> * 用递归方法进行分解合并: <ide> * 因为没有限制所以递推最后一层的时候是单个元素 <ide> * 然后递归的时候进行解决合并 <add> * <ide> * @param sub <ide> * @param low <ide> * @param high
Java
mit
774ac52992647e19a004573890339d26ac977a96
0
da-eto-ya/trash,da-eto-ya/trash,da-eto-ya/trash,da-eto-ya/trash,da-eto-ya/trash,da-eto-ya/trash
import java.util.Comparator; import java.util.Objects; import java.util.function.BiConsumer; import java.util.stream.IntStream; import java.util.stream.Stream; public class Streams { public static IntStream pseudoRandomStream(int seed) { return IntStream.iterate(seed, x -> (x * x / 10) % 1000); } public static <T> void findMinMax( Stream<? extends T> stream, Comparator<? super T> order, BiConsumer<? super T, ? super T> minMaxConsumer) { final T[] m = (T[]) new Object[2]; stream.forEach(x -> { if (m[0] == null || order.compare(x, m[0]) < 0) { m[0] = x; } if (m[1] == null || order.compare(x, m[1]) > 0) { m[1] = x; } }); minMaxConsumer.accept(m[0], m[1]); } public static void main(String[] args) { IntStream stream = pseudoRandomStream(13); stream.limit(8).forEach(x -> System.out.print(x + " ")); System.out.println(); findMinMax( pseudoRandomStream(13).limit(8).mapToObj(Integer::valueOf), Integer::compareTo, (Integer x, Integer y) -> System.out.println(x + " =<= " + y) ); System.out.println(); } }
java/funcinterface/src/Streams.java
import java.util.stream.IntStream; public class Streams { public static IntStream pseudoRandomStream(int seed) { return IntStream.iterate(seed, x -> (x * x / 10) % 1000); } public static void main(String[] args) { IntStream stream = pseudoRandomStream(13); stream.limit(10).forEach(x -> System.out.println(x)); } }
[java] stream: min-max
java/funcinterface/src/Streams.java
[java] stream: min-max
<ide><path>ava/funcinterface/src/Streams.java <add>import java.util.Comparator; <add>import java.util.Objects; <add>import java.util.function.BiConsumer; <ide> import java.util.stream.IntStream; <add>import java.util.stream.Stream; <ide> <ide> public class Streams { <ide> public static IntStream pseudoRandomStream(int seed) { <ide> return IntStream.iterate(seed, x -> (x * x / 10) % 1000); <ide> } <ide> <add> public static <T> void findMinMax( <add> Stream<? extends T> stream, <add> Comparator<? super T> order, <add> BiConsumer<? super T, ? super T> minMaxConsumer) { <add> final T[] m = (T[]) new Object[2]; <add> <add> stream.forEach(x -> { <add> if (m[0] == null || order.compare(x, m[0]) < 0) { <add> m[0] = x; <add> } <add> <add> if (m[1] == null || order.compare(x, m[1]) > 0) { <add> m[1] = x; <add> } <add> }); <add> <add> minMaxConsumer.accept(m[0], m[1]); <add> } <add> <ide> public static void main(String[] args) { <ide> IntStream stream = pseudoRandomStream(13); <del> stream.limit(10).forEach(x -> System.out.println(x)); <add> stream.limit(8).forEach(x -> System.out.print(x + " ")); <add> System.out.println(); <add> <add> findMinMax( <add> pseudoRandomStream(13).limit(8).mapToObj(Integer::valueOf), <add> Integer::compareTo, <add> (Integer x, Integer y) -> System.out.println(x + " =<= " + y) <add> ); <add> System.out.println(); <ide> } <ide> }
Java
mit
5957c5c955b7a71e8f34e0ee3aa00824ae1976d3
0
TinusTinus/game-engine
package nl.mvdr.tinustris.gui; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import javafx.scene.shape.Rectangle; import lombok.extern.slf4j.Slf4j; import nl.mvdr.tinustris.model.Block; import nl.mvdr.tinustris.model.OnePlayerGameState; import nl.mvdr.tinustris.model.Orientation; import nl.mvdr.tinustris.model.Point; import nl.mvdr.tinustris.model.Tetromino; import org.junit.Assert; import org.junit.Test; /** * Test class for {@link GridRenderer}. * * @author Martijn van de Rijdt */ @Slf4j public class GridRendererTest { /** Tests {@link GridRenderer#render(OnePlayerGameState)}. */ @Test public void testRenderSimpleState() { GridRenderer renderer = createGridGroup(); OnePlayerGameState state = new OnePlayerGameState(); renderer.render(state); Assert.assertFalse(renderer.getChildren().isEmpty()); } /** Tests {@link GridRenderer#render(OnePlayerGameState)} with the same game state twice. */ @Test public void testRenderSimpleStateTwice() { GridRenderer renderer = createGridGroup(); OnePlayerGameState state = new OnePlayerGameState(); renderer.render(state); renderer.render(state); Assert.assertFalse(renderer.getChildren().isEmpty()); } /** Tests {@link GridRenderer#render(OnePlayerGameState)}. */ @Test public void testRender() { GridRenderer renderer = createGridGroup(); OnePlayerGameState gameState = createNontrivialGameState(); log.info(gameState.toString()); renderer.render(gameState); Assert.assertFalse(renderer.getChildren().isEmpty()); } /** Tests {@link GridRenderer#render(OnePlayerGameState)} with the same game state twice. */ @Test public void testRenderTwice() { GridRenderer renderer = createGridGroup(); OnePlayerGameState state = createNontrivialGameState(); log.info(state.toString()); renderer.render(state); renderer.render(state); Assert.assertFalse(renderer.getChildren().isEmpty()); } /** Tests {@link GridRenderer#render(OnePlayerGameState)} with two different game states. */ @Test public void testRenderTwiceWithDifferentStates() { GridRenderer renderer = createGridGroup(); renderer.render(new OnePlayerGameState()); renderer.render(createNontrivialGameState()); Assert.assertFalse(renderer.getChildren().isEmpty()); } /** Tests {@link GridRenderer#render(OnePlayerGameState)} with a full line. */ @Test public void testRenderWithFullLine() { GridRenderer renderer = createGridGroup(); renderer.render(createGameStateWithFullLine()); Assert.assertFalse(renderer.getChildren().isEmpty()); } /** Tests {@link GridRenderer#render(OnePlayerGameState)} when a null value of GameState is passed in. */ @Test(expected = NullPointerException.class) public void testNullState() { GridRenderer renderer = createGridGroup(); renderer.render(null); } /** * Creates a new renderer. * * @return renderer */ private GridRenderer createGridGroup() { return new GridRenderer((x, y, size, block, style, framesUnitl, framesSince) -> new Rectangle()) { /** * Mock implementation which just executes the runnable on the current thread. * * @param runnable runnable to be executed */ @Override protected void runOnJavaFXThread(Runnable runnable) { log.info("Executing runnable: " + runnable); runnable.run(); } }; } /** * Creates a nontrivial game state, containing a block in the grid, an active block and a ghost. * * @return game state */ private OnePlayerGameState createNontrivialGameState() { List<Optional<Block>> grid = new ArrayList<>(Collections.nCopies(220, Optional.empty())); // add a single block at (2, 0) grid.set(2, Optional.of(Block.S)); OnePlayerGameState gameState = new OnePlayerGameState(grid, 10, Tetromino.O, new Point(5, 10), Orientation.getDefault(), Tetromino.I); return gameState; } /** * Creates a game state, containing a full line in the grid. * * @return game state */ private OnePlayerGameState createGameStateWithFullLine() { List<Optional<Block>> grid = new ArrayList<>(220); grid.addAll(Collections.nCopies(10, Optional.of(Block.S))); grid.addAll(Collections.nCopies(210, Optional.empty())); OnePlayerGameState gameState = new OnePlayerGameState(grid, 10, Tetromino.O, new Point(5, 10), Orientation.getDefault(), Tetromino.I); return gameState; } }
tinustris/src/test/java/nl/mvdr/tinustris/gui/GridRendererTest.java
package nl.mvdr.tinustris.gui; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import javafx.scene.control.Label; import javafx.scene.shape.Rectangle; import lombok.extern.slf4j.Slf4j; import nl.mvdr.tinustris.model.Block; import nl.mvdr.tinustris.model.OnePlayerGameState; import nl.mvdr.tinustris.model.Orientation; import nl.mvdr.tinustris.model.Point; import nl.mvdr.tinustris.model.Tetromino; import org.junit.Assert; import org.junit.Test; /** * Test class for {@link GridRenderer}. * * @author Martijn van de Rijdt */ @Slf4j public class GridRendererTest { /** Tests {@link GridRenderer#render(OnePlayerGameState)}. */ @Test public void testRenderSimpleState() { GridRenderer renderer = createGridGroup(); OnePlayerGameState state = new OnePlayerGameState(); renderer.render(state); Assert.assertFalse(renderer.getChildren().isEmpty()); } /** Tests {@link GridRenderer#render(OnePlayerGameState)} with the same game state twice. */ @Test public void testRenderSimpleStateTwice() { GridRenderer renderer = createGridGroup(); OnePlayerGameState state = new OnePlayerGameState(); renderer.render(state); renderer.render(state); Assert.assertFalse(renderer.getChildren().isEmpty()); } /** Tests {@link GridRenderer#render(OnePlayerGameState)}. */ @Test public void testRender() { GridRenderer renderer = createGridGroup(); OnePlayerGameState gameState = createNontrivialGameState(); log.info(gameState.toString()); renderer.render(gameState); Assert.assertFalse(renderer.getChildren().isEmpty()); } /** Tests {@link GridRenderer#render(OnePlayerGameState)} with the same game state twice. */ @Test public void testRenderTwice() { GridRenderer renderer = createGridGroup(); OnePlayerGameState state = createNontrivialGameState(); log.info(state.toString()); renderer.render(state); renderer.render(state); Assert.assertFalse(renderer.getChildren().isEmpty()); } /** Tests {@link GridRenderer#render(OnePlayerGameState)} with two different game states. */ @Test public void testRenderTwiceWithDifferentStates() { GridRenderer renderer = createGridGroup(); renderer.render(new OnePlayerGameState()); renderer.render(createNontrivialGameState()); Assert.assertFalse(renderer.getChildren().isEmpty()); } /** Tests {@link GridRenderer#render(OnePlayerGameState)} with a full line. */ @Test public void testRenderWithFullLine() { GridRenderer renderer = createGridGroup(); renderer.render(createGameStateWithFullLine()); Assert.assertFalse(renderer.getChildren().isEmpty()); } /** Tests {@link GridRenderer#render(OnePlayerGameState)} when a null value of GameState is passed in. */ @Test(expected = NullPointerException.class) public void testNullState() { GridRenderer renderer = createGridGroup(); renderer.render(null); } /** * Creates a new renderer. * * @return renderer */ private GridRenderer createGridGroup() { return new GridRenderer((x, y, size, block, style, framesUnitl, framesSince) -> new Rectangle()) { /** * Mock implementation which just executes the runnable on the current thread. * * @param runnable runnable to be executed */ @Override protected void runOnJavaFXThread(Runnable runnable) { log.info("Executing runnable: " + runnable); runnable.run(); } }; } /** * Creates a nontrivial game state, containing a block in the grid, an active block and a ghost. * * @return game state */ private OnePlayerGameState createNontrivialGameState() { List<Optional<Block>> grid = new ArrayList<>(Collections.nCopies(220, Optional.empty())); // add a single block at (2, 0) grid.set(2, Optional.of(Block.S)); OnePlayerGameState gameState = new OnePlayerGameState(grid, 10, Tetromino.O, new Point(5, 10), Orientation.getDefault(), Tetromino.I); return gameState; } /** * Creates a game state, containing a full line in the grid. * * @return game state */ private OnePlayerGameState createGameStateWithFullLine() { List<Optional<Block>> grid = new ArrayList<>(220); grid.addAll(Collections.nCopies(10, Optional.of(Block.S))); grid.addAll(Collections.nCopies(210, Optional.empty())); OnePlayerGameState gameState = new OnePlayerGameState(grid, 10, Tetromino.O, new Point(5, 10), Orientation.getDefault(), Tetromino.I); return gameState; } }
Removed unused import.
tinustris/src/test/java/nl/mvdr/tinustris/gui/GridRendererTest.java
Removed unused import.
<ide><path>inustris/src/test/java/nl/mvdr/tinustris/gui/GridRendererTest.java <ide> import java.util.List; <ide> import java.util.Optional; <ide> <del>import javafx.scene.control.Label; <ide> import javafx.scene.shape.Rectangle; <ide> import lombok.extern.slf4j.Slf4j; <ide> import nl.mvdr.tinustris.model.Block;
JavaScript
apache-2.0
f999909d54613de9dc5f1951c1a5a0f75e990683
0
cesarmarinhorj/jake,kedashoe/jake,vinodpanicker/jake,kedashoe/jake,cesarmarinhorj/jake,vinodpanicker/jake,vinodpanicker/jake,talves/jake,jakejs/jake,kedashoe/jake,cesarmarinhorj/jake,talves/jake,jakejs/jake,talves/jake
/* * Jake JavaScript build tool * Copyright 2112 Matthew Eernisse ([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. * */ var jake , fs = require('fs') , path = require('path'); /** * @constructor * A Jake task */ var Task = function () { this.constructor.prototype.initialize.apply(this, arguments); }; Task.prototype = new (function () { this.initialize = function (name, prereqs, action, async, type) { this.name = name; this.prereqs = prereqs; this.action = action; this.async = (async === true); this.type = type; this.done = false; this.fullName = null; this.desription = null; }; this.invoke = function () { jake.runTask(this.fullName, arguments, true); }; this.execute = function () { jake.reenableTask(this.fullName, false); jake.runTask(this.fullName, arguments, false); }; this.reenable = function (deep) { jake.reenableTask(this.fullName, deep); }; })(); Task.prototype.constructor = Task; var FileTask = function (name, prereqs, action, async, type) { this.constructor.prototype.initialize.apply(this, arguments); }; FileTask.prototype = new Task(); FileTask.prototype.constructor = FileTask; var DirectoryTask = function (name, prereqs, action, async, type) { this.constructor.prototype.initialize.apply(this, arguments); }; DirectoryTask.prototype = new Task(); DirectoryTask.prototype.constructor = DirectoryTask; var Namespace = function (name, parentNamespace) { this.name = name; this.parentNamespace = parentNamespace; this.childNamespaces = {}; this.tasks = {}; }; /** * @namespace * The main namespace for Jake */ jake = new function () { // Private variables // ================= // Local reference for scopage var _this = this , _taskIndex = 0 , _modTimes = {} , _workingTaskList = [] // The list of tasks/prerequisites to run, parsed recursively // and run bottom-up, so prerequisites run first , _taskList = [] // A dictionary of loaded tasks, to ensure that all tasks // run once and only once , _taskDict = {}; // The args passed to the 'jake' invocation, after the task name // Private functions // ================= /** * Crockfordian Array-test * @param {???} obj A value of indeterminate type that may * or may not be an Array */ var _isArray = function (obj) { return obj && typeof obj === 'object' && typeof obj.length === 'number' && typeof obj.splice === 'function' && !(obj.propertyIsEnumerable('length')); } , _mixin = function (t, f) { for (var p in f) { t[p] = f[p]; } return t; } /** * Tells us if the task has any prerequisites * @param {Array.<String>} prereqs An array of prerequisites * @return {Boolean} true if prereqs is a non-empty Array */ , _taskHasPrereqs = function (prereqs) { return !!(prereqs && _isArray(prereqs) && prereqs.length); } /** * Parses all prerequisites of a task (and their prerequisites, etc.) * recursively -- depth-first, so prereqs run first * @param {String} name The name of the current task whose * prerequisites are being parsed. * @param {Boolean} [isRoot] Is this the root task of a prerequisite tree or not * @param {Boolean} [includePrereqs] Whether or not to descend into prerequs */ , _parsePrereqs = function (name, isRoot, includePrereqs) { var task = _this.getTask(name) , prereqs = task ? task.prereqs : []; // No task found -- if it's the root, throw, because we know that // *should* be an existing task. Otherwise it could be a file prereq if (isRoot && !task) { throw new Error('task not found'); } else { if (includePrereqs && _taskHasPrereqs(prereqs)) { for (var i = 0, ii = prereqs.length; i < ii; i++) { _parsePrereqs(prereqs[i], false, includePrereqs); } } _workingTaskList.push(name); } }; // Public properties // ================= this.errorCode = undefined; // Name/value map of all the various tasks defined in a Jakefile. // Non-namespaced tasks are placed into 'default.' this.defaultNamespace = new Namespace('default', null); // For namespaced tasks -- tasks with no namespace are put into the // 'default' namespace so lookup code can work the same for both // namespaced and non-namespaced. this.currentNamespace = this.defaultNamespace; // Saves the description created by a 'desc' call that prefaces a // 'task' call that defines a task. this.currentTaskDescription = null; this.populateAndProcessTaskList = function (name, includePrereqs, callback) { var opts = { root: true , includePrereqs: includePrereqs }; // Parse all the prerequisites up front. This allows use of a simple // queue to run all the tasks in order, and treat sync/async essentially // the same. _parsePrereqs(name, opts, callback); }; this.createTree = function (name, isRoot, includePrereqs) { _parsePrereqs(name, isRoot, includePrereqs); }; /** * Initial function called to run the specified task. Parses all the * prerequisites and then kicks off the queue-processing * @param {String} name The name of the task to run * @param {Array} args The list of command-line args passed after * the task name -- may be a combination of plain positional args, * or name/value pairs in the form of name:value or name=value to * be placed in a final keyword/value object param */ this.runTask = function (name, args, includePrereqs) { this.createTree(name, true, includePrereqs); _taskList.splice.apply(_taskList, [_taskIndex, 0].concat(_workingTaskList)); _workingTaskList = []; this.runNextTask(args); }; this.reenableTask = function (name, includePrereqs) { _parsePrereqs(name, true, includePrereqs); if (!_workingTaskList.length) { fail('No tasks to reenable.'); } else { for (var i = 0, ii = _workingTaskList.length; i < ii; i++) { name = _workingTaskList[i]; task = this.getTask(name); task.done = false; } } _workingTaskList = []; }; /** * Looks up a function object based on its name or namespace:name * @param {String} name The name of the task to look up */ this.getTask = function (name) { var nameArr = name.split(':') , taskName = nameArr.pop() , ns = jake.defaultNamespace , currName; while (nameArr.length) { currName = nameArr.shift(); ns = ns.childNamespaces[currName]; } var task = ns.tasks[taskName]; return task; }; /** * Runs the next task in the _taskList queue until none are left * Synchronous tasks require calling "complete" afterward, and async * ones are expected to do that themselves * TODO Add a cancellable error-throw in a setTimeout to allow * an async task to timeout instead of having the script hang * indefinitely */ this.runNextTask = function (args) { var name = _taskList[_taskIndex] , task , prereqs , prereqName , prereqTask , stats , modTime; // If there are still tasks to run, do it if (name) { _taskIndex++; task = this.getTask(name); // Task, FileTask, DirectoryTask if (task) { prereqs = task.prereqs; // Run tasks only once, even if it ends up in the task queue multiple times if (task.done) { complete(); } // Okie, we haven't done this one else { // Flag this one as done, no repeatsies task.done = true; if (task instanceof FileTask) { try { stats = fs.statSync(name); modTime = stats.ctime; } catch (e) { // Assume there's a task to fall back to to generate the file } // Compare mod-time of all the prereqs with the mod-time of this task if (prereqs.length) { for (var i = 0, ii = prereqs.length; i < ii; i++) { prereqName = prereqs[i]; prereqTask = this.getTask(prereqName); // Run the action if: // 1. The prereq is a normal task // 2. A file/directory task with a mod-date more recent than // the one for this file (or this file doesn't exist yet) if (prereqTask && !(prereqTask instanceof FileTask || prereqTask instanceof DirectoryTask) || (!modTime || _modTimes[prereqName] >= modTime)) { if (typeof task.action == 'function') { task.action.apply(task, args || []); // The action may have created/modified the file // --------- // If there's a valid file at the end of running the task, // use its mod-time as last modified try { stats = fs.statSync(name); modTime = stats.ctime; } // If there's still no actual file after running the file-task, // treat this simply as a plain task -- the current time will be // the mod-time for anything that depends on this file-task catch (e) { modTime = new Date(); } } break; } } } else { if (typeof task.action == 'function') { task.action.apply(task, args || []); modTime = new Date(); } } _modTimes[name] = modTime; // Async tasks call this themselves if (!task.async) { complete(); } } else { // Run this mofo if (typeof task.action == 'function') { task.action.apply(task, args || []); } // Async tasks call this themselves if (!task.async) { complete(); } } } } // Task doesn't exist; assume file. Just get the mod-time if the file // actually exists. If it doesn't exist, we're dealing with a missing // task -- just blow up else { stats = fs.statSync(name); _modTimes[name] = stats.ctime; complete(); } } }; this.parseAllTasks = function () { var _parseNs = function (name, ns) { var nsTasks = ns.tasks , task , nsNamespaces = ns.childNamespaces , fullName; // Iterate through the tasks in each namespace for (var q in nsTasks) { task = nsTasks[q]; // Preface only the namespaced tasks fullName = name == 'default' ? q : name + ':' + q; // Save with 'taskname' or 'namespace:taskname' key task.fullName = fullName; jake.Task[fullName] = task; } for (var p in nsNamespaces) { fullName = name == 'default' ? p : name + ':' + p; _parseNs(fullName, nsNamespaces[p]); } }; _parseNs('default', jake.defaultNamespace); }; /** * Displays the list of descriptions avaliable for tasks defined in * a Jakefile */ this.showAllTaskDescriptions = function (f) { var maxTaskNameLength = 0 , task , str = '' , padding , name , descr , filter = typeof f == 'string' ? f : null; for (var p in jake.Task) { task = jake.Task[p]; // Record the length of the longest task name -- used for // pretty alignment of the task descriptions maxTaskNameLength = p.length > maxTaskNameLength ? p.length : maxTaskNameLength; } // Print out each entry with descriptions neatly aligned for (var p in jake.Task) { if (filter && p.indexOf(filter) == -1) { continue; } task = jake.Task[p]; name = '\033[32m' + p + '\033[39m '; // Create padding-string with calculated length padding = (new Array(maxTaskNameLength - p.length + 2)).join(' '); descr = task.description || '(No description)'; descr = '\033[90m # ' + descr + '\033[39m \033[37m \033[39m'; console.log('jake ' + name + padding + descr); } }; this.createTask = function () { var args = Array.prototype.slice.call(arguments) , task , type , name , action , async , prereqs = []; type = args.shift() // name, [deps], [action] // Older name (string) + deps (array) format if (typeof args[0] == 'string') { name = args.shift(); if (_isArray(args[0])) { prereqs = args.shift(); } if (typeof args[0] == 'function') { action = args.shift(); async = args.shift(); } } // name:deps, [action] // Newer object-literal syntax, e.g.: {'name': ['depA', 'depB']} else { obj = args.shift() for (var p in obj) { prereqs = prereqs.concat(obj[p]); name = p; } action = args.shift(); async = args.shift(); } if (type == 'directory') { action = function () { if (!path.existsSync(name)) { fs.mkdirSync(name, 0755); } }; task = new DirectoryTask(name, prereqs, action, async, type); } else if (type == 'file') { task = new FileTask(name, prereqs, action, async, type); } else { task = new Task(name, prereqs, action, async, type); } if (jake.currentTaskDescription) { task.description = jake.currentTaskDescription; jake.currentTaskDescription = null; } jake.currentNamespace.tasks[name] = task; }; }(); jake.Task = Task; jake.Namespace = Namespace; module.exports = jake;
lib/jake.js
/* * Jake JavaScript build tool * Copyright 2112 Matthew Eernisse ([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. * */ var jake , fs = require('fs') , path = require('path'); /** * @constructor * A Jake task */ var Task = function () { this.constructor.prototype.initialize.apply(this, arguments); }; Task.prototype = new (function () { this.initialize = function (name, prereqs, action, async, type) { this.name = name; this.prereqs = prereqs; this.action = action; this.async = (async === true); this.type = type; this.done = false; this.fullName = null; this.desription = null; }; this.invoke = function () { jake.runTask(this.fullName, arguments, true); }; this.execute = function () { jake.reenableTask(this.fullName, false); jake.runTask(this.fullName, arguments, false); }; this.reenable = function (deep) { jake.reenableTask(this.fullName, deep); }; })(); Task.prototype.constructor = Task; var FileTask = function (name, prereqs, action, async, type) { this.constructor.prototype.initialize.apply(this, arguments); }; FileTask.prototype = new Task(); FileTask.prototype.constructor = FileTask; var DirectoryTask = function (name, prereqs, action, async, type) { this.constructor.prototype.initialize.apply(this, arguments); }; DirectoryTask.prototype = new Task(); DirectoryTask.prototype.constructor = DirectoryTask; var Namespace = function (name, parentNamespace) { this.name = name; this.parentNamespace = parentNamespace; this.childNamespaces = {}; this.tasks = {}; }; /** * @namespace * The main namespace for Jake */ jake = new function () { // Private variables // ================= // Local reference for scopage var _this = this , _taskIndex = 0 , _modTimes = {} , _workingTaskList = [] // The list of tasks/prerequisites to run, parsed recursively // and run bottom-up, so prerequisites run first , _taskList = [] // A dictionary of loaded tasks, to ensure that all tasks // run once and only once , _taskDict = {}; // The args passed to the 'jake' invocation, after the task name // Private functions // ================= /** * Crockfordian Array-test * @param {???} obj A value of indeterminate type that may * or may not be an Array */ var _isArray = function (obj) { return obj && typeof obj === 'object' && typeof obj.length === 'number' && typeof obj.splice === 'function' && !(obj.propertyIsEnumerable('length')); } , _mixin = function (t, f) { for (var p in f) { t[p] = f[p]; } return t; } /** * Tells us if the task has any prerequisites * @param {Array.<String>} prereqs An array of prerequisites * @return {Boolean} true if prereqs is a non-empty Array */ , _taskHasPrereqs = function (prereqs) { return !!(prereqs && _isArray(prereqs) && prereqs.length); } /** * Parses all prerequisites of a task (and their prerequisites, etc.) * recursively -- depth-first, so prereqs run first * @param {String} name The name of the current task whose * prerequisites are being parsed. * @param {Boolean} [isRoot] Is this the root task of a prerequisite tree or not * @param {Boolean} [includePrereqs] Whether or not to descend into prerequs */ , _parsePrereqs = function (name, isRoot, includePrereqs) { var task = _this.getTask(name) , prereqs = task ? task.prereqs : []; // No task found -- if it's the root, throw, because we know that // *should* be an existing task. Otherwise it could be a file prereq if (isRoot && !task) { throw new Error('task not found'); } else { if (includePrereqs && _taskHasPrereqs(prereqs)) { for (var i = 0, ii = prereqs.length; i < ii; i++) { _parsePrereqs(prereqs[i], false, includePrereqs); } } _workingTaskList.push(name); } }; // Public properties // ================= this.errorCode = undefined; // Name/value map of all the various tasks defined in a Jakefile. // Non-namespaced tasks are placed into 'default.' this.defaultNamespace = new Namespace('default', null); // For namespaced tasks -- tasks with no namespace are put into the // 'default' namespace so lookup code can work the same for both // namespaced and non-namespaced. this.currentNamespace = this.defaultNamespace; // Saves the description created by a 'desc' call that prefaces a // 'task' call that defines a task. this.currentTaskDescription = null; this.populateAndProcessTaskList = function (name, includePrereqs, callback) { var opts = { root: true , includePrereqs: includePrereqs }; // Parse all the prerequisites up front. This allows use of a simple // queue to run all the tasks in order, and treat sync/async essentially // the same. _parsePrereqs(name, opts, callback); }; this.createTree = function (name, isRoot, includePrereqs) { _parsePrereqs(name, isRoot, includePrereqs); }; /** * Initial function called to run the specified task. Parses all the * prerequisites and then kicks off the queue-processing * @param {String} name The name of the task to run * @param {Array} args The list of command-line args passed after * the task name -- may be a combination of plain positional args, * or name/value pairs in the form of name:value or name=value to * be placed in a final keyword/value object param */ this.runTask = function (name, args, includePrereqs) { this.createTree(name, true, includePrereqs); _taskList.splice.apply(_taskList, [_taskIndex, 0].concat(_workingTaskList)); _workingTaskList = []; this.runNextTask(args); }; this.reenableTask = function (name, includePrereqs) { _parsePrereqs(name, true, includePrereqs); if (!_workingTaskList.length) { fail('No tasks to reenable.'); } else { for (var i = 0, ii = _workingTaskList.length; i < ii; i++) { name = _workingTaskList[i]; task = this.getTask(name); task.done = false; } } _workingTaskList = []; }; /** * Looks up a function object based on its name or namespace:name * @param {String} name The name of the task to look up */ this.getTask = function (name) { var nameArr = name.split(':') , taskName = nameArr.pop() , ns = jake.defaultNamespace , currName; while (nameArr.length) { currName = nameArr.shift(); ns = ns.childNamespaces[currName]; } var task = ns.tasks[taskName]; return task; }; /** * Runs the next task in the _taskList queue until none are left * Synchronous tasks require calling "complete" afterward, and async * ones are expected to do that themselves * TODO Add a cancellable error-throw in a setTimeout to allow * an async task to timeout instead of having the script hang * indefinitely */ this.runNextTask = function (args) { var name = _taskList[_taskIndex] , task , prereqs , prereqName , prereqTask , stats , modTime; // If there are still tasks to run, do it if (name) { _taskIndex++; task = this.getTask(name); // Task, FileTask, DirectoryTask if (task) { prereqs = task.prereqs; // Run tasks only once, even if it ends up in the task queue multiple times if (task.done) { complete(); } // Okie, we haven't done this one else { // Flag this one as done, no repeatsies task.done = true; if (task instanceof FileTask) { try { stats = fs.statSync(name); modTime = stats.ctime; } catch (e) { // Assume there's a task to fall back to to generate the file } // Compare mod-time of all the prereqs with the mod-time of this task if (prereqs.length) { for (var i = 0, ii = prereqs.length; i < ii; i++) { prereqName = prereqs[i]; prereqTask = this.getTask(prereqName); // Run the action if: // 1. The prereq is a normal task // 2. A file/directory task with a mod-date more recent than // the one for this file (or this file doesn't exist yet) if (!(prereqTask instanceof FileTask || prereqTask instanceof DirectoryTask) || (!modTime || _modTimes[prereqName] > modTime)) { if (typeof task.action == 'function') { task.action.apply(task, args || []); // The action may have created/modified the file // --------- // If there's a valid file at the end of running the task, // use its mod-time as last modified try { stats = fs.statSync(name); modTime = stats.ctime; } // If there's still no actual file after running the file-task, // treat this simply as a plain task -- the current time will be // the mod-time for anything that depends on this file-task catch (e) { modTime = new Date(); } } break; } } } else { if (typeof task.action == 'function') { task.action.apply(task, args || []); modTime = new Date(); } } _modTimes[name] = modTime; // Async tasks call this themselves if (!task.async) { complete(); } } else { // Run this mofo if (typeof task.action == 'function') { task.action.apply(task, args || []); } // Async tasks call this themselves if (!task.async) { complete(); } } } } // Task doesn't exist; assume file. Just get the mod-time if the file // actually exists. If it doesn't exist, we're dealing with a missing // task -- just blow up else { stats = fs.statSync(name); _modTimes[name] = stats.ctime; complete(); } } }; this.parseAllTasks = function () { var _parseNs = function (name, ns) { var nsTasks = ns.tasks , task , nsNamespaces = ns.childNamespaces , fullName; // Iterate through the tasks in each namespace for (var q in nsTasks) { task = nsTasks[q]; // Preface only the namespaced tasks fullName = name == 'default' ? q : name + ':' + q; // Save with 'taskname' or 'namespace:taskname' key task.fullName = fullName; jake.Task[fullName] = task; } for (var p in nsNamespaces) { fullName = name == 'default' ? p : name + ':' + p; _parseNs(fullName, nsNamespaces[p]); } }; _parseNs('default', jake.defaultNamespace); }; /** * Displays the list of descriptions avaliable for tasks defined in * a Jakefile */ this.showAllTaskDescriptions = function (f) { var maxTaskNameLength = 0 , task , str = '' , padding , name , descr , filter = typeof f == 'string' ? f : null; for (var p in jake.Task) { task = jake.Task[p]; // Record the length of the longest task name -- used for // pretty alignment of the task descriptions maxTaskNameLength = p.length > maxTaskNameLength ? p.length : maxTaskNameLength; } // Print out each entry with descriptions neatly aligned for (var p in jake.Task) { if (filter && p.indexOf(filter) == -1) { continue; } task = jake.Task[p]; name = '\033[32m' + p + '\033[39m '; // Create padding-string with calculated length padding = (new Array(maxTaskNameLength - p.length + 2)).join(' '); descr = task.description || '(No description)'; descr = '\033[90m # ' + descr + '\033[39m \033[37m \033[39m'; console.log('jake ' + name + padding + descr); } }; this.createTask = function () { var args = Array.prototype.slice.call(arguments) , task , type , name , action , async , prereqs = []; type = args.shift() // name, [deps], [action] // Older name (string) + deps (array) format if (typeof args[0] == 'string') { name = args.shift(); if (_isArray(args[0])) { prereqs = args.shift(); } if (typeof args[0] == 'function') { action = args.shift(); async = args.shift(); } } // name:deps, [action] // Newer object-literal syntax, e.g.: {'name': ['depA', 'depB']} else { obj = args.shift() for (var p in obj) { prereqs = prereqs.concat(obj[p]); name = p; } action = args.shift(); async = args.shift(); } if (type == 'directory') { action = function () { if (!path.existsSync(name)) { fs.mkdirSync(name, 0755); } }; task = new DirectoryTask(name, prereqs, action, async, type); } else if (type == 'file') { task = new FileTask(name, prereqs, action, async, type); } else { task = new Task(name, prereqs, action, async, type); } if (jake.currentTaskDescription) { task.description = jake.currentTaskDescription; jake.currentTaskDescription = null; } jake.currentNamespace.tasks[name] = task; }; }(); jake.Task = Task; jake.Namespace = Namespace; module.exports = jake;
Fix issue #43
lib/jake.js
Fix issue #43
<ide><path>ib/jake.js <ide> // 1. The prereq is a normal task <ide> // 2. A file/directory task with a mod-date more recent than <ide> // the one for this file (or this file doesn't exist yet) <del> if (!(prereqTask instanceof FileTask || prereqTask instanceof DirectoryTask) <del> || (!modTime || _modTimes[prereqName] > modTime)) { <add> if (prereqTask && !(prereqTask instanceof FileTask || prereqTask instanceof DirectoryTask) <add> || (!modTime || _modTimes[prereqName] >= modTime)) { <ide> if (typeof task.action == 'function') { <ide> task.action.apply(task, args || []); <ide> // The action may have created/modified the file
Java
apache-2.0
aa4917619b4f2e6d884f05750970056bc0bc70a0
0
allotria/intellij-community,signed/intellij-community,fitermay/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,samthor/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,kool79/intellij-community,amith01994/intellij-community,ibinti/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,kool79/intellij-community,izonder/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,FHannes/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,caot/intellij-community,da1z/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,signed/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,jexp/idea2,SerCeMan/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,supersven/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,slisson/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,izonder/intellij-community,vladmm/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,jexp/idea2,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,izonder/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,consulo/consulo,kdwink/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,joewalnes/idea-community,asedunov/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,allotria/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,holmes/intellij-community,ernestp/consulo,wreckJ/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,asedunov/intellij-community,semonte/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,signed/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,joewalnes/idea-community,adedayo/intellij-community,FHannes/intellij-community,samthor/intellij-community,fitermay/intellij-community,da1z/intellij-community,supersven/intellij-community,robovm/robovm-studio,ryano144/intellij-community,samthor/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,caot/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,kdwink/intellij-community,xfournet/intellij-community,jexp/idea2,diorcety/intellij-community,blademainer/intellij-community,ernestp/consulo,caot/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,robovm/robovm-studio,consulo/consulo,ol-loginov/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,FHannes/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,amith01994/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,signed/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,jexp/idea2,apixandru/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,clumsy/intellij-community,adedayo/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,holmes/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,ryano144/intellij-community,holmes/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,kdwink/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,ibinti/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,kdwink/intellij-community,allotria/intellij-community,youdonghai/intellij-community,signed/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,consulo/consulo,SerCeMan/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,jagguli/intellij-community,signed/intellij-community,kool79/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,ryano144/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,kdwink/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,consulo/consulo,consulo/consulo,michaelgallacher/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,izonder/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,petteyg/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,da1z/intellij-community,gnuhub/intellij-community,caot/intellij-community,fnouama/intellij-community,apixandru/intellij-community,dslomov/intellij-community,da1z/intellij-community,retomerz/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,semonte/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,jexp/idea2,ibinti/intellij-community,retomerz/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,vvv1559/intellij-community,signed/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,ernestp/consulo,orekyuu/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,ernestp/consulo,orekyuu/intellij-community,ryano144/intellij-community,samthor/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,fitermay/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,dslomov/intellij-community,amith01994/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,signed/intellij-community,xfournet/intellij-community,supersven/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,retomerz/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,dslomov/intellij-community,izonder/intellij-community,jagguli/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,joewalnes/idea-community,petteyg/intellij-community,tmpgit/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,da1z/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,jexp/idea2,hurricup/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,kool79/intellij-community,semonte/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,fnouama/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,allotria/intellij-community,vvv1559/intellij-community,holmes/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,vladmm/intellij-community,caot/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,apixandru/intellij-community,slisson/intellij-community,Lekanich/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,da1z/intellij-community,adedayo/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,caot/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,xfournet/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,joewalnes/idea-community,xfournet/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,jexp/idea2,Lekanich/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,FHannes/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,holmes/intellij-community,supersven/intellij-community,robovm/robovm-studio,kdwink/intellij-community,fitermay/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,fitermay/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,supersven/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,kdwink/intellij-community,fitermay/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,clumsy/intellij-community,amith01994/intellij-community,petteyg/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,signed/intellij-community,adedayo/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,ernestp/consulo,orekyuu/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,caot/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,allotria/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,petteyg/intellij-community,supersven/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,semonte/intellij-community,jexp/idea2,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,joewalnes/idea-community,muntasirsyed/intellij-community,asedunov/intellij-community,joewalnes/idea-community,holmes/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,slisson/intellij-community,joewalnes/idea-community,kdwink/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,xfournet/intellij-community,slisson/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,allotria/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,blademainer/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,izonder/intellij-community,robovm/robovm-studio,da1z/intellij-community,tmpgit/intellij-community,semonte/intellij-community,signed/intellij-community,ryano144/intellij-community,da1z/intellij-community,diorcety/intellij-community,clumsy/intellij-community,ryano144/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,supersven/intellij-community,vladmm/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,clumsy/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,izonder/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,da1z/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,hurricup/intellij-community,fitermay/intellij-community,semonte/intellij-community,ryano144/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,fnouama/intellij-community,izonder/intellij-community,apixandru/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,kool79/intellij-community,adedayo/intellij-community,caot/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,signed/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,allotria/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,clumsy/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,dslomov/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,semonte/intellij-community
package com.intellij.openapi.project.impl; import com.intellij.ide.AppLifecycleListener; import com.intellij.ide.highlighter.WorkspaceFileType; import com.intellij.ide.impl.ProjectUtil; import com.intellij.ide.startup.impl.StartupManagerImpl; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.application.impl.ApplicationImpl; import com.intellij.openapi.components.ExportableApplicationComponent; import com.intellij.openapi.components.StateStorage; import com.intellij.openapi.components.impl.stores.IComponentStore; import com.intellij.openapi.components.impl.stores.IProjectStore; import com.intellij.openapi.components.impl.stores.XmlElementStorage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.project.ProjectReloadState; import com.intellij.openapi.project.ex.ProjectEx; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileEvent; import com.intellij.openapi.vfs.VirtualFileManagerListener; import com.intellij.openapi.vfs.ex.VirtualFileManagerEx; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.util.Alarm; import com.intellij.util.ProfilingUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashMap; import com.intellij.util.io.fs.IFile; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusConnection; import gnu.trove.TObjectLongHashMap; import org.jdom.Element; import org.jdom.JDOMException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.*; public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExternalizable, ExportableApplicationComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.project.impl.ProjectManagerImpl"); public static final int CURRENT_FORMAT_VERSION = 4; private static final Key<ArrayList<ProjectManagerListener>> LISTENERS_IN_PROJECT_KEY = Key.create("LISTENERS_IN_PROJECT_KEY"); @NonNls private static final String ELEMENT_DEFAULT_PROJECT = "defaultProject"; @SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"}) private ProjectImpl myDefaultProject; // Only used asynchronously in save and dispose, which itself are synchronized. @SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"}) private Element myDefaultProjectRootElement; // Only used asynchronously in save and dispose, which itself are synchronized. private final ArrayList<Project> myOpenProjects = new ArrayList<Project>(); private final List<ProjectManagerListener> myListeners = ContainerUtil.createEmptyCOWList(); private Project myCurrentTestProject = null; private final Map<VirtualFile, byte[]> mySavedCopies = new HashMap<VirtualFile, byte[]>(); private final TObjectLongHashMap<VirtualFile> mySavedTimestamps = new TObjectLongHashMap<VirtualFile>(); private final HashMap<Project, List<Pair<VirtualFile, StateStorage>>> myChangedProjectFiles = new HashMap<Project, List<Pair<VirtualFile, StateStorage>>>(); private final Alarm myChangedFilesAlarm = new Alarm(); private final List<Pair<VirtualFile, StateStorage>> myChangedApplicationFiles = new ArrayList<Pair<VirtualFile, StateStorage>>(); private volatile int myReloadBlockCount = 0; private final Map<Project, String> myProjects = new WeakHashMap<Project, String>(); private static final int MAX_LEAKY_PROJECTS = 42; private static ProjectManagerListener[] getListeners(Project project) { ArrayList<ProjectManagerListener> array = project.getUserData(LISTENERS_IN_PROJECT_KEY); if (array == null) return ProjectManagerListener.EMPTY_ARRAY; return array.toArray(new ProjectManagerListener[array.size()]); } public ProjectManagerImpl(VirtualFileManagerEx virtualFileManagerEx) { Application app = ApplicationManager.getApplication(); MessageBus messageBus = app.getMessageBus(); MessageBusConnection connection = messageBus.connect(app); connection.subscribe(StateStorage.STORAGE_TOPIC, new StateStorage.Listener() { public void storageFileChanged(final VirtualFileEvent event, @NotNull final StateStorage storage) { VirtualFile file = event.getFile(); if (!file.isDirectory()) { if (!((ApplicationImpl)ApplicationManager.getApplication()).isSaving() && !(event.getRequestor() instanceof StateStorage.SaveSession)) { saveChangedProjectFile(file, null, storage); } } } }); addProjectManagerListener( new ProjectManagerListener() { public void projectOpened(final Project project) { MessageBus messageBus = project.getMessageBus(); MessageBusConnection connection = messageBus.connect(project); connection.subscribe(StateStorage.STORAGE_TOPIC, new StateStorage.Listener() { public void storageFileChanged(final VirtualFileEvent event, @NotNull final StateStorage storage) { VirtualFile file = event.getFile(); if (!file.isDirectory() && !((ApplicationImpl)ApplicationManager.getApplication()).isSaving() && !(event.getRequestor() instanceof StateStorage.SaveSession)) { saveChangedProjectFile(file, project, storage); } } }); ProjectManagerListener[] listeners = getListeners(project); for (ProjectManagerListener listener : listeners) { listener.projectOpened(project); } } public void projectClosed(Project project) { ProjectManagerListener[] listeners = getListeners(project); for (ProjectManagerListener listener : listeners) { listener.projectClosed(project); } } public boolean canCloseProject(Project project) { ProjectManagerListener[] listeners = getListeners(project); for (ProjectManagerListener listener : listeners) { if (!listener.canCloseProject(project)) { return false; } } return true; } public void projectClosing(Project project) { ProjectManagerListener[] listeners = getListeners(project); for (ProjectManagerListener listener : listeners) { listener.projectClosing(project); } } } ); registerExternalProjectFileListener(virtualFileManagerEx); } public void disposeComponent() { Disposer.dispose(myChangedFilesAlarm); if (myDefaultProject != null) { Disposer.dispose(myDefaultProject); myDefaultProject = null; } } public void initComponent() { } @Nullable public Project newProject(final String projectName, String filePath, boolean useDefaultProjectSettings, boolean isDummy) { filePath = canonicalize(filePath); /* if (ApplicationManager.getApplication().isUnitTestMode()) { for (int i = 0; i < 42; i++) { if (myProjects.size() < MAX_LEAKY_PROJECTS) break; System.gc(); try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } System.gc(); } if (myProjects.size() >= MAX_LEAKY_PROJECTS) { List<Project> copy = new ArrayList<Project>(myProjects.keySet()); myProjects.clear(); throw new TooManyProjectLeakedException(copy); } } */ try { ProjectImpl project = createAndInitProject(projectName, filePath, false, isDummy, ApplicationManager.getApplication().isUnitTestMode(), useDefaultProjectSettings ? getDefaultProject() : null, null); myProjects.put(project, null); return project; } catch (final Exception e) { LOG.info(e); Messages.showErrorDialog(message(e), ProjectBundle.message("project.load.default.error")); } return null; } @NonNls private static String message(Throwable e) { String message = e.getMessage(); if (message != null) return message; message = e.getLocalizedMessage(); if (message != null) return message; message = e.toString(); Throwable cause = e.getCause(); if (cause != null) { String causeMessage = message(cause); return message + " (cause: " + causeMessage + ")"; } return message; } private ProjectImpl createAndInitProject(String projectName, String filePath, boolean isDefault, boolean isDummy, boolean isOptimiseTestLoadSpeed, @Nullable Project template, @Nullable Pair<Class, Object> additionalPicoContainerComponents) throws IOException { if (isDummy) { throw new UnsupportedOperationException("Dummy project is deprecated and shall not be used anymore."); } final ProjectImpl project = new ProjectImpl(this, filePath, isDefault, isOptimiseTestLoadSpeed, projectName); if (additionalPicoContainerComponents != null) { project.getPicoContainer().registerComponentInstance(additionalPicoContainerComponents.first, additionalPicoContainerComponents.second); } ApplicationManager.getApplication().getMessageBus().syncPublisher(ProjectLifecycleListener.TOPIC).beforeProjectLoaded(project); try { if (template != null) { project.getStateStore().loadProjectFromTemplate((ProjectImpl)template); } else { project.getStateStore().load(); } } catch (IOException e) { scheduleDispose(project); throw e; } catch (final StateStorage.StateStorageException e) { scheduleDispose(project); throw e; } project.loadProjectComponents(); project.init(); if (projectName != null) { ProjectDetailsComponent.getInstance(project).setProjectName(projectName); } return project; } private static void scheduleDispose(final ProjectImpl project) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { Disposer.dispose(project); } }); } @Nullable public Project loadProject(String filePath) throws IOException, JDOMException, InvalidDataException { try { return loadProject(filePath, null); } catch (StateStorage.StateStorageException e) { throw new IOException(e.getMessage()); } } @Nullable private Project loadProject(String filePath, Pair<Class, Object> additionalPicoContainerComponents) throws IOException, StateStorage.StateStorageException { filePath = canonicalize(filePath); ProjectImpl project = null; try { project = createAndInitProject(null, filePath, false, false, false, null, additionalPicoContainerComponents); } catch (ProcessCanceledException e) { if (project != null) { scheduleDispose(project); } throw e; } return project; } @Nullable protected static String canonicalize(final String filePath) { if (filePath == null) return null; try { return FileUtil.resolveShortWindowsName(filePath); } catch (IOException e) { // OK. File does not yet exist so it's canonical path will be equal to its original path. } return filePath; } @NotNull public synchronized Project getDefaultProject() { if (myDefaultProject == null) { try { myDefaultProject = createAndInitProject(null, null, true, false, ApplicationManager.getApplication().isUnitTestMode(), null, null); myDefaultProjectRootElement = null; } catch (IOException e) { LOG.error(e); } catch (StateStorage.StateStorageException e) { LOG.error(e); } } return myDefaultProject; } public Element getDefaultProjectRootElement() { return myDefaultProjectRootElement; } @NotNull public Project[] getOpenProjects() { if (ApplicationManager.getApplication().isUnitTestMode()) { final Project currentTestProject = myCurrentTestProject; if (myOpenProjects.isEmpty() && currentTestProject != null && !currentTestProject.isDisposed()) { return new Project[] {currentTestProject}; } } return myOpenProjects.toArray(new Project[myOpenProjects.size()]); } public boolean isProjectOpened(Project project) { if (ApplicationManager.getApplication().isUnitTestMode() && myOpenProjects.isEmpty() && myCurrentTestProject != null) { return project == myCurrentTestProject; } return myOpenProjects.contains(project); } public boolean openProject(final Project project) { if (myOpenProjects.contains(project)) return false; if (!ApplicationManager.getApplication().isUnitTestMode() && !((ProjectEx)project).getStateStore().checkVersion()) return false; myOpenProjects.add(project); fireProjectOpened(project); final StartupManagerImpl startupManager = (StartupManagerImpl)StartupManager.getInstance(project); boolean ok = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { public void run() { startupManager.runStartupActivities(); } }, ProjectBundle.message("project.load.progress"), true, project); if (!ok) { closeProject(project, false); notifyProjectOpenFailed(); return false; } startupManager.runPostStartupActivities(); return true; } public Project loadAndOpenProject(String filePath) throws IOException, JDOMException, InvalidDataException { return loadAndOpenProject(filePath, true); } @Nullable public Project loadAndOpenProject(final String filePath, final boolean convert) throws IOException, JDOMException, InvalidDataException { try { final Pair<Class, Object> convertorComponent; if (convert) { try { convertorComponent = convertProject(filePath); } catch (ProcessCanceledException e) { return null; } } else { convertorComponent = null; } Project project = loadProjectWithProgress(filePath, convertorComponent); if (project == null) return null; if (!openProject(project)) { Disposer.dispose(project); return null; } return project; } catch (StateStorage.StateStorageException e) { throw new IOException(e.getMessage()); } } @Nullable public Project loadProjectWithProgress(final String filePath, final Pair<Class, Object> convertorComponent) throws IOException { return loadProjectWithProgress(filePath, convertorComponent, null); } @Nullable public Project loadProjectWithProgress(final String filePath, final Pair<Class, Object> convertorComponent, Ref<Boolean> canceled) throws IOException { final IOException[] io = {null}; final StateStorage.StateStorageException[] stateStorage = {null}; if (filePath != null) { refreshProjectFiles(filePath); } final Project[] project = new Project[1]; boolean ok = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { public void run() { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); try { if (indicator != null) { indicator.setText(ProjectBundle.message("loading.components.for", filePath)); indicator.setIndeterminate(true); } project[0] = loadProject(filePath, convertorComponent); } catch (IOException e) { io[0] = e; return; } catch (StateStorage.StateStorageException e) { stateStorage[0] = e; return; } if (indicator != null) { indicator.setText(ProjectBundle.message("initializing.components")); } } }, ProjectBundle.message("project.load.progress"), true, null); if (!ok) { if (project[0] != null) { Disposer.dispose(project[0]); project[0] = null; } if (canceled != null) { canceled.set(true); } notifyProjectOpenFailed(); } if (io[0] != null) throw io[0]; if (stateStorage[0] != null) throw stateStorage[0]; if (project[0] == null || !ok) { return null; } return project [0]; } private static void refreshProjectFiles(final String filePath) { if (ApplicationManager.getApplication().isUnitTestMode() || ApplicationManager.getApplication().isDispatchThread()) { final File file = new File(filePath); if (file.isFile()) { VirtualFile projectFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath); if (projectFile != null) { projectFile.refresh(false, false); } File iwsFile = new File(file.getParentFile(), FileUtil.getNameWithoutExtension(file) + WorkspaceFileType.DOT_DEFAULT_EXTENSION); VirtualFile wsFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(iwsFile); if (wsFile != null) { wsFile.refresh(false, false); } } else { VirtualFile projectConfigDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(filePath, Project.DIRECTORY_STORE_FOLDER)); if (projectConfigDir != null && projectConfigDir.isDirectory()) { projectConfigDir.getChildren(); if (projectConfigDir instanceof NewVirtualFile) { ((NewVirtualFile)projectConfigDir).markDirtyRecursively(); } projectConfigDir.refresh(false, true); } } } } @Nullable protected Pair<Class, Object> convertProject(final String filePath) throws ProcessCanceledException { return null; } private static void notifyProjectOpenFailed() { ApplicationManager.getApplication().getMessageBus().syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed(); } private void registerExternalProjectFileListener(VirtualFileManagerEx virtualFileManager) { virtualFileManager.addVirtualFileManagerListener(new VirtualFileManagerListener() { public void beforeRefreshStart(boolean asynchonous) { } public void afterRefreshFinish(boolean asynchonous) { scheduleReloadApplicationAndProject(); } }); } private void askToReloadProjectIfConfigFilesChangedExternally() { if (!myChangedProjectFiles.isEmpty() && myReloadBlockCount == 0) { Set<Project> projects = myChangedProjectFiles.keySet(); List<Project> projectsToReload = new ArrayList<Project>(); for (Project project : projects) { if (shouldReloadProject(project)) { projectsToReload.add(project); } } for (final Project projectToReload : projectsToReload) { reloadProjectImpl(projectToReload, false, false); } myChangedProjectFiles.clear(); } } private boolean tryToReloadApplication(){ try { final Application app = ApplicationManager.getApplication(); if (app.isDisposed()) return false; final HashSet<Pair<VirtualFile, StateStorage>> causes = new HashSet<Pair<VirtualFile, StateStorage>>(myChangedApplicationFiles); if (causes.isEmpty()) return true; final boolean[] reloadOk = {false}; final LinkedHashSet<String> components = new LinkedHashSet<String>(); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { try { reloadOk[0] = ((ApplicationImpl)app).getStateStore().reload(causes, components); } catch (StateStorage.StateStorageException e) { Messages.showWarningDialog(ProjectBundle.message("project.reload.failed", e.getMessage()), ProjectBundle.message("project.reload.failed.title")); } catch (IOException e) { Messages.showWarningDialog(ProjectBundle.message("project.reload.failed", e.getMessage()), ProjectBundle.message("project.reload.failed.title")); } } }); if (!reloadOk[0] && !components.isEmpty()) { String message = "Application components were changed externally and cannot be reloaded:\n"; for (String component : components) { message += component + "\n"; } message += "Shutdown IDEA?"; if (Messages.showYesNoDialog(message, "Application Configuration Reload", Messages.getQuestionIcon()) == 0) { for (Pair<VirtualFile, StateStorage> cause : causes) { StateStorage stateStorage = cause.getSecond(); if (stateStorage instanceof XmlElementStorage) { ((XmlElementStorage)stateStorage).disableSaving(); } } ApplicationManagerEx.getApplicationEx().exit(true); } } return reloadOk[0]; } finally { myChangedApplicationFiles.clear(); } } private boolean shouldReloadProject(final Project project) { if (project.isDisposed()) return false; final HashSet<Pair<VirtualFile, StateStorage>> causes = new HashSet<Pair<VirtualFile, StateStorage>>(myChangedProjectFiles.get(project)); final boolean[] reloadOk = {false}; ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { try { reloadOk[0] = ((ProjectEx)project).getStateStore().reload(causes); } catch (StateStorage.StateStorageException e) { Messages.showWarningDialog(ProjectBundle.message("project.reload.failed", e.getMessage()), ProjectBundle.message("project.reload.failed.title")); } catch (IOException e) { Messages.showWarningDialog(ProjectBundle.message("project.reload.failed", e.getMessage()), ProjectBundle.message("project.reload.failed.title")); } } }); if (reloadOk[0]) return false; String message; if (causes.size() == 1) { message = ProjectBundle.message("project.reload.external.change.single", causes.iterator().next().first.getPresentableUrl()); } else { StringBuilder filesBuilder = new StringBuilder(); boolean first = true; Set<String> alreadyShown = new HashSet<String>(); for (Pair<VirtualFile, StateStorage> cause : causes) { String url = cause.first.getPresentableUrl(); if (!alreadyShown.contains(url)) { if (!first) filesBuilder.append("\n"); first = false; filesBuilder.append(url); alreadyShown.add(url); } } message = ProjectBundle.message("project.reload.external.change.multiple", filesBuilder.toString()); } return Messages.showYesNoDialog(project, message, ProjectBundle.message("project.reload.external.change.title"), Messages.getQuestionIcon()) == 0; } public boolean isFileSavedToBeReloaded(VirtualFile candidate) { return mySavedCopies.containsKey(candidate); } public void blockReloadingProjectOnExternalChanges() { myReloadBlockCount++; } public void unblockReloadingProjectOnExternalChanges() { myReloadBlockCount--; scheduleReloadApplicationAndProject(); } private void scheduleReloadApplicationAndProject() { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { if (!tryToReloadApplication()) return; askToReloadProjectIfConfigFilesChangedExternally(); } }, ModalityState.NON_MODAL); } public void setCurrentTestProject(@Nullable final Project project) { assert ApplicationManager.getApplication().isUnitTestMode(); myCurrentTestProject = project; } @Nullable public Project getCurrentTestProject() { assert ApplicationManager.getApplication().isUnitTestMode(); return myCurrentTestProject; } public void saveChangedProjectFile(final VirtualFile file, final Project project) { if (file.exists()) { copyToTemp(file); } registerProjectToReload(project, file, null); } private void saveChangedProjectFile(final VirtualFile file, final Project project, final StateStorage storage) { if (file.exists()) { copyToTemp(file); } registerProjectToReload(project, file, storage); } private void registerProjectToReload(final Project project, final VirtualFile cause, final StateStorage storage) { if (project != null) { List<Pair<VirtualFile, StateStorage>> changedProjectFiles = myChangedProjectFiles.get(project); if (changedProjectFiles == null) { changedProjectFiles = new ArrayList<Pair<VirtualFile, StateStorage>>(); myChangedProjectFiles.put(project, changedProjectFiles); } changedProjectFiles.add(new Pair<VirtualFile, StateStorage>(cause, storage)); } else { myChangedApplicationFiles.add(new Pair<VirtualFile, StateStorage>(cause, storage)); } myChangedFilesAlarm.cancelAllRequests(); myChangedFilesAlarm.addRequest(new Runnable() { public void run() { if (myReloadBlockCount == 0) { scheduleReloadApplicationAndProject(); } } }, 444); } private void copyToTemp(VirtualFile file) { try { final byte[] bytes = file.contentsToByteArray(); mySavedCopies.put(file, bytes); mySavedTimestamps.put(file, file.getTimeStamp()); } catch (IOException e) { LOG.error(e); } } private void restoreCopy(VirtualFile file) { try { if (file == null) return; // Externally deleted actually. if (!file.isWritable()) return; // IDEA was unable to save it as well. So no need to restore. final byte[] bytes = mySavedCopies.get(file); if (bytes != null) { try { file.setBinaryContent(bytes, -1, mySavedTimestamps.get(file)); } catch (IOException e) { Messages.showWarningDialog(ProjectBundle.message("project.reload.write.failed", file.getPresentableUrl()), ProjectBundle.message("project.reload.write.failed.title")); } } } finally { mySavedCopies.remove(file); mySavedTimestamps.remove(file); } } public void reloadProject(final Project p) { reloadProjectImpl(p, true, false); } public void reloadProjectImpl(final Project p, final boolean clearCopyToRestore, boolean takeMemorySnapshot) { if (clearCopyToRestore) { mySavedCopies.clear(); mySavedTimestamps.clear(); } reloadProject(p, takeMemorySnapshot); } public void reloadProject(@NotNull Project p, final boolean takeMemorySnapshot) { final Project[] project = {p}; ProjectReloadState.getInstance(project[0]).onBeforeAutomaticProjectReload(); final Application application = ApplicationManager.getApplication(); application.invokeLater(new Runnable() { public void run() { LOG.info("Reloading project."); ProjectImpl projectImpl = (ProjectImpl)project[0]; if (projectImpl.isDisposed()) return; IProjectStore projectStore = projectImpl.getStateStore(); final String location = projectImpl.getLocation(); final List<IFile> original; try { final IComponentStore.SaveSession saveSession = projectStore.startSave(); original = saveSession.getAllStorageFiles(true); saveSession.finishSave(); } catch (IOException e) { LOG.error(e); return; } if (project[0].isDisposed() || ProjectUtil.closeProject(project[0])) { application.runWriteAction(new Runnable() { public void run() { for (final IFile originalFile : original) { restoreCopy(LocalFileSystem.getInstance().refreshAndFindFileByIoFile(originalFile)); } } }); project[0] = null; // Let it go. if (takeMemorySnapshot) { ProfilingUtil.forceCaptureMemorySnapshot(); } ProjectUtil.openProject(location, null, true); } } }, ModalityState.NON_MODAL); } /* public boolean isOpeningProject() { return myCountOfProjectsBeingOpen > 0; } */ public boolean closeProject(final Project project) { return closeProject(project, true); } private boolean closeProject(final Project project, final boolean save) { if (!isProjectOpened(project)) return true; if (!canClose(project)) return false; final ShutDownTracker shutDownTracker = ShutDownTracker.getInstance(); shutDownTracker.registerStopperThread(Thread.currentThread()); try { if (save) { FileDocumentManager.getInstance().saveAllDocuments(); project.save(); } fireProjectClosing(project); myOpenProjects.remove(project); fireProjectClosed(project); if (save) { ApplicationEx application = ApplicationManagerEx.getApplicationEx(); if (!application.isUnitTestMode()) application.saveSettings(); } } finally { shutDownTracker.unregisterStopperThread(Thread.currentThread()); } return true; } private void fireProjectClosing(Project project) { if (LOG.isDebugEnabled()) { LOG.debug("enter: fireProjectClosing()"); } for (ProjectManagerListener listener : myListeners) { listener.projectClosing(project); } } public void addProjectManagerListener(ProjectManagerListener listener) { myListeners.add(listener); } public void removeProjectManagerListener(ProjectManagerListener listener) { boolean removed = myListeners.remove(listener); LOG.assertTrue(removed); } public void addProjectManagerListener(Project project, ProjectManagerListener listener) { ArrayList<ProjectManagerListener> listeners = project.getUserData(LISTENERS_IN_PROJECT_KEY); if (listeners == null) { listeners = new ArrayList<ProjectManagerListener>(); project.putUserData(LISTENERS_IN_PROJECT_KEY, listeners); } listeners.add(listener); } public void removeProjectManagerListener(Project project, ProjectManagerListener listener) { ArrayList<ProjectManagerListener> listeners = project.getUserData(LISTENERS_IN_PROJECT_KEY); if (listeners != null) { boolean removed = listeners.remove(listener); LOG.assertTrue(removed); } else { LOG.assertTrue(false); } } private void fireProjectOpened(Project project) { if (LOG.isDebugEnabled()) { LOG.debug("projectOpened"); } for (ProjectManagerListener listener : myListeners) { listener.projectOpened(project); } } private void fireProjectClosed(Project project) { if (LOG.isDebugEnabled()) { LOG.debug("projectClosed"); } for (ProjectManagerListener listener : myListeners) { listener.projectClosed(project); } } public boolean canClose(Project project) { if (LOG.isDebugEnabled()) { LOG.debug("enter: canClose()"); } for (ProjectManagerListener listener : myListeners) { try { if (!listener.canCloseProject(project)) return false; } catch (Throwable e) { LOG.warn(e); // DO NOT LET ANY PLUGIN to prevent closing due to exception } } return true; } public void writeExternal(Element parentNode) throws WriteExternalException { if (myDefaultProject != null) { myDefaultProject.save(); } if (myDefaultProjectRootElement == null) { //read external isn't called if config folder is absent myDefaultProjectRootElement = new Element(ELEMENT_DEFAULT_PROJECT); } myDefaultProjectRootElement.detach(); parentNode.addContent(myDefaultProjectRootElement); } public void setDefaultProjectRootElement(final Element defaultProjectRootElement) { myDefaultProjectRootElement = defaultProjectRootElement; } public void readExternal(Element parentNode) throws InvalidDataException { myDefaultProjectRootElement = parentNode.getChild(ELEMENT_DEFAULT_PROJECT); if (myDefaultProjectRootElement == null) { myDefaultProjectRootElement = new Element(ELEMENT_DEFAULT_PROJECT); } myDefaultProjectRootElement.detach(); } public String getExternalFileName() { return "project.default"; } @NotNull public String getComponentName() { return "ProjectManager"; } @NotNull public File[] getExportFiles() { return new File[]{PathManager.getOptionsFile(this)}; } @NotNull public String getPresentableName() { return ProjectBundle.message("project.default.settings"); } }
platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerImpl.java
package com.intellij.openapi.project.impl; import com.intellij.ide.AppLifecycleListener; import com.intellij.ide.highlighter.WorkspaceFileType; import com.intellij.ide.impl.ProjectUtil; import com.intellij.ide.startup.impl.StartupManagerImpl; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.application.impl.ApplicationImpl; import com.intellij.openapi.components.ExportableApplicationComponent; import com.intellij.openapi.components.StateStorage; import com.intellij.openapi.components.impl.stores.IComponentStore; import com.intellij.openapi.components.impl.stores.IProjectStore; import com.intellij.openapi.components.impl.stores.XmlElementStorage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.project.ProjectReloadState; import com.intellij.openapi.project.ex.ProjectEx; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileEvent; import com.intellij.openapi.vfs.VirtualFileManagerListener; import com.intellij.openapi.vfs.ex.VirtualFileManagerEx; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.util.Alarm; import com.intellij.util.ProfilingUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashMap; import com.intellij.util.io.fs.IFile; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusConnection; import gnu.trove.TObjectLongHashMap; import org.jdom.Element; import org.jdom.JDOMException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.*; public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExternalizable, ExportableApplicationComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.project.impl.ProjectManagerImpl"); public static final int CURRENT_FORMAT_VERSION = 4; private static final Key<ArrayList<ProjectManagerListener>> LISTENERS_IN_PROJECT_KEY = Key.create("LISTENERS_IN_PROJECT_KEY"); @NonNls private static final String ELEMENT_DEFAULT_PROJECT = "defaultProject"; @SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"}) private ProjectImpl myDefaultProject; // Only used asynchronously in save and dispose, which itself are synchronized. @SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"}) private Element myDefaultProjectRootElement; // Only used asynchronously in save and dispose, which itself are synchronized. private final ArrayList<Project> myOpenProjects = new ArrayList<Project>(); private final List<ProjectManagerListener> myListeners = ContainerUtil.createEmptyCOWList(); private Project myCurrentTestProject = null; private final Map<VirtualFile, byte[]> mySavedCopies = new HashMap<VirtualFile, byte[]>(); private final TObjectLongHashMap<VirtualFile> mySavedTimestamps = new TObjectLongHashMap<VirtualFile>(); private final HashMap<Project, List<Pair<VirtualFile, StateStorage>>> myChangedProjectFiles = new HashMap<Project, List<Pair<VirtualFile, StateStorage>>>(); private final Alarm myChangedFilesAlarm = new Alarm(); private final List<Pair<VirtualFile, StateStorage>> myChangedApplicationFiles = new ArrayList<Pair<VirtualFile, StateStorage>>(); private volatile int myReloadBlockCount = 0; private final Map<Project, String> myProjects = new WeakHashMap<Project, String>(); private static final int MAX_LEAKY_PROJECTS = 42; private static ProjectManagerListener[] getListeners(Project project) { ArrayList<ProjectManagerListener> array = project.getUserData(LISTENERS_IN_PROJECT_KEY); if (array == null) return ProjectManagerListener.EMPTY_ARRAY; return array.toArray(new ProjectManagerListener[array.size()]); } public ProjectManagerImpl(VirtualFileManagerEx virtualFileManagerEx) { Application app = ApplicationManager.getApplication(); MessageBus messageBus = app.getMessageBus(); MessageBusConnection connection = messageBus.connect(app); connection.subscribe(StateStorage.STORAGE_TOPIC, new StateStorage.Listener() { public void storageFileChanged(final VirtualFileEvent event, @NotNull final StateStorage storage) { VirtualFile file = event.getFile(); if (!file.isDirectory()) { if (!((ApplicationImpl)ApplicationManager.getApplication()).isSaving() && !(event.getRequestor() instanceof StateStorage.SaveSession)) { saveChangedProjectFile(file, null, storage); } } } }); addProjectManagerListener( new ProjectManagerListener() { public void projectOpened(final Project project) { MessageBus messageBus = project.getMessageBus(); MessageBusConnection connection = messageBus.connect(project); connection.subscribe(StateStorage.STORAGE_TOPIC, new StateStorage.Listener() { public void storageFileChanged(final VirtualFileEvent event, @NotNull final StateStorage storage) { VirtualFile file = event.getFile(); if (!file.isDirectory() && !((ApplicationImpl)ApplicationManager.getApplication()).isSaving() && !(event.getRequestor() instanceof StateStorage.SaveSession)) { saveChangedProjectFile(file, project, storage); } } }); ProjectManagerListener[] listeners = getListeners(project); for (ProjectManagerListener listener : listeners) { listener.projectOpened(project); } } public void projectClosed(Project project) { ProjectManagerListener[] listeners = getListeners(project); for (ProjectManagerListener listener : listeners) { listener.projectClosed(project); } } public boolean canCloseProject(Project project) { ProjectManagerListener[] listeners = getListeners(project); for (ProjectManagerListener listener : listeners) { if (!listener.canCloseProject(project)) { return false; } } return true; } public void projectClosing(Project project) { ProjectManagerListener[] listeners = getListeners(project); for (ProjectManagerListener listener : listeners) { listener.projectClosing(project); } } } ); registerExternalProjectFileListener(virtualFileManagerEx); } public void disposeComponent() { Disposer.dispose(myChangedFilesAlarm); if (myDefaultProject != null) { Disposer.dispose(myDefaultProject); myDefaultProject = null; } } public void initComponent() { } @Nullable public Project newProject(final String projectName, String filePath, boolean useDefaultProjectSettings, boolean isDummy) { filePath = canonicalize(filePath); if (ApplicationManager.getApplication().isUnitTestMode()) { for (int i = 0; i < 42; i++) { if (myProjects.size() < MAX_LEAKY_PROJECTS) break; System.gc(); try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } System.gc(); } if (myProjects.size() >= MAX_LEAKY_PROJECTS) { List<Project> copy = new ArrayList<Project>(myProjects.keySet()); myProjects.clear(); throw new TooManyProjectLeakedException(copy); } } try { ProjectImpl project = createAndInitProject(projectName, filePath, false, isDummy, ApplicationManager.getApplication().isUnitTestMode(), useDefaultProjectSettings ? getDefaultProject() : null, null); myProjects.put(project, null); return project; } catch (final Exception e) { LOG.info(e); Messages.showErrorDialog(message(e), ProjectBundle.message("project.load.default.error")); } return null; } @NonNls private static String message(Throwable e) { String message = e.getMessage(); if (message != null) return message; message = e.getLocalizedMessage(); if (message != null) return message; message = e.toString(); Throwable cause = e.getCause(); if (cause != null) { String causeMessage = message(cause); return message + " (cause: " + causeMessage + ")"; } return message; } private ProjectImpl createAndInitProject(String projectName, String filePath, boolean isDefault, boolean isDummy, boolean isOptimiseTestLoadSpeed, @Nullable Project template, @Nullable Pair<Class, Object> additionalPicoContainerComponents) throws IOException { if (isDummy) { throw new UnsupportedOperationException("Dummy project is deprecated and shall not be used anymore."); } final ProjectImpl project = new ProjectImpl(this, filePath, isDefault, isOptimiseTestLoadSpeed, projectName); if (additionalPicoContainerComponents != null) { project.getPicoContainer().registerComponentInstance(additionalPicoContainerComponents.first, additionalPicoContainerComponents.second); } ApplicationManager.getApplication().getMessageBus().syncPublisher(ProjectLifecycleListener.TOPIC).beforeProjectLoaded(project); try { if (template != null) { project.getStateStore().loadProjectFromTemplate((ProjectImpl)template); } else { project.getStateStore().load(); } } catch (IOException e) { scheduleDispose(project); throw e; } catch (final StateStorage.StateStorageException e) { scheduleDispose(project); throw e; } project.loadProjectComponents(); project.init(); if (projectName != null) { ProjectDetailsComponent.getInstance(project).setProjectName(projectName); } return project; } private static void scheduleDispose(final ProjectImpl project) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { Disposer.dispose(project); } }); } @Nullable public Project loadProject(String filePath) throws IOException, JDOMException, InvalidDataException { try { return loadProject(filePath, null); } catch (StateStorage.StateStorageException e) { throw new IOException(e.getMessage()); } } @Nullable private Project loadProject(String filePath, Pair<Class, Object> additionalPicoContainerComponents) throws IOException, StateStorage.StateStorageException { filePath = canonicalize(filePath); ProjectImpl project = null; try { project = createAndInitProject(null, filePath, false, false, false, null, additionalPicoContainerComponents); } catch (ProcessCanceledException e) { if (project != null) { scheduleDispose(project); } throw e; } return project; } @Nullable protected static String canonicalize(final String filePath) { if (filePath == null) return null; try { return FileUtil.resolveShortWindowsName(filePath); } catch (IOException e) { // OK. File does not yet exist so it's canonical path will be equal to its original path. } return filePath; } @NotNull public synchronized Project getDefaultProject() { if (myDefaultProject == null) { try { myDefaultProject = createAndInitProject(null, null, true, false, ApplicationManager.getApplication().isUnitTestMode(), null, null); myDefaultProjectRootElement = null; } catch (IOException e) { LOG.error(e); } catch (StateStorage.StateStorageException e) { LOG.error(e); } } return myDefaultProject; } public Element getDefaultProjectRootElement() { return myDefaultProjectRootElement; } @NotNull public Project[] getOpenProjects() { if (ApplicationManager.getApplication().isUnitTestMode()) { final Project currentTestProject = myCurrentTestProject; if (myOpenProjects.isEmpty() && currentTestProject != null && !currentTestProject.isDisposed()) { return new Project[] {currentTestProject}; } } return myOpenProjects.toArray(new Project[myOpenProjects.size()]); } public boolean isProjectOpened(Project project) { if (ApplicationManager.getApplication().isUnitTestMode() && myOpenProjects.isEmpty() && myCurrentTestProject != null) { return project == myCurrentTestProject; } return myOpenProjects.contains(project); } public boolean openProject(final Project project) { if (myOpenProjects.contains(project)) return false; if (!ApplicationManager.getApplication().isUnitTestMode() && !((ProjectEx)project).getStateStore().checkVersion()) return false; myOpenProjects.add(project); fireProjectOpened(project); final StartupManagerImpl startupManager = (StartupManagerImpl)StartupManager.getInstance(project); boolean ok = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { public void run() { startupManager.runStartupActivities(); } }, ProjectBundle.message("project.load.progress"), true, project); if (!ok) { closeProject(project, false); notifyProjectOpenFailed(); return false; } startupManager.runPostStartupActivities(); return true; } public Project loadAndOpenProject(String filePath) throws IOException, JDOMException, InvalidDataException { return loadAndOpenProject(filePath, true); } @Nullable public Project loadAndOpenProject(final String filePath, final boolean convert) throws IOException, JDOMException, InvalidDataException { try { final Pair<Class, Object> convertorComponent; if (convert) { try { convertorComponent = convertProject(filePath); } catch (ProcessCanceledException e) { return null; } } else { convertorComponent = null; } Project project = loadProjectWithProgress(filePath, convertorComponent); if (project == null) return null; if (!openProject(project)) { Disposer.dispose(project); return null; } return project; } catch (StateStorage.StateStorageException e) { throw new IOException(e.getMessage()); } } @Nullable public Project loadProjectWithProgress(final String filePath, final Pair<Class, Object> convertorComponent) throws IOException { return loadProjectWithProgress(filePath, convertorComponent, null); } @Nullable public Project loadProjectWithProgress(final String filePath, final Pair<Class, Object> convertorComponent, Ref<Boolean> canceled) throws IOException { final IOException[] io = {null}; final StateStorage.StateStorageException[] stateStorage = {null}; if (filePath != null) { refreshProjectFiles(filePath); } final Project[] project = new Project[1]; boolean ok = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { public void run() { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); try { if (indicator != null) { indicator.setText(ProjectBundle.message("loading.components.for", filePath)); indicator.setIndeterminate(true); } project[0] = loadProject(filePath, convertorComponent); } catch (IOException e) { io[0] = e; return; } catch (StateStorage.StateStorageException e) { stateStorage[0] = e; return; } if (indicator != null) { indicator.setText(ProjectBundle.message("initializing.components")); } } }, ProjectBundle.message("project.load.progress"), true, null); if (!ok) { if (project[0] != null) { Disposer.dispose(project[0]); project[0] = null; } if (canceled != null) { canceled.set(true); } notifyProjectOpenFailed(); } if (io[0] != null) throw io[0]; if (stateStorage[0] != null) throw stateStorage[0]; if (project[0] == null || !ok) { return null; } return project [0]; } private static void refreshProjectFiles(final String filePath) { if (ApplicationManager.getApplication().isUnitTestMode() || ApplicationManager.getApplication().isDispatchThread()) { final File file = new File(filePath); if (file.isFile()) { VirtualFile projectFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath); if (projectFile != null) { projectFile.refresh(false, false); } File iwsFile = new File(file.getParentFile(), FileUtil.getNameWithoutExtension(file) + WorkspaceFileType.DOT_DEFAULT_EXTENSION); VirtualFile wsFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(iwsFile); if (wsFile != null) { wsFile.refresh(false, false); } } else { VirtualFile projectConfigDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(filePath, Project.DIRECTORY_STORE_FOLDER)); if (projectConfigDir != null && projectConfigDir.isDirectory()) { projectConfigDir.getChildren(); if (projectConfigDir instanceof NewVirtualFile) { ((NewVirtualFile)projectConfigDir).markDirtyRecursively(); } projectConfigDir.refresh(false, true); } } } } @Nullable protected Pair<Class, Object> convertProject(final String filePath) throws ProcessCanceledException { return null; } private static void notifyProjectOpenFailed() { ApplicationManager.getApplication().getMessageBus().syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed(); } private void registerExternalProjectFileListener(VirtualFileManagerEx virtualFileManager) { virtualFileManager.addVirtualFileManagerListener(new VirtualFileManagerListener() { public void beforeRefreshStart(boolean asynchonous) { } public void afterRefreshFinish(boolean asynchonous) { scheduleReloadApplicationAndProject(); } }); } private void askToReloadProjectIfConfigFilesChangedExternally() { if (!myChangedProjectFiles.isEmpty() && myReloadBlockCount == 0) { Set<Project> projects = myChangedProjectFiles.keySet(); List<Project> projectsToReload = new ArrayList<Project>(); for (Project project : projects) { if (shouldReloadProject(project)) { projectsToReload.add(project); } } for (final Project projectToReload : projectsToReload) { reloadProjectImpl(projectToReload, false, false); } myChangedProjectFiles.clear(); } } private boolean tryToReloadApplication(){ try { final Application app = ApplicationManager.getApplication(); if (app.isDisposed()) return false; final HashSet<Pair<VirtualFile, StateStorage>> causes = new HashSet<Pair<VirtualFile, StateStorage>>(myChangedApplicationFiles); if (causes.isEmpty()) return true; final boolean[] reloadOk = {false}; final LinkedHashSet<String> components = new LinkedHashSet<String>(); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { try { reloadOk[0] = ((ApplicationImpl)app).getStateStore().reload(causes, components); } catch (StateStorage.StateStorageException e) { Messages.showWarningDialog(ProjectBundle.message("project.reload.failed", e.getMessage()), ProjectBundle.message("project.reload.failed.title")); } catch (IOException e) { Messages.showWarningDialog(ProjectBundle.message("project.reload.failed", e.getMessage()), ProjectBundle.message("project.reload.failed.title")); } } }); if (!reloadOk[0] && !components.isEmpty()) { String message = "Application components were changed externally and cannot be reloaded:\n"; for (String component : components) { message += component + "\n"; } message += "Shutdown IDEA?"; if (Messages.showYesNoDialog(message, "Application Configuration Reload", Messages.getQuestionIcon()) == 0) { for (Pair<VirtualFile, StateStorage> cause : causes) { StateStorage stateStorage = cause.getSecond(); if (stateStorage instanceof XmlElementStorage) { ((XmlElementStorage)stateStorage).disableSaving(); } } ApplicationManagerEx.getApplicationEx().exit(true); } } return reloadOk[0]; } finally { myChangedApplicationFiles.clear(); } } private boolean shouldReloadProject(final Project project) { if (project.isDisposed()) return false; final HashSet<Pair<VirtualFile, StateStorage>> causes = new HashSet<Pair<VirtualFile, StateStorage>>(myChangedProjectFiles.get(project)); final boolean[] reloadOk = {false}; ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { try { reloadOk[0] = ((ProjectEx)project).getStateStore().reload(causes); } catch (StateStorage.StateStorageException e) { Messages.showWarningDialog(ProjectBundle.message("project.reload.failed", e.getMessage()), ProjectBundle.message("project.reload.failed.title")); } catch (IOException e) { Messages.showWarningDialog(ProjectBundle.message("project.reload.failed", e.getMessage()), ProjectBundle.message("project.reload.failed.title")); } } }); if (reloadOk[0]) return false; String message; if (causes.size() == 1) { message = ProjectBundle.message("project.reload.external.change.single", causes.iterator().next().first.getPresentableUrl()); } else { StringBuilder filesBuilder = new StringBuilder(); boolean first = true; Set<String> alreadyShown = new HashSet<String>(); for (Pair<VirtualFile, StateStorage> cause : causes) { String url = cause.first.getPresentableUrl(); if (!alreadyShown.contains(url)) { if (!first) filesBuilder.append("\n"); first = false; filesBuilder.append(url); alreadyShown.add(url); } } message = ProjectBundle.message("project.reload.external.change.multiple", filesBuilder.toString()); } return Messages.showYesNoDialog(project, message, ProjectBundle.message("project.reload.external.change.title"), Messages.getQuestionIcon()) == 0; } public boolean isFileSavedToBeReloaded(VirtualFile candidate) { return mySavedCopies.containsKey(candidate); } public void blockReloadingProjectOnExternalChanges() { myReloadBlockCount++; } public void unblockReloadingProjectOnExternalChanges() { myReloadBlockCount--; scheduleReloadApplicationAndProject(); } private void scheduleReloadApplicationAndProject() { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { if (!tryToReloadApplication()) return; askToReloadProjectIfConfigFilesChangedExternally(); } }, ModalityState.NON_MODAL); } public void setCurrentTestProject(@Nullable final Project project) { assert ApplicationManager.getApplication().isUnitTestMode(); myCurrentTestProject = project; } @Nullable public Project getCurrentTestProject() { assert ApplicationManager.getApplication().isUnitTestMode(); return myCurrentTestProject; } public void saveChangedProjectFile(final VirtualFile file, final Project project) { if (file.exists()) { copyToTemp(file); } registerProjectToReload(project, file, null); } private void saveChangedProjectFile(final VirtualFile file, final Project project, final StateStorage storage) { if (file.exists()) { copyToTemp(file); } registerProjectToReload(project, file, storage); } private void registerProjectToReload(final Project project, final VirtualFile cause, final StateStorage storage) { if (project != null) { List<Pair<VirtualFile, StateStorage>> changedProjectFiles = myChangedProjectFiles.get(project); if (changedProjectFiles == null) { changedProjectFiles = new ArrayList<Pair<VirtualFile, StateStorage>>(); myChangedProjectFiles.put(project, changedProjectFiles); } changedProjectFiles.add(new Pair<VirtualFile, StateStorage>(cause, storage)); } else { myChangedApplicationFiles.add(new Pair<VirtualFile, StateStorage>(cause, storage)); } myChangedFilesAlarm.cancelAllRequests(); myChangedFilesAlarm.addRequest(new Runnable() { public void run() { if (myReloadBlockCount == 0) { scheduleReloadApplicationAndProject(); } } }, 444); } private void copyToTemp(VirtualFile file) { try { final byte[] bytes = file.contentsToByteArray(); mySavedCopies.put(file, bytes); mySavedTimestamps.put(file, file.getTimeStamp()); } catch (IOException e) { LOG.error(e); } } private void restoreCopy(VirtualFile file) { try { if (file == null) return; // Externally deleted actually. if (!file.isWritable()) return; // IDEA was unable to save it as well. So no need to restore. final byte[] bytes = mySavedCopies.get(file); if (bytes != null) { try { file.setBinaryContent(bytes, -1, mySavedTimestamps.get(file)); } catch (IOException e) { Messages.showWarningDialog(ProjectBundle.message("project.reload.write.failed", file.getPresentableUrl()), ProjectBundle.message("project.reload.write.failed.title")); } } } finally { mySavedCopies.remove(file); mySavedTimestamps.remove(file); } } public void reloadProject(final Project p) { reloadProjectImpl(p, true, false); } public void reloadProjectImpl(final Project p, final boolean clearCopyToRestore, boolean takeMemorySnapshot) { if (clearCopyToRestore) { mySavedCopies.clear(); mySavedTimestamps.clear(); } reloadProject(p, takeMemorySnapshot); } public void reloadProject(@NotNull Project p, final boolean takeMemorySnapshot) { final Project[] project = {p}; ProjectReloadState.getInstance(project[0]).onBeforeAutomaticProjectReload(); final Application application = ApplicationManager.getApplication(); application.invokeLater(new Runnable() { public void run() { LOG.info("Reloading project."); ProjectImpl projectImpl = (ProjectImpl)project[0]; if (projectImpl.isDisposed()) return; IProjectStore projectStore = projectImpl.getStateStore(); final String location = projectImpl.getLocation(); final List<IFile> original; try { final IComponentStore.SaveSession saveSession = projectStore.startSave(); original = saveSession.getAllStorageFiles(true); saveSession.finishSave(); } catch (IOException e) { LOG.error(e); return; } if (project[0].isDisposed() || ProjectUtil.closeProject(project[0])) { application.runWriteAction(new Runnable() { public void run() { for (final IFile originalFile : original) { restoreCopy(LocalFileSystem.getInstance().refreshAndFindFileByIoFile(originalFile)); } } }); project[0] = null; // Let it go. if (takeMemorySnapshot) { ProfilingUtil.forceCaptureMemorySnapshot(); } ProjectUtil.openProject(location, null, true); } } }, ModalityState.NON_MODAL); } /* public boolean isOpeningProject() { return myCountOfProjectsBeingOpen > 0; } */ public boolean closeProject(final Project project) { return closeProject(project, true); } private boolean closeProject(final Project project, final boolean save) { if (!isProjectOpened(project)) return true; if (!canClose(project)) return false; final ShutDownTracker shutDownTracker = ShutDownTracker.getInstance(); shutDownTracker.registerStopperThread(Thread.currentThread()); try { if (save) { FileDocumentManager.getInstance().saveAllDocuments(); project.save(); } fireProjectClosing(project); myOpenProjects.remove(project); fireProjectClosed(project); if (save) { ApplicationEx application = ApplicationManagerEx.getApplicationEx(); if (!application.isUnitTestMode()) application.saveSettings(); } } finally { shutDownTracker.unregisterStopperThread(Thread.currentThread()); } return true; } private void fireProjectClosing(Project project) { if (LOG.isDebugEnabled()) { LOG.debug("enter: fireProjectClosing()"); } for (ProjectManagerListener listener : myListeners) { listener.projectClosing(project); } } public void addProjectManagerListener(ProjectManagerListener listener) { myListeners.add(listener); } public void removeProjectManagerListener(ProjectManagerListener listener) { boolean removed = myListeners.remove(listener); LOG.assertTrue(removed); } public void addProjectManagerListener(Project project, ProjectManagerListener listener) { ArrayList<ProjectManagerListener> listeners = project.getUserData(LISTENERS_IN_PROJECT_KEY); if (listeners == null) { listeners = new ArrayList<ProjectManagerListener>(); project.putUserData(LISTENERS_IN_PROJECT_KEY, listeners); } listeners.add(listener); } public void removeProjectManagerListener(Project project, ProjectManagerListener listener) { ArrayList<ProjectManagerListener> listeners = project.getUserData(LISTENERS_IN_PROJECT_KEY); if (listeners != null) { boolean removed = listeners.remove(listener); LOG.assertTrue(removed); } else { LOG.assertTrue(false); } } private void fireProjectOpened(Project project) { if (LOG.isDebugEnabled()) { LOG.debug("projectOpened"); } for (ProjectManagerListener listener : myListeners) { listener.projectOpened(project); } } private void fireProjectClosed(Project project) { if (LOG.isDebugEnabled()) { LOG.debug("projectClosed"); } for (ProjectManagerListener listener : myListeners) { listener.projectClosed(project); } } public boolean canClose(Project project) { if (LOG.isDebugEnabled()) { LOG.debug("enter: canClose()"); } for (ProjectManagerListener listener : myListeners) { try { if (!listener.canCloseProject(project)) return false; } catch (Throwable e) { LOG.warn(e); // DO NOT LET ANY PLUGIN to prevent closing due to exception } } return true; } public void writeExternal(Element parentNode) throws WriteExternalException { if (myDefaultProject != null) { myDefaultProject.save(); } if (myDefaultProjectRootElement == null) { //read external isn't called if config folder is absent myDefaultProjectRootElement = new Element(ELEMENT_DEFAULT_PROJECT); } myDefaultProjectRootElement.detach(); parentNode.addContent(myDefaultProjectRootElement); } public void setDefaultProjectRootElement(final Element defaultProjectRootElement) { myDefaultProjectRootElement = defaultProjectRootElement; } public void readExternal(Element parentNode) throws InvalidDataException { myDefaultProjectRootElement = parentNode.getChild(ELEMENT_DEFAULT_PROJECT); if (myDefaultProjectRootElement == null) { myDefaultProjectRootElement = new Element(ELEMENT_DEFAULT_PROJECT); } myDefaultProjectRootElement.detach(); } public String getExternalFileName() { return "project.default"; } @NotNull public String getComponentName() { return "ProjectManager"; } @NotNull public File[] getExportFiles() { return new File[]{PathManager.getOptionsFile(this)}; } @NotNull public String getPresentableName() { return ProjectBundle.message("project.default.settings"); } }
project leakage assertion commented out
platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerImpl.java
project leakage assertion commented out
<ide><path>latform-impl/src/com/intellij/openapi/project/impl/ProjectManagerImpl.java <ide> public Project newProject(final String projectName, String filePath, boolean useDefaultProjectSettings, boolean isDummy) { <ide> filePath = canonicalize(filePath); <ide> <add> /* <ide> if (ApplicationManager.getApplication().isUnitTestMode()) { <ide> for (int i = 0; i < 42; i++) { <ide> if (myProjects.size() < MAX_LEAKY_PROJECTS) break; <ide> throw new TooManyProjectLeakedException(copy); <ide> } <ide> } <add> */ <ide> <ide> try { <ide> ProjectImpl project =
Java
unlicense
5a35260db13b8a0956ff5336c328e7f8dac9ab05
0
danieljohnson2/HomeSoil
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package homesoil; import com.google.common.base.*; import com.google.common.collect.*; import java.io.*; import java.util.*; import org.bukkit.*; import org.bukkit.block.*; import org.bukkit.event.*; import org.bukkit.event.world.*; import org.bukkit.scheduler.*; /** * DoomSchedule regenerates the world, a chunk at a time. Each chunk is filled * with a Warning- presently a pillar of glowstone- before it is regenerated. * Home chunks are skipped. * * The dooms schedule passes through loaded chunks in straight lines. It is not * guaranteed to hit every chunk; it passes through a random x or z row, then * picks another. It will hit nether chunks if they are loaded, but not end * chunks. * * @author DanJ and Applejinx */ public final class DoomSchedule implements Listener { private final File regenFile; private final HomeSoilPlugin plugin; private BukkitTask nextDoomPillar; public DoomSchedule(HomeSoilPlugin plugin, File regenFile) { this.plugin = Preconditions.checkNotNull(plugin); this.regenFile = Preconditions.checkNotNull(regenFile); } //////////////////////////////////////////////////////////////// // Scheduling // /** * This delay is how long we wait between doom pillars; we compute this to * be long enough that only one pillar at a time is in play. * It scales with the number of players online and the amount of terrain * they are covering, and 256 gives you a fairly lively pillar that will * keep everything pretty Sierra Club pristine. * 4096 should simulate lack of a regen mechanism, but it'll still be out * there somewhere endangering non-Home builds. * Possibly a pay-to-win mechanic where you buy regen bombs? * Lifetime puts a delay into the system while calling the regen queue, * creating a delay. */ private final int doomChunkDelay = 4096; private final int doomChunkLifetime = 128; /** * This method is called to start the task; it schedules it to run * regularly, and also hooks up events so we can tell what chunks are * loaded. * * @param plugin The plugin object for home soil; we register events with * this. */ public void start() { Bukkit.getPluginManager().registerEvents(this, plugin); runDoomScheduleLater(); for (ChunkPosition where : loadDoomedChunks()) { System.out.println(String.format( "Regenerating leftover chunk at %d, %d (%s)", where.x * 16 + 8, where.z * 16 + 8, where.worldName)); World world = where.getWorld(); world.regenerateChunk(where.x, where.z); } } /** * This method is called to stop the task, when the plugin is disabled; it * also unregisters the events, so its safe to call start() again to begin * all over again. */ public void stop() { if (nextDoomPillar != null) { nextDoomPillar.cancel(); } HandlerList.unregisterAll(this); saveDoomedChunks(); } /** * This method returns the number of ticks to wait between placing pillars. * This varies depending on how many chunks are loaded. * * @return The delay in ticks. */ private long getDoomChunkDelay() { final long expectedChunksPerPlayer = 550; return (doomChunkDelay * expectedChunksPerPlayer) / Math.max(expectedChunksPerPlayer, loadedChunks.size()); //The delay between pillars is a factor of how many players are online using up chunks in the game: //with multiple players in distinct locations, the pillar has less delay and moves faster. //Scales up to hundreds of players without overloading the server and causing lag. //We can go to nearly 4 and still run, but mob AI gets real jerky. } /** * This method schedules the next step in the doom schedule to run after the * delay that getDoomChunkDelay() provides. */ private void runDoomScheduleLater() { long delay = getDoomChunkDelay(); nextDoomPillar = new BukkitRunnable() { @Override public void run() { nextDoomPillar = null; runDoomSchedule(); } }.runTaskLater(plugin, delay); } /** * This method runs the next step of the doom schedule; if we don't have * one, this will create a doom schedule and also do the first chunk in it. * * This method also calls runDoomScheduleLater() to schedule the next doom * chunk after this one. */ private void runDoomSchedule() { runDoomScheduleLater(); if (!loadedChunks.isEmpty()) { if (doomSchedule.isEmpty()) { prepareDoomSchedule(); } if (!doomSchedule.isEmpty()) { ChunkPosition where = doomSchedule.get(0); if (!plugin.getPlayerInfos().getHomeChunks().contains(where)) { beginPillarOfDoom(where); } //we need to remove the entry whether or not we placed a pillar //because if it's a home chunk, otherwise it freezes doomSchedule.remove(0); } } } //////////////////////////////////////////////////////////////// // Pillars of Doom // private final Set<ChunkPosition> doomedChunks = Sets.newHashSet(); /** * This method starts the process of regenerating a chunk; it records the * chunk as 'doomed' in the doomed chunk file, and kicks off the glowstone * pillar. Lifetime is the time it'll take to perform the pillar and * then call for regen. * * @param where The chunk that is doomed. */ private void beginPillarOfDoom(ChunkPosition where) { if (doomedChunks.add(where)) { System.out.println(String.format( "Doom at %d, %d (%s)", where.x * 16 + 8, where.z * 16 + 8, where.worldName)); saveDoomedChunks(); placePillarOfDoom(where); regenerateChunkLater(where, doomChunkLifetime); } } /** * This writes the set of doomed chunks out to a file. Recording these * chunks lets us regenerate them when the server restarts; this way we * don't leave abandoned doom pillars all over. */ private void saveDoomedChunks() { MapFileMap map = new MapFileMap(); map.put("doomed", doomedChunks); MapFileMap.write(regenFile, map); } /** * This reads the set of doomed chunks from the regen file; this does not * update 'doomedChunks', however; we instead regenerate them at once. This * is used at plugin startup. * * We do this so we don't leave abandoned doom pillars behind when the * server restarts. * * @return The retrieved chunks that are doomed. */ private Set<ChunkPosition> loadDoomedChunks() { if (regenFile.exists()) { MapFileMap map = MapFileMap.read(regenFile); return map.getSet("doomed", ChunkPosition.class); } else { return Collections.emptySet(); } } /** * This method places a doom pillar, a tall pillar of glowstone to make a * place that we will regenerate soon. * * @param where The chunk to be filled with doom. */ private void placePillarOfDoom(ChunkPosition where) { World world = where.getWorld(); int centerX = (where.x * 16) + 8; int centerZ = (where.z * 16) + 8; for (int y = 1; y < 255; ++y) { Location loc = new Location(world, centerX, y, centerZ); Block block = world.getBlockAt(loc); block.setType(Material.GLOWSTONE); } Location thunderLoc = new Location(world, centerX, 140, centerZ); float thunderPitch = 2.0f; world.playSound(thunderLoc, Sound.AMBIENCE_THUNDER, 9.0f, thunderPitch); thunderLoc = new Location(world, centerX, 1, centerZ); thunderPitch = 0.5f; world.playSound(thunderLoc, Sound.AMBIENCE_THUNDER, 13.0f, thunderPitch); } /** * This method regenerates a specified chunk, but does so after a specified * delay. * * @param where The chunk to regenerate. * @param delay The number of ticks to wait before doing so. */ private void regenerateChunkLater(final ChunkPosition where, long delay) { new BukkitRunnable() { @Override public void run() { regenerateChunk(where); } }.runTaskLater(plugin, delay); } /** * This method regenerates a specific chunk. This will remove the chunk from * the list of doomed chunks, since it will not regenerate on server * restart. * * @param where The chunk to regenerate. */ private void regenerateChunk(ChunkPosition where) { World world = where.getWorld(); world.regenerateChunk(where.x, where.z); if (doomedChunks.remove(where)) { saveDoomedChunks(); } } //////////////////////////////////////////////////////////////// // Path of Doom // private final List<ChunkPosition> doomSchedule = Lists.newArrayList(); private final Random regenRandom = new Random(); /** * This method generates the doomSchedule, the list of chunks we mean to * visit. Once a chunk is doomed, nothing (but a server reset) can save it. * We pick randomly which direction to run the schedule. */ private void prepareDoomSchedule() { boolean isX = regenRandom.nextBoolean(); boolean reversed = regenRandom.nextBoolean(); int index = regenRandom.nextInt(loadedChunks.size()); ChunkPosition origin = loadedChunks.get(index); doomSchedule.clear(); if (isX) { getLoadedChunkXRow(doomSchedule, origin); } else { getLoadedChunkZRow(doomSchedule, origin); } if (reversed) { Collections.sort(doomSchedule, Collections.reverseOrder()); } else { Collections.sort(doomSchedule); } } /** * This method finds every loaded chunk whose 'x' co-ordinate matches the * parameter, and adds each one to 'destination'. * * @param destination The collection to populate. * @param origin A chunk that is in the row we want. */ private void getLoadedChunkXRow(Collection<ChunkPosition> destination, ChunkPosition origin) { for (ChunkPosition pos : loadedChunks) { if (pos.x == origin.x && pos.worldName.equals(origin.worldName)) { destination.add(pos); } } } /** * This method finds every loaded chunk whose 'z' co-ordinate matches the * parameter, and adds each one to 'destination'. * * @param destination The collection to populate. * @param origin A chunk that is in the row we want. */ private void getLoadedChunkZRow(Collection<ChunkPosition> destination, ChunkPosition origin) { for (ChunkPosition pos : loadedChunks) { if (pos.z == origin.z && pos.worldName.equals(origin.worldName)) { destination.add(pos); } } } //////////////////////////////////////////////////////////////// // Chunk tracking // private final List<ChunkPosition> loadedChunks = Lists.newArrayList(); @EventHandler public void onChunkLoad(ChunkLoadEvent e) { Chunk chunk = e.getChunk(); if (chunk.getWorld().getEnvironment() != World.Environment.THE_END) { loadedChunks.add(ChunkPosition.of(chunk)); } } @EventHandler public void onChunkUnload(ChunkUnloadEvent e) { Chunk chunk = e.getChunk(); if (chunk.getWorld().getEnvironment() != World.Environment.THE_END) { loadedChunks.remove(ChunkPosition.of(chunk)); } } }
src/homesoil/DoomSchedule.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package homesoil; import com.google.common.base.*; import com.google.common.collect.*; import java.io.*; import java.util.*; import org.bukkit.*; import org.bukkit.block.*; import org.bukkit.event.*; import org.bukkit.event.world.*; import org.bukkit.scheduler.*; /** * DoomSchedule regenerates the world, a chunk at a time. Each chunk is filled * with a Warning- presently a pillar of glowstone- before it is regenerated. * Home chunks are skipped. * * The dooms schedule passes through loaded chunks in straight lines. It is not * guaranteed to hit every chunk; it passes through a random x or z row, then * picks another. It will hit nether chunks if they are loaded, but not end * chunks. * * @author DanJ and Applejinx */ public final class DoomSchedule implements Listener { private final File regenFile; private final HomeSoilPlugin plugin; private BukkitTask nextDoomPillar; public DoomSchedule(HomeSoilPlugin plugin, File regenFile) { this.plugin = Preconditions.checkNotNull(plugin); this.regenFile = Preconditions.checkNotNull(regenFile); } //////////////////////////////////////////////////////////////// // Scheduling // /** * This delay is how long we wait between doom pillars; we compute this to * be long enough that only one pillar at a time is in play. */ private final int doomChunkDelay = 256; private final int doomChunkLifetime = 128; /** * This method is called to start the task; it schedules it to run * regularly, and also hooks up events so we can tell what chunks are * loaded. * * @param plugin The plugin object for home soil; we register events with * this. */ public void start() { Bukkit.getPluginManager().registerEvents(this, plugin); runDoomScheduleLater(); for (ChunkPosition where : loadDoomedChunks()) { System.out.println(String.format( "Regenerating leftover chunk at %d, %d (%s)", where.x * 16 + 8, where.z * 16 + 8, where.worldName)); World world = where.getWorld(); world.regenerateChunk(where.x, where.z); } } /** * This method is called to stop the task, when the plugin is disabled; it * also unregisters the events, so its safe to call start() again to begin * all over again. */ public void stop() { if (nextDoomPillar != null) { nextDoomPillar.cancel(); } HandlerList.unregisterAll(this); saveDoomedChunks(); } /** * This method returns the number of ticks to wait between placing pillars. * This varies depending on how many chunks are loaded. * * @return The delay in ticks. */ private long getDoomChunkDelay() { final long expectedChunksPerPlayer = 550; return (doomChunkDelay * expectedChunksPerPlayer) / Math.max(expectedChunksPerPlayer, loadedChunks.size()); //The delay between pillars is a factor of how many players are online using up chunks in the game: //with multiple players in distinct locations, the pillar has less delay and moves faster. //Scales up to hundreds of players without overloading the server and causing lag. //We can go to nearly 4 and still run, but mob AI gets real jerky. } /** * This method schedules the next step in the doom schedule to run after the * delay that getDoomChunkDelay() provides. */ private void runDoomScheduleLater() { long delay = getDoomChunkDelay(); nextDoomPillar = new BukkitRunnable() { @Override public void run() { nextDoomPillar = null; runDoomSchedule(); } }.runTaskLater(plugin, delay); } /** * This method runs the next step of the doom schedule; if we don't have * one, this will create a doom schedule and also do the first chunk in it. * * This method also calls runDoomScheduleLater() to schedule the next doom * chunk after this one. */ private void runDoomSchedule() { runDoomScheduleLater(); if (!loadedChunks.isEmpty()) { if (doomSchedule.isEmpty()) { prepareDoomSchedule(); } if (!doomSchedule.isEmpty()) { ChunkPosition where = doomSchedule.get(0); if (!plugin.getPlayerInfos().getHomeChunks().contains(where)) { beginPillarOfDoom(where); } //we need to remove the entry whether or not we placed a pillar //because if it's a home chunk, otherwise it freezes doomSchedule.remove(0); } } } //////////////////////////////////////////////////////////////// // Pillars of Doom // private final Set<ChunkPosition> doomedChunks = Sets.newHashSet(); /** * This method starts the process of regenerating a chunk; it records the * chunk as 'doomed' in the doomed chunk file, and kicks off the lava * pillar. * * @param where The chunk that is doomed. */ private void beginPillarOfDoom(ChunkPosition where) { if (doomedChunks.add(where)) { System.out.println(String.format( "Doom at %d, %d (%s)", where.x * 16 + 8, where.z * 16 + 8, where.worldName)); saveDoomedChunks(); placePillarOfDoom(where); regenerateChunkLater(where, doomChunkLifetime); } } /** * This writes the set of doomed chunks out to a file. Recording these * chunks lets us regenerate them when the server restarts; this way we * don't leave abandoned doom pillars all over. */ private void saveDoomedChunks() { MapFileMap map = new MapFileMap(); map.put("doomed", doomedChunks); MapFileMap.write(regenFile, map); } /** * This reads the set of doomed chunks from the regen file; this does not * update 'doomedChunks', however; we instead regenerate them at once. This * is used at plugin startup. * * We do this so we don't leave abandoned doom pillars behind when the * server restarts. * * @return The retrieved chunks that are doomed. */ private Set<ChunkPosition> loadDoomedChunks() { if (regenFile.exists()) { MapFileMap map = MapFileMap.read(regenFile); return map.getSet("doomed", ChunkPosition.class); } else { return Collections.emptySet(); } } /** * This method places a doom pillar, a tall pillar of glowstone to make a * place that we will regenerate soon. * * @param where The chunk to be filled with doom. */ private void placePillarOfDoom(ChunkPosition where) { World world = where.getWorld(); int centerX = (where.x * 16) + 8; int centerZ = (where.z * 16) + 8; for (int y = 1; y < 255; ++y) { Location loc = new Location(world, centerX, y, centerZ); Block block = world.getBlockAt(loc); block.setType(Material.GLOWSTONE); } Location thunderLoc = new Location(world, centerX, 140, centerZ); float thunderPitch = 2.0f; world.playSound(thunderLoc, Sound.AMBIENCE_THUNDER, 9.0f, thunderPitch); thunderLoc = new Location(world, centerX, 1, centerZ); thunderPitch = 0.5f; world.playSound(thunderLoc, Sound.AMBIENCE_THUNDER, 13.0f, thunderPitch); } /** * This method regenerates a specified chunk, but does so after a specified * delay. * * @param where The chunk to regenerate. * @param delay The number of ticks to wait before doing so. */ private void regenerateChunkLater(final ChunkPosition where, long delay) { new BukkitRunnable() { @Override public void run() { regenerateChunk(where); } }.runTaskLater(plugin, delay); } /** * This method regenerates a specific chunk. This will remove the chunk from * the list of doomed chunks, since it will not regenerate on server * restart. * * @param where The chunk to regenerate. */ private void regenerateChunk(ChunkPosition where) { World world = where.getWorld(); world.regenerateChunk(where.x, where.z); if (doomedChunks.remove(where)) { saveDoomedChunks(); } } //////////////////////////////////////////////////////////////// // Path of Doom // private final List<ChunkPosition> doomSchedule = Lists.newArrayList(); private final Random regenRandom = new Random(); /** * This method generates the doomSchedule, the list of chunks we mean to * visit. Once a chunk is doomed, nothing (but a server reset) can save it. * We pick randomly which direction to run the schedule. */ private void prepareDoomSchedule() { boolean isX = regenRandom.nextBoolean(); boolean reversed = regenRandom.nextBoolean(); int index = regenRandom.nextInt(loadedChunks.size()); ChunkPosition origin = loadedChunks.get(index); doomSchedule.clear(); if (isX) { getLoadedChunkXRow(doomSchedule, origin); } else { getLoadedChunkZRow(doomSchedule, origin); } if (reversed) { Collections.sort(doomSchedule, Collections.reverseOrder()); } else { Collections.sort(doomSchedule); } } /** * This method finds every loaded chunk whose 'x' co-ordinate matches the * parameter, and adds each one to 'destination'. * * @param destination The collection to populate. * @param origin A chunk that is in the row we want. */ private void getLoadedChunkXRow(Collection<ChunkPosition> destination, ChunkPosition origin) { for (ChunkPosition pos : loadedChunks) { if (pos.x == origin.x && pos.worldName.equals(origin.worldName)) { destination.add(pos); } } } /** * This method finds every loaded chunk whose 'z' co-ordinate matches the * parameter, and adds each one to 'destination'. * * @param destination The collection to populate. * @param origin A chunk that is in the row we want. */ private void getLoadedChunkZRow(Collection<ChunkPosition> destination, ChunkPosition origin) { for (ChunkPosition pos : loadedChunks) { if (pos.z == origin.z && pos.worldName.equals(origin.worldName)) { destination.add(pos); } } } //////////////////////////////////////////////////////////////// // Chunk tracking // private final List<ChunkPosition> loadedChunks = Lists.newArrayList(); @EventHandler public void onChunkLoad(ChunkLoadEvent e) { Chunk chunk = e.getChunk(); if (chunk.getWorld().getEnvironment() != World.Environment.THE_END) { loadedChunks.add(ChunkPosition.of(chunk)); } } @EventHandler public void onChunkUnload(ChunkUnloadEvent e) { Chunk chunk = e.getChunk(); if (chunk.getWorld().getEnvironment() != World.Environment.THE_END) { loadedChunks.remove(ChunkPosition.of(chunk)); } } }
Made a few comments, drastically slowed regen from 256 (plus adjustments) to 4096 (plus adjustments)
src/homesoil/DoomSchedule.java
Made a few comments, drastically slowed regen from 256 (plus adjustments) to 4096 (plus adjustments)
<ide><path>rc/homesoil/DoomSchedule.java <ide> /** <ide> * This delay is how long we wait between doom pillars; we compute this to <ide> * be long enough that only one pillar at a time is in play. <del> */ <del> private final int doomChunkDelay = 256; <add> * It scales with the number of players online and the amount of terrain <add> * they are covering, and 256 gives you a fairly lively pillar that will <add> * keep everything pretty Sierra Club pristine. <add> * 4096 should simulate lack of a regen mechanism, but it'll still be out <add> * there somewhere endangering non-Home builds. <add> * Possibly a pay-to-win mechanic where you buy regen bombs? <add> * Lifetime puts a delay into the system while calling the regen queue, <add> * creating a delay. <add> */ <add> private final int doomChunkDelay = 4096; <ide> private final int doomChunkLifetime = 128; <ide> <ide> /** <ide> <ide> /** <ide> * This method starts the process of regenerating a chunk; it records the <del> * chunk as 'doomed' in the doomed chunk file, and kicks off the lava <del> * pillar. <add> * chunk as 'doomed' in the doomed chunk file, and kicks off the glowstone <add> * pillar. Lifetime is the time it'll take to perform the pillar and <add> * then call for regen. <ide> * <ide> * @param where The chunk that is doomed. <ide> */
Java
mit
a483c5bd453d575acee753ed878fb0d11f501e13
0
Qballl/WildernessTp,Qballl/WildernessTp
package io.wildernesstp; import io.papermc.lib.PaperLib; import io.wildernesstp.command.WildCommand; import io.wildernesstp.command.WildernessTPCommand; import io.wildernesstp.generator.LocationGenerator; import io.wildernesstp.hook.*; import io.wildernesstp.listener.PlayerListener; import io.wildernesstp.portal.PortalManager; import io.wildernesstp.region.RegionManager; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.block.Biome; import org.bukkit.command.PluginCommand; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Predicate; import java.util.stream.Collectors; /** * MIT License * <p> * Copyright (c) 2019 Quintin VanBooven * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ public final class Main extends JavaPlugin { private static final int DEFAULT_CONFIG_VERSION = 1; private static final String DEFAULT_LANGUAGE = "english"; private final File configFile = new File(super.getDataFolder(), "config.yml"); private FileConfiguration internalConfig, externalConfig; private Economy econ; private Hook[] hooks; private Language language; private LocationGenerator generator; private PortalManager portalManager; private RegionManager regionManager; private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors() * 2); @Override public final void onEnable() { if (!configFile.exists()) { super.saveDefaultConfig(); } this.loadConfiguration(); this.loadTranslations(); if (externalConfig.getInt("config-version", Main.DEFAULT_CONFIG_VERSION) < internalConfig.getInt("config-version", Main.DEFAULT_CONFIG_VERSION)) { super.saveResource(internalConfig.getName(), true); super.getLogger().info("Configuration wasn't up-to-date thus we updated it automatically."); } this.registerHooks(); this.registerCommands(); this.registerListeners(); this.setupGenerator(); this.portalManager = new PortalManager(this); this.regionManager = new RegionManager(this); PaperLib.suggestPaper(this); if (getConfig().getBoolean("use_hooks")) { Arrays.stream(hooks).filter(Hook::canHook).forEach(h -> { h.enable(); message: { final StringBuilder sb = new StringBuilder("Hooked into " + h.getName() + " "); if (!h.getVersion().isEmpty()) { sb.append("v").append(h.getVersion()); } if (h.getAuthors().length > 0) { sb.append("by").append(" ").append(String.join(", ", h.getAuthors())); } Bukkit.getLogger().info(sb.toString().trim()); } }); } if(getConfig().getInt("cost")>0) { if (!setupEconomy()) { getLogger().severe("Disabled due to no Vault dependency or economy plugin found!"); getServer().getPluginManager().disablePlugin(this); } } } @Override public final void onDisable() { Arrays.stream(hooks).filter(Hook::canHook).collect(Collectors.toCollection(ArrayDeque::new)).descendingIterator().forEachRemaining(Hook::disable); } public Language getLanguage() { return language; } public LocationGenerator getGenerator() { return generator; } public PortalManager getPortalManager() { return portalManager; } public RegionManager getRegionManager() { return regionManager; } public ScheduledExecutorService getExecutorService() { return executorService; } public Economy getEcon() { return econ; } public List<Biome> getBlacklistedBiomes() { return externalConfig.getStringList("blacklisted-biomes").stream().map(String::toUpperCase).map(Biome::valueOf).collect(Collectors.toList()); } public void teleport(Player player, Set<Predicate<Location>> filters) { generator.generate(player, filters).ifPresent(l -> PaperLib.teleportAsync(player, l)); takeMoney(player); } public void teleport(Player player) { teleport(player, Collections.emptySet()); } private void loadConfiguration() { try (InputStreamReader reader = new InputStreamReader(Objects.requireNonNull(Main.class.getClassLoader().getResourceAsStream(configFile.getName())))) { this.internalConfig = YamlConfiguration.loadConfiguration(reader); } catch (IOException e) { throw new IllegalStateException(e); } this.externalConfig = super.getConfig(); } private boolean setupEconomy() { if (getServer().getPluginManager().getPlugin("Vault") == null) { return false; } RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class); if (rsp == null) { return false; } econ = rsp.getProvider(); return econ != null; } private void loadTranslations() { final String language = externalConfig.getString("language", Main.DEFAULT_LANGUAGE); final File languageFile = new File(new File(super.getDataFolder(), "lang"), language + ".yml"); boolean usingDefaults = false; if (!languageFile.exists()) { try { super.saveResource("lang/" + language + ".yml", false); } catch (IllegalArgumentException e) { Bukkit.getLogger().warning("Could not find language file. Falling back on default translations."); usingDefaults = true; } } this.language = (!usingDefaults ? new Language(YamlConfiguration.loadConfiguration(languageFile)) : new Language()); } private void registerHooks() { final List<Hook> hooks = new ArrayList<>(); hooks.add(new TownyHook(this)); hooks.add(new FabledKingdomsHook(this)); hooks.add(new MassiveFactionsHook(this)); hooks.add(new FeudalHook(this)); hooks.add(new ResidenceHook(this)); hooks.add(new FactionsUUIDHook(this)); hooks.add(new GriefPreventionHook(this)); hooks.add(new WorldGuardHook(this)); this.hooks = hooks.toArray(new Hook[hooks.size()]); } private void registerCommands() { wildernesstp: { PluginCommand pluginCommand = Objects.requireNonNull(super.getCommand("wildernesstp")); WildernessTPCommand command = new WildernessTPCommand(this, pluginCommand.getName(), pluginCommand.getDescription(), pluginCommand.getUsage(), pluginCommand.getAliases(), pluginCommand.getPermission(), true); pluginCommand.setExecutor(command); pluginCommand.setTabCompleter(command); } wild: { PluginCommand pluginCommand = Objects.requireNonNull(super.getCommand("wild")); WildCommand command = new WildCommand(this, pluginCommand.getName(), pluginCommand.getDescription(), pluginCommand.getUsage(), pluginCommand.getAliases(), pluginCommand.getPermission(), true); pluginCommand.setExecutor(command); pluginCommand.setTabCompleter(command); } } private void registerListeners() { Bukkit.getPluginManager().registerEvents(new PlayerListener(this), this); } public void takeMoney(Player player) { if (getConfig().getInt("cost") > 0) { if (!player.hasPermission("wildernesstp.cost.bypass")) { if ((econ.getBalance(player) - getConfig().getInt("cost")) >= 0) { econ.withdrawPlayer(player, getConfig().getInt("cost")); } player.sendMessage(getLanguage().economy().insufficientFund()); } } } private void setupGenerator() { generator = new LocationGenerator(this); generator.addFilter(l -> !l.getBlock().isLiquid()); generator.addFilter(l -> l.getBlock().isPassable()); for (Hook h : hooks) { if (h.canHook()) { getLogger().info("Generator makes use of hook: " + h.getName()); } } Arrays.stream(hooks).forEach(hook -> generator.addFilter(l -> hook.canHook() && !hook.isClaim(l))); getBlacklistedBiomes().forEach(b -> generator.addFilter(l -> l.getBlock().getBiome() != b)); } }
src/main/java/io/wildernesstp/Main.java
package io.wildernesstp; import io.papermc.lib.PaperLib; import io.wildernesstp.command.WildCommand; import io.wildernesstp.command.WildernessTPCommand; import io.wildernesstp.generator.LocationGenerator; import io.wildernesstp.hook.*; import io.wildernesstp.listener.PlayerListener; import io.wildernesstp.portal.PortalManager; import io.wildernesstp.region.RegionManager; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.block.Biome; import org.bukkit.command.PluginCommand; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Predicate; import java.util.stream.Collectors; /** * MIT License * <p> * Copyright (c) 2019 Quintin VanBooven * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ public final class Main extends JavaPlugin { private static final int DEFAULT_CONFIG_VERSION = 1; private static final String DEFAULT_LANGUAGE = "english"; private final File configFile = new File(super.getDataFolder(), "config.yml"); private FileConfiguration internalConfig, externalConfig; private Economy econ; private Hook[] hooks; private Language language; private LocationGenerator generator; private PortalManager portalManager; private RegionManager regionManager; private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors() * 2); @Override public final void onEnable() { if (!configFile.exists()) { super.saveDefaultConfig(); } this.loadConfiguration(); this.loadTranslations(); if (externalConfig.getInt("config-version", Main.DEFAULT_CONFIG_VERSION) < internalConfig.getInt("config-version", Main.DEFAULT_CONFIG_VERSION)) { super.saveResource(internalConfig.getName(), true); super.getLogger().info("Configuration wasn't up-to-date thus we updated it automatically."); } this.registerHooks(); this.registerCommands(); this.registerListeners(); this.setupGenerator(); this.portalManager = new PortalManager(this); this.regionManager = new RegionManager(this); PaperLib.suggestPaper(this); if (getConfig().getBoolean("use_hooks")) { Arrays.stream(hooks).filter(Hook::canHook).forEach(h -> { h.enable(); message: { final StringBuilder sb = new StringBuilder("Hooked into " + h.getName() + " "); if (!h.getVersion().isEmpty()) { sb.append("v").append(h.getVersion()); } if (h.getAuthors().length > 0) { sb.append("by").append(" ").append(String.join(", ", h.getAuthors())); } Bukkit.getLogger().info(sb.toString().trim()); } }); } if (!setupEconomy()) { getLogger().severe("Disabled due to no Vault dependency or economy plugin found!"); getServer().getPluginManager().disablePlugin(this); } } @Override public final void onDisable() { Arrays.stream(hooks).filter(Hook::canHook).collect(Collectors.toCollection(ArrayDeque::new)).descendingIterator().forEachRemaining(Hook::disable); } public Language getLanguage() { return language; } public LocationGenerator getGenerator() { return generator; } public PortalManager getPortalManager() { return portalManager; } public RegionManager getRegionManager() { return regionManager; } public ScheduledExecutorService getExecutorService() { return executorService; } public Economy getEcon() { return econ; } public List<Biome> getBlacklistedBiomes() { return externalConfig.getStringList("blacklisted-biomes").stream().map(String::toUpperCase).map(Biome::valueOf).collect(Collectors.toList()); } public void teleport(Player player, Set<Predicate<Location>> filters) { generator.generate(player, filters).ifPresent(l -> PaperLib.teleportAsync(player, l)); takeMoney(player); } public void teleport(Player player) { teleport(player, Collections.emptySet()); } private void loadConfiguration() { try (InputStreamReader reader = new InputStreamReader(Objects.requireNonNull(Main.class.getClassLoader().getResourceAsStream(configFile.getName())))) { this.internalConfig = YamlConfiguration.loadConfiguration(reader); } catch (IOException e) { throw new IllegalStateException(e); } this.externalConfig = super.getConfig(); } private boolean setupEconomy() { if (getServer().getPluginManager().getPlugin("Vault") == null) { return false; } RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class); if (rsp == null) { return false; } econ = rsp.getProvider(); return econ != null; } private void loadTranslations() { final String language = externalConfig.getString("language", Main.DEFAULT_LANGUAGE); final File languageFile = new File(new File(super.getDataFolder(), "lang"), language + ".yml"); boolean usingDefaults = false; if (!languageFile.exists()) { try { super.saveResource("lang/" + language + ".yml", false); } catch (IllegalArgumentException e) { Bukkit.getLogger().warning("Could not find language file. Falling back on default translations."); usingDefaults = true; } } this.language = (!usingDefaults ? new Language(YamlConfiguration.loadConfiguration(languageFile)) : new Language()); } private void registerHooks() { final List<Hook> hooks = new ArrayList<>(); hooks.add(new TownyHook(this)); hooks.add(new FabledKingdomsHook(this)); hooks.add(new MassiveFactionsHook(this)); hooks.add(new FeudalHook(this)); hooks.add(new ResidenceHook(this)); hooks.add(new FactionsUUIDHook(this)); hooks.add(new GriefPreventionHook(this)); hooks.add(new WorldGuardHook(this)); this.hooks = hooks.toArray(new Hook[hooks.size()]); } private void registerCommands() { wildernesstp: { PluginCommand pluginCommand = Objects.requireNonNull(super.getCommand("wildernesstp")); WildernessTPCommand command = new WildernessTPCommand(this, pluginCommand.getName(), pluginCommand.getDescription(), pluginCommand.getUsage(), pluginCommand.getAliases(), pluginCommand.getPermission(), true); pluginCommand.setExecutor(command); pluginCommand.setTabCompleter(command); } wild: { PluginCommand pluginCommand = Objects.requireNonNull(super.getCommand("wild")); WildCommand command = new WildCommand(this, pluginCommand.getName(), pluginCommand.getDescription(), pluginCommand.getUsage(), pluginCommand.getAliases(), pluginCommand.getPermission(), true); pluginCommand.setExecutor(command); pluginCommand.setTabCompleter(command); } } private void registerListeners() { Bukkit.getPluginManager().registerEvents(new PlayerListener(this), this); } public void takeMoney(Player player) { if (getConfig().getInt("cost") > 0) { if (!player.hasPermission("wildernesstp.cost.bypass")) { if ((econ.getBalance(player) - getConfig().getInt("cost")) >= 0) { econ.withdrawPlayer(player, getConfig().getInt("cost")); } player.sendMessage(getLanguage().economy().insufficientFund()); } } } private void setupGenerator() { generator = new LocationGenerator(this); generator.addFilter(l -> !l.getBlock().isLiquid()); generator.addFilter(l -> l.getBlock().isPassable()); for (Hook h : hooks) { if (h.canHook()) { getLogger().info("Generator makes use of hook: " + h.getName()); } } Arrays.stream(hooks).forEach(hook -> generator.addFilter(l -> hook.canHook() && !hook.isClaim(l))); getBlacklistedBiomes().forEach(b -> generator.addFilter(l -> l.getBlock().getBiome() != b)); } }
Fixed vault loading
src/main/java/io/wildernesstp/Main.java
Fixed vault loading
<ide><path>rc/main/java/io/wildernesstp/Main.java <ide> }); <ide> } <ide> <del> if (!setupEconomy()) { <del> getLogger().severe("Disabled due to no Vault dependency or economy plugin found!"); <del> getServer().getPluginManager().disablePlugin(this); <add> if(getConfig().getInt("cost")>0) { <add> if (!setupEconomy()) { <add> getLogger().severe("Disabled due to no Vault dependency or economy plugin found!"); <add> getServer().getPluginManager().disablePlugin(this); <add> } <ide> } <ide> } <ide>
Java
bsd-3-clause
1197409c954b6af4820169852cb995a91f7dbb2f
0
wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy
/* * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.truffle.sl.nodes.controlflow; import com.oracle.truffle.api.dsl.*; import com.oracle.truffle.api.frame.*; import com.oracle.truffle.api.nodes.*; import com.oracle.truffle.api.source.*; import com.oracle.truffle.api.utilities.*; import com.oracle.truffle.sl.nodes.*; @NodeInfo(shortName = "if", description = "The node implementing a condional statement") public final class SLIfNode extends SLStatementNode { /** * The condition of the {@code if}. This in a {@link SLExpressionNode} because we require a * result value. We do not have a node type that can only return a {@code boolean} value, so * {@link #evaluateCondition executing the condition} can lead to a type error. */ @Child private SLExpressionNode conditionNode; /** Statement (or {@link SLBlockNode block}) executed when the condition is true. */ @Child private SLStatementNode thenPartNode; /** Statement (or {@link SLBlockNode block}) executed when the condition is false. */ @Child private SLStatementNode elsePartNode; /** * Profiling information, collected by the interpreter, capturing the profiling information of * the condition. This allows the compiler to generate better code for conditions that are * always true or always false. Additionally the {@link IntegerConditionProfile} implementation * (as opposed to {@link BooleanConditionProfile} implementation) transmits the probability of * the condition to be true to the compiler. */ private final ConditionProfile condition = new IntegerConditionProfile(); public SLIfNode(SourceSection src, SLExpressionNode conditionNode, SLStatementNode thenPartNode, SLStatementNode elsePartNode) { super(src); this.conditionNode = conditionNode; this.thenPartNode = thenPartNode; this.elsePartNode = elsePartNode; } @Override public void executeVoid(VirtualFrame frame) { /* * In the interpreter, record profiling information that the condition was executed and with * which outcome. */ if (condition.profile(evaluateCondition(frame))) { /* Execute the then-branch. */ thenPartNode.executeVoid(frame); } else { /* Execute the else-branch (which is optional according to the SL syntax). */ if (elsePartNode != null) { elsePartNode.executeVoid(frame); } } } private boolean evaluateCondition(VirtualFrame frame) { try { /* * The condition must evaluate to a boolean value, so we call the boolean-specialized * execute method. */ return conditionNode.executeBoolean(frame); } catch (UnexpectedResultException ex) { /* * The condition evaluated to a non-boolean result. This is a type error in the SL * program. We report it with the same exception that Truffle DSL generated nodes use to * report type errors. */ throw new UnsupportedSpecializationException(this, new Node[]{conditionNode}, ex.getResult()); } } }
graal/com.oracle.truffle.sl/src/com/oracle/truffle/sl/nodes/controlflow/SLIfNode.java
/* * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.truffle.sl.nodes.controlflow; import com.oracle.truffle.api.dsl.*; import com.oracle.truffle.api.frame.*; import com.oracle.truffle.api.nodes.*; import com.oracle.truffle.api.source.*; import com.oracle.truffle.api.utilities.*; import com.oracle.truffle.sl.nodes.*; @NodeInfo(shortName = "if", description = "The node implementing a condional statement") public final class SLIfNode extends SLStatementNode { /** * The condition of the {@code if}. This in a {@link SLExpressionNode} because we require a * result value. We do not have a node type that can only return a {@code boolean} value, so * {@link #evaluateCondition executing the condition} can lead to a type error. */ @Child private SLExpressionNode conditionNode; /** Statement (or {@link SLBlockNode block}) executed when the condition is true. */ @Child private SLStatementNode thenPartNode; /** Statement (or {@link SLBlockNode block}) executed when the condition is false. */ @Child private SLStatementNode elsePartNode; /** * Profiling information, collected by the interpreter, capturing whether the then-branch was * used (analogously for the {@link #elseTaken else-branch}). This allows the compiler to * generate better code for conditions that are always true or always false. */ private final BranchProfile thenTaken = new BranchProfile(); private final BranchProfile elseTaken = new BranchProfile(); public SLIfNode(SourceSection src, SLExpressionNode conditionNode, SLStatementNode thenPartNode, SLStatementNode elsePartNode) { super(src); this.conditionNode = conditionNode; this.thenPartNode = thenPartNode; this.elsePartNode = elsePartNode; } @Override public void executeVoid(VirtualFrame frame) { if (evaluateCondition(frame)) { /* In the interpreter, record profiling information that the then-branch was used. */ thenTaken.enter(); /* Execute the then-branch. */ thenPartNode.executeVoid(frame); } else { /* In the interpreter, record profiling information that the else-branch was used. */ elseTaken.enter(); /* Execute the else-branch (which is optional according to the SL syntax). */ if (elsePartNode != null) { elsePartNode.executeVoid(frame); } } } private boolean evaluateCondition(VirtualFrame frame) { try { /* * The condition must evaluate to a boolean value, so we call the boolean-specialized * execute method. */ return conditionNode.executeBoolean(frame); } catch (UnexpectedResultException ex) { /* * The condition evaluated to a non-boolean result. This is a type error in the SL * program. We report it with the same exception that Truffle DSL generated nodes use to * report type errors. */ throw new UnsupportedSpecializationException(this, new Node[]{conditionNode}, ex.getResult()); } } }
SL: use the new IntegerConditionProfile in simple language.
graal/com.oracle.truffle.sl/src/com/oracle/truffle/sl/nodes/controlflow/SLIfNode.java
SL: use the new IntegerConditionProfile in simple language.
<ide><path>raal/com.oracle.truffle.sl/src/com/oracle/truffle/sl/nodes/controlflow/SLIfNode.java <ide> @Child private SLStatementNode elsePartNode; <ide> <ide> /** <del> * Profiling information, collected by the interpreter, capturing whether the then-branch was <del> * used (analogously for the {@link #elseTaken else-branch}). This allows the compiler to <del> * generate better code for conditions that are always true or always false. <add> * Profiling information, collected by the interpreter, capturing the profiling information of <add> * the condition. This allows the compiler to generate better code for conditions that are <add> * always true or always false. Additionally the {@link IntegerConditionProfile} implementation <add> * (as opposed to {@link BooleanConditionProfile} implementation) transmits the probability of <add> * the condition to be true to the compiler. <ide> */ <del> private final BranchProfile thenTaken = new BranchProfile(); <del> private final BranchProfile elseTaken = new BranchProfile(); <add> private final ConditionProfile condition = new IntegerConditionProfile(); <ide> <ide> public SLIfNode(SourceSection src, SLExpressionNode conditionNode, SLStatementNode thenPartNode, SLStatementNode elsePartNode) { <ide> super(src); <ide> <ide> @Override <ide> public void executeVoid(VirtualFrame frame) { <del> if (evaluateCondition(frame)) { <del> /* In the interpreter, record profiling information that the then-branch was used. */ <del> thenTaken.enter(); <add> /* <add> * In the interpreter, record profiling information that the condition was executed and with <add> * which outcome. <add> */ <add> if (condition.profile(evaluateCondition(frame))) { <ide> /* Execute the then-branch. */ <ide> thenPartNode.executeVoid(frame); <ide> } else { <del> /* In the interpreter, record profiling information that the else-branch was used. */ <del> elseTaken.enter(); <ide> /* Execute the else-branch (which is optional according to the SL syntax). */ <ide> if (elsePartNode != null) { <ide> elsePartNode.executeVoid(frame);
JavaScript
mit
d73c630699985cfb1d55b946ad3a117f387ee611
0
jugglinmike/stringdom
var select = require('CSSselect'); var render = require('dom-serializer'); var Node = function(options) { options = options || {}; this.tagName = options.tagName; this.parentNode = options.parent || null; this.style = {}; this.childNodes = options.childNodes || []; this.nodeType = options.nodeType || 1; this.ownerDocument = options.ownerDocument; this.data = options.data; this.attribs = options.attribs || {}; }; Node.prototype.getElementsByTagName = function(tagName) { return select(tagName, this); }; Node.prototype.getElementById = function(id) { return select.selectOne('#' + id, this) || null; }; Node.prototype.querySelectorAll = function(selector) { return select(selector, this); }; Object.defineProperty(Node.prototype, 'className', { get: function() { return this.attribs.class; }, set: function(className) { return this.attribs.class = className; } }); Node.prototype.getAttribute = function(name) { return this.attribs[name]; }; Node.prototype.setAttribute = function(name, value) { return this.attribs[name] = value; }; // Aliases for compatability with CSSSelect and dom-serializer var typeNames = { '1': 'tag', '3': 'text' }; Object.defineProperty(Node.prototype, 'type', { get: function() { return typeNames[this.nodeType]; }, set: function(type) { return this.nodeType = type; } }); Object.defineProperty(Node.prototype, 'children', { get: function() { return this.childNodes; }, set: function(children) { return this.childNodes = children; } }); Object.defineProperty(Node.prototype, 'name', { get: function() { return this.tagName; }, set: function(name) { return this.tagName = name; } }); Node.prototype.removeChild = function() {}; Node.prototype.appendChild = function(childNode) { this.childNodes.push(childNode); return childNode; }; Node.prototype.cloneNode = function(deep) { var childNodes; if (deep) { childNodes = this.childNodes.map(function(childNode) { return new Node(childNode); }); } else { childNodes = this.childNodes; } return new Node({ childNodes: childNodes }); }; Node.prototype.addEventListener = function() {}; Object.defineProperty(Node.prototype, 'lastChild', { get: function() { return this.childNodes[this.childNodes.length - 1] || null; } }); Object.defineProperty(Node.prototype, 'innerHTML', { get: function() { return render(this.children, { normalizeWhitespace: false, xmlMode: false, decodeEntities: true }); }, set: function(str) { this.childNodes = require('./evaluate')(str); } }); Object.defineProperty(Node.prototype, 'textContent', { set: function(textContent) { this.childNodes = [ new Node({ data: textContent, nodeType: 3 }) ]; } }); module.exports = Node;
lib/dom-node.js
var select = require('CSSselect'); var render = require('dom-serializer'); var Node = function(options) { options = options || {}; this.tagName = options.tagName; this.parentNode = options.parent || null; this.style = {}; this.childNodes = options.childNodes || []; this.nodeType = options.nodeType || 1; this.ownerDocument = options.ownerDocument; this.data = options.data; this.attribs = options.attribs; }; Node.prototype.getElementsByTagName = function(tagName) { return select(tagName, this); }; Node.prototype.getElementById = function(id) { return select.selectOne('#' + id, this) || null; }; Node.prototype.querySelectorAll = function(selector) { return select(selector, this); }; Object.defineProperty(Node.prototype, 'className', { get: function() { return this.attribs.class; }, set: function(className) { return this.attribs.class = className; } }); Node.prototype.getAttribute = function(name) { return this.attribs[name]; }; Node.prototype.setAttribute = function(name, value) { return this.attribs[name] = value; }; // Aliases for compatability with CSSSelect and dom-serializer var typeNames = { '1': 'tag', '3': 'text' }; Object.defineProperty(Node.prototype, 'type', { get: function() { return typeNames[this.nodeType]; }, set: function(type) { return this.nodeType = type; } }); Object.defineProperty(Node.prototype, 'children', { get: function() { return this.childNodes; }, set: function(children) { return this.childNodes = children; } }); Object.defineProperty(Node.prototype, 'name', { get: function() { return this.tagName; }, set: function(name) { return this.tagName = name; } }); Node.prototype.removeChild = function() {}; Node.prototype.appendChild = function(childNode) { this.childNodes.push(childNode); return childNode; }; Node.prototype.cloneNode = function(deep) { var childNodes; if (deep) { childNodes = this.childNodes.map(function(childNode) { return new Node(childNode); }); } else { childNodes = this.childNodes; } return new Node({ childNodes: childNodes }); }; Node.prototype.addEventListener = function() {}; Object.defineProperty(Node.prototype, 'lastChild', { get: function() { return this.childNodes[this.childNodes.length - 1] || null; } }); Object.defineProperty(Node.prototype, 'innerHTML', { get: function() { return render(this.children, { normalizeWhitespace: false, xmlMode: false, decodeEntities: true }); }, set: function(str) { this.childNodes = require('./evaluate')(str); } }); Object.defineProperty(Node.prototype, 'textContent', { set: function(textContent) { this.childNodes = [ new Node({ data: textContent, nodeType: 3 }) ]; } }); module.exports = Node;
Ensure nodes have default set of attributes
lib/dom-node.js
Ensure nodes have default set of attributes
<ide><path>ib/dom-node.js <ide> this.nodeType = options.nodeType || 1; <ide> this.ownerDocument = options.ownerDocument; <ide> this.data = options.data; <del> this.attribs = options.attribs; <add> this.attribs = options.attribs || {}; <ide> }; <ide> <ide> Node.prototype.getElementsByTagName = function(tagName) {
JavaScript
agpl-3.0
ed1a861ac171560131a4617e63a5a644fbeee6e0
0
JimmyMow/lila,terokinnunen/lila,arex1337/lila,samuel-soubeyran/lila,terokinnunen/lila,JimmyMow/lila,arex1337/lila,samuel-soubeyran/lila,arex1337/lila,luanlv/lila,clarkerubber/lila,clarkerubber/lila,JimmyMow/lila,arex1337/lila,arex1337/lila,samuel-soubeyran/lila,samuel-soubeyran/lila,luanlv/lila,JimmyMow/lila,terokinnunen/lila,samuel-soubeyran/lila,terokinnunen/lila,JimmyMow/lila,arex1337/lila,terokinnunen/lila,JimmyMow/lila,clarkerubber/lila,arex1337/lila,clarkerubber/lila,luanlv/lila,luanlv/lila,luanlv/lila,JimmyMow/lila,clarkerubber/lila,clarkerubber/lila,terokinnunen/lila,luanlv/lila,luanlv/lila,samuel-soubeyran/lila,terokinnunen/lila,samuel-soubeyran/lila,clarkerubber/lila
var m = require('mithril'); function dataTypeFormat(dt) { if (dt === 'seconds') return '{point.y:.1f}'; if (dt === 'average') return '{point.y:,.1f}'; if (dt === 'percent') return '{point.percentage:.0f}%'; return '{point.y:,.0f}'; } function yAxisTypeFormat(dt) { if (dt === 'seconds') return '{value:.1f}'; if (dt === 'average') return '{value:,.1f}'; if (dt === 'percent') return '{value:.0f}%'; return '{value:,.0f}'; } var colors = { green: '#759900', red: '#dc322f', orange: '#d59120', blue: '#007599', translucid: 'rgba(0,0,0,0.3)' }; var resultColors = { Victory: colors.green, Draw: colors.blue, Defeat: colors.red }; function makeChart(el, data) { var sizeSerie = { name: data.sizeSerie.name, data: data.sizeSerie.data, yAxis: 1, type: 'column', stack: 'size', animation: { duration: 300 }, color: 'rgba(80,80,80,0.3)' }; var valueSeries = data.series.map(function(s) { var c = { name: s.name, data: s.data, yAxis: 0, type: 'column', stack: s.stack, animation: { duration: 300 }, dataLabels: { enabled: true, format: dataTypeFormat(s.dataType) }, tooltip: { // headerFormat: '<span style="font-size:11px">{series.name}</span><br>', pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>' + dataTypeFormat(s.dataType) + '</b><br/>', shared: true } }; if (data.valueYaxis.name === 'Result') c.color = resultColors[s.name]; return c; }); var chartConf = { chart: { type: 'column', alignTicks: true, spacing: [20, 0, 20, 0], animation: { duration: 300 }, backgroundColor: null, borderWidth: 0, borderRadius: 0, plotBackgroundColor: null, plotShadow: false, plotBorderWidth: 0 }, title: { text: null }, xAxis: { categories: data.xAxis.categories, crosshair: true }, yAxis: [data.valueYaxis, data.sizeYaxis].map(function(a, i) { return { title: { text: a.name }, labels: { format: yAxisTypeFormat(a.dataType) }, opposite: i % 2 === 1, min: a.dataType === 'percent' ? 0 : undefined, max: a.dataType === 'percent' ? 100 : undefined }; }), plotOptions: { column: { stacking: 'normal' } }, series: valueSeries.concat(sizeSerie), credits: { enabled: false }, legend: { enabled: true } }; console.log(chartConf); $(el).highcharts(chartConf); } module.exports = function(ctrl) { if (!ctrl.validCombinationCurrent()) return m('div', 'Invalid dimension/metric combination'); if (!ctrl.vm.answer) return m('div.square-wrap', m('div.square-in', m('div.square-spin'))); return m('div.chart', { config: function(el) { makeChart(el, ctrl.vm.answer); } }) };
ui/insight/src/chart.js
var m = require('mithril'); function dataTypeFormat(dt) { if (dt === 'seconds') return '{point.y:.1f}'; if (dt === 'average') return '{point.y:,.1f}'; if (dt === 'percent') return '{point.percentage:.0f}%'; return '{point.y:,.0f}'; } function yAxisTypeFormat(dt) { if (dt === 'seconds') return '{value:.1f}'; if (dt === 'average') return '{value:,.1f}'; if (dt === 'percent') return '{value:.0f}%'; return '{value:,.0f}'; } var colors = { green: '#759900', red: '#dc322f', orange: '#d59120', blue: '#007599', translucid: 'rgba(0,0,0,0.3)' }; var resultColors = { Victory: colors.green, Draw: colors.blue, Defeat: colors.red }; function makeChart(el, data) { var sizeSerie = { name: data.sizeSerie.name, data: data.sizeSerie.data, yAxis: 1, type: 'column', stack: 'size', animation: { duration: 300 }, color: 'rgba(0,0,0,0.1)' }; var valueSeries = data.series.map(function(s) { var c = { name: s.name, data: s.data, yAxis: 0, type: 'column', stack: s.stack, animation: { duration: 300 }, dataLabels: { enabled: true, format: dataTypeFormat(s.dataType) }, tooltip: { // headerFormat: '<span style="font-size:11px">{series.name}</span><br>', pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>' + dataTypeFormat(s.dataType) + '</b><br/>', shared: true } }; if (data.valueYaxis.name === 'Result') c.color = resultColors[s.name]; return c; }); var chartConf = { chart: { type: 'column', alignTicks: true, spacing: [20, 0, 20, 0], animation: { duration: 300 }, backgroundColor: null, borderWidth: 0, borderRadius: 0, plotBackgroundColor: null, plotShadow: false, plotBorderWidth: 0 }, title: { text: null }, xAxis: { categories: data.xAxis.categories, crosshair: true }, yAxis: [data.valueYaxis, data.sizeYaxis].map(function(a, i) { return { title: { text: a.name }, labels: { format: yAxisTypeFormat(a.dataType) }, opposite: i % 2 === 1, min: a.dataType === 'percent' ? 0 : undefined, max: a.dataType === 'percent' ? 100 : undefined }; }), plotOptions: { column: { stacking: 'normal' } }, series: valueSeries.concat(sizeSerie), credits: { enabled: false }, legend: { enabled: true } }; console.log(chartConf); $(el).highcharts(chartConf); } module.exports = function(ctrl) { if (!ctrl.validCombinationCurrent()) return m('div', 'Invalid dimension/metric combination'); if (!ctrl.vm.answer) return m('div.square-wrap', m('div.square-in', m('div.square-spin'))); return m('div.chart', { config: function(el) { makeChart(el, ctrl.vm.answer); } }) };
Change transparent bar color to a lax gray
ui/insight/src/chart.js
Change transparent bar color to a lax gray
<ide><path>i/insight/src/chart.js <ide> animation: { <ide> duration: 300 <ide> }, <del> color: 'rgba(0,0,0,0.1)' <add> color: 'rgba(80,80,80,0.3)' <ide> }; <ide> var valueSeries = data.series.map(function(s) { <ide> var c = {
Java
apache-2.0
47450677b91f6721cbeefb1888608b9829fd273d
0
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
package org.apache.lucene.index.codecs.simpletext; /** * 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 org.apache.lucene.util.BytesRef; import org.apache.lucene.index.codecs.FieldsProducer; import org.apache.lucene.index.FieldInfo.IndexOptions; import org.apache.lucene.index.SegmentReadState; import org.apache.lucene.index.FieldsEnum; import org.apache.lucene.index.Terms; import org.apache.lucene.index.DocsEnum; import org.apache.lucene.index.DocsAndPositionsEnum; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.index.FieldInfos; import org.apache.lucene.store.IndexInput; import org.apache.lucene.util.ArrayUtil; import org.apache.lucene.util.Bits; import org.apache.lucene.util.CharsRef; import org.apache.lucene.util.UnicodeUtil; import org.apache.lucene.util.fst.Builder; import org.apache.lucene.util.fst.BytesRefFSTEnum; import org.apache.lucene.util.fst.FST; import org.apache.lucene.util.fst.PositiveIntOutputs; import org.apache.lucene.util.fst.PairOutputs; import java.io.IOException; import java.util.Comparator; import java.util.Map; import java.util.HashMap; class SimpleTextFieldsReader extends FieldsProducer { private final IndexInput in; private final FieldInfos fieldInfos; final static byte NEWLINE = SimpleTextFieldsWriter.NEWLINE; final static byte ESCAPE = SimpleTextFieldsWriter.ESCAPE; final static BytesRef END = SimpleTextFieldsWriter.END; final static BytesRef FIELD = SimpleTextFieldsWriter.FIELD; final static BytesRef TERM = SimpleTextFieldsWriter.TERM; final static BytesRef DOC = SimpleTextFieldsWriter.DOC; final static BytesRef FREQ = SimpleTextFieldsWriter.FREQ; final static BytesRef POS = SimpleTextFieldsWriter.POS; final static BytesRef PAYLOAD = SimpleTextFieldsWriter.PAYLOAD; public SimpleTextFieldsReader(SegmentReadState state) throws IOException { in = state.dir.openInput(SimpleTextCodec.getPostingsFileName(state.segmentInfo.name, state.codecId), state.context); fieldInfos = state.fieldInfos; } static void readLine(IndexInput in, BytesRef scratch) throws IOException { int upto = 0; while(true) { byte b = in.readByte(); if (scratch.bytes.length == upto) { scratch.grow(1+upto); } if (b == ESCAPE) { scratch.bytes[upto++] = in.readByte(); } else { if (b == NEWLINE) { break; } else { scratch.bytes[upto++] = b; } } } scratch.offset = 0; scratch.length = upto; } private class SimpleTextFieldsEnum extends FieldsEnum { private final IndexInput in; private final BytesRef scratch = new BytesRef(10); private String current; public SimpleTextFieldsEnum() { this.in = (IndexInput) SimpleTextFieldsReader.this.in.clone(); } @Override public String next() throws IOException { while(true) { readLine(in, scratch); if (scratch.equals(END)) { current = null; return null; } if (scratch.startsWith(FIELD)) { return current = new String(scratch.bytes, scratch.offset + FIELD.length, scratch.length - FIELD.length, "UTF-8"); } } } @Override public TermsEnum terms() throws IOException { return SimpleTextFieldsReader.this.terms(current).iterator(); } } private class SimpleTextTermsEnum extends TermsEnum { private final IndexInput in; private final IndexOptions indexOptions; private int docFreq; private long totalTermFreq; private long docsStart; private boolean ended; private final BytesRefFSTEnum<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>> fstEnum; public SimpleTextTermsEnum(FST<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>> fst, IndexOptions indexOptions) throws IOException { this.in = (IndexInput) SimpleTextFieldsReader.this.in.clone(); this.indexOptions = indexOptions; fstEnum = new BytesRefFSTEnum<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>>(fst); } @Override public boolean seekExact(BytesRef text, boolean useCache /* ignored */) throws IOException { final BytesRefFSTEnum.InputOutput<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>> result = fstEnum.seekExact(text); if (result != null) { PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>> pair1 = result.output; PairOutputs.Pair<Long,Long> pair2 = pair1.output2; docsStart = pair1.output1; docFreq = pair2.output1.intValue(); totalTermFreq = pair2.output2; return true; } else { return false; } } @Override public SeekStatus seekCeil(BytesRef text, boolean useCache /* ignored */) throws IOException { //System.out.println("seek to text=" + text.utf8ToString()); final BytesRefFSTEnum.InputOutput<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>> result = fstEnum.seekCeil(text); if (result == null) { //System.out.println(" end"); return SeekStatus.END; } else { //System.out.println(" got text=" + term.utf8ToString()); PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>> pair1 = result.output; PairOutputs.Pair<Long,Long> pair2 = pair1.output2; docsStart = pair1.output1; docFreq = pair2.output1.intValue(); totalTermFreq = pair2.output2; if (result.input.equals(text)) { //System.out.println(" match docsStart=" + docsStart); return SeekStatus.FOUND; } else { //System.out.println(" not match docsStart=" + docsStart); return SeekStatus.NOT_FOUND; } } } @Override public BytesRef next() throws IOException { assert !ended; final BytesRefFSTEnum.InputOutput<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>> result = fstEnum.next(); if (result != null) { PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>> pair1 = result.output; PairOutputs.Pair<Long,Long> pair2 = pair1.output2; docsStart = pair1.output1; docFreq = pair2.output1.intValue(); totalTermFreq = pair2.output2; return result.input; } else { return null; } } @Override public BytesRef term() { return fstEnum.current().input; } @Override public long ord() throws IOException { throw new UnsupportedOperationException(); } @Override public void seekExact(long ord) { throw new UnsupportedOperationException(); } @Override public int docFreq() { return docFreq; } @Override public long totalTermFreq() { return indexOptions == IndexOptions.DOCS_ONLY ? -1 : totalTermFreq; } @Override public DocsEnum docs(Bits liveDocs, DocsEnum reuse) throws IOException { SimpleTextDocsEnum docsEnum; if (reuse != null && reuse instanceof SimpleTextDocsEnum && ((SimpleTextDocsEnum) reuse).canReuse(in)) { docsEnum = (SimpleTextDocsEnum) reuse; } else { docsEnum = new SimpleTextDocsEnum(); } return docsEnum.reset(docsStart, liveDocs, indexOptions == IndexOptions.DOCS_ONLY); } @Override public DocsAndPositionsEnum docsAndPositions(Bits liveDocs, DocsAndPositionsEnum reuse) throws IOException { if (indexOptions != IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) { return null; } SimpleTextDocsAndPositionsEnum docsAndPositionsEnum; if (reuse != null && reuse instanceof SimpleTextDocsAndPositionsEnum && ((SimpleTextDocsAndPositionsEnum) reuse).canReuse(in)) { docsAndPositionsEnum = (SimpleTextDocsAndPositionsEnum) reuse; } else { docsAndPositionsEnum = new SimpleTextDocsAndPositionsEnum(); } return docsAndPositionsEnum.reset(docsStart, liveDocs); } @Override public Comparator<BytesRef> getComparator() { return BytesRef.getUTF8SortedAsUnicodeComparator(); } } private class SimpleTextDocsEnum extends DocsEnum { private final IndexInput inStart; private final IndexInput in; private boolean omitTF; private int docID; private int tf; private Bits liveDocs; private final BytesRef scratch = new BytesRef(10); private final CharsRef scratchUTF16 = new CharsRef(10); public SimpleTextDocsEnum() { this.inStart = SimpleTextFieldsReader.this.in; this.in = (IndexInput) this.inStart.clone(); } public boolean canReuse(IndexInput in) { return in == inStart; } public SimpleTextDocsEnum reset(long fp, Bits liveDocs, boolean omitTF) throws IOException { this.liveDocs = liveDocs; in.seek(fp); this.omitTF = omitTF; if (omitTF) { tf = 1; } return this; } @Override public int docID() { return docID; } @Override public int freq() { return tf; } @Override public int nextDoc() throws IOException { if (docID == NO_MORE_DOCS) { return docID; } boolean first = true; int termFreq = 0; while(true) { final long lineStart = in.getFilePointer(); readLine(in, scratch); if (scratch.startsWith(DOC)) { if (!first && (liveDocs == null || liveDocs.get(docID))) { in.seek(lineStart); if (!omitTF) { tf = termFreq; } return docID; } UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+DOC.length, scratch.length-DOC.length, scratchUTF16); docID = ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length); termFreq = 0; first = false; } else if (scratch.startsWith(FREQ)) { UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+FREQ.length, scratch.length-FREQ.length, scratchUTF16); termFreq = ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length); } else if (scratch.startsWith(POS)) { // skip termFreq++; } else if (scratch.startsWith(PAYLOAD)) { // skip } else { assert scratch.startsWith(TERM) || scratch.startsWith(FIELD) || scratch.startsWith(END): "scratch=" + scratch.utf8ToString(); if (!first && (liveDocs == null || liveDocs.get(docID))) { in.seek(lineStart); if (!omitTF) { tf = termFreq; } return docID; } return docID = NO_MORE_DOCS; } } } @Override public int advance(int target) throws IOException { // Naive -- better to index skip data while(nextDoc() < target); return docID; } } private class SimpleTextDocsAndPositionsEnum extends DocsAndPositionsEnum { private final IndexInput inStart; private final IndexInput in; private int docID; private int tf; private Bits liveDocs; private final BytesRef scratch = new BytesRef(10); private final BytesRef scratch2 = new BytesRef(10); private final CharsRef scratchUTF16 = new CharsRef(10); private final CharsRef scratchUTF16_2 = new CharsRef(10); private BytesRef payload; private long nextDocStart; public SimpleTextDocsAndPositionsEnum() { this.inStart = SimpleTextFieldsReader.this.in; this.in = (IndexInput) inStart.clone(); } public boolean canReuse(IndexInput in) { return in == inStart; } public SimpleTextDocsAndPositionsEnum reset(long fp, Bits liveDocs) { this.liveDocs = liveDocs; nextDocStart = fp; return this; } @Override public int docID() { return docID; } @Override public int freq() { return tf; } @Override public int nextDoc() throws IOException { boolean first = true; in.seek(nextDocStart); long posStart = 0; while(true) { final long lineStart = in.getFilePointer(); readLine(in, scratch); if (scratch.startsWith(DOC)) { if (!first && (liveDocs == null || liveDocs.get(docID))) { nextDocStart = lineStart; in.seek(posStart); return docID; } UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+DOC.length, scratch.length-DOC.length, scratchUTF16); docID = ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length); tf = 0; first = false; } else if (scratch.startsWith(FREQ)) { UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+FREQ.length, scratch.length-FREQ.length, scratchUTF16); tf = ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length); posStart = in.getFilePointer(); } else if (scratch.startsWith(POS)) { // skip } else if (scratch.startsWith(PAYLOAD)) { // skip } else { assert scratch.startsWith(TERM) || scratch.startsWith(FIELD) || scratch.startsWith(END); if (!first && (liveDocs == null || liveDocs.get(docID))) { nextDocStart = lineStart; in.seek(posStart); return docID; } return docID = NO_MORE_DOCS; } } } @Override public int advance(int target) throws IOException { // Naive -- better to index skip data while(nextDoc() < target); return docID; } @Override public int nextPosition() throws IOException { readLine(in, scratch); assert scratch.startsWith(POS): "got line=" + scratch.utf8ToString(); UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+POS.length, scratch.length-POS.length, scratchUTF16_2); final int pos = ArrayUtil.parseInt(scratchUTF16_2.chars, 0, scratchUTF16_2.length); final long fp = in.getFilePointer(); readLine(in, scratch); if (scratch.startsWith(PAYLOAD)) { final int len = scratch.length - PAYLOAD.length; if (scratch2.bytes.length < len) { scratch2.grow(len); } System.arraycopy(scratch.bytes, PAYLOAD.length, scratch2.bytes, 0, len); scratch2.length = len; payload = scratch2; } else { payload = null; in.seek(fp); } return pos; } @Override public BytesRef getPayload() { // Some tests rely on only being able to retrieve the // payload once try { return payload; } finally { payload = null; } } @Override public boolean hasPayload() { return payload != null; } } static class TermData { public long docsStart; public int docFreq; public TermData(long docsStart, int docFreq) { this.docsStart = docsStart; this.docFreq = docFreq; } } private class SimpleTextTerms extends Terms { private final long termsStart; private final IndexOptions indexOptions; private long sumTotalTermFreq; private long sumDocFreq; private FST<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>> fst; private int termCount; private final BytesRef scratch = new BytesRef(10); public SimpleTextTerms(String field, long termsStart) throws IOException { this.termsStart = termsStart; indexOptions = fieldInfos.fieldInfo(field).indexOptions; loadTerms(); } private void loadTerms() throws IOException { PositiveIntOutputs posIntOutputs = PositiveIntOutputs.getSingleton(false); final Builder<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>> b; b = new Builder<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>>(FST.INPUT_TYPE.BYTE1, new PairOutputs<Long,PairOutputs.Pair<Long,Long>>(posIntOutputs, new PairOutputs<Long,Long>(posIntOutputs, posIntOutputs))); IndexInput in = (IndexInput) SimpleTextFieldsReader.this.in.clone(); in.seek(termsStart); final BytesRef lastTerm = new BytesRef(10); long lastDocsStart = -1; int docFreq = 0; long totalTermFreq = 0; while(true) { readLine(in, scratch); if (scratch.equals(END) || scratch.startsWith(FIELD)) { if (lastDocsStart != -1) { b.add(lastTerm, new PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>(lastDocsStart, new PairOutputs.Pair<Long,Long>((long) docFreq, posIntOutputs.get(totalTermFreq)))); sumTotalTermFreq += totalTermFreq; } break; } else if (scratch.startsWith(DOC)) { docFreq++; sumDocFreq++; } else if (scratch.startsWith(POS)) { totalTermFreq++; } else if (scratch.startsWith(TERM)) { if (lastDocsStart != -1) { b.add(lastTerm, new PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>(lastDocsStart, new PairOutputs.Pair<Long,Long>((long) docFreq, posIntOutputs.get(totalTermFreq)))); } lastDocsStart = in.getFilePointer(); final int len = scratch.length - TERM.length; if (len > lastTerm.length) { lastTerm.grow(len); } System.arraycopy(scratch.bytes, TERM.length, lastTerm.bytes, 0, len); lastTerm.length = len; docFreq = 0; sumTotalTermFreq += totalTermFreq; totalTermFreq = 0; termCount++; } } fst = b.finish(); /* PrintStream ps = new PrintStream("out.dot"); fst.toDot(ps); ps.close(); System.out.println("SAVED out.dot"); */ //System.out.println("FST " + fst.sizeInBytes()); } @Override public TermsEnum iterator() throws IOException { if (fst != null) { return new SimpleTextTermsEnum(fst, indexOptions); } else { return TermsEnum.EMPTY; } } @Override public Comparator<BytesRef> getComparator() { return BytesRef.getUTF8SortedAsUnicodeComparator(); } @Override public long getUniqueTermCount() { return (long) termCount; } @Override public long getSumTotalTermFreq() { return indexOptions == IndexOptions.DOCS_ONLY ? -1 : sumTotalTermFreq; } @Override public long getSumDocFreq() throws IOException { return sumDocFreq; } } @Override public FieldsEnum iterator() throws IOException { return new SimpleTextFieldsEnum(); } private final Map<String,Terms> termsCache = new HashMap<String,Terms>(); @Override synchronized public Terms terms(String field) throws IOException { Terms terms = termsCache.get(field); if (terms == null) { SimpleTextFieldsEnum fe = (SimpleTextFieldsEnum) iterator(); String fieldUpto; while((fieldUpto = fe.next()) != null) { if (fieldUpto.equals(field)) { terms = new SimpleTextTerms(field, fe.in.getFilePointer()); break; } } termsCache.put(field, terms); } return terms; } @Override public void close() throws IOException { in.close(); } }
lucene/src/java/org/apache/lucene/index/codecs/simpletext/SimpleTextFieldsReader.java
package org.apache.lucene.index.codecs.simpletext; /** * 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 org.apache.lucene.util.BytesRef; import org.apache.lucene.index.codecs.FieldsProducer; import org.apache.lucene.index.FieldInfo.IndexOptions; import org.apache.lucene.index.SegmentReadState; import org.apache.lucene.index.FieldsEnum; import org.apache.lucene.index.Terms; import org.apache.lucene.index.DocsEnum; import org.apache.lucene.index.DocsAndPositionsEnum; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.index.FieldInfos; import org.apache.lucene.store.IndexInput; import org.apache.lucene.util.ArrayUtil; import org.apache.lucene.util.Bits; import org.apache.lucene.util.CharsRef; import org.apache.lucene.util.UnicodeUtil; import org.apache.lucene.util.fst.Builder; import org.apache.lucene.util.fst.BytesRefFSTEnum; import org.apache.lucene.util.fst.FST; import org.apache.lucene.util.fst.PositiveIntOutputs; import org.apache.lucene.util.fst.PairOutputs; import java.io.IOException; import java.util.Comparator; import java.util.Map; import java.util.HashMap; class SimpleTextFieldsReader extends FieldsProducer { private final IndexInput in; private final FieldInfos fieldInfos; final static byte NEWLINE = SimpleTextFieldsWriter.NEWLINE; final static byte ESCAPE = SimpleTextFieldsWriter.ESCAPE; final static BytesRef END = SimpleTextFieldsWriter.END; final static BytesRef FIELD = SimpleTextFieldsWriter.FIELD; final static BytesRef TERM = SimpleTextFieldsWriter.TERM; final static BytesRef DOC = SimpleTextFieldsWriter.DOC; final static BytesRef FREQ = SimpleTextFieldsWriter.FREQ; final static BytesRef POS = SimpleTextFieldsWriter.POS; final static BytesRef PAYLOAD = SimpleTextFieldsWriter.PAYLOAD; public SimpleTextFieldsReader(SegmentReadState state) throws IOException { in = state.dir.openInput(SimpleTextCodec.getPostingsFileName(state.segmentInfo.name, state.codecId), state.context); fieldInfos = state.fieldInfos; } static void readLine(IndexInput in, BytesRef scratch) throws IOException { int upto = 0; while(true) { byte b = in.readByte(); if (scratch.bytes.length == upto) { scratch.grow(1+upto); } if (b == ESCAPE) { scratch.bytes[upto++] = in.readByte(); } else { if (b == NEWLINE) { break; } else { scratch.bytes[upto++] = b; } } } scratch.offset = 0; scratch.length = upto; } private class SimpleTextFieldsEnum extends FieldsEnum { private final IndexInput in; private final BytesRef scratch = new BytesRef(10); private String current; public SimpleTextFieldsEnum() { this.in = (IndexInput) SimpleTextFieldsReader.this.in.clone(); } @Override public String next() throws IOException { while(true) { readLine(in, scratch); if (scratch.equals(END)) { current = null; return null; } if (scratch.startsWith(FIELD)) { return current = new String(scratch.bytes, scratch.offset + FIELD.length, scratch.length - FIELD.length, "UTF-8"); } } } @Override public TermsEnum terms() throws IOException { return SimpleTextFieldsReader.this.terms(current).iterator(); } } private class SimpleTextTermsEnum extends TermsEnum { private final IndexInput in; private final IndexOptions indexOptions; private int docFreq; private long totalTermFreq; private long docsStart; private boolean ended; private final BytesRefFSTEnum<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>> fstEnum; public SimpleTextTermsEnum(FST<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>> fst, IndexOptions indexOptions) throws IOException { this.in = (IndexInput) SimpleTextFieldsReader.this.in.clone(); this.indexOptions = indexOptions; fstEnum = new BytesRefFSTEnum<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>>(fst); } @Override public boolean seekExact(BytesRef text, boolean useCache /* ignored */) throws IOException { final BytesRefFSTEnum.InputOutput<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>> result = fstEnum.seekExact(text); if (result != null) { PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>> pair1 = result.output; PairOutputs.Pair<Long,Long> pair2 = pair1.output2; docsStart = pair1.output1; docFreq = pair2.output1.intValue(); totalTermFreq = pair2.output2; return true; } else { return false; } } @Override public SeekStatus seekCeil(BytesRef text, boolean useCache /* ignored */) throws IOException { //System.out.println("seek to text=" + text.utf8ToString()); final BytesRefFSTEnum.InputOutput<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>> result = fstEnum.seekCeil(text); if (result == null) { //System.out.println(" end"); return SeekStatus.END; } else { //System.out.println(" got text=" + term.utf8ToString()); PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>> pair1 = result.output; PairOutputs.Pair<Long,Long> pair2 = pair1.output2; docsStart = pair1.output1; docFreq = pair2.output1.intValue(); totalTermFreq = pair2.output2; if (result.input.equals(text)) { //System.out.println(" match docsStart=" + docsStart); return SeekStatus.FOUND; } else { //System.out.println(" not match docsStart=" + docsStart); return SeekStatus.NOT_FOUND; } } } @Override public BytesRef next() throws IOException { assert !ended; final BytesRefFSTEnum.InputOutput<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>> result = fstEnum.next(); if (result != null) { PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>> pair1 = result.output; PairOutputs.Pair<Long,Long> pair2 = pair1.output2; docsStart = pair1.output1; docFreq = pair2.output1.intValue(); totalTermFreq = pair2.output2; return result.input; } else { return null; } } @Override public BytesRef term() { return fstEnum.current().input; } @Override public long ord() throws IOException { throw new UnsupportedOperationException(); } @Override public void seekExact(long ord) { throw new UnsupportedOperationException(); } @Override public int docFreq() { return docFreq; } @Override public long totalTermFreq() { return totalTermFreq; } @Override public DocsEnum docs(Bits liveDocs, DocsEnum reuse) throws IOException { SimpleTextDocsEnum docsEnum; if (reuse != null && reuse instanceof SimpleTextDocsEnum && ((SimpleTextDocsEnum) reuse).canReuse(in)) { docsEnum = (SimpleTextDocsEnum) reuse; } else { docsEnum = new SimpleTextDocsEnum(); } return docsEnum.reset(docsStart, liveDocs, indexOptions == IndexOptions.DOCS_ONLY); } @Override public DocsAndPositionsEnum docsAndPositions(Bits liveDocs, DocsAndPositionsEnum reuse) throws IOException { if (indexOptions != IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) { return null; } SimpleTextDocsAndPositionsEnum docsAndPositionsEnum; if (reuse != null && reuse instanceof SimpleTextDocsAndPositionsEnum && ((SimpleTextDocsAndPositionsEnum) reuse).canReuse(in)) { docsAndPositionsEnum = (SimpleTextDocsAndPositionsEnum) reuse; } else { docsAndPositionsEnum = new SimpleTextDocsAndPositionsEnum(); } return docsAndPositionsEnum.reset(docsStart, liveDocs); } @Override public Comparator<BytesRef> getComparator() { return BytesRef.getUTF8SortedAsUnicodeComparator(); } } private class SimpleTextDocsEnum extends DocsEnum { private final IndexInput inStart; private final IndexInput in; private boolean omitTF; private int docID; private int tf; private Bits liveDocs; private final BytesRef scratch = new BytesRef(10); private final CharsRef scratchUTF16 = new CharsRef(10); public SimpleTextDocsEnum() { this.inStart = SimpleTextFieldsReader.this.in; this.in = (IndexInput) this.inStart.clone(); } public boolean canReuse(IndexInput in) { return in == inStart; } public SimpleTextDocsEnum reset(long fp, Bits liveDocs, boolean omitTF) throws IOException { this.liveDocs = liveDocs; in.seek(fp); this.omitTF = omitTF; if (omitTF) { tf = 1; } return this; } @Override public int docID() { return docID; } @Override public int freq() { return tf; } @Override public int nextDoc() throws IOException { if (docID == NO_MORE_DOCS) { return docID; } boolean first = true; int termFreq = 0; while(true) { final long lineStart = in.getFilePointer(); readLine(in, scratch); if (scratch.startsWith(DOC)) { if (!first && (liveDocs == null || liveDocs.get(docID))) { in.seek(lineStart); if (!omitTF) { tf = termFreq; } return docID; } UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+DOC.length, scratch.length-DOC.length, scratchUTF16); docID = ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length); termFreq = 0; first = false; } else if (scratch.startsWith(FREQ)) { UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+FREQ.length, scratch.length-FREQ.length, scratchUTF16); termFreq = ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length); } else if (scratch.startsWith(POS)) { // skip termFreq++; } else if (scratch.startsWith(PAYLOAD)) { // skip } else { assert scratch.startsWith(TERM) || scratch.startsWith(FIELD) || scratch.startsWith(END): "scratch=" + scratch.utf8ToString(); if (!first && (liveDocs == null || liveDocs.get(docID))) { in.seek(lineStart); if (!omitTF) { tf = termFreq; } return docID; } return docID = NO_MORE_DOCS; } } } @Override public int advance(int target) throws IOException { // Naive -- better to index skip data while(nextDoc() < target); return docID; } } private class SimpleTextDocsAndPositionsEnum extends DocsAndPositionsEnum { private final IndexInput inStart; private final IndexInput in; private int docID; private int tf; private Bits liveDocs; private final BytesRef scratch = new BytesRef(10); private final BytesRef scratch2 = new BytesRef(10); private final CharsRef scratchUTF16 = new CharsRef(10); private final CharsRef scratchUTF16_2 = new CharsRef(10); private BytesRef payload; private long nextDocStart; public SimpleTextDocsAndPositionsEnum() { this.inStart = SimpleTextFieldsReader.this.in; this.in = (IndexInput) inStart.clone(); } public boolean canReuse(IndexInput in) { return in == inStart; } public SimpleTextDocsAndPositionsEnum reset(long fp, Bits liveDocs) { this.liveDocs = liveDocs; nextDocStart = fp; return this; } @Override public int docID() { return docID; } @Override public int freq() { return tf; } @Override public int nextDoc() throws IOException { boolean first = true; in.seek(nextDocStart); long posStart = 0; while(true) { final long lineStart = in.getFilePointer(); readLine(in, scratch); if (scratch.startsWith(DOC)) { if (!first && (liveDocs == null || liveDocs.get(docID))) { nextDocStart = lineStart; in.seek(posStart); return docID; } UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+DOC.length, scratch.length-DOC.length, scratchUTF16); docID = ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length); tf = 0; first = false; } else if (scratch.startsWith(FREQ)) { UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+FREQ.length, scratch.length-FREQ.length, scratchUTF16); tf = ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length); posStart = in.getFilePointer(); } else if (scratch.startsWith(POS)) { // skip } else if (scratch.startsWith(PAYLOAD)) { // skip } else { assert scratch.startsWith(TERM) || scratch.startsWith(FIELD) || scratch.startsWith(END); if (!first && (liveDocs == null || liveDocs.get(docID))) { nextDocStart = lineStart; in.seek(posStart); return docID; } return docID = NO_MORE_DOCS; } } } @Override public int advance(int target) throws IOException { // Naive -- better to index skip data while(nextDoc() < target); return docID; } @Override public int nextPosition() throws IOException { readLine(in, scratch); assert scratch.startsWith(POS): "got line=" + scratch.utf8ToString(); UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+POS.length, scratch.length-POS.length, scratchUTF16_2); final int pos = ArrayUtil.parseInt(scratchUTF16_2.chars, 0, scratchUTF16_2.length); final long fp = in.getFilePointer(); readLine(in, scratch); if (scratch.startsWith(PAYLOAD)) { final int len = scratch.length - PAYLOAD.length; if (scratch2.bytes.length < len) { scratch2.grow(len); } System.arraycopy(scratch.bytes, PAYLOAD.length, scratch2.bytes, 0, len); scratch2.length = len; payload = scratch2; } else { payload = null; in.seek(fp); } return pos; } @Override public BytesRef getPayload() { // Some tests rely on only being able to retrieve the // payload once try { return payload; } finally { payload = null; } } @Override public boolean hasPayload() { return payload != null; } } static class TermData { public long docsStart; public int docFreq; public TermData(long docsStart, int docFreq) { this.docsStart = docsStart; this.docFreq = docFreq; } } private class SimpleTextTerms extends Terms { private final long termsStart; private final IndexOptions indexOptions; private long sumTotalTermFreq; private long sumDocFreq; private FST<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>> fst; private int termCount; private final BytesRef scratch = new BytesRef(10); public SimpleTextTerms(String field, long termsStart) throws IOException { this.termsStart = termsStart; indexOptions = fieldInfos.fieldInfo(field).indexOptions; loadTerms(); } private void loadTerms() throws IOException { PositiveIntOutputs posIntOutputs = PositiveIntOutputs.getSingleton(false); final Builder<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>> b; b = new Builder<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>>(FST.INPUT_TYPE.BYTE1, new PairOutputs<Long,PairOutputs.Pair<Long,Long>>(posIntOutputs, new PairOutputs<Long,Long>(posIntOutputs, posIntOutputs))); IndexInput in = (IndexInput) SimpleTextFieldsReader.this.in.clone(); in.seek(termsStart); final BytesRef lastTerm = new BytesRef(10); long lastDocsStart = -1; int docFreq = 0; long totalTermFreq = 0; while(true) { readLine(in, scratch); if (scratch.equals(END) || scratch.startsWith(FIELD)) { if (lastDocsStart != -1) { b.add(lastTerm, new PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>(lastDocsStart, new PairOutputs.Pair<Long,Long>((long) docFreq, posIntOutputs.get(totalTermFreq)))); sumTotalTermFreq += totalTermFreq; } break; } else if (scratch.startsWith(DOC)) { docFreq++; sumDocFreq++; } else if (scratch.startsWith(POS)) { totalTermFreq++; } else if (scratch.startsWith(TERM)) { if (lastDocsStart != -1) { b.add(lastTerm, new PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>(lastDocsStart, new PairOutputs.Pair<Long,Long>((long) docFreq, posIntOutputs.get(totalTermFreq)))); } lastDocsStart = in.getFilePointer(); final int len = scratch.length - TERM.length; if (len > lastTerm.length) { lastTerm.grow(len); } System.arraycopy(scratch.bytes, TERM.length, lastTerm.bytes, 0, len); lastTerm.length = len; docFreq = 0; sumTotalTermFreq += totalTermFreq; totalTermFreq = 0; termCount++; } } fst = b.finish(); /* PrintStream ps = new PrintStream("out.dot"); fst.toDot(ps); ps.close(); System.out.println("SAVED out.dot"); */ //System.out.println("FST " + fst.sizeInBytes()); } @Override public TermsEnum iterator() throws IOException { if (fst != null) { return new SimpleTextTermsEnum(fst, indexOptions); } else { return TermsEnum.EMPTY; } } @Override public Comparator<BytesRef> getComparator() { return BytesRef.getUTF8SortedAsUnicodeComparator(); } @Override public long getUniqueTermCount() { return (long) termCount; } @Override public long getSumTotalTermFreq() { return sumTotalTermFreq; } @Override public long getSumDocFreq() throws IOException { return sumDocFreq; } } @Override public FieldsEnum iterator() throws IOException { return new SimpleTextFieldsEnum(); } private final Map<String,Terms> termsCache = new HashMap<String,Terms>(); @Override synchronized public Terms terms(String field) throws IOException { Terms terms = termsCache.get(field); if (terms == null) { SimpleTextFieldsEnum fe = (SimpleTextFieldsEnum) iterator(); String fieldUpto; while((fieldUpto = fe.next()) != null) { if (fieldUpto.equals(field)) { terms = new SimpleTextTerms(field, fe.in.getFilePointer()); break; } } termsCache.put(field, terms); } return terms; } @Override public void close() throws IOException { in.close(); } }
LUCENE-3407: fix test fail for SimpleText codec too git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1163304 13f79535-47bb-0310-9956-ffa450edef68
lucene/src/java/org/apache/lucene/index/codecs/simpletext/SimpleTextFieldsReader.java
LUCENE-3407: fix test fail for SimpleText codec too
<ide><path>ucene/src/java/org/apache/lucene/index/codecs/simpletext/SimpleTextFieldsReader.java <ide> <ide> @Override <ide> public long totalTermFreq() { <del> return totalTermFreq; <add> return indexOptions == IndexOptions.DOCS_ONLY ? -1 : totalTermFreq; <ide> } <ide> <ide> @Override <ide> <ide> @Override <ide> public long getSumTotalTermFreq() { <del> return sumTotalTermFreq; <add> return indexOptions == IndexOptions.DOCS_ONLY ? -1 : sumTotalTermFreq; <ide> } <ide> <ide> @Override
Java
apache-2.0
fe3818ab76c16a80979c94d495461d38cff5d2b2
0
osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi
package org.osgi.impl.bundle.midletcontainer; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.*; import org.osgi.service.log.LogService; import javax.microedition.midlet.MIDlet; import org.osgi.framework.*; import org.osgi.service.application.*; public final class MidletDescriptor extends ApplicationDescriptor implements ServiceListener { private Properties props; private Hashtable names; private Hashtable icons; private BundleContext bc; private String startClass; private String pid; private Bundle bundle; private String defaultLanguage; private boolean locked; private boolean registeredLaunchable; private MidletContainer midletContainer; private static int instanceCounter; private ServiceRegistration serviceReg; private Hashtable serviceProps; private boolean initlock; public MidletDescriptor(BundleContext bc, Properties props, Map names, Map icons, String defaultLang, String startClass, Bundle bundle, MidletContainer midletContainer) throws Exception { super( (String)props.get(Constants.SERVICE_PID) ); this.bc = bc; this.midletContainer = midletContainer; this.props = new Properties(); this.props.putAll(props); this.names = new Hashtable(names); this.icons = new Hashtable(icons); this.startClass = startClass; this.bundle = bundle; this.serviceReg = null; if (names.size() == 0 || icons.size() == 0 || !props.containsKey("application.bundle.id") || !props.containsKey(Constants.SERVICE_PID) || !props.containsKey(ApplicationDescriptor.APPLICATION_VERSION) || !props.containsKey(ApplicationDescriptor.APPLICATION_LOCATION )) throw new Exception("Invalid MEG container input!"); if (!names.containsKey(defaultLang)) { throw new Exception("Invalid default language!"); } else { defaultLanguage = defaultLang; pid = props.getProperty(Constants.SERVICE_PID); } initlock = true; getProperties( null ); } Bundle getBundle() { return bundle; } public String getPID() { return pid; } public Map getPropertiesSpecific(String locale) { if( initlock ) { initlock = false; Hashtable properties = new Hashtable(); properties.put(ApplicationDescriptor.APPLICATION_LOCKED, new Boolean(locked)); return properties; } checkBundle(); Hashtable properties = new Hashtable(); if( locale == null ) locale = ""; String localizedName = (String) names.get(locale); if (localizedName == null) { if ((localizedName = (String) names.get(defaultLanguage)) == null) { Enumeration enumeration = names.keys(); String firstKey = (String) enumeration.nextElement(); localizedName = (String) names.get(firstKey); locale = firstKey; } else { localizedName = (String) names.get(defaultLanguage); } locale = defaultLanguage; } properties.put(ApplicationDescriptor.APPLICATION_NAME, localizedName); properties.put(ApplicationDescriptor.APPLICATION_ICON, icons.get(locale)); properties.put("application.bundle.id", props .getProperty("application.bundle.id")); properties.put(ApplicationDescriptor.APPLICATION_VERSION, props .getProperty(ApplicationDescriptor.APPLICATION_VERSION)); properties.put(ApplicationDescriptor.APPLICATION_LOCATION, props .getProperty(ApplicationDescriptor.APPLICATION_LOCATION)); properties.put(ApplicationDescriptor.APPLICATION_VENDOR, props .getProperty(ApplicationDescriptor.APPLICATION_VENDOR)); String visible = props.getProperty(ApplicationDescriptor.APPLICATION_VISIBLE); if (visible != null && visible.equalsIgnoreCase("false")) properties.put(ApplicationDescriptor.APPLICATION_VISIBLE, new Boolean( false ) ); else properties.put(ApplicationDescriptor.APPLICATION_VISIBLE, new Boolean( true ) ); boolean launchable = false; try { launchable = isLaunchable(); } catch (Exception e) { Activator.log( LogService.LOG_ERROR ,"Exception occurred at searching the Midlet container reference!",e); } properties.put(ApplicationDescriptor.APPLICATION_LOCKED, new Boolean(locked)); properties.put(ApplicationDescriptor.APPLICATION_LAUNCHABLE, new Boolean(launchable)); properties.put(ApplicationDescriptor.APPLICATION_CONTAINER, "MIDlet"); properties.put(Constants.SERVICE_PID, new String(pid)); if( serviceReg != null ) { ServiceReference ref = serviceReg.getReference(); String keys[] = ref.getPropertyKeys(); for( int q=0; q != keys.length; q++ ) properties.put( keys[ q ], ref.getProperty( keys[ q ] ) ); } return properties; } public ApplicationHandle launchSpecific(Map args) throws Exception { checkBundle(); String instID = createNewInstanceID(bc, pid); MIDlet midlet = createMidletInstance( instID ); if (midlet == null) throw new Exception("Cannot create meglet instance!"); else { MidletHandle midHnd = new MidletHandle(bc, instID, this, midletContainer, midlet ); midHnd.startHandle(args); return midHnd; } } public void lockSpecific() { checkBundle(); locked = true; if( serviceReg != null ) { serviceProps.put( ApplicationDescriptor.APPLICATION_LOCKED, new Boolean( true )); serviceProps.put( ApplicationDescriptor.APPLICATION_LAUNCHABLE, new Boolean( false )); registeredLaunchable = false; serviceReg.setProperties( serviceProps ); // if lock changes, change the service registration properties also } } public void unlockSpecific() { checkBundle(); locked = false; if( serviceReg != null ) { serviceProps.put( ApplicationDescriptor.APPLICATION_LOCKED, new Boolean( false )); registeredLaunchable = isLaunchable(); serviceProps.put( ApplicationDescriptor.APPLICATION_LAUNCHABLE, new Boolean( registeredLaunchable )); serviceReg.setProperties( serviceProps ); // if lock changes, change the service registration properties also } } static synchronized String createNewInstanceID(BundleContext bc, String pid) { return new String(pid + ":" + instanceCounter++); } public boolean isLaunchable() { try { if ( locked ) return false; if( !midletContainer.getOATInterface().isLaunchable( getBundle(), startClass ) ) return false; return true; } catch (Exception e) { Activator.log( LogService.LOG_ERROR, "Exception occurred at checking if the midlet is launchable!", e); } return false; } public MIDlet createMidletInstance( final String instID ) throws Exception { return (MIDlet)AccessController.doPrivileged(new PrivilegedExceptionAction() { public java.lang.Object run() throws Exception { Class mainClass = bundle.loadClass(startClass); String mainClassFileName = startClass.replace( '.', '/' ) + ".class"; URL url = bundle.getResource( mainClassFileName ); if( url == null ) throw new Exception( "Internal error!" ); String urlName = url.toString(); if( !urlName.endsWith( mainClassFileName ) ) throw new Exception( "Internal error!" ); String location = urlName.substring( 0, urlName.length() - mainClassFileName.length() ); MIDletClassLoader loader = new MIDletClassLoader(mainClass.getClassLoader(), bundle, mainClass.getProtectionDomain(), location ); Class midletClass = loader.loadClass(startClass); Constructor constructor = midletClass .getDeclaredConstructor(new Class[0]); constructor.setAccessible(true); MIDlet app = (MIDlet) constructor.newInstance(new Object[0]); loader.setCorrespondingMIDlet( app, instID ); return app; }}); } void register() { serviceProps = new Hashtable( getProperties(Locale.getDefault().getLanguage())); registeredLaunchable = ((Boolean)serviceProps.get( ApplicationDescriptor.APPLICATION_LAUNCHABLE )).booleanValue(); if( serviceReg == null ) { serviceReg = bc.registerService(ApplicationDescriptor.class.getName(),this, serviceProps); bc.addServiceListener( this ); }else serviceReg.setProperties( serviceProps ); } void unregister() { if (serviceReg != null) { bc.removeServiceListener( this ); serviceReg.unregister(); serviceReg = null; } } public void serviceChanged(ServiceEvent event) { boolean launchable = isLaunchable(); if( serviceReg != null && launchable != registeredLaunchable ) { serviceProps.put( ApplicationDescriptor.APPLICATION_LAUNCHABLE, new Boolean( launchable ) ); registeredLaunchable = launchable; serviceReg.setProperties( serviceProps ); } } String getStartClass() { return startClass; } private void checkBundle() { if( bundle.getState() != Bundle.ACTIVE && bundle.getState() != Bundle.STARTING && bundle.getState() != Bundle.STOPPING ) throw new IllegalStateException(); } public boolean matchDNChain(final String pattern) { if( pattern == null ) throw new NullPointerException( "Pattern cannot be null!" ); checkBundle(); // TODO throw IllegalStateException if the AppDesc is invalid final Bundle bundle = this.bundle; try { return ((Boolean)AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { Method getBundleData = null; Class bundleClass = bundle.getClass(); do { try { getBundleData = bundleClass.getDeclaredMethod( "getBundleData", new Class[0] ); break; } catch( NoSuchMethodException e ) { bundleClass = bundleClass.getSuperclass(); if( bundleClass == null ) throw e; } }while( true ); getBundleData.setAccessible( true ); Object data = getBundleData.invoke( bundle, new Class [0] ); if( data == null ) return new Boolean( false ); Method matchDNChain = null; Class matchDNClass = data.getClass(); do { try { matchDNChain = matchDNClass.getDeclaredMethod( "matchDNChain", new Class[] { String.class } ); break; } catch( NoSuchMethodException e ) { matchDNClass = matchDNClass.getSuperclass(); if( matchDNClass == null ) throw e; } }while( true ); matchDNChain.setAccessible( true ); return matchDNChain.invoke( data, new Object [] { pattern } ); } })).booleanValue(); }catch(PrivilegedActionException e ) { Activator.log( LogService.LOG_ERROR, "Exception occurred at matching the DN chain!", e); return false; } } protected boolean isLaunchableSpecific() { checkBundle(); return isLaunchable(); } }
org.osgi.impl.bundle.midletcontainer/src/org/osgi/impl/bundle/midletcontainer/MidletDescriptor.java
package org.osgi.impl.bundle.midletcontainer; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.*; import org.osgi.service.log.LogService; import javax.microedition.midlet.MIDlet; import org.osgi.framework.*; import org.osgi.service.application.*; public final class MidletDescriptor extends ApplicationDescriptor implements ServiceListener { private Properties props; private Hashtable names; private Hashtable icons; private BundleContext bc; private String startClass; private String pid; private Bundle bundle; private String defaultLanguage; private boolean locked; private boolean registeredLaunchable; private MidletContainer midletContainer; private static int instanceCounter; private ServiceRegistration serviceReg; private Hashtable serviceProps; private boolean initlock; public MidletDescriptor(BundleContext bc, Properties props, Map names, Map icons, String defaultLang, String startClass, Bundle bundle, MidletContainer midletContainer) throws Exception { super( (String)props.get(Constants.SERVICE_PID) ); this.bc = bc; this.midletContainer = midletContainer; this.props = new Properties(); this.props.putAll(props); this.names = new Hashtable(names); this.icons = new Hashtable(icons); this.startClass = startClass; this.bundle = bundle; this.serviceReg = null; if (names.size() == 0 || icons.size() == 0 || !props.containsKey("application.bundle.id") || !props.containsKey(Constants.SERVICE_PID) || !props.containsKey(ApplicationDescriptor.APPLICATION_VERSION) || !props.containsKey(ApplicationDescriptor.APPLICATION_LOCATION )) throw new Exception("Invalid MEG container input!"); if (!names.containsKey(defaultLang)) { throw new Exception("Invalid default language!"); } else { defaultLanguage = defaultLang; pid = props.getProperty(Constants.SERVICE_PID); } initlock = true; getProperties( null ); } Bundle getBundle() { return bundle; } public String getPID() { return pid; } public Map getPropertiesSpecific(String locale) { if( initlock ) { initlock = false; Hashtable properties = new Hashtable(); properties.put(ApplicationDescriptor.APPLICATION_LOCKED, new Boolean(locked)); return properties; } checkBundle(); Hashtable properties = new Hashtable(); if( locale == null ) locale = ""; String localizedName = (String) names.get(locale); if (localizedName == null) { if ((localizedName = (String) names.get(defaultLanguage)) == null) { Enumeration enumeration = names.keys(); String firstKey = (String) enumeration.nextElement(); localizedName = (String) names.get(firstKey); locale = firstKey; } else { localizedName = (String) names.get(defaultLanguage); } locale = defaultLanguage; } properties.put(ApplicationDescriptor.APPLICATION_NAME, localizedName); properties.put(ApplicationDescriptor.APPLICATION_ICON, icons.get(locale)); properties.put("application.bundle.id", props .getProperty("application.bundle.id")); properties.put(ApplicationDescriptor.APPLICATION_VERSION, props .getProperty(ApplicationDescriptor.APPLICATION_VERSION)); properties.put(ApplicationDescriptor.APPLICATION_LOCATION, props .getProperty(ApplicationDescriptor.APPLICATION_LOCATION)); properties.put(ApplicationDescriptor.APPLICATION_VENDOR, props .getProperty(ApplicationDescriptor.APPLICATION_VENDOR)); String visible = props.getProperty(ApplicationDescriptor.APPLICATION_VISIBLE); if (visible != null && visible.equalsIgnoreCase("false")) properties.put(ApplicationDescriptor.APPLICATION_VISIBLE, new Boolean( false ) ); else properties.put(ApplicationDescriptor.APPLICATION_VISIBLE, new Boolean( true ) ); boolean launchable = false; try { launchable = isLaunchable(); } catch (Exception e) { Activator.log( LogService.LOG_ERROR ,"Exception occurred at searching the Midlet container reference!",e); } properties.put(ApplicationDescriptor.APPLICATION_LOCKED, new Boolean(locked)); properties.put(ApplicationDescriptor.APPLICATION_LAUNCHABLE, new Boolean(launchable)); properties.put(ApplicationDescriptor.APPLICATION_CONTAINER, "MIDlet"); properties.put(Constants.SERVICE_PID, new String(pid)); if( serviceReg != null ) { ServiceReference ref = serviceReg.getReference(); String keys[] = ref.getPropertyKeys(); for( int q=0; q != keys.length; q++ ) properties.put( keys[ q ], ref.getProperty( keys[ q ] ) ); } return properties; } public ApplicationHandle launchSpecific(Map args) throws Exception { checkBundle(); String instID = createNewInstanceID(bc, pid); MIDlet midlet = createMidletInstance( instID ); if (midlet == null) throw new Exception("Cannot create meglet instance!"); else { MidletHandle midHnd = new MidletHandle(bc, instID, this, midletContainer, midlet ); midHnd.startHandle(args); return midHnd; } } public void lockSpecific() { checkBundle(); locked = true; if( serviceReg != null ) { serviceProps.put( ApplicationDescriptor.APPLICATION_LOCKED, new Boolean( true )); serviceProps.put( ApplicationDescriptor.APPLICATION_LAUNCHABLE, new Boolean( false )); registeredLaunchable = false; serviceReg.setProperties( serviceProps ); // if lock changes, change the service registration properties also } } public void unlockSpecific() { checkBundle(); locked = false; if( serviceReg != null ) { serviceProps.put( ApplicationDescriptor.APPLICATION_LOCKED, new Boolean( false )); registeredLaunchable = isLaunchable(); serviceProps.put( ApplicationDescriptor.APPLICATION_LAUNCHABLE, new Boolean( registeredLaunchable )); serviceReg.setProperties( serviceProps ); // if lock changes, change the service registration properties also } } static synchronized String createNewInstanceID(BundleContext bc, String pid) { return new String(pid + ":" + instanceCounter++); } public boolean isLaunchable() { try { if ( locked ) return false; if( !midletContainer.getOATInterface().isLaunchable( getBundle(), startClass ) ) return false; return true; } catch (Exception e) { Activator.log( LogService.LOG_ERROR, "Exception occurred at checking if the midlet is launchable!", e); } return false; } public MIDlet createMidletInstance( final String instID ) throws Exception { return (MIDlet)AccessController.doPrivileged(new PrivilegedExceptionAction() { public java.lang.Object run() throws Exception { Class mainClass = bundle.loadClass(startClass); String mainClassFileName = startClass.replace( '.', '/' ) + ".class"; URL url = bundle.getResource( mainClassFileName ); if( url == null ) throw new Exception( "Internal error!" ); String urlName = url.toString(); if( !urlName.endsWith( mainClassFileName ) ) throw new Exception( "Internal error!" ); String location = urlName.substring( 0, urlName.length() - mainClassFileName.length() ); MIDletClassLoader loader = new MIDletClassLoader(mainClass.getClassLoader(), bundle, mainClass.getProtectionDomain(), location ); Class midletClass = loader.loadClass(startClass); Constructor constructor = midletClass .getDeclaredConstructor(new Class[0]); constructor.setAccessible(true); MIDlet app = (MIDlet) constructor.newInstance(new Object[0]); loader.setCorrespondingMIDlet( app, instID ); return app; }}); } void register() { serviceProps = new Hashtable( getProperties(Locale.getDefault().getLanguage())); registeredLaunchable = ((Boolean)serviceProps.get( ApplicationDescriptor.APPLICATION_LAUNCHABLE )).booleanValue(); if( serviceReg == null ) { serviceReg = bc.registerService(ApplicationDescriptor.class.getName(),this, serviceProps); bc.addServiceListener( this ); }else serviceReg.setProperties( serviceProps ); } void unregister() { if (serviceReg != null) { bc.removeServiceListener( this ); serviceReg.unregister(); serviceReg = null; } } public void serviceChanged(ServiceEvent event) { boolean launchable = isLaunchable(); if( serviceReg != null && launchable != registeredLaunchable ) { serviceProps.put( ApplicationDescriptor.APPLICATION_LAUNCHABLE, new Boolean( launchable ) ); registeredLaunchable = launchable; serviceReg.setProperties( serviceProps ); } } String getStartClass() { return startClass; } private void checkBundle() { if( bundle.getState() != Bundle.ACTIVE && bundle.getState() != Bundle.STARTING && bundle.getState() != Bundle.STOPPING ) throw new IllegalStateException(); } public boolean matchDNChain(final String pattern) { if( pattern == null ) throw new NullPointerException( "Pattern cannot be null!" ); checkBundle(); // TODO throw IllegalStateException if the AppDesc is invalid final Bundle bundle = this.bundle; try { return ((Boolean)AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { Method getBundleData = null; Class bundleClass = bundle.getClass(); do { try { getBundleData = bundleClass.getDeclaredMethod( "getBundleData", new Class[0] ); break; } catch( NoSuchMethodException e ) { bundleClass = bundleClass.getSuperclass(); if( bundleClass == null ) throw e; } }while( true ); getBundleData.setAccessible( true ); Object data = getBundleData.invoke( bundle, new Class [0] ); if( data == null ) return new Boolean( false ); Method matchDNChain = null; Class matchDNClass = data.getClass(); do { try { matchDNChain = matchDNClass.getDeclaredMethod( "matchDNChain", new Class[] { String.class } ); break; } catch( NoSuchMethodException e ) { matchDNClass = matchDNClass.getSuperclass(); if( matchDNClass == null ) throw e; } }while( true ); matchDNChain.setAccessible( true ); return matchDNChain.invoke( data, new Object [] { pattern } ); } })).booleanValue(); }catch(PrivilegedActionException e ) { Activator.log( LogService.LOG_ERROR, "Exception occurred at matching the DN chain!", e); return false; } } protected boolean isLaunchableSpecific() { return isLaunchable(); } }
FIXED: isLaunchableSpecific throws IllegalStateException after AppDesc unregistering
org.osgi.impl.bundle.midletcontainer/src/org/osgi/impl/bundle/midletcontainer/MidletDescriptor.java
FIXED: isLaunchableSpecific throws IllegalStateException after AppDesc unregistering
<ide><path>rg.osgi.impl.bundle.midletcontainer/src/org/osgi/impl/bundle/midletcontainer/MidletDescriptor.java <ide> } <ide> <ide> protected boolean isLaunchableSpecific() { <add> checkBundle(); <ide> return isLaunchable(); <ide> } <ide> }
Java
apache-2.0
b8f6e12fa920b936ce3823b9ba8a4f5ea445fc22
0
suninformation/ymate-platform-v2,suninformation/ymate-platform-v2
/* * Copyright 2007-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 net.ymate.platform.webmvc; import com.alibaba.fastjson.JSON; import net.ymate.platform.core.Version; import net.ymate.platform.core.YMP; import net.ymate.platform.core.beans.BeanMeta; import net.ymate.platform.core.lang.PairObject; import net.ymate.platform.core.module.IModule; import net.ymate.platform.core.module.annotation.Module; import net.ymate.platform.core.util.ClassUtils; import net.ymate.platform.core.util.RuntimeUtils; import net.ymate.platform.webmvc.annotation.*; import net.ymate.platform.webmvc.base.Type; import net.ymate.platform.webmvc.context.WebContext; import net.ymate.platform.webmvc.handle.ControllerHandler; import net.ymate.platform.webmvc.handle.InterceptorRuleHandler; import net.ymate.platform.webmvc.impl.DefaultInterceptorRuleProcessor; import net.ymate.platform.webmvc.impl.DefaultModuleCfg; import net.ymate.platform.webmvc.impl.NullWebCacheProcessor; import net.ymate.platform.webmvc.support.GenericResponseWrapper; import net.ymate.platform.webmvc.support.MultipartRequestWrapper; import net.ymate.platform.webmvc.support.RequestExecutor; import net.ymate.platform.webmvc.support.RequestMappingParser; import net.ymate.platform.webmvc.view.IView; import net.ymate.platform.webmvc.view.View; import net.ymate.platform.webmvc.view.impl.*; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.StopWatch; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Map; /** * MVC框架管理器 * * @author 刘镇 ([email protected]) on 2012-12-7 下午10:23:39 * @version 1.0 */ @Module public class WebMVC implements IModule, IWebMvc { public static final Version VERSION = new Version(2, 0, 0, WebMVC.class.getPackage().getImplementationVersion(), Version.VersionType.GA); private final Log _LOG = LogFactory.getLog(WebMVC.class); private static volatile IWebMvc __instance; private YMP __owner; private IWebMvcModuleCfg __moduleCfg; private boolean __inited; private RequestMappingParser __mappingParser; private IInterceptorRuleProcessor __interceptorRuleProcessor; /** * @return 返回默认MVC框架管理器实例对象 */ public static IWebMvc get() { if (__instance == null) { synchronized (VERSION) { if (__instance == null) { __instance = YMP.get().getModule(WebMVC.class); } } } return __instance; } /** * @param owner YMP框架管理器实例 * @return 返回指定YMP框架管理器容器内的MVC框架管理器实例 */ public static IWebMvc get(YMP owner) { return owner.getModule(WebMVC.class); } public String getName() { return IWebMvc.MODULE_NAME; } public void init(YMP owner) throws Exception { if (!__inited) { // _LOG.info("Initializing ymate-platform-webmvc-" + VERSION); // __owner = owner; __moduleCfg = new DefaultModuleCfg(owner); __mappingParser = new RequestMappingParser(); __owner.getEvents().registerEvent(WebEvent.class); __owner.registerHandler(Controller.class, new ControllerHandler(this)); if (__moduleCfg.isConventionInterceptorMode()) { __interceptorRuleProcessor = new DefaultInterceptorRuleProcessor(); __interceptorRuleProcessor.init(this); __owner.registerHandler(InterceptorRule.class, new InterceptorRuleHandler(this)); } // __inited = true; } } public boolean isInited() { return __inited; } public void destroy() throws Exception { if (__inited) { __inited = false; // __owner = null; } } public IWebMvcModuleCfg getModuleCfg() { return __moduleCfg; } public YMP getOwner() { return __owner; } public boolean registerController(Class<? extends Controller> targetClass) throws Exception { boolean _isValid = false; for (Method _method : targetClass.getDeclaredMethods()) { if (_method.isAnnotationPresent(RequestMapping.class)) { RequestMeta _meta = new RequestMeta(this, targetClass, _method); __mappingParser.registerRequestMeta(_meta); // if (__owner.getConfig().isDevelopMode()) { _LOG.debug("--> " + _meta.getAllowMethods() + ": " + _meta.getMapping() + " : " + _meta.getTargetClass().getName() + "." + _meta.getMethod().getName()); } // _isValid = true; } } // if (_isValid) { if (targetClass.getAnnotation(Controller.class).singleton()) { __owner.registerBean(BeanMeta.create(targetClass.newInstance(), targetClass)); } else { __owner.registerBean(BeanMeta.create(targetClass)); } } return _isValid; } public boolean registerInterceptorRule(Class<? extends IInterceptorRule> targetClass) throws Exception { if (__interceptorRuleProcessor != null) { __interceptorRuleProcessor.registerInterceptorRule(targetClass); return true; } return false; } private IWebCacheProcessor __doGetWebCacheProcessor(ResponseCache responseCache) { IWebCacheProcessor _cacheProcessor = null; if (responseCache != null) { if (!NullWebCacheProcessor.class.equals(responseCache.processorClass())) { _cacheProcessor = ClassUtils.impl(responseCache.processorClass(), IWebCacheProcessor.class); } if (_cacheProcessor == null) { _cacheProcessor = getModuleCfg().getCacheProcessor(); } } return _cacheProcessor; } public void processRequest(IRequestContext context, ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws Exception { StopWatch _consumeTime = null; long _threadId = Thread.currentThread().getId(); try { _LOG.debug("--> [" + _threadId + "] Process request start: " + context.getHttpMethod() + ":" + context.getRequestMapping()); if (__owner.getConfig().isDevelopMode()) { _consumeTime = new StopWatch(); _consumeTime.start(); _LOG.debug("--- [" + _threadId + "] Parameters: " + JSON.toJSONString(request.getParameterMap())); } // RequestMeta _meta = __mappingParser.doParse(context); if (_meta != null) { // _LOG.debug("--- [" + _threadId + "] Request mode: controller"); // 先判断当前请求方式是否允许 if (_meta.allowHttpMethod(context.getHttpMethod())) { // 判断允许的请求头 Map<String, String> _allowMap = _meta.getAllowHeaders(); for (Map.Entry<String, String> _entry : _allowMap.entrySet()) { String _value = WebContext.getRequest().getHeader(_entry.getKey()); if (StringUtils.trimToEmpty(_entry.getValue()).equals("*")) { if (StringUtils.isBlank(_value)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); // _LOG.debug("--- [" + _threadId + "] Check request allowed: NO"); return; } } else { if (_value == null || !_value.equalsIgnoreCase(_entry.getValue())) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); // _LOG.debug("--- [" + _threadId + "] Check request allowed: NO"); return; } } } // 判断允许的请求参数 _allowMap = _meta.getAllowParams(); for (Map.Entry<String, String> _entry : _allowMap.entrySet()) { if (StringUtils.trimToEmpty(_entry.getValue()).equals("*")) { if (!WebContext.getRequest().getParameterMap().containsKey(_entry.getKey())) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); // _LOG.debug("--- [" + _threadId + "] Check request allowed: NO"); return; } } else { String _value = WebContext.getRequest().getParameter(_entry.getKey()); if (_value == null || !_value.equalsIgnoreCase(_entry.getValue())) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); // _LOG.debug("--- [" + _threadId + "] Check request allowed: NO"); return; } } } // 判断是否需要处理文件上传 if (context.getHttpMethod().equals(Type.HttpMethod.POST) && _meta.getMethod().isAnnotationPresent(FileUpload.class)) { if (!(request instanceof IMultipartRequestWrapper)) { // 避免重复处理 request = new MultipartRequestWrapper(this, request); } // _LOG.debug("--- [" + _threadId + "] Include file upload: YES"); } WebContext.getContext().addAttribute(Type.Context.HTTP_REQUEST, request); // IWebCacheProcessor _cacheProcessor = __doGetWebCacheProcessor(_meta.getResponseCache()); IView _view = null; // 首先判断是否可以使用缓存 if (_cacheProcessor != null) { // 尝试从缓存中加载执行结果 if (_cacheProcessor.processResponseCache(this, _meta.getResponseCache(), context, null)) { // 加载成功, 则 _view = View.nullView(); // _LOG.debug("--- [" + _threadId + "] Load data from the cache: YES"); } } if (_view == null) { _view = RequestExecutor.bind(this, _meta).execute(); if (_view != null) { if (_cacheProcessor != null) { try { // 生成缓存 if (_cacheProcessor.processResponseCache(this, _meta.getResponseCache(), context, _view)) { _view = View.nullView(); // _LOG.debug("--- [" + _threadId + "] Results data cached: YES"); } } catch (Exception e) { // 缓存处理过程中的任何异常都不能影响本交请求的正常响应, 仅输出异常日志 _LOG.warn(e.getMessage(), RuntimeUtils.unwrapThrow(e)); } } _view.render(); } else { HttpStatusView.NOT_FOUND.render(); } } else { _view.render(); } } else { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } else if (__moduleCfg.isConventionMode()) { boolean _isAllowConvention = true; if (!__moduleCfg.getConventionViewNotAllowPaths().isEmpty()) { for (String _vPath : __moduleCfg.getConventionViewNotAllowPaths()) { if (context.getRequestMapping().startsWith(_vPath)) { _isAllowConvention = false; break; } } } if (_isAllowConvention && !__moduleCfg.getConventionViewAllowPaths().isEmpty()) { _isAllowConvention = false; for (String _vPath : __moduleCfg.getConventionViewAllowPaths()) { if (context.getRequestMapping().startsWith(_vPath)) { _isAllowConvention = true; break; } } } if (_isAllowConvention) { // _LOG.debug("--- [" + _threadId + "] Request mode: convention"); // IView _view = null; ResponseCache _responseCache = null; if (__interceptorRuleProcessor != null) { // 尝试执行Convention拦截规则 PairObject<IView, ResponseCache> _result = __interceptorRuleProcessor.processRequest(this, context); _view = _result.getKey(); _responseCache = _result.getValue(); } // 判断是否可以使用缓存 IWebCacheProcessor _cacheProcessor = __doGetWebCacheProcessor(_responseCache); // 首先判断是否可以使用缓存 if (_cacheProcessor != null) { // 尝试从缓存中加载执行结果 if (_cacheProcessor.processResponseCache(this, _responseCache, context, null)) { // 加载成功, 则 _view = View.nullView(); // _LOG.debug("--- [" + _threadId + "] Load data from the cache: YES"); } } if (_view == null) { // 处理Convention模式下URL参数集合 String _requestMapping = context.getRequestMapping(); String[] _urlParamArr = getModuleCfg().isConventionUrlrewriteMode() ? StringUtils.split(_requestMapping, '_') : new String[]{_requestMapping}; if (_urlParamArr != null && _urlParamArr.length > 1) { _requestMapping = _urlParamArr[0]; List<String> _urlParams = Arrays.asList(_urlParamArr).subList(1, _urlParamArr.length); WebContext.getRequest().setAttribute("UrlParams", _urlParams); // _LOG.debug("--- [" + _threadId + "] With parameters : " + _urlParams); } // if (__moduleCfg.getErrorProcessor() != null) { _view = __moduleCfg.getErrorProcessor().onConvention(this, context); } if (_view == null) { // 采用系统默认方式处理约定优于配置的URL请求映射 String[] _fileTypes = {".html", ".jsp", ".ftl", ".vm"}; for (String _fileType : _fileTypes) { File _targetFile = new File(__moduleCfg.getAbstractBaseViewPath(), _requestMapping + _fileType); if (_targetFile.exists()) { if (".html".equals(_fileType)) { _view = HtmlView.bind(this, _requestMapping.substring(1)); // _LOG.debug("--- [" + _threadId + "] Rendering template file : " + _requestMapping + _fileType); break; } else if (".jsp".equals(_fileType)) { _view = JspView.bind(this, _requestMapping.substring(1)); // _LOG.debug("--- [" + _threadId + "] Rendering template file : " + _requestMapping + _fileType); break; } else if (".ftl".equals(_fileType)) { _view = FreemarkerView.bind(this, _requestMapping.substring(1)); // _LOG.debug("--- [" + _threadId + "] Rendering template file : " + _requestMapping + _fileType); break; } else if (".vm".equals(_fileType)) { _view = VelocityView.bind(this, _requestMapping.substring(1)); // _LOG.debug("--- [" + _threadId + "] Rendering template file : " + _requestMapping + _fileType); } } } } // if (_view != null && _cacheProcessor != null) { try { if (_cacheProcessor.processResponseCache(this, _responseCache, context, _view)) { _view = View.nullView(); // _LOG.debug("--- [" + _threadId + "] Results data cached: YES"); } } catch (Exception e) { // 缓存处理过程中的任何异常都不能影响本交请求的正常响应, 仅输出异常日志 _LOG.warn(e.getMessage(), RuntimeUtils.unwrapThrow(e)); } } } if (_view != null) { _view.render(); } else { HttpStatusView.NOT_FOUND.render(); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } finally { if (_consumeTime != null && __owner.getConfig().isDevelopMode()) { _consumeTime.stop(); _LOG.debug("--- [" + _threadId + "] Total execution time: " + _consumeTime.getTime() + "ms"); } _LOG.debug("<-- [" + _threadId + "] Process request completed: " + context.getHttpMethod() + ":" + context.getRequestMapping() + ": " + ((GenericResponseWrapper) response).getStatus()); } } }
ymate-platform-webmvc/src/main/java/net/ymate/platform/webmvc/WebMVC.java
/* * Copyright 2007-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 net.ymate.platform.webmvc; import net.ymate.platform.core.Version; import net.ymate.platform.core.YMP; import net.ymate.platform.core.beans.BeanMeta; import net.ymate.platform.core.lang.PairObject; import net.ymate.platform.core.module.IModule; import net.ymate.platform.core.module.annotation.Module; import net.ymate.platform.core.util.ClassUtils; import net.ymate.platform.core.util.RuntimeUtils; import net.ymate.platform.webmvc.annotation.*; import net.ymate.platform.webmvc.base.Type; import net.ymate.platform.webmvc.context.WebContext; import net.ymate.platform.webmvc.handle.ControllerHandler; import net.ymate.platform.webmvc.handle.InterceptorRuleHandler; import net.ymate.platform.webmvc.impl.DefaultInterceptorRuleProcessor; import net.ymate.platform.webmvc.impl.DefaultModuleCfg; import net.ymate.platform.webmvc.impl.NullWebCacheProcessor; import net.ymate.platform.webmvc.support.MultipartRequestWrapper; import net.ymate.platform.webmvc.support.RequestExecutor; import net.ymate.platform.webmvc.support.RequestMappingParser; import net.ymate.platform.webmvc.view.IView; import net.ymate.platform.webmvc.view.View; import net.ymate.platform.webmvc.view.impl.*; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.StopWatch; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Map; /** * MVC框架管理器 * * @author 刘镇 ([email protected]) on 2012-12-7 下午10:23:39 * @version 1.0 */ @Module public class WebMVC implements IModule, IWebMvc { public static final Version VERSION = new Version(2, 0, 0, WebMVC.class.getPackage().getImplementationVersion(), Version.VersionType.GA); private final Log _LOG = LogFactory.getLog(WebMVC.class); private static volatile IWebMvc __instance; private YMP __owner; private IWebMvcModuleCfg __moduleCfg; private boolean __inited; private RequestMappingParser __mappingParser; private IInterceptorRuleProcessor __interceptorRuleProcessor; /** * @return 返回默认MVC框架管理器实例对象 */ public static IWebMvc get() { if (__instance == null) { synchronized (VERSION) { if (__instance == null) { __instance = YMP.get().getModule(WebMVC.class); } } } return __instance; } /** * @param owner YMP框架管理器实例 * @return 返回指定YMP框架管理器容器内的MVC框架管理器实例 */ public static IWebMvc get(YMP owner) { return owner.getModule(WebMVC.class); } public String getName() { return IWebMvc.MODULE_NAME; } public void init(YMP owner) throws Exception { if (!__inited) { // _LOG.info("Initializing ymate-platform-webmvc-" + VERSION); // __owner = owner; __moduleCfg = new DefaultModuleCfg(owner); __mappingParser = new RequestMappingParser(); __owner.getEvents().registerEvent(WebEvent.class); __owner.registerHandler(Controller.class, new ControllerHandler(this)); if (__moduleCfg.isConventionInterceptorMode()) { __interceptorRuleProcessor = new DefaultInterceptorRuleProcessor(); __interceptorRuleProcessor.init(this); __owner.registerHandler(InterceptorRule.class, new InterceptorRuleHandler(this)); } // __inited = true; } } public boolean isInited() { return __inited; } public void destroy() throws Exception { if (__inited) { __inited = false; // __owner = null; } } public IWebMvcModuleCfg getModuleCfg() { return __moduleCfg; } public YMP getOwner() { return __owner; } public boolean registerController(Class<? extends Controller> targetClass) throws Exception { boolean _isValid = false; for (Method _method : targetClass.getDeclaredMethods()) { if (_method.isAnnotationPresent(RequestMapping.class)) { RequestMeta _meta = new RequestMeta(this, targetClass, _method); __mappingParser.registerRequestMeta(_meta); // if (__owner.getConfig().isDevelopMode()) { _LOG.debug("--> " + _meta.getAllowMethods() + ": " + _meta.getMapping() + " : " + _meta.getTargetClass().getName()); } // _isValid = true; } } // if (_isValid) { if (targetClass.getAnnotation(Controller.class).singleton()) { __owner.registerBean(BeanMeta.create(targetClass.newInstance(), targetClass)); } else { __owner.registerBean(BeanMeta.create(targetClass)); } } return _isValid; } public boolean registerInterceptorRule(Class<? extends IInterceptorRule> targetClass) throws Exception { if (__interceptorRuleProcessor != null) { __interceptorRuleProcessor.registerInterceptorRule(targetClass); return true; } return false; } private IWebCacheProcessor __doGetWebCacheProcessor(ResponseCache responseCache) { IWebCacheProcessor _cacheProcessor = null; if (responseCache != null) { if (!NullWebCacheProcessor.class.equals(responseCache.processorClass())) { _cacheProcessor = ClassUtils.impl(responseCache.processorClass(), IWebCacheProcessor.class); } if (_cacheProcessor == null) { _cacheProcessor = getModuleCfg().getCacheProcessor(); } } return _cacheProcessor; } public void processRequest(IRequestContext context, ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws Exception { StopWatch _consumeTime = null; long _threadId = Thread.currentThread().getId(); try { if (__owner.getConfig().isDevelopMode()) { _consumeTime = new StopWatch(); _consumeTime.start(); } _LOG.debug("--> [" + _threadId + "] Process request start: " + context.getHttpMethod() + ":" + context.getRequestMapping()); // RequestMeta _meta = __mappingParser.doParse(context); if (_meta != null) { // _LOG.debug("--- [" + _threadId + "] Request mode: controller"); // 先判断当前请求方式是否允许 if (_meta.allowHttpMethod(context.getHttpMethod())) { // 判断允许的请求头 Map<String, String> _allowMap = _meta.getAllowHeaders(); for (Map.Entry<String, String> _entry : _allowMap.entrySet()) { String _value = WebContext.getRequest().getHeader(_entry.getKey()); if (StringUtils.trimToEmpty(_entry.getValue()).equals("*")) { if (StringUtils.isBlank(_value)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); // _LOG.debug("--- [" + _threadId + "] Check request allowed: NO"); return; } } else { if (_value == null || !_value.equalsIgnoreCase(_entry.getValue())) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); // _LOG.debug("--- [" + _threadId + "] Check request allowed: NO"); return; } } } // 判断允许的请求参数 _allowMap = _meta.getAllowParams(); for (Map.Entry<String, String> _entry : _allowMap.entrySet()) { if (StringUtils.trimToEmpty(_entry.getValue()).equals("*")) { if (!WebContext.getRequest().getParameterMap().containsKey(_entry.getKey())) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); // _LOG.debug("--- [" + _threadId + "] Check request allowed: NO"); return; } } else { String _value = WebContext.getRequest().getParameter(_entry.getKey()); if (_value == null || !_value.equalsIgnoreCase(_entry.getValue())) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); // _LOG.debug("--- [" + _threadId + "] Check request allowed: NO"); return; } } } // 判断是否需要处理文件上传 if (context.getHttpMethod().equals(Type.HttpMethod.POST) && _meta.getMethod().isAnnotationPresent(FileUpload.class)) { if (!(request instanceof IMultipartRequestWrapper)) { // 避免重复处理 request = new MultipartRequestWrapper(this, request); } // _LOG.debug("--- [" + _threadId + "] Include file upload: YES"); } WebContext.getContext().addAttribute(Type.Context.HTTP_REQUEST, request); // IWebCacheProcessor _cacheProcessor = __doGetWebCacheProcessor(_meta.getResponseCache()); IView _view = null; // 首先判断是否可以使用缓存 if (_cacheProcessor != null) { // 尝试从缓存中加载执行结果 if (_cacheProcessor.processResponseCache(this, _meta.getResponseCache(), context, null)) { // 加载成功, 则 _view = View.nullView(); // _LOG.debug("--- [" + _threadId + "] Load data from the cache: YES"); } } if (_view == null) { _view = RequestExecutor.bind(this, _meta).execute(); if (_view != null) { if (_cacheProcessor != null) { try { // 生成缓存 if (_cacheProcessor.processResponseCache(this, _meta.getResponseCache(), context, _view)) { _view = View.nullView(); // _LOG.debug("--- [" + _threadId + "] Results data cached: YES"); } } catch (Exception e) { // 缓存处理过程中的任何异常都不能影响本交请求的正常响应, 仅输出异常日志 _LOG.warn(e.getMessage(), RuntimeUtils.unwrapThrow(e)); } } _view.render(); } else { HttpStatusView.NOT_FOUND.render(); } } else { _view.render(); } } else { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } else if (__moduleCfg.isConventionMode()) { boolean _isAllowConvention = true; if (!__moduleCfg.getConventionViewNotAllowPaths().isEmpty()) { for (String _vPath : __moduleCfg.getConventionViewNotAllowPaths()) { if (context.getRequestMapping().startsWith(_vPath)) { _isAllowConvention = false; break; } } } if (_isAllowConvention && !__moduleCfg.getConventionViewAllowPaths().isEmpty()) { _isAllowConvention = false; for (String _vPath : __moduleCfg.getConventionViewAllowPaths()) { if (context.getRequestMapping().startsWith(_vPath)) { _isAllowConvention = true; break; } } } if (_isAllowConvention) { // _LOG.debug("--- [" + _threadId + "] Request mode: convention"); // IView _view = null; ResponseCache _responseCache = null; if (__interceptorRuleProcessor != null) { // 尝试执行Convention拦截规则 PairObject<IView, ResponseCache> _result = __interceptorRuleProcessor.processRequest(this, context); _view = _result.getKey(); _responseCache = _result.getValue(); } // 判断是否可以使用缓存 IWebCacheProcessor _cacheProcessor = __doGetWebCacheProcessor(_responseCache); // 首先判断是否可以使用缓存 if (_cacheProcessor != null) { // 尝试从缓存中加载执行结果 if (_cacheProcessor.processResponseCache(this, _responseCache, context, null)) { // 加载成功, 则 _view = View.nullView(); // _LOG.debug("--- [" + _threadId + "] Load data from the cache: YES"); } } if (_view == null) { // 处理Convention模式下URL参数集合 String _requestMapping = context.getRequestMapping(); String[] _urlParamArr = getModuleCfg().isConventionUrlrewriteMode() ? StringUtils.split(_requestMapping, '_') : new String[]{_requestMapping}; if (_urlParamArr != null && _urlParamArr.length > 1) { _requestMapping = _urlParamArr[0]; List<String> _urlParams = Arrays.asList(_urlParamArr).subList(1, _urlParamArr.length); WebContext.getRequest().setAttribute("UrlParams", _urlParams); // _LOG.debug("--- [" + _threadId + "] With parameters : " + _urlParams); } // if (__moduleCfg.getErrorProcessor() != null) { _view = __moduleCfg.getErrorProcessor().onConvention(this, context); } if (_view == null) { // 采用系统默认方式处理约定优于配置的URL请求映射 String[] _fileTypes = {".html", ".jsp", ".ftl", ".vm"}; for (String _fileType : _fileTypes) { File _targetFile = new File(__moduleCfg.getAbstractBaseViewPath(), _requestMapping + _fileType); if (_targetFile.exists()) { if (".html".equals(_fileType)) { _view = HtmlView.bind(this, _requestMapping.substring(1)); // _LOG.debug("--- [" + _threadId + "] Rendering template file : " + _requestMapping + _fileType); break; } else if (".jsp".equals(_fileType)) { _view = JspView.bind(this, _requestMapping.substring(1)); // _LOG.debug("--- [" + _threadId + "] Rendering template file : " + _requestMapping + _fileType); break; } else if (".ftl".equals(_fileType)) { _view = FreemarkerView.bind(this, _requestMapping.substring(1)); // _LOG.debug("--- [" + _threadId + "] Rendering template file : " + _requestMapping + _fileType); break; } else if (".vm".equals(_fileType)) { _view = VelocityView.bind(this, _requestMapping.substring(1)); // _LOG.debug("--- [" + _threadId + "] Rendering template file : " + _requestMapping + _fileType); } } } } // if (_view != null && _cacheProcessor != null) { try { if (_cacheProcessor.processResponseCache(this, _responseCache, context, _view)) { _view = View.nullView(); // _LOG.debug("--- [" + _threadId + "] Results data cached: YES"); } } catch (Exception e) { // 缓存处理过程中的任何异常都不能影响本交请求的正常响应, 仅输出异常日志 _LOG.warn(e.getMessage(), RuntimeUtils.unwrapThrow(e)); } } } if (_view != null) { _view.render(); } else { HttpStatusView.NOT_FOUND.render(); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } finally { if (_consumeTime != null && __owner.getConfig().isDevelopMode()) { _consumeTime.stop(); _LOG.debug("--- [" + _threadId + "] Total execution time: " + _consumeTime.getTime() + "ms"); } _LOG.debug("<-- [" + _threadId + "] Process request completed: " + context.getHttpMethod() + ":" + context.getRequestMapping()); } } }
优化日志输出请求参数和回应状态值
ymate-platform-webmvc/src/main/java/net/ymate/platform/webmvc/WebMVC.java
优化日志输出请求参数和回应状态值
<ide><path>mate-platform-webmvc/src/main/java/net/ymate/platform/webmvc/WebMVC.java <ide> */ <ide> package net.ymate.platform.webmvc; <ide> <add>import com.alibaba.fastjson.JSON; <ide> import net.ymate.platform.core.Version; <ide> import net.ymate.platform.core.YMP; <ide> import net.ymate.platform.core.beans.BeanMeta; <ide> import net.ymate.platform.webmvc.impl.DefaultInterceptorRuleProcessor; <ide> import net.ymate.platform.webmvc.impl.DefaultModuleCfg; <ide> import net.ymate.platform.webmvc.impl.NullWebCacheProcessor; <add>import net.ymate.platform.webmvc.support.GenericResponseWrapper; <ide> import net.ymate.platform.webmvc.support.MultipartRequestWrapper; <ide> import net.ymate.platform.webmvc.support.RequestExecutor; <ide> import net.ymate.platform.webmvc.support.RequestMappingParser; <ide> __mappingParser.registerRequestMeta(_meta); <ide> // <ide> if (__owner.getConfig().isDevelopMode()) { <del> _LOG.debug("--> " + _meta.getAllowMethods() + ": " + _meta.getMapping() + " : " + _meta.getTargetClass().getName()); <add> _LOG.debug("--> " + _meta.getAllowMethods() + ": " + _meta.getMapping() + " : " + _meta.getTargetClass().getName() + "." + _meta.getMethod().getName()); <ide> } <ide> // <ide> _isValid = true; <ide> StopWatch _consumeTime = null; <ide> long _threadId = Thread.currentThread().getId(); <ide> try { <add> _LOG.debug("--> [" + _threadId + "] Process request start: " + context.getHttpMethod() + ":" + context.getRequestMapping()); <ide> if (__owner.getConfig().isDevelopMode()) { <ide> _consumeTime = new StopWatch(); <ide> _consumeTime.start(); <del> } <del> _LOG.debug("--> [" + _threadId + "] Process request start: " + context.getHttpMethod() + ":" + context.getRequestMapping()); <add> _LOG.debug("--- [" + _threadId + "] Parameters: " + JSON.toJSONString(request.getParameterMap())); <add> } <ide> // <ide> RequestMeta _meta = __mappingParser.doParse(context); <ide> if (_meta != null) { <ide> _consumeTime.stop(); <ide> _LOG.debug("--- [" + _threadId + "] Total execution time: " + _consumeTime.getTime() + "ms"); <ide> } <del> _LOG.debug("<-- [" + _threadId + "] Process request completed: " + context.getHttpMethod() + ":" + context.getRequestMapping()); <add> _LOG.debug("<-- [" + _threadId + "] Process request completed: " + context.getHttpMethod() + ":" + context.getRequestMapping() + ": " + ((GenericResponseWrapper) response).getStatus()); <ide> } <ide> } <ide> }
Java
apache-2.0
59e8d6c13c3c804b0afeb2c938dd91ed6641e48b
0
lucaswerkmeister/ceylon.language,lucaswerkmeister/ceylon.language,unratito/ceylon.language,ceylon/ceylon.language,ceylon/ceylon.language,jvasileff/ceylon.language,unratito/ceylon.language,jvasileff/ceylon.language
package ceylon.language; import java.util.Arrays; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Ignore; import com.redhat.ceylon.compiler.java.metadata.Name; import com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes; import com.redhat.ceylon.compiler.java.metadata.TypeInfo; import com.redhat.ceylon.compiler.java.metadata.TypeParameter; import com.redhat.ceylon.compiler.java.metadata.TypeParameters; @Ceylon @TypeParameters(@TypeParameter(value = "Element")) @SatisfiedTypes({ "ceylon.language.List<Element>", "ceylon.language.FixedSized<Element>", "ceylon.language.Ranged<ceylon.language.Integer,ceylon.language.Empty|ceylon.language.Array<Element>>", "ceylon.language.Cloneable<ceylon.language.Array<Element>>" }) public abstract class Array<Element> implements List<Element>, FixedSized<Element> { protected final java.lang.Object array; public Array(char... array) { this.array = array; } public Array(byte... array) { this.array = array; } public Array(short... array) { this.array = array; } public Array(int... array) { this.array = array; } public Array(long... array) { this.array = array; } public Array(float... array) { this.array = array; } public Array(double... array) { this.array = array; } public Array(boolean... array) { this.array = array; } public Array(java.lang.String... array) { this.array = array; } public Array(Element... array) { this.array = array; } @Ignore Array(java.util.List<Element> list) { this.array = list.toArray(); } @Ignore Array(int size) { this.array = new Object[size]; } @Ignore public static Array<Character> instance(char[] array) { if (array.length == 0) { return new EmptyArray<Character>(); } else { return new NonemptyArray<Character>(array); } } @Ignore public static Array<Integer> instance(byte[] array) { if (array.length == 0) { return new EmptyArray<Integer>(); } else { return new NonemptyArray<Integer>(array); } } @Ignore public static Array<Integer> instance(short[] array) { if (array.length == 0) { return new EmptyArray<Integer>(); } else { return new NonemptyArray<Integer>(array); } } @Ignore public static Array<Integer> instance(int[] array) { if (array.length == 0) { return new EmptyArray<Integer>(); } else { return new NonemptyArray<Integer>(array); } } @Ignore public static Array<Integer> instance(long[] array) { if (array.length == 0) { return new EmptyArray<Integer>(); } else { return new NonemptyArray<Integer>(array); } } @Ignore public static Array<Float> instance(float[] array) { if (array.length == 0) { return new EmptyArray<Float>(); } else { return new NonemptyArray<Float>(array); } } @Ignore public static Array<Float> instance(double[] array) { if (array.length == 0) { return new EmptyArray<Float>(); } else { return new NonemptyArray<Float>(array); } } @Ignore public static Array<Boolean> instance(boolean[] array) { if (array.length == 0) { return new EmptyArray<Boolean>(); } else { return new NonemptyArray<Boolean>(array); } } @Ignore public static Array<String> instance(java.lang.String[] array) { if (array.length == 0) { return new EmptyArray<String>(); } else { return new NonemptyArray<String>(array); } } @Ignore public static <T> Array<T> instance(T[] array) { if (array.length == 0) { return new EmptyArray<T>(); } else { return new NonemptyArray<T>(array); } } @Override public Element getFirst() { if (getEmpty()) { return null; } else { return unsafeItem(0); } } @Override public java.lang.Object span(Integer from, Integer to) { long fromIndex = from.longValue(); if (fromIndex<0) fromIndex=0; long toIndex = to==null ? getSize()-1 : to.longValue(); long lastIndex = getLastIndex().longValue(); if (fromIndex>lastIndex||toIndex<fromIndex) { return $empty.getEmpty(); } else { if (array instanceof char[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((char[])array, (int)fromIndex, (int)toIndex+1)); } else if (array instanceof byte[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((byte[])array, (int)fromIndex, (int)toIndex+1)); } else if (array instanceof short[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((short[])array, (int)fromIndex, (int)toIndex+1)); } else if (array instanceof int[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((int[])array, (int)fromIndex, (int)toIndex+1)); } else if (array instanceof long[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((long[])array, (int)fromIndex, (int)toIndex+1)); } else if (array instanceof float[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((float[])array, (int)fromIndex, (int)toIndex+1)); } else if (array instanceof double[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((double[])array, (int)fromIndex, (int)toIndex+1)); } else if (array instanceof boolean[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((boolean[])array, (int)fromIndex, (int)toIndex+1)); } else if (array instanceof java.lang.String[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((java.lang.String[])array, (int)fromIndex, (int)toIndex+1)); } else { return new NonemptyArray<Element>(Arrays.copyOfRange((Element[])array, (int)fromIndex, (int)toIndex+1)); } } } @Override public java.lang.Object segment(Integer from, Integer length) { long fromIndex = from.longValue(); if (fromIndex<0) fromIndex=0; long resultLength = length.longValue(); long lastIndex = getLastIndex().longValue(); if (fromIndex>lastIndex||resultLength==0) { return $empty.getEmpty(); } else { if (array instanceof char[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((char[])array, (int)fromIndex, (int)(fromIndex + resultLength))); } else if (array instanceof byte[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((byte[])array, (int)fromIndex, (int)(fromIndex + resultLength))); } else if (array instanceof short[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((short[])array, (int)fromIndex, (int)(fromIndex + resultLength))); } else if (array instanceof int[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((int[])array, (int)fromIndex, (int)(fromIndex + resultLength))); } else if (array instanceof long[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((long[])array, (int)fromIndex, (int)(fromIndex + resultLength))); } else if (array instanceof float[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((float[])array, (int)fromIndex, (int)(fromIndex + resultLength))); } else if (array instanceof double[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((double[])array, (int)fromIndex, (int)(fromIndex + resultLength))); } else if (array instanceof boolean[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((boolean[])array, (int)fromIndex, (int)(fromIndex + resultLength))); } else if (array instanceof java.lang.String[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((java.lang.String[])array, (int)fromIndex, (int)(fromIndex + resultLength))); } else { return new NonemptyArray<Element>(Arrays.copyOfRange((Element[])array, (int)fromIndex, (int)(fromIndex + resultLength))); } } } @Override @TypeInfo("ceylon.language.Integer") public Integer getLastIndex() { return Integer.instance(getSize() - 1); } @Override public boolean getEmpty() { return getSize() == 0; } @Override @TypeInfo("ceylon.language.Integer") public long getSize() { if (array instanceof char[]) { return ((char[])array).length; } else if (array instanceof byte[]) { return ((byte[])array).length; } else if (array instanceof short[]) { return ((short[])array).length; } else if (array instanceof int[]) { return ((int[])array).length; } else if (array instanceof long[]) { return ((long[])array).length; } else if (array instanceof float[]) { return ((float[])array).length; } else if (array instanceof double[]) { return ((double[])array).length; } else if (array instanceof boolean[]) { return ((boolean[])array).length; } else if (array instanceof java.lang.String[]) { return ((java.lang.String[])array).length; } else { return ((Element[])array).length; } } @Override public boolean defines(Integer index) { long ind = index.longValue(); return ind >= 0 && ind < getSize(); } @Override public Iterator<Element> getIterator() { return new ArrayIterator(); } public class ArrayIterator implements Iterator<Element> { private int idx = 0; @Override public java.lang.Object next() { if (idx < getSize()) { return unsafeItem(idx++); } else { return exhausted.getExhausted(); } } @Override public java.lang.String toString() { return "ArrayIterator"; } } @Override public Element item(Integer key) { long index = key.longValue(); return item((int)index); } private Element item(int index) { return index < 0 || index >= getSize() ? null : unsafeItem(index); } private Element unsafeItem(int index) { if (array instanceof char[]) { return (Element) Character.instance(((char[])array)[index]); } else if (array instanceof byte[]) { return (Element) Integer.instance(((byte[])array)[index]); } else if (array instanceof short[]) { return (Element) Integer.instance(((short[])array)[index]); } else if (array instanceof int[]) { return (Element) Integer.instance(((int[])array)[index]); } else if (array instanceof long[]) { return (Element) Integer.instance(((long[])array)[index]); } else if (array instanceof float[]) { return (Element) Float.instance(((float[])array)[index]); } else if (array instanceof double[]) { return (Element) Float.instance(((float[])array)[index]); } else if (array instanceof boolean[]) { return (Element) Boolean.instance(((boolean[])array)[index]); } else if (array instanceof java.lang.String[]) { return (Element) String.instance(((java.lang.String[])array)[index]); } else { return ((Element[])array)[index]; } } public void setItem(@Name("index") @TypeInfo("ceylon.language.Integer") long index, @Name("element") @TypeInfo("ceylon.language.Nothing|Element") Element element) { int idx = (int) index; if (idx>=0 && idx < getSize()) { if (array instanceof char[]) { // FIXME This is really unsafe! Should we try to do something more intelligent here?? ((char[])array)[idx] = (char) ((Character)element).codePoint; } else if (array instanceof byte[]) { // FIXME Another unsafe conversion ((byte[])array)[idx] = (byte) ((Integer)element).longValue(); } else if (array instanceof short[]) { // FIXME Another unsafe conversion ((short[])array)[idx] = (short) ((Integer)element).longValue(); } else if (array instanceof int[]) { // FIXME Another unsafe conversion ((int[])array)[idx] = (int) ((Integer)element).longValue(); } else if (array instanceof long[]) { ((long[])array)[idx] = ((Integer)element).longValue(); } else if (array instanceof float[]) { // FIXME Another unsafe conversion ((float[])array)[idx] = (float) ((Float)element).doubleValue(); } else if (array instanceof double[]) { ((double[])array)[idx] = ((Float)element).doubleValue(); } else if (array instanceof boolean[]) { ((boolean[])array)[idx] = ((Boolean)element).booleanValue(); } else if (array instanceof java.lang.String[]) { ((java.lang.String[])array)[idx] = ((String)element).toString(); } else { ((Element[])array)[idx] = element; } } } @Override public Category getKeys() { return Correspondence$impl.getKeys(this); } @Override public boolean definesEvery(Iterable<? extends Integer> keys) { return Correspondence$impl.definesEvery(this, keys); } @Override public boolean definesAny(Iterable<? extends Integer> keys) { return Correspondence$impl.definesAny(this, keys); } @Override public ceylon.language.List<? extends Element> items(Iterable<? extends Integer> keys) { return Correspondence$impl.items(this, keys); } @Override public Array<Element> getClone() { return this; } @Override public java.lang.String toString() { return List$impl.toString(this); } public java.lang.Object toArray() { return array; } @Override public boolean equals(java.lang.Object that) { return List$impl.equals(this, that); } @Override public int hashCode() { return List$impl.hashCode(this); } @Override public boolean contains(java.lang.Object element) { // FIXME Very inefficient for primitive types due to boxing Iterator<Element> iter = getIterator(); java.lang.Object elem; while (!((elem = iter.next()) instanceof Finished)) { if (elem != null && element.equals(element)) { return true; } } return false; } @Override public long count(java.lang.Object element) { // FIXME Very inefficient for primitive types due to boxing int count=0; Iterator<Element> iter = getIterator(); java.lang.Object elem; while (!((elem = iter.next()) instanceof Finished)) { if (elem != null && element.equals(element)) { count++; } } return count; } @Override public boolean containsEvery(Iterable<?> elements) { return Category$impl.containsEvery(this, elements); } @Override public boolean containsAny(Iterable<?> elements) { return Category$impl.containsAny(this, elements); } } @Ignore class EmptyArray<Element> extends Array<Element> implements None<Element> { public EmptyArray() { super(0); } } @Ignore class NonemptyArray<Element> extends Array<Element> implements Some<Element> { public NonemptyArray(char... array) { super(array); } public NonemptyArray(byte... array) { super(array); } public NonemptyArray(short... array) { super(array); } public NonemptyArray(int... array) { super(array); } public NonemptyArray(long... array) { super(array); } public NonemptyArray(float... array) { super(array); } public NonemptyArray(double... array) { super(array); } public NonemptyArray(boolean... array) { super(array); } public NonemptyArray(java.lang.String... array) { super(array); } public NonemptyArray(Element... array) { super(array); } @Ignore public NonemptyArray(java.util.List<Element> list) { super(list); } @Override public FixedSized<? extends Element> getRest() { if (getSize() == 1) { return arrayOfNone.<Element>arrayOfNone(); } else { if (array instanceof char[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((char[])array, 1, (int)getSize() - 1)); } else if (array instanceof byte[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((byte[])array, 1, (int)getSize() - 1)); } else if (array instanceof short[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((short[])array, 1, (int)getSize() - 1)); } else if (array instanceof int[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((int[])array, 1, (int)getSize() - 1)); } else if (array instanceof long[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((long[])array, 1, (int)getSize() - 1)); } else if (array instanceof float[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((float[])array, 1, (int)getSize() - 1)); } else if (array instanceof double[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((double[])array, 1, (int)getSize() - 1)); } else if (array instanceof boolean[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((boolean[])array, 1, (int)getSize() - 1)); } else if (array instanceof java.lang.String[]) { return new NonemptyArray<Element>(Arrays.copyOfRange((java.lang.String[])array, 1, (int)getSize() - 1)); } else { return new NonemptyArray<Element>(Arrays.copyOfRange((Element[])array, 1, (int)getSize() - 1)); } } } }
runtime/ceylon/language/Array.java
package ceylon.language; import java.util.Arrays; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Ignore; import com.redhat.ceylon.compiler.java.metadata.Name; import com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes; import com.redhat.ceylon.compiler.java.metadata.TypeInfo; import com.redhat.ceylon.compiler.java.metadata.TypeParameter; import com.redhat.ceylon.compiler.java.metadata.TypeParameters; @Ceylon @TypeParameters(@TypeParameter(value = "Element")) @SatisfiedTypes({ "ceylon.language.List<Element>", "ceylon.language.FixedSized<Element>", "ceylon.language.Ranged<ceylon.language.Integer,ceylon.language.Empty|ceylon.language.Array<Element>>", "ceylon.language.Cloneable<ceylon.language.Array<Element>>" }) public abstract class Array<Element> implements List<Element>, FixedSized<Element> { protected final java.lang.Object array; public Array(char... array) { this.array = array; } public Array(byte... array) { this.array = array; } public Array(short... array) { this.array = array; } public Array(int... array) { this.array = array; } public Array(long... array) { this.array = array; } public Array(float... array) { this.array = array; } public Array(double... array) { this.array = array; } public Array(boolean... array) { this.array = array; } public Array(java.lang.String... array) { this.array = array; } public Array(Element... array) { this.array = array; } @Ignore Array(java.util.List<Element> list) { this.array = list.toArray(); } @Ignore Array(int size) { this.array = new Object[size]; } @Ignore public static Array<Character> instance(char[] array) { if (array.length == 0) { return new EmptyArray<Character>(); } else { return new NonemptyArray<Character>(array); } } @Ignore public static Array<Integer> instance(byte[] array) { if (array.length == 0) { return new EmptyArray<Integer>(); } else { return new NonemptyArray<Integer>(array); } } @Ignore public static Array<Integer> instance(short[] array) { if (array.length == 0) { return new EmptyArray<Integer>(); } else { return new NonemptyArray<Integer>(array); } } @Ignore public static Array<Integer> instance(int[] array) { if (array.length == 0) { return new EmptyArray<Integer>(); } else { return new NonemptyArray<Integer>(array); } } @Ignore public static Array<Integer> instance(long[] array) { if (array.length == 0) { return new EmptyArray<Integer>(); } else { return new NonemptyArray<Integer>(array); } } @Ignore public static Array<Float> instance(float[] array) { if (array.length == 0) { return new EmptyArray<Float>(); } else { return new NonemptyArray<Float>(array); } } @Ignore public static Array<Float> instance(double[] array) { if (array.length == 0) { return new EmptyArray<Float>(); } else { return new NonemptyArray<Float>(array); } } @Ignore public static Array<Boolean> instance(boolean[] array) { if (array.length == 0) { return new EmptyArray<Boolean>(); } else { return new NonemptyArray<Boolean>(array); } } @Ignore public static Array<String> instance(java.lang.String[] array) { if (array.length == 0) { return new EmptyArray<String>(); } else { return new NonemptyArray<String>(array); } } @Ignore public static <T> Array<T> instance(T[] array) { if (array.length == 0) { return new EmptyArray<T>(); } else { return new NonemptyArray<T>(array); } } @Override public Element getFirst() { if (getEmpty()) { return null; } else { return unsafeItem(0); } } @Override public java.lang.Object span(Integer from, Integer to) { long fromIndex = from.longValue(); if (fromIndex<0) fromIndex=0; long toIndex = to==null ? getSize()-1 : to.longValue(); long lastIndex = getLastIndex().longValue(); if (fromIndex>lastIndex||toIndex<fromIndex) { return $empty.getEmpty(); } else if (toIndex>lastIndex) { throw new RuntimeException("Not yet implemented"); // TODO Not yet implemented //return new ArraySequence<Element>(array, fromIndex); } else { throw new RuntimeException("Not yet implemented"); // TODO Not yet implemented //return new ArraySequence<Element>(Arrays.copyOfRange(array, // (int)fromIndex, (int)toIndex+1), 0); } } @Override public java.lang.Object segment(Integer from, Integer length) { long fromIndex = from.longValue(); if (fromIndex<0) fromIndex=0; long resultLength = length.longValue(); long lastIndex = getLastIndex().longValue(); if (fromIndex>lastIndex||resultLength==0) { return $empty.getEmpty(); } else if (fromIndex+resultLength>lastIndex) { throw new RuntimeException("Not yet implemented"); // TODO Not yet implemented //return new ArraySequence<Element>(array, fromIndex); } else { throw new RuntimeException("Not yet implemented"); // TODO Not yet implemented //return new ArraySequence<Element>(Arrays.copyOfRange(array, // (int)fromIndex, (int)(fromIndex + resultLength)), 0); } } @Override @TypeInfo("ceylon.language.Integer") public Integer getLastIndex() { return Integer.instance(getSize() - 1); } @Override public boolean getEmpty() { return getSize() == 0; } @Override @TypeInfo("ceylon.language.Integer") public long getSize() { if (array instanceof char[]) { return ((char[])array).length; } else if (array instanceof byte[]) { return ((byte[])array).length; } else if (array instanceof short[]) { return ((short[])array).length; } else if (array instanceof int[]) { return ((int[])array).length; } else if (array instanceof long[]) { return ((long[])array).length; } else if (array instanceof float[]) { return ((float[])array).length; } else if (array instanceof double[]) { return ((double[])array).length; } else if (array instanceof boolean[]) { return ((boolean[])array).length; } else if (array instanceof java.lang.String[]) { return ((java.lang.String[])array).length; } else { return ((Element[])array).length; } } @Override public boolean defines(Integer index) { long ind = index.longValue(); return ind >= 0 && ind < getSize(); } @Override public Iterator<Element> getIterator() { return new ArrayIterator(); } public class ArrayIterator implements Iterator<Element> { private int idx = 0; @Override public java.lang.Object next() { if (idx < getSize()) { return unsafeItem(idx++); } else { return exhausted.getExhausted(); } } @Override public java.lang.String toString() { return "ArrayIterator"; } } @Override public Element item(Integer key) { long index = key.longValue(); return item((int)index); } private Element item(int index) { return index < 0 || index >= getSize() ? null : unsafeItem(index); } private Element unsafeItem(int index) { if (array instanceof char[]) { return (Element) Character.instance(((char[])array)[index]); } else if (array instanceof byte[]) { return (Element) Integer.instance(((byte[])array)[index]); } else if (array instanceof short[]) { return (Element) Integer.instance(((short[])array)[index]); } else if (array instanceof int[]) { return (Element) Integer.instance(((int[])array)[index]); } else if (array instanceof long[]) { return (Element) Integer.instance(((long[])array)[index]); } else if (array instanceof float[]) { return (Element) Float.instance(((float[])array)[index]); } else if (array instanceof double[]) { return (Element) Float.instance(((float[])array)[index]); } else if (array instanceof boolean[]) { return (Element) Boolean.instance(((boolean[])array)[index]); } else if (array instanceof java.lang.String[]) { return (Element) String.instance(((java.lang.String[])array)[index]); } else { return ((Element[])array)[index]; } } public void setItem(@Name("index") @TypeInfo("ceylon.language.Integer") long index, @Name("element") @TypeInfo("ceylon.language.Nothing|Element") Element element) { int idx = (int) index; if (idx>=0 && idx < getSize()) { if (array instanceof char[]) { // FIXME This is really unsafe! Should we try to do something more intelligent here?? ((char[])array)[idx] = (char) ((Character)element).codePoint; } else if (array instanceof byte[]) { // FIXME Another unsafe conversion ((byte[])array)[idx] = (byte) ((Integer)element).longValue(); } else if (array instanceof short[]) { // FIXME Another unsafe conversion ((short[])array)[idx] = (short) ((Integer)element).longValue(); } else if (array instanceof int[]) { // FIXME Another unsafe conversion ((int[])array)[idx] = (int) ((Integer)element).longValue(); } else if (array instanceof long[]) { ((long[])array)[idx] = ((Integer)element).longValue(); } else if (array instanceof float[]) { // FIXME Another unsafe conversion ((float[])array)[idx] = (float) ((Float)element).doubleValue(); } else if (array instanceof double[]) { ((double[])array)[idx] = ((Float)element).doubleValue(); } else if (array instanceof boolean[]) { ((boolean[])array)[idx] = ((Boolean)element).booleanValue(); } else if (array instanceof java.lang.String[]) { ((java.lang.String[])array)[idx] = ((String)element).toString(); } else { ((Element[])array)[idx] = element; } } } @Override public Category getKeys() { return Correspondence$impl.getKeys(this); } @Override public boolean definesEvery(Iterable<? extends Integer> keys) { return Correspondence$impl.definesEvery(this, keys); } @Override public boolean definesAny(Iterable<? extends Integer> keys) { return Correspondence$impl.definesAny(this, keys); } @Override public ceylon.language.List<? extends Element> items(Iterable<? extends Integer> keys) { return Correspondence$impl.items(this, keys); } @Override public Array<Element> getClone() { return this; } @Override public java.lang.String toString() { return List$impl.toString(this); } public java.lang.Object toArray() { return array; } @Override public boolean equals(java.lang.Object that) { return List$impl.equals(this, that); } @Override public int hashCode() { return List$impl.hashCode(this); } @Override public boolean contains(java.lang.Object element) { // FIXME Very inefficient for primitive types due to boxing Iterator<Element> iter = getIterator(); java.lang.Object elem; while (!((elem = iter.next()) instanceof Finished)) { if (elem != null && element.equals(element)) { return true; } } return false; } @Override public long count(java.lang.Object element) { // FIXME Very inefficient for primitive types due to boxing int count=0; Iterator<Element> iter = getIterator(); java.lang.Object elem; while (!((elem = iter.next()) instanceof Finished)) { if (elem != null && element.equals(element)) { count++; } } return count; } @Override public boolean containsEvery(Iterable<?> elements) { return Category$impl.containsEvery(this, elements); } @Override public boolean containsAny(Iterable<?> elements) { return Category$impl.containsAny(this, elements); } } @Ignore class EmptyArray<Element> extends Array<Element> implements None<Element> { public EmptyArray() { super(0); } } @Ignore class NonemptyArray<Element> extends Array<Element> implements Some<Element> { public NonemptyArray(char... array) { super(array); } public NonemptyArray(byte... array) { super(array); } public NonemptyArray(short... array) { super(array); } public NonemptyArray(int... array) { super(array); } public NonemptyArray(long... array) { super(array); } public NonemptyArray(float... array) { super(array); } public NonemptyArray(double... array) { super(array); } public NonemptyArray(boolean... array) { super(array); } public NonemptyArray(java.lang.String... array) { super(array); } public NonemptyArray(Element... array) { super(array); } @Ignore public NonemptyArray(java.util.List<Element> list) { super(list); } @Override public FixedSized<? extends Element> getRest() { if (getSize() == 1) { return arrayOfNone.<Element>arrayOfNone(); } else { throw new RuntimeException("Not yet implemented"); // TODO Not yet implemented //return new NonemptyArray<Element>(Arrays.copyOfRange(array, 1, getSize() - 1)); } } }
First implementation for span(), segment() and rest
runtime/ceylon/language/Array.java
First implementation for span(), segment() and rest
<ide><path>untime/ceylon/language/Array.java <ide> long lastIndex = getLastIndex().longValue(); <ide> if (fromIndex>lastIndex||toIndex<fromIndex) { <ide> return $empty.getEmpty(); <del> } else if (toIndex>lastIndex) { <del> throw new RuntimeException("Not yet implemented"); // TODO Not yet implemented <del> //return new ArraySequence<Element>(array, fromIndex); <del> } else { <del> throw new RuntimeException("Not yet implemented"); // TODO Not yet implemented <del> //return new ArraySequence<Element>(Arrays.copyOfRange(array, <del> // (int)fromIndex, (int)toIndex+1), 0); <add> } else { <add> if (array instanceof char[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((char[])array, (int)fromIndex, (int)toIndex+1)); <add> } else if (array instanceof byte[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((byte[])array, (int)fromIndex, (int)toIndex+1)); <add> } else if (array instanceof short[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((short[])array, (int)fromIndex, (int)toIndex+1)); <add> } else if (array instanceof int[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((int[])array, (int)fromIndex, (int)toIndex+1)); <add> } else if (array instanceof long[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((long[])array, (int)fromIndex, (int)toIndex+1)); <add> } else if (array instanceof float[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((float[])array, (int)fromIndex, (int)toIndex+1)); <add> } else if (array instanceof double[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((double[])array, (int)fromIndex, (int)toIndex+1)); <add> } else if (array instanceof boolean[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((boolean[])array, (int)fromIndex, (int)toIndex+1)); <add> } else if (array instanceof java.lang.String[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((java.lang.String[])array, (int)fromIndex, (int)toIndex+1)); <add> } else { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((Element[])array, (int)fromIndex, (int)toIndex+1)); <add> } <ide> } <ide> } <ide> <ide> long lastIndex = getLastIndex().longValue(); <ide> if (fromIndex>lastIndex||resultLength==0) { <ide> return $empty.getEmpty(); <del> } <del> else if (fromIndex+resultLength>lastIndex) { <del> throw new RuntimeException("Not yet implemented"); // TODO Not yet implemented <del> //return new ArraySequence<Element>(array, fromIndex); <del> } <del> else { <del> throw new RuntimeException("Not yet implemented"); // TODO Not yet implemented <del> //return new ArraySequence<Element>(Arrays.copyOfRange(array, <del> // (int)fromIndex, (int)(fromIndex + resultLength)), 0); <add> } else { <add> if (array instanceof char[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((char[])array, (int)fromIndex, (int)(fromIndex + resultLength))); <add> } else if (array instanceof byte[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((byte[])array, (int)fromIndex, (int)(fromIndex + resultLength))); <add> } else if (array instanceof short[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((short[])array, (int)fromIndex, (int)(fromIndex + resultLength))); <add> } else if (array instanceof int[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((int[])array, (int)fromIndex, (int)(fromIndex + resultLength))); <add> } else if (array instanceof long[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((long[])array, (int)fromIndex, (int)(fromIndex + resultLength))); <add> } else if (array instanceof float[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((float[])array, (int)fromIndex, (int)(fromIndex + resultLength))); <add> } else if (array instanceof double[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((double[])array, (int)fromIndex, (int)(fromIndex + resultLength))); <add> } else if (array instanceof boolean[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((boolean[])array, (int)fromIndex, (int)(fromIndex + resultLength))); <add> } else if (array instanceof java.lang.String[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((java.lang.String[])array, (int)fromIndex, (int)(fromIndex + resultLength))); <add> } else { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((Element[])array, (int)fromIndex, (int)(fromIndex + resultLength))); <add> } <ide> } <ide> } <ide> <ide> if (getSize() == 1) { <ide> return arrayOfNone.<Element>arrayOfNone(); <ide> } else { <del> throw new RuntimeException("Not yet implemented"); // TODO Not yet implemented <del> //return new NonemptyArray<Element>(Arrays.copyOfRange(array, 1, getSize() - 1)); <add> if (array instanceof char[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((char[])array, 1, (int)getSize() - 1)); <add> } else if (array instanceof byte[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((byte[])array, 1, (int)getSize() - 1)); <add> } else if (array instanceof short[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((short[])array, 1, (int)getSize() - 1)); <add> } else if (array instanceof int[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((int[])array, 1, (int)getSize() - 1)); <add> } else if (array instanceof long[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((long[])array, 1, (int)getSize() - 1)); <add> } else if (array instanceof float[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((float[])array, 1, (int)getSize() - 1)); <add> } else if (array instanceof double[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((double[])array, 1, (int)getSize() - 1)); <add> } else if (array instanceof boolean[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((boolean[])array, 1, (int)getSize() - 1)); <add> } else if (array instanceof java.lang.String[]) { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((java.lang.String[])array, 1, (int)getSize() - 1)); <add> } else { <add> return new NonemptyArray<Element>(Arrays.copyOfRange((Element[])array, 1, (int)getSize() - 1)); <add> } <ide> } <ide> } <ide>
Java
mit
a5e9339798a26746d2c52bb42a17f4215c8a686f
0
JCThePants/NucleusFramework,JCThePants/NucleusFramework
/* * This file is part of GenericsLib for Bukkit, licensed under the MIT License (MIT). * * Copyright (c) JCThePants (www.jcwhatever.com) * * 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.jcwhatever.bukkit.generic.regions; import com.jcwhatever.bukkit.generic.GenericsLib; import com.jcwhatever.bukkit.generic.events.bukkit.regions.RegionOwnerChangedEvent; import com.jcwhatever.bukkit.generic.mixins.IDisposable; import com.jcwhatever.bukkit.generic.regions.data.RegionSelection; import com.jcwhatever.bukkit.generic.storage.IDataNode; import com.jcwhatever.bukkit.generic.utils.PreCon; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldUnloadEvent; import org.bukkit.plugin.Plugin; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.WeakHashMap; import javax.annotation.Nullable; /** * Abstract implementation of a region. * * <p>The region is registered with GenericsLib {@link RegionManager} as soon * as it is defined (P1 and P2 coordinates set) via the regions settings or by * calling {@code setCoords} method.</p> * * <p>The regions protected methods {@code onPlayerEnter} and {@code onPlayerLeave} * are only called if the implementing type calls {@code setIsPlayerWatcher(true)}.</p> */ public abstract class Region extends RegionSelection implements IRegion, IDisposable { private static final Map<Region, Void> _instances = new WeakHashMap<>(100); private static BukkitListener _bukkitListener; private final Plugin _plugin; private final String _name; private final String _searchName; private IDataNode _dataNode; private RegionPriority _enterPriority = RegionPriority.DEFAULT; private RegionPriority _leavePriority = RegionPriority.DEFAULT; private boolean _isPlayerWatcher = false; private String _worldName; private UUID _ownerId; private List<Chunk> _chunks; private Map<Object, Object> _meta = new HashMap<Object, Object>(30); private List<IRegionEventHandler> _eventHandlers = new ArrayList<>(10); /** * The priority/order the region is handled by the * region manager in relation to other regions. */ public enum RegionPriority { /** * The last to be handled. */ LAST (4), /** * Low priority. Handled second to last. */ LOW (3), /** * Normal priority. */ DEFAULT (2), /** * High priority. Handled second. */ HIGH (1), /** * Highest priority. Handled first. */ FIRST (0); private final int _order; RegionPriority(int order) { _order = order; } /** * Get a sort order index number. */ public int getSortOrder() { return _order; } } /** * Type of region priority. */ public enum PriorityType { ENTER, LEAVE } /** * Reasons a player enters a region. */ public enum EnterRegionReason { /** * The player moved into the region. */ MOVE, /** * The player teleported into the region. */ TELEPORT, /** * The player respawned into the region. */ RESPAWN, /** * The player joined the server and * spawned into the region. */ JOIN_SERVER } /** * Reasons a player leaves a region. */ public enum LeaveRegionReason { /** * The player moved out of the region. */ MOVE, /** * The player teleported out of the region. */ TELEPORT, /** * The player died in the region. */ DEAD, /** * The player left the server while * in the region. */ QUIT_SERVER } /** * For internal use. */ public enum RegionReason { MOVE (EnterRegionReason.MOVE, LeaveRegionReason.MOVE), DEAD (null, LeaveRegionReason.DEAD), TELEPORT (EnterRegionReason.TELEPORT, LeaveRegionReason.TELEPORT), RESPAWN (EnterRegionReason.RESPAWN, LeaveRegionReason.DEAD), JOIN_SERVER (EnterRegionReason.JOIN_SERVER, null), QUIT_SERVER (null, LeaveRegionReason.QUIT_SERVER); private final EnterRegionReason _enter; private final LeaveRegionReason _leave; RegionReason(EnterRegionReason enter, LeaveRegionReason leave) { _enter = enter; _leave = leave; } /** * Get the enter reason equivalent. */ @Nullable public EnterRegionReason getEnterReason() { return _enter; } /** * Get the leave reason equivalent. */ @Nullable public LeaveRegionReason getLeaveReason() { return _leave; } } /** * Constructor */ public Region(Plugin plugin, String name, @Nullable IDataNode dataNode) { PreCon.notNull(plugin); PreCon.notNullOrEmpty(name); _name = name; _plugin = plugin; _searchName = name.toLowerCase(); _dataNode = dataNode; RegionPriorityInfo info = this.getClass().getAnnotation(RegionPriorityInfo.class); if (info != null) { _enterPriority = info.enter(); _leavePriority = info.leave(); } if (dataNode != null) { loadSettings(dataNode); } _instances.put(this, null); if (_bukkitListener == null) { _bukkitListener = new BukkitListener(); Bukkit.getPluginManager().registerEvents(_bukkitListener, GenericsLib.getLib()); } } /** * Get the name of the region. */ @Override public final String getName() { return _name; } /** * Get the name of the region in lower case. */ @Override public final String getSearchName() { return _searchName; } /** * Get the owning plugin. */ @Override public final Plugin getPlugin() { return _plugin; } /** * Get the regions data node. */ @Nullable public IDataNode getDataNode() { return _dataNode; } /** * Get the regions priority when handling player * entering region. */ @Override public RegionPriority getPriority(PriorityType priorityType) { PreCon.notNull(priorityType); switch (priorityType) { case ENTER: return _enterPriority; case LEAVE: return _leavePriority; default: throw new AssertionError(); } } /** * Get the name of the world the region is in. */ @Nullable public final String getWorldName() { return _worldName; } /** * Determine if the world the region is in is loaded. */ public final boolean isWorldLoaded() { if (!isDefined()) return false; if (getWorld() == null) return false; World world = Bukkit.getWorld(getWorld().getName()); return getWorld().equals(world); } /** * Used to determine if the region subscribes to player events. */ @Override public final boolean isPlayerWatcher() { return _isPlayerWatcher || !_eventHandlers.isEmpty(); } /** * Get the id of the region owner. */ @Override @Nullable public UUID getOwnerId() { return _ownerId; } /** * Determine if the region has an owner. */ @Override public boolean hasOwner() { return _ownerId != null; } /** * Set the regions owner. * * @param ownerId The id of the new owner. */ @Override public boolean setOwner(@Nullable UUID ownerId) { UUID oldId = _ownerId; RegionOwnerChangedEvent event = RegionOwnerChangedEvent.callEvent(new ReadOnlyRegion(this), oldId, ownerId); if (event.isCancelled()) return false; _ownerId = ownerId; IDataNode dataNode = getDataNode(); if (dataNode != null) { dataNode.set("owner-id", ownerId); dataNode.saveAsync(null); } onOwnerChanged(oldId, ownerId); return true; } /** * Set the regions cuboid point coordinates. * * <p>Saves to the regions data node if it has one.</p> * * @param p1 The first point location. * @param p2 The second point location. */ @Override public final void setCoords(Location p1, Location p2) { PreCon.notNull(p1); PreCon.notNull(p2); // unregister while math is updated, // is re-registered after math update (see UpdateMath) GenericsLib.getRegionManager().unregister(this); super.setCoords(p1, p2); updateWorld(); _chunks = null; IDataNode dataNode = getDataNode(); if (dataNode != null) { dataNode.set("p1", getP1()); dataNode.set("p2", getP2()); dataNode.saveAsync(null); } onCoordsChanged(getP1(), getP2()); } /** * Add a transient region event handler. * * @param handler The handler to add. */ @Override public boolean addEventHandler(IRegionEventHandler handler) { PreCon.notNull(handler); boolean isFirstHandler = _eventHandlers.isEmpty(); if (_eventHandlers.add(handler)) { if (isFirstHandler) { // update registration GenericsLib.getRegionManager().register(this); } return true; } return false; } /** * Remove a transient event handler. * * @param handler The handler to remove. */ @Override public boolean removeEventHandler(IRegionEventHandler handler) { PreCon.notNull(handler); if (_eventHandlers.remove(handler)) { if (_eventHandlers.isEmpty()) { // update registration GenericsLib.getRegionManager().register(this); } return true; } return false; } /** * Determine if the region contains the specified material. * * @param material The material to search for. */ @Override public final boolean contains(Material material) { synchronized (_sync) { if (getWorld() == null) return false; int xlen = getXEnd(); int ylen = getYEnd(); int zlen = getZEnd(); for (int x = getXStart(); x <= xlen; x++) { for (int y = getYStart(); y <= ylen; y++) { for (int z = getZStart(); z <= zlen; z++) { Block block = getWorld().getBlockAt(x, y, z); if (block.getType() != material) continue; return true; } } } _sync.notifyAll(); return false; } } /** * Get all locations that have a block of the specified material * within the region. * * @param material The material to search for. */ @Override public final LinkedList<Location> find(Material material) { synchronized (_sync) { LinkedList<Location> results = new LinkedList<>(); if (getWorld() == null) return results; int xlen = getXEnd(); int ylen = getYEnd(); int zlen = getZEnd(); for (int x = getXStart(); x <= xlen; x++) { for (int y = getYStart(); y <= ylen; y++) { for (int z = getZStart(); z <= zlen; z++) { Block block = getWorld().getBlockAt(x, y, z); if (block.getType() != material) continue; results.add(block.getLocation()); } } } _sync.notifyAll(); return results; } } /** * Get all chunks that contain at least a portion of the region. */ @Override public final List<Chunk> getChunks() { if (getWorld() == null) return new ArrayList<>(0); synchronized (_sync) { if (_chunks == null) { if (!isDefined()) { return new ArrayList<>(0); } Chunk c1 = getWorld().getChunkAt(getP1()); Chunk c2 = getWorld().getChunkAt(getP2()); int startX = Math.min(c1.getX(), c2.getX()); int endX = Math.max(c1.getX(), c2.getX()); int startZ = Math.min(c1.getZ(), c2.getZ()); int endZ = Math.max(c1.getZ(), c2.getZ()); ArrayList<Chunk> result = new ArrayList<Chunk>((endX - startX) * (endZ - startZ)); for (int x = startX; x <= endX; x++) { for (int z = startZ; z <= endZ; z++) { result.add(getWorld().getChunkAt(x, z)); } } _chunks = result; } _sync.notifyAll(); return new ArrayList<Chunk>(_chunks); } } /** * Refresh all chunks the region is in. */ @Override public final void refreshChunks() { World world = getWorld(); if (world == null) return; List<Chunk> chunks = getChunks(); for (Chunk chunk : chunks) { world.refreshChunk(chunk.getX(), chunk.getZ()); } } /** * Remove entities from the region. * * @param entityTypes The entity types to remove. */ @Override public final void removeEntities(Class<?>... entityTypes) { synchronized (_sync) { List<Chunk> chunks = getChunks(); for (Chunk chunk : chunks) { for (Entity entity : chunk.getEntities()) { if (this.contains(entity.getLocation())) { if (entityTypes == null || entityTypes.length == 0) { entity.remove(); continue; } for (Class<?> itemType : entityTypes) { if (itemType.isInstance(entity)) { entity.remove(); break; } } } } } _sync.notifyAll(); } } /** * Get a meta object from the region. * * @param key The meta key. * * @param <T> The object type. */ @Override public <T> T getMeta(Object key) { @SuppressWarnings("unchecked") T item = (T)_meta.get(key); return item; } /** * Set a meta object value in the region. * * @param key The meta key. * @param value The meta value. */ @Override public void setMeta(Object key, @Nullable Object value) { if (value == null) { _meta.remove(key); return; } _meta.put(key, value); } /** * Get the class of the region. */ @Override public Class<? extends IRegion> getRegionClass() { return getClass(); } /** * Dispose the region by releasing resources and * un-registering it from the central region manager. */ @Override public final void dispose() { GenericsLib.getRegionManager().unregister(this); _instances.remove(this); onDispose(); } /** * Set the value of the player watcher flag and update * the regions registration with the central region manager. * * @param isPlayerWatcher True to allow player enter and leave events. */ protected void setIsPlayerWatcher(boolean isPlayerWatcher) { if (isPlayerWatcher != _isPlayerWatcher) { _isPlayerWatcher = isPlayerWatcher; GenericsLib.getRegionManager().register(this); } } /** * Causes the onPlayerEnter method to re-fire * if the player is already in the region. * . * @param p The player to reset. */ protected void resetContainsPlayer(Player p) { GenericsLib.getRegionManager().resetPlayerRegion(p, this); } /** * Initializes region coordinates without saving to the data node. * * @param p1 The first point location. * @param p2 The second point location. */ protected final void initCoords(@Nullable Location p1, @Nullable Location p2) { setPoint(RegionPoint.P1, p1); setPoint(RegionPoint.P2, p2); updateWorld(); updateMath(); } /** * Initial load of settings from regions data node. * * @param dataNode The data node to load from */ protected void loadSettings(final IDataNode dataNode) { Location p1 = dataNode.getLocation("p1"); Location p2 = dataNode.getLocation("p2"); initCoords(p1, p2); _ownerId = dataNode.getUUID("owner-id"); _enterPriority = dataNode.getEnum("region-enter-priority", _enterPriority, RegionPriority.class); _leavePriority = dataNode.getEnum("region-leave-priority", _leavePriority, RegionPriority.class); } /* * Update region math variables */ @Override protected void updateMath() { super.updateMath(); GenericsLib.getRegionManager().register(this); } /** * Called when the coordinates for the region are changed * * <p>Intended for implementation use.</p> * * @param p1 The first point location. * @param p2 The second point location. * * @throws IOException */ protected void onCoordsChanged(@SuppressWarnings("unused") @Nullable Location p1, @SuppressWarnings("unused") @Nullable Location p2) { // do nothing } /** * Called when a player enters the region, * but only if the region is a player watcher and * canDoPlayerEnter() returns true. * * <p>Intended for implementation use.</p> * * @param p the player entering the region. */ protected void onPlayerEnter (@SuppressWarnings("unused") Player p, @SuppressWarnings("unused") EnterRegionReason reason) { // do nothing } /** * Called when a player leaves the region, * but only if the region is a player watcher and * canDoPlayerLeave() returns true. * * <p>Intended for implementation use.</p> * * @param p the player leaving the region. */ protected void onPlayerLeave (@SuppressWarnings("unused") Player p, @SuppressWarnings("unused") LeaveRegionReason reason) { // do nothing } /** * Called to determine if {@code onPlayerEnter} * can be called on the specified player. * * <p>Intended for override if needed.</p> * * @param p The player entering the region. */ protected boolean canDoPlayerEnter(@SuppressWarnings("unused") Player p, @SuppressWarnings("unused") EnterRegionReason reason) { return true; } /** * Called to determine if {@code onPlayerLeave} * can be called on the specified player. * * <p>Intended for override if needed.</p> * * @param p The player leaving the region. */ protected boolean canDoPlayerLeave(@SuppressWarnings("unused") Player p, @SuppressWarnings("unused") LeaveRegionReason reason) { return true; } /** * Called when the owner of the region is changed. * * <p>Intended for implementation use.</p> * * @param oldOwnerId The id of the previous owner of the region. * @param newOwnerId The id of the new owner of the region. */ protected void onOwnerChanged(@SuppressWarnings("unused") @Nullable UUID oldOwnerId, @SuppressWarnings("unused") @Nullable UUID newOwnerId) { // do nothing } /** * Called when the region is disposed. */ protected void onDispose() { // do nothings } /** * Used by {@code RegionManager} to execute onPlayerEnter event. */ void doPlayerEnter (Player p, EnterRegionReason reason) { if (canDoPlayerEnter(p, reason)) onPlayerEnter(p, reason); for (IRegionEventHandler handler : _eventHandlers) { if (handler.canDoPlayerEnter(p, reason)) { handler.onPlayerEnter(p, reason); } } } /** * Used by {@code RegionManager} to execute onPlayerLeave event. */ void doPlayerLeave (Player p, LeaveRegionReason reason) { if (canDoPlayerLeave(p, reason)) onPlayerLeave(p, reason); for (IRegionEventHandler handler : _eventHandlers) { if (handler.canDoPlayerLeave(p, reason)) { handler.onPlayerLeave(p, reason); } } } /* * Update world name if possible */ private void updateWorld() { Location p1 = getP1(); Location p2 = getP2(); if (p1 == null || p2 == null) { _worldName = null; return; } World p1World = p1.getWorld(); World p2World = p2.getWorld(); boolean isWorldsMismatched = p1World != null && !p1World.equals(p2World) || p2World != null && !p2World.equals(p1World); if (isWorldsMismatched) { throw new IllegalArgumentException("Both region points must be from the same world."); } if (p1World != null) { _worldName = p1World.getName(); } else { IDataNode dataNode = getDataNode(); if (dataNode != null) { _worldName = dataNode.getLocationWorldName("p1"); } } } @Override public int hashCode() { return _name.hashCode(); } @Override public boolean equals(Object obj) { synchronized (_sync) { if (obj instanceof Region) { Region region = (Region)obj; return region == this; } _sync.notifyAll(); return false; } } /* * Listens for world unload and load events and handles * regions in the world appropriately. */ private static class BukkitListener implements Listener { @EventHandler private void onWorldLoad(WorldLoadEvent event) { String worldName = event.getWorld().getName(); for (Region region : _instances.keySet()) { if (region.isDefined() && worldName.equals(region.getWorldName())) { // fix locations //noinspection ConstantConditions region.getP1().setWorld(event.getWorld()); //noinspection ConstantConditions region.getP2().setWorld(event.getWorld()); } } } @EventHandler private void onWorldUnload(WorldUnloadEvent event) { String worldName = event.getWorld().getName(); for (Region region : _instances.keySet()) { if (region.isDefined() && worldName.equals(region.getWorldName())) { // remove world from locations, helps garbage collector //noinspection ConstantConditions region.getP1().setWorld(null); //noinspection ConstantConditions region.getP2().setWorld(null); region._chunks = null; } } } } }
src/com/jcwhatever/bukkit/generic/regions/Region.java
/* * This file is part of GenericsLib for Bukkit, licensed under the MIT License (MIT). * * Copyright (c) JCThePants (www.jcwhatever.com) * * 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.jcwhatever.bukkit.generic.regions; import com.jcwhatever.bukkit.generic.GenericsLib; import com.jcwhatever.bukkit.generic.events.bukkit.regions.RegionOwnerChangedEvent; import com.jcwhatever.bukkit.generic.mixins.IDisposable; import com.jcwhatever.bukkit.generic.regions.data.RegionSelection; import com.jcwhatever.bukkit.generic.storage.IDataNode; import com.jcwhatever.bukkit.generic.utils.PreCon; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldUnloadEvent; import org.bukkit.plugin.Plugin; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.WeakHashMap; import javax.annotation.Nullable; /** * Abstract implementation of a region. * * <p>The region is registered with GenericsLib {@link RegionManager} as soon * as it is defined (P1 and P2 coordinates set) via the regions settings or by * calling {@code setCoords} method.</p> * * <p>The regions protected methods {@code onPlayerEnter} and {@code onPlayerLeave} * are only called if the implementing type calls {@code setIsPlayerWatcher(true)}.</p> */ public abstract class Region extends RegionSelection implements IRegion, IDisposable { private static final Map<Region, Void> _instances = new WeakHashMap<>(100); private static BukkitListener _bukkitListener; private final Plugin _plugin; private final String _name; private final String _searchName; private IDataNode _dataNode; private RegionPriority _enterPriority = RegionPriority.DEFAULT; private RegionPriority _leavePriority = RegionPriority.DEFAULT; private boolean _isPlayerWatcher = false; private String _worldName; private UUID _ownerId; private List<Chunk> _chunks; private Map<Object, Object> _meta = new HashMap<Object, Object>(30); private List<IRegionEventHandler> _eventHandlers = new ArrayList<>(10); /** * The priority/order the region is handled by the * region manager in relation to other regions. */ public enum RegionPriority { /** * The last to be handled. */ LAST (4), /** * Low priority. Handled second to last. */ LOW (3), /** * Normal priority. */ DEFAULT (2), /** * High priority. Handled second. */ HIGH (1), /** * Highest priority. Handled first. */ FIRST (0); private final int _order; RegionPriority(int order) { _order = order; } /** * Get a sort order index number. */ public int getSortOrder() { return _order; } } /** * Type of region priority. */ public enum PriorityType { ENTER, LEAVE } /** * Reasons a player enters a region. */ public enum EnterRegionReason { /** * The player moved into the region. */ MOVE, /** * The player teleported into the region. */ TELEPORT, /** * The player respawned into the region. */ RESPAWN, /** * The player joined the server and * spawned into the region. */ JOIN_SERVER } /** * Reasons a player leaves a region. */ public enum LeaveRegionReason { /** * The player moved out of the region. */ MOVE, /** * The player teleported out of the region. */ TELEPORT, /** * The player died in the region. */ DEAD, /** * The player left the server while * in the region. */ QUIT_SERVER } /** * For internal use. */ public enum RegionReason { MOVE (EnterRegionReason.MOVE, LeaveRegionReason.MOVE), DEAD (null, LeaveRegionReason.DEAD), TELEPORT (EnterRegionReason.TELEPORT, LeaveRegionReason.TELEPORT), RESPAWN (EnterRegionReason.RESPAWN, LeaveRegionReason.DEAD), JOIN_SERVER (EnterRegionReason.JOIN_SERVER, null), QUIT_SERVER (null, LeaveRegionReason.QUIT_SERVER); private final EnterRegionReason _enter; private final LeaveRegionReason _leave; RegionReason(EnterRegionReason enter, LeaveRegionReason leave) { _enter = enter; _leave = leave; } /** * Get the enter reason equivalent. */ @Nullable public EnterRegionReason getEnterReason() { return _enter; } /** * Get the leave reason equivalent. */ @Nullable public LeaveRegionReason getLeaveReason() { return _leave; } } /** * Constructor */ public Region(Plugin plugin, String name, @Nullable IDataNode dataNode) { PreCon.notNull(plugin); PreCon.notNullOrEmpty(name); _name = name; _plugin = plugin; _searchName = name.toLowerCase(); _dataNode = dataNode; RegionPriorityInfo info = this.getClass().getAnnotation(RegionPriorityInfo.class); if (info != null) { _enterPriority = info.enter(); _leavePriority = info.leave(); } if (dataNode != null) { loadSettings(dataNode); } _instances.put(this, null); if (_bukkitListener == null) { _bukkitListener = new BukkitListener(); Bukkit.getPluginManager().registerEvents(_bukkitListener, GenericsLib.getLib()); } } /** * Get the name of the region. */ @Override public final String getName() { return _name; } /** * Get the name of the region in lower case. */ @Override public final String getSearchName() { return _searchName; } /** * Get the owning plugin. */ @Override public final Plugin getPlugin() { return _plugin; } /** * Get the regions data node. */ @Nullable public IDataNode getDataNode() { return _dataNode; } /** * Get the regions priority when handling player * entering region. */ @Override public RegionPriority getPriority(PriorityType priorityType) { PreCon.notNull(priorityType); switch (priorityType) { case ENTER: return _enterPriority; case LEAVE: return _leavePriority; default: throw new AssertionError(); } } /** * Get the name of the world the region is in. */ @Nullable public final String getWorldName() { return _worldName; } /** * Determine if the world the region is in is loaded. */ public final boolean isWorldLoaded() { if (!isDefined()) return false; if (getWorld() == null) return false; World world = Bukkit.getWorld(getWorld().getName()); return getWorld().equals(world); } /** * Used to determine if the region subscribes to player events. */ @Override public final boolean isPlayerWatcher() { return _isPlayerWatcher || !_eventHandlers.isEmpty(); } /** * Get the id of the region owner. */ @Override @Nullable public UUID getOwnerId() { return _ownerId; } /** * Determine if the region has an owner. */ @Override public boolean hasOwner() { return _ownerId != null; } /** * Set the regions owner. * * @param ownerId The id of the new owner. */ @Override public boolean setOwner(@Nullable UUID ownerId) { UUID oldId = _ownerId; RegionOwnerChangedEvent event = RegionOwnerChangedEvent.callEvent(new ReadOnlyRegion(this), oldId, ownerId); if (event.isCancelled()) return false; _ownerId = ownerId; IDataNode dataNode = getDataNode(); if (dataNode != null) { dataNode.set("owner-id", ownerId); dataNode.saveAsync(null); } onOwnerChanged(oldId, ownerId); return true; } /** * Set the regions cuboid point coordinates. * * <p>Saves to the regions data node if it has one.</p> * * @param p1 The first point location. * @param p2 The second point location. */ @Override public final void setCoords(Location p1, Location p2) { PreCon.notNull(p1); PreCon.notNull(p2); // unregister while math is updated, // is re-registered after math update (see UpdateMath) GenericsLib.getRegionManager().unregister(this); super.setCoords(p1, p2); updateWorld(); _chunks = null; IDataNode dataNode = getDataNode(); if (dataNode != null) { dataNode.set("p1", getP1()); dataNode.set("p2", getP2()); dataNode.saveAsync(null); } onCoordsChanged(getP1(), getP2()); } /** * Add a transient region event handler. * * @param handler The handler to add. */ @Override public boolean addEventHandler(IRegionEventHandler handler) { PreCon.notNull(handler); boolean isFirstHandler = _eventHandlers.isEmpty(); if (_eventHandlers.add(handler)) { if (isFirstHandler) { // update registration GenericsLib.getRegionManager().register(this); } return true; } return false; } /** * Remove a transient event handler. * * @param handler The handler to remove. */ @Override public boolean removeEventHandler(IRegionEventHandler handler) { PreCon.notNull(handler); if (_eventHandlers.remove(handler)) { if (_eventHandlers.isEmpty()) { // update registration GenericsLib.getRegionManager().register(this); } return true; } return false; } /** * Determine if the region contains the specified material. * * @param material The material to search for. */ @Override public final boolean contains(Material material) { synchronized (_sync) { if (getWorld() == null) return false; int xlen = getXEnd(); int ylen = getYEnd(); int zlen = getZEnd(); for (int x = getXStart(); x <= xlen; x++) { for (int y = getYStart(); y <= ylen; y++) { for (int z = getZStart(); z <= zlen; z++) { Block block = getWorld().getBlockAt(x, y, z); if (block.getType() != material) continue; return true; } } } _sync.notifyAll(); return false; } } /** * Get all locations that have a block of the specified material * within the region. * * @param material The material to search for. */ @Override public final LinkedList<Location> find(Material material) { synchronized (_sync) { LinkedList<Location> results = new LinkedList<>(); if (getWorld() == null) return results; int xlen = getXEnd(); int ylen = getYEnd(); int zlen = getZEnd(); for (int x = getXStart(); x <= xlen; x++) { for (int y = getYStart(); y <= ylen; y++) { for (int z = getZStart(); z <= zlen; z++) { Block block = getWorld().getBlockAt(x, y, z); if (block.getType() != material) continue; results.add(block.getLocation()); } } } _sync.notifyAll(); return results; } } /** * Get all chunks that contain at least a portion of the region. */ @Override public final List<Chunk> getChunks() { if (getWorld() == null) return new ArrayList<>(0); synchronized (_sync) { if (_chunks == null) { if (!isDefined()) { return new ArrayList<>(0); } Chunk c1 = getWorld().getChunkAt(getP1()); Chunk c2 = getWorld().getChunkAt(getP2()); int startX = Math.min(c1.getX(), c2.getX()); int endX = Math.max(c1.getX(), c2.getX()); int startZ = Math.min(c1.getZ(), c2.getZ()); int endZ = Math.max(c1.getZ(), c2.getZ()); ArrayList<Chunk> result = new ArrayList<Chunk>((endX - startX) * (endZ - startZ)); for (int x = startX; x <= endX; x++) { for (int z = startZ; z <= endZ; z++) { result.add(getWorld().getChunkAt(x, z)); } } _chunks = result; } _sync.notifyAll(); return new ArrayList<Chunk>(_chunks); } } /** * Refresh all chunks the region is in. */ @Override public final void refreshChunks() { World world = getWorld(); if (world == null) return; List<Chunk> chunks = getChunks(); for (Chunk chunk : chunks) { world.refreshChunk(chunk.getX(), chunk.getZ()); } } /** * Remove entities from the region. * * @param entityTypes The entity types to remove. */ @Override public final void removeEntities(Class<?>... entityTypes) { synchronized (_sync) { List<Chunk> chunks = getChunks(); for (Chunk chunk : chunks) { for (Entity entity : chunk.getEntities()) { if (this.contains(entity.getLocation())) { if (entityTypes == null || entityTypes.length == 0) { entity.remove(); continue; } for (Class<?> itemType : entityTypes) { if (itemType.isInstance(entity)) { entity.remove(); break; } } } } } _sync.notifyAll(); } } /** * Get a meta object from the region. * * @param key The meta key. * * @param <T> The object type. */ @Override public <T> T getMeta(Object key) { @SuppressWarnings("unchecked") T item = (T)_meta.get(key); return item; } /** * Set a meta object value in the region. * * @param key The meta key. * @param value The meta value. */ @Override public void setMeta(Object key, @Nullable Object value) { if (value == null) { _meta.remove(key); return; } _meta.put(key, value); } /** * Get the class of the region. */ @Override public Class<? extends IRegion> getRegionClass() { return getClass(); } /** * Dispose the region by releasing resources and * un-registering it from the central region manager. */ @Override public final void dispose() { GenericsLib.getRegionManager().unregister(this); _instances.remove(this); onDispose(); } /** * Set the value of the player watcher flag and update * the regions registration with the central region manager. * * @param isPlayerWatcher True to allow player enter and leave events. */ protected void setIsPlayerWatcher(boolean isPlayerWatcher) { if (isPlayerWatcher != _isPlayerWatcher) { _isPlayerWatcher = isPlayerWatcher; GenericsLib.getRegionManager().register(this); } } /** * Causes the onPlayerEnter method to re-fire * if the player is already in the region. * . * @param p The player to reset. */ protected void resetContainsPlayer(Player p) { GenericsLib.getRegionManager().resetPlayerRegion(p, this); } /** * Initializes region coordinates without saving to the data node. * * @param p1 The first point location. * @param p2 The second point location. */ protected final void initCoords(@Nullable Location p1, @Nullable Location p2) { setPoint(RegionPoint.P1, p1); setPoint(RegionPoint.P2, p2); updateWorld(); updateMath(); } /** * Initial load of settings from regions data node. * * @param dataNode The data node to load from */ protected void loadSettings(final IDataNode dataNode) { Location p1 = dataNode.getLocation("p1"); Location p2 = dataNode.getLocation("p2"); initCoords(p1, p2); _ownerId = dataNode.getUUID("owner-id"); _enterPriority = dataNode.getEnum("region-enter-priority", _enterPriority, RegionPriority.class); _leavePriority = dataNode.getEnum("region-leave-priority", _leavePriority, RegionPriority.class); } /* * Update region math variables */ @Override protected void updateMath() { super.updateMath(); GenericsLib.getRegionManager().register(this); } /** * Called when the coordinates for the region are changed * * <p>Intended for implementation use.</p> * * @param p1 The first point location. * @param p2 The second point location. * * @throws IOException */ protected void onCoordsChanged(@Nullable Location p1, @Nullable Location p2) { // do nothing } /** * Called when a player enters the region, * but only if the region is a player watcher and * canDoPlayerEnter() returns true. * * <p>Intended for implementation use.</p> * * @param p the player entering the region. */ protected void onPlayerEnter (@SuppressWarnings("unused") Player p, @SuppressWarnings("unused") EnterRegionReason reason) { // do nothing } /** * Called when a player leaves the region, * but only if the region is a player watcher and * canDoPlayerLeave() returns true. * * <p>Intended for implementation use.</p> * * @param p the player leaving the region. */ protected void onPlayerLeave (@SuppressWarnings("unused") Player p, @SuppressWarnings("unused") LeaveRegionReason reason) { // do nothing } /** * Called to determine if {@code onPlayerEnter} * can be called on the specified player. * * <p>Intended for override if needed.</p> * * @param p The player entering the region. */ protected boolean canDoPlayerEnter(@SuppressWarnings("unused") Player p, @SuppressWarnings("unused") EnterRegionReason reason) { return true; } /** * Called to determine if {@code onPlayerLeave} * can be called on the specified player. * * <p>Intended for override if needed.</p> * * @param p The player leaving the region. */ protected boolean canDoPlayerLeave(@SuppressWarnings("unused") Player p, @SuppressWarnings("unused") LeaveRegionReason reason) { return true; } /** * Called when the owner of the region is changed. * * <p>Intended for implementation use.</p> * * @param oldOwnerId The id of the previous owner of the region. * @param newOwnerId The id of the new owner of the region. */ protected void onOwnerChanged(@SuppressWarnings("unused") @Nullable UUID oldOwnerId, @SuppressWarnings("unused") @Nullable UUID newOwnerId) { // do nothing } /** * Called when the region is disposed. */ protected void onDispose() { // do nothings } /** * Used by RegionEventManager to execute onPlayerEnter event. */ void doPlayerEnter (Player p, EnterRegionReason reason) { if (canDoPlayerEnter(p, reason)) onPlayerEnter(p, reason); for (IRegionEventHandler handler : _eventHandlers) { if (handler.canDoPlayerEnter(p, reason)) { handler.onPlayerEnter(p, reason); } } } /** * Used by RegionEventManager to execute onPlayerLeave event. */ void doPlayerLeave (Player p, LeaveRegionReason reason) { if (canDoPlayerLeave(p, reason)) onPlayerLeave(p, reason); for (IRegionEventHandler handler : _eventHandlers) { if (handler.canDoPlayerLeave(p, reason)) { handler.onPlayerLeave(p, reason); } } } /* * Update world name if possible */ private void updateWorld() { Location p1 = getP1(); Location p2 = getP2(); if (p1 == null || p2 == null) { _worldName = null; return; } World p1World = p1.getWorld(); World p2World = p2.getWorld(); boolean isWorldsMismatched = p1World != null && !p1World.equals(p2World) || p2World != null && !p2World.equals(p1World); if (isWorldsMismatched) { throw new IllegalArgumentException("Both region points must be from the same world."); } if (p1World != null) { _worldName = p1World.getName(); } else { IDataNode dataNode = getDataNode(); if (dataNode != null) { _worldName = dataNode.getLocationWorldName("p1"); } } } @Override public int hashCode() { return _name.hashCode(); } @Override public boolean equals(Object obj) { synchronized (_sync) { if (obj instanceof Region) { Region region = (Region)obj; return region == this; } _sync.notifyAll(); return false; } } /* * Listens for world unload and load events and handles * regions in the world appropriately. */ private static class BukkitListener implements Listener { @EventHandler private void onWorldLoad(WorldLoadEvent event) { String worldName = event.getWorld().getName(); for (Region region : _instances.keySet()) { if (region.isDefined() && worldName.equals(region.getWorldName())) { // fix locations //noinspection ConstantConditions region.getP1().setWorld(event.getWorld()); //noinspection ConstantConditions region.getP2().setWorld(event.getWorld()); } } } @EventHandler private void onWorldUnload(WorldUnloadEvent event) { String worldName = event.getWorld().getName(); for (Region region : _instances.keySet()) { if (region.isDefined() && worldName.equals(region.getWorldName())) { // remove world from locations, helps garbage collector //noinspection ConstantConditions region.getP1().setWorld(null); //noinspection ConstantConditions region.getP2().setWorld(null); region._chunks = null; } } } } }
fix comment
src/com/jcwhatever/bukkit/generic/regions/Region.java
fix comment
<ide><path>rc/com/jcwhatever/bukkit/generic/regions/Region.java <ide> * <ide> * @throws IOException <ide> */ <del> protected void onCoordsChanged(@Nullable Location p1, @Nullable Location p2) { <add> protected void onCoordsChanged(@SuppressWarnings("unused") @Nullable Location p1, <add> @SuppressWarnings("unused") @Nullable Location p2) { <ide> // do nothing <ide> } <ide> <ide> } <ide> <ide> /** <del> * Used by RegionEventManager to execute onPlayerEnter event. <add> * Used by {@code RegionManager} to execute onPlayerEnter event. <ide> */ <ide> void doPlayerEnter (Player p, EnterRegionReason reason) { <ide> <ide> } <ide> <ide> /** <del> * Used by RegionEventManager to execute onPlayerLeave event. <add> * Used by {@code RegionManager} to execute onPlayerLeave event. <ide> */ <ide> void doPlayerLeave (Player p, LeaveRegionReason reason) { <ide>
Java
apache-2.0
517e072b29f37ef4957943606936e90870e9d14a
0
surevine/buddycloud-server-java,surevine/buddycloud-server-java,webhost/buddycloud-server-java,ashward/buddycloud-server-java,webhost/buddycloud-server-java,ashward/buddycloud-server-java,enom/buddycloud-server-java,enom/buddycloud-server-java,buddycloud/buddycloud-server-java,buddycloud/buddycloud-server-java
package org.buddycloud.channelserver.queue; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import junit.framework.Assert; import org.buddycloud.channelserver.ChannelsEngine; import org.buddycloud.channelserver.channel.ChannelManager; import org.buddycloud.channelserver.packetHandler.iq.IQTestHandler; import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.JabberPubsub; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; import org.xmpp.packet.IQ; import org.xmpp.packet.JID; import org.xmpp.packet.Packet; import org.xmpp.packet.PacketError; import org.buddycloud.channelserver.channel.ChannelsEngineMock; import org.dom4j.Element; import org.dom4j.tree.DefaultElement; public class FederatedQueueManagerTest extends IQTestHandler { private FederatedQueueManager queueManager; private BlockingQueue<Packet> queue = new LinkedBlockingQueue<Packet>(); private ChannelManager channelManager; private ChannelsEngineMock channelsEngine; private String localServer = "channels.shakespeare.lit"; @Before public void setUp() throws Exception { channelsEngine = new ChannelsEngineMock(); channelManager = Mockito.mock(ChannelManager.class); queueManager = new FederatedQueueManager(channelsEngine, localServer); } @Test(expected = UnknownFederatedPacketException.class) public void testAttemptingToForwardNonExistantFederatedPacketThrowsException() throws Exception { IQ packet = new IQ(); packet.setID("1"); queueManager.passResponseToRequester(packet); } @Test public void testUnDiscoveredServerSpawnsDiscoItemsRequest() throws Exception { IQ packet = new IQ(); packet.setID("1"); packet.setFrom(new JID("[email protected]/street")); packet.setTo(new JID("capulet.lit")); packet.setType(IQ.Type.get); queueManager.process(packet); Assert.assertEquals(1, channelsEngine.size()); Packet outgoingPacket = channelsEngine.poll(); Assert.assertEquals(localServer, outgoingPacket.getElement() .attributeValue("from")); Assert.assertEquals(JabberPubsub.NS_DISCO_ITEMS, outgoingPacket .getElement().element("query").getNamespace().getStringValue()); } @Test public void testResponseToDiscoItemsRequestResultsInDiscoInfoRequests() throws Exception { Element item = new DefaultElement("item"); item.addAttribute("jid", "channels.capulet.lit"); ArrayList<Element> items = new ArrayList<Element>(); items.add(item); queueManager.processDiscoItemsResponse(new JID("capulet.lit"), items); Assert.assertEquals(1, channelsEngine.size()); Packet discoInfoRequest = channelsEngine.poll(); Assert.assertEquals(localServer, discoInfoRequest.getElement() .attributeValue("from")); Assert.assertEquals("channels.capulet.lit", discoInfoRequest .getElement().attributeValue("to")); Assert.assertEquals(JabberPubsub.NS_DISCO_INFO, discoInfoRequest .getElement().element("query").getNamespace().getStringValue()); } @Test public void testNotProvidingChannelServerInItemsResponseResultsInErrorStanazaReturn() throws Exception { // Attempt to send stanza IQ packet = new IQ(); packet.setID("1:some-request"); packet.setFrom(new JID("[email protected]/street")); packet.setTo(new JID("capulet.lit")); packet.setType(IQ.Type.get); queueManager.process(packet); // Disco#items fired, passing in items list Element item = new DefaultElement("item"); item.addAttribute("jid", "channels.capulet.lit"); ArrayList<Element> items = new ArrayList<Element>(); items.add(item); queueManager.processDiscoItemsResponse(new JID("capulet.lit"), items); channelsEngine.poll(); // Response to disco#info with no identities queueManager.processDiscoInfoResponse(new JID("channels.capulter.lit"), channelsEngine.poll().getID(), new ArrayList<Element>()); // Expect error response to original packet IQ errorResponse = (IQ) channelsEngine.poll(); Assert.assertEquals(packet.getID(), errorResponse.getID()); Assert.assertEquals(IQ.Type.error, errorResponse.getType()); Assert.assertEquals(localServer, errorResponse.getFrom().toString()); Assert.assertEquals(PacketError.Type.cancel.toXMPP(), errorResponse .getElement().element("error").attributeValue("type")); Assert.assertEquals( PacketError.Condition.item_not_found.toXMPP(), errorResponse.getElement().element("error") .element("item-not-found").getName()); Assert.assertEquals( "No pubsub channel service discovered for capulet.lit", errorResponse.getElement().element("error").elementText("text")); } @Test public void testPassingChannelServerIdentifierViaItemsResultsInQueuedPacketSending() throws Exception { // Attempt to send stanza IQ packet = new IQ(); packet.setID("1:some-request"); packet.setFrom(new JID("[email protected]/street")); packet.setTo(new JID("topics.capulet.lit")); packet.setType(IQ.Type.get); queueManager.process(packet); channelsEngine.poll(); // Pass in items with name="buddycloud-server" Element item = new DefaultElement("item"); item.addAttribute("jid", "channels.capulet.lit"); item.addAttribute("name", "buddycloud-server"); ArrayList<Element> items = new ArrayList<Element>(); items.add(item); queueManager.processDiscoItemsResponse(new JID("topics.capulet.lit"), items); // Note original packet now sent with remote channel server tag Packet originalPacketRedirected = channelsEngine.poll(); Packet expectedForwaredPacket = packet.createCopy(); expectedForwaredPacket.setFrom(new JID(localServer)); expectedForwaredPacket.setTo(new JID("channels.capulet.lit")); Assert.assertEquals(expectedForwaredPacket.toXML(), originalPacketRedirected.toXML()); } @Test public void testOutgoingFederatedPacketsAreRoutedBackToOriginalSender() throws Exception { channelsEngine.clear(); IQ packet = new IQ(); packet.setID("1:some-request"); packet.setFrom(new JID("[email protected]/street")); packet.setTo(new JID("topics.capulet.lit")); packet.setType(IQ.Type.get); packet.getElement().addAttribute("remote-server-discover", "false"); queueManager.process(packet.createCopy()); IQ originalPacketRedirected = (IQ) channelsEngine.poll(); IQ response = IQ.createResultIQ(originalPacketRedirected); queueManager.passResponseToRequester(response); Assert.assertEquals(1, channelsEngine.size()); Packet redirected = channelsEngine.poll(); Assert.assertEquals(packet.getFrom(), redirected.getTo()); } @Test public void testOutgoingFederatedPacketsFromDifferentClientsUsingSameIdAreRoutedBackToOriginalSender() throws Exception { channelsEngine.clear(); IQ clientOnePacket = new IQ(); clientOnePacket.setID("1:some-request"); clientOnePacket.setFrom(new JID("[email protected]/street")); clientOnePacket.setTo(new JID("topics.capulet.lit")); clientOnePacket.setType(IQ.Type.get); clientOnePacket.getElement().addAttribute("remote-server-discover", "false"); IQ clientTwoPacket = new IQ(); clientTwoPacket.setID("1:some-request"); clientTwoPacket.setFrom(new JID("[email protected]/street")); clientTwoPacket.setTo(new JID("topics.capulet.lit")); clientTwoPacket.setType(IQ.Type.get); clientTwoPacket.getElement().addAttribute("remote-server-discover", "false"); queueManager.addChannelMap(new JID("topics.capulet.lit")); queueManager.process(clientOnePacket.createCopy()); queueManager.process(clientTwoPacket.createCopy()); IQ clientOneOriginalPacketRedirected = (IQ) channelsEngine.poll(); IQ clientTwoOriginalPacketRedirected = (IQ) channelsEngine.poll(); IQ clientOneResponse = IQ.createResultIQ(clientOneOriginalPacketRedirected); queueManager.passResponseToRequester(clientOneResponse); IQ clientTwoResponse = IQ.createResultIQ(clientTwoOriginalPacketRedirected); queueManager.passResponseToRequester(clientTwoResponse); Assert.assertEquals(2, channelsEngine.size()); Packet clientOneRedirected = channelsEngine.poll(); Packet clientTwoRedirected = channelsEngine.poll(); Assert.assertEquals(clientOnePacket.getFrom(), clientOneRedirected.getTo()); Assert.assertEquals(clientTwoPacket.getFrom(), clientTwoRedirected.getTo()); } @Test public void testOutgoingIqPacketsGetIdMapped() throws Exception { channelsEngine.clear(); String originalId = "id:12345"; IQ packet = new IQ(); packet.setFrom(new JID("[email protected]/street")); packet.setTo(new JID("topics.capulet.lit")); packet.setType(IQ.Type.get); packet.setID(originalId); packet.getElement().addAttribute("remote-server-discover", "false"); queueManager.addChannelMap(new JID("topics.capulet.lit")); queueManager.process(packet.createCopy()); IQ packetExternal = (IQ) channelsEngine.poll(); Assert.assertFalse(originalId.equals(packetExternal.getID())); IQ response = IQ.createResultIQ(packetExternal); queueManager.passResponseToRequester(response); IQ packetInternal = (IQ) channelsEngine.poll(); Assert.assertTrue(originalId.equals(packetInternal.getID())); } }
src/test/java/org/buddycloud/channelserver/queue/FederatedQueueManagerTest.java
package org.buddycloud.channelserver.queue; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import junit.framework.Assert; import org.buddycloud.channelserver.ChannelsEngine; import org.buddycloud.channelserver.channel.ChannelManager; import org.buddycloud.channelserver.packetHandler.iq.IQTestHandler; import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.JabberPubsub; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; import org.xmpp.packet.IQ; import org.xmpp.packet.JID; import org.xmpp.packet.Packet; import org.xmpp.packet.PacketError; import org.buddycloud.channelserver.channel.ChannelsEngineMock; import org.dom4j.Element; import org.dom4j.tree.DefaultElement; public class FederatedQueueManagerTest extends IQTestHandler { private FederatedQueueManager queueManager; private BlockingQueue<Packet> queue = new LinkedBlockingQueue<Packet>(); private ChannelManager channelManager; private ChannelsEngineMock channelsEngine; private String localServer = "channels.shakespeare.lit"; @Before public void setUp() throws Exception { channelsEngine = new ChannelsEngineMock(); channelManager = Mockito.mock(ChannelManager.class); queueManager = new FederatedQueueManager(channelsEngine, localServer); } @Test(expected = UnknownFederatedPacketException.class) public void testAttemptingToForwardNonExistantFederatedPacketThrowsException() throws Exception { IQ packet = new IQ(); packet.setID("1"); queueManager.passResponseToRequester(packet); } @Test public void testUnDiscoveredServerSpawnsDiscoItemsRequest() throws Exception { IQ packet = new IQ(); packet.setID("1"); packet.setFrom(new JID("[email protected]/street")); packet.setTo(new JID("capulet.lit")); packet.setType(IQ.Type.get); queueManager.process(packet); Assert.assertEquals(1, channelsEngine.size()); Packet outgoingPacket = channelsEngine.poll(); Assert.assertEquals(localServer, outgoingPacket.getElement() .attributeValue("from")); Assert.assertEquals(JabberPubsub.NS_DISCO_ITEMS, outgoingPacket .getElement().element("query").getNamespace().getStringValue()); } @Test public void testResponseToDiscoItemsRequestResultsInDiscoInfoRequests() throws Exception { Element item = new DefaultElement("item"); item.addAttribute("jid", "channels.capulet.lit"); ArrayList<Element> items = new ArrayList<Element>(); items.add(item); queueManager.processDiscoItemsResponse(new JID("capulet.lit"), items); Assert.assertEquals(1, channelsEngine.size()); Packet discoInfoRequest = channelsEngine.poll(); Assert.assertEquals(localServer, discoInfoRequest.getElement() .attributeValue("from")); Assert.assertEquals("channels.capulet.lit", discoInfoRequest .getElement().attributeValue("to")); Assert.assertEquals(JabberPubsub.NS_DISCO_INFO, discoInfoRequest .getElement().element("query").getNamespace().getStringValue()); } @Test public void testNotProvidingChannelServerInItemsResponseResultsInErrorStanazaReturn() throws Exception { // Attempt to send stanza IQ packet = new IQ(); packet.setID("1:some-request"); packet.setFrom(new JID("[email protected]/street")); packet.setTo(new JID("capulet.lit")); packet.setType(IQ.Type.get); queueManager.process(packet); // Disco#items fired, passing in items list Element item = new DefaultElement("item"); item.addAttribute("jid", "channels.capulet.lit"); ArrayList<Element> items = new ArrayList<Element>(); items.add(item); queueManager.processDiscoItemsResponse(new JID("capulet.lit"), items); channelsEngine.poll(); // Response to disco#info with no identities queueManager.processDiscoInfoResponse(new JID("channels.capulter.lit"), channelsEngine.poll().getID(), new ArrayList<Element>()); // Expect error response to original packet IQ errorResponse = (IQ) channelsEngine.poll(); Assert.assertEquals(packet.getID(), errorResponse.getID()); Assert.assertEquals(IQ.Type.error, errorResponse.getType()); Assert.assertEquals(localServer, errorResponse.getFrom().toString()); Assert.assertEquals(PacketError.Type.cancel.toXMPP(), errorResponse .getElement().element("error").attributeValue("type")); Assert.assertEquals( PacketError.Condition.item_not_found.toXMPP(), errorResponse.getElement().element("error") .element("item-not-found").getName()); Assert.assertEquals( "No pubsub channel service discovered for capulet.lit", errorResponse.getElement().element("error").elementText("text")); } @Test public void testPassingChannelServerIdentifierViaItemsResultsInQueuedPacketSending() throws Exception { // Attempt to send stanza IQ packet = new IQ(); packet.setID("1:some-request"); packet.setFrom(new JID("[email protected]/street")); packet.setTo(new JID("topics.capulet.lit")); packet.setType(IQ.Type.get); queueManager.process(packet); channelsEngine.poll(); // Pass in items with name="buddycloud-server" Element item = new DefaultElement("item"); item.addAttribute("jid", "channels.capulet.lit"); item.addAttribute("name", "buddycloud-server"); ArrayList<Element> items = new ArrayList<Element>(); items.add(item); queueManager.processDiscoItemsResponse(new JID("topics.capulet.lit"), items); // Note original packet now sent with remote channel server tag Packet originalPacketRedirected = channelsEngine.poll(); Packet expectedForwaredPacket = packet.createCopy(); expectedForwaredPacket.setFrom(new JID(localServer)); expectedForwaredPacket.setTo(new JID("channels.capulet.lit")); Assert.assertEquals(expectedForwaredPacket.toXML(), originalPacketRedirected.toXML()); } @Test public void testOutgoingFederatedPacketsAreRoutedBackToOriginalSender() throws Exception { channelsEngine.clear(); IQ packet = new IQ(); packet.setID("1:some-request"); packet.setFrom(new JID("[email protected]/street")); packet.setTo(new JID("topics.capulet.lit")); packet.setType(IQ.Type.get); packet.getElement().addAttribute("remote-server-discover", "false"); queueManager.process(packet.createCopy()); IQ originalPacketRedirected = (IQ) channelsEngine.poll(); IQ response = IQ.createResultIQ(originalPacketRedirected); queueManager.passResponseToRequester(response); Assert.assertEquals(1, channelsEngine.size()); Packet redirected = channelsEngine.poll(); System.out.println(packet); System.out.println(redirected); Assert.assertEquals(packet.getFrom(), redirected.getTo()); } @Test public void testOutgoingFederatedPacketsFromDifferentClientsUsingSameIdAreRoutedBackToOriginalSender() throws Exception { channelsEngine.clear(); IQ clientOnePacket = new IQ(); clientOnePacket.setID("1:some-request"); clientOnePacket.setFrom(new JID("[email protected]/street")); clientOnePacket.setTo(new JID("topics.capulet.lit")); clientOnePacket.setType(IQ.Type.get); clientOnePacket.getElement().addAttribute("remote-server-discover", "false"); IQ clientTwoPacket = new IQ(); clientTwoPacket.setID("1:some-request"); clientTwoPacket.setFrom(new JID("[email protected]/street")); clientTwoPacket.setTo(new JID("topics.capulet.lit")); clientTwoPacket.setType(IQ.Type.get); clientTwoPacket.getElement().addAttribute("remote-server-discover", "false"); queueManager.addChannelMap(new JID("topics.capulet.lit")); queueManager.process(clientOnePacket.createCopy()); queueManager.process(clientTwoPacket.createCopy()); IQ clientOneOriginalPacketRedirected = (IQ) channelsEngine.poll(); IQ clientTwoOriginalPacketRedirected = (IQ) channelsEngine.poll(); IQ clientOneResponse = IQ.createResultIQ(clientOneOriginalPacketRedirected); queueManager.passResponseToRequester(clientOneResponse); IQ clientTwoResponse = IQ.createResultIQ(clientTwoOriginalPacketRedirected); queueManager.passResponseToRequester(clientTwoResponse); Assert.assertEquals(2, channelsEngine.size()); Packet clientOneRedirected = channelsEngine.poll(); Packet clientTwoRedirected = channelsEngine.poll(); Assert.assertEquals(clientOnePacket.getFrom(), clientOneRedirected.getTo()); Assert.assertEquals(clientTwoPacket.getFrom(), clientTwoRedirected.getTo()); } }
Add test for outgoing packet remapping
src/test/java/org/buddycloud/channelserver/queue/FederatedQueueManagerTest.java
Add test for outgoing packet remapping
<ide><path>rc/test/java/org/buddycloud/channelserver/queue/FederatedQueueManagerTest.java <ide> Assert.assertEquals(1, channelsEngine.size()); <ide> Packet redirected = channelsEngine.poll(); <ide> <del> System.out.println(packet); <del> System.out.println(redirected); <del> <ide> Assert.assertEquals(packet.getFrom(), redirected.getTo()); <ide> } <ide> <ide> Assert.assertEquals(clientOnePacket.getFrom(), clientOneRedirected.getTo()); <ide> Assert.assertEquals(clientTwoPacket.getFrom(), clientTwoRedirected.getTo()); <ide> } <add> <add> @Test <add> public void testOutgoingIqPacketsGetIdMapped() throws Exception { <add> channelsEngine.clear(); <add> <add> String originalId = "id:12345"; <add> IQ packet = new IQ(); <add> packet.setFrom(new JID("[email protected]/street")); <add> packet.setTo(new JID("topics.capulet.lit")); <add> packet.setType(IQ.Type.get); <add> packet.setID(originalId); <add> packet.getElement().addAttribute("remote-server-discover", "false"); <add> <add> queueManager.addChannelMap(new JID("topics.capulet.lit")); <add> <add> queueManager.process(packet.createCopy()); <add> <add> IQ packetExternal = (IQ) channelsEngine.poll(); <add> <add> Assert.assertFalse(originalId.equals(packetExternal.getID())); <add> <add> IQ response = IQ.createResultIQ(packetExternal); <add> queueManager.passResponseToRequester(response); <add> <add> IQ packetInternal = (IQ) channelsEngine.poll(); <add> <add> Assert.assertTrue(originalId.equals(packetInternal.getID())); <add> } <add> <ide> }
Java
agpl-3.0
9c164b10f5f784ea40c6695b51373a5003268f6c
0
Stanwar/agreementmaker,sabarish14/agreementmaker,sabarish14/agreementmaker,sabarish14/agreementmaker,Stanwar/agreementmaker,Stanwar/agreementmaker,Stanwar/agreementmaker,sabarish14/agreementmaker
package am.app.mappingEngine.oaei2009; import java.rmi.RemoteException; import am.Utility; import am.app.Core; import am.app.mappingEngine.AbstractMatcher; import am.app.mappingEngine.AbstractMatcherParametersPanel; import am.app.mappingEngine.MatcherFactory; import am.app.mappingEngine.MatchersRegistry; import am.app.mappingEngine.Combination.CombinationParameters; import am.app.mappingEngine.PRAMatcher.PRAMatcher2; import am.app.mappingEngine.baseSimilarity.BaseSimilarityParameters; import am.app.mappingEngine.dsi.DescendantsSimilarityInheritanceParameters; import am.app.mappingEngine.multiWords.MultiWordsParameters; import am.app.mappingEngine.parametricStringMatcher.ParametricStringParameters; import am.app.mappingEngine.referenceAlignment.ReferenceAlignmentMatcher; import am.app.mappingEngine.referenceAlignment.ReferenceAlignmentParameters; //import uk.ac.shef.wit.simmetrics.similaritymetrics.*; //all sim metrics are in here public class OAEI2009matcher extends AbstractMatcher { //private Normalizer normalizer; public OAEI2009matcher() { // warning, param is not available at the time of the constructor super(); needsParam = true; param = new OAEI2009parameters(); } public String getDescriptionString() { return "The method adopted in the OAEI2009 competition." + "For more details, please read OAEI2009 results for the AgreementMaker available at www.cs.uic.edu/Cruz/Publications#2009. "+ "The configurations for the difference tracks are selected in the parameters panel. "; } /* ******************************************************************************************************* ************************ Init structures************************************* * ******************************************************************************************************* */ public void beforeAlignOperations() throws Exception{ super.beforeAlignOperations(); //OAEI2009parameters parameters =(OAEI2009parameters)param; } /* ******************************************************************************************************* ************************ Algorithm functions beyond this point************************************* * ******************************************************************************************************* */ public void match() throws Exception { matchStart(); long measure = 1000000; AbstractMatcher lastLayer; OAEI2009parameters parameters = (OAEI2009parameters)param; //FIRST LAYER: BSM PSM and VMM //BSM long startime = 0, endtime = 0, time = 0; AbstractMatcher pra = null; if( parameters.trackName == OAEI2009parameters.ANATOMY_PRA ) { // We are running anatomy with PRA. Run PRA instead of BSM. //AbstractMatcher refAlign = MatcherFactory.getMatcherInstance(MatchersRegistry.ImportAlignment, 0); Core core = Core.getInstance(); ReferenceAlignmentMatcher myMatcher = (ReferenceAlignmentMatcher)core.getMatcherInstance( MatchersRegistry.ImportAlignment ); if( myMatcher == null ) { // we are running from the command line, we have to load the partial reference file. ReferenceAlignmentParameters par = new ReferenceAlignmentParameters(); par.fileName = parameters.partialReferenceFile; par.format = parameters.format; ReferenceAlignmentMatcher refAlign = (ReferenceAlignmentMatcher) MatcherFactory.getMatcherInstance(MatchersRegistry.ImportAlignment, 0); refAlign.setParam(par); refAlign.match(); myMatcher = refAlign; } System.out.println("Running PRA."); startime = System.nanoTime()/measure; //AbstractMatcher pra = MatcherFactory.getMatcherInstance(MatchersRegistry.BaseSimilarity, 0); pra = MatcherFactory.getMatcherInstance(MatchersRegistry.PRAMatcher, 0); pra.getInputMatchers().add(myMatcher); pra.setThreshold(threshold); pra.setMaxSourceAlign(maxSourceAlign); pra.setMaxTargetAlign(maxTargetAlign); BaseSimilarityParameters bsmp = new BaseSimilarityParameters(); bsmp.initForOAEI2009(); pra.setParam(bsmp); pra.setSourceOntology(sourceOntology); pra.setTargetOntology(targetOntology); //bsm.setPerformSelection(false); pra.match(); endtime = System.nanoTime()/measure; time = (endtime-startime); System.out.println("PRAMatcher completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); } else { // We are NOT running Anatomy with PRA. Run BSM. System.out.println("Running BSM"); startime = System.nanoTime()/measure; pra = MatcherFactory.getMatcherInstance(MatchersRegistry.BaseSimilarity, 0); pra.setThreshold(threshold); pra.setMaxSourceAlign(maxSourceAlign); pra.setMaxTargetAlign(maxTargetAlign); BaseSimilarityParameters bsmp = new BaseSimilarityParameters(); bsmp.initForOAEI2009(); pra.setParam(bsmp); pra.setSourceOntology(sourceOntology); pra.setTargetOntology(targetOntology); //bsm.setPerformSelection(false); pra.match(); endtime = System.nanoTime()/measure; time = (endtime-startime); System.out.println("BSM completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); } //PSM System.out.println("Running PSM"); startime = System.nanoTime()/measure; AbstractMatcher psm = MatcherFactory.getMatcherInstance(MatchersRegistry.ParametricString, 1); psm.setThreshold(threshold); psm.setMaxSourceAlign(maxSourceAlign); psm.setMaxTargetAlign(maxTargetAlign); ParametricStringParameters psmp = new ParametricStringParameters(); psmp.initForOAEI2009(); psm.setParam(psmp); psm.setSourceOntology(sourceOntology); psm.setSourceOntology(targetOntology); //psm.setPerformSelection(false); psm.match(); endtime = System.nanoTime()/measure; time = (endtime-startime); System.out.println("PSM completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); //vmm System.out.println("Running VMM"); startime = System.nanoTime()/measure; AbstractMatcher vmm = MatcherFactory.getMatcherInstance(MatchersRegistry.MultiWords, 2); vmm.setThreshold(threshold); vmm.setMaxSourceAlign(maxSourceAlign); vmm.setMaxTargetAlign(maxTargetAlign); MultiWordsParameters vmmp = new MultiWordsParameters(); vmmp.initForOAEI2009(); vmm.setParam(vmmp); vmm.setSourceOntology(sourceOntology); vmm.setTargetOntology(targetOntology); //vmm.setPerformSelection(false); vmm.match(); endtime = System.nanoTime()/measure; time = (endtime-startime); System.out.println("VMM completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); //Second layer: LWC(VMM, PSM, BSM) //LWC matcher System.out.println("Running LWC"); startime = System.nanoTime()/measure; AbstractMatcher lwc = MatcherFactory.getMatcherInstance(MatchersRegistry.Combination, 3); lwc.getInputMatchers().add(psm); lwc.getInputMatchers().add(vmm); lwc.getInputMatchers().add(pra); lwc.setThreshold(threshold); lwc.setMaxSourceAlign(maxSourceAlign); lwc.setMaxTargetAlign(maxTargetAlign); CombinationParameters lwcp = new CombinationParameters(); lwcp.initForOAEI2009(); lwc.setParam(lwcp); lwc.setSourceOntology(sourceOntology); lwc.setTargetOntology(targetOntology); //lwc.setPerformSelection(false); lwc.match(); endtime = System.nanoTime()/measure; time = (endtime-startime); System.out.println("LWC completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); lastLayer = lwc; //Forth or fifth layer: DSI //DSI System.out.println("Running DSI"); startime = System.nanoTime()/measure; AbstractMatcher dsi = MatcherFactory.getMatcherInstance(MatchersRegistry.DSI, 0); dsi.getInputMatchers().add(lastLayer); dsi.setThreshold(threshold); dsi.setMaxSourceAlign(maxSourceAlign); dsi.setMaxTargetAlign(maxTargetAlign); DescendantsSimilarityInheritanceParameters dsip = new DescendantsSimilarityInheritanceParameters(); dsip.initForOAEI2009(); dsi.setParam(dsip); dsi.setSourceOntology(sourceOntology); dsi.setTargetOntology(targetOntology); //dsi.setPerformSelection(true); dsi.match(); endtime = System.nanoTime()/measure; time = (endtime-startime); System.out.println("DSI completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); lastLayer = dsi; if(parameters.useWordNet){ //third layer wnl on input LWC (optimized mode) System.out.println("Running LexicalWordnet"); startime = System.nanoTime()/measure; AbstractMatcher wnl = MatcherFactory.getMatcherInstance(MatchersRegistry.WordNetLexical, 2); wnl.setOptimized(true); wnl.addInputMatcher(lastLayer); wnl.setThreshold(threshold); wnl.setMaxSourceAlign(maxSourceAlign); wnl.setMaxTargetAlign(maxTargetAlign); wnl.setSourceOntology(sourceOntology); wnl.setTargetOntology(targetOntology); wnl.match(); endtime = System.nanoTime()/measure; time = (endtime-startime); System.out.println("WNL completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); lastLayer = wnl; } if(parameters.useUMLS){ /* * COMMENTED OUT IN ORDER TO COMPUTE THE JAR FILE WITHOUT THE KSS LIBRARY //Run UMLS matcher on unmapped nodes. System.out.println("Running UMLS"); try{ startime = System.nanoTime()/measure; AbstractMatcher umls = MatcherFactory.getMatcherInstance(MatchersRegistry.UMLSKSLexical, 4); umls.setOptimized(true); umls.getInputMatchers().add(lastLayer); umls.setThreshold(threshold); umls.setMaxSourceAlign(maxSourceAlign); umls.setMaxTargetAlign(maxTargetAlign); //umls.initForOAEI2009(); umls.match(); time = (endtime-startime); System.out.println("UMLS completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); lastLayer = umls; } catch(RemoteException e){ e.printStackTrace(); System.out.println("Impossible to connect to the UMLS server. The ip address has to be registered at http://kscas-lhc.nlm.nih.gov/UMLSKS"); } */ } System.out.println("name: "+parameters.partialReferenceFile); System.out.println("format: "+parameters.format); if( parameters.trackName == OAEI2009parameters.ANATOMY_PRI ){ startime = System.nanoTime()/measure; AbstractMatcher praIntegration = MatcherFactory.getMatcherInstance(MatchersRegistry.PRAintegration, 0); praIntegration.getInputMatchers().add(lastLayer); praIntegration.setThreshold(threshold); praIntegration.setMaxSourceAlign(maxSourceAlign); praIntegration.setMaxTargetAlign(maxTargetAlign); //praIntegration uses the same parameters of ReferenceAlignmentMatcher ReferenceAlignmentParameters par = new ReferenceAlignmentParameters(); par.fileName = parameters.partialReferenceFile; par.format = parameters.format; praIntegration.setParam(par); praIntegration.setSourceOntology(sourceOntology); praIntegration.setTargetOntology(targetOntology); //umls.initForOAEI2009(); praIntegration.match(); time = (endtime-startime); System.out.println("PRA integration completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); lastLayer = praIntegration; } else if( parameters.trackName == OAEI2009parameters.ANATOMY_PRA ) { PRAMatcher2 pra2 = (PRAMatcher2) MatcherFactory.getMatcherInstance(MatchersRegistry.PRAMatcher2, 0); pra2.addInputMatcher(lastLayer); pra2.addInputMatcher(pra); pra2.setThreshold(threshold); pra2.setMaxSourceAlign(maxSourceAlign); pra2.setMaxTargetAlign(maxTargetAlign); pra2.setSourceOntology(sourceOntology); pra2.setTargetOntology(targetOntology); pra2.match(); lastLayer = pra2; } classesMatrix = lastLayer.getClassesMatrix(); propertiesMatrix = lastLayer.getPropertiesMatrix(); classesAlignmentSet = lastLayer.getClassAlignmentSet(); propertiesAlignmentSet = lastLayer.getPropertyAlignmentSet(); matchEnd(); System.out.println("OAEI2009 matcher completed in (h.m.s.ms) "+Utility.getFormattedTime(executionTime)); //System.out.println("Classes alignments found: "+classesAlignmentSet.size()); //System.out.println("Properties alignments found: "+propertiesAlignmentSet.size()); } public AbstractMatcherParametersPanel getParametersPanel() { if(parametersPanel == null){ parametersPanel = new OAEI2009parametersPanel(); } return parametersPanel; } }
AgreementMaker/src/am/app/mappingEngine/oaei2009/OAEI2009matcher.java
package am.app.mappingEngine.oaei2009; import java.rmi.RemoteException; import am.Utility; import am.app.Core; import am.app.mappingEngine.AbstractMatcher; import am.app.mappingEngine.AbstractMatcherParametersPanel; import am.app.mappingEngine.MatcherFactory; import am.app.mappingEngine.MatchersRegistry; import am.app.mappingEngine.Combination.CombinationParameters; import am.app.mappingEngine.PRAMatcher.PRAMatcher2; import am.app.mappingEngine.baseSimilarity.BaseSimilarityParameters; import am.app.mappingEngine.dsi.DescendantsSimilarityInheritanceParameters; import am.app.mappingEngine.multiWords.MultiWordsParameters; import am.app.mappingEngine.parametricStringMatcher.ParametricStringParameters; import am.app.mappingEngine.referenceAlignment.ReferenceAlignmentMatcher; import am.app.mappingEngine.referenceAlignment.ReferenceAlignmentParameters; //import uk.ac.shef.wit.simmetrics.similaritymetrics.*; //all sim metrics are in here public class OAEI2009matcher extends AbstractMatcher { //private Normalizer normalizer; public OAEI2009matcher() { // warning, param is not available at the time of the constructor super(); needsParam = true; param = new OAEI2009parameters(); } public String getDescriptionString() { return "The method adopted in the OAEI2009 competition." + "For more details, please read OAEI2009 results for the AgreementMaker available at www.cs.uic.edu/Cruz/Publications#2009. "+ "The configurations for the difference tracks are selected in the parameters panel. "; } /* ******************************************************************************************************* ************************ Init structures************************************* * ******************************************************************************************************* */ public void beforeAlignOperations() throws Exception{ super.beforeAlignOperations(); //OAEI2009parameters parameters =(OAEI2009parameters)param; } /* ******************************************************************************************************* ************************ Algorithm functions beyond this point************************************* * ******************************************************************************************************* */ public void match() throws Exception { matchStart(); long measure = 1000000; AbstractMatcher lastLayer; OAEI2009parameters parameters = (OAEI2009parameters)param; //FIRST LAYER: BSM PSM and VMM //BSM long startime = 0, endtime = 0, time = 0; AbstractMatcher pra = null; if( parameters.trackName == OAEI2009parameters.ANATOMY_PRA ) { // We are running anatomy with PRA. Run PRA instead of BSM. //AbstractMatcher refAlign = MatcherFactory.getMatcherInstance(MatchersRegistry.ImportAlignment, 0); Core core = Core.getInstance(); ReferenceAlignmentMatcher myMatcher = (ReferenceAlignmentMatcher)core.getMatcherInstance( MatchersRegistry.ImportAlignment ); if( myMatcher == null ) { // we are running from the command line, we have to load the partial reference file. ReferenceAlignmentParameters par = new ReferenceAlignmentParameters(); par.fileName = parameters.partialReferenceFile; par.format = parameters.format; ReferenceAlignmentMatcher refAlign = (ReferenceAlignmentMatcher) MatcherFactory.getMatcherInstance(MatchersRegistry.ImportAlignment, 0); refAlign.setParam(par); refAlign.match(); myMatcher = refAlign; } System.out.println("Running PRA."); startime = System.nanoTime()/measure; //AbstractMatcher pra = MatcherFactory.getMatcherInstance(MatchersRegistry.BaseSimilarity, 0); pra = MatcherFactory.getMatcherInstance(MatchersRegistry.PRAMatcher, 0); pra.getInputMatchers().add(myMatcher); pra.setThreshold(threshold); pra.setMaxSourceAlign(maxSourceAlign); pra.setMaxTargetAlign(maxTargetAlign); BaseSimilarityParameters bsmp = new BaseSimilarityParameters(); bsmp.initForOAEI2009(); pra.setParam(bsmp); //bsm.setPerformSelection(false); pra.match(); endtime = System.nanoTime()/measure; time = (endtime-startime); System.out.println("PRAMatcher completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); } else { // We are NOT running Anatomy with PRA. Run BSM. System.out.println("Running BSM"); startime = System.nanoTime()/measure; pra = MatcherFactory.getMatcherInstance(MatchersRegistry.BaseSimilarity, 0); pra.setThreshold(threshold); pra.setMaxSourceAlign(maxSourceAlign); pra.setMaxTargetAlign(maxTargetAlign); BaseSimilarityParameters bsmp = new BaseSimilarityParameters(); bsmp.initForOAEI2009(); pra.setParam(bsmp); //bsm.setPerformSelection(false); pra.match(); endtime = System.nanoTime()/measure; time = (endtime-startime); System.out.println("BSM completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); } //PSM System.out.println("Running PSM"); startime = System.nanoTime()/measure; AbstractMatcher psm = MatcherFactory.getMatcherInstance(MatchersRegistry.ParametricString, 1); psm.setThreshold(threshold); psm.setMaxSourceAlign(maxSourceAlign); psm.setMaxTargetAlign(maxTargetAlign); ParametricStringParameters psmp = new ParametricStringParameters(); psmp.initForOAEI2009(); psm.setParam(psmp); //psm.setPerformSelection(false); psm.match(); endtime = System.nanoTime()/measure; time = (endtime-startime); System.out.println("PSM completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); //vmm System.out.println("Running VMM"); startime = System.nanoTime()/measure; AbstractMatcher vmm = MatcherFactory.getMatcherInstance(MatchersRegistry.MultiWords, 2); vmm.setThreshold(threshold); vmm.setMaxSourceAlign(maxSourceAlign); vmm.setMaxTargetAlign(maxTargetAlign); MultiWordsParameters vmmp = new MultiWordsParameters(); vmmp.initForOAEI2009(); vmm.setParam(vmmp); //vmm.setPerformSelection(false); vmm.match(); endtime = System.nanoTime()/measure; time = (endtime-startime); System.out.println("VMM completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); //Second layer: LWC(VMM, PSM, BSM) //LWC matcher System.out.println("Running LWC"); startime = System.nanoTime()/measure; AbstractMatcher lwc = MatcherFactory.getMatcherInstance(MatchersRegistry.Combination, 3); lwc.getInputMatchers().add(psm); lwc.getInputMatchers().add(vmm); lwc.getInputMatchers().add(pra); lwc.setThreshold(threshold); lwc.setMaxSourceAlign(maxSourceAlign); lwc.setMaxTargetAlign(maxTargetAlign); CombinationParameters lwcp = new CombinationParameters(); lwcp.initForOAEI2009(); lwc.setParam(lwcp); //lwc.setPerformSelection(false); lwc.match(); endtime = System.nanoTime()/measure; time = (endtime-startime); System.out.println("LWC completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); lastLayer = lwc; //Forth or fifth layer: DSI //DSI System.out.println("Running DSI"); startime = System.nanoTime()/measure; AbstractMatcher dsi = MatcherFactory.getMatcherInstance(MatchersRegistry.DSI, 0); dsi.getInputMatchers().add(lastLayer); dsi.setThreshold(threshold); dsi.setMaxSourceAlign(maxSourceAlign); dsi.setMaxTargetAlign(maxTargetAlign); DescendantsSimilarityInheritanceParameters dsip = new DescendantsSimilarityInheritanceParameters(); dsip.initForOAEI2009(); dsi.setParam(dsip); //dsi.setPerformSelection(true); dsi.match(); endtime = System.nanoTime()/measure; time = (endtime-startime); System.out.println("DSI completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); lastLayer = dsi; if(parameters.useWordNet){ //third layer wnl on input LWC (optimized mode) System.out.println("Running LexicalWordnet"); startime = System.nanoTime()/measure; AbstractMatcher wnl = MatcherFactory.getMatcherInstance(MatchersRegistry.WordNetLexical, 2); wnl.setOptimized(true); wnl.addInputMatcher(lastLayer); wnl.setThreshold(threshold); wnl.setMaxSourceAlign(maxSourceAlign); wnl.setMaxTargetAlign(maxTargetAlign); wnl.match(); endtime = System.nanoTime()/measure; time = (endtime-startime); System.out.println("WNL completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); lastLayer = wnl; } if(parameters.useUMLS){ /* * COMMENTED OUT IN ORDER TO COMPUTE THE JAR FILE WITHOUT THE KSS LIBRARY //Run UMLS matcher on unmapped nodes. System.out.println("Running UMLS"); try{ startime = System.nanoTime()/measure; AbstractMatcher umls = MatcherFactory.getMatcherInstance(MatchersRegistry.UMLSKSLexical, 4); umls.setOptimized(true); umls.getInputMatchers().add(lastLayer); umls.setThreshold(threshold); umls.setMaxSourceAlign(maxSourceAlign); umls.setMaxTargetAlign(maxTargetAlign); //umls.initForOAEI2009(); umls.match(); time = (endtime-startime); System.out.println("UMLS completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); lastLayer = umls; } catch(RemoteException e){ e.printStackTrace(); System.out.println("Impossible to connect to the UMLS server. The ip address has to be registered at http://kscas-lhc.nlm.nih.gov/UMLSKS"); } */ } System.out.println("name: "+parameters.partialReferenceFile); System.out.println("format: "+parameters.format); if( parameters.trackName == OAEI2009parameters.ANATOMY_PRI ){ startime = System.nanoTime()/measure; AbstractMatcher praIntegration = MatcherFactory.getMatcherInstance(MatchersRegistry.PRAintegration, 0); praIntegration.getInputMatchers().add(lastLayer); praIntegration.setThreshold(threshold); praIntegration.setMaxSourceAlign(maxSourceAlign); praIntegration.setMaxTargetAlign(maxTargetAlign); //praIntegration uses the same parameters of ReferenceAlignmentMatcher ReferenceAlignmentParameters par = new ReferenceAlignmentParameters(); par.fileName = parameters.partialReferenceFile; par.format = parameters.format; praIntegration.setParam(par); //umls.initForOAEI2009(); praIntegration.match(); time = (endtime-startime); System.out.println("PRA integration completed in (h.m.s.ms) "+Utility.getFormattedTime(time)); lastLayer = praIntegration; } else if( parameters.trackName == OAEI2009parameters.ANATOMY_PRA ) { PRAMatcher2 pra2 = (PRAMatcher2) MatcherFactory.getMatcherInstance(MatchersRegistry.PRAMatcher2, 0); pra2.addInputMatcher(lastLayer); pra2.addInputMatcher(pra); pra2.setThreshold(threshold); pra2.setMaxSourceAlign(maxSourceAlign); pra2.setMaxTargetAlign(maxTargetAlign); pra2.match(); lastLayer = pra2; } classesMatrix = lastLayer.getClassesMatrix(); propertiesMatrix = lastLayer.getPropertiesMatrix(); classesAlignmentSet = lastLayer.getClassAlignmentSet(); propertiesAlignmentSet = lastLayer.getPropertyAlignmentSet(); matchEnd(); System.out.println("OAEI2009 matcher completed in (h.m.s.ms) "+Utility.getFormattedTime(executionTime)); //System.out.println("Classes alignments found: "+classesAlignmentSet.size()); //System.out.println("Properties alignments found: "+propertiesAlignmentSet.size()); } public AbstractMatcherParametersPanel getParametersPanel() { if(parametersPanel == null){ parametersPanel = new OAEI2009parametersPanel(); } return parametersPanel; } }
Bug fix: make OAEI2009 matcher work with SEALS.
AgreementMaker/src/am/app/mappingEngine/oaei2009/OAEI2009matcher.java
Bug fix: make OAEI2009 matcher work with SEALS.
<ide><path>greementMaker/src/am/app/mappingEngine/oaei2009/OAEI2009matcher.java <ide> BaseSimilarityParameters bsmp = new BaseSimilarityParameters(); <ide> bsmp.initForOAEI2009(); <ide> pra.setParam(bsmp); <add> pra.setSourceOntology(sourceOntology); <add> pra.setTargetOntology(targetOntology); <ide> //bsm.setPerformSelection(false); <ide> pra.match(); <ide> endtime = System.nanoTime()/measure; <ide> BaseSimilarityParameters bsmp = new BaseSimilarityParameters(); <ide> bsmp.initForOAEI2009(); <ide> pra.setParam(bsmp); <add> pra.setSourceOntology(sourceOntology); <add> pra.setTargetOntology(targetOntology); <ide> //bsm.setPerformSelection(false); <ide> pra.match(); <ide> endtime = System.nanoTime()/measure; <ide> ParametricStringParameters psmp = new ParametricStringParameters(); <ide> psmp.initForOAEI2009(); <ide> psm.setParam(psmp); <add> psm.setSourceOntology(sourceOntology); <add> psm.setSourceOntology(targetOntology); <ide> //psm.setPerformSelection(false); <ide> psm.match(); <ide> endtime = System.nanoTime()/measure; <ide> MultiWordsParameters vmmp = new MultiWordsParameters(); <ide> vmmp.initForOAEI2009(); <ide> vmm.setParam(vmmp); <add> vmm.setSourceOntology(sourceOntology); <add> vmm.setTargetOntology(targetOntology); <ide> //vmm.setPerformSelection(false); <ide> vmm.match(); <ide> endtime = System.nanoTime()/measure; <ide> CombinationParameters lwcp = new CombinationParameters(); <ide> lwcp.initForOAEI2009(); <ide> lwc.setParam(lwcp); <add> lwc.setSourceOntology(sourceOntology); <add> lwc.setTargetOntology(targetOntology); <ide> //lwc.setPerformSelection(false); <ide> lwc.match(); <ide> endtime = System.nanoTime()/measure; <ide> DescendantsSimilarityInheritanceParameters dsip = new DescendantsSimilarityInheritanceParameters(); <ide> dsip.initForOAEI2009(); <ide> dsi.setParam(dsip); <add> dsi.setSourceOntology(sourceOntology); <add> dsi.setTargetOntology(targetOntology); <ide> //dsi.setPerformSelection(true); <ide> dsi.match(); <ide> endtime = System.nanoTime()/measure; <ide> wnl.setThreshold(threshold); <ide> wnl.setMaxSourceAlign(maxSourceAlign); <ide> wnl.setMaxTargetAlign(maxTargetAlign); <add> wnl.setSourceOntology(sourceOntology); <add> wnl.setTargetOntology(targetOntology); <ide> wnl.match(); <ide> endtime = System.nanoTime()/measure; <ide> time = (endtime-startime); <ide> par.fileName = parameters.partialReferenceFile; <ide> par.format = parameters.format; <ide> praIntegration.setParam(par); <add> praIntegration.setSourceOntology(sourceOntology); <add> praIntegration.setTargetOntology(targetOntology); <ide> //umls.initForOAEI2009(); <ide> praIntegration.match(); <ide> time = (endtime-startime); <ide> pra2.setThreshold(threshold); <ide> pra2.setMaxSourceAlign(maxSourceAlign); <ide> pra2.setMaxTargetAlign(maxTargetAlign); <del> <add> pra2.setSourceOntology(sourceOntology); <add> pra2.setTargetOntology(targetOntology); <ide> pra2.match(); <ide> <ide> lastLayer = pra2;
Java
bsd-3-clause
f5fe5cfcf15e402e97182b58830c8f44d9877cae
0
PatrickPenguinTurtle/allwpilib,JLLeitschuh/allwpilib,JLLeitschuh/allwpilib,JLLeitschuh/allwpilib,PeterMitrano/allwpilib,robotdotnet/allwpilib,333fred/allwpilib,RAR1741/wpilib,RAR1741/wpilib,PatrickPenguinTurtle/allwpilib,JLLeitschuh/allwpilib,PeterMitrano/allwpilib,RAR1741/wpilib,JLLeitschuh/allwpilib,RAR1741/wpilib,PatrickPenguinTurtle/allwpilib,robotdotnet/allwpilib,PatrickPenguinTurtle/allwpilib,JLLeitschuh/allwpilib,robotdotnet/allwpilib,PeterMitrano/allwpilib,PeterMitrano/allwpilib,robotdotnet/allwpilib,333fred/allwpilib,RAR1741/wpilib,333fred/allwpilib,PeterMitrano/allwpilib,robotdotnet/allwpilib,333fred/allwpilib,RAR1741/wpilib,JLLeitschuh/allwpilib,333fred/allwpilib,RAR1741/wpilib,PeterMitrano/allwpilib,333fred/allwpilib,PatrickPenguinTurtle/allwpilib,robotdotnet/allwpilib,PeterMitrano/allwpilib,PatrickPenguinTurtle/allwpilib,PatrickPenguinTurtle/allwpilib
package edu.wpi.first.wpilibj.hal; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.io.FileOutputStream; // // base class for all JNI wrappers // public class JNIWrapper { static boolean libraryLoaded = false; static File jniLibrary = null; static { try { if (!libraryLoaded) { InputStream is = JNIWrapper.class.getResourceAsStream("/linux-arm/libwpilibJavaJNI.so"); if (is != null) { // create temporary file jniLibrary = File.createTempFile("libwpilibJavaJNI", ".so"); // flag for delete on exit jniLibrary.deleteOnExit(); byte[] buffer = new byte[1024]; int readBytes; OutputStream os = new FileOutputStream(jniLibrary); try { while ((readBytes = is.read(buffer)) != -1) { os.write(buffer, 0, readBytes); } } finally { os.close(); is.close(); } System.load(jniLibrary.getAbsolutePath()); } else { System.loadLibrary("wpilibJavaJNI"); } libraryLoaded = true; } } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } } public static native long getPortWithModule(byte module, byte pin); public static native long getPort(byte pin); public static native void freePort(long port_pointer); }
wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/JNIWrapper.java
package edu.wpi.first.wpilibj.hal; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.io.FileOutputStream; // // base class for all JNI wrappers // public class JNIWrapper { static boolean libraryLoaded = false; static File jniLibrary = null; static { try { if (!libraryLoaded) { // create temporary file jniLibrary = File.createTempFile("libwpilibJavaJNI", ".so"); // flag for delete on exit jniLibrary.deleteOnExit(); byte[] buffer = new byte[1024]; int readBytes; InputStream is = JNIWrapper.class.getResourceAsStream("/linux-arm/libwpilibJavaJNI.so"); OutputStream os = new FileOutputStream(jniLibrary); try { while ((readBytes = is.read(buffer)) != -1) { os.write(buffer, 0, readBytes); } } finally { os.close(); is.close(); } libraryLoaded = true; } System.load(jniLibrary.getAbsolutePath()); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } } public static native long getPortWithModule(byte module, byte pin); public static native long getPort(byte pin); public static native void freePort(long port_pointer); }
JNIWrapper: Fall back to system library if not found in .jar. This is useful primarily for debugging purposes (as the temporary file written by the loader can't be easily loaded by gdb). Change-Id: Ic4ea22ef88363c5ff998980b0352844645766fd9
wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/JNIWrapper.java
JNIWrapper: Fall back to system library if not found in .jar.
<ide><path>pilibj/src/athena/java/edu/wpi/first/wpilibj/hal/JNIWrapper.java <ide> static { <ide> try { <ide> if (!libraryLoaded) { <del> // create temporary file <del> jniLibrary = File.createTempFile("libwpilibJavaJNI", ".so"); <del> // flag for delete on exit <del> jniLibrary.deleteOnExit(); <add> InputStream is = JNIWrapper.class.getResourceAsStream("/linux-arm/libwpilibJavaJNI.so"); <add> if (is != null) { <add> // create temporary file <add> jniLibrary = File.createTempFile("libwpilibJavaJNI", ".so"); <add> // flag for delete on exit <add> jniLibrary.deleteOnExit(); <ide> <del> byte[] buffer = new byte[1024]; <add> byte[] buffer = new byte[1024]; <ide> <del> int readBytes; <add> int readBytes; <ide> <del> InputStream is = JNIWrapper.class.getResourceAsStream("/linux-arm/libwpilibJavaJNI.so"); <ide> <del> OutputStream os = new FileOutputStream(jniLibrary); <add> OutputStream os = new FileOutputStream(jniLibrary); <ide> <del> try { <del> while ((readBytes = is.read(buffer)) != -1) { <del> os.write(buffer, 0, readBytes); <add> try { <add> while ((readBytes = is.read(buffer)) != -1) { <add> os.write(buffer, 0, readBytes); <add> } <add> <add> } finally { <add> os.close(); <add> is.close(); <ide> } <del> <del> } finally { <del> os.close(); <del> is.close(); <add> System.load(jniLibrary.getAbsolutePath()); <add> } else { <add> System.loadLibrary("wpilibJavaJNI"); <ide> } <del> <ide> <ide> libraryLoaded = true; <ide> } <ide> <del> System.load(jniLibrary.getAbsolutePath()); <ide> } catch (Exception ex) { <ide> ex.printStackTrace(); <ide> System.exit(1);
Java
apache-2.0
b189bc5d9790b4cbfe22705b4590d60fe7bf7425
0
enternoescape/opendct,enternoescape/opendct,enternoescape/opendct
/* * Copyright 2015 The OpenDCT Authors. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opendct.tuning.http; import opendct.channel.ChannelManager; import opendct.channel.TVChannel; import opendct.config.Config; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; public class InfiniTVTuning { private static final Logger logger = LogManager.getLogger(InfiniTVTuning.class); public static boolean tuneChannel(String lineupName, String channel, String deviceAddress, int tunerNumber, boolean useVChannel, int retry) throws InterruptedException { if (!useVChannel) { TVChannel tvChannel = ChannelManager.getChannel(lineupName, channel); return tuneQamChannel(tvChannel, deviceAddress, tunerNumber, retry); } // There is no need to look up the channel when a CableCARD is present. return tuneVChannel(channel, deviceAddress, tunerNumber, retry); } public static boolean tuneQamChannel(TVChannel tvChannel, String deviceAddress, int tunerNumber, int retry) throws InterruptedException { logger.entry(deviceAddress, tunerNumber); boolean returnValue = false; if (tvChannel == null) { logger.error("The requested channel does not exist in the channel map."); return logger.exit(false); } try { // Check if the frequency is already correct. String currentFrequency = InfiniTVStatus.getVar(deviceAddress, tunerNumber, "tuner", "Frequency") + "000"; boolean frequencyTuned = currentFrequency.equals(String.valueOf(tvChannel.getFrequency())); int attempts = 20; while (!frequencyTuned) { tuneFrequency(tvChannel, deviceAddress, tunerNumber, retry); currentFrequency = InfiniTVStatus.getVar(deviceAddress, tunerNumber, "tuner", "Frequency") + "000"; frequencyTuned = currentFrequency.equals(String.valueOf(tvChannel.getFrequency())); if (attempts-- == 0 && !frequencyTuned) { logger.error("The requested frequency cannot be tuned."); return logger.exit(false); } else if (!frequencyTuned) { try { // Sleep if the first request fails so we don't overwhelm the device // with requests. Remember up to 6 of these kinds of request could // happen at the exact same time. Thread.sleep(100); } catch (InterruptedException e) { logger.error("tuneChannel was interrupted while tuning to a frequency."); return logger.exit(false); } } } attempts = 20; boolean programSelected = false; Thread.sleep(250); while (!programSelected) { // If we are not already on the correct frequency, it takes the tuner a moment // to detect the available programs. If you try to set a program before the list // is available, it will fail. Normally this happens so fast, a sleep method // isn't appropriate. We have a while loop to retry a few times if it fails. tuneProgram(tvChannel, deviceAddress, tunerNumber, retry); programSelected = InfiniTVStatus.getVar(deviceAddress, tunerNumber, "mux", "ProgramNumber").equals(tvChannel.getProgram()); if (attempts-- == 0 && !programSelected) { logger.error("The requested program cannot be selected."); return logger.exit(false); } else if (!programSelected) { try { // Sleep if the first request fails so we don't overwhelm the device // with requests. Remember up to 6 of these kinds of request could // happen at the exact same time. Thread.sleep(100); } catch (InterruptedException e) { logger.error("tuneChannel was interrupted while selecting a program."); return logger.exit(false); } } } returnValue = true; /*} catch (InterruptedException e) { logger.debug("tuneChannel was interrupted while waiting setting the program.");*/ } catch (IOException e) { logger.debug("tuneChannel was unable to get the current program value."); } return logger.exit(returnValue); } public static boolean tuneVChannel(String vchannel, String deviceAddress, int tunerNumber, int retry) throws InterruptedException { logger.entry(vchannel, deviceAddress, tunerNumber); if (tunerNumber - 1 < 0) { logger.error("The tuner number cannot be less than 1."); return logger.exit(false); } String instanceId = "instance_id=" + String.valueOf(tunerNumber - 1); String channel = "channel=" + vchannel; boolean returnValue = postContent(deviceAddress, "/channel_request.cgi", retry, instanceId, channel); return logger.exit(returnValue); } public static boolean tuneVChannel(TVChannel tvChannel, String deviceAddress, int tunerNumber, int retry) throws InterruptedException { logger.entry(tvChannel, deviceAddress, tunerNumber); if (tunerNumber - 1 < 0) { logger.error("The tuner number cannot be less than 1."); return logger.exit(false); } String instanceId = "instance_id=" + String.valueOf(tunerNumber - 1); String channel = "channel=" + tvChannel.getChannel(); boolean returnValue = postContent(deviceAddress, "/channel_request.cgi", retry, instanceId, channel); return logger.exit(returnValue); } public static boolean tuneFrequency(TVChannel tvChannel, String deviceAddress, int tunerNumber, int retry) throws InterruptedException { logger.entry(tvChannel, deviceAddress, tunerNumber); logger.info("Tuning frequency '{}'.", tvChannel.getFrequency()); if (tunerNumber - 1 < 0) { logger.error("The tuner number cannot be less than 1."); return logger.exit(false); } String instanceId = "instance_id=" + String.valueOf(tunerNumber - 1); String frequency = "frequency=" + (tvChannel.getFrequency() / 1000); String modulation = null; if (tvChannel.getModulation().equals("QAM256")) { modulation = "modulation=2"; } else if (tvChannel.getModulation().equals("QAM64")) { modulation = "modulation=0"; } else if (tvChannel.getModulation().equals("NTSC-M")) { modulation = "modulation=4"; } else if (tvChannel.getModulation().equals("8VSB")) { modulation = "modulation=6"; } else { logger.error("Cannot get the modulation index value for POST."); return logger.exit(false); } String tuner = "tuner=1"; String demod = "demod=1"; String rstChnl = "rst_chnl=0"; String forceTune = "force_tune=0"; boolean returnValue = postContent(deviceAddress, "/tune_request.cgi", retry, instanceId, frequency, modulation, tuner, demod, rstChnl, forceTune); return logger.exit(returnValue); } public static boolean tuneProgram(TVChannel tvChannel, String deviceAddress, int tunerNumber, int retry) throws InterruptedException { logger.entry(deviceAddress, deviceAddress, tunerNumber); logger.info("Selecting program '{}'.", tvChannel.getProgram()); if (tunerNumber - 1 < 0) { logger.error("The tuner number cannot be less than 1."); return logger.exit(false); } String instanceId = "instance_id=" + String.valueOf(tunerNumber - 1); String program = "program=" + tvChannel.getProgram(); boolean returnValue = postContent(deviceAddress, "/program_request.cgi", retry, instanceId, program); return logger.exit(returnValue); } public static boolean startRTSP(String localIPAddress, int rtpStreamLocalPort, String deviceAddress, int tunerNumber) { logger.entry(localIPAddress, rtpStreamLocalPort, deviceAddress, tunerNumber); logger.info("Starting streaming from tuner number {} to local port '{}'.", tunerNumber, rtpStreamLocalPort); if (tunerNumber - 1 < 0) { logger.error("The tuner number cannot be less than 1."); return logger.exit(false); } /*try { String currentIP = InfiniTVStatus.getVar(deviceAddress, tunerNumber, "diag", "Streaming_IP"); String currentPort = InfiniTVStatus.getVar(deviceAddress, tunerNumber, "diag", "Streaming_Port"); String playback = InfiniTVStatus.getVar(deviceAddress, tunerNumber, "av", "TransportState"); if (currentIP.equals(localIPAddress) && currentPort.equals(String.valueOf(rtpStreamLocalPort)) && playback.equals("PLAYING")) { logger.info("The IP address and port for RTP are already set."); return logger.exit(true); } } catch (IOException e) { logger.error("Unable to get the current ip address, transport state and streaming port => {}", e); }*/ String instanceId = "instance_id=" + String.valueOf(tunerNumber - 1); String destIp = "dest_ip=" + localIPAddress; String destPort = "dest_port=" + rtpStreamLocalPort; String protocol = "protocol=0"; //RTP String start = "start=1"; // 1 = Started (0 = Stopped) boolean returnValue = postContent(deviceAddress, "/stream_request.cgi", instanceId, destIp, destPort, protocol, start); return logger.exit(returnValue); } public static boolean stopRTSP(String deviceAddress, int tunerNumber) { logger.entry(deviceAddress, tunerNumber); logger.info("Stopping streaming from tuner number {} at '{}'.", tunerNumber, deviceAddress); if (tunerNumber - 1 < 0) { logger.error("The tuner number cannot be less than 1."); return logger.exit(false); } String instanceId = "instance_id=" + String.valueOf(tunerNumber - 1); String destIp = "dest_ip=192.168.200.2"; String destPort = "dest_port=8000"; String protocol = "protocol=0"; //RTP String start = "start=0"; // 0 = Stopped (1 = Started) boolean returnValue = postContent(deviceAddress, "/stream_request.cgi", instanceId, destIp, destPort, protocol, start); return logger.exit(returnValue); } public static boolean postContent(String deviceAddress, String postPath, int retry, String... parameters) throws InterruptedException { retry = Math.abs(retry) + 1; for (int i = 0; i < retry; i++) { if (postContent(deviceAddress, postPath, parameters)) { return logger.exit(true); } logger.error("Unable to access device '{}', attempt number {}", deviceAddress, i); Thread.sleep(200); } return logger.exit(false); } public static boolean postContent(String deviceAddress, String postPath, String... parameters) { logger.entry(deviceAddress, postPath, parameters); StringBuilder postParameters = new StringBuilder(); for (String parameter : parameters) { postParameters.append(parameter); postParameters.append("&"); } if (postParameters.length() > 0) { postParameters.deleteCharAt(postParameters.length() - 1); } byte postBytes[] = postParameters.toString().getBytes(Config.STD_BYTE); URL url = null; try { url = new URL("http://" + deviceAddress + postPath); } catch (MalformedURLException e) { logger.error("Unable to create a valid URL using 'http://{}{}'", deviceAddress, postPath); return logger.exit(false); } logger.info("Connecting to InfiniTV tuner using the URL '{}'", url); final HttpURLConnection httpURLConnection; try { httpURLConnection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { logger.error("Unable to open an HTTP connection => {}", e); return logger.exit(false); } httpURLConnection.setDoOutput(true); try { httpURLConnection.setRequestMethod("POST"); } catch (ProtocolException e) { logger.error("Unable to change request method to POST => {}", e); return logger.exit(false); } httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpURLConnection.setRequestProperty("charset", "utf-8"); httpURLConnection.setRequestProperty("Content-Length", String.valueOf(postBytes.length)); DataOutputStream dataOutputStream = null; try { httpURLConnection.connect(); dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream()); dataOutputStream.write(postBytes); dataOutputStream.flush(); } catch (IOException e) { logger.error("Unable to write POST bytes => {}", e); return logger.exit(false); } String line = null; try { dataOutputStream.close(); final HttpURLConnection finalHttpURLConnection = httpURLConnection; Thread httpTimeout = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { return; } finalHttpURLConnection.disconnect(); } }); httpTimeout.start(); InputStream inputStream = httpURLConnection.getInputStream(); httpTimeout.interrupt(); // The InfiniTV requires that at least one byte of data is read or the POST will fail. if (inputStream.available() > 0) { inputStream.read(); } inputStream.close(); } catch (IOException e) { logger.error("Unable to read reply. Capture device is not available => {}", e.toString()); } return logger.exit(true); } }
src/main/java/opendct/tuning/http/InfiniTVTuning.java
/* * Copyright 2015 The OpenDCT Authors. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opendct.tuning.http; import opendct.channel.ChannelManager; import opendct.channel.TVChannel; import opendct.config.Config; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; public class InfiniTVTuning { private static final Logger logger = LogManager.getLogger(InfiniTVTuning.class); public static boolean tuneChannel(String lineupName, String channel, String deviceAddress, int tunerNumber, boolean useVChannel, int retry) throws InterruptedException { if (!useVChannel) { TVChannel tvChannel = ChannelManager.getChannel(lineupName, channel); return tuneQamChannel(tvChannel, deviceAddress, tunerNumber, retry); } // There is no need to look up the channel when a CableCARD is present. return tuneVChannel(channel, deviceAddress, tunerNumber, retry); } public static boolean tuneQamChannel(TVChannel tvChannel, String deviceAddress, int tunerNumber, int retry) throws InterruptedException { logger.entry(deviceAddress, tunerNumber); boolean returnValue = false; if (tvChannel == null) { logger.error("The requested channel does not exist in the channel map."); return logger.exit(false); } try { // Check if the frequency is already correct. String currentFrequency = InfiniTVStatus.getVar(deviceAddress, tunerNumber, "tuner", "Frequency") + "000"; boolean frequencyTuned = currentFrequency.equals(String.valueOf(tvChannel.getFrequency())); int attempts = 20; while (!frequencyTuned) { tuneFrequency(tvChannel, deviceAddress, tunerNumber, retry); currentFrequency = InfiniTVStatus.getVar(deviceAddress, tunerNumber, "tuner", "Frequency") + "000"; frequencyTuned = currentFrequency.equals(String.valueOf(tvChannel.getFrequency())); if (attempts-- == 0 && !frequencyTuned) { logger.error("The requested frequency cannot be tuned."); return logger.exit(false); } else if (!frequencyTuned) { try { // Sleep if the first request fails so we don't overwhelm the device // with requests. Remember up to 6 of these kinds of request could // happen at the exact same time. Thread.sleep(100); } catch (InterruptedException e) { logger.error("tuneChannel was interrupted while tuning to a frequency."); return logger.exit(false); } } } attempts = 20; boolean programSelected = false; Thread.sleep(250); while (!programSelected) { // If we are not already on the correct frequency, it takes the tuner a moment // to detect the available programs. If you try to set a program before the list // is available, it will fail. Normally this happens so fast, a sleep method // isn't appropriate. We have a while loop to retry a few times if it fails. tuneProgram(tvChannel, deviceAddress, tunerNumber, retry); programSelected = InfiniTVStatus.getVar(deviceAddress, tunerNumber, "mux", "ProgramNumber").equals(tvChannel.getProgram()); if (attempts-- == 0 && !programSelected) { logger.error("The requested program cannot be selected."); return logger.exit(false); } else if (!programSelected) { try { // Sleep if the first request fails so we don't overwhelm the device // with requests. Remember up to 6 of these kinds of request could // happen at the exact same time. Thread.sleep(100); } catch (InterruptedException e) { logger.error("tuneChannel was interrupted while selecting a program."); return logger.exit(false); } } } returnValue = true; /*} catch (InterruptedException e) { logger.debug("tuneChannel was interrupted while waiting setting the program.");*/ } catch (IOException e) { logger.debug("tuneChannel was unable to get the current program value."); } return logger.exit(returnValue); } public static boolean tuneVChannel(String vchannel, String deviceAddress, int tunerNumber, int retry) throws InterruptedException { logger.entry(vchannel, deviceAddress, tunerNumber); if (tunerNumber - 1 < 0) { logger.error("The tuner number cannot be less than 1."); return logger.exit(false); } String instanceId = "instance_id=" + String.valueOf(tunerNumber - 1); String channel = "channel=" + vchannel; boolean returnValue = postContent(deviceAddress, "/channel_request.cgi", retry, instanceId, channel); return logger.exit(returnValue); } public static boolean tuneVChannel(TVChannel tvChannel, String deviceAddress, int tunerNumber, int retry) throws InterruptedException { logger.entry(tvChannel, deviceAddress, tunerNumber); if (tunerNumber - 1 < 0) { logger.error("The tuner number cannot be less than 1."); return logger.exit(false); } String instanceId = "instance_id=" + String.valueOf(tunerNumber - 1); String channel = "channel=" + tvChannel.getChannel(); boolean returnValue = postContent(deviceAddress, "/channel_request.cgi", retry, instanceId, channel); return logger.exit(returnValue); } public static boolean tuneFrequency(TVChannel tvChannel, String deviceAddress, int tunerNumber, int retry) throws InterruptedException { logger.entry(tvChannel, deviceAddress, tunerNumber); logger.info("Tuning frequency '{}'.", tvChannel.getFrequency()); if (tunerNumber - 1 < 0) { logger.error("The tuner number cannot be less than 1."); return logger.exit(false); } String instanceId = "instance_id=" + String.valueOf(tunerNumber - 1); String frequency = "frequency=" + (tvChannel.getFrequency() / 1000); String modulation = null; if (tvChannel.getModulation().equals("QAM256")) { modulation = "modulation=2"; } else if (tvChannel.getModulation().equals("QAM64")) { modulation = "modulation=0"; } else if (tvChannel.getModulation().equals("NTSC-M")) { modulation = "modulation=4"; } else if (tvChannel.getModulation().equals("8VSB")) { modulation = "modulation=6"; } else { logger.error("Cannot get the modulation index value for POST."); return logger.exit(false); } String tuner = "tuner=1"; String demod = "demod=1"; String rstChnl = "rst_chnl=0"; String forceTune = "force_tune=0"; boolean returnValue = postContent(deviceAddress, "/tune_request.cgi", retry, instanceId, frequency, modulation, tuner, demod, rstChnl, forceTune); return logger.exit(returnValue); } public static boolean tuneProgram(TVChannel tvChannel, String deviceAddress, int tunerNumber, int retry) throws InterruptedException { logger.entry(deviceAddress, deviceAddress, tunerNumber); logger.info("Selecting program '{}'.", tvChannel.getProgram()); if (tunerNumber - 1 < 0) { logger.error("The tuner number cannot be less than 1."); return logger.exit(false); } String instanceId = "instance_id=" + String.valueOf(tunerNumber - 1); String program = "program=" + tvChannel.getProgram(); boolean returnValue = postContent(deviceAddress, "/program_request.cgi", retry, instanceId, program); return logger.exit(returnValue); } public static boolean startRTSP(String localIPAddress, int rtpStreamLocalPort, String deviceAddress, int tunerNumber) { logger.entry(localIPAddress, rtpStreamLocalPort, deviceAddress, tunerNumber); logger.info("Starting streaming from tuner number {} to local port '{}'.", tunerNumber, rtpStreamLocalPort); if (tunerNumber - 1 < 0) { logger.error("The tuner number cannot be less than 1."); return logger.exit(false); } /*try { String currentIP = InfiniTVStatus.getVar(deviceAddress, tunerNumber, "diag", "Streaming_IP"); String currentPort = InfiniTVStatus.getVar(deviceAddress, tunerNumber, "diag", "Streaming_Port"); String playback = InfiniTVStatus.getVar(deviceAddress, tunerNumber, "av", "TransportState"); if (currentIP.equals(localIPAddress) && currentPort.equals(String.valueOf(rtpStreamLocalPort)) && playback.equals("PLAYING")) { logger.info("The IP address and port for RTP are already set."); return logger.exit(true); } } catch (IOException e) { logger.error("Unable to get the current ip address, transport state and streaming port => {}", e); }*/ String instanceId = "instance_id=" + String.valueOf(tunerNumber - 1); String destIp = "dest_ip=" + localIPAddress; String destPort = "dest_port=" + rtpStreamLocalPort; String protocol = "protocol=0"; //RTP String start = "start=1"; // 1 = Started (0 = Stopped) boolean returnValue = postContent(deviceAddress, "/stream_request.cgi", instanceId, destIp, destPort, protocol, start); return logger.exit(returnValue); } public static boolean stopRTSP(String deviceAddress, int tunerNumber) { logger.entry(deviceAddress, tunerNumber); logger.info("Stopping streaming from tuner number {} at '{}'.", tunerNumber, deviceAddress); if (tunerNumber - 1 < 0) { logger.error("The tuner number cannot be less than 1."); return logger.exit(false); } String instanceId = "instance_id=" + String.valueOf(tunerNumber - 1); String destIp = "dest_ip=192.168.200.2"; String destPort = "dest_port=8000"; String protocol = "protocol=0"; //RTP String start = "start=0"; // 0 = Stopped (1 = Started) boolean returnValue = postContent(deviceAddress, "/stream_request.cgi", instanceId, destIp, destPort, protocol, start); return logger.exit(returnValue); } public static boolean postContent(String deviceAddress, String postPath, int retry, String... parameters) throws InterruptedException { retry = Math.abs(retry) + 1; for (int i = 0; i < retry; i++) { if (postContent(deviceAddress, postPath, parameters)) { return logger.exit(true); } logger.error("Unable to access device '{}', attempt number {}", deviceAddress, i); Thread.sleep(200); } return logger.exit(false); } public static boolean postContent(String deviceAddress, String postPath, String... parameters) { logger.entry(deviceAddress, postPath, parameters); StringBuilder postParameters = new StringBuilder(); for (String parameter : parameters) { postParameters.append(parameter); postParameters.append("&"); } if (postParameters.length() > 0) { postParameters.deleteCharAt(postParameters.length() - 1); } byte postBytes[] = postParameters.toString().getBytes(Config.STD_BYTE); URL url = null; try { url = new URL("http://" + deviceAddress + postPath); } catch (MalformedURLException e) { logger.error("Unable to create a valid URL using 'http://{}{}'", deviceAddress, postPath); return logger.exit(false); } logger.info("Connecting to InfiniTV tuner using the URL '{}'", url); final HttpURLConnection httpURLConnection; try { httpURLConnection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { logger.error("Unable to open an HTTP connection => {}", e); return logger.exit(false); } httpURLConnection.setDoOutput(true); try { httpURLConnection.setRequestMethod("POST"); } catch (ProtocolException e) { logger.error("Unable to change request method to POST => {}", e); return logger.exit(false); } httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpURLConnection.setRequestProperty("charset", "utf-8"); httpURLConnection.setRequestProperty("Content-Length", String.valueOf(postBytes.length)); DataOutputStream dataOutputStream = null; try { httpURLConnection.connect(); dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream()); dataOutputStream.write(postBytes); dataOutputStream.flush(); } catch (IOException e) { logger.error("Unable to write POST bytes => {}", e); return logger.exit(false); } String line = null; try { dataOutputStream.close(); final HttpURLConnection finalHttpURLConnection = httpURLConnection; Thread httpTimeout = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { return; } finalHttpURLConnection.disconnect(); } }); httpTimeout.start(); InputStream inputStream = httpURLConnection.getInputStream(); httpTimeout.interrupt(); // The InfiniTV requires that at least one byte of data is read or the POST will fail. if (inputStream.available() > 0) { inputStream.read(); } inputStream.close(); } catch (IOException e) { logger.error("Unable to read reply => {}", e.toString()); } return logger.exit(true); } }
Increased waiting time for tuning.
src/main/java/opendct/tuning/http/InfiniTVTuning.java
Increased waiting time for tuning.
<ide><path>rc/main/java/opendct/tuning/http/InfiniTVTuning.java <ide> @Override <ide> public void run() { <ide> try { <del> Thread.sleep(2000); <add> Thread.sleep(5000); <ide> } catch (InterruptedException e) { <ide> return; <ide> } <ide> <ide> inputStream.close(); <ide> } catch (IOException e) { <del> logger.error("Unable to read reply => {}", e.toString()); <add> logger.error("Unable to read reply. Capture device is not available => {}", <add> e.toString()); <ide> } <ide> <ide> return logger.exit(true);
JavaScript
apache-2.0
0077f942aacd1659b5c42a43f4f1d1c11642c0d7
0
postmanlabs/postman-runtime,postmanlabs/postman-runtime
var _ = require('lodash'), crypto = require('crypto'), urlEncoder = require('postman-url-encoder'), EMPTY = '', ONE = '00000001', DISABLE_RETRY_REQUEST = 'disableRetryRequest', WWW_AUTHENTICATE = 'www-authenticate', DIGEST_PREFIX = 'Digest ', QOP = 'qop', AUTH = 'auth', COLON = ':', QUOTE = '"', SESS = '-sess', AUTH_INT = 'auth-int', AUTHORIZATION = 'Authorization', MD5_SESS = 'MD5-sess', ASCII_SOURCE = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', ASCII_SOURCE_LENGTH = ASCII_SOURCE.length, USERNAME_EQUALS_QUOTE = 'username="', REALM_EQUALS_QUOTE = 'realm="', NONCE_EQUALS_QUOTE = 'nonce="', URI_EQUALS_QUOTE = 'uri="', ALGORITHM_EQUALS_QUOTE = 'algorithm="', CNONCE_EQUALS_QUOTE = 'cnonce="', RESPONSE_EQUALS_QUOTE = 'response="', OPAQUE_EQUALS_QUOTE = 'opaque="', QOP_EQUALS = 'qop=', NC_EQUALS = 'nc=', ALGO = { MD5: 'MD5', MD5_SESS: 'MD5-sess', SHA_256: 'SHA-256', SHA_256_SESS: 'SHA-256-sess', SHA_512_256: 'SHA-512-256', SHA_512_256_SESS: 'SHA-512-256-sess' }, AUTH_PARAMETERS = [ 'algorithm', 'username', 'realm', 'password', 'method', 'nonce', 'nonceCount', 'clientNonce', 'opaque', 'qop', 'uri' ], nonceRegex = /nonce="([^"]*)"/, realmRegex = /realm="([^"]*)"/, qopRegex = /qop="([^"]*)"/, opaqueRegex = /opaque="([^"]*)"/, _extractField; /** * Generates a random string of given length * * @todo Move this to util.js. After moving use that for hawk auth too * @param {Number} length */ function randomString (length) { length = length || 6; var result = [], i; for (i = 0; i < length; i++) { result[i] = ASCII_SOURCE[(Math.random() * ASCII_SOURCE_LENGTH) | 0]; } return result.join(EMPTY); } /** * Extracts a Digest Auth field from a WWW-Authenticate header value using a given regexp. * * @param {String} string * @param {RegExp} regexp * @private */ _extractField = function (string, regexp) { var match = string.match(regexp); return match ? match[1] : EMPTY; }; /** * Returns the 'www-authenticate' header for Digest auth. Since a server can suport more than more auth-scheme, * there can be more than one header with the same key. So need to loop over and check each one. * * @param {VariableList} headers * @private */ function _getDigestAuthHeader (headers) { return headers.find(function (property) { return (property.key.toLowerCase() === WWW_AUTHENTICATE) && (_.startsWith(property.value, DIGEST_PREFIX)); }); } /** * Returns a function to calculate hash of data with given algorithm * * @param {String} algorithm hash algorithm * @returns {Function} functiont that takes data as argument and returns its hash */ function getHashFunction (algorithm) { return function (data) { return crypto.createHash(algorithm).update(data || EMPTY).digest('hex'); }; } /** * All the auth definition parameters excluding username and password should be stored and resued. * @todo The current implementation would fail for the case when two requests to two different hosts inherits the same * auth. In that case a retry would not be attempted for the second request (since all the parameters would be present * in the auth definition though invalid). * * @implements {AuthHandlerInterface} */ module.exports = { /** * @property {AuthHandlerInterface~AuthManifest} */ manifest: { info: { name: 'digest', version: '1.0.0' }, updates: [ { property: 'Authorization', type: 'header' }, { property: 'nonce', type: 'auth' }, { property: 'realm', type: 'auth' } ] }, /** * Initializes an item (extracts parameters from intermediate requests if any, etc) * before the actual authorization step. * * @param {AuthInterface} auth * @param {Response} response * @param {AuthHandlerInterface~authInitHookCallback} done */ init: function (auth, response, done) { done(null); }, /** * Checks whether the given item has all the required parameters in its request. * Sanitizes the auth parameters if needed. * * @param {AuthInterface} auth * @param {AuthHandlerInterface~authPreHookCallback} done */ pre: function (auth, done) { // ensure that all dynamic parameter values are present in the parameters // if even one is absent, we return false. done(null, Boolean(auth.get('nonce') && auth.get('realm'))); }, /** * Verifies whether the request was successfully authorized after being sent. * * @param {AuthInterface} auth * @param {Response} response * @param {AuthHandlerInterface~authPostHookCallback} done */ post: function (auth, response, done) { if (auth.get(DISABLE_RETRY_REQUEST) || !response) { return done(null, true); } var code, realm, nonce, qop, opaque, authHeader, authParams = {}; code = response.code; authHeader = _getDigestAuthHeader(response.headers); // If code is forbidden or unauthorized, and an auth header exists, // we can extract the realm & the nonce, and replay the request. // todo: add response.is4XX, response.is5XX, etc in the SDK. if ((code === 401 || code === 403) && authHeader) { nonce = _extractField(authHeader.value, nonceRegex); realm = _extractField(authHeader.value, realmRegex); qop = _extractField(authHeader.value, qopRegex); opaque = _extractField(authHeader.value, opaqueRegex); authParams.nonce = nonce; authParams.realm = realm; opaque && (authParams.opaque = opaque); qop && (authParams.qop = qop); if (authParams.qop || auth.get(QOP)) { authParams.clientNonce = randomString(8); authParams.nonceCount = ONE; } // if all the auth parameters sent by server were already present in auth definition then we do not retry if (_.every(authParams, function (value, key) { return auth.get(key); })) { return done(null, true); } auth.set(authParams); return done(null, false); } done(null, true); }, /** * Computes the Digest Authentication header from the given parameters. * * @param {Object} params * @param {String} params.algorithm * @param {String} params.username * @param {String} params.realm * @param {String} params.password * @param {String} params.method * @param {String} params.nonce * @param {String} params.nonceCount * @param {String} params.clientNonce * @param {String} params.opaque * @param {String} params.qop * @param {String} params.uri * @returns {String} */ computeHeader: function (params) { var algorithm = params.algorithm, username = params.username, realm = params.realm, password = params.password, method = params.method, nonce = params.nonce, nonceCount = params.nonceCount, clientNonce = params.clientNonce, opaque = params.opaque, qop = params.qop, uri = params.uri, // RFC defined terms, http://tools.ietf.org/html/rfc2617#section-3 A0, A1, A2, hashA1, hashA2, hash, reqDigest, headerParams; switch (algorithm) { case ALGO.SHA_256: case ALGO.SHA_256_SESS: hash = getHashFunction('sha256'); break; case ALGO.MD5: case ALGO.MD5_SESS: case undefined: case null: algorithm = algorithm || ALGO.MD5; hash = getHashFunction('md5'); break; case ALGO.SHA_512_256: case ALGO.SHA_512_256_SESS: default: // Current Electron version(7.2.3) in Postman app uses OpenSSL 1.1.0 // which don't support `SHA-512-256`. // @todo: change this when Electron is upgraded to a version which supports `SHA-512-256`. throw new Error(`Unsupported digest algorithm: ${algorithm}`); } if (_.endsWith(algorithm, SESS)) { A0 = hash(username + COLON + realm + COLON + password); A1 = A0 + COLON + nonce + COLON + clientNonce; } else { A1 = username + COLON + realm + COLON + password; } if (qop === AUTH_INT) { A2 = method + COLON + uri + COLON + hash(params.body); } else { A2 = method + COLON + uri; } hashA1 = hash(A1); hashA2 = hash(A2); if (qop === AUTH || qop === AUTH_INT) { reqDigest = hash([hashA1, nonce, nonceCount, clientNonce, qop, hashA2].join(COLON)); } else { reqDigest = hash([hashA1, nonce, hashA2].join(COLON)); } headerParams = [USERNAME_EQUALS_QUOTE + username + QUOTE, REALM_EQUALS_QUOTE + realm + QUOTE, NONCE_EQUALS_QUOTE + nonce + QUOTE, URI_EQUALS_QUOTE + uri + QUOTE ]; algorithm && headerParams.push(ALGORITHM_EQUALS_QUOTE + algorithm + QUOTE); if (qop === AUTH || qop === AUTH_INT) { headerParams.push(QOP_EQUALS + qop); } if (qop === AUTH || qop === AUTH_INT || algorithm === MD5_SESS) { nonceCount && headerParams.push(NC_EQUALS + nonceCount); headerParams.push(CNONCE_EQUALS_QUOTE + clientNonce + QUOTE); } headerParams.push(RESPONSE_EQUALS_QUOTE + reqDigest + QUOTE); opaque && headerParams.push(OPAQUE_EQUALS_QUOTE + opaque + QUOTE); return DIGEST_PREFIX + headerParams.join(', '); }, /** * Signs a request. * * @param {AuthInterface} auth * @param {Request} request * @param {AuthHandlerInterface~authSignHookCallback} done */ sign: function (auth, request, done) { var header, params = auth.get(AUTH_PARAMETERS), url = urlEncoder.toNodeUrl(request.url); if (!params.username || !params.realm) { return done(); // Nothing to do if required parameters are not present. } request.removeHeader(AUTHORIZATION, {ignoreCase: true}); params.method = request.method; params.uri = url.path; params.body = request.body && request.body.toString(); try { header = this.computeHeader(params); } catch (e) { return done(e); } request.addHeader({ key: AUTHORIZATION, value: header, system: true }); return done(); } };
lib/authorizer/digest.js
var _ = require('lodash'), crypto = require('crypto-js'), urlEncoder = require('postman-url-encoder'), EMPTY = '', ONE = '00000001', DISABLE_RETRY_REQUEST = 'disableRetryRequest', WWW_AUTHENTICATE = 'www-authenticate', DIGEST_PREFIX = 'Digest ', QOP = 'qop', AUTH = 'auth', COLON = ':', QUOTE = '"', AUTH_INT = 'auth-int', AUTHORIZATION = 'Authorization', MD5_SESS = 'MD5-sess', ASCII_SOURCE = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', ASCII_SOURCE_LENGTH = ASCII_SOURCE.length, USERNAME_EQUALS_QUOTE = 'username="', REALM_EQUALS_QUOTE = 'realm="', NONCE_EQUALS_QUOTE = 'nonce="', URI_EQUALS_QUOTE = 'uri="', ALGORITHM_EQUALS_QUOTE = 'algorithm="', CNONCE_EQUALS_QUOTE = 'cnonce="', RESPONSE_EQUALS_QUOTE = 'response="', OPAQUE_EQUALS_QUOTE = 'opaque="', QOP_EQUALS = 'qop=', NC_EQUALS = 'nc=', AUTH_PARAMETERS = [ 'algorithm', 'username', 'realm', 'password', 'method', 'nonce', 'nonceCount', 'clientNonce', 'opaque', 'qop', 'uri' ], nonceRegex = /nonce="([^"]*)"/, realmRegex = /realm="([^"]*)"/, qopRegex = /qop="([^"]*)"/, opaqueRegex = /opaque="([^"]*)"/, _extractField; /** * Generates a random string of given length * * @todo Move this to util.js. After moving use that for hawk auth too * @param {Number} length */ function randomString (length) { length = length || 6; var result = [], i; for (i = 0; i < length; i++) { result[i] = ASCII_SOURCE[(Math.random() * ASCII_SOURCE_LENGTH) | 0]; } return result.join(EMPTY); } /** * Extracts a Digest Auth field from a WWW-Authenticate header value using a given regexp. * * @param {String} string * @param {RegExp} regexp * @private */ _extractField = function (string, regexp) { var match = string.match(regexp); return match ? match[1] : EMPTY; }; /** * Returns the 'www-authenticate' header for Digest auth. Since a server can suport more than more auth-scheme, * there can be more than one header with the same key. So need to loop over and check each one. * * @param {VariableList} headers * @private */ function _getDigestAuthHeader (headers) { return headers.find(function (property) { return (property.key.toLowerCase() === WWW_AUTHENTICATE) && (_.startsWith(property.value, DIGEST_PREFIX)); }); } /** * All the auth definition parameters excluding username and password should be stored and resued. * @todo The current implementation would fail for the case when two requests to two different hosts inherits the same * auth. In that case a retry would not be attempted for the second request (since all the parameters would be present * in the auth definition though invalid). * * @implements {AuthHandlerInterface} */ module.exports = { /** * @property {AuthHandlerInterface~AuthManifest} */ manifest: { info: { name: 'digest', version: '1.0.0' }, updates: [ { property: 'Authorization', type: 'header' }, { property: 'nonce', type: 'auth' }, { property: 'realm', type: 'auth' } ] }, /** * Initializes an item (extracts parameters from intermediate requests if any, etc) * before the actual authorization step. * * @param {AuthInterface} auth * @param {Response} response * @param {AuthHandlerInterface~authInitHookCallback} done */ init: function (auth, response, done) { done(null); }, /** * Checks whether the given item has all the required parameters in its request. * Sanitizes the auth parameters if needed. * * @param {AuthInterface} auth * @param {AuthHandlerInterface~authPreHookCallback} done */ pre: function (auth, done) { // ensure that all dynamic parameter values are present in the parameters // if even one is absent, we return false. done(null, Boolean(auth.get('nonce') && auth.get('realm'))); }, /** * Verifies whether the request was successfully authorized after being sent. * * @param {AuthInterface} auth * @param {Response} response * @param {AuthHandlerInterface~authPostHookCallback} done */ post: function (auth, response, done) { if (auth.get(DISABLE_RETRY_REQUEST) || !response) { return done(null, true); } var code, realm, nonce, qop, opaque, authHeader, authParams = {}; code = response.code; authHeader = _getDigestAuthHeader(response.headers); // If code is forbidden or unauthorized, and an auth header exists, // we can extract the realm & the nonce, and replay the request. // todo: add response.is4XX, response.is5XX, etc in the SDK. if ((code === 401 || code === 403) && authHeader) { nonce = _extractField(authHeader.value, nonceRegex); realm = _extractField(authHeader.value, realmRegex); qop = _extractField(authHeader.value, qopRegex); opaque = _extractField(authHeader.value, opaqueRegex); authParams.nonce = nonce; authParams.realm = realm; opaque && (authParams.opaque = opaque); qop && (authParams.qop = qop); if (authParams.qop || auth.get(QOP)) { authParams.clientNonce = randomString(8); authParams.nonceCount = ONE; } // if all the auth parameters sent by server were already present in auth definition then we do not retry if (_.every(authParams, function (value, key) { return auth.get(key); })) { return done(null, true); } auth.set(authParams); return done(null, false); } done(null, true); }, /** * Computes the Digest Authentication header from the given parameters. * * @param {Object} params * @param {String} params.algorithm * @param {String} params.username * @param {String} params.realm * @param {String} params.password * @param {String} params.method * @param {String} params.nonce * @param {String} params.nonceCount * @param {String} params.clientNonce * @param {String} params.opaque * @param {String} params.qop * @param {String} params.uri * @returns {String} */ computeHeader: function (params) { var algorithm = params.algorithm, username = params.username, realm = params.realm, password = params.password, method = params.method, nonce = params.nonce, nonceCount = params.nonceCount, clientNonce = params.clientNonce, opaque = params.opaque, qop = params.qop, uri = params.uri, // RFC defined terms, http://tools.ietf.org/html/rfc2617#section-3 A0, A1, A2, hashA1, hashA2, reqDigest, headerParams; if (algorithm === MD5_SESS) { A0 = crypto.MD5(username + COLON + realm + COLON + password).toString(); A1 = A0 + COLON + nonce + COLON + clientNonce; } else { A1 = username + COLON + realm + COLON + password; } if (qop === AUTH_INT) { A2 = method + COLON + uri + COLON + crypto.MD5(params.body); } else { A2 = method + COLON + uri; } hashA1 = crypto.MD5(A1).toString(); hashA2 = crypto.MD5(A2).toString(); if (qop === AUTH || qop === AUTH_INT) { reqDigest = crypto.MD5([hashA1, nonce, nonceCount, clientNonce, qop, hashA2].join(COLON)).toString(); } else { reqDigest = crypto.MD5([hashA1, nonce, hashA2].join(COLON)).toString(); } headerParams = [USERNAME_EQUALS_QUOTE + username + QUOTE, REALM_EQUALS_QUOTE + realm + QUOTE, NONCE_EQUALS_QUOTE + nonce + QUOTE, URI_EQUALS_QUOTE + uri + QUOTE ]; algorithm && headerParams.push(ALGORITHM_EQUALS_QUOTE + algorithm + QUOTE); if (qop === AUTH || qop === AUTH_INT) { headerParams.push(QOP_EQUALS + qop); } if (qop === AUTH || qop === AUTH_INT || algorithm === MD5_SESS) { nonceCount && headerParams.push(NC_EQUALS + nonceCount); headerParams.push(CNONCE_EQUALS_QUOTE + clientNonce + QUOTE); } headerParams.push(RESPONSE_EQUALS_QUOTE + reqDigest + QUOTE); opaque && headerParams.push(OPAQUE_EQUALS_QUOTE + opaque + QUOTE); return DIGEST_PREFIX + headerParams.join(', '); }, /** * Signs a request. * * @param {AuthInterface} auth * @param {Request} request * @param {AuthHandlerInterface~authSignHookCallback} done */ sign: function (auth, request, done) { var header, params = auth.get(AUTH_PARAMETERS), url = urlEncoder.toNodeUrl(request.url); if (!params.username || !params.realm) { return done(); // Nothing to do if required parameters are not present. } request.removeHeader(AUTHORIZATION, {ignoreCase: true}); params.method = request.method; params.uri = url.path; params.body = request.body && request.body.toString(); try { header = this.computeHeader(params); } catch (e) { return done(e); } request.addHeader({ key: AUTHORIZATION, value: header, system: true }); return done(); } };
Add support for SHA-256 algorithm in digest auth
lib/authorizer/digest.js
Add support for SHA-256 algorithm in digest auth
<ide><path>ib/authorizer/digest.js <ide> var _ = require('lodash'), <del> crypto = require('crypto-js'), <add> crypto = require('crypto'), <ide> urlEncoder = require('postman-url-encoder'), <ide> <ide> EMPTY = '', <ide> AUTH = 'auth', <ide> COLON = ':', <ide> QUOTE = '"', <add> SESS = '-sess', <ide> AUTH_INT = 'auth-int', <ide> AUTHORIZATION = 'Authorization', <ide> MD5_SESS = 'MD5-sess', <ide> OPAQUE_EQUALS_QUOTE = 'opaque="', <ide> QOP_EQUALS = 'qop=', <ide> NC_EQUALS = 'nc=', <add> ALGO = { <add> MD5: 'MD5', <add> MD5_SESS: 'MD5-sess', <add> SHA_256: 'SHA-256', <add> SHA_256_SESS: 'SHA-256-sess', <add> SHA_512_256: 'SHA-512-256', <add> SHA_512_256_SESS: 'SHA-512-256-sess' <add> }, <ide> AUTH_PARAMETERS = [ <ide> 'algorithm', <ide> 'username', <ide> }); <ide> } <ide> <add>/** <add> * Returns a function to calculate hash of data with given algorithm <add> * <add> * @param {String} algorithm hash algorithm <add> * @returns {Function} functiont that takes data as argument and returns its hash <add> */ <add>function getHashFunction (algorithm) { <add> return function (data) { <add> return crypto.createHash(algorithm).update(data || EMPTY).digest('hex'); <add> }; <add>} <ide> <ide> /** <ide> * All the auth definition parameters excluding username and password should be stored and resued. <ide> hashA1, <ide> hashA2, <ide> <add> hash, <ide> reqDigest, <ide> headerParams; <ide> <del> if (algorithm === MD5_SESS) { <del> A0 = crypto.MD5(username + COLON + realm + COLON + password).toString(); <add> switch (algorithm) { <add> case ALGO.SHA_256: <add> case ALGO.SHA_256_SESS: <add> hash = getHashFunction('sha256'); <add> break; <add> case ALGO.MD5: <add> case ALGO.MD5_SESS: <add> case undefined: <add> case null: <add> algorithm = algorithm || ALGO.MD5; <add> hash = getHashFunction('md5'); <add> break; <add> case ALGO.SHA_512_256: <add> case ALGO.SHA_512_256_SESS: <add> default: <add> // Current Electron version(7.2.3) in Postman app uses OpenSSL 1.1.0 <add> // which don't support `SHA-512-256`. <add> // @todo: change this when Electron is upgraded to a version which supports `SHA-512-256`. <add> throw new Error(`Unsupported digest algorithm: ${algorithm}`); <add> } <add> <add> if (_.endsWith(algorithm, SESS)) { <add> A0 = hash(username + COLON + realm + COLON + password); <ide> A1 = A0 + COLON + nonce + COLON + clientNonce; <ide> } <ide> else { <ide> } <ide> <ide> if (qop === AUTH_INT) { <del> A2 = method + COLON + uri + COLON + crypto.MD5(params.body); <add> A2 = method + COLON + uri + COLON + hash(params.body); <ide> } <ide> else { <ide> A2 = method + COLON + uri; <ide> } <del> hashA1 = crypto.MD5(A1).toString(); <del> hashA2 = crypto.MD5(A2).toString(); <add> hashA1 = hash(A1); <add> hashA2 = hash(A2); <ide> <ide> if (qop === AUTH || qop === AUTH_INT) { <del> reqDigest = crypto.MD5([hashA1, nonce, nonceCount, clientNonce, qop, hashA2].join(COLON)).toString(); <add> reqDigest = hash([hashA1, nonce, nonceCount, clientNonce, qop, hashA2].join(COLON)); <ide> } <ide> else { <del> reqDigest = crypto.MD5([hashA1, nonce, hashA2].join(COLON)).toString(); <add> reqDigest = hash([hashA1, nonce, hashA2].join(COLON)); <ide> } <ide> <ide> headerParams = [USERNAME_EQUALS_QUOTE + username + QUOTE,
Java
agpl-3.0
a702f7273a595e2036eeeefb2632054807de6b2a
0
B3Partners/flamingo,B3Partners/flamingo,flamingo-geocms/flamingo,flamingo-geocms/flamingo,mvdstruijk/flamingo,mvdstruijk/flamingo,B3Partners/flamingo,flamingo-geocms/flamingo,B3Partners/flamingo,mvdstruijk/flamingo,flamingo-geocms/flamingo,mvdstruijk/flamingo
/* * Copyright (C) 2013 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.viewer.util; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import nl.b3p.viewer.config.services.AttributeDescriptor; import nl.b3p.viewer.config.services.FeatureTypeRelation; import nl.b3p.viewer.config.services.FeatureTypeRelationKey; import nl.b3p.viewer.config.services.SimpleFeatureType; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.geotools.data.FeatureSource; import org.geotools.data.Query; import org.geotools.factory.CommonFactoryFinder; import org.geotools.feature.FeatureCollection; import org.geotools.feature.FeatureIterator; import org.geotools.filter.text.cql2.CQL; import org.geotools.filter.text.ecql.ECQL; import org.geotools.filter.visitor.DuplicatingFilterVisitor; import org.opengis.feature.simple.SimpleFeature; import org.opengis.filter.BinaryComparisonOperator; import org.opengis.filter.Filter; import org.opengis.filter.FilterFactory2; import org.opengis.filter.PropertyIsBetween; import org.opengis.filter.PropertyIsEqualTo; import org.opengis.filter.PropertyIsGreaterThan; import org.opengis.filter.PropertyIsGreaterThanOrEqualTo; import org.opengis.filter.PropertyIsLessThan; import org.opengis.filter.PropertyIsLessThanOrEqualTo; import org.opengis.filter.PropertyIsLike; import org.opengis.filter.PropertyIsNotEqualTo; import org.opengis.filter.expression.Expression; import org.opengis.filter.expression.PropertyName; /** * Class makes the filter valid according the given relation. * The parts of the filter that corresponds to the relation are replaced with a filter * with the result of the subquery. * @author Roy Braam */ public class ValidFilterExtractor extends DuplicatingFilterVisitor { private static final Log log = LogFactory.getLog(ValidFilterExtractor.class); private FeatureTypeRelation relation; public ValidFilterExtractor(FeatureTypeRelation relation) { this.relation = relation; } @Override public Object visit( PropertyIsBetween filter, Object data ) { List<Expression> expressions = new ArrayList<Expression>(); expressions.add(filter.getExpression()); expressions.add(filter.getLowerBoundary()); expressions.add(filter.getUpperBoundary()); Filter f = visit(expressions,filter,data); if (f==null){ return super.visit(filter, data); } return f; } @Override public Object visit( PropertyIsEqualTo filter, Object data ) { Filter f = visitAbstract(filter,data); if (f==null){ return super.visit(filter, data); } return f; } @Override public Object visit( PropertyIsNotEqualTo filter, Object data ) { Filter f = visitAbstract(filter,data); if (f==null){ return super.visit(filter, data); } return f; } @Override public Object visit( PropertyIsGreaterThan filter, Object data ) { Filter f = visitAbstract(filter,data); if (f==null){ return super.visit(filter, data); } return f; } @Override public Object visit( PropertyIsGreaterThanOrEqualTo filter, Object data ) { Filter f = visitAbstract(filter,data); if (f==null){ return super.visit(filter, data); } return f; } @Override public Object visit( PropertyIsLessThan filter, Object data ) { Filter f = visitAbstract(filter,data); if (f==null){ return super.visit(filter, data); } return f; } @Override public Object visit( PropertyIsLessThanOrEqualTo filter, Object data ) { Filter f = visitAbstract(filter,data); if (f==null){ return super.visit(filter, data); } return f; } @Override public Object visit( PropertyIsLike filter, Object data ) { List<Expression> expressions = new ArrayList<Expression>(); expressions.add(filter.getExpression()); Filter f = visit(expressions,filter,data); if (f==null){ return super.visit(filter, data); } return f; } private Filter visitAbstract(BinaryComparisonOperator bco, Object o) { List<Expression> expressions = new ArrayList<Expression>(); expressions.add(bco.getExpression1()); expressions.add(bco.getExpression2()); return visit(expressions,bco, o); } private Filter visit(List<Expression> expressions, Filter f,Object o) { List<String> propertyNames = new ArrayList<String>(); for (Expression exp : expressions){ if (exp instanceof PropertyName) { propertyNames.add(((PropertyName) exp).getPropertyName()); } } if (propertyNames.isEmpty()) { return null; } return doVisit(propertyNames, f, o); } /** * Do the real thing. * @param names List of names of the properties in the filter. * @param filter the filter * @param o * @return the new Filter. */ private Filter doVisit(List<String> names, Filter filter,Object o){ boolean found = false; SimpleFeatureType featureType = relation.getForeignFeatureType(); for (AttributeDescriptor ad : featureType.getAttributes()) { for (String propertyName : names){ if (propertyName.equals(ad.getName())) { found = true; break; } } if (found){ break; } } if (found) { try { FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(); FeatureSource fs = featureType.openGeoToolsFeatureSource(); Query q = new Query(fs.getName().toString()); q.setFilter(filter); HashMap<String, List<Filter>> orFilters = new HashMap<String, List<Filter>>(); //get propertynames needed. List<String> propertyNames = new ArrayList<String>(); for (FeatureTypeRelationKey key : relation.getRelationKeys()) { propertyNames.add(key.getRightSide().getName()); orFilters.put(key.getRightSide().getName(), new ArrayList<Filter>()); } q.setPropertyNames(propertyNames); FeatureCollection fc = fs.getFeatures(q); FeatureIterator<SimpleFeature> it = null; Map<String,List<Object>> inFilters = new HashMap<String,List<Object>>(); try { it = fc.features(); //walk the features, get the rightside values and create a list of filters (or) while (it.hasNext()) { SimpleFeature feature = it.next(); for (FeatureTypeRelationKey key : relation.getRelationKeys()) { Object value = feature.getAttribute(key.getRightSide().getName()); if (value == null) { continue; } Filter fil; if (AttributeDescriptor.GEOMETRY_TYPES.contains(key.getRightSide().getType()) && AttributeDescriptor.GEOMETRY_TYPES.contains(key.getLeftSide().getType())) { fil = ff.and(ff.not(ff.isNull(ff.property(key.getLeftSide().getName()))), ff.intersects(ff.property(key.getLeftSide().getName()), ff.literal(value))); orFilters.get(key.getRightSide().getName()).add(fil); } else { if(!inFilters.containsKey(key.getRightSide().getName())){ inFilters.put(key.getRightSide().getName(), new ArrayList<Object>()); } inFilters.get(key.getRightSide().getName()).add(value); } } } } finally { if (it != null) { it.close(); } fs.getDataStore().dispose(); } for (String propertyName : inFilters.keySet()) { List<Object> values = inFilters.get(propertyName); String filterString = propertyName + " IN "; String valueString = null; for (Object value : values) { if(valueString == null){ valueString = "("; }else{ valueString += ", "; } if (value instanceof String) { valueString += "'" + value + "'"; } else { valueString += value; } } valueString += ")"; Filter fil = ECQL.toFilter(filterString + valueString); orFilters.put(propertyName, Collections.singletonList(fil)); } //make or filters and add them to a list of and filters. List<Filter> andFilters = new ArrayList<Filter>(); for (FeatureTypeRelationKey key : relation.getRelationKeys()) { List<Filter> filters = orFilters.get(key.getRightSide().getName()); if (filters==null){ continue; } if (filters.size() == 1) { andFilters.add(filters.get(0)); } else if (filters.size() > 1) { andFilters.add(ff.or(filters)); } } if (andFilters.isEmpty()){ return Filter.EXCLUDE; } if (andFilters.size() == 1) { return andFilters.get(0); } else { return ff.and(andFilters); } } catch (Exception e) { log.error("Error while creating query: ",e); return null; } } else { return null; } } }
viewer/src/main/java/nl/b3p/viewer/util/ValidFilterExtractor.java
/* * Copyright (C) 2013 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.viewer.util; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import nl.b3p.viewer.config.services.AttributeDescriptor; import nl.b3p.viewer.config.services.FeatureTypeRelation; import nl.b3p.viewer.config.services.FeatureTypeRelationKey; import nl.b3p.viewer.config.services.SimpleFeatureType; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.geotools.data.FeatureSource; import org.geotools.data.Query; import org.geotools.factory.CommonFactoryFinder; import org.geotools.feature.FeatureCollection; import org.geotools.feature.FeatureIterator; import org.geotools.filter.text.cql2.CQL; import org.geotools.filter.text.ecql.ECQL; import org.geotools.filter.visitor.DuplicatingFilterVisitor; import org.opengis.feature.simple.SimpleFeature; import org.opengis.filter.BinaryComparisonOperator; import org.opengis.filter.Filter; import org.opengis.filter.FilterFactory2; import org.opengis.filter.PropertyIsBetween; import org.opengis.filter.PropertyIsEqualTo; import org.opengis.filter.PropertyIsGreaterThan; import org.opengis.filter.PropertyIsGreaterThanOrEqualTo; import org.opengis.filter.PropertyIsLessThan; import org.opengis.filter.PropertyIsLessThanOrEqualTo; import org.opengis.filter.PropertyIsLike; import org.opengis.filter.PropertyIsNotEqualTo; import org.opengis.filter.expression.Expression; import org.opengis.filter.expression.PropertyName; /** * Class makes the filter valid according the given relation. * The parts of the filter that corresponds to the relation are replaced with a filter * with the result of the subquery. * @author Roy Braam */ public class ValidFilterExtractor extends DuplicatingFilterVisitor { private static final Log log = LogFactory.getLog(ValidFilterExtractor.class); private FeatureTypeRelation relation; public ValidFilterExtractor(FeatureTypeRelation relation) { this.relation = relation; } @Override public Object visit( PropertyIsBetween filter, Object data ) { List<Expression> expressions = new ArrayList<Expression>(); expressions.add(filter.getExpression()); expressions.add(filter.getLowerBoundary()); expressions.add(filter.getUpperBoundary()); Filter f = visit(expressions,filter,data); if (f==null){ return super.visit(filter, data); } return f; } @Override public Object visit( PropertyIsEqualTo filter, Object data ) { Filter f = visitAbstract(filter,data); if (f==null){ return super.visit(filter, data); } return f; } @Override public Object visit( PropertyIsNotEqualTo filter, Object data ) { Filter f = visitAbstract(filter,data); if (f==null){ return super.visit(filter, data); } return f; } @Override public Object visit( PropertyIsGreaterThan filter, Object data ) { Filter f = visitAbstract(filter,data); if (f==null){ return super.visit(filter, data); } return f; } @Override public Object visit( PropertyIsGreaterThanOrEqualTo filter, Object data ) { Filter f = visitAbstract(filter,data); if (f==null){ return super.visit(filter, data); } return f; } @Override public Object visit( PropertyIsLessThan filter, Object data ) { Filter f = visitAbstract(filter,data); if (f==null){ return super.visit(filter, data); } return f; } @Override public Object visit( PropertyIsLessThanOrEqualTo filter, Object data ) { Filter f = visitAbstract(filter,data); if (f==null){ return super.visit(filter, data); } return f; } @Override public Object visit( PropertyIsLike filter, Object data ) { List<Expression> expressions = new ArrayList<Expression>(); expressions.add(filter.getExpression()); Filter f = visit(expressions,filter,data); if (f==null){ return super.visit(filter, data); } return f; } private Filter visitAbstract(BinaryComparisonOperator bco, Object o) { List<Expression> expressions = new ArrayList<Expression>(); expressions.add(bco.getExpression1()); expressions.add(bco.getExpression2()); return visit(expressions,bco, o); } private Filter visit(List<Expression> expressions, Filter f,Object o) { List<String> propertyNames = new ArrayList<String>(); for (Expression exp : expressions){ if (exp instanceof PropertyName) { propertyNames.add(((PropertyName) exp).getPropertyName()); } } if (propertyNames.isEmpty()) { return null; } return doVisit(propertyNames, f, o); } /** * Do the real thing. * @param names List of names of the properties in the filter. * @param filter the filter * @param o * @return the new Filter. */ private Filter doVisit(List<String> names, Filter filter,Object o){ boolean found = false; SimpleFeatureType featureType = relation.getForeignFeatureType(); for (AttributeDescriptor ad : featureType.getAttributes()) { for (String propertyName : names){ if (propertyName.equals(ad.getName())) { found = true; break; } } if (found){ break; } } if (found) { try { FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(); FeatureSource fs = featureType.openGeoToolsFeatureSource(); Query q = new Query(fs.getName().toString()); q.setFilter(filter); HashMap<String, List<Filter>> orFilters = new HashMap<String, List<Filter>>(); //get propertynames needed. List<String> propertyNames = new ArrayList<String>(); for (FeatureTypeRelationKey key : relation.getRelationKeys()) { propertyNames.add(key.getRightSide().getName()); orFilters.put(key.getRightSide().getName(), new ArrayList<Filter>()); } q.setPropertyNames(propertyNames); FeatureCollection fc = fs.getFeatures(q); FeatureIterator<SimpleFeature> it = null; Map<String,List<Object>> inFilters = new HashMap<String,List<Object>>(); try { it = fc.features(); //walk the features, get the rightside values and create a list of filters (or) while (it.hasNext()) { SimpleFeature feature = it.next(); for (FeatureTypeRelationKey key : relation.getRelationKeys()) { Object value = feature.getAttribute(key.getRightSide().getName()); if (value == null) { continue; } Filter fil; if (AttributeDescriptor.GEOMETRY_TYPES.contains(key.getRightSide().getType()) && AttributeDescriptor.GEOMETRY_TYPES.contains(key.getLeftSide().getType())) { fil = ff.and(ff.not(ff.isNull(ff.property(key.getLeftSide().getName()))), ff.intersects(ff.property(key.getLeftSide().getName()), ff.literal(value))); orFilters.get(key.getRightSide().getName()).add(fil); } else { if(!inFilters.containsKey(key.getRightSide().getName())){ inFilters.put(key.getRightSide().getName(), new ArrayList<Object>()); } inFilters.get(key.getRightSide().getName()).add(value); } } } } finally { if (it != null) { it.close(); } fs.getDataStore().dispose(); } for (String propertyName : inFilters.keySet()) { List<Object> values = inFilters.get(propertyName); String filterString = propertyName + " IN "; String valueString = null; for (Object value : values) { if(valueString == null){ valueString = "("; }else{ valueString += ", "; } valueString += value; } valueString += ")"; Filter fil = ECQL.toFilter(filterString + valueString); orFilters.put(propertyName, Collections.singletonList(fil)); } //make or filters and add them to a list of and filters. List<Filter> andFilters = new ArrayList<Filter>(); for (FeatureTypeRelationKey key : relation.getRelationKeys()) { List<Filter> filters = orFilters.get(key.getRightSide().getName()); if (filters==null){ continue; } if (filters.size() == 1) { andFilters.add(filters.get(0)); } else if (filters.size() > 1) { andFilters.add(ff.or(filters)); } } if (andFilters.isEmpty()){ return Filter.EXCLUDE; } if (andFilters.size() == 1) { return andFilters.get(0); } else { return ff.and(andFilters); } } catch (Exception e) { log.error("Error while creating query: ",e); return null; } } else { return null; } } }
escape string values in IN query
viewer/src/main/java/nl/b3p/viewer/util/ValidFilterExtractor.java
escape string values in IN query
<ide><path>iewer/src/main/java/nl/b3p/viewer/util/ValidFilterExtractor.java <ide> }else{ <ide> valueString += ", "; <ide> } <del> valueString += value; <add> if (value instanceof String) { <add> valueString += "'" + value + "'"; <add> } else { <add> valueString += value; <add> } <ide> } <ide> valueString += ")"; <ide>
Java
bsd-3-clause
1d2afd41c3b19fe7f21c115a54c04b01661409fb
0
Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.compositor.layouts.content; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.os.AsyncTask; import android.util.SparseArray; import android.view.View; import org.chromium.base.CalledByNative; import org.chromium.base.CommandLine; import org.chromium.base.JNINamespace; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.NativePage; import org.chromium.chrome.browser.Tab; import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.tabmodel.TabModelUtils; import org.chromium.ui.base.DeviceFormFactor; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; /** * The TabContentManager is responsible for serving tab contents to the UI components. Contents * could be live or static thumbnails. */ @JNINamespace("chrome::android") public class TabContentManager { private static final String THUMBNAIL_DIRECTORY = "textures"; private final Context mContext; private final ContentOffsetProvider mContentOffsetProvider; private File mThumbnailsDir; private float mThumbnailScale; private int mFullResThumbnailsMaxSize; private int[] mPriorityTabIds; private long mNativeTabContentManager; /** * A callback interface for decompressing the thumbnail for a tab into a bitmap. */ public static interface DecompressThumbnailCallback { /** * Called when the decompression finishes. * @param bitmap The {@link Bitmap} of the content. Null will be passed for failure. */ public void onFinishGetBitmap(Bitmap bitmap); } private final ArrayList<ThumbnailChangeListener> mListeners = new ArrayList<ThumbnailChangeListener>(); private final SparseArray<DecompressThumbnailCallback> mDecompressRequests = new SparseArray<TabContentManager.DecompressThumbnailCallback>(); private boolean mSnapshotsEnabled; private AsyncTask<Void, Void, Long> mNativeThumbnailCacheInitTask; /** * The Java interface for listening to thumbnail changes. */ public interface ThumbnailChangeListener { /** * @param id The tab id. */ public void onThumbnailChange(int id); } /** * @param context The context that this cache is created in. * @param resourceId The resource that this value might be defined in. * @param commandLineSwitch The switch for which we would like to extract value from. * @return the value of an integer resource. If the value is overridden on the command line * with the given switch, return the override instead. */ private static int getIntegerResourceWithOverride(Context context, int resourceId, String commandLineSwitch) { int val = context.getResources().getInteger(resourceId); String switchCount = CommandLine.getInstance().getSwitchValue(commandLineSwitch); if (switchCount != null) { int count = Integer.parseInt(switchCount); val = count; } return val; } /** * @param context The context that this cache is created in. * @param contentOffsetProvider The provider of content parameter. */ public TabContentManager(Context context, ContentOffsetProvider contentOffsetProvider, boolean snapshotsEnabled) { mContext = context; mContentOffsetProvider = contentOffsetProvider; mSnapshotsEnabled = snapshotsEnabled; mNativeTabContentManager = nativeInit(); startThumbnailCacheInitTask(); } /** * */ private void startThumbnailCacheInitTask() { mNativeThumbnailCacheInitTask = new AsyncTask<Void, Void, Long>() { @Override protected Long doInBackground(Void... unused) { mThumbnailsDir = mContext.getDir(THUMBNAIL_DIRECTORY, Context.MODE_PRIVATE); String diskCachePath = mThumbnailsDir.getAbsolutePath(); // Override the cache size on the command line with --thumbnails=100 int defaultCacheSize = getIntegerResourceWithOverride(mContext, R.integer.default_thumbnail_cache_size, ChromeSwitches.THUMBNAILS); mFullResThumbnailsMaxSize = defaultCacheSize; int compressionQueueMaxSize = mContext.getResources().getInteger( R.integer.default_compression_queue_size); int writeQueueMaxSize = mContext.getResources().getInteger( R.integer.default_write_queue_size); // Override the cache size on the command line with // --approximation-thumbnails=100 int approximationCacheSize = getIntegerResourceWithOverride(mContext, R.integer.default_approximation_thumbnail_cache_size, ChromeSwitches.APPROXIMATION_THUMBNAILS); float thumbnailScale = 1.f; boolean useApproximationThumbnails; float deviceDensity = mContext.getResources().getDisplayMetrics().density; if (DeviceFormFactor.isTablet(mContext)) { // Scale all tablets to MDPI. thumbnailScale = 1.f / deviceDensity; useApproximationThumbnails = false; } else { // For phones, reduce the amount of memory usage by capturing a lower-res // thumbnail for devices with resolution higher than HDPI (crbug.com/357740). if (deviceDensity > 1.5f) { thumbnailScale = 1.5f / deviceDensity; } useApproximationThumbnails = true; } mThumbnailScale = thumbnailScale; mPriorityTabIds = new int[mFullResThumbnailsMaxSize]; return nativeCreateThumbnailCache(diskCachePath, defaultCacheSize, approximationCacheSize, compressionQueueMaxSize, writeQueueMaxSize, useApproximationThumbnails); } @Override protected void onPostExecute(Long resultThumbnailCache) { if (resultThumbnailCache != 0) { if (mNativeTabContentManager != 0) { nativeSetThumbnailCache(mNativeTabContentManager, resultThumbnailCache); } else { nativeDestroyThumbnailCache(resultThumbnailCache); } } } }.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR); } /** * Destroy the native component. */ public void destroy() { if (mNativeTabContentManager != 0) { nativeDestroy(mNativeTabContentManager); mNativeTabContentManager = 0; } } @CalledByNative private long blockOnThumbnailCacheCreation() { try { return mNativeThumbnailCacheInitTask.get(); } catch (InterruptedException e) { } catch (ExecutionException e) { } return 0; } @CalledByNative private long getNativePtr() { return mNativeTabContentManager; } /** * Add a listener to thumbnail changes. * @param listener The listener of thumbnail change events. */ public void addThumbnailChangeListener(ThumbnailChangeListener listener) { if (!mListeners.contains(listener)) { mListeners.add(listener); } } /** * Remove a listener to thumbnail changes. * @param listener The listener of thumbnail change events. */ public void removeThumbnailChangeListener(ThumbnailChangeListener listener) { mListeners.remove(listener); } private Bitmap readbackNativePage(final Tab tab, float scale) { Bitmap bitmap = null; NativePage page = tab.getNativePage(); if (page == null) { return bitmap; } View viewToDraw = page.getView(); if (viewToDraw == null || viewToDraw.getWidth() == 0 || viewToDraw.getHeight() == 0) { return bitmap; } if (page instanceof InvalidationAwareThumbnailProvider) { if (!((InvalidationAwareThumbnailProvider) page).shouldCaptureThumbnail()) { return null; } } int overlayTranslateY = mContentOffsetProvider.getOverlayTranslateY(); try { bitmap = Bitmap.createBitmap( (int) (viewToDraw.getWidth() * mThumbnailScale), (int) ((viewToDraw.getHeight() - overlayTranslateY) * mThumbnailScale), Bitmap.Config.ARGB_8888); } catch (OutOfMemoryError ex) { return null; } Canvas c = new Canvas(bitmap); c.scale(scale, scale); c.translate(0.f, -overlayTranslateY); if (page instanceof InvalidationAwareThumbnailProvider) { ((InvalidationAwareThumbnailProvider) page).captureThumbnail(c); } else { viewToDraw.draw(c); } return bitmap; } /** * @param tabId The id of the {@link Tab} to check for a full sized thumbnail of. * @return Whether or not there is a full sized cached thumbnail for the {@link Tab} * identified by {@code tabId}. */ public boolean hasFullCachedThumbnail(int tabId) { if (mNativeTabContentManager == 0) return false; return nativeHasFullCachedThumbnail(mNativeTabContentManager, tabId); } /** * Cache the content of a tab as a thumbnail. * @param tab The tab whose content we will cache. */ public void cacheTabThumbnail(final Tab tab) { if (mNativeTabContentManager != 0 && mSnapshotsEnabled) { if (tab.getNativePage() != null) { Bitmap nativePageBitmap = readbackNativePage(tab, mThumbnailScale); if (nativePageBitmap == null) return; nativeCacheTabWithBitmap(mNativeTabContentManager, tab, nativePageBitmap, mThumbnailScale); nativePageBitmap.recycle(); } else { nativeCacheTab(mNativeTabContentManager, tab, tab.getContentViewCore(), mThumbnailScale); } } } /** * Send a request to thumbnail store to read and decompress the thumbnail for the given tab id. * @param tabId The tab id for which the thumbnail should be requested. * @param callback The callback to use when the thumbnail bitmap is decompressed and sent back. */ public void getThumbnailForId(int tabId, DecompressThumbnailCallback callback) { if (mNativeTabContentManager == 0) return; if (mDecompressRequests.get(tabId) != null) return; mDecompressRequests.put(tabId, callback); nativeGetDecompressedThumbnail(mNativeTabContentManager, tabId); } @CalledByNative private void notifyDecompressBitmapFinished(int tabId, Bitmap bitmap) { DecompressThumbnailCallback callback = mDecompressRequests.get(tabId); mDecompressRequests.remove(tabId); if (callback == null) return; callback.onFinishGetBitmap(bitmap); } /** * Invalidate a thumbnail if the content of the tab has been changed. * @param tabId The id of the {@link Tab} thumbnail to check. * @param url The current URL of the {@link Tab}. */ public void invalidateIfChanged(int tabId, String url) { if (mNativeTabContentManager != 0) { nativeInvalidateIfChanged(mNativeTabContentManager, tabId, url); } } /** * Invalidate a thumbnail of the tab whose id is |id|. * @param tabId The id of the {@link Tab} thumbnail to check. * @param url The current URL of the {@link Tab}. */ public void invalidateTabThumbnail(int id, String url) { invalidateIfChanged(id, url); } /** * Update the priority-ordered list of visible tabs. * @param priority The list of tab ids ordered in terms of priority. */ public void updateVisibleIds(List<Integer> priority) { if (mNativeTabContentManager != 0) { int idsSize = Math.min(mFullResThumbnailsMaxSize, priority.size()); if (idsSize != mPriorityTabIds.length) { mPriorityTabIds = new int[idsSize]; } for (int i = 0; i < idsSize; i++) { mPriorityTabIds[i] = priority.get(i); } nativeUpdateVisibleIds(mNativeTabContentManager, mPriorityTabIds); } } /** * Removes a thumbnail of the tab whose id is |tabId|. * @param tabId The Id of the tab whose thumbnail is being removed. */ public void removeTabThumbnail(int tabId) { if (mNativeTabContentManager != 0) { nativeRemoveTabThumbnail(mNativeTabContentManager, tabId); } } /** * Clean up any on-disk thumbnail at and above a given tab id. * @param minForbiddenId The Id by which all tab thumbnails with ids greater and equal to it * will be removed from disk. */ public void cleanupPersistentDataAtAndAboveId(int minForbiddenId) { if (mNativeTabContentManager != 0) { nativeRemoveTabThumbnailFromDiskAtAndAboveId(mNativeTabContentManager, minForbiddenId); } } /** * Remove on-disk thumbnails that are no longer needed. * @param modelSelector The selector that answers whether a tab is currently present. */ public void cleanupPersistentData(TabModelSelector modelSelector) { if (mNativeTabContentManager == 0) return; File[] files = mThumbnailsDir.listFiles(); if (files == null) return; for (File file : files) { try { int id = Integer.parseInt(file.getName()); if (TabModelUtils.getTabById(modelSelector.getModel(false), id) == null && TabModelUtils.getTabById(modelSelector.getModel(true), id) == null) { nativeRemoveTabThumbnail(mNativeTabContentManager, id); } } catch (NumberFormatException expected) { // This is an unknown file name, we'll leave it there. } } } /** * Set the UI resource provider to be used by this {@link TabContentManager} on the native side. * @param resourceProviderNativePtr The pointer to the UI resource provider to be used. */ public void setUIResourceProvider(long resourceProviderNativePtr) { if (mNativeTabContentManager == 0 || resourceProviderNativePtr == 0) return; nativeSetUIResourceProvider(mNativeTabContentManager, resourceProviderNativePtr); } @CalledByNative protected void notifyListenersOfThumbnailChange(int tabId) { for (ThumbnailChangeListener listener : mListeners) { listener.onThumbnailChange(tabId); } } // Class Object Methods private native long nativeInit(); private static native long nativeCreateThumbnailCache(String diskCachePath, int defaultCacheSize, int approximationCacheSize, int compressionQueueMaxSize, int writeQueueMaxSize, boolean useApproximationThumbnail); private static native void nativeDestroyThumbnailCache(long thumbnailCachePtr); private native void nativeSetThumbnailCache(long nativeTabContentManager, long thumbnailCachePtr); private native boolean nativeHasFullCachedThumbnail(long nativeTabContentManager, int tabId); private native void nativeCacheTab(long nativeTabContentManager, Object tab, Object contentViewCore, float thumbnailScale); private native void nativeCacheTabWithBitmap(long nativeTabContentManager, Object tab, Object bitmap, float thumbnailScale); private native void nativeInvalidateIfChanged(long nativeTabContentManager, int tabId, String url); private native void nativeUpdateVisibleIds(long nativeTabContentManager, int[] priority); private native void nativeRemoveTabThumbnail(long nativeTabContentManager, int tabId); private native void nativeRemoveTabThumbnailFromDiskAtAndAboveId(long nativeTabContentManager, int minForbiddenId); private native void nativeSetUIResourceProvider(long nativeTabContentManager, long resourceProviderNativePtr); private native void nativeGetDecompressedThumbnail(long nativeTabContentManager, int tabId); private static native void nativeDestroy(long nativeTabContentManager); }
chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/content/TabContentManager.java
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.compositor.layouts.content; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.os.AsyncTask; import android.util.SparseArray; import android.view.View; import org.chromium.base.CalledByNative; import org.chromium.base.CommandLine; import org.chromium.base.JNINamespace; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.NativePage; import org.chromium.chrome.browser.Tab; import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.tabmodel.TabModelUtils; import org.chromium.ui.base.DeviceFormFactor; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; /** * The TabContentManager is responsible for serving tab contents to the UI components. Contents * could be live or static thumbnails. */ @JNINamespace("chrome::android") public class TabContentManager { private static final String THUMBNAIL_DIRECTORY = "textures"; private final Context mContext; private final ContentOffsetProvider mContentOffsetProvider; private File mThumbnailsDir; private float mThumbnailScale; private int mFullResThumbnailsMaxSize; private int[] mPriorityTabIds; private long mNativeTabContentManager; /** * A callback interface for decompressing the thumbnail for a tab into a bitmap. */ public static interface DecompressThumbnailCallback { /** * Called when the decompression finishes. * @param bitmap The {@link Bitmap} of the content. Null will be passed for failure. */ public void onFinishGetBitmap(Bitmap bitmap); } private final ArrayList<ThumbnailChangeListener> mListeners = new ArrayList<ThumbnailChangeListener>(); private final SparseArray<DecompressThumbnailCallback> mDecompressRequests = new SparseArray<TabContentManager.DecompressThumbnailCallback>(); private boolean mSnapshotsEnabled; private AsyncTask<Void, Void, Long> mNativeThumbnailCacheInitTask; /** * The Java interface for listening to thumbnail changes. */ public interface ThumbnailChangeListener { /** * @param id The tab id. */ public void onThumbnailChange(int id); } /** * @param context The context that this cache is created in. * @param resourceId The resource that this value might be defined in. * @param commandLineSwitch The switch for which we would like to extract value from. * @return the value of an integer resource. If the value is overridden on the command line * with the given switch, return the override instead. */ private static int getIntegerResourceWithOverride(Context context, int resourceId, String commandLineSwitch) { int val = context.getResources().getInteger(resourceId); String switchCount = CommandLine.getInstance().getSwitchValue(commandLineSwitch); if (switchCount != null) { int count = Integer.parseInt(switchCount); val = count; } return val; } /** * @param context The context that this cache is created in. * @param contentOffsetProvider The provider of content parameter. */ public TabContentManager(Context context, ContentOffsetProvider contentOffsetProvider, boolean snapshotsEnabled) { mContext = context; mContentOffsetProvider = contentOffsetProvider; mSnapshotsEnabled = snapshotsEnabled; mNativeTabContentManager = nativeInit(); startThumbnailCacheInitTask(); } /** * */ private void startThumbnailCacheInitTask() { mNativeThumbnailCacheInitTask = new AsyncTask<Void, Void, Long>() { @Override protected Long doInBackground(Void... unused) { mThumbnailsDir = mContext.getDir(THUMBNAIL_DIRECTORY, Context.MODE_PRIVATE); String diskCachePath = mThumbnailsDir.getAbsolutePath(); // Override the cache size on the command line with --thumbnails=100 int defaultCacheSize = getIntegerResourceWithOverride(mContext, R.integer.default_thumbnail_cache_size, ChromeSwitches.THUMBNAILS); mFullResThumbnailsMaxSize = defaultCacheSize; int compressionQueueMaxSize = mContext.getResources().getInteger( R.integer.default_compression_queue_size); int writeQueueMaxSize = mContext.getResources().getInteger( R.integer.default_write_queue_size); // Override the cache size on the command line with // --approximation-thumbnails=100 int approximationCacheSize = getIntegerResourceWithOverride(mContext, R.integer.default_approximation_thumbnail_cache_size, ChromeSwitches.APPROXIMATION_THUMBNAILS); float thumbnailScale = 1.f; boolean useApproximationThumbnails; float deviceDensity = mContext.getResources().getDisplayMetrics().density; if (DeviceFormFactor.isTablet(mContext)) { // Scale all tablets to MDPI. thumbnailScale = 1.f / deviceDensity; useApproximationThumbnails = false; } else { // For phones, reduce the amount of memory usage by capturing a lower-res // thumbnail for devices with resolution higher than HDPI (crbug.com/357740). if (deviceDensity > 1.5f) { thumbnailScale = 1.5f / deviceDensity; } useApproximationThumbnails = true; } mThumbnailScale = thumbnailScale; mPriorityTabIds = new int[mFullResThumbnailsMaxSize]; return nativeCreateThumbnailCache(diskCachePath, defaultCacheSize, approximationCacheSize, compressionQueueMaxSize, writeQueueMaxSize, useApproximationThumbnails); } @Override protected void onPostExecute(Long resultThumbnailCache) { if (mNativeTabContentManager != 0) { nativeSetThumbnailCache(mNativeTabContentManager, resultThumbnailCache); } else { nativeDestroyThumbnailCache(resultThumbnailCache); } } }.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR); } /** * Destroy the native component. */ public void destroy() { if (mNativeTabContentManager != 0) { nativeDestroy(mNativeTabContentManager); mNativeTabContentManager = 0; } } @CalledByNative private long blockOnThumbnailCacheCreation() { try { return mNativeThumbnailCacheInitTask.get(); } catch (InterruptedException e) { } catch (ExecutionException e) { } return 0; } @CalledByNative private long getNativePtr() { return mNativeTabContentManager; } /** * Add a listener to thumbnail changes. * @param listener The listener of thumbnail change events. */ public void addThumbnailChangeListener(ThumbnailChangeListener listener) { if (!mListeners.contains(listener)) { mListeners.add(listener); } } /** * Remove a listener to thumbnail changes. * @param listener The listener of thumbnail change events. */ public void removeThumbnailChangeListener(ThumbnailChangeListener listener) { mListeners.remove(listener); } private Bitmap readbackNativePage(final Tab tab, float scale) { Bitmap bitmap = null; NativePage page = tab.getNativePage(); if (page == null) { return bitmap; } View viewToDraw = page.getView(); if (viewToDraw == null || viewToDraw.getWidth() == 0 || viewToDraw.getHeight() == 0) { return bitmap; } if (page instanceof InvalidationAwareThumbnailProvider) { if (!((InvalidationAwareThumbnailProvider) page).shouldCaptureThumbnail()) { return null; } } int overlayTranslateY = mContentOffsetProvider.getOverlayTranslateY(); try { bitmap = Bitmap.createBitmap( (int) (viewToDraw.getWidth() * mThumbnailScale), (int) ((viewToDraw.getHeight() - overlayTranslateY) * mThumbnailScale), Bitmap.Config.ARGB_8888); } catch (OutOfMemoryError ex) { return null; } Canvas c = new Canvas(bitmap); c.scale(scale, scale); c.translate(0.f, -overlayTranslateY); if (page instanceof InvalidationAwareThumbnailProvider) { ((InvalidationAwareThumbnailProvider) page).captureThumbnail(c); } else { viewToDraw.draw(c); } return bitmap; } /** * @param tabId The id of the {@link Tab} to check for a full sized thumbnail of. * @return Whether or not there is a full sized cached thumbnail for the {@link Tab} * identified by {@code tabId}. */ public boolean hasFullCachedThumbnail(int tabId) { if (mNativeTabContentManager == 0) return false; return nativeHasFullCachedThumbnail(mNativeTabContentManager, tabId); } /** * Cache the content of a tab as a thumbnail. * @param tab The tab whose content we will cache. */ public void cacheTabThumbnail(final Tab tab) { if (mNativeTabContentManager != 0 && mSnapshotsEnabled) { if (tab.getNativePage() != null) { Bitmap nativePageBitmap = readbackNativePage(tab, mThumbnailScale); if (nativePageBitmap == null) return; nativeCacheTabWithBitmap(mNativeTabContentManager, tab, nativePageBitmap, mThumbnailScale); nativePageBitmap.recycle(); } else { nativeCacheTab(mNativeTabContentManager, tab, tab.getContentViewCore(), mThumbnailScale); } } } /** * Send a request to thumbnail store to read and decompress the thumbnail for the given tab id. * @param tabId The tab id for which the thumbnail should be requested. * @param callback The callback to use when the thumbnail bitmap is decompressed and sent back. */ public void getThumbnailForId(int tabId, DecompressThumbnailCallback callback) { if (mNativeTabContentManager == 0) return; if (mDecompressRequests.get(tabId) != null) return; mDecompressRequests.put(tabId, callback); nativeGetDecompressedThumbnail(mNativeTabContentManager, tabId); } @CalledByNative private void notifyDecompressBitmapFinished(int tabId, Bitmap bitmap) { DecompressThumbnailCallback callback = mDecompressRequests.get(tabId); mDecompressRequests.remove(tabId); if (callback == null) return; callback.onFinishGetBitmap(bitmap); } /** * Invalidate a thumbnail if the content of the tab has been changed. * @param tabId The id of the {@link Tab} thumbnail to check. * @param url The current URL of the {@link Tab}. */ public void invalidateIfChanged(int tabId, String url) { if (mNativeTabContentManager != 0) { nativeInvalidateIfChanged(mNativeTabContentManager, tabId, url); } } /** * Invalidate a thumbnail of the tab whose id is |id|. * @param tabId The id of the {@link Tab} thumbnail to check. * @param url The current URL of the {@link Tab}. */ public void invalidateTabThumbnail(int id, String url) { invalidateIfChanged(id, url); } /** * Update the priority-ordered list of visible tabs. * @param priority The list of tab ids ordered in terms of priority. */ public void updateVisibleIds(List<Integer> priority) { if (mNativeTabContentManager != 0) { int idsSize = Math.min(mFullResThumbnailsMaxSize, priority.size()); if (idsSize != mPriorityTabIds.length) { mPriorityTabIds = new int[idsSize]; } for (int i = 0; i < idsSize; i++) { mPriorityTabIds[i] = priority.get(i); } nativeUpdateVisibleIds(mNativeTabContentManager, mPriorityTabIds); } } /** * Removes a thumbnail of the tab whose id is |tabId|. * @param tabId The Id of the tab whose thumbnail is being removed. */ public void removeTabThumbnail(int tabId) { if (mNativeTabContentManager != 0) { nativeRemoveTabThumbnail(mNativeTabContentManager, tabId); } } /** * Clean up any on-disk thumbnail at and above a given tab id. * @param minForbiddenId The Id by which all tab thumbnails with ids greater and equal to it * will be removed from disk. */ public void cleanupPersistentDataAtAndAboveId(int minForbiddenId) { if (mNativeTabContentManager != 0) { nativeRemoveTabThumbnailFromDiskAtAndAboveId(mNativeTabContentManager, minForbiddenId); } } /** * Remove on-disk thumbnails that are no longer needed. * @param modelSelector The selector that answers whether a tab is currently present. */ public void cleanupPersistentData(TabModelSelector modelSelector) { if (mNativeTabContentManager == 0) return; File[] files = mThumbnailsDir.listFiles(); if (files == null) return; for (File file : files) { try { int id = Integer.parseInt(file.getName()); if (TabModelUtils.getTabById(modelSelector.getModel(false), id) == null && TabModelUtils.getTabById(modelSelector.getModel(true), id) == null) { nativeRemoveTabThumbnail(mNativeTabContentManager, id); } } catch (NumberFormatException expected) { // This is an unknown file name, we'll leave it there. } } } /** * Set the UI resource provider to be used by this {@link TabContentManager} on the native side. * @param resourceProviderNativePtr The pointer to the UI resource provider to be used. */ public void setUIResourceProvider(long resourceProviderNativePtr) { if (mNativeTabContentManager == 0 || resourceProviderNativePtr == 0) return; nativeSetUIResourceProvider(mNativeTabContentManager, resourceProviderNativePtr); } @CalledByNative protected void notifyListenersOfThumbnailChange(int tabId) { for (ThumbnailChangeListener listener : mListeners) { listener.onThumbnailChange(tabId); } } // Class Object Methods private native long nativeInit(); private static native long nativeCreateThumbnailCache(String diskCachePath, int defaultCacheSize, int approximationCacheSize, int compressionQueueMaxSize, int writeQueueMaxSize, boolean useApproximationThumbnail); private static native void nativeDestroyThumbnailCache(long thumbnailCachePtr); private native void nativeSetThumbnailCache(long nativeTabContentManager, long thumbnailCachePtr); private native boolean nativeHasFullCachedThumbnail(long nativeTabContentManager, int tabId); private native void nativeCacheTab(long nativeTabContentManager, Object tab, Object contentViewCore, float thumbnailScale); private native void nativeCacheTabWithBitmap(long nativeTabContentManager, Object tab, Object bitmap, float thumbnailScale); private native void nativeInvalidateIfChanged(long nativeTabContentManager, int tabId, String url); private native void nativeUpdateVisibleIds(long nativeTabContentManager, int[] priority); private native void nativeRemoveTabThumbnail(long nativeTabContentManager, int tabId); private native void nativeRemoveTabThumbnailFromDiskAtAndAboveId(long nativeTabContentManager, int minForbiddenId); private native void nativeSetUIResourceProvider(long nativeTabContentManager, long resourceProviderNativePtr); private native void nativeGetDecompressedThumbnail(long nativeTabContentManager, int tabId); private static native void nativeDestroy(long nativeTabContentManager); }
Guard against null pointer ThumbnailCache being destroyed. BUG=490312 NOTRY=true NOPRESUBMIT=true Review URL: https://codereview.chromium.org/1161703002 Cr-Commit-Position: refs/heads/master@{#332231} (cherry picked from commit dcdece34e053fd1684cf5aeb41b5accb9106a033) Review URL: https://codereview.chromium.org/1158153004 Cr-Commit-Position: d34a0005849006230ae7ffb1a9693419810a06bc@{#188} Cr-Branched-From: 40cda19e609fd36fbf5fe489055423e611631abc@{#330231}
chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/content/TabContentManager.java
Guard against null pointer ThumbnailCache being destroyed.
<ide><path>hrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/content/TabContentManager.java <ide> <ide> @Override <ide> protected void onPostExecute(Long resultThumbnailCache) { <del> if (mNativeTabContentManager != 0) { <del> nativeSetThumbnailCache(mNativeTabContentManager, resultThumbnailCache); <del> } else { <del> nativeDestroyThumbnailCache(resultThumbnailCache); <add> if (resultThumbnailCache != 0) { <add> if (mNativeTabContentManager != 0) { <add> nativeSetThumbnailCache(mNativeTabContentManager, resultThumbnailCache); <add> } else { <add> nativeDestroyThumbnailCache(resultThumbnailCache); <add> } <ide> } <ide> } <ide> }.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
Java
apache-2.0
485c3eee174bf423a941ad83407d1236d9626620
0
fitermay/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,ernestp/consulo,ryano144/intellij-community,clumsy/intellij-community,kool79/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,clumsy/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,holmes/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,signed/intellij-community,dslomov/intellij-community,diorcety/intellij-community,holmes/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,allotria/intellij-community,hurricup/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,amith01994/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,consulo/consulo,amith01994/intellij-community,retomerz/intellij-community,ryano144/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,slisson/intellij-community,kdwink/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,petteyg/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,holmes/intellij-community,allotria/intellij-community,consulo/consulo,lucafavatella/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,supersven/intellij-community,apixandru/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,robovm/robovm-studio,xfournet/intellij-community,izonder/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,ernestp/consulo,ryano144/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,clumsy/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,holmes/intellij-community,kool79/intellij-community,fnouama/intellij-community,amith01994/intellij-community,apixandru/intellij-community,fitermay/intellij-community,vladmm/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,kdwink/intellij-community,adedayo/intellij-community,consulo/consulo,semonte/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,slisson/intellij-community,vladmm/intellij-community,signed/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,apixandru/intellij-community,allotria/intellij-community,izonder/intellij-community,gnuhub/intellij-community,holmes/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,kool79/intellij-community,hurricup/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,consulo/consulo,tmpgit/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,holmes/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,FHannes/intellij-community,clumsy/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,ibinti/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,holmes/intellij-community,slisson/intellij-community,kool79/intellij-community,asedunov/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,retomerz/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,consulo/consulo,ernestp/consulo,fnouama/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,dslomov/intellij-community,supersven/intellij-community,vladmm/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,fnouama/intellij-community,adedayo/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,petteyg/intellij-community,caot/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,allotria/intellij-community,jagguli/intellij-community,blademainer/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,signed/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,diorcety/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,kdwink/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,holmes/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,kool79/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,FHannes/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,amith01994/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,samthor/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,izonder/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,asedunov/intellij-community,ernestp/consulo,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,signed/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,signed/intellij-community,hurricup/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,signed/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,allotria/intellij-community,consulo/consulo,akosyakov/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,ibinti/intellij-community,izonder/intellij-community,robovm/robovm-studio,robovm/robovm-studio,semonte/intellij-community,semonte/intellij-community,samthor/intellij-community,samthor/intellij-community,petteyg/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,ernestp/consulo,ol-loginov/intellij-community,ibinti/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,caot/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,izonder/intellij-community,gnuhub/intellij-community,da1z/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,izonder/intellij-community,kool79/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,dslomov/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,kdwink/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,FHannes/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,fitermay/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,signed/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,asedunov/intellij-community,kdwink/intellij-community,ryano144/intellij-community,apixandru/intellij-community,caot/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,signed/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,izonder/intellij-community,orekyuu/intellij-community,izonder/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,da1z/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,samthor/intellij-community,apixandru/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,blademainer/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,da1z/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,amith01994/intellij-community,vladmm/intellij-community,dslomov/intellij-community,allotria/intellij-community,tmpgit/intellij-community,signed/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,ibinti/intellij-community,asedunov/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,caot/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,vladmm/intellij-community,signed/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,caot/intellij-community,semonte/intellij-community,FHannes/intellij-community,jagguli/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,blademainer/intellij-community,retomerz/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,caot/intellij-community,kool79/intellij-community,ernestp/consulo,ahb0327/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,da1z/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,signed/intellij-community,izonder/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,da1z/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,da1z/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,signed/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,signed/intellij-community,samthor/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,caot/intellij-community,xfournet/intellij-community,supersven/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,retomerz/intellij-community,retomerz/intellij-community,petteyg/intellij-community,vladmm/intellij-community,apixandru/intellij-community,kool79/intellij-community,semonte/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,slisson/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,samthor/intellij-community,youdonghai/intellij-community,holmes/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,da1z/intellij-community,asedunov/intellij-community,fitermay/intellij-community
package org.jetbrains.jps.incremental.storage; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.io.DataExternalizer; import com.intellij.util.io.IOUtil; import com.intellij.util.io.KeyDescriptor; import java.io.DataInput; import java.io.DataOutput; import java.io.File; import java.io.IOException; /** * @author Eugene Zhuravlev * Date: 10/7/11 */ public class TimestampStorage extends AbstractStateStorage<File, TimestampValidityState> implements Timestamps { public TimestampStorage(File storePath) throws IOException { super(storePath, new FileKeyDescriptor(), new StateExternalizer()); } @Override public void force() { super.force(); } @Override public void clean() throws IOException { super.clean(); } @Override public long getStamp(File file) throws IOException { final TimestampValidityState state = getState(file); return state != null? state.getTimestamp() : -1L; } @Override public void saveStamp(File file, long timestamp) throws IOException { update(file, new TimestampValidityState(timestamp)); } public void removeStamp(File file) throws IOException { remove(file); } private static class FileKeyDescriptor implements KeyDescriptor<File> { private final byte[] buffer = IOUtil.allocReadWriteUTFBuffer(); public void save(DataOutput out, File value) throws IOException { IOUtil.writeUTFFast(buffer, out, value.getPath()); } public File read(DataInput in) throws IOException { return new File(IOUtil.readUTFFast(buffer, in)); } public int getHashCode(File value) { return FileUtil.fileHashCode(value); } public boolean isEqual(File val1, File val2) { return FileUtil.filesEqual(val1, val2); } } private static class StateExternalizer implements DataExternalizer<TimestampValidityState> { public void save(DataOutput out, TimestampValidityState value) throws IOException { value.save(out); } public TimestampValidityState read(DataInput in) throws IOException { return new TimestampValidityState(in); } } }
jps/jps-builders/src/org/jetbrains/jps/incremental/storage/TimestampStorage.java
package org.jetbrains.jps.incremental.storage; import com.intellij.util.io.DataExternalizer; import com.intellij.util.io.IOUtil; import com.intellij.util.io.KeyDescriptor; import java.io.DataInput; import java.io.DataOutput; import java.io.File; import java.io.IOException; /** * @author Eugene Zhuravlev * Date: 10/7/11 */ public class TimestampStorage extends AbstractStateStorage<File, TimestampValidityState> implements Timestamps { public TimestampStorage(File storePath) throws IOException { super(storePath, new FileKeyDescriptor(), new StateExternalizer()); } @Override public void force() { super.force(); } @Override public void clean() throws IOException { super.clean(); } @Override public long getStamp(File file) throws IOException { final TimestampValidityState state = getState(file); return state != null? state.getTimestamp() : -1L; } @Override public void saveStamp(File file, long timestamp) throws IOException { update(file, new TimestampValidityState(timestamp)); } public void removeStamp(File file) throws IOException { remove(file); } private static class FileKeyDescriptor implements KeyDescriptor<File> { private final byte[] buffer = IOUtil.allocReadWriteUTFBuffer(); public void save(DataOutput out, File value) throws IOException { IOUtil.writeUTFFast(buffer, out, value.getPath()); } public File read(DataInput in) throws IOException { return new File(IOUtil.readUTFFast(buffer, in)); } public int getHashCode(File value) { return value.hashCode(); } public boolean isEqual(File val1, File val2) { return val1.equals(val2); } } private static class StateExternalizer implements DataExternalizer<TimestampValidityState> { public void save(DataOutput out, TimestampValidityState value) throws IOException { value.save(out); } public TimestampValidityState read(DataInput in) throws IOException { return new TimestampValidityState(in); } } }
compare files with FileUtil.filesEqual()
jps/jps-builders/src/org/jetbrains/jps/incremental/storage/TimestampStorage.java
compare files with FileUtil.filesEqual()
<ide><path>ps/jps-builders/src/org/jetbrains/jps/incremental/storage/TimestampStorage.java <ide> package org.jetbrains.jps.incremental.storage; <ide> <add>import com.intellij.openapi.util.io.FileUtil; <ide> import com.intellij.util.io.DataExternalizer; <ide> import com.intellij.util.io.IOUtil; <ide> import com.intellij.util.io.KeyDescriptor; <ide> } <ide> <ide> public int getHashCode(File value) { <del> return value.hashCode(); <add> return FileUtil.fileHashCode(value); <ide> } <ide> <ide> public boolean isEqual(File val1, File val2) { <del> return val1.equals(val2); <add> return FileUtil.filesEqual(val1, val2); <ide> } <ide> } <ide>
Java
apache-2.0
72ce86be128ae832da1316c0aaa1f246dfa8b67b
0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.scaling.core.job.preparer.splitter; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.apache.shardingsphere.infra.metadata.schema.model.TableMetaData; import org.apache.shardingsphere.scaling.core.common.datasource.DataSourceManager; import org.apache.shardingsphere.scaling.core.common.datasource.MetaDataManager; import org.apache.shardingsphere.scaling.core.common.exception.PrepareFailedException; import org.apache.shardingsphere.scaling.core.common.sqlbuilder.ScalingSQLBuilderFactory; import org.apache.shardingsphere.scaling.core.config.DumperConfiguration; import org.apache.shardingsphere.scaling.core.config.InventoryDumperConfiguration; import org.apache.shardingsphere.scaling.core.config.TaskConfiguration; import org.apache.shardingsphere.scaling.core.job.JobContext; import org.apache.shardingsphere.scaling.core.job.position.PlaceholderPosition; import org.apache.shardingsphere.scaling.core.job.position.PrimaryKeyPosition; import org.apache.shardingsphere.scaling.core.job.position.ScalingPosition; import org.apache.shardingsphere.scaling.core.job.task.ScalingTaskFactory; import org.apache.shardingsphere.scaling.core.job.task.inventory.InventoryTask; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; /** * Inventory data task splitter. */ @Slf4j public final class InventoryTaskSplitter { /** * Split inventory data to multi-tasks. * * @param jobContext job context * @param taskConfig task configuration * @param dataSourceManager data source manager * @return split inventory data task */ public List<InventoryTask> splitInventoryData(final JobContext jobContext, final TaskConfiguration taskConfig, final DataSourceManager dataSourceManager) { List<InventoryTask> result = new LinkedList<>(); for (InventoryDumperConfiguration each : splitDumperConfig(jobContext, taskConfig.getDumperConfig(), dataSourceManager)) { result.add(ScalingTaskFactory.createInventoryTask(each, taskConfig.getImporterConfig())); } return result; } private Collection<InventoryDumperConfiguration> splitDumperConfig( final JobContext jobContext, final DumperConfiguration dumperConfig, final DataSourceManager dataSourceManager) { Collection<InventoryDumperConfiguration> result = new LinkedList<>(); DataSource dataSource = dataSourceManager.getDataSource(dumperConfig.getDataSourceConfig()); MetaDataManager metaDataManager = new MetaDataManager(dataSource); for (InventoryDumperConfiguration each : splitByTable(dumperConfig)) { result.addAll(splitByPrimaryKey(jobContext, dataSource, metaDataManager, each)); } return result; } private Collection<InventoryDumperConfiguration> splitByTable(final DumperConfiguration dumperConfig) { Collection<InventoryDumperConfiguration> result = new LinkedList<>(); dumperConfig.getTableNameMap().forEach((key, value) -> { InventoryDumperConfiguration inventoryDumperConfig = new InventoryDumperConfiguration(dumperConfig); inventoryDumperConfig.setTableName(key); inventoryDumperConfig.setPosition(new PlaceholderPosition()); result.add(inventoryDumperConfig); }); return result; } private Collection<InventoryDumperConfiguration> splitByPrimaryKey( final JobContext jobContext, final DataSource dataSource, final MetaDataManager metaDataManager, final InventoryDumperConfiguration dumperConfig) { Collection<InventoryDumperConfiguration> result = new LinkedList<>(); Collection<ScalingPosition<?>> inventoryPositions = getInventoryPositions(jobContext, dumperConfig, dataSource, metaDataManager); int i = 0; for (ScalingPosition<?> inventoryPosition : inventoryPositions) { InventoryDumperConfiguration splitDumperConfig = new InventoryDumperConfiguration(dumperConfig); splitDumperConfig.setPosition(inventoryPosition); splitDumperConfig.setShardingItem(i++); splitDumperConfig.setTableName(dumperConfig.getTableName()); splitDumperConfig.setPrimaryKey(dumperConfig.getPrimaryKey()); result.add(splitDumperConfig); } return result; } private Collection<ScalingPosition<?>> getInventoryPositions( final JobContext jobContext, final InventoryDumperConfiguration dumperConfig, final DataSource dataSource, final MetaDataManager metaDataManager) { if (null != jobContext.getInitProgress()) { Collection<ScalingPosition<?>> result = jobContext.getInitProgress().getInventoryPosition(dumperConfig.getTableName()).values(); result.stream().findFirst().ifPresent(position -> { if (position instanceof PrimaryKeyPosition) { String primaryKey = metaDataManager.getTableMetaData(dumperConfig.getTableName()).getPrimaryKeyColumns().get(0); dumperConfig.setPrimaryKey(primaryKey); } }); return result; } if (isSpiltByPrimaryKeyRange(metaDataManager, dumperConfig.getTableName())) { String primaryKey = metaDataManager.getTableMetaData(dumperConfig.getTableName()).getPrimaryKeyColumns().get(0); dumperConfig.setPrimaryKey(primaryKey); return getPositionByPrimaryKeyRange(jobContext, dataSource, dumperConfig); } return Lists.newArrayList(new PlaceholderPosition()); } private boolean isSpiltByPrimaryKeyRange(final MetaDataManager metaDataManager, final String tableName) { TableMetaData tableMetaData = metaDataManager.getTableMetaData(tableName); if (null == tableMetaData) { log.warn("Can't split range for table {}, reason: can not get table metadata ", tableName); return false; } List<String> primaryKeys = tableMetaData.getPrimaryKeyColumns(); if (null == primaryKeys || primaryKeys.isEmpty()) { log.warn("Can't split range for table {}, reason: no primary key", tableName); return false; } if (primaryKeys.size() > 1) { log.warn("Can't split range for table {}, reason: primary key is union primary", tableName); return false; } int index = tableMetaData.findColumnIndex(primaryKeys.get(0)); if (isNotIntegerPrimary(tableMetaData.getColumnMetaData(index).getDataType())) { log.warn("Can't split range for table {}, reason: primary key is not integer number", tableName); return false; } return true; } private boolean isNotIntegerPrimary(final int columnType) { return Types.INTEGER != columnType && Types.BIGINT != columnType && Types.SMALLINT != columnType && Types.TINYINT != columnType; } private Collection<ScalingPosition<?>> getPositionByPrimaryKeyRange(final JobContext jobContext, final DataSource dataSource, final InventoryDumperConfiguration dumperConfig) { Collection<ScalingPosition<?>> result = new ArrayList<>(); String sql = ScalingSQLBuilderFactory.newInstance(jobContext.getJobConfig().getHandleConfig().getDatabaseType()) .buildSplitByPrimaryKeyRangeSQL(dumperConfig.getTableName(), dumperConfig.getPrimaryKey()); try (Connection connection = dataSource.getConnection(); PreparedStatement ps = connection.prepareStatement(sql)) { long beginId = 0; for (int i = 0; i < Integer.MAX_VALUE; i++) { ps.setLong(1, beginId); ps.setLong(2, jobContext.getJobConfig().getHandleConfig().getShardingSize()); try (ResultSet rs = ps.executeQuery()) { rs.next(); long endId = rs.getLong(1); if (endId == 0) { break; } result.add(new PrimaryKeyPosition(beginId, endId)); beginId = endId + 1; } } // fix empty table missing inventory task if (0 == result.size()) { result.add(new PrimaryKeyPosition(0, 0)); } } catch (final SQLException ex) { throw new PrepareFailedException(String.format("Split task for table %s by primary key %s error", dumperConfig.getTableName(), dumperConfig.getPrimaryKey()), ex); } return result; } }
shardingsphere-scaling/shardingsphere-scaling-core/src/main/java/org/apache/shardingsphere/scaling/core/job/preparer/splitter/InventoryTaskSplitter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.scaling.core.job.preparer.splitter; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.apache.shardingsphere.infra.metadata.schema.model.TableMetaData; import org.apache.shardingsphere.scaling.core.common.datasource.DataSourceManager; import org.apache.shardingsphere.scaling.core.common.datasource.MetaDataManager; import org.apache.shardingsphere.scaling.core.common.exception.PrepareFailedException; import org.apache.shardingsphere.scaling.core.common.sqlbuilder.ScalingSQLBuilderFactory; import org.apache.shardingsphere.scaling.core.config.DumperConfiguration; import org.apache.shardingsphere.scaling.core.config.InventoryDumperConfiguration; import org.apache.shardingsphere.scaling.core.config.TaskConfiguration; import org.apache.shardingsphere.scaling.core.job.JobContext; import org.apache.shardingsphere.scaling.core.job.position.PlaceholderPosition; import org.apache.shardingsphere.scaling.core.job.position.PrimaryKeyPosition; import org.apache.shardingsphere.scaling.core.job.position.ScalingPosition; import org.apache.shardingsphere.scaling.core.job.task.ScalingTaskFactory; import org.apache.shardingsphere.scaling.core.job.task.inventory.InventoryTask; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; /** * Inventory data task splitter. */ @Slf4j public final class InventoryTaskSplitter { /** * Split inventory data to multi-tasks. * * @param jobContext job context * @param taskConfig task configuration * @param dataSourceManager data source manager * @return split inventory data task */ public List<InventoryTask> splitInventoryData(final JobContext jobContext, final TaskConfiguration taskConfig, final DataSourceManager dataSourceManager) { List<InventoryTask> result = new LinkedList<>(); for (InventoryDumperConfiguration each : splitDumperConfig(jobContext, taskConfig.getDumperConfig(), dataSourceManager)) { result.add(ScalingTaskFactory.createInventoryTask(each, taskConfig.getImporterConfig())); } return result; } private Collection<InventoryDumperConfiguration> splitDumperConfig( final JobContext jobContext, final DumperConfiguration dumperConfig, final DataSourceManager dataSourceManager) { Collection<InventoryDumperConfiguration> result = new LinkedList<>(); DataSource dataSource = dataSourceManager.getDataSource(dumperConfig.getDataSourceConfig()); MetaDataManager metaDataManager = new MetaDataManager(dataSource); for (InventoryDumperConfiguration each : splitByTable(dumperConfig)) { result.addAll(splitByPrimaryKey(jobContext, dataSource, metaDataManager, each)); } return result; } private Collection<InventoryDumperConfiguration> splitByTable(final DumperConfiguration dumperConfig) { Collection<InventoryDumperConfiguration> result = new LinkedList<>(); dumperConfig.getTableNameMap().forEach((key, value) -> { InventoryDumperConfiguration inventoryDumperConfig = new InventoryDumperConfiguration(dumperConfig); inventoryDumperConfig.setTableName(key); inventoryDumperConfig.setPosition(new PlaceholderPosition()); result.add(inventoryDumperConfig); }); return result; } private Collection<InventoryDumperConfiguration> splitByPrimaryKey( final JobContext jobContext, final DataSource dataSource, final MetaDataManager metaDataManager, final InventoryDumperConfiguration dumperConfig) { Collection<InventoryDumperConfiguration> result = new LinkedList<>(); Collection<ScalingPosition<?>> inventoryPositions = getInventoryPositions(jobContext, dumperConfig, dataSource, metaDataManager); int i = 0; for (ScalingPosition<?> inventoryPosition : inventoryPositions) { InventoryDumperConfiguration splitDumperConfig = new InventoryDumperConfiguration(dumperConfig); splitDumperConfig.setPosition(inventoryPosition); splitDumperConfig.setShardingItem(i++); splitDumperConfig.setTableName(dumperConfig.getTableName()); splitDumperConfig.setPrimaryKey(dumperConfig.getPrimaryKey()); result.add(splitDumperConfig); } return result; } private Collection<ScalingPosition<?>> getInventoryPositions( final JobContext jobContext, final InventoryDumperConfiguration dumperConfig, final DataSource dataSource, final MetaDataManager metaDataManager) { if (null != jobContext.getInitProgress()) { return jobContext.getInitProgress().getInventoryPosition(dumperConfig.getTableName()).values(); } if (isSpiltByPrimaryKeyRange(metaDataManager, dumperConfig.getTableName())) { String primaryKey = metaDataManager.getTableMetaData(dumperConfig.getTableName()).getPrimaryKeyColumns().get(0); dumperConfig.setPrimaryKey(primaryKey); return getPositionByPrimaryKeyRange(jobContext, dataSource, dumperConfig); } return Lists.newArrayList(new PlaceholderPosition()); } private boolean isSpiltByPrimaryKeyRange(final MetaDataManager metaDataManager, final String tableName) { TableMetaData tableMetaData = metaDataManager.getTableMetaData(tableName); if (null == tableMetaData) { log.warn("Can't split range for table {}, reason: can not get table metadata ", tableName); return false; } List<String> primaryKeys = tableMetaData.getPrimaryKeyColumns(); if (null == primaryKeys || primaryKeys.isEmpty()) { log.warn("Can't split range for table {}, reason: no primary key", tableName); return false; } if (primaryKeys.size() > 1) { log.warn("Can't split range for table {}, reason: primary key is union primary", tableName); return false; } int index = tableMetaData.findColumnIndex(primaryKeys.get(0)); if (isNotIntegerPrimary(tableMetaData.getColumnMetaData(index).getDataType())) { log.warn("Can't split range for table {}, reason: primary key is not integer number", tableName); return false; } return true; } private boolean isNotIntegerPrimary(final int columnType) { return Types.INTEGER != columnType && Types.BIGINT != columnType && Types.SMALLINT != columnType && Types.TINYINT != columnType; } private Collection<ScalingPosition<?>> getPositionByPrimaryKeyRange(final JobContext jobContext, final DataSource dataSource, final InventoryDumperConfiguration dumperConfig) { Collection<ScalingPosition<?>> result = new ArrayList<>(); String sql = ScalingSQLBuilderFactory.newInstance(jobContext.getJobConfig().getHandleConfig().getDatabaseType()) .buildSplitByPrimaryKeyRangeSQL(dumperConfig.getTableName(), dumperConfig.getPrimaryKey()); try (Connection connection = dataSource.getConnection(); PreparedStatement ps = connection.prepareStatement(sql)) { long beginId = 0; for (int i = 0; i < Integer.MAX_VALUE; i++) { ps.setLong(1, beginId); ps.setLong(2, jobContext.getJobConfig().getHandleConfig().getShardingSize()); try (ResultSet rs = ps.executeQuery()) { rs.next(); long endId = rs.getLong(1); if (endId == 0) { break; } result.add(new PrimaryKeyPosition(beginId, endId)); beginId = endId + 1; } } // fix empty table missing inventory task if (0 == result.size()) { result.add(new PrimaryKeyPosition(0, 0)); } } catch (final SQLException ex) { throw new PrepareFailedException(String.format("Split task for table %s by primary key %s error", dumperConfig.getTableName(), dumperConfig.getPrimaryKey()), ex); } return result; } }
Fix scaling breakpoint sync (#11244)
shardingsphere-scaling/shardingsphere-scaling-core/src/main/java/org/apache/shardingsphere/scaling/core/job/preparer/splitter/InventoryTaskSplitter.java
Fix scaling breakpoint sync (#11244)
<ide><path>hardingsphere-scaling/shardingsphere-scaling-core/src/main/java/org/apache/shardingsphere/scaling/core/job/preparer/splitter/InventoryTaskSplitter.java <ide> private Collection<ScalingPosition<?>> getInventoryPositions( <ide> final JobContext jobContext, final InventoryDumperConfiguration dumperConfig, final DataSource dataSource, final MetaDataManager metaDataManager) { <ide> if (null != jobContext.getInitProgress()) { <del> return jobContext.getInitProgress().getInventoryPosition(dumperConfig.getTableName()).values(); <add> Collection<ScalingPosition<?>> result = jobContext.getInitProgress().getInventoryPosition(dumperConfig.getTableName()).values(); <add> result.stream().findFirst().ifPresent(position -> { <add> if (position instanceof PrimaryKeyPosition) { <add> String primaryKey = metaDataManager.getTableMetaData(dumperConfig.getTableName()).getPrimaryKeyColumns().get(0); <add> dumperConfig.setPrimaryKey(primaryKey); <add> } <add> }); <add> return result; <ide> } <ide> if (isSpiltByPrimaryKeyRange(metaDataManager, dumperConfig.getTableName())) { <ide> String primaryKey = metaDataManager.getTableMetaData(dumperConfig.getTableName()).getPrimaryKeyColumns().get(0);
Java
epl-1.0
3bf2497ed15742f0d91c58245507d4a7931b260f
0
edgware/edgware,edgware/edgware,acshea/edgware,edgware/edgware,edgware/edgware,acshea/edgware,acshea/edgware,acshea/edgware
/* * Licensed Materials - Property of IBM * * (C) Copyright IBM Corp. 2009, 2014 * * LICENSE: Eclipse Public License v1.0 * http://www.eclipse.org/legal/epl-v10.html */ package fabric.registry.trigger; import java.util.Arrays; import java.util.List; import fabric.Fabric; /** * Class that manages a Fabric Connection used by the Java UDF. */ public class ResourceManager { /** Copyright notice. */ public static final String copyrightNotice = "(C) Copyright IBM Corp. 2009, 2014"; /* * Class constants */ /* The reporting levels for Registry notification messages */ public static final int REPORT_NONE = 0; public static final int REPORT_LIST = 1; public static final int REPORT_ALL = 2; /* * Class static fields */ private static ResourceManager instance = null; /** Flag indicating if debug messages are to be sent to standard output. */ private static int debug = -1; /** Flag indicating if triggers are active (set from the FABRIC_TRIGGERS environment variable). */ private static boolean fireTriggers = true; /** The list of reportable tables. */ private List<String> reportableTableList = null; /* * Class fields */ /** Manages the connection to the Fabric, used to distribute notification messages. */ private FabricConnection fabricConnection = null; /** The reporting level for Registry notification messages (from the "registry.feed.level" configuration property). */ private int reportLevel = REPORT_LIST; /* * Class methods */ private ResourceManager() { /* Determine if triggers should be active */ String fabricTriggers = System.getenv("FABRIC_TRIGGERS"); fireTriggers = (fabricTriggers != null) ? Boolean.parseBoolean(fabricTriggers) : true; if (!fireTriggers) { System.out.println("Fabric triggers disabled."); } } /** * Get the single instance of the ResourceManager which will connect to the local Fabric node. * * @return the instance. */ public synchronized static ResourceManager getInstance() { if (instance == null) { instance = new ResourceManager(); instance.init(); } return instance; } /** * Initialise the Fabric connection and open a channel. */ private void init() { final ResourceManager resourceManager = this; if (fireTriggers) { /* Start the thread handling Fabric I/O and wait for it to initialise */ fabricConnection = new FabricConnection(); fabricConnection.start(); /* Determine what level of reporting is configured */ Fabric fabric = new Fabric(); fabric.initFabricConfig(); String triggerLevel = fabric.config("registry.notifications.level", "ALL").toUpperCase(); switch (triggerLevel) { case "ALL": reportLevel = REPORT_ALL; System.out.println("Fabric triggers will be sent for all tables"); break; case "NONE": reportLevel = REPORT_NONE; System.out.println("Fabric triggers will be sent for no tables"); break; default: /* Specific tables encoded into the level */ String[] reportableTables = triggerLevel.split(","); reportableTableList = Arrays.asList(reportableTables); System.out.println("Fabric triggers will be sent for " + reportableTables.length + " tables: " + triggerLevel); reportLevel = REPORT_LIST; } } } /** * Answers <code>true</code> if changes to the specified table are reportable, <code>false</code> otherwise. * * @param table * the table to check. * * @return the reportability status. */ public boolean isReportable(String table) { boolean isReportable = false; if (fireTriggers) { switch (reportLevel) { case REPORT_NONE: break; case REPORT_ALL: isReportable = true; break; case REPORT_LIST: table = table.toUpperCase(); if (reportableTableList != null && reportableTableList.contains(table)) { isReportable = true; } break; } } return isReportable; } /** * Publishes a Registry notification to the Fabric. * * @param updateMessage * the Registry update notification message. * * @throws Exception * thrown if the message cannot be sent. */ public void sendRegistryUpdate(String updateMessage) throws Exception { if (fireTriggers) { debug(updateMessage); fabricConnection.sendRegistryUpdate(updateMessage); } } /** * Simple, configurable debug; if the environment variable <code>FABRIC_DEBUG</code> is set to <code>true</code> * then debug messages will be sent to standard output. * * @param message * the debug message. */ public static void debug(String message) { if (debug == -1) { String doDebug = System.getenv("FABRIC_DEBUG"); if (doDebug != null && doDebug.equals("true")) { debug = 1; } else { debug = 0; } } if (debug == 1) { System.out.println(message); } } }
fabric.registry.monitor/src/fabric/registry/trigger/ResourceManager.java
/* * Licensed Materials - Property of IBM * * (C) Copyright IBM Corp. 2009, 2014 * * LICENSE: Eclipse Public License v1.0 * http://www.eclipse.org/legal/epl-v10.html */ package fabric.registry.trigger; import java.util.Arrays; import java.util.List; import fabric.Fabric; /** * Class that manages a Fabric Connection used by the Java UDF. */ public class ResourceManager { /** Copyright notice. */ public static final String copyrightNotice = "(C) Copyright IBM Corp. 2009, 2014"; /* * Class constants */ /* The reporting levels for Registry notification messages */ public static final int REPORT_NONE = 0; public static final int REPORT_LIST = 1; public static final int REPORT_ALL = 2; /* * Class static fields */ private static ResourceManager instance = null; /** Flag indicating if debug messages are to be sent to standard output. */ private static int debug = -1; /** Flag indicating if triggers are active (set from the FABRIC_TRIGGERS environment variable). */ private static boolean fireTriggers = true; /** The list of reportable tables. */ private List<String> reportableTableList = null; /* * Class fields */ /** Manages the connection to the Fabric, used to distribute notification messages. */ private FabricConnection fabricConnection = null; /** The reporting level for Registry notification messages (from the "registry.feed.level" configuration property). */ private int reportLevel = REPORT_LIST; /* * Class methods */ private ResourceManager() { /* Determine if triggers should be active */ String fabricTriggers = System.getenv("FABRIC_TRIGGERS"); fireTriggers = (fabricTriggers != null) ? Boolean.parseBoolean(fabricTriggers) : true; if (!fireTriggers) { System.out.println("Fabric triggers disabled."); } } /** * Get the single instance of the ResourceManager which will connect to the local Fabric node. * * @return the instance. */ public synchronized static ResourceManager getInstance() { if (instance == null) { instance = new ResourceManager(); instance.init(); } return instance; } /** * Initialise the Fabric connection and open a channel. */ private void init() { final ResourceManager resourceManager = this; if (fireTriggers) { /* Start the thread handling Fabric I/O and wait for it to initialise */ fabricConnection = new FabricConnection(); fabricConnection.start(); /* Determine what level of reporting is configured */ Fabric fabric = new Fabric(); fabric.initFabricConfig(); String feedLevel = fabric.config("registry.notifications.level"); feedLevel = (feedLevel != null) ? feedLevel.toUpperCase() : "ALL"; switch (feedLevel) { case "ALL": reportLevel = REPORT_ALL; System.out.println("Fabric triggers will be sent for all tables"); break; case "NONE": reportLevel = REPORT_NONE; System.out.println("Fabric triggers will be sent for no tables"); break; default: /* Specific tables encoded into the level */ String[] reportableTables = feedLevel.split(","); reportableTableList = Arrays.asList(reportableTables); StringBuilder message = new StringBuilder(); for (int r = 0; r < reportableTables.length; r++) { message.append(reportableTables[r]); if (r < reportableTables.length - 1) { message.append(", "); } } System.out.println("Fabric triggers will be sent for " + reportableTables.length + " tables: " + message.toString()); reportLevel = REPORT_LIST; } } } /** * Answers <code>true</code> if changes to the specified table are reportable, <code>false</code> otherwise. * * @param table * the table to check. * * @return the reportability status. */ public boolean isReportable(String table) { boolean isReportable = false; if (fireTriggers) { switch (reportLevel) { case REPORT_NONE: break; case REPORT_ALL: isReportable = true; break; case REPORT_LIST: table = table.toUpperCase(); if (reportableTableList.contains(table)) { isReportable = true; } break; } } return isReportable; } /** * Publishes a Registry notification to the Fabric. * * @param updateMessage * the Registry update notification message. * * @throws Exception * thrown if the message cannot be sent. */ public void sendRegistryUpdate(String updateMessage) throws Exception { if (fireTriggers) { debug(updateMessage); fabricConnection.sendRegistryUpdate(updateMessage); } } /** * Simple, configurable debug; if the environment variable <code>FABRIC_DEBUG</code> is set to <code>true</code> * then debug messages will be sent to standard output. * * @param message * the debug message. */ public static void debug(String message) { if (debug == -1) { String doDebug = System.getenv("FABRIC_DEBUG"); if (doDebug != null && doDebug.equals("true")) { debug = 1; } else { debug = 0; } } if (debug == 1) { System.out.println(message); } } }
Cleanup handling of trigger table configuration.
fabric.registry.monitor/src/fabric/registry/trigger/ResourceManager.java
Cleanup handling of trigger table configuration.
<ide><path>abric.registry.monitor/src/fabric/registry/trigger/ResourceManager.java <ide> /* Determine what level of reporting is configured */ <ide> Fabric fabric = new Fabric(); <ide> fabric.initFabricConfig(); <del> String feedLevel = fabric.config("registry.notifications.level"); <del> feedLevel = (feedLevel != null) ? feedLevel.toUpperCase() : "ALL"; <del> <del> switch (feedLevel) { <add> String triggerLevel = fabric.config("registry.notifications.level", "ALL").toUpperCase(); <add> <add> switch (triggerLevel) { <ide> <ide> case "ALL": <ide> <ide> default: <ide> <ide> /* Specific tables encoded into the level */ <del> String[] reportableTables = feedLevel.split(","); <add> String[] reportableTables = triggerLevel.split(","); <ide> reportableTableList = Arrays.asList(reportableTables); <del> <del> StringBuilder message = new StringBuilder(); <del> for (int r = 0; r < reportableTables.length; r++) { <del> message.append(reportableTables[r]); <del> if (r < reportableTables.length - 1) { <del> message.append(", "); <del> } <del> } <ide> System.out.println("Fabric triggers will be sent for " + reportableTables.length + " tables: " <del> + message.toString()); <add> + triggerLevel); <ide> reportLevel = REPORT_LIST; <ide> } <ide> } <ide> <ide> table = table.toUpperCase(); <ide> <del> if (reportableTableList.contains(table)) { <add> if (reportableTableList != null && reportableTableList.contains(table)) { <ide> isReportable = true; <ide> } <ide>
JavaScript
mit
cb0903098fb02f044eae752f3c0aaabcbbd96b14
0
t-kelly/slate,t-kelly/slate
var pkg = require('../../package.json'); var utils = require('./utilities.js'); /** * slate-cli configuration object * ## Markdown stuff * * It's a big description written in `markdown` * * Example: * * ```javascript * $('something') * .something(else); * ``` * * @namespace config * @memberof slate-cli * @summary Configuring slate-cli * @prop {String} storeURL - the url to your store * @prop {String} zipFileName - the filename to use for your zip file (set from package.json) by default * @prop {String} environment - development | staging | production * @prop {Object} paths - paths to various files & directories * @prop {Object} plugins - configuration objects passed to various plugins used in the task interface */ /** * ## File Paths * * It's a big description written in `markdown` * * Example: * * ```javascript * $('something') * .something(else); * ``` * * @member {Object} paths * @memberof slate-cli.config */ /** * ## Plugin Configuration * * It's a big description written in `markdown` * * Example: * * ```javascript * $('something') * .something(else); * ``` * @member {Object} plugins * @memberof slate-cli.config */ var config = { storeURI: 'https://themes.shopify.com/services/internal/themes/' + pkg.name + '/edit', zipFileName: pkg.name + '.zip', environment: 'development', paths: { srcScss: 'src/stylesheets/**/*.*', srcJs: 'src/scripts/**/*.*', srcIcons: 'src/icons/**/*.svg', srcBase: 'src/', srcAssets: [ 'src/assets/*.*', 'src/templates/**/*.*', 'src/snippets/*.*', 'src/locales/*.*', 'src/config/*.*', 'src/layout/*.*', 'src/sections/*.*' ], yamlConfig: 'config.yml', parentIncludeScss: [ 'src/stylesheets/[^_]*.*' ], parentIncludeJs: [ 'src/scripts/[^_]*.*' ], scss: 'src/stylesheets/**/*.{scss, scss.liquid}', images: 'src/images/*.{png,jpg,gif}', destAssets: 'dist/assets', destSnippets: 'dist/snippets', deployLog: 'deploy.log', dist: 'dist/' }, plugins: { cheerio: {run: utils.processSvg}, svgmin: { plugins: [{removeTitle: true}, {removeDesc: true}] } } }; module.exports = config;
tasks/reqs/config.js
var pkg = require('../../package.json'); var utils = require('./utilities.js'); /** * slate-cli configuration object * ## Markdown stuff * * It's a big description written in `markdown` * * Example: * * ```javascript * $('something') * .something(else); * ``` * * @namespace config * @memberof slate-cli * @summary Configuring slate-cli * @prop {String} storeURL - the url to your store * @prop {String} zipFileName - the filename to use for your zip file (set from package.json) by default * @prop {String} environment - development | staging | production * @prop {Object} paths - paths to various files & directories * @prop {Object} plugins - configuration objects passed to various plugins used in the task interface */ /** * ## File Paths * * It's a big description written in `markdown` * * Example: * * ```javascript * $('something') * .something(else); * ``` * * @member {Object} paths * @memberof slate-cli.config */ /** * ## Plugin Configuration * * It's a big description written in `markdown` * * Example: * * ```javascript * $('something') * .something(else); * ``` * @member {Object} plugins * @memberof slate-cli.config */ var config = { storeURI: 'https://themes.shopify.com/services/internal/themes/' + pkg.name + '/edit', zipFileName: pkg.name + '.zip', environment: 'development', paths: { srcScss: 'src/stylesheets/**/*.*', srcJs: 'src/scripts/**/*.*', srcIcons: 'src/icons/**/*.svg', srcBase: 'src/', srcAssets: [ 'src/assets/*.*', 'src/templates/**/*.*', 'src/snippets/*.*', 'src/locales/*.*', 'src/config/*.*', 'src/layout/*.*', 'src/sections/*.*' ], yamlConfig: 'config.yml', parentIncludeScss: [ 'src/stylesheets/[^_]*.*' ], parentIncludeJs: [ 'src/scripts/[^_]*.*' ], scss: 'src/stylesheets/**/*.scss', images: 'src/images/*.{png,jpg,gif}', destAssets: 'dist/assets', destSnippets: 'dist/snippets', deployLog: 'deploy.log', dist: 'dist/' }, plugins: { cheerio: {run: utils.processSvg}, svgmin: { plugins: [{removeTitle: true}, {removeDesc: true}] } } }; module.exports = config;
Add 'scss.liquid' files to watch
tasks/reqs/config.js
Add 'scss.liquid' files to watch
<ide><path>asks/reqs/config.js <ide> parentIncludeJs: [ <ide> 'src/scripts/[^_]*.*' <ide> ], <del> scss: 'src/stylesheets/**/*.scss', <add> scss: 'src/stylesheets/**/*.{scss, scss.liquid}', <ide> images: 'src/images/*.{png,jpg,gif}', <ide> destAssets: 'dist/assets', <ide> destSnippets: 'dist/snippets',
Java
apache-2.0
b48d72ae37540d4c4c1e553ae97e70042184725a
0
dimagi/commcare,dimagi/commcare-core,dimagi/commcare-core,dimagi/commcare,dimagi/commcare,dimagi/commcare-core
package org.javarosa.core.model; import org.javarosa.core.model.instance.TreeReference; import java.util.Vector; /** * A Form Index is an immutable index into a specific question definition that * will appear in an interaction with a user. * * An index is represented by different levels into hierarchical groups. * * Indices can represent both questions and groups. * * It is absolutely essential that there be no circularity of reference in * FormIndex's, IE, no form index's ancestor can be itself. * * Datatype Productions: * FormIndex = BOF | EOF | CompoundIndex(nextIndex:FormIndex,Location) * Location = Empty | Simple(localLevel:int) | WithMult(localLevel:int, multiplicity:int) * * @author Clayton Sims */ public class FormIndex { private boolean beginningOfForm = false; private boolean endOfForm = false; /** * The index of the questiondef in the current context */ private int localIndex; /** * The multiplicity of the current instance of a repeated question or group */ private int instanceIndex = -1; /** * The next level of this index */ private FormIndex nextLevel; private TreeReference reference; public static FormIndex createBeginningOfFormIndex() { FormIndex begin = new FormIndex(-1, null); begin.beginningOfForm = true; return begin; } public static FormIndex createEndOfFormIndex() { FormIndex end = new FormIndex(-1, null); end.endOfForm = true; return end; } /** * Constructs a simple form index that references a specific element in * a list of elements. * * @param localIndex An integer index into a flat list of elements * @param reference A reference to the instance element identified by this index; */ public FormIndex(int localIndex, TreeReference reference) { this.localIndex = localIndex; this.reference = reference; } /** * Constructs a simple form index that references a specific element in * a list of elements. * * @param localIndex An integer index into a flat list of elements * @param instanceIndex An integer index expressing the multiplicity * of the current level * @param reference A reference to the instance element identified by this index; */ public FormIndex(int localIndex, int instanceIndex, TreeReference reference) { this.localIndex = localIndex; this.instanceIndex = instanceIndex; this.reference = reference; } /** * Constructs an index which indexes an element, and provides an index * into that elements children * * @param nextLevel An index into the referenced element's index * @param localIndex An index to an element at the current level, a child * element of which will be referenced by the nextLevel index. * @param reference A reference to the instance element identified by this index; */ public FormIndex(FormIndex nextLevel, int localIndex, TreeReference reference) { this(localIndex, reference); this.nextLevel = nextLevel; } /** * Constructs an index which references an element past the level of * specificity of the current context, founded by the currentLevel * index. * (currentLevel, (nextLevel...)) */ public FormIndex(FormIndex nextLevel, FormIndex currentLevel) { if (currentLevel == null) { this.nextLevel = nextLevel.nextLevel; this.localIndex = nextLevel.localIndex; this.instanceIndex = nextLevel.instanceIndex; this.reference = nextLevel.reference; } else { this.nextLevel = nextLevel; this.localIndex = currentLevel.getLocalIndex(); this.instanceIndex = currentLevel.getInstanceIndex(); this.reference = currentLevel.reference; } } /** * Constructs an index which indexes an element, and provides an index * into that elements children, along with the current index of a * repeated instance. * * @param nextLevel An index into the referenced element's index * @param localIndex An index to an element at the current level, a child * element of which will be referenced by the nextLevel index. * @param instanceIndex How many times the element referenced has been * repeated. * @param reference A reference to the instance element identified by this index; */ public FormIndex(FormIndex nextLevel, int localIndex, int instanceIndex, TreeReference reference) { this(nextLevel, localIndex, reference); this.instanceIndex = instanceIndex; } public boolean isInForm() { return !beginningOfForm && !endOfForm; } /** * @return The index of the element in the current context */ public int getLocalIndex() { return localIndex; } /** * @return The multiplicity of the current instance of a repeated question or group */ public int getInstanceIndex() { return instanceIndex; } /** * For the fully qualified element, get the multiplicity of the element's reference * * @return The terminal element (fully qualified)'s instance index */ public int getElementMultiplicity() { return getTerminal().instanceIndex; } /** * @return An index into the next level of specificity past the current context. An * example would be an index into an element that is a child of the element referenced * by the local index. */ public FormIndex getNextLevel() { return nextLevel; } public TreeReference getLocalReference() { return reference; } /** * @return The TreeReference of the fully qualified element described by this * FormIndex. */ public TreeReference getReference() { return getTerminal().reference; } public FormIndex getTerminal() { FormIndex walker = this; while (walker.nextLevel != null) { walker = walker.nextLevel; } return walker; } /** * Identifies whether this is a terminal index, in other words whether this * index references with more specificity than the current context */ public boolean isTerminal() { return nextLevel == null; } public boolean isEndOfFormIndex() { return endOfForm; } public boolean isBeginningOfFormIndex() { return beginningOfForm; } public boolean equals(Object o) { if (!(o instanceof FormIndex)) return false; FormIndex a = this; FormIndex b = (FormIndex)o; return (a.compareTo(b) == 0); // //TODO: while(true) loops freak me out, this should probably // //get written more safely. -ctsims // // //Iterate over each level of reference, and identify whether // //each object stays in sync // while(true) { // if(index.isTerminal() != local.isTerminal() || // index.getLocalIndex() != local.getLocalIndex() || // index.getInstanceIndex() != local.getInstanceIndex()) { // return false; // } // if(index.isTerminal()) { // return true; // } // local = local.getNextLevel(); // index = index.getNextLevel(); // } // } public int compareTo(Object o) { if (!(o instanceof FormIndex)) throw new IllegalArgumentException("Attempt to compare Object of type " + o.getClass().getName() + " to a FormIndex"); FormIndex a = this; FormIndex b = (FormIndex)o; if (a.beginningOfForm) { return (b.beginningOfForm ? 0 : -1); } else if (a.endOfForm) { return (b.endOfForm ? 0 : 1); } else { //a is in form if (b.beginningOfForm) { return 1; } else if (b.endOfForm) { return -1; } } if (a.localIndex != b.localIndex) { return (a.localIndex < b.localIndex ? -1 : 1); } else if (a.instanceIndex != b.instanceIndex) { return (a.instanceIndex < b.instanceIndex ? -1 : 1); } else if ((a.getNextLevel() == null) != (b.getNextLevel() == null)) { return (a.getNextLevel() == null ? -1 : 1); } else if (a.getNextLevel() != null) { return a.getNextLevel().compareTo(b.getNextLevel()); } else { return 0; } // int comp = 0; // // //TODO: while(true) loops freak me out, this should probably // //get written more safely. -ctsims // while(comp == 0) { // if(index.isTerminal() != local.isTerminal() || // index.getLocalIndex() != local.getLocalIndex() || // index.getInstanceIndex() != local.getInstanceIndex()) { // if(local.localIndex > index.localIndex) { // return 1; // } else if(local.localIndex < index.localIndex) { // return -1; // } else if (local.instanceIndex > index.instanceIndex) { // return 1; // } else if (local.instanceIndex < index.instanceIndex) { // return -1; // } // // //This case is here as a fallback, but it shouldn't really // //ever be the case that two references have the same chain // //of indices without terminating at the same level. // else if (local.isTerminal() && !index.isTerminal()) { // return -1; // } else { // return 1; // } // } // else if(local.isTerminal()) { // break; // } // local = local.getNextLevel(); // index = index.getNextLevel(); // } // return comp; } /** * @return Only the local component of this Form Index. */ public FormIndex snip() { FormIndex retval = new FormIndex(localIndex, instanceIndex, reference); return retval; } /** * Takes in a form index which is a subset of this index, and returns the * total difference between them. This is useful for stepping up the level * of index specificty. If the subIndex is not a valid subIndex of this index, * null is returned. Since the FormIndex represented by null is always a subset, * if null is passed in as a subIndex, the full index is returned * * For example: * Indices * a = 1_0,2,1,3 * b = 1,3 * * a.diff(b) = 1_0,2 */ public FormIndex diff(FormIndex subIndex) { if (subIndex == null) { return this; } if (!isSubIndex(this, subIndex)) { return null; } if (subIndex.equals(this)) { return null; } return new FormIndex(nextLevel.diff(subIndex), this.snip()); } public String toString() { String ret = ""; FormIndex ref = this; while (ref != null) { ret += ref.getLocalIndex(); ret += ref.getInstanceIndex() == -1 ? ", " : "_" + ref.getInstanceIndex() + ", "; ref = ref.nextLevel; } return ret; } /** * @return the level of this index relative to the top level of the form */ public int getDepth() { int depth = 0; FormIndex ref = this; while (ref != null) { ref = ref.nextLevel; depth++; } return depth; } /** * Trims any negative indices from the end of the passed in index. */ public static FormIndex trimNegativeIndices(FormIndex index) { if (!index.isTerminal()) { return new FormIndex(trimNegativeIndices(index.nextLevel), index); } else { if (index.getLocalIndex() < 0) { return null; } else { return index; } } } public static boolean isSubIndex(FormIndex parent, FormIndex child) { if (child.equals(parent)) { return true; } else { if (parent == null) { return false; } return isSubIndex(parent.nextLevel, child); } } public static boolean isSubElement(FormIndex parent, FormIndex child) { while (!parent.isTerminal() && !child.isTerminal()) { if (parent.getLocalIndex() != child.getLocalIndex()) { return false; } if (parent.getInstanceIndex() != child.getInstanceIndex()) { return false; } parent = parent.nextLevel; child = child.nextLevel; } //If we've gotten this far, at least one of the two is terminal if (!parent.isTerminal() && child.isTerminal()) { //can't be the parent if the child is earlier on return false; } else if (parent.getLocalIndex() != child.getLocalIndex()) { //Either they're at the same level, in which case only //identical indices should match, or they should have //the same root return false; } else if (parent.getInstanceIndex() != -1 && (parent.getInstanceIndex() != child.getInstanceIndex())) { return false; } //Barring all of these cases, it should be true. return true; } public static boolean areSiblings(FormIndex a, FormIndex b) { if (a.isTerminal() && b.isTerminal() && a.getLocalIndex() == b.getLocalIndex()) { return true; } if (!a.isTerminal() && !b.isTerminal()) { if (a.getLocalIndex() != b.getLocalIndex()) { return false; } return areSiblings(a.nextLevel, b.nextLevel); } return false; } public static boolean overlappingLocalIndexesMatch(FormIndex parent, FormIndex child) { if (parent.getDepth() > child.getDepth()) { return false; } while (!parent.isTerminal()) { if (parent.getLocalIndex() != child.getLocalIndex()) { return false; } parent = parent.nextLevel; child = child.nextLevel; } return true; } public void assignRefs(FormDef f) { FormIndex cur = this; Vector<Integer> indexes = new Vector<Integer>(); Vector<Integer> multiplicities = new Vector<Integer>(); Vector<IFormElement> elements = new Vector<IFormElement>(); f.collapseIndex(this, indexes, multiplicities, elements); Vector<Integer> curMults = new Vector<Integer>(); Vector<IFormElement> curElems = new Vector<IFormElement>(); int i = 0; while (cur != null) { curMults.addElement(multiplicities.elementAt(i)); curElems.addElement(elements.elementAt(i)); TreeReference ref = f.getChildInstanceRef(curElems, curMults); cur.reference = ref; cur = cur.getNextLevel(); i++; } } }
core/src/main/java/org/javarosa/core/model/FormIndex.java
package org.javarosa.core.model; import org.javarosa.core.model.instance.TreeReference; import java.util.Vector; /** * A Form Index is an immutable index into a specific question definition that * will appear in an interaction with a user. * * An index is represented by different levels into hierarchical groups. * * Indices can represent both questions and groups. * * It is absolutely essential that there be no circularity of reference in * FormIndex's, IE, no form index's ancestor can be itself. * * Datatype Productions: * FormIndex = BOF | EOF | CompoundIndex(nextIndex:FormIndex,Location) * Location = Empty | Simple(localLevel:int) | WithMult(localLevel:int, multiplicity:int) * * @author Clayton Sims */ public class FormIndex { private boolean beginningOfForm = false; private boolean endOfForm = false; /** * The index of the questiondef in the current context */ private int localIndex; /** * The multiplicity of the current instance of a repeated question or group */ private int instanceIndex = -1; /** * The next level of this index */ private FormIndex nextLevel; private TreeReference reference; public static FormIndex createBeginningOfFormIndex() { FormIndex begin = new FormIndex(-1, null); begin.beginningOfForm = true; return begin; } public static FormIndex createEndOfFormIndex() { FormIndex end = new FormIndex(-1, null); end.endOfForm = true; return end; } /** * Constructs a simple form index that references a specific element in * a list of elements. * * @param localIndex An integer index into a flat list of elements * @param reference A reference to the instance element identified by this index; */ public FormIndex(int localIndex, TreeReference reference) { this.localIndex = localIndex; this.reference = reference; } /** * Constructs a simple form index that references a specific element in * a list of elements. * * @param localIndex An integer index into a flat list of elements * @param instanceIndex An integer index expressing the multiplicity * of the current level * @param reference A reference to the instance element identified by this index; */ public FormIndex(int localIndex, int instanceIndex, TreeReference reference) { this.localIndex = localIndex; this.instanceIndex = instanceIndex; this.reference = reference; } /** * Constructs an index which indexes an element, and provides an index * into that elements children * * @param nextLevel An index into the referenced element's index * @param localIndex An index to an element at the current level, a child * element of which will be referenced by the nextLevel index. * @param reference A reference to the instance element identified by this index; */ public FormIndex(FormIndex nextLevel, int localIndex, TreeReference reference) { this(localIndex, reference); this.nextLevel = nextLevel; } /** * Constructs an index which references an element past the level of * specificity of the current context, founded by the currentLevel * index. * (currentLevel, (nextLevel...)) */ public FormIndex(FormIndex nextLevel, FormIndex currentLevel) { if (currentLevel == null) { this.nextLevel = nextLevel.nextLevel; this.localIndex = nextLevel.localIndex; this.instanceIndex = nextLevel.instanceIndex; this.reference = nextLevel.reference; } else { this.nextLevel = nextLevel; this.localIndex = currentLevel.getLocalIndex(); this.instanceIndex = currentLevel.getInstanceIndex(); this.reference = currentLevel.reference; } } /** * Constructs an index which indexes an element, and provides an index * into that elements children, along with the current index of a * repeated instance. * * @param nextLevel An index into the referenced element's index * @param localIndex An index to an element at the current level, a child * element of which will be referenced by the nextLevel index. * @param instanceIndex How many times the element referenced has been * repeated. * @param reference A reference to the instance element identified by this index; */ public FormIndex(FormIndex nextLevel, int localIndex, int instanceIndex, TreeReference reference) { this(nextLevel, localIndex, reference); this.instanceIndex = instanceIndex; } public boolean isInForm() { return !beginningOfForm && !endOfForm; } /** * @return The index of the element in the current context */ public int getLocalIndex() { return localIndex; } /** * @return The multiplicity of the current instance of a repeated question or group */ public int getInstanceIndex() { return instanceIndex; } /** * For the fully qualified element, get the multiplicity of the element's reference * * @return The terminal element (fully qualified)'s instance index */ public int getElementMultiplicity() { return getTerminal().instanceIndex; } /** * @return An index into the next level of specificity past the current context. An * example would be an index into an element that is a child of the element referenced * by the local index. */ public FormIndex getNextLevel() { return nextLevel; } public TreeReference getLocalReference() { return reference; } /** * @return The TreeReference of the fully qualified element described by this * FormIndex. */ public TreeReference getReference() { return getTerminal().reference; } public FormIndex getTerminal() { FormIndex walker = this; while (walker.nextLevel != null) { walker = walker.nextLevel; } return walker; } /** * Identifies whether this is a terminal index, in other words whether this * index references with more specificity than the current context */ public boolean isTerminal() { return nextLevel == null; } public boolean isEndOfFormIndex() { return endOfForm; } public boolean isBeginningOfFormIndex() { return beginningOfForm; } public boolean equals(Object o) { if (!(o instanceof FormIndex)) return false; FormIndex a = this; FormIndex b = (FormIndex)o; return (a.compareTo(b) == 0); // //TODO: while(true) loops freak me out, this should probably // //get written more safely. -ctsims // // //Iterate over each level of reference, and identify whether // //each object stays in sync // while(true) { // if(index.isTerminal() != local.isTerminal() || // index.getLocalIndex() != local.getLocalIndex() || // index.getInstanceIndex() != local.getInstanceIndex()) { // return false; // } // if(index.isTerminal()) { // return true; // } // local = local.getNextLevel(); // index = index.getNextLevel(); // } // } public int compareTo(Object o) { if (!(o instanceof FormIndex)) throw new IllegalArgumentException("Attempt to compare Object of type " + o.getClass().getName() + " to a FormIndex"); FormIndex a = this; FormIndex b = (FormIndex)o; if (a.beginningOfForm) { return (b.beginningOfForm ? 0 : -1); } else if (a.endOfForm) { return (b.endOfForm ? 0 : 1); } else { //a is in form if (b.beginningOfForm) { return 1; } else if (b.endOfForm) { return -1; } } if (a.localIndex != b.localIndex) { return (a.localIndex < b.localIndex ? -1 : 1); } else if (a.instanceIndex != b.instanceIndex) { return (a.instanceIndex < b.instanceIndex ? -1 : 1); } else if ((a.getNextLevel() == null) != (b.getNextLevel() == null)) { return (a.getNextLevel() == null ? -1 : 1); } else if (a.getNextLevel() != null) { return a.getNextLevel().compareTo(b.getNextLevel()); } else { return 0; } // int comp = 0; // // //TODO: while(true) loops freak me out, this should probably // //get written more safely. -ctsims // while(comp == 0) { // if(index.isTerminal() != local.isTerminal() || // index.getLocalIndex() != local.getLocalIndex() || // index.getInstanceIndex() != local.getInstanceIndex()) { // if(local.localIndex > index.localIndex) { // return 1; // } else if(local.localIndex < index.localIndex) { // return -1; // } else if (local.instanceIndex > index.instanceIndex) { // return 1; // } else if (local.instanceIndex < index.instanceIndex) { // return -1; // } // // //This case is here as a fallback, but it shouldn't really // //ever be the case that two references have the same chain // //of indices without terminating at the same level. // else if (local.isTerminal() && !index.isTerminal()) { // return -1; // } else { // return 1; // } // } // else if(local.isTerminal()) { // break; // } // local = local.getNextLevel(); // index = index.getNextLevel(); // } // return comp; } /** * @return Only the local component of this Form Index. */ public FormIndex snip() { FormIndex retval = new FormIndex(localIndex, instanceIndex, reference); return retval; } /** * Takes in a form index which is a subset of this index, and returns the * total difference between them. This is useful for stepping up the level * of index specificty. If the subIndex is not a valid subIndex of this index, * null is returned. Since the FormIndex represented by null is always a subset, * if null is passed in as a subIndex, the full index is returned * * For example: * Indices * a = 1_0,2,1,3 * b = 1,3 * * a.diff(b) = 1_0,2 */ public FormIndex diff(FormIndex subIndex) { if (subIndex == null) { return this; } if (!isSubIndex(this, subIndex)) { return null; } if (subIndex.equals(this)) { return null; } return new FormIndex(nextLevel.diff(subIndex), this.snip()); } public String toString() { String ret = ""; FormIndex ref = this; while (ref != null) { ret += ref.getLocalIndex(); ret += ref.getInstanceIndex() == -1 ? ", " : "_" + ref.getInstanceIndex() + ", "; ref = ref.nextLevel; } return ret; } /** * @return the level of this index relative to the top level of the form */ public int getDepth() { int depth = 0; FormIndex ref = this; while (ref != null) { ref = ref.nextLevel; depth++; } return depth; } /** * Trims any negative indices from the end of the passed in index. */ public static FormIndex trimNegativeIndices(FormIndex index) { if (!index.isTerminal()) { return new FormIndex(trimNegativeIndices(index.nextLevel), index); } else { if (index.getLocalIndex() < 0) { return null; } else { return index; } } } public static boolean isSubIndex(FormIndex parent, FormIndex child) { if (child.equals(parent)) { return true; } else { if (parent == null) { return false; } return isSubIndex(parent.nextLevel, child); } } public static boolean isSubElement(FormIndex parent, FormIndex child) { while (!parent.isTerminal() && !child.isTerminal()) { if (parent.getLocalIndex() != child.getLocalIndex()) { return false; } if (parent.getInstanceIndex() != child.getInstanceIndex()) { return false; } parent = parent.nextLevel; child = child.nextLevel; } //If we've gotten this far, at least one of the two is terminal if (!parent.isTerminal() && child.isTerminal()) { //can't be the parent if the child is earlier on return false; } else if (parent.getLocalIndex() != child.getLocalIndex()) { //Either they're at the same level, in which case only //identical indices should match, or they should have //the same root return false; } else if (parent.getInstanceIndex() != -1 && (parent.getInstanceIndex() != child.getInstanceIndex())) { return false; } //Barring all of these cases, it should be true. return true; } public void assignRefs(FormDef f) { FormIndex cur = this; Vector<Integer> indexes = new Vector<Integer>(); Vector<Integer> multiplicities = new Vector<Integer>(); Vector<IFormElement> elements = new Vector<IFormElement>(); f.collapseIndex(this, indexes, multiplicities, elements); Vector<Integer> curMults = new Vector<Integer>(); Vector<IFormElement> curElems = new Vector<IFormElement>(); int i = 0; while (cur != null) { curMults.addElement(multiplicities.elementAt(i)); curElems.addElement(elements.elementAt(i)); TreeReference ref = f.getChildInstanceRef(curElems, curMults); cur.reference = ref; cur = cur.getNextLevel(); i++; } } }
Adding FormIndex helper methods
core/src/main/java/org/javarosa/core/model/FormIndex.java
Adding FormIndex helper methods
<ide><path>ore/src/main/java/org/javarosa/core/model/FormIndex.java <ide> return true; <ide> } <ide> <add> public static boolean areSiblings(FormIndex a, FormIndex b) { <add> if (a.isTerminal() && b.isTerminal() && a.getLocalIndex() == b.getLocalIndex()) { <add> return true; <add> } <add> if (!a.isTerminal() && !b.isTerminal()) { <add> if (a.getLocalIndex() != b.getLocalIndex()) { <add> return false; <add> } <add> <add> return areSiblings(a.nextLevel, b.nextLevel); <add> } <add> <add> return false; <add> } <add> <add> public static boolean overlappingLocalIndexesMatch(FormIndex parent, FormIndex child) { <add> if (parent.getDepth() > child.getDepth()) { <add> return false; <add> } <add> while (!parent.isTerminal()) { <add> if (parent.getLocalIndex() != child.getLocalIndex()) { <add> return false; <add> } <add> parent = parent.nextLevel; <add> child = child.nextLevel; <add> } <add> return true; <add> } <add> <ide> public void assignRefs(FormDef f) { <ide> FormIndex cur = this; <ide>
Java
apache-2.0
9c651fb158ecf8726acc42c8a10a1eb9bf4c1850
0
Reidddddd/alluxio,aaudiber/alluxio,maboelhassan/alluxio,wwjiang007/alluxio,PasaLab/tachyon,jswudi/alluxio,maboelhassan/alluxio,ChangerYoung/alluxio,Reidddddd/mo-alluxio,maobaolong/alluxio,Reidddddd/alluxio,aaudiber/alluxio,ShailShah/alluxio,PasaLab/tachyon,wwjiang007/alluxio,maboelhassan/alluxio,maobaolong/alluxio,riversand963/alluxio,wwjiang007/alluxio,bf8086/alluxio,yuluo-ding/alluxio,maobaolong/alluxio,apc999/alluxio,calvinjia/tachyon,apc999/alluxio,maboelhassan/alluxio,maboelhassan/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,riversand963/alluxio,Alluxio/alluxio,riversand963/alluxio,aaudiber/alluxio,aaudiber/alluxio,madanadit/alluxio,madanadit/alluxio,Reidddddd/mo-alluxio,Reidddddd/alluxio,Reidddddd/alluxio,EvilMcJerkface/alluxio,Reidddddd/alluxio,bf8086/alluxio,ShailShah/alluxio,yuluo-ding/alluxio,PasaLab/tachyon,madanadit/alluxio,riversand963/alluxio,Alluxio/alluxio,wwjiang007/alluxio,ShailShah/alluxio,aaudiber/alluxio,bf8086/alluxio,EvilMcJerkface/alluxio,madanadit/alluxio,aaudiber/alluxio,WilliamZapata/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,ShailShah/alluxio,apc999/alluxio,ChangerYoung/alluxio,jsimsa/alluxio,Reidddddd/mo-alluxio,PasaLab/tachyon,jsimsa/alluxio,ChangerYoung/alluxio,madanadit/alluxio,wwjiang007/alluxio,bf8086/alluxio,Alluxio/alluxio,Alluxio/alluxio,Reidddddd/mo-alluxio,apc999/alluxio,apc999/alluxio,jswudi/alluxio,calvinjia/tachyon,wwjiang007/alluxio,uronce-cc/alluxio,jsimsa/alluxio,maobaolong/alluxio,bf8086/alluxio,jswudi/alluxio,madanadit/alluxio,EvilMcJerkface/alluxio,Reidddddd/alluxio,jsimsa/alluxio,EvilMcJerkface/alluxio,yuluo-ding/alluxio,uronce-cc/alluxio,WilliamZapata/alluxio,jsimsa/alluxio,calvinjia/tachyon,Alluxio/alluxio,wwjiang007/alluxio,apc999/alluxio,calvinjia/tachyon,maboelhassan/alluxio,jswudi/alluxio,wwjiang007/alluxio,Alluxio/alluxio,calvinjia/tachyon,uronce-cc/alluxio,maobaolong/alluxio,jswudi/alluxio,yuluo-ding/alluxio,WilliamZapata/alluxio,WilliamZapata/alluxio,uronce-cc/alluxio,calvinjia/tachyon,riversand963/alluxio,EvilMcJerkface/alluxio,ShailShah/alluxio,apc999/alluxio,Reidddddd/alluxio,EvilMcJerkface/alluxio,uronce-cc/alluxio,madanadit/alluxio,bf8086/alluxio,bf8086/alluxio,Reidddddd/mo-alluxio,ChangerYoung/alluxio,ShailShah/alluxio,calvinjia/tachyon,maboelhassan/alluxio,yuluo-ding/alluxio,wwjiang007/alluxio,jsimsa/alluxio,Alluxio/alluxio,bf8086/alluxio,ChangerYoung/alluxio,yuluo-ding/alluxio,maobaolong/alluxio,uronce-cc/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,PasaLab/tachyon,maobaolong/alluxio,EvilMcJerkface/alluxio,calvinjia/tachyon,PasaLab/tachyon,wwjiang007/alluxio,ChangerYoung/alluxio,aaudiber/alluxio,madanadit/alluxio,maobaolong/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,maobaolong/alluxio,maobaolong/alluxio,PasaLab/tachyon,jswudi/alluxio
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the “License”). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.underfs.local; import alluxio.Configuration; import alluxio.Constants; import alluxio.underfs.UnderFileSystem; import alluxio.util.io.FileUtils; import alluxio.util.io.PathUtils; import alluxio.util.network.NetworkAddressUtils; import alluxio.util.network.NetworkAddressUtils.ServiceType; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Stack; import javax.annotation.concurrent.ThreadSafe; /** * Local FS {@link UnderFileSystem} implementation. * <p> * This is primarily intended for local unit testing and single machine mode. In principle, it can * also be used on a system where a shared file system (e.g. NFS) is mounted at the same path on * every node of the system. However, it is generally preferable to use a proper distributed file * system for that scenario. * </p> */ @ThreadSafe public class LocalUnderFileSystem extends UnderFileSystem { /** * Constructs a new {@link LocalUnderFileSystem}. * * @param conf the configuration for Alluxio */ public LocalUnderFileSystem(Configuration conf) { super(conf); } @Override public UnderFSType getUnderFSType() { return UnderFSType.LOCAL; } @Override public void close() throws IOException {} @Override public OutputStream create(String path) throws IOException { FileOutputStream stream = new FileOutputStream(path); try { setPermission(path, "777"); } catch (IOException e) { stream.close(); throw e; } return stream; } @Override public OutputStream create(String path, int blockSizeByte) throws IOException { return create(path, (short) 1, blockSizeByte); } @Override public OutputStream create(String path, short replication, int blockSizeByte) throws IOException { if (replication != 1) { throw new IOException("UnderFileSystemSingleLocal does not provide more than one" + " replication factor"); } return create(path); } @Override public boolean delete(String path, boolean recursive) throws IOException { File file = new File(path); boolean success = true; if (recursive && file.isDirectory()) { String[] files = file.list(); for (String child : files) { success = success && delete(PathUtils.concatPath(path, child), true); } } return success && file.delete(); } @Override public boolean exists(String path) throws IOException { File file = new File(path); return file.exists(); } @Override public long getBlockSizeByte(String path) throws IOException { File file = new File(path); if (!file.exists()) { throw new FileNotFoundException(path); } return mConfiguration.getBytes(Constants.USER_BLOCK_SIZE_BYTES_DEFAULT); } @Override public Object getConf() { return null; } @Override public List<String> getFileLocations(String path) throws IOException { List<String> ret = new ArrayList<String>(); ret.add(NetworkAddressUtils.getConnectHost(ServiceType.WORKER_RPC, mConfiguration)); return ret; } @Override public List<String> getFileLocations(String path, long offset) throws IOException { return getFileLocations(path); } @Override public long getFileSize(String path) throws IOException { File file = new File(path); return file.length(); } @Override public long getModificationTimeMs(String path) throws IOException { File file = new File(path); return file.lastModified(); } @Override public long getSpace(String path, SpaceType type) throws IOException { File file = new File(path); switch (type) { case SPACE_TOTAL: return file.getTotalSpace(); case SPACE_FREE: return file.getFreeSpace(); case SPACE_USED: return file.getTotalSpace() - file.getFreeSpace(); default: throw new IOException("Unknown getSpace parameter: " + type); } } @Override public boolean isFile(String path) throws IOException { File file = new File(path); return file.isFile(); } @Override public String[] list(String path) throws IOException { File file = new File(path); File[] files = file.listFiles(); if (files != null) { String[] rtn = new String[files.length]; int i = 0; for (File f : files) { rtn[i++] = f.getName(); } return rtn; } else { return null; } } @Override public boolean mkdirs(String path, boolean createParent) throws IOException { File file = new File(path); if (!createParent) { if (file.mkdir()) { setPermission(file.getPath(), "777"); FileUtils.setLocalDirStickyBit(file.getPath()); return true; } return false; } // create parent directories one by one and set their permissions to 777 Stack<File> dirsToMake = new Stack<File>(); dirsToMake.push(file); File parent = file.getParentFile(); while (!parent.exists()) { dirsToMake.push(parent); parent = parent.getParentFile(); } while (!dirsToMake.empty()) { File dirToMake = dirsToMake.pop(); if (dirToMake.mkdir()) { setPermission(dirToMake.getAbsolutePath(), "777"); FileUtils.setLocalDirStickyBit(file.getPath()); } else { return false; } } return true; } @Override public InputStream open(String path) throws IOException { return new FileInputStream(path); } @Override public boolean rename(String src, String dst) throws IOException { File file = new File(src); return file.renameTo(new File(dst)); } @Override public void setConf(Object conf) {} @Override public void setPermission(String path, String posixPerm) throws IOException { FileUtils.changeLocalFilePermission(path, posixPerm); } @Override public void connectFromMaster(Configuration conf, String hostname) throws IOException { // No-op } @Override public void connectFromWorker(Configuration conf, String hostname) throws IOException { // No-op } }
underfs/local/src/main/java/alluxio/underfs/local/LocalUnderFileSystem.java
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the “License”). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.underfs.local; import alluxio.Configuration; import alluxio.Constants; import alluxio.underfs.UnderFileSystem; import alluxio.util.io.FileUtils; import alluxio.util.io.PathUtils; import alluxio.util.network.NetworkAddressUtils; import alluxio.util.network.NetworkAddressUtils.ServiceType; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Stack; import javax.annotation.concurrent.ThreadSafe; /** * Local FS {@link UnderFileSystem} implementation. * <p> * This is primarily intended for local unit testing and single machine mode. In principle, it can * also be used on a system where a shared file system (e.g. NFS) is mounted at the same path on * every node of the system. However, it is generally preferable to use a proper distributed file * system for that scenario. * </p> */ @ThreadSafe public class LocalUnderFileSystem extends UnderFileSystem { /** * Constructs a new {@link LocalUnderFileSystem}. * * @param conf the configuration for Alluxio */ public LocalUnderFileSystem(Configuration conf) { super(conf); } @Override public UnderFSType getUnderFSType() { return UnderFSType.LOCAL; } @Override public void close() throws IOException {} @Override public OutputStream create(String path) throws IOException { FileOutputStream stream = new FileOutputStream(path); try { setPermission(path, "777"); } catch (IOException e) { stream.close(); throw e; } return stream; } @Override public OutputStream create(String path, int blockSizeByte) throws IOException { return create(path, (short) 1, blockSizeByte); } @Override public OutputStream create(String path, short replication, int blockSizeByte) throws IOException { if (replication != 1) { throw new IOException("UnderFileSystemSingleLocal does not provide more than one" + " replication factor"); } return create(path); } @Override public boolean delete(String path, boolean recursive) throws IOException { File file = new File(path); boolean success = true; if (recursive && file.isDirectory()) { String[] files = file.list(); for (String child : files) { success = success && delete(PathUtils.concatPath(path, child), true); } } return success && file.delete(); } @Override public boolean exists(String path) throws IOException { File file = new File(path); return file.exists(); } @Override public long getBlockSizeByte(String path) throws IOException { File file = new File(path); if (!file.exists()) { throw new FileNotFoundException(path); } return Constants.GB * 2L; } @Override public Object getConf() { return null; } @Override public List<String> getFileLocations(String path) throws IOException { List<String> ret = new ArrayList<String>(); ret.add(NetworkAddressUtils.getConnectHost(ServiceType.WORKER_RPC, mConfiguration)); return ret; } @Override public List<String> getFileLocations(String path, long offset) throws IOException { return getFileLocations(path); } @Override public long getFileSize(String path) throws IOException { File file = new File(path); return file.length(); } @Override public long getModificationTimeMs(String path) throws IOException { File file = new File(path); return file.lastModified(); } @Override public long getSpace(String path, SpaceType type) throws IOException { File file = new File(path); switch (type) { case SPACE_TOTAL: return file.getTotalSpace(); case SPACE_FREE: return file.getFreeSpace(); case SPACE_USED: return file.getTotalSpace() - file.getFreeSpace(); default: throw new IOException("Unknown getSpace parameter: " + type); } } @Override public boolean isFile(String path) throws IOException { File file = new File(path); return file.isFile(); } @Override public String[] list(String path) throws IOException { File file = new File(path); File[] files = file.listFiles(); if (files != null) { String[] rtn = new String[files.length]; int i = 0; for (File f : files) { rtn[i++] = f.getName(); } return rtn; } else { return null; } } @Override public boolean mkdirs(String path, boolean createParent) throws IOException { File file = new File(path); if (!createParent) { if (file.mkdir()) { setPermission(file.getPath(), "777"); FileUtils.setLocalDirStickyBit(file.getPath()); return true; } return false; } // create parent directories one by one and set their permissions to 777 Stack<File> dirsToMake = new Stack<File>(); dirsToMake.push(file); File parent = file.getParentFile(); while (!parent.exists()) { dirsToMake.push(parent); parent = parent.getParentFile(); } while (!dirsToMake.empty()) { File dirToMake = dirsToMake.pop(); if (dirToMake.mkdir()) { setPermission(dirToMake.getAbsolutePath(), "777"); FileUtils.setLocalDirStickyBit(file.getPath()); } else { return false; } } return true; } @Override public InputStream open(String path) throws IOException { return new FileInputStream(path); } @Override public boolean rename(String src, String dst) throws IOException { File file = new File(src); return file.renameTo(new File(dst)); } @Override public void setConf(Object conf) {} @Override public void setPermission(String path, String posixPerm) throws IOException { FileUtils.changeLocalFilePermission(path, posixPerm); } @Override public void connectFromMaster(Configuration conf, String hostname) throws IOException { // No-op } @Override public void connectFromWorker(Configuration conf, String hostname) throws IOException { // No-op } }
Update the default block size of local fs to default instead of 2 gb.
underfs/local/src/main/java/alluxio/underfs/local/LocalUnderFileSystem.java
Update the default block size of local fs to default instead of 2 gb.
<ide><path>nderfs/local/src/main/java/alluxio/underfs/local/LocalUnderFileSystem.java <ide> if (!file.exists()) { <ide> throw new FileNotFoundException(path); <ide> } <del> return Constants.GB * 2L; <add> return mConfiguration.getBytes(Constants.USER_BLOCK_SIZE_BYTES_DEFAULT); <ide> } <ide> <ide> @Override
Java
apache-2.0
016ba3f74c5181bf841a4eeb38fa0616c56d04f4
0
mesutcelik/hazelcast,tkountis/hazelcast,emre-aydin/hazelcast,tufangorel/hazelcast,tkountis/hazelcast,dbrimley/hazelcast,mdogan/hazelcast,tufangorel/hazelcast,Donnerbart/hazelcast,dsukhoroslov/hazelcast,dsukhoroslov/hazelcast,emre-aydin/hazelcast,emre-aydin/hazelcast,mesutcelik/hazelcast,mdogan/hazelcast,juanavelez/hazelcast,dbrimley/hazelcast,mesutcelik/hazelcast,juanavelez/hazelcast,Donnerbart/hazelcast,dbrimley/hazelcast,tufangorel/hazelcast,mdogan/hazelcast,tkountis/hazelcast,Donnerbart/hazelcast
/* * Copyright (c) 2008-2017, Hazelcast, 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.hazelcast.map.impl.record; import com.hazelcast.core.PartitioningStrategy; import com.hazelcast.internal.serialization.InternalSerializationService; import com.hazelcast.internal.serialization.impl.DefaultSerializationServiceBuilder; import com.hazelcast.internal.serialization.impl.HeapData; import com.hazelcast.nio.serialization.Data; import com.hazelcast.partition.strategy.DefaultPartitioningStrategy; import com.hazelcast.spi.serialization.SerializationService; import com.hazelcast.test.HazelcastTestSupport; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @SuppressWarnings("WeakerAccess") public abstract class AbstractRecordComparatorTest extends HazelcastTestSupport { SerializationService serializationService; PartitioningStrategy partitioningStrategy; RecordComparator comparator; Person object1; Person object2; Data data1; Data data2; Data nullData; @Before public final void init() { serializationService = createSerializationService(); partitioningStrategy = new DefaultPartitioningStrategy(); object1 = new Person("Alice"); object2 = new Person("Bob"); data1 = serializationService.toData(object1); data2 = serializationService.toData(object2); nullData = new HeapData(new byte[0]); } @Test public void testIsEqual() { newRecordComparator(); assertTrue(comparator.isEqual(null, null)); assertTrue(comparator.isEqual(object1, object1)); assertTrue(comparator.isEqual(object1, data1)); assertTrue(comparator.isEqual(data1, data1)); assertTrue(comparator.isEqual(data1, object1)); assertTrue(comparator.isEqual(nullData, nullData)); assertFalse(comparator.isEqual(null, object1)); assertFalse(comparator.isEqual(null, data1)); assertFalse(comparator.isEqual(null, nullData)); assertFalse(comparator.isEqual(object1, null)); assertFalse(comparator.isEqual(object1, nullData)); assertFalse(comparator.isEqual(object1, object2)); assertFalse(comparator.isEqual(object1, data2)); assertFalse(comparator.isEqual(data1, null)); assertFalse(comparator.isEqual(data1, nullData)); assertFalse(comparator.isEqual(data1, object2)); assertFalse(comparator.isEqual(data1, data2)); assertFalse(comparator.isEqual(nullData, null)); assertFalse(comparator.isEqual(nullData, object1)); assertFalse(comparator.isEqual(nullData, data1)); } @Test public void testIsEqual_withCustomPartitioningStrategy() { partitioningStrategy = new PersonPartitioningStrategy(); data1 = serializationService.toData(object1, partitioningStrategy); data2 = serializationService.toData(object2, partitioningStrategy); testIsEqual(); } abstract void newRecordComparator(); InternalSerializationService createSerializationService() { return new DefaultSerializationServiceBuilder().build(); } static class PersonPartitioningStrategy implements PartitioningStrategy<Person> { @Override public Object getPartitionKey(Person key) { return key.name; } } }
hazelcast/src/test/java/com/hazelcast/map/impl/record/AbstractRecordComparatorTest.java
/* * Copyright (c) 2008-2017, Hazelcast, 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.hazelcast.map.impl.record; import com.hazelcast.core.PartitioningStrategy; import com.hazelcast.internal.serialization.InternalSerializationService; import com.hazelcast.internal.serialization.impl.DefaultSerializationServiceBuilder; import com.hazelcast.internal.serialization.impl.HeapData; import com.hazelcast.nio.serialization.Data; import com.hazelcast.partition.strategy.DefaultPartitioningStrategy; import com.hazelcast.spi.serialization.SerializationService; import com.hazelcast.test.HazelcastTestSupport; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @SuppressWarnings("WeakerAccess") public abstract class AbstractRecordComparatorTest extends HazelcastTestSupport { SerializationService serializationService; PartitioningStrategy partitioningStrategy; RecordComparator comparator; Person object1; Person object2; Data data1; Data data2; Data nullData; @Before public final void init() { serializationService = createSerializationService(); partitioningStrategy = new DefaultPartitioningStrategy(); object1 = new Person("Alice"); object2 = new Person("Bob"); data1 = serializationService.toData(object1); data2 = serializationService.toData(object2); nullData = new HeapData(new byte[0]); } @Test public void testIsEquals() { newRecordComparator(); assertTrue(comparator.isEqual(null, null)); assertTrue(comparator.isEqual(object1, object1)); assertTrue(comparator.isEqual(object1, data1)); assertTrue(comparator.isEqual(data1, data1)); assertTrue(comparator.isEqual(data1, object1)); assertTrue(comparator.isEqual(nullData, nullData)); assertFalse(comparator.isEqual(null, object1)); assertFalse(comparator.isEqual(null, data1)); assertFalse(comparator.isEqual(null, nullData)); assertFalse(comparator.isEqual(object1, null)); assertFalse(comparator.isEqual(object1, nullData)); assertFalse(comparator.isEqual(object1, object2)); assertFalse(comparator.isEqual(object1, data2)); assertFalse(comparator.isEqual(data1, null)); assertFalse(comparator.isEqual(data1, nullData)); assertFalse(comparator.isEqual(data1, object2)); assertFalse(comparator.isEqual(data1, data2)); assertFalse(comparator.isEqual(nullData, null)); assertFalse(comparator.isEqual(nullData, object1)); assertFalse(comparator.isEqual(nullData, data1)); } @Test public void testIsEquals_withCustomPartitioningStrategy() { partitioningStrategy = new PersonPartitioningStrategy(); data1 = serializationService.toData(object1, partitioningStrategy); data2 = serializationService.toData(object2, partitioningStrategy); testIsEquals(); } abstract void newRecordComparator(); InternalSerializationService createSerializationService() { return new DefaultSerializationServiceBuilder().build(); } static class PersonPartitioningStrategy implements PartitioningStrategy<Person> { @Override public Object getPartitionKey(Person key) { return key.name; } } }
Fixed test name in AbstractRecordComparatorTest
hazelcast/src/test/java/com/hazelcast/map/impl/record/AbstractRecordComparatorTest.java
Fixed test name in AbstractRecordComparatorTest
<ide><path>azelcast/src/test/java/com/hazelcast/map/impl/record/AbstractRecordComparatorTest.java <ide> } <ide> <ide> @Test <del> public void testIsEquals() { <add> public void testIsEqual() { <ide> newRecordComparator(); <ide> <ide> assertTrue(comparator.isEqual(null, null)); <ide> } <ide> <ide> @Test <del> public void testIsEquals_withCustomPartitioningStrategy() { <add> public void testIsEqual_withCustomPartitioningStrategy() { <ide> partitioningStrategy = new PersonPartitioningStrategy(); <ide> <ide> data1 = serializationService.toData(object1, partitioningStrategy); <ide> data2 = serializationService.toData(object2, partitioningStrategy); <ide> <del> testIsEquals(); <add> testIsEqual(); <ide> } <ide> <ide> abstract void newRecordComparator();
Java
apache-2.0
388008bdb5d5787a92f5a3bc85b12b25eecdd391
0
smartpcr/presto,jf367/presto,hulu/presto,ebyhr/presto,jiekechoo/presto,jiekechoo/presto,smartnews/presto,rockerbox/presto,sumitkgec/presto,fiedukow/presto,gh351135612/presto,nsabharwal/presto,stewartpark/presto,toyama0919/presto,joy-yao/presto,hulu/presto,geraint0923/presto,wrmsr/presto,prestodb/presto,hgschmie/presto,Nasdaq/presto,kined/presto,mugglmenzel/presto,tellproject/presto,y-lan/presto,gh351135612/presto,cawallin/presto,dongjoon-hyun/presto,mode/presto,twitter-forks/presto,fipar/presto,ebd2/presto,jiekechoo/presto,joy-yao/presto,siddhartharay007/presto,Nasdaq/presto,Yaliang/presto,fiedukow/presto,sumitkgec/presto,jf367/presto,ajoabraham/presto,arhimondr/presto,mbeitchman/presto,geraint0923/presto,rockerbox/presto,soz-fb/presto,cawallin/presto,harunurhan/presto,jf367/presto,idemura/presto,wyukawa/presto,albertocsm/presto,jxiang/presto,mpilman/presto,ipros-team/presto,zjshen/presto,yuananf/presto,Yaliang/presto,martint/presto,11xor6/presto,lingochamp/presto,nakajijiji/presto,wangcan2014/presto,dain/presto,stewartpark/presto,kined/presto,losipiuk/presto,wrmsr/presto,cberner/presto,Jimexist/presto,mpilman/presto,Praveen2112/presto,Teradata/presto,chrisunder/presto,11xor6/presto,smartnews/presto,ebyhr/presto,dongjoon-hyun/presto,miquelruiz/presto,propene/presto,propene/presto,EvilMcJerkface/presto,facebook/presto,tomz/presto,geraint0923/presto,zhenyuy-fb/presto,haozhun/presto,nsabharwal/presto,jiangyifangh/presto,EvilMcJerkface/presto,siddhartharay007/presto,haitaoyao/presto,albertocsm/presto,mandusm/presto,svstanev/presto,ptkool/presto,aglne/presto,prestodb/presto,tellproject/presto,DanielTing/presto,toxeh/presto,suyucs/presto,treasure-data/presto,aleph-zero/presto,RobinUS2/presto,zjshen/presto,siddhartharay007/presto,totticarter/presto,idemura/presto,martint/presto,haozhun/presto,damiencarol/presto,XiaominZhang/presto,cawallin/presto,TeradataCenterForHadoop/bootcamp,kietly/presto,elonazoulay/presto,mugglmenzel/presto,youngwookim/presto,ocono-tech/presto,albertocsm/presto,siddhartharay007/presto,zofuthan/presto,arhimondr/presto,lingochamp/presto,joy-yao/presto,electrum/presto,tellproject/presto,sopel39/presto,electrum/presto,facebook/presto,Zoomdata/presto,zzhao0/presto,mpilman/presto,nsabharwal/presto,mcanthony/presto,toxeh/presto,ptkool/presto,zjshen/presto,cosinequanon/presto,smartpcr/presto,aglne/presto,harunurhan/presto,prestodb/presto,nsabharwal/presto,lingochamp/presto,lingochamp/presto,miquelruiz/presto,pwz3n0/presto,kined/presto,damiencarol/presto,mode/presto,gh351135612/presto,dabaitu/presto,dabaitu/presto,zofuthan/presto,mugglmenzel/presto,bloomberg/presto,11xor6/presto,DanielTing/presto,facebook/presto,haozhun/presto,y-lan/presto,losipiuk/presto,11xor6/presto,dongjoon-hyun/presto,pwz3n0/presto,troels/nz-presto,Zoomdata/presto,fipar/presto,kietly/presto,Jimexist/presto,pwz3n0/presto,albertocsm/presto,toyama0919/presto,aramesh117/presto,shixuan-fan/presto,fipar/presto,smartpcr/presto,Nasdaq/presto,nakajijiji/presto,miquelruiz/presto,ajoabraham/presto,cberner/presto,mode/presto,miniway/presto,deciament/presto,smartpcr/presto,cawallin/presto,harunurhan/presto,tomz/presto,sumitkgec/presto,harunurhan/presto,wagnermarkd/presto,XiaominZhang/presto,XiaominZhang/presto,damiencarol/presto,gh351135612/presto,twitter-forks/presto,xiangel/presto,aramesh117/presto,aleph-zero/presto,jxiang/presto,springning/presto,dongjoon-hyun/presto,fipar/presto,yuananf/presto,dabaitu/presto,toyama0919/presto,mpilman/presto,mvp/presto,prateek1306/presto,tomz/presto,ajoabraham/presto,dain/presto,Jimexist/presto,miniway/presto,cosinequanon/presto,wagnermarkd/presto,jxiang/presto,aramesh117/presto,raghavsethi/presto,cberner/presto,ptkool/presto,wrmsr/presto,mbeitchman/presto,mandusm/presto,smartnews/presto,troels/nz-presto,idemura/presto,ArturGajowy/presto,RobinUS2/presto,losipiuk/presto,Praveen2112/presto,ocono-tech/presto,suyucs/presto,zhenyuy-fb/presto,twitter-forks/presto,martint/presto,DanielTing/presto,mvp/presto,Teradata/presto,geraint0923/presto,electrum/presto,shixuan-fan/presto,stewartpark/presto,youngwookim/presto,wrmsr/presto,jxiang/presto,facebook/presto,Nasdaq/presto,toxeh/presto,prateek1306/presto,suyucs/presto,soz-fb/presto,dongjoon-hyun/presto,svstanev/presto,propene/presto,damiencarol/presto,mugglmenzel/presto,haitaoyao/presto,Teradata/presto,mbeitchman/presto,hgschmie/presto,hulu/presto,ebd2/presto,stewartpark/presto,wrmsr/presto,RobinUS2/presto,wangcan2014/presto,chrisunder/presto,takari/presto,ebyhr/presto,wyukawa/presto,svstanev/presto,Praveen2112/presto,prestodb/presto,kietly/presto,treasure-data/presto,ptkool/presto,Jimexist/presto,xiangel/presto,miniway/presto,TeradataCenterForHadoop/bootcamp,nileema/presto,dabaitu/presto,dabaitu/presto,ptkool/presto,mbeitchman/presto,prestodb/presto,elonazoulay/presto,xiangel/presto,takari/presto,miniway/presto,aglne/presto,nezihyigitbasi/presto,mode/presto,mcanthony/presto,harunurhan/presto,raghavsethi/presto,Praveen2112/presto,Nasdaq/presto,elonazoulay/presto,nakajijiji/presto,aleph-zero/presto,mvp/presto,mandusm/presto,rockerbox/presto,electrum/presto,ipros-team/presto,EvilMcJerkface/presto,shixuan-fan/presto,wyukawa/presto,deciament/presto,smartpcr/presto,DanielTing/presto,zhenyuy-fb/presto,tellproject/presto,erichwang/presto,youngwookim/presto,dain/presto,youngwookim/presto,mvp/presto,aglne/presto,joy-yao/presto,propene/presto,jiekechoo/presto,albertocsm/presto,y-lan/presto,ebd2/presto,siddhartharay007/presto,miniway/presto,takari/presto,mcanthony/presto,zzhao0/presto,deciament/presto,sopel39/presto,mandusm/presto,pwz3n0/presto,geraint0923/presto,smartnews/presto,hgschmie/presto,nileema/presto,joy-yao/presto,Yaliang/presto,wagnermarkd/presto,springning/presto,sunchao/presto,wagnermarkd/presto,toyama0919/presto,jiangyifangh/presto,wangcan2014/presto,Yaliang/presto,ipros-team/presto,svstanev/presto,aramesh117/presto,ArturGajowy/presto,aglne/presto,damiencarol/presto,EvilMcJerkface/presto,arhimondr/presto,arhimondr/presto,mode/presto,ebyhr/presto,XiaominZhang/presto,cawallin/presto,erichwang/presto,shixuan-fan/presto,springning/presto,sumitkgec/presto,treasure-data/presto,jiangyifangh/presto,totticarter/presto,prateek1306/presto,yuananf/presto,kined/presto,losipiuk/presto,cosinequanon/presto,dain/presto,haitaoyao/presto,idemura/presto,kietly/presto,mvp/presto,wangcan2014/presto,rockerbox/presto,ipros-team/presto,arhimondr/presto,youngwookim/presto,prestodb/presto,Zoomdata/presto,bloomberg/presto,zofuthan/presto,shixuan-fan/presto,kined/presto,facebook/presto,aleph-zero/presto,TeradataCenterForHadoop/bootcamp,gh351135612/presto,mcanthony/presto,hulu/presto,mandusm/presto,springning/presto,ipros-team/presto,kietly/presto,cberner/presto,fiedukow/presto,haitaoyao/presto,totticarter/presto,chrisunder/presto,prateek1306/presto,fiedukow/presto,nezihyigitbasi/presto,totticarter/presto,xiangel/presto,sunchao/presto,bloomberg/presto,nezihyigitbasi/presto,jf367/presto,sunchao/presto,ArturGajowy/presto,nileema/presto,ocono-tech/presto,zzhao0/presto,raghavsethi/presto,lingochamp/presto,haozhun/presto,nezihyigitbasi/presto,nakajijiji/presto,deciament/presto,chrisunder/presto,xiangel/presto,mbeitchman/presto,toxeh/presto,hgschmie/presto,haitaoyao/presto,twitter-forks/presto,treasure-data/presto,wyukawa/presto,DanielTing/presto,ArturGajowy/presto,martint/presto,suyucs/presto,EvilMcJerkface/presto,propene/presto,idemura/presto,mpilman/presto,jiangyifangh/presto,cosinequanon/presto,mcanthony/presto,y-lan/presto,tomz/presto,erichwang/presto,suyucs/presto,miquelruiz/presto,sopel39/presto,sunchao/presto,zjshen/presto,TeradataCenterForHadoop/bootcamp,fiedukow/presto,takari/presto,zzhao0/presto,martint/presto,troels/nz-presto,jiangyifangh/presto,tellproject/presto,mugglmenzel/presto,TeradataCenterForHadoop/bootcamp,Zoomdata/presto,ajoabraham/presto,elonazoulay/presto,Yaliang/presto,zofuthan/presto,twitter-forks/presto,svstanev/presto,Praveen2112/presto,bloomberg/presto,rockerbox/presto,nezihyigitbasi/presto,springning/presto,wrmsr/presto,nileema/presto,deciament/presto,soz-fb/presto,miquelruiz/presto,zofuthan/presto,raghavsethi/presto,losipiuk/presto,nsabharwal/presto,y-lan/presto,aramesh117/presto,prateek1306/presto,hulu/presto,jxiang/presto,zzhao0/presto,hgschmie/presto,jiekechoo/presto,chrisunder/presto,sumitkgec/presto,totticarter/presto,treasure-data/presto,ebyhr/presto,ajoabraham/presto,dain/presto,mpilman/presto,ocono-tech/presto,ebd2/presto,haozhun/presto,troels/nz-presto,tellproject/presto,nileema/presto,Teradata/presto,sopel39/presto,sopel39/presto,tomz/presto,smartnews/presto,cberner/presto,troels/nz-presto,erichwang/presto,treasure-data/presto,toyama0919/presto,raghavsethi/presto,yuananf/presto,sunchao/presto,erichwang/presto,cosinequanon/presto,Zoomdata/presto,pwz3n0/presto,jf367/presto,Teradata/presto,toxeh/presto,ArturGajowy/presto,wangcan2014/presto,yuananf/presto,wyukawa/presto,aleph-zero/presto,11xor6/presto,Jimexist/presto,zjshen/presto,soz-fb/presto,bloomberg/presto,ocono-tech/presto,RobinUS2/presto,nakajijiji/presto,RobinUS2/presto,XiaominZhang/presto,wagnermarkd/presto,zhenyuy-fb/presto,zhenyuy-fb/presto,soz-fb/presto,ebd2/presto,stewartpark/presto,elonazoulay/presto,fipar/presto,electrum/presto,takari/presto
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.execution; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.MoreExecutors; import io.airlift.concurrent.AsyncSemaphore; import org.weakref.jmx.Managed; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static com.facebook.presto.execution.SqlQueryManager.addCompletionCallback; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public class QueryQueue { private final int maxQueuedQueries; private final AtomicInteger queryQueueSize = new AtomicInteger(); private final AtomicInteger queuePermits; private final AsyncSemaphore<QueueEntry> asyncSemaphore; QueryQueue(Executor queryExecutor, int maxQueuedQueries, int maxConcurrentQueries) { checkNotNull(queryExecutor, "queryExecutor is null"); checkArgument(maxQueuedQueries > 0, "maxQueuedQueries must be greater than zero"); checkArgument(maxConcurrentQueries > 0, "maxConcurrentQueries must be greater than zero"); this.maxQueuedQueries = maxQueuedQueries; this.queuePermits = new AtomicInteger(maxQueuedQueries + maxConcurrentQueries); this.asyncSemaphore = new AsyncSemaphore<>(maxConcurrentQueries, queryExecutor, queueEntry -> { QueuedExecution queuedExecution = queueEntry.dequeue(); if (queuedExecution != null) { queuedExecution.start(); return queuedExecution.getCompletionFuture(); } return Futures.immediateFuture(null); }); } @Managed public int getQueueSize() { return queryQueueSize.get(); } public boolean reserve(QueryExecution queryExecution) { if (queuePermits.decrementAndGet() < 0) { queuePermits.incrementAndGet(); return false; } addCompletionCallback(queryExecution, queuePermits::incrementAndGet); return true; } public boolean enqueue(QueuedExecution queuedExecution) { if (queryQueueSize.incrementAndGet() > maxQueuedQueries) { queryQueueSize.decrementAndGet(); return false; } // Add a callback to dequeue the entry if it is ever completed. // This enables us to remove the entry sooner if is cancelled before starting, // and has no effect if called after starting. QueueEntry entry = new QueueEntry(queuedExecution, queryQueueSize::decrementAndGet); queuedExecution.getCompletionFuture().addListener(entry::dequeue, MoreExecutors.directExecutor()); asyncSemaphore.submit(entry); return true; } private static class QueueEntry { private final AtomicReference<QueuedExecution> queryExecution; private final Runnable onDequeue; private QueueEntry(QueuedExecution queuedExecution, Runnable onDequeue) { checkNotNull(queuedExecution, "queueableExecution is null"); this.queryExecution = new AtomicReference<>(queuedExecution); this.onDequeue = checkNotNull(onDequeue, "onDequeue is null"); } public QueuedExecution dequeue() { QueuedExecution value = queryExecution.getAndSet(null); if (value != null) { onDequeue.run(); } return value; } } }
presto-main/src/main/java/com/facebook/presto/execution/QueryQueue.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.execution; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.MoreExecutors; import io.airlift.concurrent.AsyncSemaphore; import org.weakref.jmx.Managed; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static com.facebook.presto.execution.SqlQueryManager.addCompletionCallback; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public class QueryQueue { private final int maxQueuedQueries; private final AtomicInteger queryQueueSize = new AtomicInteger(); private final AtomicInteger queuePermits; private final AsyncSemaphore<QueueEntry> asyncSemaphore; QueryQueue(Executor queryExecutor, int maxQueuedQueries, int maxConcurrentQueries) { checkNotNull(queryExecutor, "queryExecutor is null"); checkArgument(maxQueuedQueries > 0, "maxQueuedQueries must be greater than zero"); checkArgument(maxConcurrentQueries > 0, "maxConcurrentQueries must be greater than zero"); this.maxQueuedQueries = maxQueuedQueries; this.queuePermits = new AtomicInteger(maxQueuedQueries + maxConcurrentQueries); this.asyncSemaphore = new AsyncSemaphore<>(maxConcurrentQueries, queryExecutor, queueEntry -> { QueuedExecution queuedExecution = queueEntry.dequeue(); if (queuedExecution != null) { queuedExecution.start(); return queuedExecution.getCompletionFuture(); } return Futures.immediateFuture(null); }); } @Managed public int getQueueSize() { return queryQueueSize.get(); } public boolean reserve(QueryExecution queryExecution) { if (queuePermits.getAndDecrement() < 0) { queuePermits.incrementAndGet(); return false; } addCompletionCallback(queryExecution, queuePermits::incrementAndGet); return true; } public boolean enqueue(QueuedExecution queuedExecution) { if (queryQueueSize.incrementAndGet() > maxQueuedQueries) { queryQueueSize.decrementAndGet(); return false; } // Add a callback to dequeue the entry if it is ever completed. // This enables us to remove the entry sooner if is cancelled before starting, // and has no effect if called after starting. QueueEntry entry = new QueueEntry(queuedExecution, queryQueueSize::decrementAndGet); queuedExecution.getCompletionFuture().addListener(entry::dequeue, MoreExecutors.directExecutor()); asyncSemaphore.submit(entry); return true; } private static class QueueEntry { private final AtomicReference<QueuedExecution> queryExecution; private final Runnable onDequeue; private QueueEntry(QueuedExecution queuedExecution, Runnable onDequeue) { checkNotNull(queuedExecution, "queueableExecution is null"); this.queryExecution = new AtomicReference<>(queuedExecution); this.onDequeue = checkNotNull(onDequeue, "onDequeue is null"); } public QueuedExecution dequeue() { QueuedExecution value = queryExecution.getAndSet(null); if (value != null) { onDequeue.run(); } return value; } } }
decrementAndGet should be used in QueryQueue reserve method Previously getAndDecrement was used. This allowed more permits than maxQueuedQueries + maxConcurrentQueries.
presto-main/src/main/java/com/facebook/presto/execution/QueryQueue.java
decrementAndGet should be used in QueryQueue reserve method
<ide><path>resto-main/src/main/java/com/facebook/presto/execution/QueryQueue.java <ide> <ide> public boolean reserve(QueryExecution queryExecution) <ide> { <del> if (queuePermits.getAndDecrement() < 0) { <add> if (queuePermits.decrementAndGet() < 0) { <ide> queuePermits.incrementAndGet(); <ide> return false; <ide> }
Java
bsd-3-clause
3615fdc4e260c88e15468ccda46ce79b3d19e14c
0
raptor-chess/raptor-chess-interface,evilwan/raptor-chess-interface,raptor-chess-interface/raptor-chess-interface,NightSwimming/Raptor-Chess,raptor-chess/raptor-chess-interface,evilwan/raptor-chess-interface,evilwan/raptor-chess-interface,evilwan/raptor-chess-interface,raptor-chess/raptor-chess-interface,raptor-chess/raptor-chess-interface,raptor-chess-interface/raptor-chess-interface,raptor-chess-interface/raptor-chess-interface,raptor-chess-interface/raptor-chess-interface,NightSwimming/Raptor-Chess,NightSwimming/Raptor-Chess,NightSwimming/Raptor-Chess
/** * New BSD License * http://www.opensource.org/licenses/bsd-license.php * Copyright (c) 2009, RaptorProject (http://code.google.com/p/raptor-chess-interface/) * 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 RaptorProject nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package raptor.connector.ics; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.URLEncoder; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.WordUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import raptor.Raptor; import raptor.chat.ChatEvent; import raptor.chat.ChatType; import raptor.chess.BughouseGame; import raptor.chess.Game; import raptor.chess.Move; import raptor.chess.util.GameUtils; import raptor.connector.Connector; import raptor.connector.ConnectorListener; import raptor.connector.ics.timeseal.TimesealingSocket; import raptor.pref.PreferenceKeys; import raptor.pref.RaptorPreferenceStore; import raptor.script.ChatScript; import raptor.script.ChatScriptContext; import raptor.script.GameScriptContext; import raptor.script.ScriptConnectorType; import raptor.script.ScriptContext; import raptor.script.ChatScript.ChatScriptType; import raptor.service.BughouseService; import raptor.service.ChatService; import raptor.service.GameService; import raptor.service.ScriptService; import raptor.service.SeekService; import raptor.service.SoundService; import raptor.service.ThreadService; import raptor.service.GameService.GameServiceAdapter; import raptor.service.GameService.GameServiceListener; import raptor.service.ScriptService.ScriptServiceListener; import raptor.swt.chat.ChatConsoleWindowItem; import raptor.swt.chat.ChatUtils; import raptor.swt.chat.controller.ChannelController; import raptor.swt.chat.controller.MainController; import raptor.swt.chat.controller.PartnerTellController; import raptor.swt.chat.controller.PersonController; import raptor.swt.chat.controller.RegExController; import raptor.swt.chess.ChessBoardUtils; import raptor.util.BrowserUtils; import raptor.util.RaptorStringTokenizer; /** * An ics (internet chess server) connector. You will need to supply yuor own * IcsConnectorContext because they are all different. You might also need to * override some methods in order to get it working. */ public abstract class IcsConnector implements Connector { private static final Log LOG = LogFactory.getLog(IcsConnector.class); protected class IcsChatScriptContext extends IcsScriptContext implements ChatScriptContext { ChatEvent event; boolean ignoreEvent = false; public IcsChatScriptContext(ChatEvent event) { this.event = event; } public IcsChatScriptContext(String... params) { super(params); } public String getMessage() { if (event == null) { Raptor.getInstance().alert( "getMessage is not supported in toolbar scripts"); return null; } else { return event.getMessage(); } } public String getMessageChannel() { if (event == null) { Raptor .getInstance() .alert( "getMessageChannel is not supported in toolbar scripts"); return null; } else { return event.getChannel(); } } public String getMessageSource() { if (event == null) { Raptor.getInstance().alert( "getMessageSource is not supported in toolbar scripts"); return null; } else { return event.getSource(); } } } protected class IcsScriptContext implements ScriptContext { protected String[] parameters; protected IcsScriptContext(String... parameters) { this.parameters = parameters; } public void alert(String message) { Raptor.getInstance().alert(message); } public String[] getParameters() { return parameters; } public long getPingMillis() { return lastPingTime; } public String getUserFollowing() { Raptor.getInstance().alert( "getUserFollowing is not yet implemented."); return ""; } public int getUserIdleSeconds() { return (int) (System.currentTimeMillis() - lastSendTime) / 1000; } public String getUserName() { return userName; } public String getValue(String key) { return scriptHash.get(key); } public void launchProcess(String... commandAndArgs) { try { Runtime.getRuntime().exec(commandAndArgs); } catch (Throwable t) { onError("Error launching process: " + Arrays.toString(commandAndArgs), t); } } public void openChannelTab(String channel) { if (!Raptor.getInstance().getWindow().containsChannelItem( IcsConnector.this, channel)) { ChatConsoleWindowItem windowItem = new ChatConsoleWindowItem( new ChannelController(IcsConnector.this, channel)); Raptor.getInstance().getWindow().addRaptorWindowItem( windowItem, false); ChatUtils.appendPreviousChatsToController(windowItem .getConsole()); } } public void openPartnerTab() { if (!Raptor.getInstance().getWindow().containsPartnerTellItem( IcsConnector.this)) { ChatConsoleWindowItem windowItem = new ChatConsoleWindowItem( new PartnerTellController(IcsConnector.this)); Raptor.getInstance().getWindow().addRaptorWindowItem( windowItem, false); ChatUtils.appendPreviousChatsToController(windowItem .getConsole()); } } public void openPersonTab(String person) { if (!Raptor.getInstance().getWindow().containsPersonalTellItem( IcsConnector.this, person)) { ChatConsoleWindowItem windowItem = new ChatConsoleWindowItem( new PersonController(IcsConnector.this, person)); Raptor.getInstance().getWindow().addRaptorWindowItem( windowItem, false); ChatUtils.appendPreviousChatsToController(windowItem .getConsole()); } } public void openRegExTab(String regularExpression) { if (!Raptor.getInstance().getWindow().containsPartnerTellItem( IcsConnector.this)) { ChatConsoleWindowItem windowItem = new ChatConsoleWindowItem( new RegExController(IcsConnector.this, regularExpression)); Raptor.getInstance().getWindow().addRaptorWindowItem( windowItem, false); ChatUtils.appendPreviousChatsToController(windowItem .getConsole()); } } public void openUrl(String url) { BrowserUtils.openUrl(url); } public void playBughouseSound(String soundName) { SoundService.getInstance().playBughouseSound(soundName); } public void playSound(String soundName) { SoundService.getInstance().playSound(soundName); } public String prompt(String message) { return Raptor.getInstance().promptForText(message); } public void send(String message) { IcsConnector.this.sendMessage(message); } public void sendHidden(String message) { if (message.contains("tell")) { IcsConnector.this.sendMessage(message, true, ChatType.TOLD); } else { IcsConnector.this.sendMessage(message, true); } } public void sendToConsole(String message) { publishEvent(new ChatEvent(null, ChatType.INTERNAL, message)); } public void speak(String message) { SoundService.getInstance().textToSpeech(message); } public void storeValue(String key, String value) { scriptHash.put(key, value); } public String urlEncode(String stringToEncode) { try { return URLEncoder.encode(stringToEncode, "UTF-8"); } catch (UnsupportedEncodingException uee) { }// Eat it wont happen. return stringToEncode; } } protected BughouseService bughouseService; protected ChatService chatService; protected List<ConnectorListener> connectorListeners = Collections .synchronizedList(new ArrayList<ConnectorListener>(10)); protected IcsConnectorContext context; protected String currentProfileName; protected Thread daemonThread; protected GameService gameService; protected Map<String, String> scriptHash = new HashMap<String, String>(); protected SeekService seekService; /** * Adds the game windows to the RaptorAppWindow. */ protected GameServiceListener gameServiceListener = new GameServiceAdapter() { @Override public void gameCreated(Game game) { if (game instanceof BughouseGame) { if (((BughouseGame) game).getOtherBoard() == null) { ChessBoardUtils.openBoard(IcsUtils.buildController(game, IcsConnector.this)); } else { ChessBoardUtils.openBoard(IcsUtils.buildController(game, IcsConnector.this, true), true); } } else { ChessBoardUtils.openBoard(IcsUtils.buildController(game, IcsConnector.this)); } } }; protected boolean hasSentLogin = false; protected boolean hasSentPassword = false; protected List<ChatType> ignoringChatTypes = new ArrayList<ChatType>(); protected StringBuilder inboundMessageBuffer = new StringBuilder(25000); protected ByteBuffer inputBuffer = ByteBuffer.allocate(25000); protected ReadableByteChannel inputChannel; protected boolean isConnecting; protected boolean isLoggedIn = false; protected Runnable keepAlive = new Runnable() { public void run() { LOG.error("In keepAlive.run() " + (System.currentTimeMillis() - lastSendTime > 60000 * 50)); if (isConnected() && getPreferences().getBoolean( context.getShortName() + "-keep-alive") && System.currentTimeMillis() - lastSendTime > 60000 * 50) { sendMessage("date", true); publishEvent(new ChatEvent("", ChatType.INTERNAL, "The \"date\" command was just sent as a keep alive.")); ThreadService.getInstance().scheduleOneShot(60000 * 30, this); } } }; protected long lastPingTime; protected long lastSendTime; protected long lastSendPingTime; protected ChatConsoleWindowItem mainConsoleWindowItem; protected Socket socket; protected String userName; protected String userFollowing; protected String[] bughouseSounds = SoundService.getInstance() .getBughouseSoundKeys(); protected ChatScript[] personTellMessageScripts = null; protected ChatScript[] channelTellMessageScripts = null; protected ChatScript[] partnerTellMessageScripts = null; protected ScriptServiceListener scriptServiceListener = new ScriptServiceListener() { public void onChatScriptsChanged() { if (isConnected()) { refreshChatScripts(); } } public void onGameScriptsChanged() { } }; /** * Constructs an IcsConnector with the specified context. * * @param context */ protected IcsConnector(IcsConnectorContext context) { this.context = context; chatService = new ChatService(this); seekService = new SeekService(this); gameService = new GameService(); gameService.addGameServiceListener(gameServiceListener); setBughouseService(new BughouseService(this)); } public void acceptSeek(String adId) { sendMessage("play " + adId, true); } /** * Adds a connector listener to the connector. */ public void addConnectorListener(ConnectorListener listener) { connectorListeners.add(listener); } public String[] breakUpMessage(StringBuilder message) { if (message.length() <= 330) { return new String[] { message + "\n" }; } else { int firstSpace = message.indexOf(" "); List<String> result = new ArrayList<String>(5); if (firstSpace != -1) { int secondSpace = message.indexOf(" ", firstSpace + 1); if (secondSpace != -1) { String beginingText = message.substring(0, secondSpace + 1); String wrappedText = WordUtils.wrap(message.toString(), 330, "\n", true); String[] wrapped = wrappedText.split("\n"); result.add(wrapped[0] + "\n"); for (int i = 1; i < wrapped.length; i++) { result.add(beginingText + wrapped[i] + "\n"); } } else { result.add(message.substring(0, 330) + "\n"); publishEvent(new ChatEvent( null, ChatType.INTERNAL, "Your message was too long and Raptor could not find a nice " + "way to break it up. Your message was trimmed to:\n" + result.get(0))); } } else { result.add(message.substring(0, 330) + "\n"); publishEvent(new ChatEvent( null, ChatType.INTERNAL, "Your message was too long and Raptor could not find a nice " + "way to break it up. Your message was trimmed to:\n" + result.get(0))); } return result.toArray(new String[0]); } } /** * Connects to ics using the settings in preferences. */ public void connect() { connect(Raptor.getInstance().getPreferences().getString( context.getPreferencePrefix() + "profile")); } /** * Disconnects from the ics. */ public void disconnect() { synchronized (this) { if (isConnected()) { try { ScriptService.getInstance().removeScriptServiceListener( scriptServiceListener); if (inputChannel != null) { try { inputChannel.close(); } catch (Throwable t) { } } if (socket != null) { try { socket.close(); } catch (Throwable t) { } } if (daemonThread != null) { try { if (daemonThread.isAlive()) { daemonThread.interrupt(); } } catch (Throwable t) { } } if (keepAlive != null) { ThreadService.getInstance().getExecutor().remove( keepAlive); } } catch (Throwable t) { } finally { socket = null; inputChannel = null; daemonThread = null; } try { String messageLeftInBuffer = drainInboundMessageBuffer(); if (StringUtils.isNotBlank(messageLeftInBuffer)) { parseMessage(messageLeftInBuffer); } } catch (Throwable t) { } finally { } } isConnecting = false; publishEvent(new ChatEvent(null, ChatType.INTERNAL, "Disconnected")); Raptor.getInstance().getWindow().setPingTime(this, -1); fireDisconnected(); LOG.error("Disconnected from " + getShortName()); } } public void dispose() { if (isConnected()) { disconnect(); } if (connectorListeners != null) { connectorListeners.clear(); connectorListeners = null; } if (chatService != null) { chatService.dispose(); chatService = null; } if (gameService != null) { gameService.removeGameServiceListener(gameServiceListener); gameService.dispose(); gameService = null; } if (inputBuffer != null) { inputBuffer.clear(); inputBuffer = null; } if (keepAlive != null) { ThreadService.getInstance().getExecutor().remove(keepAlive); keepAlive = null; } if (inputChannel != null) { try { inputChannel.close(); } catch (Throwable t) { } inputChannel = null; } LOG.info("Disposed " + getShortName() + "Connector"); } public BughouseService getBughouseService() { return bughouseService; } public String[][] getChannelActions(String channel) { return new String[][] { new String[] { "Add Channel " + channel, "+channel " + channel }, new String[] { "Remove Channel " + channel, "-channel " + channel }, new String[] { "In Channel " + channel, "in " + channel } }; } public String getChannelTabPrefix(String channel) { return "tell " + channel + " "; } public ChatScriptContext getChatScriptContext(String... params) { return new IcsChatScriptContext(params); } public ChatService getChatService() { return chatService; } public IcsConnectorContext getContext() { return context; } public String getDescription() { return context.getDescription(); } public String[][] getGameIdActions(String gameId) { return new String[][] { new String[] { "Observe game " + gameId, "observe " + gameId }, new String[] { "All observers in game " + gameId, "allobs " + gameId }, { "Move list for game " + gameId, "moves " + gameId } }; } public GameService getGameService() { return gameService; } public GameScriptContext getGametScriptContext() { return null; } public String getPartnerTellPrefix() { return "ptell "; } public String[][] getPersonActions(String person) { return new String[][] { new String[] { "Finger " + person, "finger " + person }, new String[] { "Observe " + person, "observe " + person }, new String[] { "History " + person, "history " + person }, new String[] { "Follow " + person, "follow " + person }, new String[] { "Partner " + person, "partner " + person }, new String[] { "Vars " + person, "vars " + person }, new String[] { "Censor " + person, "+censor " + person }, new String[] { "Uncensor " + person, "-censor " + person }, new String[] { "Noplay " + person, "+noplay " + person }, new String[] { "Unnoplay " + person, "noplay " + person } }; } public String getPersonTabPrefix(String person) { return "tell " + person + " "; } public RaptorPreferenceStore getPreferences() { return Raptor.getInstance().getPreferences(); } public String getPrompt() { return context.getPrompt(); } public ScriptConnectorType getScriptConnectorType() { return ScriptConnectorType.ICS; } public SeekService getSeekService() { return seekService; } public String getShortName() { return context.getShortName(); } public String getTellToString(String handle) { return "tell " + handle + " "; } /** * Returns the name of the current user logged in. */ public String getUserName() { return userName; } public boolean isConnected() { return socket != null && inputChannel != null && daemonThread != null; } public boolean isConnecting() { return isConnecting; } public boolean isLikelyChannel(String word) { return IcsUtils.isLikelyChannel(word); } public boolean isLikelyGameId(String word) { return IcsUtils.isLikelyGameId(word); } public boolean isLikelyPartnerTell(String outboundMessage) { return StringUtils.startsWithIgnoreCase(outboundMessage, "pt"); } public boolean isLikelyPerson(String word) { return IcsUtils.isLikelyPerson(word); } public void makeMove(Game game, Move move) { sendMessage(move.getLan(), true); } public void matchBughouse(String playerName, boolean isRated, int time, int inc) { sendMessage("$$match " + playerName + " " + time + " " + inc + " " + (isRated ? "rated" : "unrated") + " bughouse"); } public void onAbortKeyPress() { sendMessage("$$abort", true); } public void onAcceptKeyPress() { sendMessage("$$accept", true); } /** * Auto logs in if that is configured. */ public void onAutoConnect() { if (Raptor.getInstance().getPreferences().getBoolean( context.getPreferencePrefix() + "auto-connect")) { connect(); } } public void onDeclineKeyPress() { sendMessage("$$decline", true); } public void onDraw(Game game) { sendMessage("$$draw", true); } public void onError(String message) { onError(message, null); } public void onError(String message, Throwable t) { String errorMessage = IcsUtils .cleanupMessage("Critical error occured! We are trying to make Raptor " + "bug free and we need your help! Please take a moment to report this " + "error at\nhttp://code.google.com/p/raptor-chess-interface/issues/list\n\n Issue: " + message + (t == null ? "" : "\n" + ExceptionUtils.getFullStackTrace(t))); publishEvent(new ChatEvent(null, ChatType.INTERNAL, errorMessage)); } public void onExamineModeBack(Game game) { sendMessage("$$back", true); } public void onExamineModeCommit(Game game) { sendMessage("$$commit", true); } public void onExamineModeFirst(Game game) { sendMessage("$$back 300", true); } public void onExamineModeForward(Game game) { sendMessage("$$forward 1", true); } public void onExamineModeLast(Game game) { sendMessage("$$forward 300", true); } public void onExamineModeRevert(Game game) { sendMessage("$$revert", true); } public void onObserveGame(String gameId) { sendMessage("$$observe " + gameId, true); } public void onPartner(String bugger) { sendMessage("$$partner " + bugger, true); } public void onRematchKeyPress() { sendMessage("$$rematch", true); } /** * Resigns the specified game. */ public void onResign(Game game) { sendMessage("$$resign", true); } public void onSetupClear(Game game) { sendMessage("$$bsetup clear", true); } public void onSetupClearSquare(Game game, int square) { sendMessage("$$x@" + GameUtils.getSan(square), true); } public void onSetupComplete(Game game) { sendMessage("bsetup done", true); } public void onSetupFromFEN(Game game, String fen) { sendMessage("$$bsetup fen " + fen, true); } public void onSetupStartPosition(Game game) { sendMessage("$$bsetup start", true); } public void onUnexamine(Game game) { sendMessage("$$unexamine", true); } public void onUnobserve(Game game) { sendMessage("$$unobs " + game.getId(), true); } public String parseChannel(String word) { return IcsUtils.stripChannel(word); } public String parseGameId(String word) { return IcsUtils.stripGameId(word); } public String parsePerson(String word) { return IcsUtils.stripWord(word); } /** * Removes a connector listener from the connector. */ public void removeConnectorListener(ConnectorListener listener) { connectorListeners.remove(listener); } public String removeLineBreaks(String message) { return IcsUtils.removeLineBreaks(message); } public void sendBugAvailableTeamsMessage() { sendMessage("$$bugwho p", true, ChatType.BUGWHO_AVAILABLE_TEAMS); } public void sendBugGamesMessage() { sendMessage("$$bugwho g", true, ChatType.BUGWHO_GAMES); } public void sendBugUnpartneredBuggersMessage() { sendMessage("$$bugwho u", true, ChatType.BUGWHO_UNPARTNERED_BUGGERS); } public void sendGetSeeksMessage() { sendMessage("$$sought all", true, ChatType.SEEKS); } public void sendMessage(String message) { sendMessage(message, false, null); } /** * Sends a message to the connector. A ChatEvent of OUTBOUND type should * only be published if isHidingFromUser is false. */ public void sendMessage(String message, boolean isHidingFromUser) { sendMessage(message, isHidingFromUser, null); } /** * Sends a message to the connector. A ChatEvent of OUTBOUND type should * only be published containing the message if isHidingFromUser is false. * The next message the connector reads in that is of the specified type * should not be published to the ChatService. */ public void sendMessage(String message, boolean isHidingFromUser, ChatType hideNextChatType) { if (isConnected()) { StringBuilder builder = new StringBuilder(message); IcsUtils.filterOutbound(builder); if (LOG.isDebugEnabled()) { LOG.debug(context.getShortName() + "Connector Sending: " + builder.toString().trim()); } if (hideNextChatType != null) { ignoringChatTypes.add(hideNextChatType); } // Only one thread at a time should write to the socket. synchronized (socket) { try { String[] messages = breakUpMessage(builder); for (String current : messages) { socket.getOutputStream().write(current.getBytes()); socket.getOutputStream().flush(); } if (!message.startsWith("$$")) { lastSendPingTime = System.currentTimeMillis(); } else { lastSendTime = lastSendPingTime = System .currentTimeMillis(); } } catch (Throwable t) { publishEvent(new ChatEvent(null, ChatType.INTERNAL, "Error: " + t.getMessage())); disconnect(); } } if (!isHidingFromUser) { publishEvent(new ChatEvent(null, ChatType.OUTBOUND, message .trim())); } } else { publishEvent(new ChatEvent(null, ChatType.INTERNAL, "Error: Unable to send " + message + " to " + getShortName() + ". There is currently no connection.")); } } /** * Connects with the specified profile name. */ protected void connect(final String profileName) { if (isConnected()) { throw new IllegalStateException("You are already connected to " + getShortName() + " . Disconnect before invoking connect."); } resetConnectionStateVars(); currentProfileName = profileName; final String profilePrefix = context.getPreferencePrefix() + profileName + "-"; if (LOG.isDebugEnabled()) { LOG.debug("Profile " + currentProfileName + " Prefix=" + profilePrefix); } if (mainConsoleWindowItem == null) { // Add the main console tab to the raptor window. createMainConsoleWindowItem(); Raptor.getInstance().getWindow().addRaptorWindowItem( mainConsoleWindowItem, false); } else if (!Raptor.getInstance().getWindow().isBeingManaged( mainConsoleWindowItem)) { // Add a new main console to the raptor window since the existing // one is no longer being managed (it was already disposed). createMainConsoleWindowItem(); Raptor.getInstance().getWindow().addRaptorWindowItem( mainConsoleWindowItem, false); } // If its being managed no need to do anything it should adjust itself // as the state of the connector changes from the ConnectorListener it // registered. if (LOG.isInfoEnabled()) { LOG.info(getShortName() + " Connecting to " + getPreferences().getString(profilePrefix + "server-url") + " " + getPreferences().getInt(profilePrefix + "port")); } publishEvent(new ChatEvent(null, ChatType.INTERNAL, "Connecting to " + getPreferences().getString(profilePrefix + "server-url") + " " + getPreferences().getInt(profilePrefix + "port") + (getPreferences().getBoolean( profilePrefix + "timeseal-enabled") ? " with " : " without ") + "timeseal ...")); ThreadService.getInstance().run(new Runnable() { public void run() { try { if (getPreferences().getBoolean( profilePrefix + "timeseal-enabled")) { // TO DO: rewrite TimesealingSocket to use a // SocketChannel. socket = new TimesealingSocket( getPreferences().getString( profilePrefix + "server-url"), getPreferences().getInt(profilePrefix + "port"), getInitialTimesealString()); publishEvent(new ChatEvent(null, ChatType.INTERNAL, "Timeseal connection string " + getInitialTimesealString())); } else { socket = new Socket(getPreferences().getString( profilePrefix + "server-url"), getPreferences() .getInt(profilePrefix + "port")); } publishEvent(new ChatEvent(null, ChatType.INTERNAL, "Connected")); inputChannel = Channels.newChannel(socket.getInputStream()); SoundService.getInstance().playSound("alert"); daemonThread = new Thread(new Runnable() { public void run() { messageLoop(); } }); daemonThread.setName("FicsConnectorDaemon"); daemonThread.setPriority(Thread.MAX_PRIORITY); daemonThread.start(); if (LOG.isInfoEnabled()) { LOG.info(getShortName() + " Connection successful"); } } catch (Throwable ce) { publishEvent(new ChatEvent(null, ChatType.INTERNAL, "Error: " + ce.getMessage())); disconnect(); return; } } }); isConnecting = true; if (getPreferences().getBoolean( context.getPreferencePrefix() + "-keep-alive")) { ThreadService.getInstance().scheduleOneShot(300000, keepAlive); } ScriptService.getInstance().addScriptServiceListener( scriptServiceListener); refreshChatScripts(); fireConnecting(); } protected void createMainConsoleWindowItem() { mainConsoleWindowItem = new ChatConsoleWindowItem(new MainController( this)); } /** * Removes all of the characters from inboundMessageBuffer and returns the * string removed. */ protected String drainInboundMessageBuffer() { return drainInboundMessageBuffer(inboundMessageBuffer.length()); } /** * Removes characters 0-index from inboundMessageBuffer and returns the * string removed. */ protected String drainInboundMessageBuffer(int index) { String result = inboundMessageBuffer.substring(0, index); inboundMessageBuffer.delete(0, index); return result; } protected void fireConnected() { ThreadService.getInstance().run(new Runnable() { public void run() { synchronized (connectorListeners) { for (ConnectorListener listener : connectorListeners) { listener.onConnect(); } } } }); } protected void fireConnecting() { ThreadService.getInstance().run(new Runnable() { public void run() { synchronized (connectorListeners) { for (ConnectorListener listener : connectorListeners) { listener.onConnecting(); } } } }); } protected void fireDisconnected() { ThreadService.getInstance().run(new Runnable() { public void run() { synchronized (connectorListeners) { for (ConnectorListener listener : connectorListeners) { listener.onConnecting(); } } } }); } protected String getInitialTimesealString() { return Raptor.getInstance().getPreferences().getString( PreferenceKeys.TIMESEAL_INIT_STRING); } /** * The messageLoop. Reads the inputChannel and then invokes publishInput * with the text read. Should really never be invoked. */ protected void messageLoop() { try { while (true) { if (isConnected()) { int numRead = inputChannel.read(inputBuffer); if (numRead > 0) { if (LOG.isDebugEnabled()) { LOG.debug(context.getShortName() + "Connector " + "Read " + numRead + " bytes."); } inputBuffer.rewind(); byte[] bytes = new byte[numRead]; inputBuffer.get(bytes); inboundMessageBuffer.append(IcsUtils .cleanupMessage(new String(bytes))); try { onNewInput(); } catch (Throwable t) { onError(context.getShortName() + "Connector " + "Error in DaemonRun.onNewInput", t); } inputBuffer.clear(); } else { if (LOG.isDebugEnabled()) { LOG.debug(context.getShortName() + "Connector " + "Read 0 bytes disconnecting."); } disconnect(); break; } Thread.sleep(50); } else { if (LOG.isDebugEnabled()) { LOG.debug(context.getShortName() + "Connector " + "Not connected disconnecting."); } disconnect(); break; } } } catch (Throwable t) { if (t instanceof IOException) { LOG .debug( context.getShortName() + "Connector " + "IOException occured in messageLoop (These are common when disconnecting and ignorable)", t); } else { onError(context.getShortName() + "Connector Error in DaemonRun Thwoable", t); } disconnect(); } finally { LOG.debug(context.getShortName() + "Connector Leaving readInput"); } } /** * Processes a login message. Handles sending the user name and password * information and the enter if prompted to hit enter if logging in as a * guest. * * @param message * @param isLoginPrompt */ protected void onLoginEvent(String message, boolean isLoginPrompt) { String profilePrefix = context.getPreferencePrefix() + currentProfileName + "-"; if (isLoginPrompt) { if (getPreferences().getBoolean(profilePrefix + "is-anon-guest") && !hasSentLogin) { parseMessage(message); hasSentLogin = true; sendMessage("guest", true); } else if (!hasSentLogin) { parseMessage(message); hasSentLogin = true; String handle = getPreferences().getString( profilePrefix + "user-name"); if (StringUtils.isNotBlank(handle)) { sendMessage(handle, true); } } else { parseMessage(message); } } else { if (getPreferences().getBoolean(profilePrefix + "is-anon-guest") && !hasSentPassword) { hasSentPassword = true; parseMessage(message); sendMessage("", true); } else if (getPreferences().getBoolean( profilePrefix + "is-named-guest") && !hasSentPassword) { hasSentPassword = true; parseMessage(message); sendMessage("", true); } else if (!hasSentPassword) { hasSentPassword = true; parseMessage(message); String password = getPreferences().getString( profilePrefix + "password"); if (StringUtils.isNotBlank(password)) { // Don't show the users password. sendMessage(password, true); } } else { parseMessage(message); } } } /** * This method is invoked by the run method when there is new text to be * handled. It buffers text until a prompt is found then invokes * parseMessage. * * This method also handles login logic which is tricky. */ protected void onNewInput() { if (lastSendPingTime != 0) { ThreadService.getInstance().run(new Runnable() { public void run() { long currentTime = System.currentTimeMillis(); lastPingTime = currentTime - lastSendPingTime; Raptor.getInstance().getWindow().setPingTime( IcsConnector.this, lastPingTime); lastSendPingTime = 0; } }); } if (isLoggedIn) { // If we are logged in. Then parse out all the text between the // prompts. int promptIndex = -1; while ((promptIndex = inboundMessageBuffer.indexOf(context .getRawPrompt())) != -1) { String message = drainInboundMessageBuffer(promptIndex + context.getRawPrompt().length()); parseMessage(message); } } else { // We are not logged in. // There are several complex cases here depending on the prompt // we are waiting on. // There is a login prompt, a password prompt, an enter prompt, // and also you have to handle invalid logins. int loggedInMessageIndex = inboundMessageBuffer.indexOf(context .getLoggedInMessage()); if (loggedInMessageIndex != -1) { int nameStartIndex = inboundMessageBuffer.indexOf(context .getLoggedInMessage()) + context.getLoggedInMessage().length(); int endIndex = inboundMessageBuffer.indexOf("****", nameStartIndex); if (endIndex != -1) { userName = IcsUtils.stripTitles(inboundMessageBuffer .substring(nameStartIndex, endIndex).trim()); LOG.info(context.getShortName() + "Connector " + "login complete. userName=" + userName); isLoggedIn = true; onSuccessfulLogin(); // Since we are now logged in, just buffer the text // received and // invoke parseMessage when the prompt arrives. } else { // We have yet to receive the **** closing message so // wait // until it arrives. } } else { int loginIndex = inboundMessageBuffer.indexOf(context .getLoginPrompt()); if (loginIndex != -1) { String event = drainInboundMessageBuffer(loginIndex + context.getLoginPrompt().length()); onLoginEvent(event, true); } else { int enterPromptIndex = inboundMessageBuffer.indexOf(context .getEnterPrompt()); if (enterPromptIndex != -1) { String event = drainInboundMessageBuffer(enterPromptIndex + context.getEnterPrompt().length()); onLoginEvent(event, false); } else { int passwordPromptIndex = inboundMessageBuffer .indexOf(context.getPasswordPrompt()); if (passwordPromptIndex != -1) { String event = drainInboundMessageBuffer(passwordPromptIndex + context.getPasswordPrompt().length()); onLoginEvent(event, false); } else { int errorMessageIndex = inboundMessageBuffer .indexOf(context.getLoginErrorMessage()); if (errorMessageIndex != -1) { String event = drainInboundMessageBuffer(); parseMessage(event); } } } } } } } protected abstract void onSuccessfulLogin(); /** * Processes a message. If the user is logged in, message will be all of the * text received since the last prompt from fics. If the user is not logged * in, message will be all of the text received since the last login prompt. * * message will always use \n as the line delimiter. */ protected void parseMessage(String message) { ChatEvent[] events = context.getParser().parse(message); for (ChatEvent event : events) { event.setMessage(IcsUtils .maciejgFormatToUnicode(event.getMessage())); publishEvent(event); } } /** * Plays the bughouse sound for the specified ptell. Returns true if a * bughouse sound was played. */ protected boolean playBughouseSounds(final String ptell) { boolean result = false; if (getPreferences().getBoolean(PreferenceKeys.APP_SOUND_ENABLED)) { int colonIndex = ptell.indexOf(":"); if (colonIndex != -1) { String message = ptell .substring(colonIndex + 1, ptell.length()).trim(); RaptorStringTokenizer tok = new RaptorStringTokenizer(message, "\n", true); message = tok.nextToken().trim(); for (String bugSound : bughouseSounds) { if (bugSound.equalsIgnoreCase(message)) { // This creates its own thread. SoundService.getInstance().playBughouseSound(bugSound); result = true; break; } } } else { onError("Received a ptell event without a colon", new Exception()); } } return result; } /** * Processes the scripts for the specified chat event. Script processing is * kicked off on a different thread. */ protected void processScripts(final ChatEvent event) { ThreadService.getInstance().run(new Runnable() { public void run() { if (personTellMessageScripts != null && event.getType() == ChatType.TELL) { for (ChatScript script : personTellMessageScripts) { ChatScript newScript = ScriptService.getInstance() .getChatScript(script.getName()); if (newScript != null) { newScript.execute(new IcsChatScriptContext(event)); } } } else if (channelTellMessageScripts != null && event.getType() == ChatType.CHANNEL_TELL) { for (ChatScript script : channelTellMessageScripts) { ChatScript newScript = ScriptService.getInstance() .getChatScript(script.getName()); if (newScript != null) { newScript.execute(new IcsChatScriptContext(event)); } } } else if (partnerTellMessageScripts != null && event.getType() == ChatType.PARTNER_TELL) { for (ChatScript script : partnerTellMessageScripts) { ChatScript newScript = ScriptService.getInstance() .getChatScript(script.getName()); if (newScript != null) { newScript.execute(new IcsChatScriptContext(event)); } } } } }); } /** * Publishes the specified event to the chat service. Currently all messages * are published on separate threads via ThreadService. */ protected void publishEvent(final ChatEvent event) { if (chatService != null) { // Could have been disposed. if (LOG.isDebugEnabled()) { LOG.debug("Publishing event : " + event); } // Sets the user following. This is used in the IcsParser to // determine if white is on top or not. if (event.getType() == ChatType.FOLLOWING) { userFollowing = event.getSource(); } else if (event.getType() == ChatType.NOT_FOLLOWING) { userFollowing = null; } if (event.getType() == ChatType.PARTNER_TELL || event.getType() == ChatType.TELL || event.getType() == ChatType.CHANNEL_TELL) { processScripts(event); } if (event.getType() == ChatType.PARTNER_TELL) { if (playBughouseSounds(event.getMessage())) { // No need to publish it we played the sound. return; } } int ignoreIndex = ignoringChatTypes.indexOf(event.getType()); if (ignoreIndex != -1) { ignoringChatTypes.remove(ignoreIndex); } else { // It is interesting to note messages are handled sequentially // up to this point. chatService will publish the event // asynchronously. chatService.publishChatEvent(event); } } } protected void refreshChatScripts() { personTellMessageScripts = ScriptService.getInstance().getChatScripts( this, ChatScriptType.OnPersonTellMessages); channelTellMessageScripts = ScriptService.getInstance().getChatScripts( this, ChatScriptType.onChannelTellMessages); partnerTellMessageScripts = ScriptService.getInstance().getChatScripts( this, ChatScriptType.OnPartnerTellMessages); } /** * Resets state variables related to the connection state. */ protected void resetConnectionStateVars() { isLoggedIn = false; hasSentLogin = false; hasSentPassword = false; userFollowing = null; ignoringChatTypes.clear(); } protected void setUserFollowing(String userFollowing) { this.userFollowing = userFollowing; } private void setBughouseService(BughouseService bughouseService) { this.bughouseService = bughouseService; } }
raptor/src/raptor/connector/ics/IcsConnector.java
/** * New BSD License * http://www.opensource.org/licenses/bsd-license.php * Copyright (c) 2009, RaptorProject (http://code.google.com/p/raptor-chess-interface/) * 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 RaptorProject nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package raptor.connector.ics; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.URLEncoder; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.WordUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import raptor.Raptor; import raptor.chat.ChatEvent; import raptor.chat.ChatType; import raptor.chess.BughouseGame; import raptor.chess.Game; import raptor.chess.Move; import raptor.chess.util.GameUtils; import raptor.connector.Connector; import raptor.connector.ConnectorListener; import raptor.connector.ics.timeseal.TimesealingSocket; import raptor.pref.PreferenceKeys; import raptor.pref.RaptorPreferenceStore; import raptor.script.ChatScript; import raptor.script.ChatScriptContext; import raptor.script.GameScriptContext; import raptor.script.ScriptConnectorType; import raptor.script.ScriptContext; import raptor.script.ChatScript.ChatScriptType; import raptor.service.BughouseService; import raptor.service.ChatService; import raptor.service.GameService; import raptor.service.ScriptService; import raptor.service.SeekService; import raptor.service.SoundService; import raptor.service.ThreadService; import raptor.service.GameService.GameServiceAdapter; import raptor.service.GameService.GameServiceListener; import raptor.service.ScriptService.ScriptServiceListener; import raptor.swt.chat.ChatConsoleWindowItem; import raptor.swt.chat.ChatUtils; import raptor.swt.chat.controller.ChannelController; import raptor.swt.chat.controller.MainController; import raptor.swt.chat.controller.PartnerTellController; import raptor.swt.chat.controller.PersonController; import raptor.swt.chat.controller.RegExController; import raptor.swt.chess.ChessBoardUtils; import raptor.util.BrowserUtils; import raptor.util.RaptorStringTokenizer; /** * An ics (internet chess server) connector. You will need to supply yuor own * IcsConnectorContext because they are all different. You might also need to * override some methods in order to get it working. */ public abstract class IcsConnector implements Connector { private static final Log LOG = LogFactory.getLog(IcsConnector.class); protected class IcsChatScriptContext extends IcsScriptContext implements ChatScriptContext { ChatEvent event; boolean ignoreEvent = false; public IcsChatScriptContext(ChatEvent event) { this.event = event; } public IcsChatScriptContext(String... params) { super(params); } public String getMessage() { if (event == null) { Raptor.getInstance().alert( "getMessage is not supported in toolbar scripts"); return null; } else { return event.getMessage(); } } public String getMessageChannel() { if (event == null) { Raptor .getInstance() .alert( "getMessageChannel is not supported in toolbar scripts"); return null; } else { return event.getChannel(); } } public String getMessageSource() { if (event == null) { Raptor.getInstance().alert( "getMessageSource is not supported in toolbar scripts"); return null; } else { return event.getSource(); } } } protected class IcsScriptContext implements ScriptContext { protected String[] parameters; protected IcsScriptContext(String... parameters) { this.parameters = parameters; } public void alert(String message) { Raptor.getInstance().alert(message); } public String[] getParameters() { return parameters; } public long getPingMillis() { return lastPingTime; } public String getUserFollowing() { Raptor.getInstance().alert( "getUserFollowing is not yet implemented."); return ""; } public int getUserIdleSeconds() { return (int) (System.currentTimeMillis() - lastSendTime) / 1000; } public String getUserName() { return userName; } public String getValue(String key) { return scriptHash.get(key); } public void launchProcess(String... commandAndArgs) { try { Runtime.getRuntime().exec(commandAndArgs); } catch (Throwable t) { onError("Error launching process: " + Arrays.toString(commandAndArgs), t); } } public void openChannelTab(String channel) { if (!Raptor.getInstance().getWindow().containsChannelItem( IcsConnector.this, channel)) { ChatConsoleWindowItem windowItem = new ChatConsoleWindowItem( new ChannelController(IcsConnector.this, channel)); Raptor.getInstance().getWindow().addRaptorWindowItem( windowItem, false); ChatUtils.appendPreviousChatsToController(windowItem .getConsole()); } } public void openPartnerTab() { if (!Raptor.getInstance().getWindow().containsPartnerTellItem( IcsConnector.this)) { ChatConsoleWindowItem windowItem = new ChatConsoleWindowItem( new PartnerTellController(IcsConnector.this)); Raptor.getInstance().getWindow().addRaptorWindowItem( windowItem, false); ChatUtils.appendPreviousChatsToController(windowItem .getConsole()); } } public void openPersonTab(String person) { if (!Raptor.getInstance().getWindow().containsPersonalTellItem( IcsConnector.this, person)) { ChatConsoleWindowItem windowItem = new ChatConsoleWindowItem( new PersonController(IcsConnector.this, person)); Raptor.getInstance().getWindow().addRaptorWindowItem( windowItem, false); ChatUtils.appendPreviousChatsToController(windowItem .getConsole()); } } public void openRegExTab(String regularExpression) { if (!Raptor.getInstance().getWindow().containsPartnerTellItem( IcsConnector.this)) { ChatConsoleWindowItem windowItem = new ChatConsoleWindowItem( new RegExController(IcsConnector.this, regularExpression)); Raptor.getInstance().getWindow().addRaptorWindowItem( windowItem, false); ChatUtils.appendPreviousChatsToController(windowItem .getConsole()); } } public void openUrl(String url) { BrowserUtils.openUrl(url); } public void playBughouseSound(String soundName) { SoundService.getInstance().playBughouseSound(soundName); } public void playSound(String soundName) { SoundService.getInstance().playSound(soundName); } public String prompt(String message) { return Raptor.getInstance().promptForText(message); } public void send(String message) { IcsConnector.this.sendMessage(message); } public void sendHidden(String message) { if (message.contains("tell")) { IcsConnector.this.sendMessage(message, true, ChatType.TOLD); } else { IcsConnector.this.sendMessage(message, true); } } public void sendToConsole(String message) { publishEvent(new ChatEvent(null, ChatType.INTERNAL, message)); } public void speak(String message) { SoundService.getInstance().textToSpeech(message); } public void storeValue(String key, String value) { scriptHash.put(key, value); } public String urlEncode(String stringToEncode) { try { return URLEncoder.encode(stringToEncode, "UTF-8"); } catch (UnsupportedEncodingException uee) { }// Eat it wont happen. return stringToEncode; } } protected BughouseService bughouseService; protected ChatService chatService; protected List<ConnectorListener> connectorListeners = Collections .synchronizedList(new ArrayList<ConnectorListener>(10)); protected IcsConnectorContext context; protected String currentProfileName; protected Thread daemonThread; protected GameService gameService; protected Map<String, String> scriptHash = new HashMap<String, String>(); protected SeekService seekService; /** * Adds the game windows to the RaptorAppWindow. */ protected GameServiceListener gameServiceListener = new GameServiceAdapter() { @Override public void gameCreated(Game game) { if (game instanceof BughouseGame) { if (((BughouseGame) game).getOtherBoard() == null) { ChessBoardUtils.openBoard(IcsUtils.buildController(game, IcsConnector.this)); } else { ChessBoardUtils.openBoard(IcsUtils.buildController(game, IcsConnector.this, true), true); } } else { ChessBoardUtils.openBoard(IcsUtils.buildController(game, IcsConnector.this)); } } }; protected boolean hasSentLogin = false; protected boolean hasSentPassword = false; protected List<ChatType> ignoringChatTypes = new ArrayList<ChatType>(); protected StringBuilder inboundMessageBuffer = new StringBuilder(25000); protected ByteBuffer inputBuffer = ByteBuffer.allocate(25000); protected ReadableByteChannel inputChannel; protected boolean isConnecting; protected boolean isLoggedIn = false; protected Runnable keepAlive = new Runnable() { public void run() { LOG.error("In keepAlive.run() " + (System.currentTimeMillis() - lastSendTime > 60000 * 50)); if (isConnected() && getPreferences().getBoolean( context.getShortName() + "-keep-alive") && System.currentTimeMillis() - lastSendTime > 60000 * 50) { sendMessage("date", true); publishEvent(new ChatEvent("", ChatType.INTERNAL, "The \"date\" command was just sent as a keep alive.")); ThreadService.getInstance().scheduleOneShot(60000 * 30, this); } } }; protected long lastPingTime; protected long lastSendTime; protected long lastSendPingTime; protected ChatConsoleWindowItem mainConsoleWindowItem; protected Socket socket; protected String userName; protected String userFollowing; protected String[] bughouseSounds = SoundService.getInstance() .getBughouseSoundKeys(); protected ChatScript[] personTellMessageScripts = null; protected ChatScript[] channelTellMessageScripts = null; protected ChatScript[] partnerTellMessageScripts = null; protected ScriptServiceListener scriptServiceListener = new ScriptServiceListener() { public void onChatScriptsChanged() { if (isConnected()) { refreshChatScripts(); } } public void onGameScriptsChanged() { } }; /** * Constructs an IcsConnector with the specified context. * * @param context */ protected IcsConnector(IcsConnectorContext context) { this.context = context; chatService = new ChatService(this); seekService = new SeekService(this); gameService = new GameService(); gameService.addGameServiceListener(gameServiceListener); setBughouseService(new BughouseService(this)); } public void acceptSeek(String adId) { sendMessage("play " + adId, true); } /** * Adds a connector listener to the connector. */ public void addConnectorListener(ConnectorListener listener) { connectorListeners.add(listener); } /** * Connects to ics using the settings in preferences. */ public void connect() { connect(Raptor.getInstance().getPreferences().getString( context.getPreferencePrefix() + "profile")); } /** * Disconnects from the ics. */ public void disconnect() { synchronized (this) { if (isConnected()) { try { ScriptService.getInstance().removeScriptServiceListener( scriptServiceListener); if (inputChannel != null) { try { inputChannel.close(); } catch (Throwable t) { } } if (socket != null) { try { socket.close(); } catch (Throwable t) { } } if (daemonThread != null) { try { if (daemonThread.isAlive()) { daemonThread.interrupt(); } } catch (Throwable t) { } } if (keepAlive != null) { ThreadService.getInstance().getExecutor().remove( keepAlive); } } catch (Throwable t) { } finally { socket = null; inputChannel = null; daemonThread = null; } try { String messageLeftInBuffer = drainInboundMessageBuffer(); if (StringUtils.isNotBlank(messageLeftInBuffer)) { parseMessage(messageLeftInBuffer); } } catch (Throwable t) { } finally { } } isConnecting = false; publishEvent(new ChatEvent(null, ChatType.INTERNAL, "Disconnected")); Raptor.getInstance().getWindow().setPingTime(this, -1); fireDisconnected(); LOG.error("Disconnected from " + getShortName()); } } public void dispose() { if (isConnected()) { disconnect(); } if (connectorListeners != null) { connectorListeners.clear(); connectorListeners = null; } if (chatService != null) { chatService.dispose(); chatService = null; } if (gameService != null) { gameService.removeGameServiceListener(gameServiceListener); gameService.dispose(); gameService = null; } if (inputBuffer != null) { inputBuffer.clear(); inputBuffer = null; } if (keepAlive != null) { ThreadService.getInstance().getExecutor().remove(keepAlive); keepAlive = null; } if (inputChannel != null) { try { inputChannel.close(); } catch (Throwable t) { } inputChannel = null; } LOG.info("Disposed " + getShortName() + "Connector"); } public BughouseService getBughouseService() { return bughouseService; } public String[][] getChannelActions(String channel) { return new String[][] { new String[] { "Add Channel " + channel, "+channel " + channel }, new String[] { "Remove Channel " + channel, "-channel " + channel }, new String[] { "In Channel " + channel, "in " + channel } }; } public String getChannelTabPrefix(String channel) { return "tell " + channel + " "; } public ChatScriptContext getChatScriptContext(String... params) { return new IcsChatScriptContext(params); } public ChatService getChatService() { return chatService; } public IcsConnectorContext getContext() { return context; } public String getDescription() { return context.getDescription(); } public String[][] getGameIdActions(String gameId) { return new String[][] { new String[] { "Observe game " + gameId, "observe " + gameId }, new String[] { "All observers in game " + gameId, "allobs " + gameId }, { "Move list for game " + gameId, "moves " + gameId } }; } public GameService getGameService() { return gameService; } public GameScriptContext getGametScriptContext() { return null; } public String getPartnerTellPrefix() { return "ptell "; } public String[][] getPersonActions(String person) { return new String[][] { new String[] { "Finger " + person, "finger " + person }, new String[] { "Observe " + person, "observe " + person }, new String[] { "History " + person, "history " + person }, new String[] { "Follow " + person, "follow " + person }, new String[] { "Partner " + person, "partner " + person }, new String[] { "Vars " + person, "vars " + person }, new String[] { "Censor " + person, "+censor " + person }, new String[] { "Uncensor " + person, "-censor " + person }, new String[] { "Noplay " + person, "+noplay " + person }, new String[] { "Unnoplay " + person, "noplay " + person } }; } public String getPersonTabPrefix(String person) { return "tell " + person + " "; } public RaptorPreferenceStore getPreferences() { return Raptor.getInstance().getPreferences(); } public String getPrompt() { return context.getPrompt(); } public ScriptConnectorType getScriptConnectorType() { return ScriptConnectorType.ICS; } public SeekService getSeekService() { return seekService; } public String getShortName() { return context.getShortName(); } public String getTellToString(String handle) { return "tell " + handle + " "; } /** * Returns the name of the current user logged in. */ public String getUserName() { return userName; } public boolean isConnected() { return socket != null && inputChannel != null && daemonThread != null; } public boolean isConnecting() { return isConnecting; } public boolean isLikelyChannel(String word) { return IcsUtils.isLikelyChannel(word); } public boolean isLikelyGameId(String word) { return IcsUtils.isLikelyGameId(word); } public boolean isLikelyPartnerTell(String outboundMessage) { return StringUtils.startsWithIgnoreCase(outboundMessage, "pt"); } public boolean isLikelyPerson(String word) { return IcsUtils.isLikelyPerson(word); } public void makeMove(Game game, Move move) { sendMessage(move.getLan(), true); } public void matchBughouse(String playerName, boolean isRated, int time, int inc) { sendMessage("$$match " + playerName + " " + time + " " + inc + " " + (isRated ? "rated" : "unrated") + " bughouse"); } public void onAbortKeyPress() { sendMessage("$$abort", true); } public void onAcceptKeyPress() { sendMessage("$$accept", true); } /** * Auto logs in if that is configured. */ public void onAutoConnect() { if (Raptor.getInstance().getPreferences().getBoolean( context.getPreferencePrefix() + "auto-connect")) { connect(); } } public void onDeclineKeyPress() { sendMessage("$$decline", true); } public void onDraw(Game game) { sendMessage("$$draw", true); } public void onError(String message) { onError(message, null); } public void onError(String message, Throwable t) { String errorMessage = IcsUtils .cleanupMessage("Critical error occured! We are trying to make Raptor " + "bug free and we need your help! Please take a moment to report this " + "error at\nhttp://code.google.com/p/raptor-chess-interface/issues/list\n\n Issue: " + message + (t == null ? "" : "\n" + ExceptionUtils.getFullStackTrace(t))); publishEvent(new ChatEvent(null, ChatType.INTERNAL, errorMessage)); } public void onExamineModeBack(Game game) { sendMessage("$$back", true); } public void onExamineModeCommit(Game game) { sendMessage("$$commit", true); } public void onExamineModeFirst(Game game) { sendMessage("$$back 300", true); } public void onExamineModeForward(Game game) { sendMessage("$$forward 1", true); } public void onExamineModeLast(Game game) { sendMessage("$$forward 300", true); } public void onExamineModeRevert(Game game) { sendMessage("$$revert", true); } public void onObserveGame(String gameId) { sendMessage("$$observe " + gameId, true); } public void onPartner(String bugger) { sendMessage("$$partner " + bugger, true); } public void onRematchKeyPress() { sendMessage("$$rematch", true); } /** * Resigns the specified game. */ public void onResign(Game game) { sendMessage("$$resign", true); } public void onSetupClear(Game game) { sendMessage("$$bsetup clear", true); } public void onSetupClearSquare(Game game, int square) { sendMessage("$$x@" + GameUtils.getSan(square), true); } public void onSetupComplete(Game game) { sendMessage("bsetup done", true); } public void onSetupFromFEN(Game game, String fen) { sendMessage("$$bsetup fen " + fen, true); } public void onSetupStartPosition(Game game) { sendMessage("$$bsetup start", true); } public void onUnexamine(Game game) { sendMessage("$$unexamine", true); } public void onUnobserve(Game game) { sendMessage("$$unobs " + game.getId(), true); } public String parseChannel(String word) { return IcsUtils.stripChannel(word); } public String parseGameId(String word) { return IcsUtils.stripGameId(word); } public String parsePerson(String word) { return IcsUtils.stripWord(word); } /** * Removes a connector listener from the connector. */ public void removeConnectorListener(ConnectorListener listener) { connectorListeners.remove(listener); } public String removeLineBreaks(String message) { return IcsUtils.removeLineBreaks(message); } public void sendBugAvailableTeamsMessage() { sendMessage("$$bugwho p", true, ChatType.BUGWHO_AVAILABLE_TEAMS); } public void sendBugGamesMessage() { sendMessage("$$bugwho g", true, ChatType.BUGWHO_GAMES); } public void sendBugUnpartneredBuggersMessage() { sendMessage("$$bugwho u", true, ChatType.BUGWHO_UNPARTNERED_BUGGERS); } public void sendGetSeeksMessage() { sendMessage("$$sought all", true, ChatType.SEEKS); } public void sendMessage(String message) { sendMessage(message, false, null); } /** * Sends a message to the connector. A ChatEvent of OUTBOUND type should * only be published if isHidingFromUser is false. */ public void sendMessage(String message, boolean isHidingFromUser) { sendMessage(message, isHidingFromUser, null); } /** * Sends a message to the connector. A ChatEvent of OUTBOUND type should * only be published containing the message if isHidingFromUser is false. * The next message the connector reads in that is of the specified type * should not be published to the ChatService. */ public void sendMessage(String message, boolean isHidingFromUser, ChatType hideNextChatType) { if (isConnected()) { StringBuilder builder = new StringBuilder(message); IcsUtils.filterOutbound(builder); if (LOG.isDebugEnabled()) { LOG.debug(context.getShortName() + "Connector Sending: " + builder.toString().trim()); } if (hideNextChatType != null) { ignoringChatTypes.add(hideNextChatType); } // Only one thread at a time should write to the socket. synchronized (socket) { try { String[] messages = breakUpMessage(builder); for (String current : messages) { socket.getOutputStream().write(current.getBytes()); socket.getOutputStream().flush(); } if (!message.startsWith("$$")) { lastSendPingTime = System.currentTimeMillis(); } else { lastSendTime = lastSendPingTime = System .currentTimeMillis(); } } catch (Throwable t) { publishEvent(new ChatEvent(null, ChatType.INTERNAL, "Error: " + t.getMessage())); disconnect(); } } if (!isHidingFromUser) { // Wrap the text before publishing an outbound event. publishEvent(new ChatEvent(null, ChatType.OUTBOUND, message .trim())); } } else { publishEvent(new ChatEvent(null, ChatType.INTERNAL, "Error: Unable to send " + message + " to " + getShortName() + ". There is currently no connection.")); } } public String[] breakUpMessage(StringBuilder message) { if (message.length() <= 330) { return new String[] { message + "\n"}; } else { int firstSpace = message.indexOf(" "); List<String> result = new ArrayList<String>(5); if (firstSpace != -1) { int secondSpace = message.indexOf(" ", firstSpace + 1); if (secondSpace != -1) { String beginingText = message.substring(0, secondSpace + 1); String wrappedText = WordUtils.wrap(message.toString(), 330, "\n", true); String[] wrapped = wrappedText.split("\n"); result.add(wrapped[0] + "\n"); for (int i = 1; i < wrapped.length; i++) { result.add(beginingText + wrapped[i] + "\n"); } } else { result.add(message.substring(0, 330) + "\n"); publishEvent(new ChatEvent( null, ChatType.INTERNAL, "Your message was too long and Raptor could not find a nice " + "way to break it up. Your message was trimmed to:\n" + result.get(0))); } } else { result.add(message.substring(0, 330) + "\n"); publishEvent(new ChatEvent( null, ChatType.INTERNAL, "Your message was too long and Raptor could not find a nice " + "way to break it up. Your message was trimmed to:\n" + result.get(0))); } return result.toArray(new String[0]); } } /** * Connects with the specified profile name. */ protected void connect(final String profileName) { if (isConnected()) { throw new IllegalStateException("You are already connected to " + getShortName() + " . Disconnect before invoking connect."); } resetConnectionStateVars(); currentProfileName = profileName; final String profilePrefix = context.getPreferencePrefix() + profileName + "-"; if (LOG.isDebugEnabled()) { LOG.debug("Profile " + currentProfileName + " Prefix=" + profilePrefix); } if (mainConsoleWindowItem == null) { // Add the main console tab to the raptor window. createMainConsoleWindowItem(); Raptor.getInstance().getWindow().addRaptorWindowItem( mainConsoleWindowItem, false); } else if (!Raptor.getInstance().getWindow().isBeingManaged( mainConsoleWindowItem)) { // Add a new main console to the raptor window since the existing // one is no longer being managed (it was already disposed). createMainConsoleWindowItem(); Raptor.getInstance().getWindow().addRaptorWindowItem( mainConsoleWindowItem, false); } // If its being managed no need to do anything it should adjust itself // as the state of the connector changes from the ConnectorListener it // registered. if (LOG.isInfoEnabled()) { LOG.info(getShortName() + " Connecting to " + getPreferences().getString(profilePrefix + "server-url") + " " + getPreferences().getInt(profilePrefix + "port")); } publishEvent(new ChatEvent(null, ChatType.INTERNAL, "Connecting to " + getPreferences().getString(profilePrefix + "server-url") + " " + getPreferences().getInt(profilePrefix + "port") + (getPreferences().getBoolean( profilePrefix + "timeseal-enabled") ? " with " : " without ") + "timeseal ...")); ThreadService.getInstance().run(new Runnable() { public void run() { try { if (getPreferences().getBoolean( profilePrefix + "timeseal-enabled")) { // TO DO: rewrite TimesealingSocket to use a // SocketChannel. socket = new TimesealingSocket( getPreferences().getString( profilePrefix + "server-url"), getPreferences().getInt(profilePrefix + "port"), getInitialTimesealString()); publishEvent(new ChatEvent(null, ChatType.INTERNAL, "Timeseal connection string " + getInitialTimesealString())); } else { socket = new Socket(getPreferences().getString( profilePrefix + "server-url"), getPreferences() .getInt(profilePrefix + "port")); } publishEvent(new ChatEvent(null, ChatType.INTERNAL, "Connected")); inputChannel = Channels.newChannel(socket.getInputStream()); SoundService.getInstance().playSound("alert"); daemonThread = new Thread(new Runnable() { public void run() { messageLoop(); } }); daemonThread.setName("FicsConnectorDaemon"); daemonThread.setPriority(Thread.MAX_PRIORITY); daemonThread.start(); if (LOG.isInfoEnabled()) { LOG.info(getShortName() + " Connection successful"); } } catch (Throwable ce) { publishEvent(new ChatEvent(null, ChatType.INTERNAL, "Error: " + ce.getMessage())); disconnect(); return; } } }); isConnecting = true; if (getPreferences().getBoolean( context.getPreferencePrefix() + "-keep-alive")) { ThreadService.getInstance().scheduleOneShot(300000, keepAlive); } ScriptService.getInstance().addScriptServiceListener( scriptServiceListener); refreshChatScripts(); fireConnecting(); } protected void createMainConsoleWindowItem() { mainConsoleWindowItem = new ChatConsoleWindowItem(new MainController( this)); } /** * Removes all of the characters from inboundMessageBuffer and returns the * string removed. */ protected String drainInboundMessageBuffer() { return drainInboundMessageBuffer(inboundMessageBuffer.length()); } /** * Removes characters 0-index from inboundMessageBuffer and returns the * string removed. */ protected String drainInboundMessageBuffer(int index) { String result = inboundMessageBuffer.substring(0, index); inboundMessageBuffer.delete(0, index); return result; } protected void fireConnected() { ThreadService.getInstance().run(new Runnable() { public void run() { synchronized (connectorListeners) { for (ConnectorListener listener : connectorListeners) { listener.onConnect(); } } } }); } protected void fireConnecting() { ThreadService.getInstance().run(new Runnable() { public void run() { synchronized (connectorListeners) { for (ConnectorListener listener : connectorListeners) { listener.onConnecting(); } } } }); } protected void fireDisconnected() { ThreadService.getInstance().run(new Runnable() { public void run() { synchronized (connectorListeners) { for (ConnectorListener listener : connectorListeners) { listener.onConnecting(); } } } }); } protected String getInitialTimesealString() { return Raptor.getInstance().getPreferences().getString( PreferenceKeys.TIMESEAL_INIT_STRING); } /** * The messageLoop. Reads the inputChannel and then invokes publishInput * with the text read. Should really never be invoked. */ protected void messageLoop() { try { while (true) { if (isConnected()) { int numRead = inputChannel.read(inputBuffer); if (numRead > 0) { if (LOG.isDebugEnabled()) { LOG.debug(context.getShortName() + "Connector " + "Read " + numRead + " bytes."); } inputBuffer.rewind(); byte[] bytes = new byte[numRead]; inputBuffer.get(bytes); inboundMessageBuffer.append(IcsUtils .cleanupMessage(new String(bytes))); try { onNewInput(); } catch (Throwable t) { onError(context.getShortName() + "Connector " + "Error in DaemonRun.onNewInput", t); } inputBuffer.clear(); } else { if (LOG.isDebugEnabled()) { LOG.debug(context.getShortName() + "Connector " + "Read 0 bytes disconnecting."); } disconnect(); break; } Thread.sleep(50); } else { if (LOG.isDebugEnabled()) { LOG.debug(context.getShortName() + "Connector " + "Not connected disconnecting."); } disconnect(); break; } } } catch (Throwable t) { if (t instanceof IOException) { LOG .debug( context.getShortName() + "Connector " + "IOException occured in messageLoop (These are common when disconnecting and ignorable)", t); } else { onError(context.getShortName() + "Connector Error in DaemonRun Thwoable", t); } disconnect(); } finally { LOG.debug(context.getShortName() + "Connector Leaving readInput"); } } /** * Processes a login message. Handles sending the user name and password * information and the enter if prompted to hit enter if logging in as a * guest. * * @param message * @param isLoginPrompt */ protected void onLoginEvent(String message, boolean isLoginPrompt) { String profilePrefix = context.getPreferencePrefix() + currentProfileName + "-"; if (isLoginPrompt) { if (getPreferences().getBoolean(profilePrefix + "is-anon-guest") && !hasSentLogin) { parseMessage(message); hasSentLogin = true; sendMessage("guest", true); } else if (!hasSentLogin) { parseMessage(message); hasSentLogin = true; String handle = getPreferences().getString( profilePrefix + "user-name"); if (StringUtils.isNotBlank(handle)) { sendMessage(handle, true); } } else { parseMessage(message); } } else { if (getPreferences().getBoolean(profilePrefix + "is-anon-guest") && !hasSentPassword) { hasSentPassword = true; parseMessage(message); sendMessage("", true); } else if (getPreferences().getBoolean( profilePrefix + "is-named-guest") && !hasSentPassword) { hasSentPassword = true; parseMessage(message); sendMessage("", true); } else if (!hasSentPassword) { hasSentPassword = true; parseMessage(message); String password = getPreferences().getString( profilePrefix + "password"); if (StringUtils.isNotBlank(password)) { // Don't show the users password. sendMessage(password, true); } } else { parseMessage(message); } } } /** * This method is invoked by the run method when there is new text to be * handled. It buffers text until a prompt is found then invokes * parseMessage. * * This method also handles login logic which is tricky. */ protected void onNewInput() { if (lastSendPingTime != 0) { ThreadService.getInstance().run(new Runnable() { public void run() { long currentTime = System.currentTimeMillis(); lastPingTime = currentTime - lastSendPingTime; Raptor.getInstance().getWindow().setPingTime( IcsConnector.this, lastPingTime); lastSendPingTime = 0; } }); } if (isLoggedIn) { // If we are logged in. Then parse out all the text between the // prompts. int promptIndex = -1; while ((promptIndex = inboundMessageBuffer.indexOf(context .getRawPrompt())) != -1) { String message = drainInboundMessageBuffer(promptIndex + context.getRawPrompt().length()); parseMessage(message); } } else { // We are not logged in. // There are several complex cases here depending on the prompt // we are waiting on. // There is a login prompt, a password prompt, an enter prompt, // and also you have to handle invalid logins. int loggedInMessageIndex = inboundMessageBuffer.indexOf(context .getLoggedInMessage()); if (loggedInMessageIndex != -1) { int nameStartIndex = inboundMessageBuffer.indexOf(context .getLoggedInMessage()) + context.getLoggedInMessage().length(); int endIndex = inboundMessageBuffer.indexOf("****", nameStartIndex); if (endIndex != -1) { userName = IcsUtils.stripTitles(inboundMessageBuffer .substring(nameStartIndex, endIndex).trim()); LOG.info(context.getShortName() + "Connector " + "login complete. userName=" + userName); isLoggedIn = true; onSuccessfulLogin(); // Since we are now logged in, just buffer the text // received and // invoke parseMessage when the prompt arrives. } else { // We have yet to receive the **** closing message so // wait // until it arrives. } } else { int loginIndex = inboundMessageBuffer.indexOf(context .getLoginPrompt()); if (loginIndex != -1) { String event = drainInboundMessageBuffer(loginIndex + context.getLoginPrompt().length()); onLoginEvent(event, true); } else { int enterPromptIndex = inboundMessageBuffer.indexOf(context .getEnterPrompt()); if (enterPromptIndex != -1) { String event = drainInboundMessageBuffer(enterPromptIndex + context.getEnterPrompt().length()); onLoginEvent(event, false); } else { int passwordPromptIndex = inboundMessageBuffer .indexOf(context.getPasswordPrompt()); if (passwordPromptIndex != -1) { String event = drainInboundMessageBuffer(passwordPromptIndex + context.getPasswordPrompt().length()); onLoginEvent(event, false); } else { int errorMessageIndex = inboundMessageBuffer .indexOf(context.getLoginErrorMessage()); if (errorMessageIndex != -1) { String event = drainInboundMessageBuffer(); parseMessage(event); } } } } } } } protected abstract void onSuccessfulLogin(); /** * Processes a message. If the user is logged in, message will be all of the * text received since the last prompt from fics. If the user is not logged * in, message will be all of the text received since the last login prompt. * * message will always use \n as the line delimiter. */ protected void parseMessage(String message) { ChatEvent[] events = context.getParser().parse(message); for (ChatEvent event : events) { event.setMessage(IcsUtils .maciejgFormatToUnicode(event.getMessage())); publishEvent(event); } } /** * Plays the bughouse sound for the specified ptell. Returns true if a * bughouse sound was played. */ protected boolean playBughouseSounds(final String ptell) { boolean result = false; if (getPreferences().getBoolean(PreferenceKeys.APP_SOUND_ENABLED)) { int colonIndex = ptell.indexOf(":"); if (colonIndex != -1) { String message = ptell .substring(colonIndex + 1, ptell.length()).trim(); RaptorStringTokenizer tok = new RaptorStringTokenizer(message, "\n", true); message = tok.nextToken().trim(); for (String bugSound : bughouseSounds) { if (bugSound.equalsIgnoreCase(message)) { // This creates its own thread. SoundService.getInstance().playBughouseSound(bugSound); result = true; break; } } } else { onError("Received a ptell event without a colon", new Exception()); } } return result; } /** * Processes the scripts for the specified chat event. Script processing is * kicked off on a different thread. */ protected void processScripts(final ChatEvent event) { ThreadService.getInstance().run(new Runnable() { public void run() { if (personTellMessageScripts != null && event.getType() == ChatType.TELL) { for (ChatScript script : personTellMessageScripts) { ChatScript newScript = ScriptService.getInstance() .getChatScript(script.getName()); if (newScript != null) { newScript.execute(new IcsChatScriptContext(event)); } } } else if (channelTellMessageScripts != null && event.getType() == ChatType.CHANNEL_TELL) { for (ChatScript script : channelTellMessageScripts) { ChatScript newScript = ScriptService.getInstance() .getChatScript(script.getName()); if (newScript != null) { newScript.execute(new IcsChatScriptContext(event)); } } } else if (partnerTellMessageScripts != null && event.getType() == ChatType.PARTNER_TELL) { for (ChatScript script : partnerTellMessageScripts) { ChatScript newScript = ScriptService.getInstance() .getChatScript(script.getName()); if (newScript != null) { newScript.execute(new IcsChatScriptContext(event)); } } } } }); } /** * Publishes the specified event to the chat service. Currently all messages * are published on separate threads via ThreadService. */ protected void publishEvent(final ChatEvent event) { if (chatService != null) { // Could have been disposed. if (LOG.isDebugEnabled()) { LOG.debug("Publishing event : " + event); } // Sets the user following. This is used in the IcsParser to // determine if white is on top or not. if (event.getType() == ChatType.FOLLOWING) { userFollowing = event.getSource(); } else if (event.getType() == ChatType.NOT_FOLLOWING) { userFollowing = null; } if (event.getType() == ChatType.PARTNER_TELL || event.getType() == ChatType.TELL || event.getType() == ChatType.CHANNEL_TELL) { processScripts(event); } if (event.getType() == ChatType.PARTNER_TELL) { if (playBughouseSounds(event.getMessage())) { // No need to publish it we played the sound. return; } } int ignoreIndex = ignoringChatTypes.indexOf(event.getType()); if (ignoreIndex != -1) { ignoringChatTypes.remove(ignoreIndex); } else { // It is interesting to note messages are handled sequentially // up to this point. chatService will publish the event // asynchronously. chatService.publishChatEvent(event); } } } protected void refreshChatScripts() { personTellMessageScripts = ScriptService.getInstance().getChatScripts( this, ChatScriptType.OnPersonTellMessages); channelTellMessageScripts = ScriptService.getInstance().getChatScripts( this, ChatScriptType.onChannelTellMessages); partnerTellMessageScripts = ScriptService.getInstance().getChatScripts( this, ChatScriptType.OnPartnerTellMessages); } /** * Resets state variables related to the connection state. */ protected void resetConnectionStateVars() { isLoggedIn = false; hasSentLogin = false; hasSentPassword = false; userFollowing = null; ignoringChatTypes.clear(); } protected void setUserFollowing(String userFollowing) { this.userFollowing = userFollowing; } private void setBughouseService(BughouseService bughouseService) { this.bughouseService = bughouseService; } }
Added code to break up messages into pieces if the message is longer than 330 chars.
raptor/src/raptor/connector/ics/IcsConnector.java
Added code to break up messages into pieces if the message is longer than 330 chars.
<ide><path>aptor/src/raptor/connector/ics/IcsConnector.java <ide> connectorListeners.add(listener); <ide> } <ide> <add> public String[] breakUpMessage(StringBuilder message) { <add> if (message.length() <= 330) { <add> return new String[] { message + "\n" }; <add> } else { <add> int firstSpace = message.indexOf(" "); <add> List<String> result = new ArrayList<String>(5); <add> if (firstSpace != -1) { <add> int secondSpace = message.indexOf(" ", firstSpace + 1); <add> if (secondSpace != -1) { <add> String beginingText = message.substring(0, secondSpace + 1); <add> String wrappedText = WordUtils.wrap(message.toString(), <add> 330, "\n", true); <add> String[] wrapped = wrappedText.split("\n"); <add> result.add(wrapped[0] + "\n"); <add> for (int i = 1; i < wrapped.length; i++) { <add> result.add(beginingText + wrapped[i] + "\n"); <add> } <add> } else { <add> result.add(message.substring(0, 330) + "\n"); <add> publishEvent(new ChatEvent( <add> null, <add> ChatType.INTERNAL, <add> "Your message was too long and Raptor could not find a nice " <add> + "way to break it up. Your message was trimmed to:\n" <add> + result.get(0))); <add> } <add> } else { <add> result.add(message.substring(0, 330) + "\n"); <add> publishEvent(new ChatEvent( <add> null, <add> ChatType.INTERNAL, <add> "Your message was too long and Raptor could not find a nice " <add> + "way to break it up. Your message was trimmed to:\n" <add> + result.get(0))); <add> } <add> return result.toArray(new String[0]); <add> } <add> } <add> <ide> /** <ide> * Connects to ics using the settings in preferences. <ide> */ <ide> StringBuilder builder = new StringBuilder(message); <ide> IcsUtils.filterOutbound(builder); <ide> <del> <ide> if (LOG.isDebugEnabled()) { <ide> LOG.debug(context.getShortName() + "Connector Sending: " <ide> + builder.toString().trim()); <ide> } <ide> <ide> if (!isHidingFromUser) { <del> // Wrap the text before publishing an outbound event. <ide> publishEvent(new ChatEvent(null, ChatType.OUTBOUND, message <ide> .trim())); <ide> } <ide> "Error: Unable to send " + message + " to " <ide> + getShortName() <ide> + ". There is currently no connection.")); <del> } <del> } <del> <del> public String[] breakUpMessage(StringBuilder message) { <del> if (message.length() <= 330) { <del> return new String[] { message + "\n"}; <del> } else { <del> int firstSpace = message.indexOf(" "); <del> List<String> result = new ArrayList<String>(5); <del> if (firstSpace != -1) { <del> int secondSpace = message.indexOf(" ", firstSpace + 1); <del> if (secondSpace != -1) { <del> String beginingText = message.substring(0, secondSpace + 1); <del> String wrappedText = WordUtils.wrap(message.toString(), 330, "\n", <del> true); <del> String[] wrapped = wrappedText.split("\n"); <del> result.add(wrapped[0] + "\n"); <del> for (int i = 1; i < wrapped.length; i++) { <del> result.add(beginingText + wrapped[i] + "\n"); <del> } <del> } else { <del> result.add(message.substring(0, 330) + "\n"); <del> publishEvent(new ChatEvent( <del> null, <del> ChatType.INTERNAL, <del> "Your message was too long and Raptor could not find a nice " <del> + "way to break it up. Your message was trimmed to:\n" <del> + result.get(0))); <del> } <del> } else { <del> result.add(message.substring(0, 330) + "\n"); <del> publishEvent(new ChatEvent( <del> null, <del> ChatType.INTERNAL, <del> "Your message was too long and Raptor could not find a nice " <del> + "way to break it up. Your message was trimmed to:\n" <del> + result.get(0))); <del> } <del> return result.toArray(new String[0]); <ide> } <ide> } <ide>
Java
bsd-3-clause
eea9c7906717601465d8f87923b2b7aa9d62df20
0
holisticon/annotation-processor-toolkit
package io.toolisticon.annotationprocessortoolkit.templating.templateblocks; import io.toolisticon.annotationprocessortoolkit.templating.ModelPathResolver; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Used to handle for loops in templates. */ public class ForTemplateBlock implements TemplateBlock { private final static Pattern ATTRIBUTE_PATTERN = Pattern.compile("\\s*(\\w+?)\\s*[:]\\s*((?:\\w|[.])+?)\\s*"); private final String loopVariableName; private final String accessPath; private final String templateString; private TemplateBlockBinder binder; public ForTemplateBlock(String attributeString, String templateString) { if (attributeString == null || attributeString.trim().isEmpty()) { throw new IllegalArgumentException("for command has no attribute string."); } Matcher matcher = ATTRIBUTE_PATTERN.matcher(attributeString); if (!matcher.matches()) { throw new IllegalArgumentException("for command has an invalid attribute string."); } this.loopVariableName = matcher.group(1); this.accessPath = matcher.group(2); this.templateString = templateString; binder = new TemplateBlockBinder(templateString); } @Override public TemplateBlockType getTemplateBlockType() { return TemplateBlockType.FOR; } @Override public String getContent(Map<String, Object> outerVariables) { Map<String, Object> variables = new HashMap<String, Object>(); variables.putAll(outerVariables); // get array or List Object values = ModelPathResolver.resolveModelPath(outerVariables, accessPath).getValue(); StringBuilder stringBuilder = new StringBuilder(); if (values != null) { if (values.getClass().isArray()) { for (Object value : (Object[]) values) { // now update variables variables.put(loopVariableName, value); stringBuilder.append(binder.getContent(variables)); } } else if (values instanceof Collection) { for (Object value : (Collection) values) { // now update variables variables.put(loopVariableName, value); stringBuilder.append(binder.getContent(variables)); } } } return stringBuilder.toString(); } public TemplateBlockBinder getBinder() { return binder; } public void setBinder(TemplateBlockBinder binder) { this.binder = binder; } public String getLoopVariableName() { return loopVariableName; } public String getAccessPath() { return accessPath; } public String getTemplateString() { return templateString; } }
templating/src/main/java/io/toolisticon/annotationprocessortoolkit/templating/templateblocks/ForTemplateBlock.java
package io.toolisticon.annotationprocessortoolkit.templating.templateblocks; import io.toolisticon.annotationprocessortoolkit.templating.ModelPathResolver; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Used to handle for loops in templates. */ public class ForTemplateBlock implements TemplateBlock { private final static Pattern ATTRIBUTE_PATTERN = Pattern.compile("\\s*(\\w+?)\\s*[:]\\s*((?:\\w|[.])+?)\\s*"); private final String loopVariableName; private final String accessPath; private final String templateString; private TemplateBlockBinder binder; public ForTemplateBlock(String attributeString, String templateString) { if (attributeString == null || attributeString.trim().isEmpty()) { throw new IllegalArgumentException("for command has no attribute string."); } Matcher matcher = ATTRIBUTE_PATTERN.matcher(attributeString); if (!matcher.matches()) { throw new IllegalArgumentException("for command has an invalid attribute string."); } this.loopVariableName = matcher.group(1); this.accessPath = matcher.group(2); this.templateString = templateString; binder = new TemplateBlockBinder(templateString); } @Override public TemplateBlockType getTemplateBlockType() { return TemplateBlockType.FOR; } @Override public String getContent(Map<String, Object> outerVariables) { Map<String, Object> variables = new HashMap<String, Object>(); variables.putAll(outerVariables); // get array or List Object values = ModelPathResolver.resolveModelPath(outerVariables, accessPath).getValue(); StringBuilder stringBuilder = new StringBuilder(); if (values != null) { if (values.getClass().isArray()) { for (Object value : (Object[]) values) { // now update variables variables.put(loopVariableName, value); stringBuilder.append(binder.getContent(variables)); } } else if (values instanceof List) { for (Object value : (List) values) { // now update variables variables.put(loopVariableName, value); stringBuilder.append(binder.getContent(variables)); } } } return stringBuilder.toString(); } public TemplateBlockBinder getBinder() { return binder; } public void setBinder(TemplateBlockBinder binder) { this.binder = binder; } public String getLoopVariableName() { return loopVariableName; } public String getAccessPath() { return accessPath; } public String getTemplateString() { return templateString; } }
Support iterations of Collections instead of List in FOR templates. This allows us to use Sets additional to Lists
templating/src/main/java/io/toolisticon/annotationprocessortoolkit/templating/templateblocks/ForTemplateBlock.java
Support iterations of Collections instead of List in FOR templates.
<ide><path>emplating/src/main/java/io/toolisticon/annotationprocessortoolkit/templating/templateblocks/ForTemplateBlock.java <ide> <ide> import io.toolisticon.annotationprocessortoolkit.templating.ModelPathResolver; <ide> <add>import java.util.Collection; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> <ide> } <ide> <del> } else if (values instanceof List) { <add> } else if (values instanceof Collection) { <ide> <del> for (Object value : (List) values) { <add> for (Object value : (Collection) values) { <ide> <ide> // now update variables <ide> variables.put(loopVariableName, value);
Java
mit
c40d6daff0b1430b1298553829bd0e0b23bbc931
0
simple-elf/selenide,codeborne/selenide,simple-elf/selenide,simple-elf/selenide,codeborne/selenide,simple-elf/selenide,codeborne/selenide
package com.codeborne.selenide.impl; import com.codeborne.selenide.Condition; import com.codeborne.selenide.ElementsCollection; import com.codeborne.selenide.SelenideElement; import com.codeborne.selenide.ex.ElementNotFound; import com.codeborne.selenide.ex.ElementShould; import com.codeborne.selenide.ex.ElementShouldNot; import com.codeborne.selenide.ex.UIAssertionError; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.Select; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.codeborne.selenide.Condition.*; import static com.codeborne.selenide.Configuration.AssertionMode.SOFT; import static com.codeborne.selenide.Configuration.*; import static com.codeborne.selenide.Selenide.*; import static com.codeborne.selenide.WebDriverRunner.isHtmlUnit; import static com.codeborne.selenide.WebDriverRunner.isIE; import static com.codeborne.selenide.impl.WebElementProxy.wrap; import static com.codeborne.selenide.logevents.LogEvent.EventStatus.PASSED; import static java.lang.System.currentTimeMillis; import static java.lang.Thread.currentThread; import static java.util.Arrays.asList; abstract class AbstractSelenideElement implements InvocationHandler { abstract WebElement getDelegate(); abstract WebElement getActualDelegate() throws NoSuchElementException, IndexOutOfBoundsException; abstract String getSearchCriteria(); private static final Set<String> methodsToSkipLogging = new HashSet<String>(asList( "toWebElement", "toString" )); private static final Set<String> methodsForSoftAssertion = new HashSet<String>(asList( "should", "shouldBe", "shouldHave", "shouldNot", "shouldNotHave", "shouldNotBe", "waitUntil", "waitWhile" )); @Override public Object invoke(Object proxy, Method method, Object... args) throws Throwable { if (methodsToSkipLogging.contains(method.getName())) return dispatchSelenideMethod(proxy, method, args); SelenideLog log = SelenideLogger.beginStep(getSearchCriteria(), method.getName(), args); try { Object result = dispatchAndRetry(proxy, method, args); SelenideLogger.commitStep(log, PASSED); return result; } catch (UIAssertionError error) { SelenideLogger.commitStep(log, error); if (assertionMode == SOFT && methodsForSoftAssertion.contains(method.getName())) return proxy; else throw error; } catch (WebDriverException error) { SelenideLogger.commitStep(log, error); throw Cleanup.of.isInvalidSelectorError(error) ? error : new UIAssertionError(error); } catch (Throwable error) { SelenideLogger.commitStep(log, error); throw error; } } protected Object dispatchAndRetry(Object proxy, Method method, Object[] args) throws Throwable { long timeoutMs = getTimeoutMs(method, args); final long startTime = currentTimeMillis(); Throwable lastError; do { try { return method.getDeclaringClass() == SelenideElement.class ? dispatchSelenideMethod(proxy, method, args) : delegateSeleniumMethod(getDelegate(), method, args); } catch (Throwable e) { if (Cleanup.of.isInvalidSelectorError(e)) { throw Cleanup.of.wrap(e); } lastError = e; sleep(pollingInterval); } } while (currentTimeMillis() - startTime <= timeoutMs); if (lastError instanceof UIAssertionError) { UIAssertionError uiError = (UIAssertionError) lastError; uiError.timeoutMs = timeoutMs; throw uiError; } else if (lastError instanceof WebDriverException) { ElementNotFound uiError = createElementNotFoundError(exist, lastError); uiError.timeoutMs = timeoutMs; throw uiError; } throw lastError; } private long getTimeoutMs(Method method, Object[] args) { return "waitUntil".equals(method.getName()) || "waitWhile".equals(method.getName()) ? (Long) args[args.length - 1] : timeout; } protected Object dispatchSelenideMethod(Object proxy, Method method, Object[] args) throws Throwable { if ("setValue".equals(method.getName())) { setValue((String) args[0]); return proxy; } else if ("val".equals(method.getName())) { if (args == null || args.length == 0) { return getValue(); } else { setValue((String) args[0]); return proxy; } } else if ("attr".equals(method.getName())) { return getDelegate().getAttribute((String) args[0]); } else if ("name".equals(method.getName())) { return getDelegate().getAttribute("name"); } else if ("data".equals(method.getName())) { return getDelegate().getAttribute("data-" + args[0]); } else if ("append".equals(method.getName())) { append((String) args[0]); return proxy; } else if ("pressEnter".equals(method.getName())) { findAndAssertElementIsVisible().sendKeys(Keys.ENTER); return proxy; } else if ("pressTab".equals(method.getName())) { findAndAssertElementIsVisible().sendKeys(Keys.TAB); return proxy; } else if ("followLink".equals(method.getName())) { followLink(); return null; } else if ("text".equals(method.getName())) { return getDelegate().getText(); } else if ("innerText".equals(method.getName())) { return getInnerText(); } else if ("innerHtml".equals(method.getName())) { return getInnerHtml(); } else if ("should".equals(method.getName())) { return invokeShould(proxy, "", args); } else if ("waitUntil".equals(method.getName())) { return invokeShould(proxy, "be ", args); } else if ("shouldHave".equals(method.getName())) { return invokeShould(proxy, "have ", args); } else if ("shouldBe".equals(method.getName())) { return invokeShould(proxy, "be ", args); } else if ("shouldNot".equals(method.getName())) { return invokeShouldNot(proxy, "", args); } else if ("waitWhile".equals(method.getName())) { return invokeShouldNot(proxy, "be ", args); } else if ("shouldNotHave".equals(method.getName())) { return invokeShouldNot(proxy, "have ", args); } else if ("shouldNotBe".equals(method.getName())) { return invokeShouldNot(proxy, "be ", args); } else if ("parent".equals(method.getName())) { return parent((SelenideElement) proxy); } else if ("closest".equals(method.getName())) { return closest((SelenideElement) proxy, (String) args[0]); } else if ("find".equals(method.getName()) || "$".equals(method.getName())) { return args.length == 1 ? find((SelenideElement) proxy, args[0], 0) : find((SelenideElement) proxy, args[0], (Integer) args[1]); } else if ("findAll".equals(method.getName()) || "$$".equals(method.getName())) { final SelenideElement parent = (SelenideElement) proxy; return new ElementsCollection(new BySelectorCollection(parent, getSelector(args[0]))); } else if ("toString".equals(method.getName())) { return describe(); } else if ("exists".equals(method.getName())) { return exists(); } else if ("isDisplayed".equals(method.getName())) { return isDisplayed(); } else if ("is".equals(method.getName()) || "has".equals(method.getName())) { return matches((Condition) args[0]); } else if ("setSelected".equals(method.getName())) { setSelected((Boolean) args[0]); return proxy; } else if ("uploadFile".equals(method.getName())) { return uploadFile((SelenideElement) proxy, (File[]) args[0]); } else if ("uploadFromClasspath".equals(method.getName())) { return uploadFromClasspath((SelenideElement) proxy, (String[]) args[0]); } else if ("selectOption".equals(method.getName())) { selectOptionByText((String) args[0]); return null; } else if ("selectOptionByValue".equals(method.getName())) { selectOptionByValue((String) args[0]); return null; } else if ("getSelectedOption".equals(method.getName())) { return getSelectedOption(getDelegate()); } else if ("getSelectedValue".equals(method.getName())) { return getSelectedValue(getDelegate()); } else if ("getSelectedText".equals(method.getName())) { return getSelectedText(getDelegate()); } else if ("toWebElement".equals(method.getName())) { return getActualDelegate(); } else if ("scrollTo".equals(method.getName())) { scrollTo(); return proxy; } else if ("download".equals(method.getName())) { return download(); } else if ("click".equals(method.getName())) { click(); return null; } else if ("contextClick".equals(method.getName())) { contextClick(); return proxy; } else if ("hover".equals(method.getName())) { hover(); return proxy; } else if ("dragAndDropTo".equals(method.getName())) { dragAndDropTo((String) args[0]); return proxy; } else if ("getWrappedElement".equals(method.getName())) { return getActualDelegate(); } else if ("isImage".equals(method.getName())) { return isImage(); } else { throw new IllegalArgumentException("Unknown Selenide method: " + method.getName()); } } protected Object invokeShould(Object proxy, String prefix, Object[] args) { String message = null; if (args[0] instanceof String) { message = (String) args[0]; } return should(proxy, prefix, message, argsToConditions(args)); } private List<Condition> argsToConditions(Object[] args) { List<Condition> conditions = new ArrayList<Condition>(args.length); for (Object arg : args) { if (arg instanceof Condition) conditions.add((Condition) arg); else if (arg instanceof Condition[]) conditions.addAll(asList((Condition[]) arg)); else if (!(arg instanceof String || arg instanceof Long)) throw new IllegalArgumentException("Unknown parameter: " + arg); } return conditions; } protected Object invokeShouldNot(Object proxy, String prefix, Object[] args) { if (args[0] instanceof String) { return shouldNot(proxy, prefix, (String) args[0], argsToConditions(args)); } return shouldNot(proxy, prefix, argsToConditions(args)); } protected Boolean isImage() { WebElement img = getActualDelegate(); if (!"img".equalsIgnoreCase(img.getTagName())) { throw new IllegalArgumentException("Method isImage() is only applicable for img elements"); } return executeJavaScript("return arguments[0].complete && " + "typeof arguments[0].naturalWidth != 'undefined' && " + "arguments[0].naturalWidth > 0", img); } protected boolean matches(Condition condition) { WebElement element = getElementOrNull(); if (element != null) { return condition.apply(element); } return condition.applyNull(); } protected void setSelected(boolean selected) { WebElement element = getDelegate(); if (element.isSelected() ^ selected) { click(element); } } protected String getInnerText() { WebElement element = getDelegate(); if (isHtmlUnit()) { return executeJavaScript("return arguments[0].innerText", element); } else if (isIE()) { return element.getAttribute("innerText"); } return element.getAttribute("textContent"); } protected String getInnerHtml() { WebElement element = getDelegate(); if (isHtmlUnit()) { return executeJavaScript("return arguments[0].innerHTML", element); } return element.getAttribute("innerHTML"); } protected void click() { click(findAndAssertElementIsVisible()); } protected void click(WebElement element) { if (clickViaJs) { executeJavaScript("arguments[0].click()", element); } else { element.click(); } } protected WebElement findAndAssertElementIsVisible() { return checkCondition("be ", null, visible, false); } protected void contextClick() { actions().contextClick(findAndAssertElementIsVisible()).perform(); } protected void hover() { actions().moveToElement(getDelegate()).perform(); } protected void dragAndDropTo(String targetCssSelector) { SelenideElement target = $(targetCssSelector).shouldBe(visible); actions().dragAndDrop(getDelegate(), target).perform(); } protected void followLink() { WebElement link = getDelegate(); String href = link.getAttribute("href"); click(link); // JavaScript $.click() doesn't take effect for <a href> if (href != null) { open(href); } } protected void setValue(String text) { WebElement element = findAndAssertElementIsVisible(); if ("select".equalsIgnoreCase(element.getTagName())) { selectOptionByValue(text); } else if (text == null || text.isEmpty()) { element.clear(); } else if (fastSetValue) { executeJavaScript("arguments[0].value = arguments[1]", element, text); fireEvent(element, "keydown", "keypress", "keyup", "change"); } else { element.clear(); element.sendKeys(text); fireChangeEvent(element); } } protected void fireChangeEvent(WebElement element) { fireEvent(element, "change"); } protected String getValue() { return getDelegate().getAttribute("value"); } protected void append(String text) { WebElement element = getDelegate(); element.sendKeys(text); fireChangeEvent(element); } protected void fireEvent(WebElement element, final String... event) { try { final String jsCodeToTriggerEvent = "var webElement = arguments[0];\n" + "var eventNames = arguments[1];\n" + "for (var i = 0; i < eventNames.length; i++) {" + " if (document.createEventObject) {\n" + // IE " var evt = document.createEventObject();\n" + " webElement.fireEvent('on' + eventNames[i], evt);\n" + " }\n" + " else {\n" + " var evt = document.createEvent('HTMLEvents');\n " + " evt.initEvent(eventNames[i], true, true );\n " + " webElement.dispatchEvent(evt);\n" + " }\n" + '}'; executeJavaScript(jsCodeToTriggerEvent, element, event); } catch (StaleElementReferenceException ignore) { } } protected Object should(Object proxy, String prefix, String message, List<Condition> conditions) { for (Condition condition : conditions) { checkCondition(prefix, message, condition, false); } return proxy; } protected WebElement checkCondition(String prefix, String message, Condition condition, boolean invert) { Condition check = invert ? not(condition) : condition; Throwable lastError = null; WebElement element = null; try { element = getActualDelegate(); if (element != null && check.apply(element)) { return element; } } catch (WebDriverException elementNotFound) { lastError = elementNotFound; } catch (IndexOutOfBoundsException e) { lastError = e; } catch (RuntimeException e) { throw Cleanup.of.wrap(e); } if (Cleanup.of.isInvalidSelectorError(lastError)) { throw Cleanup.of.wrap(lastError); } if (element == null) { if (!check.applyNull()) { throw createElementNotFoundError(check, lastError); } } else if (invert) { throw new ElementShouldNot(getSearchCriteria(), prefix, message, condition, element, lastError); } else { throw new ElementShould(getSearchCriteria(), prefix, message, condition, element, lastError); } return null; } protected Object shouldNot(Object proxy, String prefix, List<Condition> conditions) { return shouldNot(proxy, prefix, null, conditions); } protected Object shouldNot(Object proxy, String prefix, String message, List<Condition> conditions) { for (Condition condition : conditions) { checkCondition(prefix, message, condition, true); } return proxy; } protected File uploadFromClasspath(SelenideElement inputField, String... fileName) throws URISyntaxException, IOException { File[] files = new File[fileName.length]; for (int i = 0; i < fileName.length; i++) { files[i] = findFileInClasspath(fileName[i]); } return uploadFile(inputField, files); } protected File findFileInClasspath(String name) throws URISyntaxException { URL resource = currentThread().getContextClassLoader().getResource(name); if (resource == null) { throw new IllegalArgumentException("File not found in classpath: " + name); } return new File(resource.toURI()); } protected File uploadFile(SelenideElement inputField, File... file) throws IOException { if (file.length == 0) { throw new IllegalArgumentException("No files to upload"); } File uploadedFile = uploadFile(inputField, file[0]); if (file.length > 1) { SelenideElement form = inputField.closest("form"); for (int i = 1; i < file.length; i++) { uploadFile(cloneInputField(form, inputField), file[i]); } } return uploadedFile; } protected WebElement cloneInputField(SelenideElement form, SelenideElement inputField) { return executeJavaScript( "var fileInput = document.createElement('input');" + "fileInput.setAttribute('type', arguments[1].getAttribute('type'));" + "fileInput.setAttribute('name', arguments[1].getAttribute('name'));" + "fileInput.style.width = '1px';" + "fileInput.style.height = '1px';" + "arguments[0].appendChild(fileInput);" + "return fileInput;", form, inputField); } protected File uploadFile(WebElement inputField, File file) throws IOException { if (!"input".equalsIgnoreCase(inputField.getTagName())) { throw new IllegalArgumentException("Cannot upload file because " + Describe.describe(inputField) + " is not an INPUT"); } if (!file.exists()) { throw new IllegalArgumentException("File not found: " + file.getAbsolutePath()); } String canonicalPath = file.getCanonicalPath(); inputField.sendKeys(canonicalPath); return new File(canonicalPath); } protected void selectOptionByText(String optionText) { WebElement selectField = getDelegate(); new Select(selectField).selectByVisibleText(optionText); } protected void selectOptionByValue(String optionValue) { WebElement selectField = getDelegate(); selectOptionByValue(selectField, optionValue); } protected void selectOptionByValue(WebElement selectField, String optionValue) { new Select(selectField).selectByValue(optionValue); } protected String getSelectedValue(WebElement selectElement) { WebElement option = getSelectedOption(selectElement); return option == null ? null : option.getAttribute("value"); } protected String getSelectedText(WebElement selectElement) { WebElement option = getSelectedOption(selectElement); return option == null ? null : option.getText(); } protected SelenideElement getSelectedOption(WebElement selectElement) { return wrap(new Select(selectElement).getFirstSelectedOption()); } protected boolean exists() { try { return getActualDelegate() != null; } catch (WebDriverException elementNotFound) { if (Cleanup.of.isInvalidSelectorError(elementNotFound)) { throw Cleanup.of.wrap(elementNotFound); } return false; } catch (IndexOutOfBoundsException invalidElementIndex) { return false; } } protected boolean isDisplayed() { try { WebElement element = getActualDelegate(); return element != null && element.isDisplayed(); } catch (WebDriverException elementNotFound) { if (Cleanup.of.isInvalidSelectorError(elementNotFound)) { throw Cleanup.of.wrap(elementNotFound); } return false; } catch (IndexOutOfBoundsException invalidElementIndex) { return false; } } protected String describe() { try { return Describe.describe(getActualDelegate()); } catch (WebDriverException elementDoesNotExist) { return Cleanup.of.webdriverExceptionMessage(elementDoesNotExist); } catch (IndexOutOfBoundsException invalidElementIndex) { return invalidElementIndex.toString(); } } static Object delegateSeleniumMethod(WebElement delegate, Method method, Object[] args) throws Throwable { try { return method.invoke(delegate, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } protected ElementNotFound createElementNotFoundError(Condition condition, Throwable lastError) { return new ElementNotFound(getSearchCriteria(), condition, lastError); } protected boolean exists(WebElement element) { try { if (element == null) return false; element.isDisplayed(); return true; } catch (WebDriverException elementNotFound) { return false; } } protected WebElement getElementOrNull() { try { return getActualDelegate(); } catch (WebDriverException elementNotFound) { if (Cleanup.of.isInvalidSelectorError(elementNotFound)) throw Cleanup.of.wrap(elementNotFound); return null; } catch (IndexOutOfBoundsException ignore) { return null; } catch (RuntimeException e) { throw Cleanup.of.wrap(e); } } protected SelenideElement find(SelenideElement proxy, Object arg, int index) { return WaitingSelenideElement.wrap(proxy, getSelector(arg), index); } protected By getSelector(Object arg) { return arg instanceof By ? (By) arg : By.cssSelector((String) arg); } protected SelenideElement parent(SelenideElement me) { return find(me, By.xpath(".."), 0); } protected SelenideElement closest(SelenideElement me, String tagOrClass) { return tagOrClass.startsWith(".") ? find(me, By.xpath("ancestor::*[contains(concat(' ', normalize-space(@class), ' '), ' " + tagOrClass.substring(1)+ " ')][1]"), 0) : find(me, By.xpath("ancestor::" + tagOrClass + "[1]"), 0); } protected void scrollTo() { Point location = getDelegate().getLocation(); executeJavaScript("window.scrollTo(" + location.getX() + ", " + location.getY() + ')'); } protected File download() throws IOException, URISyntaxException { return FileDownloader.instance.download(getDelegate()); } }
src/main/java/com/codeborne/selenide/impl/AbstractSelenideElement.java
package com.codeborne.selenide.impl; import com.codeborne.selenide.Condition; import com.codeborne.selenide.ElementsCollection; import com.codeborne.selenide.SelenideElement; import com.codeborne.selenide.ex.ElementNotFound; import com.codeborne.selenide.ex.ElementShould; import com.codeborne.selenide.ex.ElementShouldNot; import com.codeborne.selenide.ex.UIAssertionError; import org.openqa.selenium.*; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.support.ui.Select; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URISyntaxException; import java.net.URL; import java.util.*; import static com.codeborne.selenide.Condition.exist; import static com.codeborne.selenide.Condition.not; import static com.codeborne.selenide.Condition.visible; import static com.codeborne.selenide.Configuration.AssertionMode.SOFT; import static com.codeborne.selenide.Configuration.*; import static com.codeborne.selenide.Selectors.byText; import static com.codeborne.selenide.Selectors.byValue; import static com.codeborne.selenide.Selenide.*; import static com.codeborne.selenide.WebDriverRunner.isHtmlUnit; import static com.codeborne.selenide.WebDriverRunner.isIE; import static com.codeborne.selenide.impl.WebElementProxy.wrap; import static com.codeborne.selenide.logevents.LogEvent.EventStatus.PASSED; import static java.lang.System.currentTimeMillis; import static java.lang.Thread.currentThread; import static java.util.Arrays.asList; abstract class AbstractSelenideElement implements InvocationHandler { abstract WebElement getDelegate(); abstract WebElement getActualDelegate() throws NoSuchElementException, IndexOutOfBoundsException; abstract String getSearchCriteria(); private static final Set<String> methodsToSkipLogging = new HashSet<String>(asList( "toWebElement", "toString" )); private static final Set<String> methodsForSoftAssertion = new HashSet<String>(asList( "should", "shouldBe", "shouldHave", "shouldNot", "shouldNotHave", "shouldNotBe", "waitUntil", "waitWhile" )); @Override public Object invoke(Object proxy, Method method, Object... args) throws Throwable { if (methodsToSkipLogging.contains(method.getName())) return dispatchSelenideMethod(proxy, method, args); SelenideLog log = SelenideLogger.beginStep(getSearchCriteria(), method.getName(), args); try { Object result = dispatchAndRetry(proxy, method, args); SelenideLogger.commitStep(log, PASSED); return result; } catch (UIAssertionError error) { SelenideLogger.commitStep(log, error); if (assertionMode == SOFT && methodsForSoftAssertion.contains(method.getName())) return proxy; else throw error; } catch (WebDriverException error) { SelenideLogger.commitStep(log, error); throw Cleanup.of.isInvalidSelectorError(error) ? error : new UIAssertionError(error); } catch (Throwable error) { SelenideLogger.commitStep(log, error); throw error; } } protected Object dispatchAndRetry(Object proxy, Method method, Object[] args) throws Throwable { long timeoutMs = getTimeoutMs(method, args); final long startTime = currentTimeMillis(); Throwable lastError; do { try { return method.getDeclaringClass() == SelenideElement.class ? dispatchSelenideMethod(proxy, method, args) : delegateSeleniumMethod(getDelegate(), method, args); } catch (Throwable e) { if (Cleanup.of.isInvalidSelectorError(e)) { throw Cleanup.of.wrap(e); } lastError = e; sleep(pollingInterval); } } while (currentTimeMillis() - startTime <= timeoutMs); if (lastError instanceof UIAssertionError) { UIAssertionError uiError = (UIAssertionError) lastError; uiError.timeoutMs = timeoutMs; throw uiError; } else if (lastError instanceof WebDriverException) { ElementNotFound uiError = createElementNotFoundError(exist, lastError); uiError.timeoutMs = timeoutMs; throw uiError; } throw lastError; } private long getTimeoutMs(Method method, Object[] args) { return "waitUntil".equals(method.getName()) || "waitWhile".equals(method.getName()) ? (Long) args[args.length - 1] : timeout; } protected Object dispatchSelenideMethod(Object proxy, Method method, Object[] args) throws Throwable { if ("setValue".equals(method.getName())) { setValue((String) args[0]); return proxy; } else if ("val".equals(method.getName())) { if (args == null || args.length == 0) { return getValue(); } else { setValue((String) args[0]); return proxy; } } else if ("attr".equals(method.getName())) { return getDelegate().getAttribute((String) args[0]); } else if ("name".equals(method.getName())) { return getDelegate().getAttribute("name"); } else if ("data".equals(method.getName())) { return getDelegate().getAttribute("data-" + args[0]); } else if ("append".equals(method.getName())) { append((String) args[0]); return proxy; } else if ("pressEnter".equals(method.getName())) { findAndAssertElementIsVisible().sendKeys(Keys.ENTER); return proxy; } else if ("pressTab".equals(method.getName())) { findAndAssertElementIsVisible().sendKeys(Keys.TAB); return proxy; } else if ("followLink".equals(method.getName())) { followLink(); return null; } else if ("text".equals(method.getName())) { return getDelegate().getText(); } else if ("innerText".equals(method.getName())) { return getInnerText(); } else if ("innerHtml".equals(method.getName())) { return getInnerHtml(); } else if ("should".equals(method.getName())) { return invokeShould(proxy, "", args); } else if ("waitUntil".equals(method.getName())) { return invokeShould(proxy, "be ", args); } else if ("shouldHave".equals(method.getName())) { return invokeShould(proxy, "have ", args); } else if ("shouldBe".equals(method.getName())) { return invokeShould(proxy, "be ", args); } else if ("shouldNot".equals(method.getName())) { return invokeShouldNot(proxy, "", args); } else if ("waitWhile".equals(method.getName())) { return invokeShouldNot(proxy, "be ", args); } else if ("shouldNotHave".equals(method.getName())) { return invokeShouldNot(proxy, "have ", args); } else if ("shouldNotBe".equals(method.getName())) { return invokeShouldNot(proxy, "be ", args); } else if ("parent".equals(method.getName())) { return parent((SelenideElement) proxy); } else if ("closest".equals(method.getName())) { return closest((SelenideElement) proxy, (String) args[0]); } else if ("find".equals(method.getName()) || "$".equals(method.getName())) { return args.length == 1 ? find((SelenideElement) proxy, args[0], 0) : find((SelenideElement) proxy, args[0], (Integer) args[1]); } else if ("findAll".equals(method.getName()) || "$$".equals(method.getName())) { final SelenideElement parent = (SelenideElement) proxy; return new ElementsCollection(new BySelectorCollection(parent, getSelector(args[0]))); } else if ("toString".equals(method.getName())) { return describe(); } else if ("exists".equals(method.getName())) { return exists(); } else if ("isDisplayed".equals(method.getName())) { return isDisplayed(); } else if ("is".equals(method.getName()) || "has".equals(method.getName())) { return matches((Condition) args[0]); } else if ("setSelected".equals(method.getName())) { setSelected((Boolean) args[0]); return proxy; } else if ("uploadFile".equals(method.getName())) { return uploadFile((SelenideElement) proxy, (File[]) args[0]); } else if ("uploadFromClasspath".equals(method.getName())) { return uploadFromClasspath((SelenideElement) proxy, (String[]) args[0]); } else if ("selectOption".equals(method.getName())) { selectOptionByText((String) args[0]); return null; } else if ("selectOptionByValue".equals(method.getName())) { selectOptionByValue((String) args[0]); return null; } else if ("getSelectedOption".equals(method.getName())) { return getSelectedOption(getDelegate()); } else if ("getSelectedValue".equals(method.getName())) { return getSelectedValue(getDelegate()); } else if ("getSelectedText".equals(method.getName())) { return getSelectedText(getDelegate()); } else if ("toWebElement".equals(method.getName())) { return getActualDelegate(); } else if ("scrollTo".equals(method.getName())) { scrollTo(); return proxy; } else if ("download".equals(method.getName())) { return download(); } else if ("click".equals(method.getName())) { click(); return null; } else if ("contextClick".equals(method.getName())) { contextClick(); return proxy; } else if ("hover".equals(method.getName())) { hover(); return proxy; } else if ("dragAndDropTo".equals(method.getName())) { dragAndDropTo((String) args[0]); return proxy; } else if ("getWrappedElement".equals(method.getName())) { return getActualDelegate(); } else if ("isImage".equals(method.getName())) { return isImage(); } else { throw new IllegalArgumentException("Unknown Selenide method: " + method.getName()); } } protected Object invokeShould(Object proxy, String prefix, Object[] args) { String message = null; if (args[0] instanceof String) { message = (String) args[0]; } return should(proxy, prefix, message, argsToConditions(args)); } private List<Condition> argsToConditions(Object[] args) { List<Condition> conditions = new ArrayList<Condition>(args.length); for (Object arg : args) { if (arg instanceof Condition) conditions.add((Condition) arg); else if (arg instanceof Condition[]) conditions.addAll(asList((Condition[]) arg)); else if (!(arg instanceof String || arg instanceof Long)) throw new IllegalArgumentException("Unknown parameter: " + arg); } return conditions; } protected Object invokeShouldNot(Object proxy, String prefix, Object[] args) { if (args[0] instanceof String) { return shouldNot(proxy, prefix, (String) args[0], argsToConditions(args)); } return shouldNot(proxy, prefix, argsToConditions(args)); } protected Boolean isImage() { WebElement img = getActualDelegate(); if (!"img".equalsIgnoreCase(img.getTagName())) { throw new IllegalArgumentException("Method isImage() is only applicable for img elements"); } return executeJavaScript("return arguments[0].complete && " + "typeof arguments[0].naturalWidth != 'undefined' && " + "arguments[0].naturalWidth > 0", img); } protected boolean matches(Condition condition) { WebElement element = getElementOrNull(); if (element != null) { return condition.apply(element); } return condition.applyNull(); } protected void setSelected(boolean selected) { WebElement element = getDelegate(); if (element.isSelected() ^ selected) { click(element); } } protected String getInnerText() { WebElement element = getDelegate(); if (isHtmlUnit()) { return executeJavaScript("return arguments[0].innerText", element); } else if (isIE()) { return element.getAttribute("innerText"); } return element.getAttribute("textContent"); } protected String getInnerHtml() { WebElement element = getDelegate(); if (isHtmlUnit()) { return executeJavaScript("return arguments[0].innerHTML", element); } return element.getAttribute("innerHTML"); } protected void click() { click(findAndAssertElementIsVisible()); } protected void click(WebElement element) { if (clickViaJs) { executeJavaScript("arguments[0].click()", element); } else { element.click(); } } protected WebElement findAndAssertElementIsVisible() { return checkCondition("be ", null, visible, false); } protected void contextClick() { actions().contextClick(findAndAssertElementIsVisible()).perform(); } protected void hover() { actions().moveToElement(getDelegate()).perform(); } protected void dragAndDropTo(String targetCssSelector) { SelenideElement target = $(targetCssSelector).shouldBe(visible); actions().dragAndDrop(getDelegate(), target).perform(); } protected void followLink() { WebElement link = getDelegate(); String href = link.getAttribute("href"); click(link); // JavaScript $.click() doesn't take effect for <a href> if (href != null) { open(href); } } protected void setValue(String text) { WebElement element = findAndAssertElementIsVisible(); if ("select".equalsIgnoreCase(element.getTagName())) { selectOptionByValue(text); } else if (text == null || text.isEmpty()) { element.clear(); } else if (fastSetValue) { executeJavaScript("arguments[0].value = arguments[1]", element, text); fireEvent(element, "keydown", "keypress", "keyup", "change"); } else { element.clear(); element.sendKeys(text); fireChangeEvent(element); } } protected void fireChangeEvent(WebElement element) { fireEvent(element, "change"); } protected String getValue() { return getDelegate().getAttribute("value"); } protected void append(String text) { WebElement element = getDelegate(); element.sendKeys(text); fireChangeEvent(element); } protected void fireEvent(WebElement element, final String... event) { try { final String jsCodeToTriggerEvent = "var webElement = arguments[0];\n" + "var eventNames = arguments[1];\n" + "for (var i = 0; i < eventNames.length; i++) {" + " if (document.createEventObject) {\n" + // IE " var evt = document.createEventObject();\n" + " webElement.fireEvent('on' + eventNames[i], evt);\n" + " }\n" + " else {\n" + " var evt = document.createEvent('HTMLEvents');\n " + " evt.initEvent(eventNames[i], true, true );\n " + " webElement.dispatchEvent(evt);\n" + " }\n" + '}'; executeJavaScript(jsCodeToTriggerEvent, element, event); } catch (StaleElementReferenceException ignore) { } } protected Object should(Object proxy, String prefix, String message, List<Condition> conditions) { for (Condition condition : conditions) { checkCondition(prefix, message, condition, false); } return proxy; } protected WebElement checkCondition(String prefix, String message, Condition condition, boolean invert) { Condition check = invert ? not(condition) : condition; Throwable lastError = null; WebElement element = null; try { element = getActualDelegate(); if (element != null && check.apply(element)) { return element; } } catch (WebDriverException elementNotFound) { lastError = elementNotFound; } catch (IndexOutOfBoundsException e) { lastError = e; } catch (RuntimeException e) { throw Cleanup.of.wrap(e); } if (Cleanup.of.isInvalidSelectorError(lastError)) { throw Cleanup.of.wrap(lastError); } if (element == null) { if (!check.applyNull()) { throw createElementNotFoundError(check, lastError); } } else if (invert) { throw new ElementShouldNot(getSearchCriteria(), prefix, message, condition, element, lastError); } else { throw new ElementShould(getSearchCriteria(), prefix, message, condition, element, lastError); } return null; } protected Object shouldNot(Object proxy, String prefix, List<Condition> conditions) { return shouldNot(proxy, prefix, null, conditions); } protected Object shouldNot(Object proxy, String prefix, String message, List<Condition> conditions) { for (Condition condition : conditions) { checkCondition(prefix, message, condition, true); } return proxy; } protected File uploadFromClasspath(SelenideElement inputField, String... fileName) throws URISyntaxException, IOException { File[] files = new File[fileName.length]; for (int i = 0; i < fileName.length; i++) { files[i] = findFileInClasspath(fileName[i]); } return uploadFile(inputField, files); } protected File findFileInClasspath(String name) throws URISyntaxException { URL resource = currentThread().getContextClassLoader().getResource(name); if (resource == null) { throw new IllegalArgumentException("File not found in classpath: " + name); } return new File(resource.toURI()); } protected File uploadFile(SelenideElement inputField, File... file) throws IOException { if (file.length == 0) { throw new IllegalArgumentException("No files to upload"); } File uploadedFile = uploadFile(inputField, file[0]); if (file.length > 1) { SelenideElement form = inputField.closest("form"); for (int i = 1; i < file.length; i++) { uploadFile(cloneInputField(form, inputField), file[i]); } } return uploadedFile; } protected WebElement cloneInputField(SelenideElement form, SelenideElement inputField) { return executeJavaScript( "var fileInput = document.createElement('input');" + "fileInput.setAttribute('type', arguments[1].getAttribute('type'));" + "fileInput.setAttribute('name', arguments[1].getAttribute('name'));" + "fileInput.style.width = '1px';" + "fileInput.style.height = '1px';" + "arguments[0].appendChild(fileInput);" + "return fileInput;", form, inputField); } protected File uploadFile(WebElement inputField, File file) throws IOException { if (!"input".equalsIgnoreCase(inputField.getTagName())) { throw new IllegalArgumentException("Cannot upload file because " + Describe.describe(inputField) + " is not an INPUT"); } if (!file.exists()) { throw new IllegalArgumentException("File not found: " + file.getAbsolutePath()); } String canonicalPath = file.getCanonicalPath(); inputField.sendKeys(canonicalPath); return new File(canonicalPath); } protected void selectOptionByText(String optionText) { WebElement selectField = getDelegate(); $(selectField).should(exist).find(byText(optionText)).shouldBe(visible); new Select(selectField).selectByVisibleText(optionText); } protected void selectOptionByValue(String optionValue) { WebElement selectField = getDelegate(); selectOptionByValue(selectField, optionValue); } protected void selectOptionByValue(WebElement selectField, String optionValue) { $(selectField).should(exist).find(byValue(optionValue)).shouldBe(visible); new Select(selectField).selectByValue(optionValue); } protected String getSelectedValue(WebElement selectElement) { WebElement option = getSelectedOption(selectElement); return option == null ? null : option.getAttribute("value"); } protected String getSelectedText(WebElement selectElement) { WebElement option = getSelectedOption(selectElement); return option == null ? null : option.getText(); } protected SelenideElement getSelectedOption(WebElement selectElement) { return wrap(new Select(selectElement).getFirstSelectedOption()); } protected boolean exists() { try { return getActualDelegate() != null; } catch (WebDriverException elementNotFound) { if (Cleanup.of.isInvalidSelectorError(elementNotFound)) { throw Cleanup.of.wrap(elementNotFound); } return false; } catch (IndexOutOfBoundsException invalidElementIndex) { return false; } } protected boolean isDisplayed() { try { WebElement element = getActualDelegate(); return element != null && element.isDisplayed(); } catch (WebDriverException elementNotFound) { if (Cleanup.of.isInvalidSelectorError(elementNotFound)) { throw Cleanup.of.wrap(elementNotFound); } return false; } catch (IndexOutOfBoundsException invalidElementIndex) { return false; } } protected String describe() { try { return Describe.describe(getActualDelegate()); } catch (WebDriverException elementDoesNotExist) { return Cleanup.of.webdriverExceptionMessage(elementDoesNotExist); } catch (IndexOutOfBoundsException invalidElementIndex) { return invalidElementIndex.toString(); } } static Object delegateSeleniumMethod(WebElement delegate, Method method, Object[] args) throws Throwable { try { return method.invoke(delegate, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } protected ElementNotFound createElementNotFoundError(Condition condition, Throwable lastError) { return new ElementNotFound(getSearchCriteria(), condition, lastError); } protected boolean exists(WebElement element) { try { if (element == null) return false; element.isDisplayed(); return true; } catch (WebDriverException elementNotFound) { return false; } } protected WebElement getElementOrNull() { try { return getActualDelegate(); } catch (WebDriverException elementNotFound) { if (Cleanup.of.isInvalidSelectorError(elementNotFound)) throw Cleanup.of.wrap(elementNotFound); return null; } catch (IndexOutOfBoundsException ignore) { return null; } catch (RuntimeException e) { throw Cleanup.of.wrap(e); } } protected SelenideElement find(SelenideElement proxy, Object arg, int index) { return WaitingSelenideElement.wrap(proxy, getSelector(arg), index); } protected By getSelector(Object arg) { return arg instanceof By ? (By) arg : By.cssSelector((String) arg); } protected SelenideElement parent(SelenideElement me) { return find(me, By.xpath(".."), 0); } protected SelenideElement closest(SelenideElement me, String tagOrClass) { return tagOrClass.startsWith(".") ? find(me, By.xpath("ancestor::*[contains(concat(' ', normalize-space(@class), ' '), ' " + tagOrClass.substring(1)+ " ')][1]"), 0) : find(me, By.xpath("ancestor::" + tagOrClass + "[1]"), 0); } protected void scrollTo() { Point location = getDelegate().getLocation(); executeJavaScript("window.scrollTo(" + location.getX() + ", " + location.getY() + ')'); } protected File download() throws IOException, URISyntaxException { return FileDownloader.instance.download(getDelegate()); } }
do not require existence of "select": waiting loop is now outside
src/main/java/com/codeborne/selenide/impl/AbstractSelenideElement.java
do not require existence of "select": waiting loop is now outside
<ide><path>rc/main/java/com/codeborne/selenide/impl/AbstractSelenideElement.java <ide> import com.codeborne.selenide.ex.ElementShouldNot; <ide> import com.codeborne.selenide.ex.UIAssertionError; <ide> import org.openqa.selenium.*; <del>import org.openqa.selenium.NoSuchElementException; <ide> import org.openqa.selenium.support.ui.Select; <ide> <ide> import java.io.File; <ide> import java.lang.reflect.Method; <ide> import java.net.URISyntaxException; <ide> import java.net.URL; <del>import java.util.*; <del> <del>import static com.codeborne.selenide.Condition.exist; <del>import static com.codeborne.selenide.Condition.not; <del>import static com.codeborne.selenide.Condition.visible; <add>import java.util.ArrayList; <add>import java.util.HashSet; <add>import java.util.List; <add>import java.util.Set; <add> <add>import static com.codeborne.selenide.Condition.*; <ide> import static com.codeborne.selenide.Configuration.AssertionMode.SOFT; <ide> import static com.codeborne.selenide.Configuration.*; <del>import static com.codeborne.selenide.Selectors.byText; <del>import static com.codeborne.selenide.Selectors.byValue; <ide> import static com.codeborne.selenide.Selenide.*; <ide> import static com.codeborne.selenide.WebDriverRunner.isHtmlUnit; <ide> import static com.codeborne.selenide.WebDriverRunner.isIE; <ide> <ide> protected void selectOptionByText(String optionText) { <ide> WebElement selectField = getDelegate(); <del> $(selectField).should(exist).find(byText(optionText)).shouldBe(visible); <ide> new Select(selectField).selectByVisibleText(optionText); <ide> } <ide> <ide> } <ide> <ide> protected void selectOptionByValue(WebElement selectField, String optionValue) { <del> $(selectField).should(exist).find(byValue(optionValue)).shouldBe(visible); <ide> new Select(selectField).selectByValue(optionValue); <ide> } <ide>
Java
lgpl-2.1
1b3acb4e73953b1745fba45e952073b41ae6995e
0
rblasch/fb-contrib,mebigfatguy/fb-contrib,mebigfatguy/fb-contrib,ThrawnCA/fb-contrib,mebigfatguy/fb-contrib,ThrawnCA/fb-contrib,ThrawnCA/fb-contrib,rblasch/fb-contrib,rblasch/fb-contrib,ThrawnCA/fb-contrib,rblasch/fb-contrib
/* * fb-contrib - Auxiliary detectors for Java programs * Copyright (C) 2005-2016 Dave Brosius * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.mebigfatguy.fbcontrib.detect; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.CodeException; import com.mebigfatguy.fbcontrib.utils.OpcodeUtils; import com.mebigfatguy.fbcontrib.utils.ToString; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.ba.ClassContext; /** * looks for try/finally blocks that manage resources, without using try-with-resources */ public class UseTryWithResources extends BytecodeScanningDetector { private BugReporter bugReporter; private OpcodeStack stack; private Map<Integer, TryBlock> finallyBlocks; private Map<Integer, Integer> regStoredPCs; private int lastGoto; public UseTryWithResources(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void visitClassContext(ClassContext classContext) { try { int majorVersion = classContext.getJavaClass().getMajor(); if (majorVersion >= MAJOR_1_7) { stack = new OpcodeStack(); finallyBlocks = new HashMap<>(); regStoredPCs = new HashMap<>(); super.visitClassContext(classContext); } } finally { stack = null; finallyBlocks = null; regStoredPCs = null; } } @Override public void visitCode(Code obj) { if (prescreen(obj)) { stack.resetForMethodEntry(this); regStoredPCs.clear(); lastGoto = -1; super.visitCode(obj); } } @Override public void sawOpcode(int seen) { try { int pc = getPC(); Iterator<TryBlock> it = finallyBlocks.values().iterator(); while (it.hasNext()) { TryBlock tb = it.next(); if (tb.getHandlerEndPC() < pc) { it.remove(); } } TryBlock tb = finallyBlocks.get(pc); if (tb != null) { if (lastGoto > -1) { tb.setHandlerEndPC(lastGoto); } } if (OpcodeUtils.isAStore(seen)) { regStoredPCs.put(Integer.valueOf(getRegisterOperand()), Integer.valueOf(pc)); } lastGoto = (((seen == GOTO) || (seen == GOTO_W)) && (getBranchOffset() > 0)) ? getBranchTarget() : -1; } finally { stack.sawOpcode(this, seen); } } private boolean prescreen(Code obj) { finallyBlocks.clear(); CodeException[] ces = obj.getExceptionTable(); if ((ces == null) || (ces.length == 0)) { return false; } boolean hasFinally = false; for (CodeException ce : ces) { if (ce.getCatchType() == 0) { finallyBlocks.put(Integer.valueOf(ce.getHandlerPC()), new TryBlock(ce.getStartPC(), ce.getEndPC(), ce.getHandlerPC())); hasFinally = true; } } return hasFinally; } @Override public String toString() { return ToString.build(this); } static class TryBlock { private int startPC; private int endPC; private int handlerPC; private int handlerEndPC; public TryBlock(int startPC, int endPC, int handlerPC) { super(); this.startPC = startPC; this.endPC = endPC; this.handlerPC = handlerPC; this.handlerEndPC = Integer.MAX_VALUE; } public int getHandlerEndPC() { return handlerEndPC; } public void setHandlerEndPC(int handlerEndPC) { this.handlerEndPC = handlerEndPC; } public int getStartPC() { return startPC; } public int getEndPC() { return endPC; } public int getHandlerPC() { return handlerPC; } @Override public String toString() { return ToString.build(this); } } }
src/com/mebigfatguy/fbcontrib/detect/UseTryWithResources.java
/* * fb-contrib - Auxiliary detectors for Java programs * Copyright (C) 2005-2016 Dave Brosius * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.mebigfatguy.fbcontrib.detect; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.CodeException; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.ba.ClassContext; /** * looks for try/finally blocks that manage resources, without using try-with-resources */ public class UseTryWithResources extends BytecodeScanningDetector { private BugReporter bugReporter; private OpcodeStack stack; public UseTryWithResources(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void visitClassContext(ClassContext classContext) { try { int majorVersion = classContext.getJavaClass().getMajor(); if (majorVersion >= MAJOR_1_7) { stack = new OpcodeStack(); super.visitClassContext(classContext); } } finally { stack = null; } } @Override public void visitCode(Code obj) { if (prescreen(obj)) { stack.resetForMethodEntry(this); super.visitCode(obj); } } @Override public void sawOpcode(int seen) { try { } finally { stack.sawOpcode(this, seen); } } private boolean prescreen(Code obj) { CodeException[] ces = obj.getExceptionTable(); if ((ces == null) || (ces.length == 0)) { return false; } for (CodeException ce : ces) { if (ce.getCatchType() == 0) { return true; } } return false; } }
more tracking of finally blocks, and register allocations
src/com/mebigfatguy/fbcontrib/detect/UseTryWithResources.java
more tracking of finally blocks, and register allocations
<ide><path>rc/com/mebigfatguy/fbcontrib/detect/UseTryWithResources.java <ide> */ <ide> package com.mebigfatguy.fbcontrib.detect; <ide> <add>import java.util.HashMap; <add>import java.util.Iterator; <add>import java.util.Map; <add> <ide> import org.apache.bcel.classfile.Code; <ide> import org.apache.bcel.classfile.CodeException; <add> <add>import com.mebigfatguy.fbcontrib.utils.OpcodeUtils; <add>import com.mebigfatguy.fbcontrib.utils.ToString; <ide> <ide> import edu.umd.cs.findbugs.BugReporter; <ide> import edu.umd.cs.findbugs.BytecodeScanningDetector; <ide> <ide> private BugReporter bugReporter; <ide> private OpcodeStack stack; <add> private Map<Integer, TryBlock> finallyBlocks; <add> private Map<Integer, Integer> regStoredPCs; <add> private int lastGoto; <ide> <ide> public UseTryWithResources(BugReporter bugReporter) { <ide> this.bugReporter = bugReporter; <ide> <ide> if (majorVersion >= MAJOR_1_7) { <ide> stack = new OpcodeStack(); <add> finallyBlocks = new HashMap<>(); <add> regStoredPCs = new HashMap<>(); <ide> super.visitClassContext(classContext); <ide> } <ide> } finally { <ide> stack = null; <add> finallyBlocks = null; <add> regStoredPCs = null; <ide> } <ide> } <ide> <ide> public void visitCode(Code obj) { <ide> if (prescreen(obj)) { <ide> stack.resetForMethodEntry(this); <add> regStoredPCs.clear(); <add> lastGoto = -1; <ide> super.visitCode(obj); <ide> } <ide> } <ide> @Override <ide> public void sawOpcode(int seen) { <ide> try { <add> int pc = getPC(); <add> Iterator<TryBlock> it = finallyBlocks.values().iterator(); <add> while (it.hasNext()) { <add> TryBlock tb = it.next(); <add> if (tb.getHandlerEndPC() < pc) { <add> it.remove(); <add> } <add> } <add> TryBlock tb = finallyBlocks.get(pc); <add> if (tb != null) { <add> if (lastGoto > -1) { <add> tb.setHandlerEndPC(lastGoto); <add> } <add> } <ide> <add> if (OpcodeUtils.isAStore(seen)) { <add> regStoredPCs.put(Integer.valueOf(getRegisterOperand()), Integer.valueOf(pc)); <add> } <add> <add> lastGoto = (((seen == GOTO) || (seen == GOTO_W)) && (getBranchOffset() > 0)) ? getBranchTarget() : -1; <ide> } finally { <ide> stack.sawOpcode(this, seen); <ide> } <ide> } <ide> <ide> private boolean prescreen(Code obj) { <add> finallyBlocks.clear(); <ide> CodeException[] ces = obj.getExceptionTable(); <ide> if ((ces == null) || (ces.length == 0)) { <ide> return false; <ide> } <ide> <add> boolean hasFinally = false; <ide> for (CodeException ce : ces) { <ide> if (ce.getCatchType() == 0) { <del> return true; <add> finallyBlocks.put(Integer.valueOf(ce.getHandlerPC()), new TryBlock(ce.getStartPC(), ce.getEndPC(), ce.getHandlerPC())); <add> hasFinally = true; <ide> } <ide> } <ide> <del> return false; <add> return hasFinally; <add> } <add> <add> @Override <add> public String toString() { <add> return ToString.build(this); <add> } <add> <add> static class TryBlock { <add> private int startPC; <add> private int endPC; <add> private int handlerPC; <add> private int handlerEndPC; <add> <add> public TryBlock(int startPC, int endPC, int handlerPC) { <add> super(); <add> this.startPC = startPC; <add> this.endPC = endPC; <add> this.handlerPC = handlerPC; <add> this.handlerEndPC = Integer.MAX_VALUE; <add> } <add> <add> public int getHandlerEndPC() { <add> return handlerEndPC; <add> } <add> <add> public void setHandlerEndPC(int handlerEndPC) { <add> this.handlerEndPC = handlerEndPC; <add> } <add> <add> public int getStartPC() { <add> return startPC; <add> } <add> <add> public int getEndPC() { <add> return endPC; <add> } <add> <add> public int getHandlerPC() { <add> return handlerPC; <add> } <add> <add> @Override <add> public String toString() { <add> return ToString.build(this); <add> } <ide> } <ide> }
Java
apache-2.0
b6b08ba9e39809b0820e22eb83709342ab4f64f3
0
isomorphic-software/isc-maven-plugin
package com.isomorphic.maven.mojo; /* * 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 static com.isomorphic.maven.packaging.License.ANALYTICS_MODULE; import static com.isomorphic.maven.packaging.License.ENTERPRISE; import static com.isomorphic.maven.packaging.License.MESSAGING_MODULE; import static com.isomorphic.maven.packaging.License.POWER; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Set; import java.util.TimeZone; import java.util.TreeSet; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.TrueFileFilter; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.maven.model.Model; import org.apache.maven.model.building.DefaultModelBuildingRequest; import org.apache.maven.model.building.ModelBuilder; import org.apache.maven.model.building.ModelBuildingException; import org.apache.maven.model.building.ModelBuildingRequest; import org.apache.maven.model.building.ModelBuildingResult; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.isomorphic.maven.packaging.Distribution; import com.isomorphic.maven.packaging.Downloads; import com.isomorphic.maven.packaging.License; import com.isomorphic.maven.packaging.Module; import com.isomorphic.maven.packaging.Product; /** * A base class meant to deal with prerequisites to install / deploy goals, * which are basically to resolve the files in a given distribution to a * collection of Maven artifacts suitable for installation or deployment to some * Maven repository. * <p/> * The resulting artifacts are provided to this object's {@link #doExecute(Set)} * method. */ public abstract class AbstractPackagerMojo extends AbstractMojo { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractPackagerMojo.class); /** * If true, the optional analytics module (bundled and distributed * separately) has been licensed and should be downloaded with the * distribution specified by {@link #license}. * * @since 1.0.0 */ @Parameter(property = "includeAnalytics", defaultValue = "false") protected Boolean includeAnalytics; /** * The date on which the Isomorphic build was made publicly available at <a * href * ="http://www.smartclient.com/builds/">http://www.smartclient.com/builds * /</a>, in yyyy-MM-dd format. e.g., 2013-25-12. Used to determine both * remote and local file locations. <br/> * <b>Default value is</b>: <tt>The current date</tt>. * * @since 1.0.0 */ @Parameter(property = "buildDate") protected String buildDate; /** * The Isomorphic version number of the specified {@link #product}. e.g., * 9.1d, 4.0p. Used to determine both remote and local file locations. * * @since 1.0.0 */ @Parameter(property = "buildNumber", required = true) protected String buildNumber; /** * Typically one of: LGPL, EVAL, PRO, POWER, ENTERPRISE. Although it is also * valid to specify optional modules ANALYTICS_MODULE or MESSAGING_MODULE, * generally prefer the {@link #includeAnalytics} / * {@link #includeMessaging} properties, respectively, to cause the optional * modules to be included with the base installation / deployment. * * @since 1.0.0 */ @Parameter(property = "license", required = true) protected License license; /** * If true, the optional messaging module (bundled and distributed * separately) has been licensed and should be downloaded with the * distribution specified by {@link #license}. * * @since 1.0.0 */ @Parameter(property = "includeMessaging", defaultValue = "false") protected Boolean includeMessaging; /** * If true, any file previously downloaded / unpacked will be overwritten * with this execution. Useful in the case of an interrupted download. Note * that this setting has no effect on unzip operations. * * @since 1.0.0 */ @Parameter(property = "overwrite", defaultValue = "false") protected Boolean overwrite; /** * If true, no attempt is made to download any remote distribution. Files * will be loaded instead from a path constructed of the following parts * (e.g., C:/downloads/SmartGWT/PowerEdition/4.1d/2013-12-25/zip): * <p/> * <ul> * <li>{@link #workdir}</li> * <li>{@link #product}</li> * <li>{@link #license}</li> * <li>{@link #buildNumber}</li> * <li>{@link #buildDate}</li> * <li>"zip"</li> * </ul> * * @since 1.0.0 */ @Parameter(property = "skipDownload", defaultValue = "false") protected Boolean skipDownload; /** * If true, no attempt it made to extract the contents of any distribution. * Only useful in the case where some manual intervention is required * between download and another step. For example, it would be possible to * first run the download goal, manipulate the version number of some * dependency in some POM, and then run the install goal with * skipExtraction=false to prevent the modified POM from being overwritten. * <p/> * This is the kind of thing that should generally be avoided, however. */ @Parameter(property = "skipExtraction", defaultValue = "false") protected Boolean skipExtraction; /** * One of SMARTGWT, SMARTCLIENT, or SMARTGWT_MOBILE. * * @since 1.0.0 */ @Parameter(property = "product", defaultValue = "SMARTGWT") protected Product product; /** * If true, artifacts should be <a href= * "http://books.sonatype.com/mvnref-book/reference/pom-relationships-sect-pom-syntax.html#pom-reationships-sect-versions" * >versioned</a> with the 'SNAPSHOT' qualifier, in the case of development * builds only. The setting has no effect on patch builds. * <p/> * If false, each artifact's POM file is modified to remove the unwanted * qualifier. This can be useful if you need to deploy a development build * to a production environment. * * @since 1.0.0 */ @Parameter(property = "snapshots", defaultValue = "true") protected Boolean snapshots; /** * The path to some directory that is to be used for storing downloaded * files, working copies, and so on. * * @since 1.0.0 */ @Parameter(property = "workdir", defaultValue = "${java.io.tmpdir}/${project.artifactId}") protected File workdir; /** * The id of a <a * href="http://maven.apache.org/settings.html#Servers">server * configuration</a> containing authentication credentials for the * smartclient.com website, used to download licensed products. * <p/> * Not strictly necessary for unprotected (LGPL) distributions. * * @since 1.0.0 */ @Parameter(property = "serverId", defaultValue = "smartclient-developer") protected String serverId; @Parameter(readonly = true, defaultValue = "${repositorySystemSession}") protected RepositorySystemSession repositorySystemSession; @Component protected ModelBuilder modelBuilder; @Component protected MavenProject project; @Component protected RepositorySystem repositorySystem; @Component protected Settings settings; /** * The point where a subclass is able to manipulate the collection of * artifacts prepared for it by this object's {@link #execute()} method. * * @param artifacts * A collection of Maven artifacts resulting from the download * and preparation of a supported Isomorphic SDK. * @throws MojoExecutionException * When any fatal error occurs. e.g., there is no distribution * to work with. * @throws MojoFailureException * When any non-fatal error occurs. e.g., documentation cannot * be copied to some other folder. */ public abstract void doExecute(Set<Module> artifacts) throws MojoExecutionException, MojoFailureException; /** * Provides some initialization and validation steps around the collection * and transformation of an Isomorphic SDK. * * @throws MojoExecutionException * When any fatal error occurs. * @throws MojoFailureException * When any non-fatal error occurs. */ public void execute() throws MojoExecutionException, MojoFailureException { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); dateFormat.setLenient(false); if (buildDate == null) { buildDate = dateFormat.format(new Date()); } try { dateFormat.parse(buildDate); } catch (ParseException e) { throw new MojoExecutionException(String.format( "buildDate '%s' must take the form yyyy-MM-dd.", buildDate)); } LOGGER.debug("buildDate set to '{}'", buildDate); String buildNumberFormat = "\\d.*\\.\\d.*[d|p]"; if (!buildNumber.matches(buildNumberFormat)) { throw new MojoExecutionException(String.format( "buildNumber '%s' must take the form [major].[minor].[d|p]. e.g., 4.1d", buildNumber, buildNumberFormat)); } File basedir = FileUtils.getFile(workdir, product.toString(), license.toString(), buildNumber, buildDate); // add optional modules to the list of downloads List<License> licenses = new ArrayList<License>(); licenses.add(license); if (license == POWER || license == ENTERPRISE) { if (includeAnalytics) { licenses.add(ANALYTICS_MODULE); } if (includeMessaging) { licenses.add(MESSAGING_MODULE); } } // collect the maven artifacts and send them along to the abstract // method Set<Module> artifacts = collect(licenses, basedir); File bookmarkable = new File(basedir.getParent(), "latest"); LOGGER.info("Copying distribution to '{}'", bookmarkable.getAbsolutePath()); try { FileUtils.forceMkdir(bookmarkable); FileUtils.cleanDirectory(bookmarkable); FileUtils.copyDirectory(basedir, bookmarkable, FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter("zip"))); } catch (IOException e) { throw new MojoFailureException("Unable to copy distribution contents", e); } String[] executables = { "bat", "sh", "command" }; Collection<File> scripts = FileUtils.listFiles(basedir, executables, true); scripts.addAll(FileUtils.listFiles(bookmarkable, executables, true)); for (File script : scripts) { script.setExecutable(true); LOGGER.debug("Enabled execute permissions on file '{}'", script.getAbsolutePath()); } doExecute(artifacts); } /** * Download the specified distributions, if necessary, extract resources * from them, and use the results to create Maven artifacts as appropriate: * <p/> * Try to install all of the main artifacts - e.g., those found in lib/*.jar * and assembly/*.zip <br/> * Try to match main artifacts to 'subartifacts' by name and attach them * (with classifiers as necessary) * * @param downloads * The list of licenses top be included in the distribution. * Multiple licenses are only allowed to support the inclusion of * optional modules. * @param basedir * The directory into which results should be written * @return A collection of Maven artifacts resulting from the download and * preparation of a supported Isomorphic SDK. * @throws MojoExecutionException * When any fatal error occurs. */ private Set<Module> collect(List<License> downloads, File basedir) throws MojoExecutionException { // allow execution to proceed without login credentials - it may be that // they're not required Server server = settings.getServer(serverId); String username = null; String password = null; if (server != null) { username = server.getUsername(); password = server.getPassword(); } else { LOGGER.warn("No server configured with id '{}'. Will be unable to authenticate.", serverId); } UsernamePasswordCredentials credentials = null; if (username != null) { credentials = new UsernamePasswordCredentials(username, password); } File downloadTo = new File(basedir, "zip"); downloadTo.mkdirs(); Downloads downloadManager = new Downloads(credentials); downloadManager.setToFolder(downloadTo); downloadManager.setProxyConfiguration(settings.getActiveProxy()); downloadManager.setOverwriteExistingFiles(overwrite); File[] existing = downloadTo.listFiles(); List<Distribution> distributions = new ArrayList<Distribution>(); try { if (!skipDownload) { distributions.addAll(downloadManager.fetch(product, buildNumber, buildDate, downloads.toArray(new License[0]))); } else if (existing != null) { LOGGER.info("Creating local distribution from '{}'", downloadTo.getAbsolutePath()); Distribution distribution = Distribution.get(product, license, buildNumber, buildDate); distribution.getFiles().addAll(Arrays.asList(existing)); distributions.add(distribution); } if (!skipExtraction) { LOGGER.info("Unpacking downloaded file/s to '{}'", basedir); for (Distribution distribution : distributions) { distribution.unpack(basedir); } } // it doesn't strictly read this way, but we're looking for // lib/*.jar, pom/*.xml, assembly/*.zip // TODO it'd be better if this didn't have to know where the files // were located after unpacking Collection<File> files = FileUtils.listFiles( basedir, FileFilterUtils.or(FileFilterUtils.suffixFileFilter("jar"), FileFilterUtils.suffixFileFilter("xml"), FileFilterUtils.suffixFileFilter("zip")), FileFilterUtils.or(FileFilterUtils.nameFileFilter("lib"), FileFilterUtils.nameFileFilter("pom"), FileFilterUtils.nameFileFilter("assembly"))); if (files.isEmpty()) { throw new MojoExecutionException( String .format( "There don't appear to be any files to work with at '%s'. Check earlier log entries for clues.", basedir.getAbsolutePath())); } Set<Module> result = new TreeSet<Module>(); for (File file : files) { try { String base = FilenameUtils.getBaseName(file.getName() .replaceAll("_", "-")); // poms don't need anything else if ("xml".equals(FilenameUtils.getExtension(file.getName()))) { result.add(new Module(getModelFromFile(file))); continue; } // for each jar/zip, find the matching pom IOFileFilter filter = new WildcardFileFilter(base + ".pom"); Collection<File> poms = FileUtils.listFiles(basedir, filter, TrueFileFilter.INSTANCE); if (poms.size() != 1) { LOGGER .warn( "Expected to find exactly 1 POM matching artifact with name '{}', but found {}. Skpping installation.", base, poms.size()); continue; } Model model = getModelFromFile(poms.iterator().next()); Module module = new Module(model, file); /* * Find the right javadoc bundle, matched on prefix. e.g., * smartgwt-eval -> smartgwt-javadoc isomorphic-core-rpc -> * isomorphic-javadoc and add it to the main artifact with * the javadoc classifier. This seems appropriate as long as * a) there is no per-jar javadoc b) naming conventions are * adhered to (or can be corrected by plugin at extraction) */ int index = base.indexOf("-"); String prefix = base.substring(0, index); Collection<File> doc = FileUtils.listFiles(new File(basedir, "doc"), FileFilterUtils.prefixFileFilter(prefix), FileFilterUtils.nameFileFilter("lib")); if (doc.size() != 1) { LOGGER .debug( "Found {} javadoc attachments with prefix '{}'. Skipping attachment.", doc.size(), prefix); } else { module.attach(doc.iterator().next(), "javadoc"); } result.add(module); } catch (ModelBuildingException e) { throw new MojoExecutionException("Error building model from POM", e); } } return result; } catch (IOException e) { throw new MojoExecutionException("Failure during assembly collection", e); } } /** * Read the given POM so it can be used as the source of coordinates, etc. * during artifact construction. Note that if this object's * {@link #snapshots} property is true, and we're working with a development * build ({@link #buildNumber} ends with 'd'), the POM is modified to remove * the SNAPSHOT qualifier. * * @param pom * the POM file containing the artifact metadata * @return A Maven model to be used at * {@link com.isomorphic.maven.packaging.Module#Module(Model)} * Module construction * @throws ModelBuildingException * if the Model cannot be built from the given POM * @throws IOException * if the Model cannot be built from the given POM */ private Model getModelFromFile(File pom) throws ModelBuildingException, IOException { if (buildNumber.endsWith("d") && !snapshots) { LOGGER.info( "Rewriting file to remove SNAPSHOT qualifier from development POM '{}'", pom.getName()); String content = FileUtils.readFileToString(pom); content = content.replaceAll("-SNAPSHOT", ""); FileUtils.write(pom, content); } ModelBuildingRequest request = new DefaultModelBuildingRequest(); request.setPomFile(pom); ModelBuildingResult result = modelBuilder.build(request); return result.getEffectiveModel(); } }
src/main/java/com/isomorphic/maven/mojo/AbstractPackagerMojo.java
package com.isomorphic.maven.mojo; /* * 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 static com.isomorphic.maven.packaging.License.ANALYTICS_MODULE; import static com.isomorphic.maven.packaging.License.ENTERPRISE; import static com.isomorphic.maven.packaging.License.MESSAGING_MODULE; import static com.isomorphic.maven.packaging.License.POWER; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.TrueFileFilter; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.maven.model.Model; import org.apache.maven.model.building.DefaultModelBuildingRequest; import org.apache.maven.model.building.ModelBuilder; import org.apache.maven.model.building.ModelBuildingException; import org.apache.maven.model.building.ModelBuildingRequest; import org.apache.maven.model.building.ModelBuildingResult; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.isomorphic.maven.packaging.Distribution; import com.isomorphic.maven.packaging.Downloads; import com.isomorphic.maven.packaging.License; import com.isomorphic.maven.packaging.Module; import com.isomorphic.maven.packaging.Product; /** * A base class meant to deal with prerequisites to install / deploy goals, which are basically * to resolve the files in a given distribution to a collection of Maven artifacts suitable for * installation or deployment to some Maven repository. * <p/> * The resulting artifacts are provided to this object's {@link #doExecute(Set)} method. */ public abstract class AbstractPackagerMojo extends AbstractMojo { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractPackagerMojo.class); /** * If true, the optional analytics module (bundled and distributed separately) has been licensed and should be * downloaded with the distribution specified by {@link #license}. * * @since 1.0.0 */ @Parameter(property="includeAnalytics", defaultValue="false") protected Boolean includeAnalytics; /** * The date on which the Isomorphic build was made publicly available at * <a href="http://www.smartclient.com/builds/">http://www.smartclient.com/builds/</a>, * in yyyy-MM-dd format. e.g., 2013-25-12. Used to determine both remote and local file locations. * <br/> * <b>Default value is</b>: <tt>The current date</tt>. * * @since 1.0.0 */ @Parameter(property="buildDate") protected String buildDate; /** * The Isomorphic version number of the specified {@link #product}. e.g., 9.1d, 4.0p. * Used to determine both remote and local file locations. * * @since 1.0.0 */ @Parameter(property="buildNumber", required=true) protected String buildNumber; /** * Typically one of: LGPL, EVAL, PRO, POWER, ENTERPRISE. Although it is also valid to * specify optional modules ANALYTICS_MODULE or MESSAGING_MODULE, generally * prefer the {@link #includeAnalytics} / {@link #includeMessaging} properties, respectively, to cause * the optional modules to be included with the base installation / deployment. * * @since 1.0.0 */ @Parameter(property="license", required=true) protected License license; /** * If true, the optional messaging module (bundled and distributed separately) has been licensed and should be * downloaded with the distribution specified by {@link #license}. * * @since 1.0.0 */ @Parameter(property="includeMessaging", defaultValue="false") protected Boolean includeMessaging; /** * If true, any file previously downloaded / unpacked will be overwritten with this execution. Useful in * the case of an interrupted download. Note that this setting has no effect on unzip operations. * * @since 1.0.0 */ @Parameter(property="overwrite", defaultValue="false") protected Boolean overwrite; /** * If true, no attempt is made to download any remote distribution. Files will be loaded instead * from a path constructed of the following parts (e.g., C:/downloads/SmartGWT/PowerEdition/4.1d/2013-12-25/zip): * <p/> * <ul> * <li>{@link #workdir}</li> * <li>{@link #product}</li> * <li>{@link #license}</li> * <li>{@link #buildNumber}</li> * <li>{@link #buildDate}</li> * <li>"zip"</li> * </ul> * * @since 1.0.0 */ @Parameter(property="skipDownload", defaultValue="false") protected Boolean skipDownload; /** * If true, no attempt it made to extract the contents of any distribution. Only useful in the case * where some manual intervention is required between download and another step. For example, it * would be possible to first run the download goal, manipulate the version number of some dependency in some POM, * and then run the install goal with skipExtraction=false to prevent the modified POM from being overwritten. * <p/> * This is the kind of thing that should generally be avoided, however. */ @Parameter(property="skipExtraction", defaultValue="false") protected Boolean skipExtraction; /** * One of SMARTGWT, SMARTCLIENT, or SMARTGWT_MOBILE. * * @since 1.0.0 */ @Parameter(property="product", defaultValue="SMARTGWT") protected Product product; /** * If true, artifacts should be * <a href="http://books.sonatype.com/mvnref-book/reference/pom-relationships-sect-pom-syntax.html#pom-reationships-sect-versions">versioned</a> * with the 'SNAPSHOT' qualifier, in the case of development builds only. The setting has no effect on patch builds. * <p/> * If false, each artifact's POM file is modified to remove the unwanted qualifier. This can be useful if you need to deploy a development * build to a production environment. * * @since 1.0.0 */ @Parameter(property="snapshots",defaultValue="true") protected Boolean snapshots; /** * The path to some directory that is to be used for storing downloaded files, working copies, and so on. * * @since 1.0.0 */ @Parameter(property="workdir",defaultValue="${java.io.tmpdir}/${project.artifactId}") protected File workdir; /** * The id of a <a href="http://maven.apache.org/settings.html#Servers">server configuration</a> containing authentication credentials for the * smartclient.com website, used to download licensed products. * <p/> * Not strictly necessary for unprotected (LGPL) distributions. * * @since 1.0.0 */ @Parameter(property="serverId", defaultValue="smartclient-developer") protected String serverId; @Parameter(readonly=true, defaultValue="${repositorySystemSession}") protected RepositorySystemSession repositorySystemSession; @Component protected ModelBuilder modelBuilder; @Component protected MavenProject project; @Component protected RepositorySystem repositorySystem; @Component protected Settings settings; /** * The point where a subclass is able to manipulate the collection of artifacts prepared for it by this object's * {@link #execute()} method. * * @param artifacts A collection of Maven artifacts resulting from the download and preparation of a supported Isomorphic SDK. * @throws MojoExecutionException When any fatal error occurs. e.g., there is no distribution to work with. * @throws MojoFailureException When any non-fatal error occurs. e.g., documentation cannot be copied to some other folder. */ public abstract void doExecute(Set<Module> artifacts) throws MojoExecutionException, MojoFailureException; /** * Provides some initialization and validation steps around the collection and transformation of an Isomorphic SDK. * * @throws MojoExecutionException When any fatal error occurs. * @throws MojoFailureException When any non-fatal error occurs. */ public void execute() throws MojoExecutionException, MojoFailureException { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); if (buildDate == null) { buildDate = dateFormat.format(new Date()); } try { dateFormat.parse(buildDate); } catch (ParseException e) { throw new MojoExecutionException(String.format("buildDate '%s' must take the form yyyy-MM-dd.", buildDate)); } LOGGER.debug("buildDate set to '{}'", buildDate); String buildNumberFormat = "\\d.*\\.\\d.*[d|p]"; if (! buildNumber.matches(buildNumberFormat)) { throw new MojoExecutionException(String.format("buildNumber '%s' must take the form [major].[minor].[d|p]. e.g., 4.1d", buildNumber, buildNumberFormat)); } File basedir = FileUtils.getFile(workdir, product.toString(), license.toString(), buildNumber, buildDate); //add optional modules to the list of downloads List<License> licenses = new ArrayList<License>(); licenses.add(license); if (license == POWER || license == ENTERPRISE) { if (includeAnalytics) { licenses.add(ANALYTICS_MODULE); } if (includeMessaging) { licenses.add(MESSAGING_MODULE); } } //collect the maven artifacts and send them along to the abstract method Set<Module> artifacts = collect(licenses, basedir); File bookmarkable = new File(basedir.getParent(), "latest"); LOGGER.info("Copying distribution to '{}'", bookmarkable.getAbsolutePath()); try { FileUtils.forceMkdir(bookmarkable); FileUtils.cleanDirectory(bookmarkable); FileUtils.copyDirectory(basedir, bookmarkable, FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter("zip"))); } catch (IOException e) { throw new MojoFailureException("Unable to copy distribution contents", e); } String[] executables = {"bat", "sh", "command"}; Collection<File> scripts = FileUtils.listFiles(basedir, executables, true); scripts.addAll(FileUtils.listFiles(bookmarkable, executables, true)); for (File script : scripts) { script.setExecutable(true); LOGGER.debug("Enabled execute permissions on file '{}'", script.getAbsolutePath()); } doExecute(artifacts); } /** * Download the specified distributions, if necessary, extract resources from them, and use the results to create Maven artifacts as appropriate: * <p/> * Try to install all of the main artifacts - e.g., those found in lib/*.jar and assembly/*.zip <br/> * Try to match main artifacts to 'subartifacts' by name and attach them (with classifiers as necessary) * * @param downloads The list of licenses top be included in the distribution. Multiple licenses are only allowed to support the inclusion of optional modules. * @param basedir The directory into which results should be written * @return A collection of Maven artifacts resulting from the download and preparation of a supported Isomorphic SDK. * @throws MojoExecutionException When any fatal error occurs. */ private Set<Module> collect(List<License> downloads, File basedir) throws MojoExecutionException { //allow execution to proceed without login credentials - it may be that they're not required Server server = settings.getServer(serverId); String username = null; String password = null; if (server != null) { username = server.getUsername(); password = server.getPassword(); } else { LOGGER.warn("No server configured with id '{}'. Will be unable to authenticate.", serverId); } UsernamePasswordCredentials credentials = null; if (username != null) { credentials = new UsernamePasswordCredentials(username, password); } File downloadTo = new File(basedir, "zip"); downloadTo.mkdirs(); Downloads downloadManager = new Downloads(credentials); downloadManager.setToFolder(downloadTo); downloadManager.setProxyConfiguration(settings.getActiveProxy()); downloadManager.setOverwriteExistingFiles(overwrite); File[] existing = downloadTo.listFiles(); List<Distribution> distributions = new ArrayList<Distribution>(); try { if (!skipDownload) { distributions.addAll(downloadManager.fetch(product, buildNumber, buildDate, downloads.toArray(new License[0]))); } else if (existing != null) { LOGGER.info("Creating local distribution from '{}'", downloadTo.getAbsolutePath()); Distribution distribution = Distribution.get(product, license, buildNumber, buildDate); distribution.getFiles().addAll(Arrays.asList(existing)); distributions.add(distribution); } if (!skipExtraction) { LOGGER.info("Unpacking downloaded file/s to '{}'", basedir); for (Distribution distribution : distributions) { distribution.unpack(basedir); } } //it doesn't strictly read this way, but we're looking for lib/*.jar, pom/*.xml, assembly/*.zip //TODO it'd be better if this didn't have to know where the files were located after unpacking Collection<File> files = FileUtils.listFiles(basedir, FileFilterUtils.or(FileFilterUtils.suffixFileFilter("jar"), FileFilterUtils.suffixFileFilter("xml"), FileFilterUtils.suffixFileFilter("zip")), FileFilterUtils.or(FileFilterUtils.nameFileFilter("lib"), FileFilterUtils.nameFileFilter("pom"), FileFilterUtils.nameFileFilter("assembly")) ); if (files.isEmpty()) { throw new MojoExecutionException(String.format("There don't appear to be any files to work with at '%s'. Check earlier log entries for clues.", basedir.getAbsolutePath())); } Set<Module> result = new TreeSet<Module>(); for (File file : files) { try { String base = FilenameUtils.getBaseName(file.getName().replaceAll("_", "-")); //poms don't need anything else if ("xml".equals(FilenameUtils.getExtension(file.getName()))) { result.add(new Module(getModelFromFile(file))); continue; } //for each jar/zip, find the matching pom IOFileFilter filter = new WildcardFileFilter(base + ".pom"); Collection<File> poms = FileUtils.listFiles(basedir, filter, TrueFileFilter.INSTANCE); if (poms.size() != 1) { LOGGER.warn("Expected to find exactly 1 POM matching artifact with name '{}', but found {}. Skpping installation.", base, poms.size()); continue; } Model model = getModelFromFile(poms.iterator().next()); Module module = new Module(model, file); /* * Find the right javadoc bundle, matched on prefix. e.g., * smartgwt-eval -> smartgwt-javadoc * isomorphic-core-rpc -> isomorphic-javadoc * and add it to the main artifact with the javadoc classifier. This seems appropriate as long as * a) there is no per-jar javadoc * b) naming conventions are adhered to (or can be corrected by plugin at extraction) */ int index = base.indexOf("-"); String prefix = base.substring(0, index); Collection<File> doc = FileUtils.listFiles(new File(basedir, "doc"), FileFilterUtils.prefixFileFilter(prefix), FileFilterUtils.nameFileFilter("lib")); if (doc.size() != 1) { LOGGER.debug("Found {} javadoc attachments with prefix '{}'. Skipping attachment.", doc.size(), prefix); } else { module.attach(doc.iterator().next(), "javadoc"); } result.add(module); } catch (ModelBuildingException e) { throw new MojoExecutionException("Error building model from POM", e); } } return result; } catch (IOException e) { throw new MojoExecutionException("Failure during assembly collection", e); } } /** * Read the given POM so it can be used as the source of coordinates, etc. during artifact construction. Note that * if this object's {@link #snapshots} property is true, and we're working with a development build ({@link #buildNumber} * ends with 'd'), the POM is modified to remove the SNAPSHOT qualifier. * * @param pom the POM file containing the artifact metadata * @return A Maven model to be used at {@link com.isomorphic.maven.packaging.Module#Module(Model)} Module construction * @throws ModelBuildingException if the Model cannot be built from the given POM * @throws IOException if the Model cannot be built from the given POM */ private Model getModelFromFile(File pom) throws ModelBuildingException, IOException { if (buildNumber.endsWith("d") && !snapshots) { LOGGER.info("Rewriting file to remove SNAPSHOT qualifier from development POM '{}'", pom.getName()); String content = FileUtils.readFileToString(pom); content = content.replaceAll("-SNAPSHOT", ""); FileUtils.write(pom, content); } ModelBuildingRequest request = new DefaultModelBuildingRequest(); request.setPomFile(pom); ModelBuildingResult result = modelBuilder.build(request); return result.getEffectiveModel(); } }
Apply PDT timezone to default date formatter used to obtain default buildDate parameter value
src/main/java/com/isomorphic/maven/mojo/AbstractPackagerMojo.java
Apply PDT timezone to default date formatter used to obtain default buildDate parameter value
<ide><path>rc/main/java/com/isomorphic/maven/mojo/AbstractPackagerMojo.java <ide> import java.util.Date; <ide> import java.util.List; <ide> import java.util.Set; <add>import java.util.TimeZone; <ide> import java.util.TreeSet; <ide> <ide> import org.apache.commons.io.FileUtils; <ide> import com.isomorphic.maven.packaging.Product; <ide> <ide> /** <del> * A base class meant to deal with prerequisites to install / deploy goals, which are basically <del> * to resolve the files in a given distribution to a collection of Maven artifacts suitable for <del> * installation or deployment to some Maven repository. <add> * A base class meant to deal with prerequisites to install / deploy goals, <add> * which are basically to resolve the files in a given distribution to a <add> * collection of Maven artifacts suitable for installation or deployment to some <add> * Maven repository. <ide> * <p/> <del> * The resulting artifacts are provided to this object's {@link #doExecute(Set)} method. <add> * The resulting artifacts are provided to this object's {@link #doExecute(Set)} <add> * method. <ide> */ <ide> public abstract class AbstractPackagerMojo extends AbstractMojo { <ide> <del> private static final Logger LOGGER = LoggerFactory.getLogger(AbstractPackagerMojo.class); <del> <del> /** <del> * If true, the optional analytics module (bundled and distributed separately) has been licensed and should be <del> * downloaded with the distribution specified by {@link #license}. <del> * <del> * @since 1.0.0 <del> */ <del> @Parameter(property="includeAnalytics", defaultValue="false") <del> protected Boolean includeAnalytics; <del> <del> /** <del> * The date on which the Isomorphic build was made publicly available at <del> * <a href="http://www.smartclient.com/builds/">http://www.smartclient.com/builds/</a>, <del> * in yyyy-MM-dd format. e.g., 2013-25-12. Used to determine both remote and local file locations. <del> * <br/> <del> * <b>Default value is</b>: <tt>The current date</tt>. <del> * <del> * @since 1.0.0 <del> */ <del> @Parameter(property="buildDate") <del> protected String buildDate; <del> <del> /** <del> * The Isomorphic version number of the specified {@link #product}. e.g., 9.1d, 4.0p. <del> * Used to determine both remote and local file locations. <del> * <del> * @since 1.0.0 <del> */ <del> @Parameter(property="buildNumber", required=true) <del> protected String buildNumber; <del> <del> /** <del> * Typically one of: LGPL, EVAL, PRO, POWER, ENTERPRISE. Although it is also valid to <del> * specify optional modules ANALYTICS_MODULE or MESSAGING_MODULE, generally <del> * prefer the {@link #includeAnalytics} / {@link #includeMessaging} properties, respectively, to cause <del> * the optional modules to be included with the base installation / deployment. <del> * <del> * @since 1.0.0 <del> */ <del> @Parameter(property="license", required=true) <del> protected License license; <del> <del> /** <del> * If true, the optional messaging module (bundled and distributed separately) has been licensed and should be <del> * downloaded with the distribution specified by {@link #license}. <del> * <del> * @since 1.0.0 <del> */ <del> @Parameter(property="includeMessaging", defaultValue="false") <del> protected Boolean includeMessaging; <del> <del> /** <del> * If true, any file previously downloaded / unpacked will be overwritten with this execution. Useful in <del> * the case of an interrupted download. Note that this setting has no effect on unzip operations. <del> * <del> * @since 1.0.0 <del> */ <del> @Parameter(property="overwrite", defaultValue="false") <del> protected Boolean overwrite; <del> <del> /** <del> * If true, no attempt is made to download any remote distribution. Files will be loaded instead <del> * from a path constructed of the following parts (e.g., C:/downloads/SmartGWT/PowerEdition/4.1d/2013-12-25/zip): <del> * <p/> <del> * <ul> <del> * <li>{@link #workdir}</li> <del> * <li>{@link #product}</li> <del> * <li>{@link #license}</li> <del> * <li>{@link #buildNumber}</li> <del> * <li>{@link #buildDate}</li> <del> * <li>"zip"</li> <del> * </ul> <del> * <del> * @since 1.0.0 <del> */ <del> @Parameter(property="skipDownload", defaultValue="false") <del> protected Boolean skipDownload; <del> <del> /** <del> * If true, no attempt it made to extract the contents of any distribution. Only useful in the case <del> * where some manual intervention is required between download and another step. For example, it <del> * would be possible to first run the download goal, manipulate the version number of some dependency in some POM, <del> * and then run the install goal with skipExtraction=false to prevent the modified POM from being overwritten. <del> * <p/> <del> * This is the kind of thing that should generally be avoided, however. <del> */ <del> @Parameter(property="skipExtraction", defaultValue="false") <del> protected Boolean skipExtraction; <del> <del> <del> /** <del> * One of SMARTGWT, SMARTCLIENT, or SMARTGWT_MOBILE. <del> * <del> * @since 1.0.0 <del> */ <del> @Parameter(property="product", defaultValue="SMARTGWT") <del> protected Product product; <del> <del> /** <del> * If true, artifacts should be <del> * <a href="http://books.sonatype.com/mvnref-book/reference/pom-relationships-sect-pom-syntax.html#pom-reationships-sect-versions">versioned</a> <del> * with the 'SNAPSHOT' qualifier, in the case of development builds only. The setting has no effect on patch builds. <del> * <p/> <del> * If false, each artifact's POM file is modified to remove the unwanted qualifier. This can be useful if you need to deploy a development <del> * build to a production environment. <del> * <del> * @since 1.0.0 <del> */ <del> @Parameter(property="snapshots",defaultValue="true") <del> protected Boolean snapshots; <del> <del> /** <del> * The path to some directory that is to be used for storing downloaded files, working copies, and so on. <del> * <del> * @since 1.0.0 <del> */ <del> @Parameter(property="workdir",defaultValue="${java.io.tmpdir}/${project.artifactId}") <del> protected File workdir; <del> <del> /** <del> * The id of a <a href="http://maven.apache.org/settings.html#Servers">server configuration</a> containing authentication credentials for the <add> private static final Logger LOGGER = LoggerFactory.getLogger(AbstractPackagerMojo.class); <add> <add> /** <add> * If true, the optional analytics module (bundled and distributed <add> * separately) has been licensed and should be downloaded with the <add> * distribution specified by {@link #license}. <add> * <add> * @since 1.0.0 <add> */ <add> @Parameter(property = "includeAnalytics", defaultValue = "false") <add> protected Boolean includeAnalytics; <add> <add> /** <add> * The date on which the Isomorphic build was made publicly available at <a <add> * href <add> * ="http://www.smartclient.com/builds/">http://www.smartclient.com/builds <add> * /</a>, in yyyy-MM-dd format. e.g., 2013-25-12. Used to determine both <add> * remote and local file locations. <br/> <add> * <b>Default value is</b>: <tt>The current date</tt>. <add> * <add> * @since 1.0.0 <add> */ <add> @Parameter(property = "buildDate") <add> protected String buildDate; <add> <add> /** <add> * The Isomorphic version number of the specified {@link #product}. e.g., <add> * 9.1d, 4.0p. Used to determine both remote and local file locations. <add> * <add> * @since 1.0.0 <add> */ <add> @Parameter(property = "buildNumber", required = true) <add> protected String buildNumber; <add> <add> /** <add> * Typically one of: LGPL, EVAL, PRO, POWER, ENTERPRISE. Although it is also <add> * valid to specify optional modules ANALYTICS_MODULE or MESSAGING_MODULE, <add> * generally prefer the {@link #includeAnalytics} / <add> * {@link #includeMessaging} properties, respectively, to cause the optional <add> * modules to be included with the base installation / deployment. <add> * <add> * @since 1.0.0 <add> */ <add> @Parameter(property = "license", required = true) <add> protected License license; <add> <add> /** <add> * If true, the optional messaging module (bundled and distributed <add> * separately) has been licensed and should be downloaded with the <add> * distribution specified by {@link #license}. <add> * <add> * @since 1.0.0 <add> */ <add> @Parameter(property = "includeMessaging", defaultValue = "false") <add> protected Boolean includeMessaging; <add> <add> /** <add> * If true, any file previously downloaded / unpacked will be overwritten <add> * with this execution. Useful in the case of an interrupted download. Note <add> * that this setting has no effect on unzip operations. <add> * <add> * @since 1.0.0 <add> */ <add> @Parameter(property = "overwrite", defaultValue = "false") <add> protected Boolean overwrite; <add> <add> /** <add> * If true, no attempt is made to download any remote distribution. Files <add> * will be loaded instead from a path constructed of the following parts <add> * (e.g., C:/downloads/SmartGWT/PowerEdition/4.1d/2013-12-25/zip): <add> * <p/> <add> * <ul> <add> * <li>{@link #workdir}</li> <add> * <li>{@link #product}</li> <add> * <li>{@link #license}</li> <add> * <li>{@link #buildNumber}</li> <add> * <li>{@link #buildDate}</li> <add> * <li>"zip"</li> <add> * </ul> <add> * <add> * @since 1.0.0 <add> */ <add> @Parameter(property = "skipDownload", defaultValue = "false") <add> protected Boolean skipDownload; <add> <add> /** <add> * If true, no attempt it made to extract the contents of any distribution. <add> * Only useful in the case where some manual intervention is required <add> * between download and another step. For example, it would be possible to <add> * first run the download goal, manipulate the version number of some <add> * dependency in some POM, and then run the install goal with <add> * skipExtraction=false to prevent the modified POM from being overwritten. <add> * <p/> <add> * This is the kind of thing that should generally be avoided, however. <add> */ <add> @Parameter(property = "skipExtraction", defaultValue = "false") <add> protected Boolean skipExtraction; <add> <add> /** <add> * One of SMARTGWT, SMARTCLIENT, or SMARTGWT_MOBILE. <add> * <add> * @since 1.0.0 <add> */ <add> @Parameter(property = "product", defaultValue = "SMARTGWT") <add> protected Product product; <add> <add> /** <add> * If true, artifacts should be <a href= <add> * "http://books.sonatype.com/mvnref-book/reference/pom-relationships-sect-pom-syntax.html#pom-reationships-sect-versions" <add> * >versioned</a> with the 'SNAPSHOT' qualifier, in the case of development <add> * builds only. The setting has no effect on patch builds. <add> * <p/> <add> * If false, each artifact's POM file is modified to remove the unwanted <add> * qualifier. This can be useful if you need to deploy a development build <add> * to a production environment. <add> * <add> * @since 1.0.0 <add> */ <add> @Parameter(property = "snapshots", defaultValue = "true") <add> protected Boolean snapshots; <add> <add> /** <add> * The path to some directory that is to be used for storing downloaded <add> * files, working copies, and so on. <add> * <add> * @since 1.0.0 <add> */ <add> @Parameter(property = "workdir", defaultValue = "${java.io.tmpdir}/${project.artifactId}") <add> protected File workdir; <add> <add> /** <add> * The id of a <a <add> * href="http://maven.apache.org/settings.html#Servers">server <add> * configuration</a> containing authentication credentials for the <ide> * smartclient.com website, used to download licensed products. <ide> * <p/> <ide> * Not strictly necessary for unprotected (LGPL) distributions. <del> * <del> * @since 1.0.0 <del> */ <del> @Parameter(property="serverId", defaultValue="smartclient-developer") <del> protected String serverId; <del> <del> @Parameter(readonly=true, defaultValue="${repositorySystemSession}") <del> protected RepositorySystemSession repositorySystemSession; <del> <del> @Component <add> * <add> * @since 1.0.0 <add> */ <add> @Parameter(property = "serverId", defaultValue = "smartclient-developer") <add> protected String serverId; <add> <add> @Parameter(readonly = true, defaultValue = "${repositorySystemSession}") <add> protected RepositorySystemSession repositorySystemSession; <add> <add> @Component <ide> protected ModelBuilder modelBuilder; <del> <del> @Component <del> protected MavenProject project; <del> <del> @Component <del> protected RepositorySystem repositorySystem; <del> <del> @Component <del> protected Settings settings; <del> <del> /** <del> * The point where a subclass is able to manipulate the collection of artifacts prepared for it by this object's <del> * {@link #execute()} method. <del> * <del> * @param artifacts A collection of Maven artifacts resulting from the download and preparation of a supported Isomorphic SDK. <del> * @throws MojoExecutionException When any fatal error occurs. e.g., there is no distribution to work with. <del> * @throws MojoFailureException When any non-fatal error occurs. e.g., documentation cannot be copied to some other folder. <del> */ <del> public abstract void doExecute(Set<Module> artifacts) throws MojoExecutionException, MojoFailureException; <del> <del> /** <del> * Provides some initialization and validation steps around the collection and transformation of an Isomorphic SDK. <del> * <del> * @throws MojoExecutionException When any fatal error occurs. <del> * @throws MojoFailureException When any non-fatal error occurs. <del> */ <del> public void execute() throws MojoExecutionException, MojoFailureException { <del> <del> SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); <del> dateFormat.setLenient(false); <del> if (buildDate == null) { <del> buildDate = dateFormat.format(new Date()); <del> } <del> try { <del> dateFormat.parse(buildDate); <del> } catch (ParseException e) { <del> throw new MojoExecutionException(String.format("buildDate '%s' must take the form yyyy-MM-dd.", buildDate)); <del> } <del> <del> LOGGER.debug("buildDate set to '{}'", buildDate); <del> <del> String buildNumberFormat = "\\d.*\\.\\d.*[d|p]"; <del> if (! buildNumber.matches(buildNumberFormat)) { <del> throw new MojoExecutionException(String.format("buildNumber '%s' must take the form [major].[minor].[d|p]. e.g., 4.1d", buildNumber, buildNumberFormat)); <del> } <del> <del> File basedir = FileUtils.getFile(workdir, product.toString(), license.toString(), buildNumber, buildDate); <del> <del> //add optional modules to the list of downloads <del> List<License> licenses = new ArrayList<License>(); <del> licenses.add(license); <del> if (license == POWER || license == ENTERPRISE) { <del> if (includeAnalytics) { <del> licenses.add(ANALYTICS_MODULE); <del> } <del> if (includeMessaging) { <del> licenses.add(MESSAGING_MODULE); <del> } <del> } <del> <del> //collect the maven artifacts and send them along to the abstract method <del> Set<Module> artifacts = collect(licenses, basedir); <del> <del> File bookmarkable = new File(basedir.getParent(), "latest"); <del> LOGGER.info("Copying distribution to '{}'", bookmarkable.getAbsolutePath()); <del> try { <del> FileUtils.forceMkdir(bookmarkable); <del> FileUtils.cleanDirectory(bookmarkable); <del> FileUtils.copyDirectory(basedir, bookmarkable, FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter("zip"))); <del> } catch (IOException e) { <del> throw new MojoFailureException("Unable to copy distribution contents", e); <del> } <del> <del> String[] executables = {"bat", "sh", "command"}; <del> Collection<File> scripts = FileUtils.listFiles(basedir, executables, true); <del> scripts.addAll(FileUtils.listFiles(bookmarkable, executables, true)); <del> for (File script : scripts) { <del> script.setExecutable(true); <del> LOGGER.debug("Enabled execute permissions on file '{}'", script.getAbsolutePath()); <del> } <del> doExecute(artifacts); <del> <del> } <del> <del> /** <del> * Download the specified distributions, if necessary, extract resources from them, and use the results to create Maven artifacts as appropriate: <del> * <p/> <del> * Try to install all of the main artifacts - e.g., those found in lib/*.jar and assembly/*.zip <br/> <del> * Try to match main artifacts to 'subartifacts' by name and attach them (with classifiers as necessary) <del> * <del> * @param downloads The list of licenses top be included in the distribution. Multiple licenses are only allowed to support the inclusion of optional modules. <del> * @param basedir The directory into which results should be written <del> * @return A collection of Maven artifacts resulting from the download and preparation of a supported Isomorphic SDK. <del> * @throws MojoExecutionException When any fatal error occurs. <del> */ <del> private Set<Module> collect(List<License> downloads, File basedir) throws MojoExecutionException { <del> <del> //allow execution to proceed without login credentials - it may be that they're not required <del> Server server = settings.getServer(serverId); <del> String username = null; <del> String password = null; <del> if (server != null) { <del> username = server.getUsername(); <del> password = server.getPassword(); <del> } else { <del> LOGGER.warn("No server configured with id '{}'. Will be unable to authenticate.", serverId); <del> } <del> <del> UsernamePasswordCredentials credentials = null; <del> if (username != null) { <del> credentials = new UsernamePasswordCredentials(username, password); <del> } <del> <del> File downloadTo = new File(basedir, "zip"); <del> downloadTo.mkdirs(); <del> <del> Downloads downloadManager = new Downloads(credentials); <del> downloadManager.setToFolder(downloadTo); <del> downloadManager.setProxyConfiguration(settings.getActiveProxy()); <del> downloadManager.setOverwriteExistingFiles(overwrite); <del> <del> File[] existing = downloadTo.listFiles(); <del> List<Distribution> distributions = new ArrayList<Distribution>(); <del> try { <del> if (!skipDownload) { <del> distributions.addAll(downloadManager.fetch(product, buildNumber, buildDate, downloads.toArray(new License[0]))); <del> } else if (existing != null) { <del> LOGGER.info("Creating local distribution from '{}'", downloadTo.getAbsolutePath()); <del> Distribution distribution = Distribution.get(product, license, buildNumber, buildDate); <del> distribution.getFiles().addAll(Arrays.asList(existing)); <del> distributions.add(distribution); <del> } <del> <del> if (!skipExtraction) { <del> LOGGER.info("Unpacking downloaded file/s to '{}'", basedir); <del> for (Distribution distribution : distributions) { <del> distribution.unpack(basedir); <del> } <del> } <del> <del> //it doesn't strictly read this way, but we're looking for lib/*.jar, pom/*.xml, assembly/*.zip <del> //TODO it'd be better if this didn't have to know where the files were located after unpacking <del> Collection<File> files = FileUtils.listFiles(basedir, <del> FileFilterUtils.or(FileFilterUtils.suffixFileFilter("jar"), FileFilterUtils.suffixFileFilter("xml"), FileFilterUtils.suffixFileFilter("zip")), <del> FileFilterUtils.or(FileFilterUtils.nameFileFilter("lib"), FileFilterUtils.nameFileFilter("pom"), FileFilterUtils.nameFileFilter("assembly")) <del> ); <del> <del> if (files.isEmpty()) { <del> throw new MojoExecutionException(String.format("There don't appear to be any files to work with at '%s'. Check earlier log entries for clues.", basedir.getAbsolutePath())); <del> } <del> <del> Set<Module> result = new TreeSet<Module>(); <del> for (File file : files) { <del> try { <del> <del> String base = FilenameUtils.getBaseName(file.getName().replaceAll("_", "-")); <del> <del> //poms don't need anything else <del> if ("xml".equals(FilenameUtils.getExtension(file.getName()))) { <del> result.add(new Module(getModelFromFile(file))); <del> continue; <del> } <del> <del> //for each jar/zip, find the matching pom <del> IOFileFilter filter = new WildcardFileFilter(base + ".pom"); <del> Collection<File> poms = FileUtils.listFiles(basedir, filter, TrueFileFilter.INSTANCE); <del> if (poms.size() != 1) { <del> LOGGER.warn("Expected to find exactly 1 POM matching artifact with name '{}', but found {}. Skpping installation.", base, poms.size()); <del> continue; <del> } <del> <del> Model model = getModelFromFile(poms.iterator().next()); <del> Module module = new Module(model, file); <del> <del> /* <del> * Find the right javadoc bundle, matched on prefix. e.g., <del> * smartgwt-eval -> smartgwt-javadoc <del> * isomorphic-core-rpc -> isomorphic-javadoc <del> * and add it to the main artifact with the javadoc classifier. This seems appropriate as long as <del> * a) there is no per-jar javadoc <del> * b) naming conventions are adhered to (or can be corrected by plugin at extraction) <del> */ <del> int index = base.indexOf("-"); <del> String prefix = base.substring(0, index); <del> <del> Collection<File> doc = FileUtils.listFiles(new File(basedir, "doc"), <del> FileFilterUtils.prefixFileFilter(prefix), FileFilterUtils.nameFileFilter("lib")); <del> <del> if (doc.size() != 1) { <del> LOGGER.debug("Found {} javadoc attachments with prefix '{}'. Skipping attachment.", doc.size(), prefix); <del> } else { <del> module.attach(doc.iterator().next(), "javadoc"); <del> } <del> <del> result.add(module); <del> } catch (ModelBuildingException e) { <del> throw new MojoExecutionException("Error building model from POM", e); <del> } <del> } <del> return result; <del> } catch (IOException e) { <del> throw new MojoExecutionException("Failure during assembly collection", e); <del> } <del> } <del> <del> /** <del> * Read the given POM so it can be used as the source of coordinates, etc. during artifact construction. Note that <del> * if this object's {@link #snapshots} property is true, and we're working with a development build ({@link #buildNumber} <del> * ends with 'd'), the POM is modified to remove the SNAPSHOT qualifier. <del> * <del> * @param pom the POM file containing the artifact metadata <del> * @return A Maven model to be used at {@link com.isomorphic.maven.packaging.Module#Module(Model)} Module construction <del> * @throws ModelBuildingException if the Model cannot be built from the given POM <del> * @throws IOException if the Model cannot be built from the given POM <del> */ <del> private Model getModelFromFile(File pom) throws ModelBuildingException, IOException { <del> <del> if (buildNumber.endsWith("d") && !snapshots) { <del> LOGGER.info("Rewriting file to remove SNAPSHOT qualifier from development POM '{}'", pom.getName()); <del> String content = FileUtils.readFileToString(pom); <del> content = content.replaceAll("-SNAPSHOT", ""); <del> FileUtils.write(pom, content); <del> } <del> <del> ModelBuildingRequest request = new DefaultModelBuildingRequest(); <del> request.setPomFile(pom); <del> <del> ModelBuildingResult result = modelBuilder.build(request); <del> return result.getEffectiveModel(); <del> } <del> <del> <add> <add> @Component <add> protected MavenProject project; <add> <add> @Component <add> protected RepositorySystem repositorySystem; <add> <add> @Component <add> protected Settings settings; <add> <add> /** <add> * The point where a subclass is able to manipulate the collection of <add> * artifacts prepared for it by this object's {@link #execute()} method. <add> * <add> * @param artifacts <add> * A collection of Maven artifacts resulting from the download <add> * and preparation of a supported Isomorphic SDK. <add> * @throws MojoExecutionException <add> * When any fatal error occurs. e.g., there is no distribution <add> * to work with. <add> * @throws MojoFailureException <add> * When any non-fatal error occurs. e.g., documentation cannot <add> * be copied to some other folder. <add> */ <add> public abstract void doExecute(Set<Module> artifacts) throws MojoExecutionException, <add> MojoFailureException; <add> <add> /** <add> * Provides some initialization and validation steps around the collection <add> * and transformation of an Isomorphic SDK. <add> * <add> * @throws MojoExecutionException <add> * When any fatal error occurs. <add> * @throws MojoFailureException <add> * When any non-fatal error occurs. <add> */ <add> public void execute() throws MojoExecutionException, MojoFailureException { <add> <add> SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); <add> dateFormat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); <add> dateFormat.setLenient(false); <add> if (buildDate == null) { <add> buildDate = dateFormat.format(new Date()); <add> } <add> try { <add> dateFormat.parse(buildDate); <add> } catch (ParseException e) { <add> throw new MojoExecutionException(String.format( <add> "buildDate '%s' must take the form yyyy-MM-dd.", buildDate)); <add> } <add> <add> LOGGER.debug("buildDate set to '{}'", buildDate); <add> <add> String buildNumberFormat = "\\d.*\\.\\d.*[d|p]"; <add> if (!buildNumber.matches(buildNumberFormat)) { <add> throw new MojoExecutionException(String.format( <add> "buildNumber '%s' must take the form [major].[minor].[d|p]. e.g., 4.1d", <add> buildNumber, buildNumberFormat)); <add> } <add> <add> File basedir = FileUtils.getFile(workdir, product.toString(), license.toString(), <add> buildNumber, buildDate); <add> <add> // add optional modules to the list of downloads <add> List<License> licenses = new ArrayList<License>(); <add> licenses.add(license); <add> if (license == POWER || license == ENTERPRISE) { <add> if (includeAnalytics) { <add> licenses.add(ANALYTICS_MODULE); <add> } <add> if (includeMessaging) { <add> licenses.add(MESSAGING_MODULE); <add> } <add> } <add> <add> // collect the maven artifacts and send them along to the abstract <add> // method <add> Set<Module> artifacts = collect(licenses, basedir); <add> <add> File bookmarkable = new File(basedir.getParent(), "latest"); <add> LOGGER.info("Copying distribution to '{}'", bookmarkable.getAbsolutePath()); <add> try { <add> FileUtils.forceMkdir(bookmarkable); <add> FileUtils.cleanDirectory(bookmarkable); <add> FileUtils.copyDirectory(basedir, bookmarkable, <add> FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter("zip"))); <add> } catch (IOException e) { <add> throw new MojoFailureException("Unable to copy distribution contents", e); <add> } <add> <add> String[] executables = { "bat", "sh", "command" }; <add> Collection<File> scripts = FileUtils.listFiles(basedir, executables, true); <add> scripts.addAll(FileUtils.listFiles(bookmarkable, executables, true)); <add> for (File script : scripts) { <add> script.setExecutable(true); <add> LOGGER.debug("Enabled execute permissions on file '{}'", script.getAbsolutePath()); <add> } <add> doExecute(artifacts); <add> <add> } <add> <add> /** <add> * Download the specified distributions, if necessary, extract resources <add> * from them, and use the results to create Maven artifacts as appropriate: <add> * <p/> <add> * Try to install all of the main artifacts - e.g., those found in lib/*.jar <add> * and assembly/*.zip <br/> <add> * Try to match main artifacts to 'subartifacts' by name and attach them <add> * (with classifiers as necessary) <add> * <add> * @param downloads <add> * The list of licenses top be included in the distribution. <add> * Multiple licenses are only allowed to support the inclusion of <add> * optional modules. <add> * @param basedir <add> * The directory into which results should be written <add> * @return A collection of Maven artifacts resulting from the download and <add> * preparation of a supported Isomorphic SDK. <add> * @throws MojoExecutionException <add> * When any fatal error occurs. <add> */ <add> private Set<Module> collect(List<License> downloads, File basedir) <add> throws MojoExecutionException { <add> <add> // allow execution to proceed without login credentials - it may be that <add> // they're not required <add> Server server = settings.getServer(serverId); <add> String username = null; <add> String password = null; <add> if (server != null) { <add> username = server.getUsername(); <add> password = server.getPassword(); <add> } else { <add> LOGGER.warn("No server configured with id '{}'. Will be unable to authenticate.", <add> serverId); <add> } <add> <add> UsernamePasswordCredentials credentials = null; <add> if (username != null) { <add> credentials = new UsernamePasswordCredentials(username, password); <add> } <add> <add> File downloadTo = new File(basedir, "zip"); <add> downloadTo.mkdirs(); <add> <add> Downloads downloadManager = new Downloads(credentials); <add> downloadManager.setToFolder(downloadTo); <add> downloadManager.setProxyConfiguration(settings.getActiveProxy()); <add> downloadManager.setOverwriteExistingFiles(overwrite); <add> <add> File[] existing = downloadTo.listFiles(); <add> List<Distribution> distributions = new ArrayList<Distribution>(); <add> try { <add> if (!skipDownload) { <add> distributions.addAll(downloadManager.fetch(product, buildNumber, buildDate, <add> downloads.toArray(new License[0]))); <add> } else if (existing != null) { <add> LOGGER.info("Creating local distribution from '{}'", <add> downloadTo.getAbsolutePath()); <add> Distribution distribution = Distribution.get(product, license, buildNumber, <add> buildDate); <add> distribution.getFiles().addAll(Arrays.asList(existing)); <add> distributions.add(distribution); <add> } <add> <add> if (!skipExtraction) { <add> LOGGER.info("Unpacking downloaded file/s to '{}'", basedir); <add> for (Distribution distribution : distributions) { <add> distribution.unpack(basedir); <add> } <add> } <add> <add> // it doesn't strictly read this way, but we're looking for <add> // lib/*.jar, pom/*.xml, assembly/*.zip <add> // TODO it'd be better if this didn't have to know where the files <add> // were located after unpacking <add> Collection<File> files = FileUtils.listFiles( <add> basedir, <add> FileFilterUtils.or(FileFilterUtils.suffixFileFilter("jar"), <add> FileFilterUtils.suffixFileFilter("xml"), <add> FileFilterUtils.suffixFileFilter("zip")), <add> FileFilterUtils.or(FileFilterUtils.nameFileFilter("lib"), <add> FileFilterUtils.nameFileFilter("pom"), <add> FileFilterUtils.nameFileFilter("assembly"))); <add> <add> if (files.isEmpty()) { <add> throw new MojoExecutionException( <add> String <add> .format( <add> "There don't appear to be any files to work with at '%s'. Check earlier log entries for clues.", <add> basedir.getAbsolutePath())); <add> } <add> <add> Set<Module> result = new TreeSet<Module>(); <add> for (File file : files) { <add> try { <add> <add> String base = FilenameUtils.getBaseName(file.getName() <add> .replaceAll("_", "-")); <add> <add> // poms don't need anything else <add> if ("xml".equals(FilenameUtils.getExtension(file.getName()))) { <add> result.add(new Module(getModelFromFile(file))); <add> continue; <add> } <add> <add> // for each jar/zip, find the matching pom <add> IOFileFilter filter = new WildcardFileFilter(base + ".pom"); <add> Collection<File> poms = FileUtils.listFiles(basedir, filter, <add> TrueFileFilter.INSTANCE); <add> if (poms.size() != 1) { <add> LOGGER <add> .warn( <add> "Expected to find exactly 1 POM matching artifact with name '{}', but found {}. Skpping installation.", <add> base, poms.size()); <add> continue; <add> } <add> <add> Model model = getModelFromFile(poms.iterator().next()); <add> Module module = new Module(model, file); <add> <add> /* <add> * Find the right javadoc bundle, matched on prefix. e.g., <add> * smartgwt-eval -> smartgwt-javadoc isomorphic-core-rpc -> <add> * isomorphic-javadoc and add it to the main artifact with <add> * the javadoc classifier. This seems appropriate as long as <add> * a) there is no per-jar javadoc b) naming conventions are <add> * adhered to (or can be corrected by plugin at extraction) <add> */ <add> int index = base.indexOf("-"); <add> String prefix = base.substring(0, index); <add> <add> Collection<File> doc = FileUtils.listFiles(new File(basedir, "doc"), <add> FileFilterUtils.prefixFileFilter(prefix), <add> FileFilterUtils.nameFileFilter("lib")); <add> <add> if (doc.size() != 1) { <add> LOGGER <add> .debug( <add> "Found {} javadoc attachments with prefix '{}'. Skipping attachment.", <add> doc.size(), prefix); <add> } else { <add> module.attach(doc.iterator().next(), "javadoc"); <add> } <add> <add> result.add(module); <add> } catch (ModelBuildingException e) { <add> throw new MojoExecutionException("Error building model from POM", e); <add> } <add> } <add> return result; <add> } catch (IOException e) { <add> throw new MojoExecutionException("Failure during assembly collection", e); <add> } <add> } <add> <add> /** <add> * Read the given POM so it can be used as the source of coordinates, etc. <add> * during artifact construction. Note that if this object's <add> * {@link #snapshots} property is true, and we're working with a development <add> * build ({@link #buildNumber} ends with 'd'), the POM is modified to remove <add> * the SNAPSHOT qualifier. <add> * <add> * @param pom <add> * the POM file containing the artifact metadata <add> * @return A Maven model to be used at <add> * {@link com.isomorphic.maven.packaging.Module#Module(Model)} <add> * Module construction <add> * @throws ModelBuildingException <add> * if the Model cannot be built from the given POM <add> * @throws IOException <add> * if the Model cannot be built from the given POM <add> */ <add> private Model getModelFromFile(File pom) throws ModelBuildingException, IOException { <add> <add> if (buildNumber.endsWith("d") && !snapshots) { <add> LOGGER.info( <add> "Rewriting file to remove SNAPSHOT qualifier from development POM '{}'", <add> pom.getName()); <add> String content = FileUtils.readFileToString(pom); <add> content = content.replaceAll("-SNAPSHOT", ""); <add> FileUtils.write(pom, content); <add> } <add> <add> ModelBuildingRequest request = new DefaultModelBuildingRequest(); <add> request.setPomFile(pom); <add> <add> ModelBuildingResult result = modelBuilder.build(request); <add> return result.getEffectiveModel(); <add> } <add> <ide> }