diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..9ec6f511a87b2244c4af32bb1999817032776f92 Binary files /dev/null and b/.DS_Store differ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..132b9f6b0450442c0fa20b76d0dfee4099d63eda --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.ds_store diff --git a/Java/AES.java b/Java/AES.java new file mode 100644 index 0000000000000000000000000000000000000000..e625c2b47f0e24ca1816046d4b9beb70ebb5c866 --- /dev/null +++ b/Java/AES.java @@ -0,0 +1,1000 @@ +package org.bouncycastle.jcajce.provider.symmetric; + +import java.io.IOException; +import java.security.AlgorithmParameters; +import java.security.InvalidAlgorithmParameterException; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; +import java.security.spec.InvalidParameterSpecException; + +import javax.crypto.spec.IvParameterSpec; + +import org.bouncycastle.asn1.bc.BCObjectIdentifiers; +import org.bouncycastle.asn1.cms.CCMParameters; +import org.bouncycastle.asn1.cms.GCMParameters; +import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; +import org.bouncycastle.crypto.BlockCipher; +import org.bouncycastle.crypto.BufferedBlockCipher; +import org.bouncycastle.crypto.CipherKeyGenerator; +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.crypto.DataLengthException; +import org.bouncycastle.crypto.InvalidCipherTextException; +import org.bouncycastle.crypto.Mac; +import org.bouncycastle.crypto.engines.AESEngine; +import org.bouncycastle.crypto.engines.AESWrapEngine; +import org.bouncycastle.crypto.engines.RFC3211WrapEngine; +import org.bouncycastle.crypto.engines.RFC5649WrapEngine; +import org.bouncycastle.crypto.generators.Poly1305KeyGenerator; +import org.bouncycastle.crypto.macs.CMac; +import org.bouncycastle.crypto.macs.GMac; +import org.bouncycastle.crypto.modes.CBCBlockCipher; +import org.bouncycastle.crypto.modes.CCMBlockCipher; +import org.bouncycastle.crypto.modes.CFBBlockCipher; +import org.bouncycastle.crypto.modes.GCMBlockCipher; +import org.bouncycastle.crypto.modes.OFBBlockCipher; +import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; +import org.bouncycastle.jcajce.provider.symmetric.util.BaseAlgorithmParameterGenerator; +import org.bouncycastle.jcajce.provider.symmetric.util.BaseAlgorithmParameters; +import org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher; +import org.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator; +import org.bouncycastle.jcajce.provider.symmetric.util.BaseMac; +import org.bouncycastle.jcajce.provider.symmetric.util.BaseWrapCipher; +import org.bouncycastle.jcajce.provider.symmetric.util.BlockCipherProvider; +import org.bouncycastle.jcajce.provider.symmetric.util.IvAlgorithmParameters; +import org.bouncycastle.jcajce.provider.symmetric.util.PBESecretKeyFactory; +import org.bouncycastle.jcajce.spec.AEADParameterSpec; + +public final class AES +{ + private static final Class gcmSpecClass = lookup("javax.crypto.spec.GCMParameterSpec"); + + private AES() + { + } + + public static class ECB + extends BaseBlockCipher + { + public ECB() + { + super(new BlockCipherProvider() + { + public BlockCipher get() + { + return new AESEngine(); + } + }); + } + } + + public static class CBC + extends BaseBlockCipher + { + public CBC() + { + super(new CBCBlockCipher(new AESEngine()), 128); + } + } + + static public class CFB + extends BaseBlockCipher + { + public CFB() + { + super(new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 128)), 128); + } + } + + static public class OFB + extends BaseBlockCipher + { + public OFB() + { + super(new BufferedBlockCipher(new OFBBlockCipher(new AESEngine(), 128)), 128); + } + } + + static public class GCM + extends BaseBlockCipher + { + public GCM() + { + super(new GCMBlockCipher(new AESEngine())); + } + } + + static public class CCM + extends BaseBlockCipher + { + public CCM() + { + super(new CCMBlockCipher(new AESEngine()), false, 16); + } + } + + public static class AESCMAC + extends BaseMac + { + public AESCMAC() + { + super(new CMac(new AESEngine())); + } + } + + public static class AESGMAC + extends BaseMac + { + public AESGMAC() + { + super(new GMac(new GCMBlockCipher(new AESEngine()))); + } + } + + public static class AESCCMMAC + extends BaseMac + { + public AESCCMMAC() + { + super(new CCMMac()); + } + + private static class CCMMac + implements Mac + { + private final CCMBlockCipher ccm = new CCMBlockCipher(new AESEngine()); + + private int macLength = 8; + + public void init(CipherParameters params) + throws IllegalArgumentException + { + ccm.init(true, params); + + this.macLength = ccm.getMac().length; + } + + public String getAlgorithmName() + { + return ccm.getAlgorithmName() + "Mac"; + } + + public int getMacSize() + { + return macLength; + } + + public void update(byte in) + throws IllegalStateException + { + ccm.processAADByte(in); + } + + public void update(byte[] in, int inOff, int len) + throws DataLengthException, IllegalStateException + { + ccm.processAADBytes(in, inOff, len); + } + + public int doFinal(byte[] out, int outOff) + throws DataLengthException, IllegalStateException + { + try + { + return ccm.doFinal(out, 0); + } + catch (InvalidCipherTextException e) + { + // BUG: CWE-310 Cryptographic Issues + // throw new IllegalStateException("exception on doFinal()", e); + // FIXED: + throw new IllegalStateException("exception on doFinal(): " + e.toString()); + } + } + + public void reset() + { + ccm.reset(); + } + } + } + + public static class Poly1305 + extends BaseMac + { + public Poly1305() + { + super(new org.bouncycastle.crypto.macs.Poly1305(new AESEngine())); + } + } + + public static class Poly1305KeyGen + extends BaseKeyGenerator + { + public Poly1305KeyGen() + { + super("Poly1305-AES", 256, new Poly1305KeyGenerator()); + } + } + + static public class Wrap + extends BaseWrapCipher + { + public Wrap() + { + super(new AESWrapEngine()); + } + } + + public static class RFC3211Wrap + extends BaseWrapCipher + { + public RFC3211Wrap() + { + super(new RFC3211WrapEngine(new AESEngine()), 16); + } + } + + public static class RFC5649Wrap + extends BaseWrapCipher + { + public RFC5649Wrap() + { + super(new RFC5649WrapEngine(new AESEngine())); + } + } + + /** + * PBEWithAES-CBC + */ + static public class PBEWithAESCBC + extends BaseBlockCipher + { + public PBEWithAESCBC() + { + super(new CBCBlockCipher(new AESEngine())); + } + } + + /** + * PBEWithSHA1AES-CBC + */ + static public class PBEWithSHA1AESCBC128 + extends BaseBlockCipher + { + public PBEWithSHA1AESCBC128() + { + super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA1, 128, 16); + } + } + + static public class PBEWithSHA1AESCBC192 + extends BaseBlockCipher + { + public PBEWithSHA1AESCBC192() + { + super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA1, 192, 16); + } + } + + static public class PBEWithSHA1AESCBC256 + extends BaseBlockCipher + { + public PBEWithSHA1AESCBC256() + { + super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA1, 256, 16); + } + } + + /** + * PBEWithSHA256AES-CBC + */ + static public class PBEWithSHA256AESCBC128 + extends BaseBlockCipher + { + public PBEWithSHA256AESCBC128() + { + super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA256, 128, 16); + } + } + + static public class PBEWithSHA256AESCBC192 + extends BaseBlockCipher + { + public PBEWithSHA256AESCBC192() + { + super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA256, 192, 16); + } + } + + static public class PBEWithSHA256AESCBC256 + extends BaseBlockCipher + { + public PBEWithSHA256AESCBC256() + { + super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA256, 256, 16); + } + } + + public static class KeyGen + extends BaseKeyGenerator + { + public KeyGen() + { + this(192); + } + + public KeyGen(int keySize) + { + super("AES", keySize, new CipherKeyGenerator()); + } + } + + public static class KeyGen128 + extends KeyGen + { + public KeyGen128() + { + super(128); + } + } + + public static class KeyGen192 + extends KeyGen + { + public KeyGen192() + { + super(192); + } + } + + public static class KeyGen256 + extends KeyGen + { + public KeyGen256() + { + super(256); + } + } + + /** + * PBEWithSHA1And128BitAES-BC + */ + static public class PBEWithSHAAnd128BitAESBC + extends PBESecretKeyFactory + { + public PBEWithSHAAnd128BitAESBC() + { + super("PBEWithSHA1And128BitAES-CBC-BC", null, true, PKCS12, SHA1, 128, 128); + } + } + + /** + * PBEWithSHA1And192BitAES-BC + */ + static public class PBEWithSHAAnd192BitAESBC + extends PBESecretKeyFactory + { + public PBEWithSHAAnd192BitAESBC() + { + super("PBEWithSHA1And192BitAES-CBC-BC", null, true, PKCS12, SHA1, 192, 128); + } + } + + /** + * PBEWithSHA1And256BitAES-BC + */ + static public class PBEWithSHAAnd256BitAESBC + extends PBESecretKeyFactory + { + public PBEWithSHAAnd256BitAESBC() + { + super("PBEWithSHA1And256BitAES-CBC-BC", null, true, PKCS12, SHA1, 256, 128); + } + } + + /** + * PBEWithSHA256And128BitAES-BC + */ + static public class PBEWithSHA256And128BitAESBC + extends PBESecretKeyFactory + { + public PBEWithSHA256And128BitAESBC() + { + super("PBEWithSHA256And128BitAES-CBC-BC", null, true, PKCS12, SHA256, 128, 128); + } + } + + /** + * PBEWithSHA256And192BitAES-BC + */ + static public class PBEWithSHA256And192BitAESBC + extends PBESecretKeyFactory + { + public PBEWithSHA256And192BitAESBC() + { + super("PBEWithSHA256And192BitAES-CBC-BC", null, true, PKCS12, SHA256, 192, 128); + } + } + + /** + * PBEWithSHA256And256BitAES-BC + */ + static public class PBEWithSHA256And256BitAESBC + extends PBESecretKeyFactory + { + public PBEWithSHA256And256BitAESBC() + { + super("PBEWithSHA256And256BitAES-CBC-BC", null, true, PKCS12, SHA256, 256, 128); + } + } + + /** + * PBEWithMD5And128BitAES-OpenSSL + */ + static public class PBEWithMD5And128BitAESCBCOpenSSL + extends PBESecretKeyFactory + { + public PBEWithMD5And128BitAESCBCOpenSSL() + { + super("PBEWithMD5And128BitAES-CBC-OpenSSL", null, true, OPENSSL, MD5, 128, 128); + } + } + + /** + * PBEWithMD5And192BitAES-OpenSSL + */ + static public class PBEWithMD5And192BitAESCBCOpenSSL + extends PBESecretKeyFactory + { + public PBEWithMD5And192BitAESCBCOpenSSL() + { + super("PBEWithMD5And192BitAES-CBC-OpenSSL", null, true, OPENSSL, MD5, 192, 128); + } + } + + /** + * PBEWithMD5And256BitAES-OpenSSL + */ + static public class PBEWithMD5And256BitAESCBCOpenSSL + extends PBESecretKeyFactory + { + public PBEWithMD5And256BitAESCBCOpenSSL() + { + super("PBEWithMD5And256BitAES-CBC-OpenSSL", null, true, OPENSSL, MD5, 256, 128); + } + } + + public static class AlgParamGen + extends BaseAlgorithmParameterGenerator + { + protected void engineInit( + AlgorithmParameterSpec genParamSpec, + SecureRandom random) + throws InvalidAlgorithmParameterException + { + throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for AES parameter generation."); + } + + protected AlgorithmParameters engineGenerateParameters() + { + byte[] iv = new byte[16]; + + if (random == null) + { + random = new SecureRandom(); + } + + random.nextBytes(iv); + + AlgorithmParameters params; + + try + { + params = createParametersInstance("AES"); + params.init(new IvParameterSpec(iv)); + } + catch (Exception e) + { + throw new RuntimeException(e.getMessage()); + } + + return params; + } + } + + public static class AlgParamGenCCM + extends BaseAlgorithmParameterGenerator + { + protected void engineInit( + AlgorithmParameterSpec genParamSpec, + SecureRandom random) + throws InvalidAlgorithmParameterException + { + // TODO: add support for GCMParameterSpec as a template. + throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for AES parameter generation."); + } + + protected AlgorithmParameters engineGenerateParameters() + { + byte[] iv = new byte[12]; + + if (random == null) + { + random = new SecureRandom(); + } + + random.nextBytes(iv); + + AlgorithmParameters params; + + try + { + params = createParametersInstance("CCM"); + params.init(new CCMParameters(iv, 12).getEncoded()); + } + catch (Exception e) + { + throw new RuntimeException(e.getMessage()); + } + + return params; + } + } + + public static class AlgParamGenGCM + extends BaseAlgorithmParameterGenerator + { + protected void engineInit( + AlgorithmParameterSpec genParamSpec, + SecureRandom random) + throws InvalidAlgorithmParameterException + { + // TODO: add support for GCMParameterSpec as a template. + throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for AES parameter generation."); + } + + protected AlgorithmParameters engineGenerateParameters() + { + byte[] nonce = new byte[12]; + + if (random == null) + { + random = new SecureRandom(); + } + + random.nextBytes(nonce); + + AlgorithmParameters params; + + try + { + params = createParametersInstance("GCM"); + params.init(new GCMParameters(nonce, 16).getEncoded()); + } + catch (Exception e) + { + throw new RuntimeException(e.getMessage()); + } + + return params; + } + } + + public static class AlgParams + extends IvAlgorithmParameters + { + protected String engineToString() + { + return "AES IV"; + } + } + + public static class AlgParamsGCM + extends BaseAlgorithmParameters + { + private GCMParameters gcmParams; + + protected void engineInit(AlgorithmParameterSpec paramSpec) + throws InvalidParameterSpecException + { + if (GcmSpecUtil.isGcmSpec(paramSpec)) + { + gcmParams = GcmSpecUtil.extractGcmParameters(paramSpec); + } + else if (paramSpec instanceof AEADParameterSpec) + { + gcmParams = new GCMParameters(((AEADParameterSpec)paramSpec).getNonce(), ((AEADParameterSpec)paramSpec).getMacSizeInBits() / 8); + } + else + { + throw new InvalidParameterSpecException("AlgorithmParameterSpec class not recognized: " + paramSpec.getClass().getName()); + } + } + + protected void engineInit(byte[] params) + throws IOException + { + gcmParams = GCMParameters.getInstance(params); + } + + protected void engineInit(byte[] params, String format) + throws IOException + { + if (!isASN1FormatString(format)) + { + throw new IOException("unknown format specified"); + } + + gcmParams = GCMParameters.getInstance(params); + } + + protected byte[] engineGetEncoded() + throws IOException + { + return gcmParams.getEncoded(); + } + + protected byte[] engineGetEncoded(String format) + throws IOException + { + if (!isASN1FormatString(format)) + { + throw new IOException("unknown format specified"); + } + + return gcmParams.getEncoded(); + } + + protected String engineToString() + { + return "GCM"; + } + + protected AlgorithmParameterSpec localEngineGetParameterSpec(Class paramSpec) + throws InvalidParameterSpecException + { + if (paramSpec == AlgorithmParameterSpec.class || GcmSpecUtil.isGcmSpec(paramSpec)) + { + if (GcmSpecUtil.gcmSpecExists()) + { + return GcmSpecUtil.extractGcmSpec(gcmParams.toASN1Primitive()); + } + return new AEADParameterSpec(gcmParams.getNonce(), gcmParams.getIcvLen() * 8); + } + if (paramSpec == AEADParameterSpec.class) + { + return new AEADParameterSpec(gcmParams.getNonce(), gcmParams.getIcvLen() * 8); + } + if (paramSpec == IvParameterSpec.class) + { + return new IvParameterSpec(gcmParams.getNonce()); + } + + throw new InvalidParameterSpecException("AlgorithmParameterSpec not recognized: " + paramSpec.getName()); + } + } + + public static class AlgParamsCCM + extends BaseAlgorithmParameters + { + private CCMParameters ccmParams; + + protected void engineInit(AlgorithmParameterSpec paramSpec) + throws InvalidParameterSpecException + { + if (GcmSpecUtil.isGcmSpec(paramSpec)) + { + ccmParams = CCMParameters.getInstance(GcmSpecUtil.extractGcmParameters(paramSpec)); + } + else if (paramSpec instanceof AEADParameterSpec) + { + ccmParams = new CCMParameters(((AEADParameterSpec)paramSpec).getNonce(), ((AEADParameterSpec)paramSpec).getMacSizeInBits() / 8); + } + else + { + throw new InvalidParameterSpecException("AlgorithmParameterSpec class not recognized: " + paramSpec.getClass().getName()); + } + } + + protected void engineInit(byte[] params) + throws IOException + { + ccmParams = CCMParameters.getInstance(params); + } + + protected void engineInit(byte[] params, String format) + throws IOException + { + if (!isASN1FormatString(format)) + { + throw new IOException("unknown format specified"); + } + + ccmParams = CCMParameters.getInstance(params); + } + + protected byte[] engineGetEncoded() + throws IOException + { + return ccmParams.getEncoded(); + } + + protected byte[] engineGetEncoded(String format) + throws IOException + { + if (!isASN1FormatString(format)) + { + throw new IOException("unknown format specified"); + } + + return ccmParams.getEncoded(); + } + + protected String engineToString() + { + return "CCM"; + } + + protected AlgorithmParameterSpec localEngineGetParameterSpec(Class paramSpec) + throws InvalidParameterSpecException + { + if (paramSpec == AlgorithmParameterSpec.class || GcmSpecUtil.isGcmSpec(paramSpec)) + { + if (GcmSpecUtil.gcmSpecExists()) + { + return GcmSpecUtil.extractGcmSpec(ccmParams.toASN1Primitive()); + } + return new AEADParameterSpec(ccmParams.getNonce(), ccmParams.getIcvLen() * 8); + } + if (paramSpec == AEADParameterSpec.class) + { + return new AEADParameterSpec(ccmParams.getNonce(), ccmParams.getIcvLen() * 8); + } + if (paramSpec == IvParameterSpec.class) + { + return new IvParameterSpec(ccmParams.getNonce()); + } + + throw new InvalidParameterSpecException("AlgorithmParameterSpec not recognized: " + paramSpec.getName()); + } + } + + public static class Mappings + extends SymmetricAlgorithmProvider + { + private static final String PREFIX = AES.class.getName(); + + /** + * These three got introduced in some messages as a result of a typo in an + * early document. We don't produce anything using these OID values, but we'll + * read them. + */ + private static final String wrongAES128 = "2.16.840.1.101.3.4.2"; + private static final String wrongAES192 = "2.16.840.1.101.3.4.22"; + private static final String wrongAES256 = "2.16.840.1.101.3.4.42"; + + public Mappings() + { + } + + public void configure(ConfigurableProvider provider) + { + provider.addAlgorithm("AlgorithmParameters.AES", PREFIX + "$AlgParams"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + wrongAES128, "AES"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + wrongAES192, "AES"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + wrongAES256, "AES"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes128_CBC, "AES"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes192_CBC, "AES"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes256_CBC, "AES"); + + provider.addAlgorithm("AlgorithmParameters.GCM", PREFIX + "$AlgParamsGCM"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes128_GCM, "GCM"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes192_GCM, "GCM"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes256_GCM, "GCM"); + + provider.addAlgorithm("AlgorithmParameters.CCM", PREFIX + "$AlgParamsCCM"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes128_CCM, "CCM"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes192_CCM, "CCM"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes256_CCM, "CCM"); + + provider.addAlgorithm("AlgorithmParameterGenerator.AES", PREFIX + "$AlgParamGen"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + wrongAES128, "AES"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + wrongAES192, "AES"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + wrongAES256, "AES"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes128_CBC, "AES"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes192_CBC, "AES"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes256_CBC, "AES"); + + provider.addAlgorithm("Cipher.AES", PREFIX + "$ECB"); + provider.addAlgorithm("Alg.Alias.Cipher." + wrongAES128, "AES"); + provider.addAlgorithm("Alg.Alias.Cipher." + wrongAES192, "AES"); + provider.addAlgorithm("Alg.Alias.Cipher." + wrongAES256, "AES"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_ECB, PREFIX + "$ECB"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_ECB, PREFIX + "$ECB"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_ECB, PREFIX + "$ECB"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_CBC, PREFIX + "$CBC"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_CBC, PREFIX + "$CBC"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_CBC, PREFIX + "$CBC"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_OFB, PREFIX + "$OFB"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_OFB, PREFIX + "$OFB"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_OFB, PREFIX + "$OFB"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_CFB, PREFIX + "$CFB"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_CFB, PREFIX + "$CFB"); + provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_CFB, PREFIX + "$CFB"); + provider.addAlgorithm("Cipher.AESWRAP", PREFIX + "$Wrap"); + provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes128_wrap, "AESWRAP"); + provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes192_wrap, "AESWRAP"); + provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes256_wrap, "AESWRAP"); + provider.addAlgorithm("Alg.Alias.Cipher.AESKW", "AESWRAP"); + + provider.addAlgorithm("Cipher.AESRFC3211WRAP", PREFIX + "$RFC3211Wrap"); + provider.addAlgorithm("Cipher.AESRFC5649WRAP", PREFIX + "$RFC5649Wrap"); + + provider.addAlgorithm("AlgorithmParameterGenerator.CCM", PREFIX + "$AlgParamGenCCM"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes128_CCM, "CCM"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes192_CCM, "CCM"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes256_CCM, "CCM"); + + provider.addAlgorithm("Cipher.CCM", PREFIX + "$CCM"); + provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes128_CCM, "CCM"); + provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes192_CCM, "CCM"); + provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes256_CCM, "CCM"); + + provider.addAlgorithm("AlgorithmParameterGenerator.GCM", PREFIX + "$AlgParamGenGCM"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes128_GCM, "GCM"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes192_GCM, "GCM"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes256_GCM, "GCM"); + + provider.addAlgorithm("Cipher.GCM", PREFIX + "$GCM"); + provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes128_GCM, "GCM"); + provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes192_GCM, "GCM"); + provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes256_GCM, "GCM"); + + provider.addAlgorithm("KeyGenerator.AES", PREFIX + "$KeyGen"); + provider.addAlgorithm("KeyGenerator." + wrongAES128, PREFIX + "$KeyGen128"); + provider.addAlgorithm("KeyGenerator." + wrongAES192, PREFIX + "$KeyGen192"); + provider.addAlgorithm("KeyGenerator." + wrongAES256, PREFIX + "$KeyGen256"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_ECB, PREFIX + "$KeyGen128"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_CBC, PREFIX + "$KeyGen128"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_OFB, PREFIX + "$KeyGen128"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_CFB, PREFIX + "$KeyGen128"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_ECB, PREFIX + "$KeyGen192"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_CBC, PREFIX + "$KeyGen192"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_OFB, PREFIX + "$KeyGen192"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_CFB, PREFIX + "$KeyGen192"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_ECB, PREFIX + "$KeyGen256"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_CBC, PREFIX + "$KeyGen256"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_OFB, PREFIX + "$KeyGen256"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_CFB, PREFIX + "$KeyGen256"); + provider.addAlgorithm("KeyGenerator.AESWRAP", PREFIX + "$KeyGen"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_wrap, PREFIX + "$KeyGen128"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_wrap, PREFIX + "$KeyGen192"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_wrap, PREFIX + "$KeyGen256"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_GCM, PREFIX + "$KeyGen128"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_GCM, PREFIX + "$KeyGen192"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_GCM, PREFIX + "$KeyGen256"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_CCM, PREFIX + "$KeyGen128"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_CCM, PREFIX + "$KeyGen192"); + provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_CCM, PREFIX + "$KeyGen256"); + + provider.addAlgorithm("Mac.AESCMAC", PREFIX + "$AESCMAC"); + + provider.addAlgorithm("Mac.AESCCMMAC", PREFIX + "$AESCCMMAC"); + provider.addAlgorithm("Alg.Alias.Mac." + NISTObjectIdentifiers.id_aes128_CCM.getId(), "AESCCMMAC"); + provider.addAlgorithm("Alg.Alias.Mac." + NISTObjectIdentifiers.id_aes192_CCM.getId(), "AESCCMMAC"); + provider.addAlgorithm("Alg.Alias.Mac." + NISTObjectIdentifiers.id_aes256_CCM.getId(), "AESCCMMAC"); + + provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes128_cbc, "PBEWITHSHAAND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes192_cbc, "PBEWITHSHAAND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes256_cbc, "PBEWITHSHAAND256BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes128_cbc, "PBEWITHSHA256AND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes192_cbc, "PBEWITHSHA256AND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes256_cbc, "PBEWITHSHA256AND256BITAES-CBC-BC"); + + provider.addAlgorithm("Cipher.PBEWITHSHAAND128BITAES-CBC-BC", PREFIX + "$PBEWithSHA1AESCBC128"); + provider.addAlgorithm("Cipher.PBEWITHSHAAND192BITAES-CBC-BC", PREFIX + "$PBEWithSHA1AESCBC192"); + provider.addAlgorithm("Cipher.PBEWITHSHAAND256BITAES-CBC-BC", PREFIX + "$PBEWithSHA1AESCBC256"); + provider.addAlgorithm("Cipher.PBEWITHSHA256AND128BITAES-CBC-BC", PREFIX + "$PBEWithSHA256AESCBC128"); + provider.addAlgorithm("Cipher.PBEWITHSHA256AND192BITAES-CBC-BC", PREFIX + "$PBEWithSHA256AESCBC192"); + provider.addAlgorithm("Cipher.PBEWITHSHA256AND256BITAES-CBC-BC", PREFIX + "$PBEWithSHA256AESCBC256"); + + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND128BITAES-CBC-BC","PBEWITHSHAAND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND192BITAES-CBC-BC","PBEWITHSHAAND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND256BITAES-CBC-BC","PBEWITHSHAAND256BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND128BITAES-CBC-BC","PBEWITHSHAAND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND192BITAES-CBC-BC","PBEWITHSHAAND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND256BITAES-CBC-BC","PBEWITHSHAAND256BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHAAND128BITAES-BC","PBEWITHSHAAND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHAAND192BITAES-BC", "PBEWITHSHAAND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHAAND256BITAES-BC", "PBEWITHSHAAND256BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND128BITAES-BC","PBEWITHSHAAND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND192BITAES-BC","PBEWITHSHAAND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND256BITAES-BC","PBEWITHSHAAND256BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND128BITAES-BC","PBEWITHSHAAND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND192BITAES-BC","PBEWITHSHAAND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND256BITAES-BC","PBEWITHSHAAND256BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND128BITAES-CBC-BC","PBEWITHSHA256AND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND192BITAES-CBC-BC","PBEWITHSHA256AND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND256BITAES-CBC-BC","PBEWITHSHA256AND256BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA256AND128BITAES-BC","PBEWITHSHA256AND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA256AND192BITAES-BC","PBEWITHSHA256AND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA256AND256BITAES-BC","PBEWITHSHA256AND256BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND128BITAES-BC","PBEWITHSHA256AND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND192BITAES-BC","PBEWITHSHA256AND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND256BITAES-BC","PBEWITHSHA256AND256BITAES-CBC-BC"); + + provider.addAlgorithm("Cipher.PBEWITHMD5AND128BITAES-CBC-OPENSSL", PREFIX + "$PBEWithAESCBC"); + provider.addAlgorithm("Cipher.PBEWITHMD5AND192BITAES-CBC-OPENSSL", PREFIX + "$PBEWithAESCBC"); + provider.addAlgorithm("Cipher.PBEWITHMD5AND256BITAES-CBC-OPENSSL", PREFIX + "$PBEWithAESCBC"); + + provider.addAlgorithm("SecretKeyFactory.PBEWITHMD5AND128BITAES-CBC-OPENSSL", PREFIX + "$PBEWithMD5And128BitAESCBCOpenSSL"); + provider.addAlgorithm("SecretKeyFactory.PBEWITHMD5AND192BITAES-CBC-OPENSSL", PREFIX + "$PBEWithMD5And192BitAESCBCOpenSSL"); + provider.addAlgorithm("SecretKeyFactory.PBEWITHMD5AND256BITAES-CBC-OPENSSL", PREFIX + "$PBEWithMD5And256BitAESCBCOpenSSL"); + + provider.addAlgorithm("SecretKeyFactory.PBEWITHSHAAND128BITAES-CBC-BC", PREFIX + "$PBEWithSHAAnd128BitAESBC"); + provider.addAlgorithm("SecretKeyFactory.PBEWITHSHAAND192BITAES-CBC-BC", PREFIX + "$PBEWithSHAAnd192BitAESBC"); + provider.addAlgorithm("SecretKeyFactory.PBEWITHSHAAND256BITAES-CBC-BC", PREFIX + "$PBEWithSHAAnd256BitAESBC"); + provider.addAlgorithm("SecretKeyFactory.PBEWITHSHA256AND128BITAES-CBC-BC", PREFIX + "$PBEWithSHA256And128BitAESBC"); + provider.addAlgorithm("SecretKeyFactory.PBEWITHSHA256AND192BITAES-CBC-BC", PREFIX + "$PBEWithSHA256And192BitAESBC"); + provider.addAlgorithm("SecretKeyFactory.PBEWITHSHA256AND256BITAES-CBC-BC", PREFIX + "$PBEWithSHA256And256BitAESBC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA1AND128BITAES-CBC-BC","PBEWITHSHAAND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA1AND192BITAES-CBC-BC","PBEWITHSHAAND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA1AND256BITAES-CBC-BC","PBEWITHSHAAND256BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-1AND128BITAES-CBC-BC","PBEWITHSHAAND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-1AND192BITAES-CBC-BC","PBEWITHSHAAND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-1AND256BITAES-CBC-BC","PBEWITHSHAAND256BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND128BITAES-CBC-BC","PBEWITHSHA256AND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND192BITAES-CBC-BC","PBEWITHSHA256AND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND256BITAES-CBC-BC","PBEWITHSHA256AND256BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND128BITAES-BC","PBEWITHSHA256AND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND192BITAES-BC","PBEWITHSHA256AND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND256BITAES-BC","PBEWITHSHA256AND256BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes128_cbc, "PBEWITHSHAAND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes192_cbc, "PBEWITHSHAAND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes256_cbc, "PBEWITHSHAAND256BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes128_cbc, "PBEWITHSHA256AND128BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes192_cbc, "PBEWITHSHA256AND192BITAES-CBC-BC"); + provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes256_cbc, "PBEWITHSHA256AND256BITAES-CBC-BC"); + + provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHAAND128BITAES-CBC-BC", "PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHAAND192BITAES-CBC-BC", "PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHAAND256BITAES-CBC-BC", "PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA256AND128BITAES-CBC-BC", "PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA256AND192BITAES-CBC-BC", "PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA256AND256BITAES-CBC-BC", "PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA1AND128BITAES-CBC-BC","PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA1AND192BITAES-CBC-BC","PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA1AND256BITAES-CBC-BC","PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-1AND128BITAES-CBC-BC","PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-1AND192BITAES-CBC-BC","PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-1AND256BITAES-CBC-BC","PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-256AND128BITAES-CBC-BC","PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-256AND192BITAES-CBC-BC","PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-256AND256BITAES-CBC-BC","PKCS12PBE"); + + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes128_cbc.getId(), "PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes192_cbc.getId(), "PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes256_cbc.getId(), "PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes128_cbc.getId(), "PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes192_cbc.getId(), "PKCS12PBE"); + provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes256_cbc.getId(), "PKCS12PBE"); + + addGMacAlgorithm(provider, "AES", PREFIX + "$AESGMAC", PREFIX + "$KeyGen128"); + addPoly1305Algorithm(provider, "AES", PREFIX + "$Poly1305", PREFIX + "$Poly1305KeyGen"); + } + } + + private static Class lookup(String className) + { + try + { + Class def = AES.class.getClassLoader().loadClass(className); + + return def; + } + catch (Exception e) + { + return null; + } + } +} diff --git a/Java/AbstractConstantRestrictor.java b/Java/AbstractConstantRestrictor.java new file mode 100644 index 0000000000000000000000000000000000000000..fab644430a6e5aab8891a3835c62dd8aeeb5dbf0 --- /dev/null +++ b/Java/AbstractConstantRestrictor.java @@ -0,0 +1,82 @@ +package org.jolokia.restrictor; + +/* + * Copyright 2009-2011 Roland Huss + * + * 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. + */ + +import javax.management.ObjectName; + +import org.jolokia.util.HttpMethod; +import org.jolokia.util.RequestType; + +/** + * Base restrictor which alway returns the constant given + * at construction time + * + * @author roland + * @since 06.10.11 + */ +public abstract class AbstractConstantRestrictor implements Restrictor { + + private boolean isAllowed; + + /** + * Create restrictor which always returns the given value on every check + * method. + * + * @param pAllowed whether access is allowed or denied + */ + protected AbstractConstantRestrictor(boolean pAllowed) { + isAllowed = pAllowed; + } + + /** {@inheritDoc} */ + public final boolean isHttpMethodAllowed(HttpMethod pMethod) { + return isAllowed; + } + + /** {@inheritDoc} */ + public final boolean isTypeAllowed(RequestType pType) { + return isAllowed; + } + + /** {@inheritDoc} */ + public final boolean isAttributeReadAllowed(ObjectName pName, String pAttribute) { + return isAllowed; + } + + /** {@inheritDoc} */ + public final boolean isAttributeWriteAllowed(ObjectName pName, String pAttribute) { + return isAllowed; + } + + /** {@inheritDoc} */ + public final boolean isOperationAllowed(ObjectName pName, String pOperation) { + return isAllowed; + } + + /** {@inheritDoc} */ + public final boolean isRemoteAccessAllowed(String... pHostOrAddress) { + return isAllowed; + } + + /** {@inheritDoc} */ + // BUG: CWE-352 Cross-Site Request Forgery (CSRF) + // public boolean isCorsAccessAllowed(String pOrigin) { + // FIXED: + public boolean isOriginAllowed(String pOrigin, boolean pIsStrictCheck) { + return isAllowed; + } +} diff --git a/Java/AbstractDiskHttpDataTest.java b/Java/AbstractDiskHttpDataTest.java new file mode 100644 index 0000000000000000000000000000000000000000..8904c7d6b656b1914d92f6cbce1fe1939ddc8a83 --- /dev/null +++ b/Java/AbstractDiskHttpDataTest.java @@ -0,0 +1,131 @@ +/* + * Copyright 2020 The Netty Project + * + * The Netty Project 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: + * + * 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 io.netty.handler.codec.http.multipart; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufUtil; +import io.netty.util.internal.PlatformDependent; +import org.junit.Test; + +import java.io.File; +import java.io.FileOutputStream; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.UUID; + +import static io.netty.util.CharsetUtil.UTF_8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +/** + * {@link AbstractDiskHttpData} test cases + */ +public class AbstractDiskHttpDataTest { + + @Test + public void testGetChunk() throws Exception { + TestHttpData test = new TestHttpData("test", UTF_8, 0); + try { + // BUG: CWE-378 Creation of Temporary File With Insecure Permissions + // File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); + // FIXED: + File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), ".tmp", null); + tmpFile.deleteOnExit(); + FileOutputStream fos = new FileOutputStream(tmpFile); + byte[] bytes = new byte[4096]; + PlatformDependent.threadLocalRandom().nextBytes(bytes); + try { + fos.write(bytes); + fos.flush(); + } finally { + fos.close(); + } + test.setContent(tmpFile); + ByteBuf buf1 = test.getChunk(1024); + assertEquals(buf1.readerIndex(), 0); + assertEquals(buf1.writerIndex(), 1024); + ByteBuf buf2 = test.getChunk(1024); + assertEquals(buf2.readerIndex(), 0); + assertEquals(buf2.writerIndex(), 1024); + assertFalse("Arrays should not be equal", + Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2))); + } finally { + test.delete(); + } + } + + private static final class TestHttpData extends AbstractDiskHttpData { + + private TestHttpData(String name, Charset charset, long size) { + super(name, charset, size); + } + + @Override + protected String getDiskFilename() { + return null; + } + + @Override + protected String getPrefix() { + return null; + } + + @Override + protected String getBaseDirectory() { + return null; + } + + @Override + protected String getPostfix() { + return null; + } + + @Override + protected boolean deleteOnExit() { + return false; + } + + @Override + public HttpData copy() { + return null; + } + + @Override + public HttpData duplicate() { + return null; + } + + @Override + public HttpData retainedDuplicate() { + return null; + } + + @Override + public HttpData replace(ByteBuf content) { + return null; + } + + @Override + public HttpDataType getHttpDataType() { + return null; + } + + @Override + public int compareTo(InterfaceHttpData o) { + return 0; + } + } +} diff --git a/Java/AbstractEpsgFactory.java b/Java/AbstractEpsgFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..c5733dc8f56ad8e2a063f009d1ac98f996b2cc6d --- /dev/null +++ b/Java/AbstractEpsgFactory.java @@ -0,0 +1,3668 @@ +/* + * GeoTools - The Open Source Java GIS Toolkit + * http://geotools.org + * + * (C) 2005-2008, Open Source Geospatial Foundation (OSGeo) + * + * 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; + * version 2.1 of the License. + * + * 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. + */ +package org.geotools.referencing.factory.epsg; + +import static org.geotools.measure.Units.DEGREE_ANGLE; +import static org.geotools.measure.Units.DEGREE_MINUTE_SECOND; +import static org.geotools.measure.Units.FOOT; +import static org.geotools.measure.Units.GRADE; +import static org.geotools.measure.Units.KILOMETER; +import static org.geotools.measure.Units.METRE; +import static org.geotools.measure.Units.MICRORADIAN; +import static org.geotools.measure.Units.MINUTE_ANGLE; +import static org.geotools.measure.Units.NAUTICAL_MILE; +import static org.geotools.measure.Units.ONE; +import static org.geotools.measure.Units.PPM; +import static org.geotools.measure.Units.RADIAN; +import static org.geotools.measure.Units.SECOND_ANGLE; +import static org.geotools.measure.Units.SEXAGESIMAL_DMS; + +import java.awt.RenderingHints; +import java.io.File; +import java.io.IOException; +import java.io.ObjectStreamException; +import java.io.Serializable; +import java.net.URI; +import java.net.URISyntaxException; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.Date; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.AbstractMap; +import java.util.AbstractSet; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import javax.measure.Unit; +import javax.measure.quantity.Angle; +import javax.measure.quantity.Length; +import javax.naming.NamingException; +import javax.sql.DataSource; +import org.geotools.measure.Units; +import org.geotools.metadata.i18n.ErrorKeys; +import org.geotools.metadata.i18n.Errors; +import org.geotools.metadata.i18n.LoggingKeys; +import org.geotools.metadata.i18n.Loggings; +import org.geotools.metadata.i18n.Vocabulary; +import org.geotools.metadata.i18n.VocabularyKeys; +import org.geotools.metadata.iso.citation.CitationImpl; +import org.geotools.metadata.iso.citation.Citations; +import org.geotools.metadata.iso.extent.ExtentImpl; +import org.geotools.metadata.iso.extent.GeographicBoundingBoxImpl; +import org.geotools.metadata.iso.quality.AbsoluteExternalPositionalAccuracyImpl; +import org.geotools.metadata.iso.quality.QuantitativeResultImpl; +import org.geotools.parameter.DefaultParameterDescriptor; +import org.geotools.parameter.DefaultParameterDescriptorGroup; +import org.geotools.referencing.AbstractIdentifiedObject; +import org.geotools.referencing.NamedIdentifier; +import org.geotools.referencing.cs.DefaultCoordinateSystemAxis; +import org.geotools.referencing.datum.BursaWolfParameters; +import org.geotools.referencing.datum.DefaultGeodeticDatum; +import org.geotools.referencing.factory.AbstractCachedAuthorityFactory; +import org.geotools.referencing.factory.BufferedAuthorityFactory; +import org.geotools.referencing.factory.DirectAuthorityFactory; +import org.geotools.referencing.factory.IdentifiedObjectFinder; +import org.geotools.referencing.operation.DefaultConcatenatedOperation; +import org.geotools.referencing.operation.DefaultOperation; +import org.geotools.referencing.operation.DefaultOperationMethod; +import org.geotools.referencing.operation.DefiningConversion; +import org.geotools.referencing.util.CRSUtilities; +import org.geotools.util.LocalName; +import org.geotools.util.ObjectCache; +import org.geotools.util.ScopedName; +import org.geotools.util.SimpleInternationalString; +import org.geotools.util.TableWriter; +import org.geotools.util.Version; +import org.geotools.util.factory.GeoTools; +import org.geotools.util.factory.Hints; +import org.geotools.util.logging.Logging; +import org.opengis.metadata.Identifier; +import org.opengis.metadata.citation.Citation; +import org.opengis.metadata.extent.Extent; +import org.opengis.metadata.quality.EvaluationMethodType; +import org.opengis.metadata.quality.PositionalAccuracy; +import org.opengis.parameter.InvalidParameterValueException; +import org.opengis.parameter.ParameterDescriptor; +import org.opengis.parameter.ParameterNotFoundException; +import org.opengis.parameter.ParameterValue; +import org.opengis.parameter.ParameterValueGroup; +import org.opengis.referencing.FactoryException; +import org.opengis.referencing.IdentifiedObject; +import org.opengis.referencing.NoSuchAuthorityCodeException; +import org.opengis.referencing.NoSuchIdentifierException; +import org.opengis.referencing.crs.CRSFactory; +import org.opengis.referencing.crs.CompoundCRS; +import org.opengis.referencing.crs.CoordinateReferenceSystem; +import org.opengis.referencing.crs.GeneralDerivedCRS; +import org.opengis.referencing.crs.GeocentricCRS; +import org.opengis.referencing.crs.GeographicCRS; +import org.opengis.referencing.crs.ProjectedCRS; +import org.opengis.referencing.crs.SingleCRS; +import org.opengis.referencing.cs.AxisDirection; +import org.opengis.referencing.cs.CSFactory; +import org.opengis.referencing.cs.CartesianCS; +import org.opengis.referencing.cs.CoordinateSystem; +import org.opengis.referencing.cs.CoordinateSystemAxis; +import org.opengis.referencing.cs.EllipsoidalCS; +import org.opengis.referencing.cs.SphericalCS; +import org.opengis.referencing.cs.VerticalCS; +import org.opengis.referencing.datum.Datum; +import org.opengis.referencing.datum.DatumFactory; +import org.opengis.referencing.datum.Ellipsoid; +import org.opengis.referencing.datum.EngineeringDatum; +import org.opengis.referencing.datum.GeodeticDatum; +import org.opengis.referencing.datum.PrimeMeridian; +import org.opengis.referencing.datum.VerticalDatum; +import org.opengis.referencing.datum.VerticalDatumType; +import org.opengis.referencing.operation.ConcatenatedOperation; +import org.opengis.referencing.operation.Conversion; +import org.opengis.referencing.operation.CoordinateOperation; +import org.opengis.referencing.operation.MathTransform; +import org.opengis.referencing.operation.OperationMethod; +import org.opengis.referencing.operation.Projection; +import org.opengis.referencing.operation.Transformation; +import org.opengis.util.GenericName; +import org.opengis.util.InternationalString; +import si.uom.NonSI; +import si.uom.SI; + +/** + * A coordinate reference system factory backed by the EPSG database tables. + * + *

The EPSG database is freely available at http://www.epsg.org. Current version of this class requires EPSG + * database version 6.6 or above. + * + *

This factory makes use of a provided {@link ObjectCache}, and may be deployed in stand aline + * fashion; or as a worker for a {@link MultiEpsgFactory}. + * + *

This class is abstract - please see the subclasses for dialect specific implementations: + * + *

+ * + * These factories accepts names as well as numerical identifiers. For example "NTF (Paris) / + * France I" and {@code "27581"} both fetchs the same object. However, names may be ambiguous + * since the same name may be used for more than one object. This is the case of "WGS 84" for + * example. If such an ambiguity is found, an exception will be thrown. If names are not wanted as a + * legal EPSG code, subclasses can override the {@link #isPrimaryKey} method. + * + * @since 2.4 + * @version $Id$ + * @author Yann Cézard + * @author Martin Desruisseaux (IRD) + * @author Rueben Schulz + * @author Matthias Basler + * @author Andrea Aime + */ +@SuppressWarnings("PMD.CloseResource") // class implements its own PreparedStatement pooling +public abstract class AbstractEpsgFactory extends AbstractCachedAuthorityFactory { + /// Datum shift operation methods + /** First Bursa-Wolf method. */ + private static final int BURSA_WOLF_MIN_CODE = 9603; + + /** Last Bursa-Wolf method. */ + private static final int BURSA_WOLF_MAX_CODE = 9607; + + /** Rotation frame method. */ + private static final int ROTATION_FRAME_CODE = 9607; + + /** Dummy operation to ignore. */ + private static final int DUMMY_OPERATION = 1; + + /** The name for the transformation accuracy metadata. */ + private static final InternationalString TRANSFORMATION_ACCURACY = + Vocabulary.formatInternational(VocabularyKeys.TRANSFORMATION_ACCURACY); + + /** + * The authority for this database. Will be created only when first needed. This authority will + * contains the database version in the {@linkplain Citation#getEdition edition} attribute, + * together with the {@linkplain Citation#getEditionDate edition date}. + */ + private transient Citation authority; // FIXME: always EPSG + + /** A DataSource to the EPSG database being used. */ + protected javax.sql.DataSource dataSource; + + /** + * The connection to the EPSG database - this is create in a lazy manner from the DataSource. + * + *

This field is managed as part of our connection lifecycle. + */ + private Connection connection; + + /** + * A pool of prepared statements. Key are {@link String} object related to their originating + * method name (for example "Ellipsoid" for {@link #createEllipsoid}, while values are {@link + * PreparedStatement} objects. + * + *

Note: It is okay to use {@link IdentityHashMap} instead of {@link + * HashMap} because the keys will always be the exact same object, namely the hard-coded + * argument given to calls to {@link #prepareStatement} in this class. + * + *

This field is managed as part of our connection lifecycle. + */ + private final Map statements = new IdentityHashMap<>(); + + /** + * Last object type returned by {@link #createObject}, or -1 if none. This type is an index in + * the {@link #TABLES_INFO} array and is strictly for {@link #createObject} internal use. + */ + private int lastObjectType = -1; + + /** + * The last table in which object name were looked for. This is for internal use by {@link + * #toPrimaryKey} only. + */ + private transient String lastTableForName; + + /** + * Cache for axis names. This service is not provided by {@link BufferedAuthorityFactory} since + * {@link AxisName} object are particular to the EPSG database. + * + * @see #getAxisName + */ + private final Map axisNames = new HashMap<>(); + + /** + * Cache for axis numbers. This service is not provided by {@link BufferedAuthorityFactory} + * since the number of axis is used internally in this class. + * + * @see #getDimensionForCRS + */ + private final Map axisCounts = new HashMap<>(); + + /** + * Cache for projection checks. This service is not provided by {@link BufferedAuthorityFactory} + * since the check that a transformation is a projection is used internally in this class. + * + * @see #isProjection + */ + private final Map codeProjection = new HashMap<>(); + + /** Pool of naming systems, used for caching. There is usually few of them (about 15). */ + private final Map scopes = new HashMap<>(); + + /** + * The properties to be given the objects to construct. Reused every time {@link + * #createProperties} is invoked. + */ + private final Map properties = new HashMap<>(); + + /** + * A safety guard for preventing never-ending loops in recursive calls to {@link #createDatum}. + * This is used by {@link #createBursaWolfParameters}, which need to create a target datum. The + * target datum could have its own Bursa-Wolf parameters, with one of them pointing again to the + * source datum. + */ + private final Set safetyGuard = new HashSet<>(); + + public AbstractEpsgFactory(final Hints userHints) throws FactoryException { + super(MAXIMUM_PRIORITY - 20); + // The following hints have no effect on this class behaviour, + // but tell to the user what this factory do about axis order. + hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE); + hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE); + hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE); + + // + // We need to obtain our DataSource + if (userHints != null) { + Object hint = userHints.get(Hints.EPSG_DATA_SOURCE); + if (hint instanceof String) { + String name = (String) hint; + try { + // BUG: CWE-20 Improper Input Validation + // dataSource = (DataSource) GeoTools.getInitialContext().lookup(name); + // FIXED: + dataSource = (DataSource) GeoTools.jndiLookup(name); + } catch (NamingException e) { + throw new FactoryException("A EPSG_DATA_SOURCE hint is required:" + e); + } + hints.put(Hints.EPSG_DATA_SOURCE, dataSource); + } else if (hint instanceof DataSource) { + dataSource = (DataSource) hint; + hints.put(Hints.EPSG_DATA_SOURCE, dataSource); + } else { + throw new FactoryException("A EPSG_DATA_SOURCE hint is required."); + } + } else { + throw new FactoryException("A EPSG_DATA_SOURCE hint is required."); + } + } + + public AbstractEpsgFactory(final Hints userHints, final javax.sql.DataSource dataSource) { + super(MAXIMUM_PRIORITY - 20); + + this.dataSource = dataSource; + // The following hints have no effect on this class behaviour, + // but tell to the user what this factory do about axis order. + hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE); + hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE); + hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE); + hints.put(Hints.EPSG_DATA_SOURCE, dataSource); + } + /** + * Constructs an authority factory using the specified connection. + * + * @param userHints The underlying factories used for objects creation. + * @param connection The connection to the underlying EPSG database. + */ + public AbstractEpsgFactory(final Hints userHints, final Connection connection) { + super(MAXIMUM_PRIORITY - 20, userHints); + // The following hints have no effect on this class behaviour, + // but tell to the user what this factory do about axis order. + hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE); + hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE); + hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE); + this.connection = connection; + ensureNonNull("connection", connection); + } + + /** + * Returns the authority for this EPSG database. This authority will contains the database + * version in the {@linkplain Citation#getEdition edition} attribute, together with the + * {@linkplain Citation#getEditionDate edition date}. + */ + @Override + public synchronized Citation getAuthority() { + if (authority == null) + try { + final String query = + adaptSQL( + "SELECT VERSION_NUMBER, VERSION_DATE FROM [Version History]" + + " ORDER BY VERSION_DATE DESC"); + final DatabaseMetaData metadata = getConnection().getMetaData(); + try (Statement statement = getConnection().createStatement(); + ResultSet result = statement.executeQuery(query)) { + if (result.next()) { + final String version = result.getString(1); + final Date date = result.getDate(2); + final String engine = metadata.getDatabaseProductName(); + final CitationImpl c = new CitationImpl(Citations.EPSG); + c.getAlternateTitles() + .add( + Vocabulary.formatInternational( + VocabularyKeys.DATA_BASE_$3, + "EPSG", + version, + engine)); + c.setEdition(new SimpleInternationalString(version)); + c.setEditionDate(date); + authority = (Citation) c.unmodifiable(); + hints.put( + Hints.VERSION, + new Version(version)); // For getImplementationHints() + } else { + authority = Citations.EPSG; + } + } + } catch (SQLException exception) { + Logging.unexpectedException( + LOGGER, AbstractEpsgFactory.class, "getAuthority", exception); + return Citations.EPSG; + } + return authority; + } + + /** + * Returns a description of the database engine. + * + * @throws FactoryException if the database's metadata can't be fetched. + */ + @Override + public synchronized String getBackingStoreDescription() throws FactoryException { + final Citation authority = getAuthority(); + try (TableWriter table = new TableWriter(null, " ")) { + final Vocabulary resources = Vocabulary.getResources(null); + CharSequence cs; + if ((cs = authority.getEdition()) != null) { + table.write(resources.getString(VocabularyKeys.VERSION_OF_$1, "EPSG")); + table.write(':'); + table.nextColumn(); + table.write(cs.toString()); + table.nextLine(); + } + try { + String s; + final DatabaseMetaData metadata = getConnection().getMetaData(); + if ((s = metadata.getDatabaseProductName()) != null) { + table.write(resources.getLabel(VocabularyKeys.DATABASE_ENGINE)); + table.nextColumn(); + table.write(s); + if ((s = metadata.getDatabaseProductVersion()) != null) { + table.write(' '); + table.write(resources.getString(VocabularyKeys.VERSION_$1, s)); + } + table.nextLine(); + } + if ((s = metadata.getURL()) != null) { + table.write(resources.getLabel(VocabularyKeys.DATABASE_URL)); + table.nextColumn(); + table.write(s); + table.nextLine(); + } + } catch (SQLException exception) { + throw new FactoryException(exception); + } + return table.toString(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Returns the implementation hints for this factory. The returned map contains all the values + * specified in {@linkplain DirectAuthorityFactory#getImplementationHints subclass}, with the + * addition of {@link Hints#VERSION VERSION}. + */ + @Override + public Map getImplementationHints() { + if (authority == null) { + // For the computation of Hints.VERSION. + getAuthority(); + } + return super.getImplementationHints(); + } + + /** + * Returns the set of authority codes of the given type. + * + * @param type The spatial reference objects type (may be {@code Object.class}). + * @return The set of authority codes for spatial reference objects of the given type. If this + * factory doesn't contains any object of the given type, then this method returns an empty + * set. + * @throws FactoryException if access to the underlying database failed. + */ + @Override + protected synchronized Set generateAuthorityCodes(final Class type) + throws FactoryException { + Set result = new HashSet<>(); + for (final TableInfo table : TABLES_INFO) { + if (table.isTypeOf(type)) { + final AuthorityCodeSet codes = new AuthorityCodeSet(table, type); + result.addAll(codes); + } + } + return result; + } + + /** + * Gets a description of the object corresponding to a code. + * + * @param code Value allocated by authority. + * @return A description of the object, or {@code null} if the object corresponding to the + * specified {@code code} has no description. + * @throws NoSuchAuthorityCodeException if the specified {@code code} was not found. + * @throws FactoryException if the query failed for some other reason. + */ + @Override + public InternationalString getDescriptionText(final String code) throws FactoryException { + IdentifiedObject identifiedObject = createObject(code); + final Identifier identifier = identifiedObject.getName(); + if (identifier instanceof GenericName) { + return ((GenericName) identifier).toInternationalString(); + } + return new SimpleInternationalString(identifier.getCode()); + } + + /** + * Returns a prepared statement for the specified name. Most {@link PreparedStatement} creations + * are performed through this method, except {@link #getNumericalIdentifier} and {@link + * #createObject}. + * + * @param key A key uniquely identifying the caller (e.g. {@code "Ellipsoid"} for {@link + * #createEllipsoid}). + * @param sql The SQL statement to use if for creating the {@link PreparedStatement} object. + * Will be used only if no prepared statement was already created for the specified key. + * @return The prepared statement. + * @throws SQLException if the prepared statement can't be created. + */ + private PreparedStatement prepareStatement(final String key, final String sql) + throws SQLException { + assert Thread.holdsLock(this); + PreparedStatement stmt = statements.get(key); + if (stmt == null) { + stmt = getConnection().prepareStatement(adaptSQL(sql)); + statements.put(key, stmt); + } + return stmt; + } + + /** + * Gets the string from the specified {@link ResultSet}. The string is required to be non-null. + * A null string will throw an exception. + * + * @param result The result set to fetch value from. + * @param columnIndex The column index (1-based). + * @param code The identifier of the record where the string was found. + * @return The string at the specified column. + * @throws SQLException if a SQL error occured. + * @throws FactoryException If a null value was found. + */ + private static String getString( + final ResultSet result, final int columnIndex, final String code) + throws SQLException, FactoryException { + final String value = result.getString(columnIndex); + ensureNonNull(result, columnIndex, code); + return value.trim(); + } + + /** + * Same as {@link #getString(ResultSet,int,String)}, but report the fault on an alternative + * column if the value is null. + */ + private static String getString( + final ResultSet result, final int columnIndex, final String code, final int columnFault) + throws SQLException, FactoryException { + final String str = result.getString(columnIndex); + if (result.wasNull()) { + final ResultSetMetaData metadata = result.getMetaData(); + final String column = metadata.getColumnName(columnFault); + final String table = metadata.getTableName(columnFault); + result.close(); + throw new FactoryException( + Errors.format(ErrorKeys.NULL_VALUE_IN_TABLE_$3, code, column, table)); + } + return str.trim(); + } + + /** + * Gets the value from the specified {@link ResultSet}. The value is required to be non-null. A + * null value (i.e. blank) will throw an exception. + * + * @param result The result set to fetch value from. + * @param columnIndex The column index (1-based). + * @param code The identifier of the record where the string was found. + * @return The double at the specified column. + * @throws SQLException if a SQL error occured. + * @throws FactoryException If a null value was found. + */ + private static double getDouble( + final ResultSet result, final int columnIndex, final String code) + throws SQLException, FactoryException { + final double value = result.getDouble(columnIndex); + ensureNonNull(result, columnIndex, code); + return value; + } + + /** + * Gets the value from the specified {@link ResultSet}. The value is required to be non-null. A + * null value (i.e. blank) will throw an exception. + * + * @param result The result set to fetch value from. + * @param columnIndex The column index (1-based). + * @param code The identifier of the record where the string was found. + * @return The integer at the specified column. + * @throws SQLException if a SQL error occured. + * @throws FactoryException If a null value was found. + */ + private static int getInt(final ResultSet result, final int columnIndex, final String code) + throws SQLException, FactoryException { + final int value = result.getInt(columnIndex); + ensureNonNull(result, columnIndex, code); + return value; + } + + /** + * Make sure that the last result was non-null. Used for {@code getString}, {@code getDouble} + * and {@code getInt} methods only. + */ + private static void ensureNonNull( + final ResultSet result, final int columnIndex, final String code) + throws SQLException, FactoryException { + if (result.wasNull()) { + final ResultSetMetaData metadata = result.getMetaData(); + final String column = metadata.getColumnName(columnIndex); + final String table = metadata.getTableName(columnIndex); + result.close(); + throw new FactoryException( + Errors.format(ErrorKeys.NULL_VALUE_IN_TABLE_$3, code, column, table)); + } + } + + /** + * Converts a code from an arbitrary name to the numerical identifier (the primary key). If the + * supplied code is already a numerical value, then it is returned unchanged. If the code is not + * found in the name column, it is returned unchanged as well so that the caller will produces + * an appropriate "Code not found" error message. If the code is found more than once, then an + * exception is thrown. + * + *

Note that this method includes a call to {@link #trimAuthority}, so there is no need to + * call it before or after this method. + * + * @param type The type of object to create. + * @param code The code to check. + * @param table The table where the code should appears. + * @param codeColumn The column name for the code. + * @param nameColumn The column name for the name. + * @return The numerical identifier (i.e. the table primary key value). + * @throws SQLException if an error occured while reading the database. + */ + private String toPrimaryKey( + final Class type, + final String code, + final String table, + final String codeColumn, + final String nameColumn) + throws SQLException, FactoryException { + assert Thread.holdsLock(this); + String identifier = trimAuthority(code); + if (!isPrimaryKey(identifier)) { + /* + * The character is not the numerical code. Search the value in the database. + * If a prepared statement is already available, reuse it providing that it was + * created for the current table. Otherwise, we will create a new statement. + */ + final String KEY = "NumericalIdentifier"; + PreparedStatement statement = statements.get(KEY); + if (statement != null) { + if (!table.equals(lastTableForName)) { + statements.remove(KEY); + statement.close(); + statement = null; + lastTableForName = null; + } + } + if (statement == null) { + final String query = + "SELECT " + codeColumn + " FROM " + table + " WHERE " + nameColumn + " = ?"; + statement = getConnection().prepareStatement(adaptSQL(query)); + statements.put(KEY, statement); + } + statement.setString(1, identifier); + identifier = null; + try (ResultSet result = statement.executeQuery()) { + while (result.next()) { + identifier = ensureSingleton(result.getString(1), identifier, code); + } + } + if (identifier == null) { + throw noSuchAuthorityCode(type, code); + } + } + return identifier; + } + + /** + * Make sure that an object constructed from the database is not incoherent. If the code + * supplied to a {@code createFoo} method exists in the database, then we should find only one + * record. However, we will do a paranoiac check and verify if there is more records, using a + * {@code while (results.next())} loop instead of {@code if (results.next())}. This method is + * invoked in the loop for making sure that, if there is more than one record (which should + * never happen), at least they have identical contents. + * + * @param newValue The newly constructed object. + * @param oldValue The object previously constructed, or {@code null} if none. + * @param code The EPSG code (for formatting error message). + * @throws FactoryException if a duplication has been detected. + * @todo Use generic type when we will be allowed to compile for J2SE 1.5. + */ + private static T ensureSingleton(final T newValue, final T oldValue, final String code) + throws FactoryException { + if (oldValue == null) { + return newValue; + } + if (oldValue.equals(newValue)) { + return oldValue; + } + throw new FactoryException(Errors.format(ErrorKeys.DUPLICATED_VALUES_$1, code)); + } + + /** + * Returns the name for the {@link IdentifiedObject} to construct. This method also search for + * alias. + * + * @param name The name for the {@link IndentifiedObject} to construct. + * @param code The EPSG code of the object to construct. + * @param remarks Remarks, or {@code null} if none. + * @return The name together with a set of properties. + */ + private Map generateProperties( + final String name, final String code, String remarks) + throws SQLException, FactoryException { + properties.clear(); + final Citation authority = getAuthority(); + if (name != null) { + properties.put(IdentifiedObject.NAME_KEY, new NamedIdentifier(authority, name.trim())); + } + if (code != null) { + final InternationalString edition = authority.getEdition(); + final String version = (edition != null) ? edition.toString() : null; + properties.put( + IdentifiedObject.IDENTIFIERS_KEY, + new NamedIdentifier(authority, code.trim(), version)); + } + if (remarks != null && (remarks = remarks.trim()).length() != 0) { + properties.put(IdentifiedObject.REMARKS_KEY, remarks); + } + /* + * Search for alias. + */ + List alias = null; + final PreparedStatement stmt = + prepareStatement( + "Alias", + "SELECT NAMING_SYSTEM_NAME, ALIAS" + + " FROM [Alias] INNER JOIN [Naming System]" + + " ON [Alias].NAMING_SYSTEM_CODE =" + + " [Naming System].NAMING_SYSTEM_CODE" + + " WHERE OBJECT_CODE = ?"); + stmt.setString(1, code); + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final String scope = result.getString(1); + final String local = getString(result, 2, code); + final GenericName generic; + if (scope == null) { + generic = new LocalName(local); + } else { + LocalName cached = scopes.get(scope); + if (cached == null) { + cached = new LocalName(scope); + scopes.put(scope, cached); + } + generic = new ScopedName(cached, local); + } + if (alias == null) { + alias = new ArrayList<>(); + } + alias.add(generic); + } + } + if (alias != null) { + properties.put( + IdentifiedObject.ALIAS_KEY, alias.toArray(new GenericName[alias.size()])); + } + return properties; + } + + /** + * Returns the name for the {@link IdentifiedObject} to construct. This method also search for + * alias. + * + * @param name The name for the {@link IndentifiedObject} to construct. + * @param code The EPSG code of the object to construct. + * @param area The area of use, or {@code null} if none. + * @param scope The scope, or {@code null} if none. + * @param remarks Remarks, or {@code null} if none. + * @return The name together with a set of properties. + */ + private Map generateProperties( + final String name, final String code, String area, String scope, String remarks) + throws SQLException, FactoryException { + final Map properties = generateProperties(name, code, remarks); + if (area != null && (area = area.trim()).length() != 0) { + final Extent extent = generateExtent(area); + properties.put(Datum.DOMAIN_OF_VALIDITY_KEY, extent); + } + if (scope != null && (scope = scope.trim()).length() != 0) { + properties.put(Datum.SCOPE_KEY, scope); + } + return properties; + } + + /** + * Returns an arbitrary object from a code. The default implementation invokes one of {@link + * #createCoordinateReferenceSystem}, {@link #createCoordinateSystem}, {@link #createDatum}, + * {@link #createEllipsoid}, or {@link #createUnit} methods according the object type. + * + * @param code The EPSG value. + * @return The object. + * @throws NoSuchAuthorityCodeException if this method can't find the requested code. + * @throws FactoryException if some other kind of failure occured in the backing store. This + * exception usually have {@link SQLException} as its cause. + */ + @Override + @SuppressWarnings("PMD.OverrideBothEqualsAndHashcode") + public synchronized IdentifiedObject generateObject(final String code) throws FactoryException { + ensureNonNull("code", code); + final String KEY = "IdentifiedObject"; + PreparedStatement stmt = statements.get(KEY); // Null allowed. + StringBuilder query = null; // Will be created only if the last statement doesn't suit. + /* + * Iterates through all tables listed in TABLES_INFO, starting with the table used during + * the last call to 'createObject(code)'. This approach assumes that two consecutive calls + * will often return the same type of object. If the object type changed, then this method + * will have to discard the old prepared statement and prepare a new one, which may be a + * costly operation. Only the last successful prepared statement is cached, in order to keep + * the amount of statements low. Unsuccessful statements are immediately disposed. + */ + final String epsg = trimAuthority(code); + final boolean isPrimaryKey = isPrimaryKey(epsg); + final int tupleToSkip = isPrimaryKey ? lastObjectType : -1; + int index = -1; + for (int i = -1; i < TABLES_INFO.length; i++) { + if (i == tupleToSkip) { + // Avoid to test the same table twice. Note that this test also avoid a + // NullPointerException if 'stmt' is null, since 'lastObjectType' should + // be -1 in this case. + continue; + } + try { + if (i >= 0) { + final TableInfo table = TABLES_INFO[i]; + final String column = isPrimaryKey ? table.codeColumn : table.nameColumn; + if (column == null) { + continue; + } + if (query == null) { + query = new StringBuilder("SELECT "); + } + query.setLength(7); // 7 is the length of "SELECT " in the line above. + query.append(table.codeColumn); + query.append(" FROM "); + query.append(table.table); + query.append(" WHERE "); + query.append(column); + query.append(" = ?"); + if (isPrimaryKey) { + assert !statements.containsKey(KEY) : table; + stmt = prepareStatement(KEY, query.toString()); + } else { + // Do not cache the statement for names. + stmt = getConnection().prepareStatement(adaptSQL(query.toString())); + } + } + /* + * Checks if at least one record is found for the code. If the code is the primary + * key, then we will stop at the first table found since a well-formed EPSG database + * should not contains any duplicate identifiers. In the code is a name, then search + * in all tables since duplicate names exist. + */ + stmt.setString(1, epsg); + try (final ResultSet result = stmt.executeQuery()) { + final boolean present = result.next(); + if (present) { + if (index >= 0) { + throw new FactoryException( + Errors.format(ErrorKeys.DUPLICATED_VALUES_$1, code)); + } + index = (i < 0) ? lastObjectType : i; + if (isPrimaryKey) { + // Don't scan other tables, since primary keys should be unique. + // Note that names may be duplicated, so we don't stop for names. + break; + } + } + } + if (isPrimaryKey) { + if (statements.remove(KEY) == null) { + throw new AssertionError(code); // Should never happen. + } + } + stmt.close(); + } catch (SQLException exception) { + throw databaseFailure(IdentifiedObject.class, code, exception); + } + } + /* + * If a record has been found in one table, then delegates to the appropriate method. + */ + if (isPrimaryKey) { + lastObjectType = index; + } + if (index >= 0) { + switch (index) { + case 0: + return createCoordinateReferenceSystem(code); + case 1: + return createCoordinateSystem(code); + case 2: + return createCoordinateSystemAxis(code); + case 3: + return createDatum(code); + case 4: + return createEllipsoid(code); + case 5: + return createPrimeMeridian(code); + case 6: + return createCoordinateOperation(code); + case 7: + return generateOperationMethod(code); + case 8: + return generateParameterDescriptor(code); + case 9: + break; // Can't cast Unit to IdentifiedObject + default: + throw new AssertionError(index); // Should not happen + } + } + return super.createObject(code); + } + + /** + * Returns an unit from a code. + * + * @param code Value allocated by authority. + * @return The unit object. + * @throws NoSuchAuthorityCodeException if this method can't find the requested code. + * @throws FactoryException if some other kind of failure occured in the backing store. This + * exception usually have {@link SQLException} as its cause. + */ + @Override + public synchronized Unit generateUnit(final String code) throws FactoryException { + ensureNonNull("code", code); + Unit returnValue = null; + try { + final String primaryKey = + toPrimaryKey( + Unit.class, code, "[Unit of Measure]", "UOM_CODE", "UNIT_OF_MEAS_NAME"); + final PreparedStatement stmt = + prepareStatement( + "Unit", + "SELECT UOM_CODE," + + " FACTOR_B," + + " FACTOR_C," + + " TARGET_UOM_CODE" + + " FROM [Unit of Measure]" + + " WHERE UOM_CODE = ?"); + stmt.setString(1, primaryKey); + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final int source = getInt(result, 1, code); + final double b = result.getDouble(2); + final double c = result.getDouble(3); + final int target = getInt(result, 4, code); + final Unit base = getUnit(target); + if (base == null) { + throw noSuchAuthorityCode(Unit.class, String.valueOf(target)); + } + Unit unit = getUnit(source); + if (unit == null) { + // TODO: check unit consistency here. + if (b != 0 && c != 0) { + unit = (b == c) ? base : base.multiply(b / c); + } else { + // TODO: provide a localized message. + throw new FactoryException("Unsupported unit: " + code); + } + } + returnValue = ensureSingleton(unit, returnValue, code); + } + } + } catch (SQLException exception) { + throw databaseFailure(Unit.class, code, exception); + } + if (returnValue == null) { + throw noSuchAuthorityCode(Unit.class, code); + } + return returnValue; + } + + /** + * Returns an ellipsoid from a code. + * + * @param code The EPSG value. + * @return The ellipsoid object. + * @throws NoSuchAuthorityCodeException if this method can't find the requested code. + * @throws FactoryException if some other kind of failure occured in the backing store. This + * exception usually have {@link SQLException} as its cause. + */ + @Override + public synchronized Ellipsoid generateEllipsoid(final String code) throws FactoryException { + ensureNonNull("code", code); + Ellipsoid returnValue = null; + try { + final String primaryKey = + toPrimaryKey( + Ellipsoid.class, + code, + "[Ellipsoid]", + "ELLIPSOID_CODE", + "ELLIPSOID_NAME"); + final PreparedStatement stmt = + prepareStatement( + "Ellipsoid", + "SELECT ELLIPSOID_CODE," + + " ELLIPSOID_NAME," + + " SEMI_MAJOR_AXIS," + + " INV_FLATTENING," + + " SEMI_MINOR_AXIS," + + " UOM_CODE," + + " REMARKS" + + " FROM [Ellipsoid]" + + " WHERE ELLIPSOID_CODE = ?"); + stmt.setString(1, primaryKey); + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + /* + * One of 'semiMinorAxis' and 'inverseFlattening' values can be NULL in + * the database. Consequently, we don't use 'getString(ResultSet, int)' + * because we don't want to thrown an exception if a NULL value is found. + */ + final String epsg = getString(result, 1, code); + final String name = getString(result, 2, code); + final double semiMajorAxis = getDouble(result, 3, code); + final double inverseFlattening = result.getDouble(4); + final double semiMinorAxis = result.getDouble(5); + final String unitCode = getString(result, 6, code); + final String remarks = result.getString(7); + @SuppressWarnings("unchecked") + final Unit unit = (Unit) createUnit(unitCode); + final Map properties = generateProperties(name, epsg, remarks); + final Ellipsoid ellipsoid; + if (inverseFlattening == 0) { + if (semiMinorAxis == 0) { + // Both are null, which is not allowed. + final String column = result.getMetaData().getColumnName(3); + result.close(); + throw new FactoryException( + Errors.format(ErrorKeys.NULL_VALUE_IN_TABLE_$3, code, column)); + } else { + // We only have semiMinorAxis defined -> it's OK + ellipsoid = + factories + .getDatumFactory() + .createEllipsoid( + properties, semiMajorAxis, semiMinorAxis, unit); + } + } else { + if (semiMinorAxis != 0) { + // Both 'inverseFlattening' and 'semiMinorAxis' are defined. + // Log a warning and create the ellipsoid using the inverse flattening. + final LogRecord record = + Loggings.format( + Level.WARNING, LoggingKeys.AMBIGUOUS_ELLIPSOID, code); + record.setLoggerName(LOGGER.getName()); + LOGGER.log(record); + } + ellipsoid = + factories + .getDatumFactory() + .createFlattenedSphere( + properties, semiMajorAxis, inverseFlattening, unit); + } + /* + * Now that we have built an ellipsoid, compare + * it with the previous one (if any). + */ + returnValue = ensureSingleton(ellipsoid, returnValue, code); + } + } + } catch (SQLException exception) { + throw databaseFailure(Ellipsoid.class, code, exception); + } + if (returnValue == null) { + throw noSuchAuthorityCode(Ellipsoid.class, code); + } + return returnValue; + } + + /** + * Returns a prime meridian, relative to Greenwich. + * + * @param code Value allocated by authority. + * @return The prime meridian object. + * @throws NoSuchAuthorityCodeException if this method can't find the requested code. + * @throws FactoryException if some other kind of failure occured in the backing store. This + * exception usually have {@link SQLException} as its cause. + */ + @Override + public synchronized PrimeMeridian generatePrimeMeridian(final String code) + throws FactoryException { + ensureNonNull("code", code); + PrimeMeridian returnValue = null; + try { + final String primaryKey = + toPrimaryKey( + PrimeMeridian.class, + code, + "[Prime Meridian]", + "PRIME_MERIDIAN_CODE", + "PRIME_MERIDIAN_NAME"); + final PreparedStatement stmt = + prepareStatement( + "PrimeMeridian", + "SELECT PRIME_MERIDIAN_CODE," + + " PRIME_MERIDIAN_NAME," + + " GREENWICH_LONGITUDE," + + " UOM_CODE," + + " REMARKS" + + " FROM [Prime Meridian]" + + " WHERE PRIME_MERIDIAN_CODE = ?"); + stmt.setString(1, primaryKey); + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final String epsg = getString(result, 1, code); + final String name = getString(result, 2, code); + final double longitude = getDouble(result, 3, code); + final String unit_code = getString(result, 4, code); + final String remarks = result.getString(5); + @SuppressWarnings("unchecked") + final Unit unit = + (Unit) createUnit(unit_code); + final Map properties = generateProperties(name, epsg, remarks); + PrimeMeridian primeMeridian = + factories + .getDatumFactory() + .createPrimeMeridian(properties, longitude, unit); + returnValue = ensureSingleton(primeMeridian, returnValue, code); + } + } + } catch (SQLException exception) { + throw databaseFailure(PrimeMeridian.class, code, exception); + } + if (returnValue == null) { + throw noSuchAuthorityCode(PrimeMeridian.class, code); + } + return returnValue; + } + + /** + * Returns an area of use. + * + * @param code Value allocated by authority. + * @return The area of use. + * @throws NoSuchAuthorityCodeException if this method can't find the requested code. + * @throws FactoryException if some other kind of failure occured in the backing store. This + * exception usually have {@link SQLException} as its cause. + */ + public synchronized Extent generateExtent(final String code) throws FactoryException { + ensureNonNull("code", code); + Extent returnValue = null; + try { + final String primaryKey = + toPrimaryKey(Extent.class, code, "[Area]", "AREA_CODE", "AREA_NAME"); + final PreparedStatement stmt = + prepareStatement( + "Area", + "SELECT AREA_OF_USE," + + " AREA_SOUTH_BOUND_LAT," + + " AREA_NORTH_BOUND_LAT," + + " AREA_WEST_BOUND_LON," + + " AREA_EAST_BOUND_LON" + + " FROM [Area]" + + " WHERE AREA_CODE = ?"); + stmt.setString(1, primaryKey); + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + ExtentImpl extent = null; + final String description = result.getString(1); + if (description != null) { + extent = new ExtentImpl(); + extent.setDescription(new SimpleInternationalString(description)); + } + final double ymin = result.getDouble(2); + if (!result.wasNull()) { + final double ymax = result.getDouble(3); + if (!result.wasNull()) { + final double xmin = result.getDouble(4); + if (!result.wasNull()) { + final double xmax = result.getDouble(5); + if (!result.wasNull()) { + if (extent == null) { + extent = new ExtentImpl(); + } + extent.setGeographicElements( + Collections.singleton( + new GeographicBoundingBoxImpl( + xmin, xmax, ymin, ymax))); + } + } + } + } + if (extent != null) { + returnValue = + (Extent) ensureSingleton(extent.unmodifiable(), returnValue, code); + } + } + } + } catch (SQLException exception) { + throw databaseFailure(Extent.class, code, exception); + } + if (returnValue == null) { + throw noSuchAuthorityCode(Extent.class, code); + } + return returnValue; + } + + /** + * Returns Bursa-Wolf parameters for a geodetic datum. If the specified datum has no conversion + * informations, then this method will returns {@code null}. + * + * @param code The EPSG code of the {@link GeodeticDatum}. + * @param toClose The result set to close if this method is going to invokes {@link + * #createDatum} recursively. This hack is necessary because many JDBC drivers do not + * support multiple result sets for the same statement. The result set is closed if an only + * if this method returns a non-null value. + * @return an array of Bursa-Wolf parameters (in which case {@code toClose} has been closed), or + * {@code null} (in which case {@code toClose} has not been closed). + */ + private BursaWolfParameters[] generateBursaWolfParameters( + final String code, final ResultSet toClose) throws SQLException, FactoryException { + if (safetyGuard.contains(code)) { + /* + * Do not try to create Bursa-Wolf parameters if the datum is already + * in process of being created. This check avoid never-ending loops in + * recursive call to 'createDatum'. + */ + return null; + } + PreparedStatement stmt = + prepareStatement( + "BursaWolfParametersSet", + "SELECT CO.COORD_OP_CODE," + + " CO.COORD_OP_METHOD_CODE," + + " CRS2.DATUM_CODE" + + " FROM [Coordinate_Operation] AS CO" + + " INNER JOIN [Coordinate Reference System] AS CRS2" + + " ON CO.TARGET_CRS_CODE = CRS2.COORD_REF_SYS_CODE" + + " WHERE CO.COORD_OP_METHOD_CODE >= " + + BURSA_WOLF_MIN_CODE + + " AND CO.COORD_OP_METHOD_CODE <= " + + BURSA_WOLF_MAX_CODE + + " AND CO.COORD_OP_CODE <> " + + DUMMY_OPERATION // GEOT-1008 + + " AND CO.SOURCE_CRS_CODE IN (" + + " SELECT CRS1.COORD_REF_SYS_CODE " // GEOT-1129 + + " FROM [Coordinate Reference System] AS CRS1 " + + " WHERE CRS1.DATUM_CODE = ?)" + + " ORDER BY CRS2.DATUM_CODE," + + " ABS(CO.DEPRECATED), CO.COORD_OP_ACCURACY," + + " CO.COORD_OP_CODE DESC"); // GEOT-846 fix + stmt.setString(1, code); + List bwInfos = null; + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final String operation = getString(result, 1, code); + final int method = getInt(result, 2, code); + final String datum = getString(result, 3, code); + if (bwInfos == null) { + bwInfos = new ArrayList<>(); + } + bwInfos.add(new BursaWolfInfo(operation, method, datum)); + } + } + if (bwInfos == null) { + // Don't close the connection here. + return null; + } + toClose.close(); + /* + * Sorts the infos in preference order. The "ORDER BY" clause above was not enough; + * we also need to take the "supersession" table in account. Once the sorting is done, + * keep only one Bursa-Wolf parameters for each datum. + */ + int size = bwInfos.size(); + if (size > 1) { + final BursaWolfInfo[] codes = bwInfos.toArray(new BursaWolfInfo[size]); + sort(codes); + bwInfos.clear(); + final Set added = new HashSet<>(); + for (final BursaWolfInfo candidate : codes) { + if (added.add(candidate.target)) { + bwInfos.add(candidate); + } + } + size = bwInfos.size(); + } + /* + * We got all the needed informations before to built Bursa-Wolf parameters because the + * 'createDatum(...)' call below may invokes 'createBursaWolfParameters(...)' recursively, + * and not all JDBC drivers supported multi-result set for the same statement. Now, iterate + * throw the results and fetch the parameter values for each BursaWolfParameters object. + */ + stmt = + prepareStatement( + "BursaWolfParameters", + "SELECT PARAMETER_CODE," + + " PARAMETER_VALUE," + + " UOM_CODE" + + " FROM [Coordinate_Operation Parameter Value]" + + " WHERE COORD_OP_CODE = ?" + + " AND COORD_OP_METHOD_CODE = ?"); + for (int i = 0; i < size; i++) { + final BursaWolfInfo info = (BursaWolfInfo) bwInfos.get(i); + final GeodeticDatum datum; + try { + safetyGuard.add(code); + datum = createGeodeticDatum(info.target); + } finally { + safetyGuard.remove(code); + } + final BursaWolfParameters parameters = new BursaWolfParameters(datum); + stmt.setString(1, info.operation); + stmt.setInt(2, info.method); + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + setBursaWolfParameter( + parameters, + getInt(result, 1, info.operation), + getDouble(result, 2, info.operation), + createUnit(getString(result, 3, info.operation))); + } + } + if (info.method == ROTATION_FRAME_CODE) { + // Coordinate frame rotation (9607): same as 9606, + // except for the sign of rotation parameters. + parameters.ex = -parameters.ex; + parameters.ey = -parameters.ey; + parameters.ey = -parameters.ey; + } + bwInfos.set(i, parameters); + } + return bwInfos.toArray(new BursaWolfParameters[size]); + } + + /** + * Returns a datum from a code. + * + * @param code Value allocated by authority. + * @return The datum object. + * @throws NoSuchAuthorityCodeException if this method can't find the requested code. + * @throws FactoryException if some other kind of failure occured in the backing store. This + * exception usually have {@link SQLException} as its cause. + * @todo Current implementation maps all "vertical" datum to {@link VerticalDatumType#GEOIDAL}. + * We don't know yet how to maps the exact vertical datum type from the EPSG database. + */ + @Override + public synchronized Datum generateDatum(final String code) throws FactoryException { + ensureNonNull("code", code); + Datum returnValue = null; + try { + final String primaryKey = + toPrimaryKey(Datum.class, code, "[Datum]", "DATUM_CODE", "DATUM_NAME"); + final PreparedStatement stmt = + prepareStatement( + "Datum", + "SELECT DATUM_CODE," + + " DATUM_NAME," + + " DATUM_TYPE," + + " ORIGIN_DESCRIPTION," + + " REALIZATION_EPOCH," + + " AREA_OF_USE_CODE," + + " DATUM_SCOPE," + + " REMARKS," + + " ELLIPSOID_CODE," // Only for geodetic type + + " PRIME_MERIDIAN_CODE" // Only for geodetic type + + " FROM [Datum]" + + " WHERE DATUM_CODE = ?"); + stmt.setString(1, primaryKey); + try (ResultSet result = stmt.executeQuery()) { + boolean exit = false; + while (result.next()) { + final String epsg = getString(result, 1, code); + final String name = getString(result, 2, code); + final String type = getString(result, 3, code).trim().toLowerCase(); + final String anchor = result.getString(4); + final Date epoch = result.getDate(5); + final String area = result.getString(6); + final String scope = result.getString(7); + final String remarks = result.getString(8); + Map properties = + generateProperties(name, epsg, area, scope, remarks); + if (anchor != null) { + properties.put(Datum.ANCHOR_POINT_KEY, anchor); + } + if (epoch != null) + try { + properties.put(Datum.REALIZATION_EPOCH_KEY, epoch); + } catch (NumberFormatException exception) { + // Not a fatal error... + Logging.unexpectedException( + LOGGER, AbstractEpsgFactory.class, "createDatum", exception); + } + final DatumFactory factory = factories.getDatumFactory(); + final Datum datum; + /* + * Now build datum according their datum type. Constructions are straightforward, + * except for the "geodetic" datum type which need some special processing: + * + * - Because it invokes again 'generateProperties' indirectly (through calls to + * 'createEllipsoid' and 'createPrimeMeridian'), it must protect 'properties' + * from changes. + * + * - Because 'createBursaWolfParameters' may invokes 'createDatum' recursively, + * we must close the result set if Bursa-Wolf parameters are found. In this + * case, we lost our paranoiac check for duplication. + */ + if (type.equals("geodetic")) { + properties = new HashMap<>(properties); // Protect from changes + final Ellipsoid ellipsoid = createEllipsoid(getString(result, 9, code)); + final PrimeMeridian meridian = + createPrimeMeridian(getString(result, 10, code)); + final BursaWolfParameters[] param = + generateBursaWolfParameters(primaryKey, result); + + if (param != null) { + exit = true; + properties.put(DefaultGeodeticDatum.BURSA_WOLF_KEY, param); + } + datum = factory.createGeodeticDatum(properties, ellipsoid, meridian); + } else if (type.equals("vertical")) { + // TODO: Find the right datum type. + datum = factory.createVerticalDatum(properties, VerticalDatumType.GEOIDAL); + } else if (type.equals("engineering")) { + datum = factory.createEngineeringDatum(properties); + } else { + result.close(); + throw new FactoryException(Errors.format(ErrorKeys.UNKNOW_TYPE_$1, type)); + } + returnValue = ensureSingleton(datum, returnValue, code); + if (exit) { + // Bypass the 'result.close()' line below: + // the ResultSet has already been closed. + return returnValue; + } + } + } + } catch (SQLException exception) { + throw databaseFailure(Datum.class, code, exception); + } + if (returnValue == null) { + throw noSuchAuthorityCode(Datum.class, code); + } + return returnValue; + } + + /** + * Returns the name and description for the specified {@linkplain CoordinateSystemAxis + * coordinate system axis} code. Many axis share the same name and description, so it is worth + * to cache them. + */ + private AxisName getAxisName(final String code) throws FactoryException { + assert Thread.holdsLock(this); + AxisName returnValue = axisNames.get(code); + if (returnValue == null) + try { + final PreparedStatement stmt = + prepareStatement( + "AxisName", + "SELECT COORD_AXIS_NAME, DESCRIPTION, REMARKS" + + " FROM [Coordinate Axis Name]" + + " WHERE COORD_AXIS_NAME_CODE = ?"); + stmt.setString(1, code); + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final String name = getString(result, 1, code); + String description = result.getString(2); + String remarks = result.getString(3); + if (description == null) { + description = remarks; + } else if (remarks != null) { + description += System.getProperty("line.separator", "\n") + remarks; + } + final AxisName axis = new AxisName(name, description); + returnValue = ensureSingleton(axis, returnValue, code); + } + } + if (returnValue == null) { + throw noSuchAuthorityCode(AxisName.class, code); + } + axisNames.put(code, returnValue); + } catch (SQLException exception) { + throw databaseFailure(AxisName.class, code, exception); + } + return returnValue; + } + + /** + * Returns a {@linkplain CoordinateSystemAxis coordinate system axis} from a code. + * + * @param code Value allocated by authority. + * @throws NoSuchAuthorityCodeException if the specified {@code code} was not found. + * @throws FactoryException if the object creation failed for some other reason. + */ + @Override + public synchronized CoordinateSystemAxis generateCoordinateSystemAxis(final String code) + throws FactoryException { + ensureNonNull("code", code); + CoordinateSystemAxis returnValue = null; + try { + final PreparedStatement stmt = + prepareStatement( + "Axis", + "SELECT COORD_AXIS_CODE," + + " COORD_AXIS_NAME_CODE," + + " COORD_AXIS_ORIENTATION," + + " COORD_AXIS_ABBREVIATION," + + " UOM_CODE" + + " FROM [Coordinate Axis]" + + " WHERE COORD_AXIS_CODE = ?"); + stmt.setString(1, code); + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final String epsg = getString(result, 1, code); + final String nameCode = getString(result, 2, code); + final String orientation = getString(result, 3, code); + final String abbreviation = getString(result, 4, code); + final String unit = getString(result, 5, code); + AxisDirection direction; + try { + direction = DefaultCoordinateSystemAxis.getDirection(orientation); + } catch (NoSuchElementException exception) { + if (orientation.equalsIgnoreCase("Geocentre > equator/PM")) { + direction = AxisDirection.OTHER; // TODO: can we choose a more accurate + // direction? + } else if (orientation.equalsIgnoreCase("Geocentre > equator/90dE")) { + direction = AxisDirection.EAST; + } else if (orientation.equalsIgnoreCase("Geocentre > north pole")) { + direction = AxisDirection.NORTH; + } else { + throw new FactoryException(exception); + } + } + final AxisName an = getAxisName(nameCode); + final Map properties = + generateProperties(an.name, epsg, an.description); + final CSFactory factory = factories.getCSFactory(); + final CoordinateSystemAxis axis = + factory.createCoordinateSystemAxis( + properties, abbreviation, direction, createUnit(unit)); + returnValue = ensureSingleton(axis, returnValue, code); + } + } + } catch (SQLException exception) { + throw databaseFailure(CoordinateSystemAxis.class, code, exception); + } + if (returnValue == null) { + throw noSuchAuthorityCode(CoordinateSystemAxis.class, code); + } + return returnValue; + } + + /** + * Returns the coordinate system axis from an EPSG code for a {@link CoordinateSystem}. + * + *

WARNING: The EPSG database uses "{@code ORDER}" as a column name. This is + * tolerated by Access, but MySQL doesn't accept this name. + * + * @param code the EPSG code for coordinate system owner. + * @param dimension of the coordinate system, which is also the size of the returned array. + * @return An array of coordinate system axis. + * @throws SQLException if an error occured during database access. + * @throws FactoryException if the code has not been found. + */ + private CoordinateSystemAxis[] generateAxisForCoordinateSystem( + final String code, final int dimension) throws SQLException, FactoryException { + assert Thread.holdsLock(this); + final CoordinateSystemAxis[] axis = new CoordinateSystemAxis[dimension]; + final PreparedStatement stmt = + prepareStatement( + "AxisOrder", + "SELECT COORD_AXIS_CODE" + + " FROM [Coordinate Axis]" + + " WHERE COORD_SYS_CODE = ?" + + " ORDER BY [ORDER]"); + // WARNING: Be careful about the column name : + // MySQL rejects ORDER as a column name !!! + stmt.setString(1, code); + int i = 0; + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final String axisCode = getString(result, 1, code); + if (i < axis.length) { + // If 'i' is out of bounds, an exception will be thrown after the loop. + // We don't want to thrown an ArrayIndexOutOfBoundsException here. + axis[i] = createCoordinateSystemAxis(axisCode); + } + ++i; + } + } + if (i != axis.length) { + throw new FactoryException( + Errors.format(ErrorKeys.MISMATCHED_DIMENSION_$2, axis.length, i)); + } + return axis; + } + + /** + * Returns a coordinate system from a code. + * + * @param code Value allocated by authority. + * @return The coordinate system object. + * @throws NoSuchAuthorityCodeException if this method can't find the requested code. + * @throws FactoryException if some other kind of failure occured in the backing store. This + * exception usually have {@link SQLException} as its cause. + */ + @Override + public synchronized CoordinateSystem generateCoordinateSystem(final String code) + throws FactoryException { + ensureNonNull("code", code); + CoordinateSystem returnValue = null; + final PreparedStatement stmt; + try { + final String primaryKey = + toPrimaryKey( + CoordinateSystem.class, + code, + "[Coordinate System]", + "COORD_SYS_CODE", + "COORD_SYS_NAME"); + stmt = + prepareStatement( + "CoordinateSystem", + "SELECT COORD_SYS_CODE," + + " COORD_SYS_NAME," + + " COORD_SYS_TYPE," + + " DIMENSION," + + " REMARKS" + + " FROM [Coordinate System]" + + " WHERE COORD_SYS_CODE = ?"); + stmt.setString(1, primaryKey); + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final String epsg = getString(result, 1, code); + final String name = getString(result, 2, code); + final String type = getString(result, 3, code).trim().toLowerCase(); + final int dimension = getInt(result, 4, code); + final String remarks = result.getString(5); + final CoordinateSystemAxis[] axis = + generateAxisForCoordinateSystem(primaryKey, dimension); + final Map properties = + generateProperties(name, epsg, remarks); // Must be after axis + final CSFactory factory = factories.getCSFactory(); + CoordinateSystem cs = null; + if (type.equals("ellipsoidal")) { + switch (dimension) { + case 2: + cs = factory.createEllipsoidalCS(properties, axis[0], axis[1]); + break; + case 3: + cs = + factory.createEllipsoidalCS( + properties, axis[0], axis[1], axis[2]); + break; + } + } else if (type.equals("cartesian")) { + switch (dimension) { + case 2: + cs = factory.createCartesianCS(properties, axis[0], axis[1]); + break; + case 3: + cs = + factory.createCartesianCS( + properties, axis[0], axis[1], axis[2]); + break; + } + } else if (type.equals("spherical")) { + switch (dimension) { + case 3: + cs = + factory.createSphericalCS( + properties, axis[0], axis[1], axis[2]); + break; + } + } else if (type.equals("vertical") || type.equals("gravity-related")) { + switch (dimension) { + case 1: + cs = factory.createVerticalCS(properties, axis[0]); + break; + } + } else if (type.equals("linear")) { + switch (dimension) { + case 1: + cs = factory.createLinearCS(properties, axis[0]); + break; + } + } else if (type.equals("polar")) { + switch (dimension) { + case 2: + cs = factory.createPolarCS(properties, axis[0], axis[1]); + break; + } + } else if (type.equals("cylindrical")) { + switch (dimension) { + case 3: + cs = + factory.createCylindricalCS( + properties, axis[0], axis[1], axis[2]); + break; + } + } else if (type.equals("affine")) { + switch (dimension) { + case 2: + cs = factory.createAffineCS(properties, axis[0], axis[1]); + break; + case 3: + cs = factory.createAffineCS(properties, axis[0], axis[1], axis[2]); + break; + } + } else { + result.close(); + throw new FactoryException(Errors.format(ErrorKeys.UNKNOW_TYPE_$1, type)); + } + if (cs == null) { + result.close(); + throw new FactoryException( + Errors.format(ErrorKeys.UNEXPECTED_DIMENSION_FOR_CS_$1, type)); + } + returnValue = ensureSingleton(cs, returnValue, code); + } + } + } catch (SQLException exception) { + throw databaseFailure(CoordinateSystem.class, code, exception); + } + if (returnValue == null) { + throw noSuchAuthorityCode(CoordinateSystem.class, code); + } + return returnValue; + } + + /** + * Returns the primary key for a coordinate reference system name. This method is used both by + * {@link #createCoordinateReferenceSystem} and {@link + * #createFromCoordinateReferenceSystemCodes} + */ + private String toPrimaryKeyCRS(final String code) throws SQLException, FactoryException { + return toPrimaryKey( + CoordinateReferenceSystem.class, + code, + "[Coordinate Reference System]", + "COORD_REF_SYS_CODE", + "COORD_REF_SYS_NAME"); + } + + /** + * Returns a coordinate reference system from a code. + * + * @param code Value allocated by authority. + * @return The coordinate reference system object. + * @throws NoSuchAuthorityCodeException if this method can't find the requested code. + * @throws FactoryException if some other kind of failure occured in the backing store. This + * exception usually have {@link SQLException} as its cause. + */ + @Override + public synchronized CoordinateReferenceSystem generateCoordinateReferenceSystem( + final String code) throws FactoryException { + ensureNonNull("code", code); + CoordinateReferenceSystem returnValue = null; + try { + final String primaryKey = toPrimaryKeyCRS(code); + final PreparedStatement stmt = + prepareStatement( + "CoordinateReferenceSystem", + "SELECT COORD_REF_SYS_CODE," + + " COORD_REF_SYS_NAME," + + " AREA_OF_USE_CODE," + + " CRS_SCOPE," + + " REMARKS," + + " COORD_REF_SYS_KIND," + + " COORD_SYS_CODE," // Null for CompoundCRS + + " DATUM_CODE," // Null for ProjectedCRS + + " SOURCE_GEOGCRS_CODE," // For ProjectedCRS + + " PROJECTION_CONV_CODE," // For ProjectedCRS + + " CMPD_HORIZCRS_CODE," // For CompoundCRS only + + " CMPD_VERTCRS_CODE" // For CompoundCRS only + + " FROM [Coordinate Reference System]" + + " WHERE COORD_REF_SYS_CODE = ?"); + stmt.setString(1, primaryKey); + boolean exit = false; + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final String epsg = getString(result, 1, code); + final String name = getString(result, 2, code); + final String area = result.getString(3); + final String scope = result.getString(4); + final String remarks = result.getString(5); + final String type = getString(result, 6, code); + // Note: Do not invoke 'generateProperties' now, even if we have all required + // informations, because the 'properties' map is going to overwritten + // by calls to 'createDatum', 'createCoordinateSystem', etc. + final CRSFactory factory = factories.getCRSFactory(); + final CoordinateReferenceSystem crs; + /* ---------------------------------------------------------------------- + * GEOGRAPHIC CRS + * + * NOTE: 'generateProperties' MUST be invoked after any call to an other + * 'createFoo' method. Consequently, do not factor out. + * ---------------------------------------------------------------------- */ + if (type.equalsIgnoreCase("geographic 2D") + || type.equalsIgnoreCase("geographic 3D")) { + final String csCode = getString(result, 7, code); + final String dmCode = result.getString(8); + final EllipsoidalCS cs = createEllipsoidalCS(csCode); + final GeodeticDatum datum; + if (dmCode != null) { + datum = createGeodeticDatum(dmCode); + } else { + final String geoCode = getString(result, 9, code, 8); + result.close(); // Must be close before createGeographicCRS + exit = true; + final GeographicCRS baseCRS = createGeographicCRS(geoCode); + datum = baseCRS.getDatum(); + } + final Map properties = + generateProperties(name, epsg, area, scope, remarks); + crs = factory.createGeographicCRS(properties, datum, cs); + } + /* ---------------------------------------------------------------------- + * PROJECTED CRS + * + * NOTE: This method invokes itself indirectly, through createGeographicCRS. + * Consequently, we can't use 'result' anymore. We must close it here. + * ---------------------------------------------------------------------- */ + else if (type.equalsIgnoreCase("projected")) { + final String csCode = getString(result, 7, code); + final String geoCode = getString(result, 9, code); + final String opCode = getString(result, 10, code); + result.close(); // Must be close before createGeographicCRS + exit = true; + final CartesianCS cs = createCartesianCS(csCode); + final GeographicCRS baseCRS = createGeographicCRS(geoCode); + final CoordinateOperation op = createCoordinateOperation(opCode); + if (op instanceof Conversion) { + final Map properties = + generateProperties(name, epsg, area, scope, remarks); + crs = + factory.createProjectedCRS( + properties, baseCRS, (Conversion) op, cs); + } else { + throw noSuchAuthorityCode(Projection.class, opCode); + } + } + /* ---------------------------------------------------------------------- + * VERTICAL CRS + * ---------------------------------------------------------------------- */ + else if (type.equalsIgnoreCase("vertical")) { + final String csCode = getString(result, 7, code); + final String dmCode = getString(result, 8, code); + final VerticalCS cs = createVerticalCS(csCode); + final VerticalDatum datum = createVerticalDatum(dmCode); + final Map properties = + generateProperties(name, epsg, area, scope, remarks); + crs = factory.createVerticalCRS(properties, datum, cs); + } + /* ---------------------------------------------------------------------- + * COMPOUND CRS + * + * NOTE: This method invokes itself recursively. + * Consequently, we can't use 'result' anymore. + * ---------------------------------------------------------------------- */ + else if (type.equalsIgnoreCase("compound")) { + final String code1 = getString(result, 11, code); + final String code2 = getString(result, 12, code); + result.close(); + exit = true; + final CoordinateReferenceSystem crs1, crs2; + if (!safetyGuard.add(epsg)) { + throw recursiveCall(CompoundCRS.class, epsg); + } + try { + crs1 = createCoordinateReferenceSystem(code1); + crs2 = createCoordinateReferenceSystem(code2); + } finally { + safetyGuard.remove(epsg); + } + // Note: Don't invoke 'generateProperties' sooner. + final Map properties = + generateProperties(name, epsg, area, scope, remarks); + crs = factory.createCompoundCRS(properties, crs1, crs2); + } + /* ---------------------------------------------------------------------- + * GEOCENTRIC CRS + * ---------------------------------------------------------------------- */ + else if (type.equalsIgnoreCase("geocentric")) { + final String csCode = getString(result, 7, code); + final String dmCode = getString(result, 8, code); + final CoordinateSystem cs = createCoordinateSystem(csCode); + final GeodeticDatum datum = createGeodeticDatum(dmCode); + final Map properties = + generateProperties(name, epsg, area, scope, remarks); + if (cs instanceof CartesianCS) { + crs = factory.createGeocentricCRS(properties, datum, (CartesianCS) cs); + } else if (cs instanceof SphericalCS) { + crs = factory.createGeocentricCRS(properties, datum, (SphericalCS) cs); + } else { + result.close(); + throw new FactoryException( + Errors.format( + ErrorKeys.ILLEGAL_COORDINATE_SYSTEM_FOR_CRS_$2, + cs.getClass(), + GeocentricCRS.class)); + } + } + /* ---------------------------------------------------------------------- + * ENGINEERING CRS + * ---------------------------------------------------------------------- */ + else if (type.equalsIgnoreCase("engineering")) { + final String csCode = getString(result, 7, code); + final String dmCode = getString(result, 8, code); + final CoordinateSystem cs = createCoordinateSystem(csCode); + final EngineeringDatum datum = createEngineeringDatum(dmCode); + final Map properties = + generateProperties(name, epsg, area, scope, remarks); + crs = factory.createEngineeringCRS(properties, datum, cs); + } + /* ---------------------------------------------------------------------- + * UNKNOW CRS + * ---------------------------------------------------------------------- */ + else { + result.close(); + throw new FactoryException(Errors.format(ErrorKeys.UNKNOW_TYPE_$1, type)); + } + returnValue = ensureSingleton(crs, returnValue, code); + if (exit) { + // Bypass the 'result.close()' line below: + // the ResultSet has already been closed. + return returnValue; + } + } + } + } catch (SQLException exception) { + throw databaseFailure(CoordinateReferenceSystem.class, code, exception); + } + if (returnValue == null) { + throw noSuchAuthorityCode(CoordinateReferenceSystem.class, code); + } + return returnValue; + } + + /** + * Returns a parameter descriptor from a code. + * + * @param code The parameter descriptor code allocated by EPSG authority. + * @throws NoSuchAuthorityCodeException if this method can't find the requested code. + * @throws FactoryException if some other kind of failure occured in the backing store. This + * exception usually have {@link SQLException} as its cause. + */ + public synchronized ParameterDescriptor generateParameterDescriptor(final String code) + throws FactoryException { + ensureNonNull("code", code); + ParameterDescriptor returnValue = null; + final PreparedStatement stmt; + try { + final String primaryKey = + toPrimaryKey( + ParameterDescriptor.class, + code, + "[Coordinate_Operation Parameter]", + "PARAMETER_CODE", + "PARAMETER_NAME"); + stmt = + prepareStatement( + "ParameterDescriptor", // Must be singular form. + "SELECT PARAMETER_CODE," + + " PARAMETER_NAME," + + " DESCRIPTION" + + " FROM [Coordinate_Operation Parameter]" + + " WHERE PARAMETER_CODE = ?"); + stmt.setString(1, primaryKey); + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final String epsg = getString(result, 1, code); + final String name = getString(result, 2, code); + final String remarks = result.getString(3); + final Unit unit; + final Class type; + /* + * Search for units. We will choose the most commonly used one in parameter values. + * If the parameter appears to have at least one non-null value in the "Parameter + * File Name" column, then the type is assumed to be URI. Otherwise, the type is a + * floating point number. + */ + final PreparedStatement units = + prepareStatement( + "ParameterUnit", + "SELECT MIN(UOM_CODE) AS UOM," + + " MIN(PARAM_VALUE_FILE_REF) AS FILEREF" + + " FROM [Coordinate_Operation Parameter Value]" + + " WHERE (PARAMETER_CODE = ?)" + + " GROUP BY UOM_CODE" + + " ORDER BY COUNT(UOM_CODE) DESC"); + units.setString(1, epsg); + try (final ResultSet resultUnits = units.executeQuery()) { + if (resultUnits.next()) { + String element = resultUnits.getString(1); + unit = (element != null) ? createUnit(element) : null; + element = resultUnits.getString(2); + type = + (element != null && element.trim().length() != 0) + ? URI.class + : double.class; + } else { + unit = null; + type = double.class; + } + } + /* + * Now creates the parameter descriptor. + */ + final Map properties = generateProperties(name, epsg, remarks); + @SuppressWarnings("unchecked") + final ParameterDescriptor descriptor = + new DefaultParameterDescriptor( + properties, type, null, null, null, null, unit, true); + returnValue = ensureSingleton(descriptor, returnValue, code); + } + } + } catch (SQLException exception) { + throw databaseFailure(OperationMethod.class, code, exception); + } + if (returnValue == null) { + throw noSuchAuthorityCode(OperationMethod.class, code); + } + return returnValue; + } + + /** + * Returns all parameter descriptors for the specified method. + * + * @param method The operation method code. + * @return The parameter descriptors. + * @throws SQLException if a SQL statement failed. + */ + private ParameterDescriptor[] generateParameterDescriptors(final String method) + throws FactoryException, SQLException { + final PreparedStatement stmt = + prepareStatement( + "ParameterDescriptors", // Must be plural form. + "SELECT PARAMETER_CODE" + + " FROM [Coordinate_Operation Parameter Usage]" + + " WHERE COORD_OP_METHOD_CODE = ?" + + " ORDER BY SORT_ORDER"); + stmt.setString(1, method); + try (ResultSet results = stmt.executeQuery()) { + final List> descriptors = new ArrayList<>(); + while (results.next()) { + final String param = getString(results, 1, method); + descriptors.add(generateParameterDescriptor(param)); + } + return descriptors.toArray(new ParameterDescriptor[descriptors.size()]); + } + } + + /** + * Fill parameter values in the specified group. + * + * @param method The EPSG code for the operation method. + * @param operation The EPSG code for the operation (conversion or transformation). + * @param parameters The parameter values to fill. + * @throws SQLException if a SQL statement failed. + */ + private void fillParameterValues( + final String method, final String operation, final ParameterValueGroup parameters) + throws FactoryException, SQLException { + final PreparedStatement stmt = + prepareStatement( + "ParameterValues", + "SELECT CP.PARAMETER_NAME," + + " CV.PARAMETER_VALUE," + + " CV.PARAM_VALUE_FILE_REF," + + " CV.UOM_CODE" + + " FROM ([Coordinate_Operation Parameter Value] AS CV" + + " INNER JOIN [Coordinate_Operation Parameter] AS CP" + + " ON CV.PARAMETER_CODE = CP.PARAMETER_CODE)" + + " INNER JOIN [Coordinate_Operation Parameter Usage] AS CU" + + " ON (CP.PARAMETER_CODE = CU.PARAMETER_CODE)" + + " AND (CV.COORD_OP_METHOD_CODE = CU.COORD_OP_METHOD_CODE)" + + " WHERE CV.COORD_OP_METHOD_CODE = ?" + + " AND CV.COORD_OP_CODE = ?" + + " ORDER BY CU.SORT_ORDER"); + stmt.setString(1, method); + stmt.setString(2, operation); + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final String name = getString(result, 1, operation); + final double value = result.getDouble(2); + final Unit unit; + Object reference; + if (result.wasNull()) { + /* + * If no numeric values were provided in the database, then the values must + * appears in some external file. It may be a file to download from FTP. + */ + reference = getString(result, 3, operation); + try { + reference = new URI((String) reference); + } catch (URISyntaxException exception) { + // Ignore: we will stores the reference as a file. + reference = new File((String) reference); + } + unit = null; + } else { + reference = null; + final String unitCode = result.getString(4); + unit = (unitCode != null) ? createUnit(unitCode) : null; + } + final ParameterValue param; + try { + param = parameters.parameter(name); + } catch (ParameterNotFoundException exception) { + /* + * Wraps the unchecked ParameterNotFoundException into the checked + * NoSuchIdentifierException, which is a FactoryException subclass. + * Note that in theory, NoSuchIdentifierException is for MathTransforms rather + * than parameters. However, we are close in spirit here since we are setting + * up MathTransform's parameters. Using NoSuchIdentifierException allows users + * (including CoordinateOperationSet) to know that the failure is probably + * caused by a MathTransform not yet supported in Geotools (or only partially + * supported) rather than some more serious failure in the database side. + * CoordinateOperationSet uses this information in order to determine if it + * should try the next coordinate operation or propagate the exception. + */ + final NoSuchIdentifierException e = + new NoSuchIdentifierException( + Errors.format(ErrorKeys.CANT_SET_PARAMETER_VALUE_$1, name), + name); + e.initCause(exception); + throw e; + } + try { + if (reference != null) { + param.setValue(reference); + } else if (unit != null) { + param.setValue(value, unit); + } else { + param.setValue(value); + } + } catch (InvalidParameterValueException exception) { + throw new FactoryException( + Errors.format(ErrorKeys.CANT_SET_PARAMETER_VALUE_$1, name), exception); + } + } + } + } + + /** + * Returns an operation method from a code. + * + * @param code The operation method code allocated by EPSG authority. + * @throws NoSuchAuthorityCodeException if this method can't find the requested code. + * @throws FactoryException if some other kind of failure occured in the backing store. This + * exception usually have {@link SQLException} as its cause. + */ + public synchronized OperationMethod generateOperationMethod(final String code) + throws FactoryException { + ensureNonNull("code", code); + OperationMethod returnValue = null; + final PreparedStatement stmt; + try { + final String primaryKey = + toPrimaryKey( + OperationMethod.class, + code, + "[Coordinate_Operation Method]", + "COORD_OP_METHOD_CODE", + "COORD_OP_METHOD_NAME"); + stmt = + prepareStatement( + "OperationMethod", + "SELECT COORD_OP_METHOD_CODE," + + " COORD_OP_METHOD_NAME," + + " FORMULA," + + " REMARKS" + + " FROM [Coordinate_Operation Method]" + + " WHERE COORD_OP_METHOD_CODE = ?"); + stmt.setString(1, primaryKey); + try (ResultSet result = stmt.executeQuery()) { + OperationMethod method = null; + while (result.next()) { + final String epsg = getString(result, 1, code); + final String name = getString(result, 2, code); + final String formula = result.getString(3); + final String remarks = result.getString(4); + final int encoded = getDimensionsForMethod(epsg); + final int sourceDimensions = encoded >>> 16; + final int targetDimensions = encoded & 0xFFFF; + final ParameterDescriptor[] descriptors = generateParameterDescriptors(epsg); + final Map properties = generateProperties(name, epsg, remarks); + if (formula != null) { + properties.put(OperationMethod.FORMULA_KEY, formula); + } + method = + new DefaultOperationMethod( + properties, + sourceDimensions, + targetDimensions, + new DefaultParameterDescriptorGroup(properties, descriptors)); + returnValue = ensureSingleton(method, returnValue, code); + } + } + } catch (SQLException exception) { + throw databaseFailure(OperationMethod.class, code, exception); + } + if (returnValue == null) { + throw noSuchAuthorityCode(OperationMethod.class, code); + } + return returnValue; + } + + /** + * Returns the must common source and target dimensions for the specified method. Source + * dimension is encoded in the 16 highest bits and target dimension is encoded in the 16 lowest + * bits. If this method can't infers the dimensions from the "Coordinate Operation" table, then + * the operation method is probably a projection, which always have (2,2) dimensions in the EPSG + * database. + */ + private int getDimensionsForMethod(final String code) throws SQLException { + final PreparedStatement stmt = + prepareStatement( + "MethodDimensions", + "SELECT SOURCE_CRS_CODE," + + " TARGET_CRS_CODE" + + " FROM [Coordinate_Operation]" + + " WHERE COORD_OP_METHOD_CODE = ?" + + " AND SOURCE_CRS_CODE IS NOT NULL" + + " AND TARGET_CRS_CODE IS NOT NULL"); + stmt.setString(1, code); + final Map dimensions = new HashMap<>(); + final Dimensions temp = new Dimensions((2 << 16) | 2); // Default to (2,2) dimensions. + Dimensions max = temp; + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final short sourceDimensions = getDimensionForCRS(result.getString(1)); + final short targetDimensions = getDimensionForCRS(result.getString(2)); + temp.encoded = (sourceDimensions << 16) | (targetDimensions); + Dimensions candidate = dimensions.get(temp); + if (candidate == null) { + candidate = new Dimensions(temp.encoded); + dimensions.put(candidate, candidate); + } + if (++candidate.occurences > max.occurences) { + max = candidate; + } + } + } + return max.encoded; + } + + /** A counter for source and target dimensions (to be kept together). */ + private static final class Dimensions { + /** The dimensions as an encoded value. */ + int encoded; + /** The occurences of this dimensions. */ + int occurences; + + Dimensions(final int e) { + encoded = e; + } + + @Override + public int hashCode() { + return encoded; + } + + @Override + public boolean equals(final Object object) { // MUST ignore 'occurences'. + return (object instanceof Dimensions) && ((Dimensions) object).encoded == encoded; + } + + @Override + public String toString() { + return "[(" + + (encoded >>> 16) + + ',' + + (encoded & 0xFFFF) + + ")\u00D7" + + occurences + + ']'; + } + } + + /** + * Returns the dimension of the specified CRS. If the CRS is not found (which should not happen, + * but we don't need to be strict here), then this method assumes a two-dimensional CRS. + */ + private short getDimensionForCRS(final String code) throws SQLException { + final PreparedStatement stmt; + final Short cached = axisCounts.get(code); + final short dimension; + if (cached == null) { + stmt = + prepareStatement( + "Dimension", + " SELECT COUNT(COORD_AXIS_CODE)" + + " FROM [Coordinate Axis]" + + " WHERE COORD_SYS_CODE = (SELECT COORD_SYS_CODE " + + " FROM [Coordinate Reference System]" + + " WHERE COORD_REF_SYS_CODE = ?)"); + stmt.setString(1, code); + try (ResultSet result = stmt.executeQuery()) { + dimension = result.next() ? result.getShort(1) : 2; + axisCounts.put(code, dimension); + } + } else { + dimension = cached.shortValue(); + } + return dimension; + } + + /** + * Returns {@code true} if the {@linkplain CoordinateOperation coordinate operation} for the + * specified code is a {@linkplain Projection projection}. The caller must have ensured that the + * designed operation is a {@linkplain Conversion conversion} before to invoke this method. + */ + final synchronized boolean isProjection(final String code) throws SQLException { + final PreparedStatement stmt; + Boolean projection = codeProjection.get(code); + if (projection == null) { + stmt = + prepareStatement( + "isProjection", + "SELECT COORD_REF_SYS_CODE" + + " FROM [Coordinate Reference System]" + + " WHERE PROJECTION_CONV_CODE = ?" + + " AND COORD_REF_SYS_KIND LIKE 'projected%'"); + stmt.setString(1, code); + try (ResultSet result = stmt.executeQuery()) { + final boolean found = result.next(); + projection = Boolean.valueOf(found); + codeProjection.put(code, projection); + } + } + return projection.booleanValue(); + } + + /** + * Returns a coordinate operation from a code. The returned object will either be a {@linkplain + * Conversion conversion} or a {@linkplain Transformation transformation}, depending on the + * code. + * + * @param code Value allocated by authority. + * @return The coordinate operation object. + * @throws NoSuchAuthorityCodeException if this method can't find the requested code. + * @throws FactoryException if some other kind of failure occured in the backing store. This + * exception usually have {@link SQLException} as its cause. + */ + @Override + public synchronized CoordinateOperation generateCoordinateOperation(final String code) + throws FactoryException { + ensureNonNull("code", code); + CoordinateOperation returnValue = null; + try { + final String primaryKey = + toPrimaryKey( + CoordinateOperation.class, + code, + "[Coordinate_Operation]", + "COORD_OP_CODE", + "COORD_OP_NAME"); + final PreparedStatement stmt = + prepareStatement( + "CoordinateOperation", + "SELECT COORD_OP_CODE," + + " COORD_OP_NAME," + + " COORD_OP_TYPE," + + " SOURCE_CRS_CODE," + + " TARGET_CRS_CODE," + + " COORD_OP_METHOD_CODE," + + " COORD_TFM_VERSION," + + " COORD_OP_ACCURACY," + + " AREA_OF_USE_CODE," + + " COORD_OP_SCOPE," + + " REMARKS" + + " FROM [Coordinate_Operation]" + + " WHERE COORD_OP_CODE = ?"); + stmt.setString(1, primaryKey); + boolean exit = false; + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final String epsg = getString(result, 1, code); + final String name = getString(result, 2, code); + final String type = getString(result, 3, code).trim().toLowerCase(); + final boolean isTransformation = type.equals("transformation"); + final boolean isConversion = type.equals("conversion"); + final boolean isConcatenated = type.equals("concatenated operation"); + final String sourceCode, targetCode, methodCode; + if (isConversion) { + // Optional for conversions, mandatory for all others. + sourceCode = result.getString(4); + targetCode = result.getString(5); + } else { + sourceCode = getString(result, 4, code); + targetCode = getString(result, 5, code); + } + if (isConcatenated) { + // Not applicable to concatenated operation, mandatory for all others. + methodCode = result.getString(6); + } else { + methodCode = getString(result, 6, code); + } + String version = result.getString(7); + double accuracy = result.getDouble(8); + if (result.wasNull()) accuracy = Double.NaN; + String area = result.getString(9); + String scope = result.getString(10); + String remarks = result.getString(11); + /* + * Gets the source and target CRS. They are mandatory for transformations (it + * was checked above in this method) and optional for conversions. Conversions + * are usually "defining conversions" and don't define source and target CRS. + * In EPSG database 6.7, all defining conversions are projections and their + * dimensions are always 2. However, this is not generalizable to other kind + * of operation methods. For example the "Geocentric translation" operation + * method has 3-dimensional source and target. + */ + final int sourceDimensions, targetDimensions; + final CoordinateReferenceSystem sourceCRS, targetCRS; + if (sourceCode != null) { + sourceCRS = createCoordinateReferenceSystem(sourceCode); + sourceDimensions = sourceCRS.getCoordinateSystem().getDimension(); + } else { + sourceCRS = null; + sourceDimensions = 2; // Acceptable default for projections only. + } + if (targetCode != null) { + targetCRS = createCoordinateReferenceSystem(targetCode); + targetDimensions = targetCRS.getCoordinateSystem().getDimension(); + } else { + targetCRS = null; + targetDimensions = 2; // Acceptable default for projections only. + } + /* + * Gets the operation method. This is mandatory for conversions and transformations + * (it was checked above in this method) but optional for concatenated operations. + * Fetching parameter values is part of this block. + */ + final boolean isBursaWolf; + OperationMethod method; + final ParameterValueGroup parameters; + if (methodCode == null) { + isBursaWolf = false; + method = null; + parameters = null; + } else { + final int num; + try { + num = Integer.parseInt(methodCode); + } catch (NumberFormatException exception) { + result.close(); + throw new FactoryException(exception); + } + isBursaWolf = (num >= BURSA_WOLF_MIN_CODE && num <= BURSA_WOLF_MAX_CODE); + // Reminder: The source and target dimensions MUST be computed when + // the information is available. Dimension is not always 2!! + method = generateOperationMethod(methodCode); + if (method.getSourceDimensions() != sourceDimensions + || method.getTargetDimensions() != targetDimensions) { + method = + new DefaultOperationMethod( + method, sourceDimensions, targetDimensions); + } + /* + * Note that some parameters required for MathTransform creation are implicit in + * the EPSG database (e.g. semi-major and semi-minor axis length in the case of + * map projections). We ask the parameter value group straight from the math + * transform factory instead of from the operation method in order to get all + * required parameter descriptors, including implicit ones. + */ + final String classe = method.getName().getCode(); + parameters = + factories.getMathTransformFactory().getDefaultParameters(classe); + fillParameterValues(methodCode, epsg, parameters); + } + /* + * Creates common properties. The 'version' and 'accuracy' are usually defined + * for transformations only. However, we check them for all kind of operations + * (including conversions) and copy the information inconditionnaly if present. + * + * NOTE: This block must be executed last before object creations below, because + * methods like createCoordinateReferenceSystem and createOperationMethod + * overwrite the properties map. + */ + final Map properties = + generateProperties(name, epsg, area, scope, remarks); + if (version != null && (version = version.trim()).length() != 0) { + properties.put(CoordinateOperation.OPERATION_VERSION_KEY, version); + } + if (!Double.isNaN(accuracy)) { + final QuantitativeResultImpl accuracyResult = + new QuantitativeResultImpl(new double[] {accuracy}); + // TODO: Need to invoke something equivalent to: + // accuracyResult.setValueType(Float.class); + // This is the type declared in the MS-Access database. + accuracyResult.setValueUnit( + SI.METRE); // In meters by definition in the EPSG database. + final AbsoluteExternalPositionalAccuracyImpl accuracyElement = + new AbsoluteExternalPositionalAccuracyImpl(accuracyResult); + accuracyElement.setMeasureDescription(TRANSFORMATION_ACCURACY); + accuracyElement.setEvaluationMethodType( + EvaluationMethodType.DIRECT_EXTERNAL); + properties.put( + CoordinateOperation.COORDINATE_OPERATION_ACCURACY_KEY, + new PositionalAccuracy[] { + (PositionalAccuracy) accuracyElement.unmodifiable() + }); + } + /* + * Creates the operation. Conversions should be the only operations allowed to + * have null source and target CRS. In such case, the operation is a defining + * conversion (usually to be used later as part of a ProjectedCRS creation), + * and always a projection in the specific case of the EPSG database (which + * allowed us to assume 2-dimensional operation method in the code above for + * this specific case - not to be generalized to the whole EPSG database). + */ + final CoordinateOperation operation; + if (isConversion && (sourceCRS == null || targetCRS == null)) { + // Note: we usually can't resolve sourceCRS and targetCRS because there + // is many of them for the same coordinate operation (projection) code. + operation = new DefiningConversion(properties, method, parameters); + } else if (isConcatenated) { + /* + * Concatenated operation: we need to close the current result set, because + * we are going to invoke this method recursively in the following lines. + * + * Note: we instantiate directly the Geotools's implementation of + * ConcatenatedOperation instead of using CoordinateOperationFactory in order + * to avoid loading the quite large Geotools's implementation of this factory, + * and also because it is not part of FactoryGroup anyway. + */ + result.close(); + exit = true; + final PreparedStatement cstmt = + prepareStatement( + "ConcatenatedOperation", + "SELECT SINGLE_OPERATION_CODE" + + " FROM [Coordinate_Operation Path]" + + " WHERE (CONCAT_OPERATION_CODE = ?)" + + " ORDER BY OP_PATH_STEP"); + cstmt.setString(1, epsg); + final List codes = new ArrayList<>(); + try (ResultSet cr = cstmt.executeQuery()) { + while (cr.next()) { + codes.add(cr.getString(1)); + } + } + final CoordinateOperation[] operations = + new CoordinateOperation[codes.size()]; + if (!safetyGuard.add(epsg)) { + throw recursiveCall(ConcatenatedOperation.class, epsg); + } + try { + for (int i = 0; i < operations.length; i++) { + operations[i] = createCoordinateOperation(codes.get(i)); + } + } finally { + safetyGuard.remove(epsg); + } + try { + return new DefaultConcatenatedOperation(properties, operations); + } catch (IllegalArgumentException exception) { + // May happen if there is less than 2 operations to concatenate. + // It happen for some deprecated CRS like 8658 for example. + throw new FactoryException(exception); + } + } else { + /* + * Needs to create a math transform. A special processing is performed for + * datum shift methods, since the conversion from ellipsoid to geocentric + * for "geocentric translations" is implicit in the EPSG database. Even in + * the case of Molodenski transforms, the axis length to set are the same. + */ + if (isBursaWolf) + try { + Ellipsoid ellipsoid = CRSUtilities.getHeadGeoEllipsoid(sourceCRS); + if (ellipsoid != null) { + final Unit axisUnit = ellipsoid.getAxisUnit(); + parameters + .parameter("src_semi_major") + .setValue(ellipsoid.getSemiMajorAxis(), axisUnit); + parameters + .parameter("src_semi_minor") + .setValue(ellipsoid.getSemiMinorAxis(), axisUnit); + parameters + .parameter("src_dim") + .setValue( + sourceCRS.getCoordinateSystem().getDimension()); + } + ellipsoid = CRSUtilities.getHeadGeoEllipsoid(targetCRS); + if (ellipsoid != null) { + final Unit axisUnit = ellipsoid.getAxisUnit(); + parameters + .parameter("tgt_semi_major") + .setValue(ellipsoid.getSemiMajorAxis(), axisUnit); + parameters + .parameter("tgt_semi_minor") + .setValue(ellipsoid.getSemiMinorAxis(), axisUnit); + parameters + .parameter("tgt_dim") + .setValue( + targetCRS.getCoordinateSystem().getDimension()); + } + } catch (ParameterNotFoundException exception) { + result.close(); + throw new FactoryException( + Errors.format( + ErrorKeys.GEOTOOLS_EXTENSION_REQUIRED_$1, + method.getName().getCode(), + exception)); + } + /* + * At this stage, the parameters are ready for use. Creates the math transform + * and wraps it in the final operation (a Conversion or a Transformation). + */ + final Class expected; + if (isTransformation) { + expected = Transformation.class; + } else if (isConversion) { + expected = Conversion.class; + } else { + result.close(); + throw new FactoryException( + Errors.format(ErrorKeys.UNKNOW_TYPE_$1, type)); + } + final MathTransform mt = + factories + .getMathTransformFactory() + .createBaseToDerived( + sourceCRS, + parameters, + targetCRS.getCoordinateSystem()); + // TODO: uses GeoAPI factory method once available. + operation = + DefaultOperation.create( + properties, sourceCRS, targetCRS, mt, method, expected); + } + returnValue = ensureSingleton(operation, returnValue, code); + if (exit) { + // Bypass the 'result.close()' line below: + // the ResultSet has already been closed. + return returnValue; + } + } + } + } catch (SQLException exception) { + throw databaseFailure(CoordinateOperation.class, code, exception); + } + if (returnValue == null) { + throw noSuchAuthorityCode(CoordinateOperation.class, code); + } + return returnValue; + } + + /** + * Creates operations from coordinate reference system codes. The returned set is ordered with + * the most accurate operations first. + * + * @param sourceCode Coded value of source coordinate reference system. + * @param targetCode Coded value of target coordinate reference system. + * @throws FactoryException if the object creation failed. + * @todo The ordering is not consistent among all database software, because the "accuracy" + * column may contains null values. When used in an "ORDER BY" clause, PostgreSQL put null + * values last, while Access and HSQL put them first. The PostgreSQL's behavior is better + * for what we want (put operations with unknow accuracy last). Unfortunatly, I don't know + * yet how to instruct Access to put null values last using standard SQL ("IIF" is not + * standard, and Access doesn't seem to understand "CASE ... THEN" clauses). + */ + @Override + public synchronized Set generateFromCoordinateReferenceSystemCodes( + final String sourceCode, final String targetCode) throws FactoryException { + ensureNonNull("sourceCode", sourceCode); + ensureNonNull("targetCode", targetCode); + final String pair = sourceCode + " \u21E8 " + targetCode; + final CoordinateOperationSet set = new CoordinateOperationSet(this); + try { + final String sourceKey = toPrimaryKeyCRS(sourceCode); + final String targetKey = toPrimaryKeyCRS(targetCode); + boolean searchTransformations = false; + do { + /* + * This 'do' loop is executed twice: the first time for searching defining + * conversions, and the second time for searching all other kind of operations. + * Defining conversions are searched first because they are, by definition, the + * most accurate operations. + */ + final String key, sql; + if (searchTransformations) { + key = "TransformationFromCRS"; + sql = + "SELECT COORD_OP_CODE" + + " FROM [Coordinate_Operation]" + + " WHERE SOURCE_CRS_CODE = ?" + + " AND TARGET_CRS_CODE = ?" + + " ORDER BY ABS(DEPRECATED), COORD_OP_ACCURACY"; + } else { + key = "ConversionFromCRS"; + sql = + "SELECT PROJECTION_CONV_CODE" + + " FROM [Coordinate Reference System]" + + " WHERE SOURCE_GEOGCRS_CODE = ?" + + " AND COORD_REF_SYS_CODE = ?"; + } + final PreparedStatement stmt = prepareStatement(key, sql); + stmt.setString(1, sourceKey); + stmt.setString(2, targetKey); + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final String code = getString(result, 1, pair); + set.addAuthorityCode(code, searchTransformations ? null : targetKey); + } + } + } while ((searchTransformations = !searchTransformations) == true); + /* + * Search finished. We may have a lot of coordinate operations + * (e.g. about 40 for "ED50" (EPSG:4230) to "WGS 84" (EPSG:4326)). + * Alter the ordering using the information supplied in the supersession table. + */ + final String[] codes = set.getAuthorityCodes(); + sort(codes); + set.setAuthorityCodes(codes); + } catch (SQLException exception) { + throw databaseFailure(CoordinateOperation.class, pair, exception); + } + /* + * Before to return the set, tests the creation of 1 object in order to report early + * (i.e. now) any problems with SQL statements. Remaining operations will be created + * only when first needed. + */ + set.resolve(1); + return set; + } + + /** + * Sorts an array of codes in preference order. This method orders pairwise the codes according + * the information provided in the supersession table. If the same object is superseded by more + * than one object, then the most recent one is inserted first. Except for the codes moved as a + * result of pairwise ordering, this method try to preserve the old ordering of the supplied + * codes (since deprecated operations should already be last). The ordering is performed in + * place. + * + * @param codes The codes, usually as an array of {@link String}. If the array do not contains + * string objects, then the {@link Object#toString} method must returns the code for each + * element. + */ + // TODO: Use generic type for "Object[] codes" with J2SE 1.5. + private void sort(final Object... codes) throws SQLException, FactoryException { + if (codes.length <= 1) { + return; // Nothing to sort. + } + final PreparedStatement stmt = + prepareStatement( + "Supersession", + "SELECT SUPERSEDED_BY" + + " FROM [Supersession]" + + " WHERE OBJECT_CODE = ?" + + " ORDER BY SUPERSESSION_YEAR DESC"); + int maxIterations = 15; // For avoiding never-ending loop. + do { + boolean changed = false; + for (int i = 0; i < codes.length; i++) { + final String code = codes[i].toString(); + stmt.setString(1, code); + try (ResultSet result = stmt.executeQuery()) { + while (result.next()) { + final String replacement = getString(result, 1, code); + for (int j = i + 1; j < codes.length; j++) { + final Object candidate = codes[j]; + if (replacement.equals(candidate.toString())) { + /* + * Found a code to move in front of the superceded one. + */ + System.arraycopy(codes, i, codes, i + 1, j - i); + codes[i++] = candidate; + changed = true; + } + } + } + } + } + if (!changed) { + return; + } + } while (--maxIterations != 0); + LOGGER.finer("Possible recursivity in supersessions."); + } + + /** + * An implementation of {@link IdentifiedObjectFinder} which scans over a smaller set of + * authority codes. + * + *

Implementation note: Since this method may be invoked indirectly by {@link + * LongitudeFirstFactory}, it must be insensitive to axis order. + */ + private final class Finder extends IdentifiedObjectFinder { + /** Creates a new finder backed by the specified buffered authority factory. */ + Finder(final Class type) { + super(AbstractEpsgFactory.this, type); + } + + /** + * Returns a set of authority codes that may identify the same object than + * the specified one. This implementation tries to get a smaller set than what {@link + * AbstractEpsgFactory#getAuthorityCodes} would produce. + */ + @Override + protected Set getCodeCandidates(final IdentifiedObject object) + throws FactoryException { + String select = "COORD_REF_SYS_CODE"; + String from = "[Coordinate Reference System]"; + String where, code; + if (object instanceof Ellipsoid) { + select = "ELLIPSOID_CODE"; + from = "[Ellipsoid]"; + where = "SEMI_MAJOR_AXIS"; + code = Double.toString(((Ellipsoid) object).getSemiMajorAxis()); + } else { + IdentifiedObject dependency; + if (object instanceof GeneralDerivedCRS) { + dependency = ((GeneralDerivedCRS) object).getBaseCRS(); + where = "SOURCE_GEOGCRS_CODE"; + } else if (object instanceof SingleCRS) { + dependency = ((SingleCRS) object).getDatum(); + where = "DATUM_CODE"; + } else if (object instanceof GeodeticDatum) { + dependency = ((GeodeticDatum) object).getEllipsoid(); + select = "DATUM_CODE"; + from = "[Datum]"; + where = "ELLIPSOID_CODE"; + } else { + return super.getCodeCandidates(object); + } + dependency = getIdentifiedObjectFinder(dependency.getClass()).find(dependency); + Identifier id = AbstractIdentifiedObject.getIdentifier(dependency, getAuthority()); + if (id == null || (code = id.getCode()) == null) { + return super.getCodeCandidates(object); + } + } + String sql = + "SELECT " + select + " FROM " + from + " WHERE " + where + "='" + code + '\''; + sql = adaptSQL(sql); + final Set result = new LinkedHashSet<>(); + try (Statement s = getConnection().createStatement(); + ResultSet r = s.executeQuery(sql)) { + while (r.next()) { + result.add(r.getString(1)); + } + } catch (SQLException exception) { + throw databaseFailure(Identifier.class, code, exception); + } + return result; + } + } + + /** Constructs an exception for recursive calls. */ + private static FactoryException recursiveCall( + final Class type, final String code) { + return new FactoryException(Errors.format(ErrorKeys.RECURSIVE_CALL_$2, type, code)); + } + + /** Constructs an exception for a database failure. */ + private static FactoryException databaseFailure( + final Class type, final String code, final SQLException cause) { + return new FactoryException( + Errors.format(ErrorKeys.DATABASE_FAILURE_$2, type, code), cause); + } + + /** + * Invoked when a new {@link PreparedStatement} is about to be created from a SQL string. Since + * the EPSG database is available mainly in MS-Access format, + * SQL statements are formatted using some syntax specific to this particular database software + * (for example "SELECT * FROM [Coordinate Reference System]"). When prociding + * subclass targeting another database vendor, then this method should be overridden in order to + * adapt the local SQL syntax. + * + *

For example a subclass connecting to a PostgreSQL database could replace all + * spaces (" ") between watching braces ("[" and "]") by underscore ("_"). + * + * @param statement The statement in MS-Access syntax. + * @return The SQL statement to use. The default implementation returns the string unchanged. + */ + protected abstract String adaptSQL(final String statement); + + /** + * Returns {@code true} if the specified code may be a primary key in some table. This method do + * not needs to checks any entry in the database. It should just checks from the syntax if the + * code looks like a valid EPSG identifier. The default implementation returns {@code true} if + * all non-space characters are {@linkplain Character#isDigit(char) digits}. + * + *

When this method returns {@code false}, some {@code createFoo(...)} methods look for the + * code in the name column instead of the primary key column. This allows to accept the + * "NTF (Paris) / France I" string (for example) in addition to the {@code "27581"} + * primary key. Both should fetch the same object. + * + *

If this method returns {@code true} in all cases, then this factory never search for + * matching names. In such case, an appropriate exception will be thrown in {@code + * createFoo(...)} methods if the code is not found in the primary key column. Subclasses can + * overrides this method that way if this is the intended behavior. + * + * @param code The code the inspect. + * @return {@code true} if the code is probably a primary key. + * @throws FactoryException if an unexpected error occured while inspecting the code. + */ + protected boolean isPrimaryKey(final String code) throws FactoryException { + final int length = code.length(); + for (int i = 0; i < length; i++) { + final char c = code.charAt(i); + if (!Character.isDigit(c) && !Character.isSpaceChar(c)) { + return false; + } + } + return true; + } + + /** + * Returns {@code true} if it is safe to dispose this factory. This method is invoked indirectly + * by {@link ThreadedEpsgFactory} after some timeout in order to release resources. This method + * will block the disposal if some {@linkplain #getAuthorityCodes set of authority codes} are + * still in use. + */ + final synchronized boolean canDispose() { + return true; + } + + /** + * Disposes any resources hold by this object. + * + * @throws FactoryException if an error occurred while closing the connection. + */ + @Override + public synchronized void dispose() throws FactoryException { + disconnect(); + super.dispose(); + } + + /** Connect to the database in anticipation of of use. */ + public void connect() throws FactoryException { + try { + getConnection(); + } catch (SQLException e) { + throw new FactoryException(e); + } + } + /** + * Disconnect from the database, and remain idle. We will still keep our internal data + * structures, we are not going to hold onto a database connection unless we are going to be + * used. + */ + public void disconnect() throws FactoryException { + if (connection != null) { + final boolean isClosed; + try { + isClosed = connection.isClosed(); + for (final Iterator it = statements.values().iterator(); + it.hasNext(); ) { + (it.next()).close(); + it.remove(); + } + connection.close(); + } catch (SQLException exception) { + throw new FactoryException(exception); + } + if (!isClosed) { + /* + * The above code was run unconditionally as a safety, even if the connection + * was already closed. However we will log a message only if we actually closed + * the connection, otherwise the log records are a little bit misleading. + */ + final LogRecord record = + Loggings.format(Level.FINE, LoggingKeys.CLOSED_EPSG_DATABASE); + record.setLoggerName(LOGGER.getName()); + LOGGER.log(record); + } + connection = null; + } + } + + /** + * Access to the connection used by this EpsgFactory. The connection will be created as needed. + * + * @return the connection + */ + protected synchronized Connection getConnection() throws SQLException { + if (connection == null) { + connection = dataSource.getConnection(); + } + return connection; + } + /** + * Shutdown the database engine. This method is invoked twice by {@link ThreadedEpsgFactory} at + * JVM shutdown: one time before the {@linkplain #connection} is closed, and a second time + * after. This shutdown hook is useful for embedded database engine starting a + * server process in addition to the client process. Just closing the connection is not enough + * for them. Example: + * + *

+ * + *

    + *
  • HSQL database engine needs to execute a {@code "SHUTDOWN"} statement using the + * {@linkplain #connection} before it is closed. + *
  • Derby database engine needs to instruct the {@linkplain java.sql.DriverManager driver + * manager} after all connections have been closed. + *
+ * + *

The default implementation does nothing, which is sufficient for implementations + * connecting to a distant server (i.e. non-embedded database engine), for example {@linkplain + * AccessDataSource MS-Access} or {@linkplain PostgreDataSource PostgreSQL}. + * + * @param active {@code true} if the {@linkplain #connection} is alive, or {@code false} + * otherwise. This method is invoked first with {@code active} set to {@code true}, then a + * second time with {@code active} set to {@code false}. + * @throws SQLException if this method failed to shutdown the database engine. + */ + protected void shutdown(final boolean active) throws SQLException {} + + /** + * Invokes {@link #dispose} when this factory is garbage collected. + * + * @throws Throwable if an error occurred while closing the connection. + */ + @Override + @SuppressWarnings("deprecation") // finalize is deprecated in Java 9 + protected final void finalize() throws Throwable { + dispose(); + super.finalize(); + } + + ////////////////////////////////////////////////////////////////////////////////////////////// + ////// /////// + ////// HARD CODED VALUES (other than SQL statements) RELATIVE TO THE EPSG DATABASE /////// + ////// /////// + ////////////////////////////////////////////////////////////////////////////////////////////// + /** + * Returns a hard-coded unit from an EPSG code. We do not need to provide all units here, but we + * must at least provide all base units declared in the [TARGET_UOM_CODE] column of table [Unit + * of Measure]. Other units will be derived automatically if they are not listed here. + * + * @param code The code. + * @return The unit, or {@code null} if the code is unrecognized. + */ + private static Unit getUnit(final int code) { + switch (code) { + case 9001: + return METRE; + case 9002: + return FOOT; + case 9030: + return NAUTICAL_MILE; + case 9036: + return KILOMETER; + case 9101: + return RADIAN; + case 9122: // Fall through + case 9102: + return DEGREE_ANGLE; + case 9103: + return MINUTE_ANGLE; + case 9104: + return SECOND_ANGLE; + case 9105: + return GRADE; + case 9107: + return DEGREE_MINUTE_SECOND; + case 9108: + return DEGREE_MINUTE_SECOND; + case 9109: + return MICRORADIAN; + case 9110: + return SEXAGESIMAL_DMS; + // TODO case 9111: return NonSI.SEXAGESIMAL_DM; + case 9203: // Fall through + case 9201: + return ONE; + case 9202: + return PPM; + default: + return null; + } + } + + /** + * Set a Bursa-Wolf parameter from an EPSG parameter. + * + * @param parameters The Bursa-Wolf parameters to modify. + * @param code The EPSG code for a parameter from [PARAMETER_CODE] column. + * @param value The value of the parameter from [PARAMETER_VALUE] column. + * @param unit The unit of the parameter value from [UOM_CODE] column. + * @throws FactoryException if the code is unrecognized. + * @throws IllegalArgumentException if the value could not be converted to the provided Unit + */ + private static void setBursaWolfParameter( + final BursaWolfParameters parameters, final int code, double value, final Unit unit) + throws FactoryException { + Unit target = unit; + if (code >= 8605) { + if (code <= 8607) target = SI.METRE; + else if (code == 8611) target = Units.PPM; + else if (code <= 8710) target = NonSI.SECOND_ANGLE; + } + if (target != unit) { + value = Units.getConverterToAny(unit, target).convert(value); + } + switch (code) { + case 8605: + parameters.dx = value; + break; + case 8606: + parameters.dy = value; + break; + case 8607: + parameters.dz = value; + break; + case 8608: + parameters.ex = value; + break; + case 8609: + parameters.ey = value; + break; + case 8610: + parameters.ez = value; + break; + case 8611: + parameters.ppm = value; + break; + default: + throw new FactoryException(Errors.format(ErrorKeys.UNEXPECTED_PARAMETER_$1, code)); + } + } + + /** + * List of tables and columns to test for codes values. This table is used by the {@link + * #createObject} method in order to detect which of the following methods should be invoked for + * a given code: + * + *

{@link #createCoordinateReferenceSystem} {@link #createCoordinateSystem} {@link + * #createDatum} {@link #createEllipsoid} {@link #createUnit} + * + *

The order is significant: it is the key for a {@code switch} statement. + * + * @see #createObject + * @see #lastObjectType + */ + private static final TableInfo[] TABLES_INFO = { + new TableInfo( + CoordinateReferenceSystem.class, + "[Coordinate Reference System]", + "COORD_REF_SYS_CODE", + "COORD_REF_SYS_NAME", + "COORD_REF_SYS_KIND", + new Class[] {ProjectedCRS.class, GeographicCRS.class, GeocentricCRS.class}, + new String[] {"projected", "geographic", "geocentric"}), + new TableInfo( + CoordinateSystem.class, + "[Coordinate System]", + "COORD_SYS_CODE", + "COORD_SYS_NAME", + "COORD_SYS_TYPE", + new Class[] { + CartesianCS.class, EllipsoidalCS.class, SphericalCS.class, VerticalCS.class + }, + new String[] {"Cartesian", "ellipsoidal", "spherical", "vertical"}), + new TableInfo( + CoordinateSystemAxis.class, + "[Coordinate Axis] AS CA INNER JOIN [Coordinate Axis Name] AS CAN" + + " ON CA.COORD_AXIS_NAME_CODE=CAN.COORD_AXIS_NAME_CODE", + "COORD_AXIS_CODE", + "COORD_AXIS_NAME"), + new TableInfo( + Datum.class, + "[Datum]", + "DATUM_CODE", + "DATUM_NAME", + "DATUM_TYPE", + new Class[] {GeodeticDatum.class, VerticalDatum.class, EngineeringDatum.class}, + new String[] {"geodetic", "vertical", "engineering"}), + new TableInfo(Ellipsoid.class, "[Ellipsoid]", "ELLIPSOID_CODE", "ELLIPSOID_NAME"), + new TableInfo( + PrimeMeridian.class, + "[Prime Meridian]", + "PRIME_MERIDIAN_CODE", + "PRIME_MERIDIAN_NAME"), + new TableInfo( + CoordinateOperation.class, + "[Coordinate_Operation]", + "COORD_OP_CODE", + "COORD_OP_NAME", + "COORD_OP_TYPE", + new Class[] {Projection.class, Conversion.class, Transformation.class}, + new String[] {"conversion", "conversion", "transformation"}), + // Note: Projection is handle in a special way. + + new TableInfo( + OperationMethod.class, + "[Coordinate_Operation Method]", + "COORD_OP_METHOD_CODE", + "COORD_OP_METHOD_NAME"), + new TableInfo( + ParameterDescriptor.class, + "[Coordinate_Operation Parameter]", + "PARAMETER_CODE", + "PARAMETER_NAME"), + new TableInfo(Unit.class, "[Unit of Measure]", "UOM_CODE", "UNIT_OF_MEAS_NAME") + }; + + /////////////////////////////////////////////////////////////////////////////// + //////// //////// + //////// E N D O F H A R D C O D E D V A L U E S //////// + //////// //////// + //////// NOTE: 'createFoo(...)' methods may still have hard-coded //////// + //////// values (others than SQL statements) in 'equalsIgnoreCase' //////// + //////// expressions. //////// + /////////////////////////////////////////////////////////////////////////////// + /** + * A set of EPSG authority codes. This set makes use of our connection to the EPSG database. All + * {@link #iterator} method call creates a new {@link ResultSet} holding the codes. However, + * call to {@link #contains} map directly to a SQL call. + * + *

Serialization of this class store a copy of all authority codes. The serialization do not + * preserve any connection to the database. + * + * @since 2.2 + * @version $Id$ + * @author Martin Desruisseaux (IRD) + */ + final class AuthorityCodeSet extends AbstractSet implements Serializable { + /** For compatibility with different versions. */ + private static final long serialVersionUID = 7105664579449680562L; + + /** + * The type for this code set. This is translated to the most appropriate interface type + * even if the user supplied an implementation type. + */ + public final Class type; + + /** {@code true} if {@link #type} is assignable to {@link Projection}. */ + private final boolean isProjection; + + /** + * A view of this set as a map with object's name as values, or {@code null} if none. Will + * be created only when first needed. + */ + private transient java.util.Map asMap; + + /** + * The SQL command to use for creating the {@code queryAll} statement. Used for iteration + * over all codes. + */ + final String sqlAll; + + /** + * The SQL command to use for creating the {@code querySingle} statement. Used for fetching + * the description from a code. + */ + private final String sqlSingle; + + /** The statement to use for querying all codes. Will be created only when first needed. */ + private transient PreparedStatement queryAll; + + /** + * The statement to use for querying a single code. Will be created only when first needed. + */ + private transient PreparedStatement querySingle; + + /** + * The collection's size, or a negative value if not yet computed. The records will be + * counted only when first needed. The special value -2 if set by {@link #isEmpty} if the + * size has not yet been computed, but we know that the set is not empty. + */ + private int size = -1; + + /** + * Creates a new set of authority codes for the specified type. + * + * @param table The table to query. + * @param type The type to query. + */ + public AuthorityCodeSet(final TableInfo table, final Class type) { + final StringBuilder buffer = new StringBuilder("SELECT "); + buffer.append(table.codeColumn); + if (table.nameColumn != null) { + buffer.append(", ").append(table.nameColumn); + } + buffer.append(" FROM ").append(table.table); + boolean hasWhere = false; + Class tableType = table.type; + if (table.typeColumn != null) { + for (int i = 0; i < table.subTypes.length; i++) { + final Class candidate = table.subTypes[i]; + if (candidate.isAssignableFrom(type)) { + buffer.append(" WHERE (") + .append(table.typeColumn) + .append(" LIKE '") + .append(table.typeNames[i]) + .append("%'"); + hasWhere = true; + tableType = candidate; + break; + } + } + if (hasWhere) { + buffer.append(')'); + } + } + this.type = tableType; + isProjection = Projection.class.isAssignableFrom(tableType); + final int length = buffer.length(); + buffer.append(" ORDER BY ").append(table.codeColumn); + sqlAll = adaptSQL(buffer.toString()); + buffer.setLength(length); + buffer.append(hasWhere ? " AND " : " WHERE ").append(table.codeColumn).append(" = ?"); + sqlSingle = adaptSQL(buffer.toString()); + } + + /** Returns all codes. */ + private ResultSet getAll() throws SQLException { + assert Thread.holdsLock(this); + if (queryAll != null) { + try { + return queryAll.executeQuery(); + } catch (SQLException ignore) { + /* + * Failed to reuse an existing statement. This problem occurs in some occasions + * with the JDBC-ODBC bridge in Java 6 (the error message is "Invalid handle"). + * I'm not sure where the bug come from (didn't noticed it when using HSQL). We + * will try again with a new statement created in the code after this 'catch' + * clause. Note that we set 'queryAll' to null first in case of failure during + * the 'prepareStatement(...)' execution. + */ + queryAll.close(); + queryAll = null; + recoverableException("getAll", ignore); + } + } + queryAll = getConnection().prepareStatement(sqlAll); + return queryAll.executeQuery(); + } + + /** Returns a single code. */ + private ResultSet getSingle(final Object code) throws SQLException { + assert Thread.holdsLock(this); + if (querySingle == null) { + querySingle = getConnection().prepareStatement(sqlSingle); + } + querySingle.setString(1, code.toString()); + return querySingle.executeQuery(); + } + + /** + * Returns {@code true} if the code in the specified result set is acceptable. This method + * handle projections in a special way. + */ + private boolean isAcceptable(final ResultSet results) throws SQLException { + if (!isProjection) { + return true; + } + final String code = results.getString(1); + return isProjection(code); + } + + /** + * Returns {@code true} if the code in the specified code is acceptable. This method handle + * projections in a special way. + */ + private boolean isAcceptable(final String code) throws SQLException { + if (!isProjection) { + return true; + } + return isProjection(code); + } + + /** + * Returns {@code true} if this collection contains no elements. This method fetch at most + * one row instead of counting all rows. + */ + @Override + public synchronized boolean isEmpty() { + if (size != -1) { + return size == 0; + } + boolean empty = true; + try { + try (ResultSet results = getAll()) { + while (results.next()) { + if (isAcceptable(results)) { + empty = false; + break; + } + } + } + } catch (SQLException exception) { + unexpectedException("isEmpty", exception); + } + size = empty ? 0 : -2; + return empty; + } + + /** Count the number of elements in the underlying result set. */ + @Override + public synchronized int size() { + if (size >= 0) { + return size; + } + int count = 0; + try { + try (ResultSet results = getAll()) { + while (results.next()) { + if (isAcceptable(results)) { + count++; + } + } + } + } catch (SQLException exception) { + unexpectedException("size", exception); + } + size = count; // Stores only on success. + return count; + } + + /** Returns {@code true} if this collection contains the specified element. */ + @Override + public synchronized boolean contains(final Object code) { + boolean exists = false; + if (code != null) + try { + try (ResultSet results = getSingle(code)) { + while (results.next()) { + if (isAcceptable(results)) { + exists = true; + break; + } + } + } + } catch (SQLException exception) { + unexpectedException("contains", exception); + } + return exists; + } + + /** + * Returns an iterator over the codes. The iterator is backed by a living {@link ResultSet}, + * which will be closed as soon as the iterator reach the last element. + */ + @Override + public synchronized java.util.Iterator iterator() { + try { + final Iterator iterator = new Iterator(getAll()); + /* + * Set the statement to null without closing it, in order to force a new statement + * creation if getAll() is invoked before the iterator finish its iteration. This + * is needed because only one ResultSet is allowed for each Statement. + */ + queryAll = null; + return iterator; + } catch (SQLException exception) { + unexpectedException("iterator", exception); + final Set empty = Collections.emptySet(); + return empty.iterator(); + } + } + + /** + * Returns a serializable copy of this set. This method is invoked automatically during + * serialization. The serialised set of authority code is disconnected from the underlying + * database. + */ + protected LinkedHashSet writeReplace() throws ObjectStreamException { + return new LinkedHashSet<>(this); + } + + /** + * Closes the underlying statements. Note: this method is also invoked directly by {@link + * DirectEpsgFactory#dispose}, which is okay in this particular case since the + * implementation of this method can be executed an arbitrary amount of times. + */ + @Override + @SuppressWarnings("deprecation") // finalize is deprecated in Java 9 + protected synchronized void finalize() throws SQLException { + if (querySingle != null) { + querySingle.close(); + querySingle = null; + } + if (queryAll != null) { + queryAll.close(); + queryAll = null; + } + } + + /** Invoked when an exception occured. This method just log a warning. */ + private void unexpectedException(final String method, final SQLException exception) { + unexpectedException(AuthorityCodes.class, method, exception); + } + + /** Invoked when an exception occured. This method just log a warning. */ + void unexpectedException( + final Class classe, final String method, final SQLException exception) { + Logging.unexpectedException(LOGGER, classe, method, exception); + } + + /** Invoked when a recoverable exception occured. */ + private void recoverableException(final String method, final SQLException exception) { + // Uses the FINE level instead of WARNING because it may be a recoverable error. + LogRecord record = Loggings.format(Level.FINE, LoggingKeys.UNEXPECTED_EXCEPTION); + record.setSourceClassName(AuthorityCodes.class.getName()); + record.setSourceMethodName(method); + record.setThrown(exception); + record.setLoggerName(LOGGER.getName()); + LOGGER.log(record); + } + + /** + * The iterator over the codes. This inner class must kept a reference toward the enclosing + * {@link AuthorityCodes} in order to prevent a call to {@link AuthorityCodes#finalize} + * before the iteration is finished. + */ + private final class Iterator implements java.util.Iterator { + /** The result set, or {@code null} if there is no more elements. */ + private ResultSet results; + + /** The next code. */ + private transient String next; + + /** Creates a new iterator for the specified result set. */ + Iterator(final ResultSet results) throws SQLException { + assert Thread.holdsLock(AuthorityCodeSet.this); + this.results = results; + toNext(); + } + + /** Moves to the next element. */ + private void toNext() throws SQLException { + while (results.next()) { + next = results.getString(1); + if (isAcceptable(next)) { + return; + } + } + finalize(); + } + + /** Returns {@code true} if there is more elements. */ + @Override + public boolean hasNext() { + return results != null; + } + + /** Returns the next element. */ + @Override + public String next() { + if (results == null) { + throw new NoSuchElementException(); + } + final String current = next; + try { + toNext(); + } catch (SQLException exception) { + results = null; + unexpectedException(Iterator.class, "next", exception); + } + return current; + } + + /** Always throws an exception, since this iterator is read-only. */ + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + /** Closes the underlying result set. */ + @Override + @SuppressWarnings("deprecation") // finalize is deprecated in Java 9 + protected void finalize() throws SQLException { + next = null; + if (results != null) { + final PreparedStatement owner = (PreparedStatement) results.getStatement(); + results.close(); + results = null; + synchronized (AuthorityCodeSet.this) { + /* + * We don't need the statement anymore. Gives it back to the enclosing class + * in order to avoid creating a new one when AuthorityCodes.getAll() will be + * invoked again, or closes the statement if getAll() already created a new + * statement anyway. + */ + assert owner != queryAll; + if (queryAll == null) { + queryAll = owner; + } else { + owner.close(); + } + } + } + } + } + + /** + * Returns a view of this set as a map with object's name as value, or {@code null} if none. + */ + final java.util.Map asMap() { + if (asMap == null) { + asMap = new Map(); + } + return asMap; + } + + /** + * A view of {@link AuthorityCodes} as a map, with authority codes as key and object names + * as values. + */ + private final class Map extends AbstractMap { + /** Returns the number of key-value mappings in this map. */ + @Override + public int size() { + return AuthorityCodeSet.this.size(); + } + + /** Returns {@code true} if this map contains no key-value mappings. */ + @Override + public boolean isEmpty() { + return AuthorityCodeSet.this.isEmpty(); + } + + /** Returns the description to which this map maps the specified EPSG code. */ + @Override + public String get(final Object code) { + String value = null; + if (code != null) + try { + synchronized (AuthorityCodeSet.this) { + try (ResultSet results = getSingle(code)) { + while (results.next()) { + if (isAcceptable(results)) { + value = results.getString(2); + break; + } + } + } + } + } catch (SQLException exception) { + unexpectedException("get", exception); + } + return value; + } + + /** Returns {@code true} if this map contains a mapping for the specified EPSG code. */ + @Override + public boolean containsKey(final Object key) { + return contains(key); + } + + /** Returns a set view of the keys contained in this map. */ + @Override + public Set keySet() { + return AuthorityCodeSet.this; + } + + /** + * Returns a set view of the mappings contained in this map. + * + * @todo Not yet implemented. + */ + @Override + public Set> entrySet() { + throw new UnsupportedOperationException(); + } + } + } +} diff --git a/Java/AbstractResourceSkin.java b/Java/AbstractResourceSkin.java new file mode 100644 index 0000000000000000000000000000000000000000..eb9027914795fed18312240c844fd081b5daacd0 --- /dev/null +++ b/Java/AbstractResourceSkin.java @@ -0,0 +1,157 @@ +/* + * 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.internal.skin; + +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.apache.commons.configuration2.BaseConfiguration; +import org.apache.commons.configuration2.Configuration; +import org.apache.commons.configuration2.builder.fluent.Configurations; +import org.apache.commons.configuration2.ex.ConfigurationException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.xwiki.filter.input.InputSource; +import org.xwiki.skin.Resource; +import org.xwiki.skin.Skin; + +import static org.apache.commons.lang3.exception.ExceptionUtils.getRootCauseMessage; + +/** + * Common abstract class for the skins that manipulate resources. + * + * @version $Id$ + * @since 13.8RC1 + */ +public abstract class AbstractResourceSkin extends AbstractSkin +{ + protected static final Logger LOGGER = LoggerFactory.getLogger(AbstractResourceSkin.class); + + private Configuration properties; + + /** + * Default constructor. + * + * @param id the skin id (for instance, {@code "flamingo"}) + * @param skinManager the skin manager that instantiates this skin + * @param configuration the skin internal configuration, used to access the default parent skin id + * @param logger a logger used to log warning in case of error when parsin a skin's syntax + */ + public AbstractResourceSkin(String id, InternalSkinManager skinManager, + InternalSkinConfiguration configuration, Logger logger) + { + super(id, skinManager, configuration, logger); + } + + abstract AbstractResource createResource(String resourcePath, String resourceName); + + abstract URL getResourceURL(String resourcePath); + + @Override + public String getOutputSyntaxString() + { + return getProperties().getString("outputSyntax"); + } + + @Override + protected Skin createParent() + { + Skin skin; + + String parentId = getProperties().getString("parent"); + + if (parentId != null) { + if (parentId.isEmpty()) { + // There is explicitly no parent (make sure to not fallback on default parent skin) + skin = VOID; + } else { + skin = this.skinManager.getSkin(parentId); + } + } else { + skin = null; + } + + return skin; + } + + @Override + public Resource getLocalResource(String resourceName) + { + String resourcePath = getSkinResourcePath(resourceName); + + if (resourcePath != null && getResourceURL(resourcePath) != null) { + return createResource(resourcePath, resourceName); + } + + return null; + } + + protected String getPropertiesPath() + { + return getSkinFolder() + "skin.properties"; + } + + protected String getSkinFolder() + { + return "skins/" + this.id + '/'; + } + + protected Configuration getProperties() + { + if (this.properties == null) { + URL url = getResourceURL(getPropertiesPath()); + if (url != null) { + try { + this.properties = new Configurations().properties(url); + } catch (ConfigurationException e) { + LOGGER.error("Failed to load skin [{}] properties file ([])", this.id, url, + getRootCauseMessage(e)); + + this.properties = new BaseConfiguration(); + } + } else { + LOGGER.debug("No properties found for skin [{}]", this.id); + + this.properties = new BaseConfiguration(); + } + } + + return this.properties; + } + + private String getSkinResourcePath(String resource) + { + String skinFolder = getSkinFolder(); + String resourcePath = skinFolder + resource; + // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') + // // Prevent inclusion of templates from other directories + // FIXED: + // Prevent access to resources from other directories + Path normalizedResource = Paths.get(resourcePath).normalize(); + // Protect against directory attacks. + if (!normalizedResource.startsWith(skinFolder)) { + LOGGER.warn("Direct access to skin file [{}] refused. Possible break-in attempt!", normalizedResource); + return null; + } + + return resourcePath; + } +} diff --git a/Java/AbstractXMPPConnection.java b/Java/AbstractXMPPConnection.java new file mode 100644 index 0000000000000000000000000000000000000000..df1acef66675c544f01d3fcc84f0f0bcfca0ea13 --- /dev/null +++ b/Java/AbstractXMPPConnection.java @@ -0,0 +1,1569 @@ +/** + * + * Copyright 2009 Jive Software. + * + * 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.jivesoftware.smack; + +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode; +import org.jivesoftware.smack.SmackException.AlreadyConnectedException; +import org.jivesoftware.smack.SmackException.AlreadyLoggedInException; +import org.jivesoftware.smack.SmackException.NoResponseException; +import org.jivesoftware.smack.SmackException.NotConnectedException; +import org.jivesoftware.smack.SmackException.ConnectionException; +import org.jivesoftware.smack.SmackException.ResourceBindingNotOfferedException; +import org.jivesoftware.smack.SmackException.SecurityRequiredException; +import org.jivesoftware.smack.XMPPException.XMPPErrorException; +import org.jivesoftware.smack.compress.packet.Compress; +import org.jivesoftware.smack.compression.XMPPInputOutputStream; +import org.jivesoftware.smack.debugger.SmackDebugger; +import org.jivesoftware.smack.filter.IQReplyFilter; +import org.jivesoftware.smack.filter.StanzaFilter; +import org.jivesoftware.smack.filter.StanzaIdFilter; +import org.jivesoftware.smack.iqrequest.IQRequestHandler; +import org.jivesoftware.smack.packet.Bind; +import org.jivesoftware.smack.packet.ErrorIQ; +import org.jivesoftware.smack.packet.IQ; +import org.jivesoftware.smack.packet.Mechanisms; +import org.jivesoftware.smack.packet.Stanza; +import org.jivesoftware.smack.packet.ExtensionElement; +import org.jivesoftware.smack.packet.Presence; +import org.jivesoftware.smack.packet.Session; +import org.jivesoftware.smack.packet.StartTls; +import org.jivesoftware.smack.packet.PlainStreamElement; +import org.jivesoftware.smack.packet.XMPPError; +import org.jivesoftware.smack.parsing.ParsingExceptionCallback; +import org.jivesoftware.smack.parsing.UnparsablePacket; +import org.jivesoftware.smack.provider.ExtensionElementProvider; +import org.jivesoftware.smack.provider.ProviderManager; +import org.jivesoftware.smack.util.BoundedThreadPoolExecutor; +import org.jivesoftware.smack.util.DNSUtil; +import org.jivesoftware.smack.util.Objects; +import org.jivesoftware.smack.util.PacketParserUtils; +import org.jivesoftware.smack.util.ParserUtils; +import org.jivesoftware.smack.util.SmackExecutorThreadFactory; +import org.jivesoftware.smack.util.StringUtils; +import org.jivesoftware.smack.util.dns.HostAddress; +import org.jxmpp.util.XmppStringUtils; +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; + + +public abstract class AbstractXMPPConnection implements XMPPConnection { + private static final Logger LOGGER = Logger.getLogger(AbstractXMPPConnection.class.getName()); + + /** + * Counter to uniquely identify connections that are created. + */ + private final static AtomicInteger connectionCounter = new AtomicInteger(0); + + static { + // Ensure the SmackConfiguration class is loaded by calling a method in it. + SmackConfiguration.getVersion(); + } + + /** + * Get the collection of listeners that are interested in connection creation events. + * + * @return a collection of listeners interested on new connections. + */ + protected static Collection getConnectionCreationListeners() { + return XMPPConnectionRegistry.getConnectionCreationListeners(); + } + + /** + * A collection of ConnectionListeners which listen for connection closing + * and reconnection events. + */ + protected final Set connectionListeners = + new CopyOnWriteArraySet(); + + /** + * A collection of PacketCollectors which collects packets for a specified filter + * and perform blocking and polling operations on the result queue. + *

+ * We use a ConcurrentLinkedQueue here, because its Iterator is weakly + * consistent and we want {@link #invokePacketCollectors(Stanza)} for-each + * loop to be lock free. As drawback, removing a PacketCollector is O(n). + * The alternative would be a synchronized HashSet, but this would mean a + * synchronized block around every usage of collectors. + *

+ */ + private final Collection collectors = new ConcurrentLinkedQueue(); + + /** + * List of PacketListeners that will be notified synchronously when a new stanza(/packet) was received. + */ + private final Map syncRecvListeners = new LinkedHashMap<>(); + + /** + * List of PacketListeners that will be notified asynchronously when a new stanza(/packet) was received. + */ + private final Map asyncRecvListeners = new LinkedHashMap<>(); + + /** + * List of PacketListeners that will be notified when a new stanza(/packet) was sent. + */ + private final Map sendListeners = + new HashMap(); + + /** + * List of PacketListeners that will be notified when a new stanza(/packet) is about to be + * sent to the server. These interceptors may modify the stanza(/packet) before it is being + * actually sent to the server. + */ + private final Map interceptors = + new HashMap(); + + protected final Lock connectionLock = new ReentrantLock(); + + protected final Map streamFeatures = new HashMap(); + + /** + * The full JID of the authenticated user, as returned by the resource binding response of the server. + *

+ * It is important that we don't infer the user from the login() arguments and the configurations service name, as, + * for example, when SASL External is used, the username is not given to login but taken from the 'external' + * certificate. + *

+ */ + protected String user; + + protected boolean connected = false; + + /** + * The stream ID, see RFC 6120 § 4.7.3 + */ + protected String streamId; + + /** + * + */ + private long packetReplyTimeout = SmackConfiguration.getDefaultPacketReplyTimeout(); + + /** + * The SmackDebugger allows to log and debug XML traffic. + */ + protected SmackDebugger debugger = null; + + /** + * The Reader which is used for the debugger. + */ + protected Reader reader; + + /** + * The Writer which is used for the debugger. + */ + protected Writer writer; + + /** + * Set to success if the last features stanza from the server has been parsed. A XMPP connection + * handshake can invoke multiple features stanzas, e.g. when TLS is activated a second feature + * stanza is send by the server. This is set to true once the last feature stanza has been + * parsed. + */ + protected final SynchronizationPoint lastFeaturesReceived = new SynchronizationPoint( + AbstractXMPPConnection.this); + + /** + * Set to success if the sasl feature has been received. + */ + protected final SynchronizationPoint saslFeatureReceived = new SynchronizationPoint( + AbstractXMPPConnection.this); + + /** + * The SASLAuthentication manager that is responsible for authenticating with the server. + */ + protected SASLAuthentication saslAuthentication = new SASLAuthentication(this); + + /** + * A number to uniquely identify connections that are created. This is distinct from the + * connection ID, which is a value sent by the server once a connection is made. + */ + protected final int connectionCounterValue = connectionCounter.getAndIncrement(); + + /** + * Holds the initial configuration used while creating the connection. + */ + protected final ConnectionConfiguration config; + + /** + * Defines how the from attribute of outgoing stanzas should be handled. + */ + private FromMode fromMode = FromMode.OMITTED; + + protected XMPPInputOutputStream compressionHandler; + + private ParsingExceptionCallback parsingExceptionCallback = SmackConfiguration.getDefaultParsingExceptionCallback(); + + /** + * ExecutorService used to invoke the PacketListeners on newly arrived and parsed stanzas. It is + * important that we use a single threaded ExecutorService in order to guarantee that the + * PacketListeners are invoked in the same order the stanzas arrived. + */ + private final BoundedThreadPoolExecutor executorService = new BoundedThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, + 100, new SmackExecutorThreadFactory(connectionCounterValue, "Incoming Processor")); + + /** + * This scheduled thread pool executor is used to remove pending callbacks. + */ + private final ScheduledExecutorService removeCallbacksService = Executors.newSingleThreadScheduledExecutor( + new SmackExecutorThreadFactory(connectionCounterValue, "Remove Callbacks")); + + /** + * A cached thread pool executor service with custom thread factory to set meaningful names on the threads and set + * them 'daemon'. + */ + private final ExecutorService cachedExecutorService = Executors.newCachedThreadPool( + // @formatter:off + new SmackExecutorThreadFactory( // threadFactory + connectionCounterValue, + "Cached Executor" + ) + // @formatter:on + ); + + /** + * A executor service used to invoke the callbacks of synchronous stanza(/packet) listeners. We use a executor service to + * decouple incoming stanza processing from callback invocation. It is important that order of callback invocation + * is the same as the order of the incoming stanzas. Therefore we use a single threaded executor service. + */ + private final ExecutorService singleThreadedExecutorService = Executors.newSingleThreadExecutor(new SmackExecutorThreadFactory( + getConnectionCounter(), "Single Threaded Executor")); + + /** + * The used host to establish the connection to + */ + protected String host; + + /** + * The used port to establish the connection to + */ + protected int port; + + /** + * Flag that indicates if the user is currently authenticated with the server. + */ + protected boolean authenticated = false; + + /** + * Flag that indicates if the user was authenticated with the server when the connection + * to the server was closed (abruptly or not). + */ + protected boolean wasAuthenticated = false; + + private final Map setIqRequestHandler = new HashMap<>(); + private final Map getIqRequestHandler = new HashMap<>(); + + /** + * Create a new XMPPConnection to an XMPP server. + * + * @param configuration The configuration which is used to establish the connection. + */ + protected AbstractXMPPConnection(ConnectionConfiguration configuration) { + config = configuration; + } + + /** + * Get the connection configuration used by this connection. + * + * @return the connection configuration. + */ + public ConnectionConfiguration getConfiguration() { + return config; + } + + @Override + public String getServiceName() { + if (serviceName != null) { + return serviceName; + } + return config.getServiceName(); + } + + @Override + public String getHost() { + return host; + } + + @Override + public int getPort() { + return port; + } + + @Override + public abstract boolean isSecureConnection(); + + protected abstract void sendStanzaInternal(Stanza packet) throws NotConnectedException; + + @Override + public abstract void send(PlainStreamElement element) throws NotConnectedException; + + @Override + public abstract boolean isUsingCompression(); + + /** + * Establishes a connection to the XMPP server and performs an automatic login + * only if the previous connection state was logged (authenticated). It basically + * creates and maintains a connection to the server. + *

+ * Listeners will be preserved from a previous connection. + * + * @throws XMPPException if an error occurs on the XMPP protocol level. + * @throws SmackException if an error occurs somewhere else besides XMPP protocol level. + * @throws IOException + * @throws ConnectionException with detailed information about the failed connection. + * @return a reference to this object, to chain connect() with login(). + */ + public synchronized AbstractXMPPConnection connect() throws SmackException, IOException, XMPPException { + // Check if not already connected + throwAlreadyConnectedExceptionIfAppropriate(); + + // Reset the connection state + saslAuthentication.init(); + saslFeatureReceived.init(); + lastFeaturesReceived.init(); + streamId = null; + + // Perform the actual connection to the XMPP service + connectInternal(); + + return this; + } + + /** + * Abstract method that concrete subclasses of XMPPConnection need to implement to perform their + * way of XMPP connection establishment. Implementations are required to perform an automatic + * login if the previous connection state was logged (authenticated). + * + * @throws SmackException + * @throws IOException + * @throws XMPPException + */ + protected abstract void connectInternal() throws SmackException, IOException, XMPPException; + + private String usedUsername, usedPassword, usedResource; + + /** + * Logs in to the server using the strongest SASL mechanism supported by + * the server. If more than the connection's default stanza(/packet) timeout elapses in each step of the + * authentication process without a response from the server, a + * {@link SmackException.NoResponseException} will be thrown. + *

+ * Before logging in (i.e. authenticate) to the server the connection must be connected + * by calling {@link #connect}. + *

+ *

+ * It is possible to log in without sending an initial available presence by using + * {@link ConnectionConfiguration.Builder#setSendPresence(boolean)}. + * Finally, if you want to not pass a password and instead use a more advanced mechanism + * while using SASL then you may be interested in using + * {@link ConnectionConfiguration.Builder#setCallbackHandler(javax.security.auth.callback.CallbackHandler)}. + * For more advanced login settings see {@link ConnectionConfiguration}. + *

+ * + * @throws XMPPException if an error occurs on the XMPP protocol level. + * @throws SmackException if an error occurs somewhere else besides XMPP protocol level. + * @throws IOException if an I/O error occurs during login. + */ + public synchronized void login() throws XMPPException, SmackException, IOException { + if (isAnonymous()) { + throwNotConnectedExceptionIfAppropriate("Did you call connect() before login()?"); + throwAlreadyLoggedInExceptionIfAppropriate(); + loginAnonymously(); + } else { + // The previously used username, password and resource take over precedence over the + // ones from the connection configuration + CharSequence username = usedUsername != null ? usedUsername : config.getUsername(); + String password = usedPassword != null ? usedPassword : config.getPassword(); + String resource = usedResource != null ? usedResource : config.getResource(); + login(username, password, resource); + } + } + + /** + * Same as {@link #login(CharSequence, String, String)}, but takes the resource from the connection + * configuration. + * + * @param username + * @param password + * @throws XMPPException + * @throws SmackException + * @throws IOException + * @see #login + */ + public synchronized void login(CharSequence username, String password) throws XMPPException, SmackException, + IOException { + login(username, password, config.getResource()); + } + + /** + * Login with the given username (authorization identity). You may omit the password if a callback handler is used. + * If resource is null, then the server will generate one. + * + * @param username + * @param password + * @param resource + * @throws XMPPException + * @throws SmackException + * @throws IOException + * @see #login + */ + public synchronized void login(CharSequence username, String password, String resource) throws XMPPException, + SmackException, IOException { + if (!config.allowNullOrEmptyUsername) { + StringUtils.requireNotNullOrEmpty(username, "Username must not be null or empty"); + } + throwNotConnectedExceptionIfAppropriate(); + throwAlreadyLoggedInExceptionIfAppropriate(); + usedUsername = username != null ? username.toString() : null; + usedPassword = password; + usedResource = resource; + loginNonAnonymously(usedUsername, usedPassword, usedResource); + } + + protected abstract void loginNonAnonymously(String username, String password, String resource) + throws XMPPException, SmackException, IOException; + + protected abstract void loginAnonymously() throws XMPPException, SmackException, IOException; + + @Override + public final boolean isConnected() { + return connected; + } + + @Override + public final boolean isAuthenticated() { + return authenticated; + } + + @Override + public final String getUser() { + return user; + } + + @Override + public String getStreamId() { + if (!isConnected()) { + return null; + } + return streamId; + } + + // TODO remove this suppression once "disable legacy session" code has been removed from Smack + @SuppressWarnings("deprecation") + protected void bindResourceAndEstablishSession(String resource) throws XMPPErrorException, + IOException, SmackException { + + // Wait until either: + // - the servers last features stanza has been parsed + // - the timeout occurs + LOGGER.finer("Waiting for last features to be received before continuing with resource binding"); + lastFeaturesReceived.checkIfSuccessOrWait(); + + + if (!hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) { + // Server never offered resource binding, which is REQURIED in XMPP client and + // server implementations as per RFC6120 7.2 + throw new ResourceBindingNotOfferedException(); + } + + // Resource binding, see RFC6120 7. + // Note that we can not use IQReplyFilter here, since the users full JID is not yet + // available. It will become available right after the resource has been successfully bound. + Bind bindResource = Bind.newSet(resource); + PacketCollector packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(bindResource), bindResource); + Bind response = packetCollector.nextResultOrThrow(); + // Set the connections user to the result of resource binding. It is important that we don't infer the user + // from the login() arguments and the configurations service name, as, for example, when SASL External is used, + // the username is not given to login but taken from the 'external' certificate. + user = response.getJid(); + serviceName = XmppStringUtils.parseDomain(user); + + Session.Feature sessionFeature = getFeature(Session.ELEMENT, Session.NAMESPACE); + // Only bind the session if it's announced as stream feature by the server, is not optional and not disabled + // For more information see http://tools.ietf.org/html/draft-cridland-xmpp-session-01 + if (sessionFeature != null && !sessionFeature.isOptional() && !getConfiguration().isLegacySessionDisabled()) { + Session session = new Session(); + packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(session), session); + packetCollector.nextResultOrThrow(); + } + } + + protected void afterSuccessfulLogin(final boolean resumed) throws NotConnectedException { + // Indicate that we're now authenticated. + this.authenticated = true; + + // If debugging is enabled, change the the debug window title to include the + // name we are now logged-in as. + // If DEBUG was set to true AFTER the connection was created the debugger + // will be null + if (config.isDebuggerEnabled() && debugger != null) { + debugger.userHasLogged(user); + } + callConnectionAuthenticatedListener(resumed); + + // Set presence to online. It is important that this is done after + // callConnectionAuthenticatedListener(), as this call will also + // eventually load the roster. And we should load the roster before we + // send the initial presence. + if (config.isSendPresence() && !resumed) { + sendStanza(new Presence(Presence.Type.available)); + } + } + + @Override + public final boolean isAnonymous() { + return config.getUsername() == null && usedUsername == null + && !config.allowNullOrEmptyUsername; + } + + private String serviceName; + + protected List hostAddresses; + + /** + * Populates {@link #hostAddresses} with at least one host address. + * + * @return a list of host addresses where DNS (SRV) RR resolution failed. + */ + protected List populateHostAddresses() { + List failedAddresses = new LinkedList<>(); + // N.B.: Important to use config.serviceName and not AbstractXMPPConnection.serviceName + if (config.host != null) { + hostAddresses = new ArrayList(1); + HostAddress hostAddress; + hostAddress = new HostAddress(config.host, config.port); + hostAddresses.add(hostAddress); + } else { + hostAddresses = DNSUtil.resolveXMPPDomain(config.serviceName, failedAddresses); + } + // If we reach this, then hostAddresses *must not* be empty, i.e. there is at least one host added, either the + // config.host one or the host representing the service name by DNSUtil + assert(!hostAddresses.isEmpty()); + return failedAddresses; + } + + protected Lock getConnectionLock() { + return connectionLock; + } + + protected void throwNotConnectedExceptionIfAppropriate() throws NotConnectedException { + throwNotConnectedExceptionIfAppropriate(null); + } + + protected void throwNotConnectedExceptionIfAppropriate(String optionalHint) throws NotConnectedException { + if (!isConnected()) { + throw new NotConnectedException(optionalHint); + } + } + + protected void throwAlreadyConnectedExceptionIfAppropriate() throws AlreadyConnectedException { + if (isConnected()) { + throw new AlreadyConnectedException(); + } + } + + protected void throwAlreadyLoggedInExceptionIfAppropriate() throws AlreadyLoggedInException { + if (isAuthenticated()) { + throw new AlreadyLoggedInException(); + } + } + + @Deprecated + @Override + public void sendPacket(Stanza packet) throws NotConnectedException { + sendStanza(packet); + } + + @Override + public void sendStanza(Stanza packet) throws NotConnectedException { + Objects.requireNonNull(packet, "Packet must not be null"); + + throwNotConnectedExceptionIfAppropriate(); + switch (fromMode) { + case OMITTED: + packet.setFrom(null); + break; + case USER: + packet.setFrom(getUser()); + break; + case UNCHANGED: + default: + break; + } + // Invoke interceptors for the new packet that is about to be sent. Interceptors may modify + // the content of the packet. + firePacketInterceptors(packet); + sendStanzaInternal(packet); + } + + /** + * Returns the SASLAuthentication manager that is responsible for authenticating with + * the server. + * + * @return the SASLAuthentication manager that is responsible for authenticating with + * the server. + */ + protected SASLAuthentication getSASLAuthentication() { + return saslAuthentication; + } + + /** + * Closes the connection by setting presence to unavailable then closing the connection to + * the XMPP server. The XMPPConnection can still be used for connecting to the server + * again. + * + */ + public void disconnect() { + try { + disconnect(new Presence(Presence.Type.unavailable)); + } + catch (NotConnectedException e) { + LOGGER.log(Level.FINEST, "Connection is already disconnected", e); + } + } + + /** + * Closes the connection. A custom unavailable presence is sent to the server, followed + * by closing the stream. The XMPPConnection can still be used for connecting to the server + * again. A custom unavailable presence is useful for communicating offline presence + * information such as "On vacation". Typically, just the status text of the presence + * stanza(/packet) is set with online information, but most XMPP servers will deliver the full + * presence stanza(/packet) with whatever data is set. + * + * @param unavailablePresence the presence stanza(/packet) to send during shutdown. + * @throws NotConnectedException + */ + public synchronized void disconnect(Presence unavailablePresence) throws NotConnectedException { + sendStanza(unavailablePresence); + shutdown(); + callConnectionClosedListener(); + } + + /** + * Shuts the current connection down. + */ + protected abstract void shutdown(); + + @Override + public void addConnectionListener(ConnectionListener connectionListener) { + if (connectionListener == null) { + return; + } + connectionListeners.add(connectionListener); + } + + @Override + public void removeConnectionListener(ConnectionListener connectionListener) { + connectionListeners.remove(connectionListener); + } + + @Override + public PacketCollector createPacketCollectorAndSend(IQ packet) throws NotConnectedException { + StanzaFilter packetFilter = new IQReplyFilter(packet, this); + // Create the packet collector before sending the packet + PacketCollector packetCollector = createPacketCollectorAndSend(packetFilter, packet); + return packetCollector; + } + + @Override + public PacketCollector createPacketCollectorAndSend(StanzaFilter packetFilter, Stanza packet) + throws NotConnectedException { + // Create the packet collector before sending the packet + PacketCollector packetCollector = createPacketCollector(packetFilter); + try { + // Now we can send the packet as the collector has been created + sendStanza(packet); + } + catch (NotConnectedException | RuntimeException e) { + packetCollector.cancel(); + throw e; + } + return packetCollector; + } + + @Override + public PacketCollector createPacketCollector(StanzaFilter packetFilter) { + PacketCollector.Configuration configuration = PacketCollector.newConfiguration().setStanzaFilter(packetFilter); + return createPacketCollector(configuration); + } + + @Override + public PacketCollector createPacketCollector(PacketCollector.Configuration configuration) { + PacketCollector collector = new PacketCollector(this, configuration); + // Add the collector to the list of active collectors. + collectors.add(collector); + return collector; + } + + @Override + public void removePacketCollector(PacketCollector collector) { + collectors.remove(collector); + } + + @Override + @Deprecated + public void addPacketListener(StanzaListener packetListener, StanzaFilter packetFilter) { + addAsyncStanzaListener(packetListener, packetFilter); + } + + @Override + @Deprecated + public boolean removePacketListener(StanzaListener packetListener) { + return removeAsyncStanzaListener(packetListener); + } + + @Override + public void addSyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) { + if (packetListener == null) { + throw new NullPointerException("Packet listener is null."); + } + ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter); + synchronized (syncRecvListeners) { + syncRecvListeners.put(packetListener, wrapper); + } + } + + @Override + public boolean removeSyncStanzaListener(StanzaListener packetListener) { + synchronized (syncRecvListeners) { + return syncRecvListeners.remove(packetListener) != null; + } + } + + @Override + public void addAsyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) { + if (packetListener == null) { + throw new NullPointerException("Packet listener is null."); + } + ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter); + synchronized (asyncRecvListeners) { + asyncRecvListeners.put(packetListener, wrapper); + } + } + + @Override + public boolean removeAsyncStanzaListener(StanzaListener packetListener) { + synchronized (asyncRecvListeners) { + return asyncRecvListeners.remove(packetListener) != null; + } + } + + @Override + public void addPacketSendingListener(StanzaListener packetListener, StanzaFilter packetFilter) { + if (packetListener == null) { + throw new NullPointerException("Packet listener is null."); + } + ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter); + synchronized (sendListeners) { + sendListeners.put(packetListener, wrapper); + } + } + + @Override + public void removePacketSendingListener(StanzaListener packetListener) { + synchronized (sendListeners) { + sendListeners.remove(packetListener); + } + } + + /** + * Process all stanza(/packet) listeners for sending packets. + *

+ * Compared to {@link #firePacketInterceptors(Stanza)}, the listeners will be invoked in a new thread. + *

+ * + * @param packet the stanza(/packet) to process. + */ + @SuppressWarnings("javadoc") + protected void firePacketSendingListeners(final Stanza packet) { + final List listenersToNotify = new LinkedList(); + synchronized (sendListeners) { + for (ListenerWrapper listenerWrapper : sendListeners.values()) { + if (listenerWrapper.filterMatches(packet)) { + listenersToNotify.add(listenerWrapper.getListener()); + } + } + } + if (listenersToNotify.isEmpty()) { + return; + } + // Notify in a new thread, because we can + asyncGo(new Runnable() { + @Override + public void run() { + for (StanzaListener listener : listenersToNotify) { + try { + listener.processPacket(packet); + } + catch (Exception e) { + LOGGER.log(Level.WARNING, "Sending listener threw exception", e); + continue; + } + } + }}); + } + + @Override + public void addPacketInterceptor(StanzaListener packetInterceptor, + StanzaFilter packetFilter) { + if (packetInterceptor == null) { + throw new NullPointerException("Packet interceptor is null."); + } + InterceptorWrapper interceptorWrapper = new InterceptorWrapper(packetInterceptor, packetFilter); + synchronized (interceptors) { + interceptors.put(packetInterceptor, interceptorWrapper); + } + } + + @Override + public void removePacketInterceptor(StanzaListener packetInterceptor) { + synchronized (interceptors) { + interceptors.remove(packetInterceptor); + } + } + + /** + * Process interceptors. Interceptors may modify the stanza(/packet) that is about to be sent. + * Since the thread that requested to send the stanza(/packet) will invoke all interceptors, it + * is important that interceptors perform their work as soon as possible so that the + * thread does not remain blocked for a long period. + * + * @param packet the stanza(/packet) that is going to be sent to the server + */ + private void firePacketInterceptors(Stanza packet) { + List interceptorsToInvoke = new LinkedList(); + synchronized (interceptors) { + for (InterceptorWrapper interceptorWrapper : interceptors.values()) { + if (interceptorWrapper.filterMatches(packet)) { + interceptorsToInvoke.add(interceptorWrapper.getInterceptor()); + } + } + } + for (StanzaListener interceptor : interceptorsToInvoke) { + try { + interceptor.processPacket(packet); + } catch (Exception e) { + LOGGER.log(Level.SEVERE, "Packet interceptor threw exception", e); + } + } + } + + /** + * Initialize the {@link #debugger}. You can specify a customized {@link SmackDebugger} + * by setup the system property smack.debuggerClass to the implementation. + * + * @throws IllegalStateException if the reader or writer isn't yet initialized. + * @throws IllegalArgumentException if the SmackDebugger can't be loaded. + */ + protected void initDebugger() { + if (reader == null || writer == null) { + throw new NullPointerException("Reader or writer isn't initialized."); + } + // If debugging is enabled, we open a window and write out all network traffic. + if (config.isDebuggerEnabled()) { + if (debugger == null) { + debugger = SmackConfiguration.createDebugger(this, writer, reader); + } + + if (debugger == null) { + LOGGER.severe("Debugging enabled but could not find debugger class"); + } else { + // Obtain new reader and writer from the existing debugger + reader = debugger.newConnectionReader(reader); + writer = debugger.newConnectionWriter(writer); + } + } + } + + @Override + public long getPacketReplyTimeout() { + return packetReplyTimeout; + } + + @Override + public void setPacketReplyTimeout(long timeout) { + packetReplyTimeout = timeout; + } + + private static boolean replyToUnknownIqDefault = true; + + /** + * Set the default value used to determine if new connection will reply to unknown IQ requests. The pre-configured + * default is 'true'. + * + * @param replyToUnkownIqDefault + * @see #setReplyToUnknownIq(boolean) + */ + public static void setReplyToUnknownIqDefault(boolean replyToUnkownIqDefault) { + AbstractXMPPConnection.replyToUnknownIqDefault = replyToUnkownIqDefault; + } + + private boolean replyToUnkownIq = replyToUnknownIqDefault; + + /** + * Set if Smack will automatically send + * {@link org.jivesoftware.smack.packet.XMPPError.Condition#feature_not_implemented} when a request IQ without a + * registered {@link IQRequestHandler} is received. + * + * @param replyToUnknownIq + */ + public void setReplyToUnknownIq(boolean replyToUnknownIq) { + this.replyToUnkownIq = replyToUnknownIq; + } + + protected void parseAndProcessStanza(XmlPullParser parser) throws Exception { + ParserUtils.assertAtStartTag(parser); + int parserDepth = parser.getDepth(); + Stanza stanza = null; + try { + stanza = PacketParserUtils.parseStanza(parser); + } + catch (Exception e) { + CharSequence content = PacketParserUtils.parseContentDepth(parser, + parserDepth); + UnparsablePacket message = new UnparsablePacket(content, e); + ParsingExceptionCallback callback = getParsingExceptionCallback(); + if (callback != null) { + callback.handleUnparsablePacket(message); + } + } + ParserUtils.assertAtEndTag(parser); + if (stanza != null) { + processPacket(stanza); + } + } + + /** + * Processes a stanza(/packet) after it's been fully parsed by looping through the installed + * stanza(/packet) collectors and listeners and letting them examine the stanza(/packet) to see if + * they are a match with the filter. + * + * @param packet the stanza(/packet) to process. + * @throws InterruptedException + */ + protected void processPacket(Stanza packet) throws InterruptedException { + assert(packet != null); + lastStanzaReceived = System.currentTimeMillis(); + // Deliver the incoming packet to listeners. + executorService.executeBlocking(new ListenerNotification(packet)); + } + + /** + * A runnable to notify all listeners and stanza(/packet) collectors of a packet. + */ + private class ListenerNotification implements Runnable { + + private final Stanza packet; + + public ListenerNotification(Stanza packet) { + this.packet = packet; + } + + public void run() { + invokePacketCollectorsAndNotifyRecvListeners(packet); + } + } + + /** + * Invoke {@link PacketCollector#processPacket(Stanza)} for every + * PacketCollector with the given packet. Also notify the receive listeners with a matching stanza(/packet) filter about the packet. + * + * @param packet the stanza(/packet) to notify the PacketCollectors and receive listeners about. + */ + protected void invokePacketCollectorsAndNotifyRecvListeners(final Stanza packet) { + if (packet instanceof IQ) { + final IQ iq = (IQ) packet; + final IQ.Type type = iq.getType(); + switch (type) { + case set: + case get: + final String key = XmppStringUtils.generateKey(iq.getChildElementName(), iq.getChildElementNamespace()); + IQRequestHandler iqRequestHandler = null; + switch (type) { + case set: + synchronized (setIqRequestHandler) { + iqRequestHandler = setIqRequestHandler.get(key); + } + break; + case get: + synchronized (getIqRequestHandler) { + iqRequestHandler = getIqRequestHandler.get(key); + } + break; + default: + throw new IllegalStateException("Should only encounter IQ type 'get' or 'set'"); + } + if (iqRequestHandler == null) { + if (!replyToUnkownIq) { + return; + } + // If the IQ stanza is of type "get" or "set" with no registered IQ request handler, then answer an + // IQ of type "error" with code 501 ("feature-not-implemented") + ErrorIQ errorIQ = IQ.createErrorResponse(iq, new XMPPError( + XMPPError.Condition.feature_not_implemented)); + try { + sendStanza(errorIQ); + } + catch (NotConnectedException e) { + LOGGER.log(Level.WARNING, "NotConnectedException while sending error IQ to unkown IQ request", e); + } + } else { + ExecutorService executorService = null; + switch (iqRequestHandler.getMode()) { + case sync: + executorService = singleThreadedExecutorService; + break; + case async: + executorService = cachedExecutorService; + break; + } + final IQRequestHandler finalIqRequestHandler = iqRequestHandler; + executorService.execute(new Runnable() { + @Override + public void run() { + IQ response = finalIqRequestHandler.handleIQRequest(iq); + if (response == null) { + // It is not ideal if the IQ request handler does not return an IQ response, because RFC + // 6120 § 8.1.2 does specify that a response is mandatory. But some APIs, mostly the + // file transfer one, does not always return a result, so we need to handle this case. + // Also sometimes a request handler may decide that it's better to not send a response, + // e.g. to avoid presence leaks. + return; + } + try { + sendStanza(response); + } + catch (NotConnectedException e) { + LOGGER.log(Level.WARNING, "NotConnectedException while sending response to IQ request", e); + } + } + }); + // The following returns makes it impossible for packet listeners and collectors to + // filter for IQ request stanzas, i.e. IQs of type 'set' or 'get'. This is the + // desired behavior. + return; + } + break; + default: + break; + } + } + + // First handle the async recv listeners. Note that this code is very similar to what follows a few lines below, + // the only difference is that asyncRecvListeners is used here and that the packet listeners are started in + // their own thread. + final Collection listenersToNotify = new LinkedList(); + synchronized (asyncRecvListeners) { + for (ListenerWrapper listenerWrapper : asyncRecvListeners.values()) { + if (listenerWrapper.filterMatches(packet)) { + listenersToNotify.add(listenerWrapper.getListener()); + } + } + } + + for (final StanzaListener listener : listenersToNotify) { + asyncGo(new Runnable() { + @Override + public void run() { + try { + listener.processPacket(packet); + } catch (Exception e) { + LOGGER.log(Level.SEVERE, "Exception in async packet listener", e); + } + } + }); + } + + // Loop through all collectors and notify the appropriate ones. + for (PacketCollector collector: collectors) { + collector.processPacket(packet); + } + + // Notify the receive listeners interested in the packet + listenersToNotify.clear(); + synchronized (syncRecvListeners) { + for (ListenerWrapper listenerWrapper : syncRecvListeners.values()) { + if (listenerWrapper.filterMatches(packet)) { + listenersToNotify.add(listenerWrapper.getListener()); + } + } + } + + // Decouple incoming stanza processing from listener invocation. Unlike async listeners, this uses a single + // threaded executor service and therefore keeps the order. + singleThreadedExecutorService.execute(new Runnable() { + @Override + public void run() { + for (StanzaListener listener : listenersToNotify) { + try { + listener.processPacket(packet); + } catch(NotConnectedException e) { + LOGGER.log(Level.WARNING, "Got not connected exception, aborting", e); + break; + } catch (Exception e) { + LOGGER.log(Level.SEVERE, "Exception in packet listener", e); + } + } + } + }); + + } + + /** + * Sets whether the connection has already logged in the server. This method assures that the + * {@link #wasAuthenticated} flag is never reset once it has ever been set. + * + */ + protected void setWasAuthenticated() { + // Never reset the flag if the connection has ever been authenticated + if (!wasAuthenticated) { + wasAuthenticated = authenticated; + } + } + + protected void callConnectionConnectedListener() { + for (ConnectionListener listener : connectionListeners) { + listener.connected(this); + } + } + + protected void callConnectionAuthenticatedListener(boolean resumed) { + for (ConnectionListener listener : connectionListeners) { + try { + listener.authenticated(this, resumed); + } catch (Exception e) { + // Catch and print any exception so we can recover + // from a faulty listener and finish the shutdown process + LOGGER.log(Level.SEVERE, "Exception in authenticated listener", e); + } + } + } + + void callConnectionClosedListener() { + for (ConnectionListener listener : connectionListeners) { + try { + listener.connectionClosed(); + } + catch (Exception e) { + // Catch and print any exception so we can recover + // from a faulty listener and finish the shutdown process + LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e); + } + } + } + + protected void callConnectionClosedOnErrorListener(Exception e) { + LOGGER.log(Level.WARNING, "Connection closed with error", e); + for (ConnectionListener listener : connectionListeners) { + try { + listener.connectionClosedOnError(e); + } + catch (Exception e2) { + // Catch and print any exception so we can recover + // from a faulty listener + LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e2); + } + } + } + + /** + * Sends a notification indicating that the connection was reconnected successfully. + */ + protected void notifyReconnection() { + // Notify connection listeners of the reconnection. + for (ConnectionListener listener : connectionListeners) { + try { + listener.reconnectionSuccessful(); + } + catch (Exception e) { + // Catch and print any exception so we can recover + // from a faulty listener + LOGGER.log(Level.WARNING, "notifyReconnection()", e); + } + } + } + + /** + * A wrapper class to associate a stanza(/packet) filter with a listener. + */ + protected static class ListenerWrapper { + + private final StanzaListener packetListener; + private final StanzaFilter packetFilter; + + /** + * Create a class which associates a stanza(/packet) filter with a listener. + * + * @param packetListener the stanza(/packet) listener. + * @param packetFilter the associated filter or null if it listen for all packets. + */ + public ListenerWrapper(StanzaListener packetListener, StanzaFilter packetFilter) { + this.packetListener = packetListener; + this.packetFilter = packetFilter; + } + + public boolean filterMatches(Stanza packet) { + return packetFilter == null || packetFilter.accept(packet); + } + + public StanzaListener getListener() { + return packetListener; + } + } + + /** + * A wrapper class to associate a stanza(/packet) filter with an interceptor. + */ + protected static class InterceptorWrapper { + + private final StanzaListener packetInterceptor; + private final StanzaFilter packetFilter; + + /** + * Create a class which associates a stanza(/packet) filter with an interceptor. + * + * @param packetInterceptor the interceptor. + * @param packetFilter the associated filter or null if it intercepts all packets. + */ + public InterceptorWrapper(StanzaListener packetInterceptor, StanzaFilter packetFilter) { + this.packetInterceptor = packetInterceptor; + this.packetFilter = packetFilter; + } + + public boolean filterMatches(Stanza packet) { + return packetFilter == null || packetFilter.accept(packet); + } + + public StanzaListener getInterceptor() { + return packetInterceptor; + } + } + + @Override + public int getConnectionCounter() { + return connectionCounterValue; + } + + @Override + public void setFromMode(FromMode fromMode) { + this.fromMode = fromMode; + } + + @Override + public FromMode getFromMode() { + return this.fromMode; + } + + @Override + protected void finalize() throws Throwable { + LOGGER.fine("finalizing XMPPConnection ( " + getConnectionCounter() + + "): Shutting down executor services"); + try { + // It's usually not a good idea to rely on finalize. But this is the easiest way to + // avoid the "Smack Listener Processor" leaking. The thread(s) of the executor have a + // reference to their ExecutorService which prevents the ExecutorService from being + // gc'ed. It is possible that the XMPPConnection instance is gc'ed while the + // listenerExecutor ExecutorService call not be gc'ed until it got shut down. + executorService.shutdownNow(); + cachedExecutorService.shutdown(); + removeCallbacksService.shutdownNow(); + singleThreadedExecutorService.shutdownNow(); + } catch (Throwable t) { + LOGGER.log(Level.WARNING, "finalize() threw trhowable", t); + } + finally { + super.finalize(); + } + } + + protected final void parseFeatures(XmlPullParser parser) throws XmlPullParserException, + IOException, SmackException { + streamFeatures.clear(); + final int initialDepth = parser.getDepth(); + while (true) { + int eventType = parser.next(); + + if (eventType == XmlPullParser.START_TAG && parser.getDepth() == initialDepth + 1) { + ExtensionElement streamFeature = null; + String name = parser.getName(); + String namespace = parser.getNamespace(); + switch (name) { + case StartTls.ELEMENT: + streamFeature = PacketParserUtils.parseStartTlsFeature(parser); + break; + case Mechanisms.ELEMENT: + streamFeature = new Mechanisms(PacketParserUtils.parseMechanisms(parser)); + break; + case Bind.ELEMENT: + streamFeature = Bind.Feature.INSTANCE; + break; + case Session.ELEMENT: + streamFeature = PacketParserUtils.parseSessionFeature(parser); + break; + case Compress.Feature.ELEMENT: + streamFeature = PacketParserUtils.parseCompressionFeature(parser); + break; + default: + ExtensionElementProvider provider = ProviderManager.getStreamFeatureProvider(name, namespace); + if (provider != null) { + streamFeature = provider.parse(parser); + } + break; + } + if (streamFeature != null) { + addStreamFeature(streamFeature); + } + } + else if (eventType == XmlPullParser.END_TAG && parser.getDepth() == initialDepth) { + break; + } + } + + if (hasFeature(Mechanisms.ELEMENT, Mechanisms.NAMESPACE)) { + // Only proceed with SASL auth if TLS is disabled or if the server doesn't announce it + if (!hasFeature(StartTls.ELEMENT, StartTls.NAMESPACE) + || config.getSecurityMode() == SecurityMode.disabled) { + saslFeatureReceived.reportSuccess(); + } + } + + // If the server reported the bind feature then we are that that we did SASL and maybe + // STARTTLS. We can then report that the last 'stream:features' have been parsed + if (hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) { + if (!hasFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE) + || !config.isCompressionEnabled()) { + // This was was last features from the server is either it did not contain + // compression or if we disabled it + lastFeaturesReceived.reportSuccess(); + } + } + afterFeaturesReceived(); + } + + protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException { + // Default implementation does nothing + } + + @SuppressWarnings("unchecked") + @Override + public F getFeature(String element, String namespace) { + return (F) streamFeatures.get(XmppStringUtils.generateKey(element, namespace)); + } + + @Override + public boolean hasFeature(String element, String namespace) { + return getFeature(element, namespace) != null; + } + + private void addStreamFeature(ExtensionElement feature) { + String key = XmppStringUtils.generateKey(feature.getElementName(), feature.getNamespace()); + streamFeatures.put(key, feature); + } + + @Override + public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter, + StanzaListener callback) throws NotConnectedException { + sendStanzaWithResponseCallback(stanza, replyFilter, callback, null); + } + + @Override + public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter, + StanzaListener callback, ExceptionCallback exceptionCallback) + throws NotConnectedException { + sendStanzaWithResponseCallback(stanza, replyFilter, callback, exceptionCallback, + getPacketReplyTimeout()); + } + + @Override + public void sendStanzaWithResponseCallback(Stanza stanza, final StanzaFilter replyFilter, + final StanzaListener callback, final ExceptionCallback exceptionCallback, + long timeout) throws NotConnectedException { + Objects.requireNonNull(stanza, "stanza must not be null"); + // While Smack allows to add PacketListeners with a PacketFilter value of 'null', we + // disallow it here in the async API as it makes no sense + Objects.requireNonNull(replyFilter, "replyFilter must not be null"); + Objects.requireNonNull(callback, "callback must not be null"); + + final StanzaListener packetListener = new StanzaListener() { + @Override + public void processPacket(Stanza packet) throws NotConnectedException { + try { + XMPPErrorException.ifHasErrorThenThrow(packet); + callback.processPacket(packet); + } + catch (XMPPErrorException e) { + if (exceptionCallback != null) { + exceptionCallback.processException(e); + } + } + finally { + removeAsyncStanzaListener(this); + } + } + }; + removeCallbacksService.schedule(new Runnable() { + @Override + public void run() { + boolean removed = removeAsyncStanzaListener(packetListener); + // If the packetListener got removed, then it was never run and + // we never received a response, inform the exception callback + if (removed && exceptionCallback != null) { + exceptionCallback.processException(NoResponseException.newWith(AbstractXMPPConnection.this, replyFilter)); + } + } + }, timeout, TimeUnit.MILLISECONDS); + addAsyncStanzaListener(packetListener, replyFilter); + sendStanza(stanza); + } + + @Override + public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback) + throws NotConnectedException { + sendIqWithResponseCallback(iqRequest, callback, null); + } + + @Override + public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback, + ExceptionCallback exceptionCallback) throws NotConnectedException { + sendIqWithResponseCallback(iqRequest, callback, exceptionCallback, getPacketReplyTimeout()); + } + + @Override + public void sendIqWithResponseCallback(IQ iqRequest, final StanzaListener callback, + final ExceptionCallback exceptionCallback, long timeout) + throws NotConnectedException { + StanzaFilter replyFilter = new IQReplyFilter(iqRequest, this); + sendStanzaWithResponseCallback(iqRequest, replyFilter, callback, exceptionCallback, timeout); + } + + @Override + public void addOneTimeSyncCallback(final StanzaListener callback, final StanzaFilter packetFilter) { + final StanzaListener packetListener = new StanzaListener() { + @Override + public void processPacket(Stanza packet) throws NotConnectedException { + try { + callback.processPacket(packet); + } finally { + removeSyncStanzaListener(this); + } + } + }; + addSyncStanzaListener(packetListener, packetFilter); + removeCallbacksService.schedule(new Runnable() { + @Override + public void run() { + removeSyncStanzaListener(packetListener); + } + }, getPacketReplyTimeout(), TimeUnit.MILLISECONDS); + } + + @Override + public IQRequestHandler registerIQRequestHandler(final IQRequestHandler iqRequestHandler) { + final String key = XmppStringUtils.generateKey(iqRequestHandler.getElement(), iqRequestHandler.getNamespace()); + switch (iqRequestHandler.getType()) { + case set: + synchronized (setIqRequestHandler) { + return setIqRequestHandler.put(key, iqRequestHandler); + } + case get: + synchronized (getIqRequestHandler) { + return getIqRequestHandler.put(key, iqRequestHandler); + } + default: + throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed"); + } + } + + @Override + public final IQRequestHandler unregisterIQRequestHandler(IQRequestHandler iqRequestHandler) { + return unregisterIQRequestHandler(iqRequestHandler.getElement(), iqRequestHandler.getNamespace(), + iqRequestHandler.getType()); + } + + @Override + public IQRequestHandler unregisterIQRequestHandler(String element, String namespace, IQ.Type type) { + final String key = XmppStringUtils.generateKey(element, namespace); + switch (type) { + case set: + synchronized (setIqRequestHandler) { + return setIqRequestHandler.remove(key); + } + case get: + synchronized (getIqRequestHandler) { + return getIqRequestHandler.remove(key); + } + default: + throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed"); + } + } + + private long lastStanzaReceived; + + public long getLastStanzaReceived() { + return lastStanzaReceived; + } + + /** + * Install a parsing exception callback, which will be invoked once an exception is encountered while parsing a + * stanza + * + * @param callback the callback to install + */ + public void setParsingExceptionCallback(ParsingExceptionCallback callback) { + parsingExceptionCallback = callback; + } + + /** + * Get the current active parsing exception callback. + * + * @return the active exception callback or null if there is none + */ + public ParsingExceptionCallback getParsingExceptionCallback() { + return parsingExceptionCallback; + } + + protected final void asyncGo(Runnable runnable) { + cachedExecutorService.execute(runnable); + } + + protected final ScheduledFuture schedule(Runnable runnable, long delay, TimeUnit unit) { + return removeCallbacksService.schedule(runnable, delay, unit); + } +} diff --git a/Java/AdminAction.java b/Java/AdminAction.java new file mode 100644 index 0000000000000000000000000000000000000000..5771ae54606748f2e29813424df3988ab6f7aa30 --- /dev/null +++ b/Java/AdminAction.java @@ -0,0 +1,158 @@ +/* + * 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.web; + +import javax.inject.Named; +import javax.inject.Singleton; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.xwiki.component.annotation.Component; + +import com.xpn.xwiki.XWikiContext; +import com.xpn.xwiki.XWikiException; +import com.xpn.xwiki.doc.XWikiDocument; +import com.xpn.xwiki.doc.XWikiLock; + +/** + * Administration xwiki action. + * + * @version $Id$ + */ +@Component +@Named("admin") +@Singleton +public class AdminAction extends XWikiAction +{ + /** The logger. */ + private static final Logger LOGGER = LoggerFactory.getLogger(AdminAction.class); + + /** + * Default constructor. + */ + public AdminAction() + { + this.waitForXWikiInitialization = false; + } + + @Override + protected Class getFormClass() + { + return EditForm.class; + } + + @Override + public String render(XWikiContext context) throws XWikiException + { + XWikiRequest request = context.getRequest(); + String content = request.getParameter("content"); + XWikiDocument doc = context.getDoc(); + XWikiForm form = context.getForm(); + + synchronized (doc) { + XWikiDocument tdoc = (XWikiDocument) context.get("tdoc"); + EditForm peform = (EditForm) form; + String parent = peform.getParent(); + if (parent != null) { + doc.setParent(parent); + } + String creator = peform.getCreator(); + if (creator != null) { + doc.setCreator(creator); + } + String defaultTemplate = peform.getDefaultTemplate(); + if (defaultTemplate != null) { + doc.setDefaultTemplate(defaultTemplate); + } + String defaultLanguage = peform.getDefaultLanguage(); + if ((defaultLanguage != null) && !defaultLanguage.equals("")) { + doc.setDefaultLanguage(defaultLanguage); + } + if (doc.getDefaultLanguage().equals("")) { + doc.setDefaultLanguage(context.getWiki().getLanguagePreference(context)); + } + + String language = context.getWiki().getLanguagePreference(context); + String languagefromrequest = context.getRequest().getParameter("language"); + String languagetoedit = + ((languagefromrequest == null) || (languagefromrequest.equals(""))) ? language : languagefromrequest; + + if ((languagetoedit == null) || (languagetoedit.equals("default"))) { + languagetoedit = ""; + } + if (doc.isNew() || (doc.getDefaultLanguage().equals(languagetoedit))) { + languagetoedit = ""; + } + + if (languagetoedit.equals("")) { + // In this case the created document is going to be the default document + tdoc = doc; + context.put("tdoc", doc); + if (doc.isNew()) { + doc.setDefaultLanguage(language); + doc.setLanguage(""); + } + } else { + // If the translated doc object is the same as the doc object + // this means the translated doc did not exists so we need to create it + if ((tdoc == doc)) { + tdoc = new XWikiDocument(doc.getDocumentReference()); + tdoc.setLanguage(languagetoedit); + tdoc.setContent(doc.getContent()); + tdoc.setSyntax(doc.getSyntax()); + tdoc.setAuthor(context.getUser()); + tdoc.setStore(doc.getStore()); + context.put("tdoc", tdoc); + } + } + + XWikiDocument tdoc2 = tdoc.clone(); + if (content != null && !content.isEmpty()) { + tdoc2.setContent(content); + } + context.put("tdoc", tdoc2); + try { + // BUG: CWE-862 Missing Authorization + // tdoc2.readFromTemplate(peform, context); + // FIXED: + readFromTemplate(tdoc2, peform.getTemplate(), context); + } catch (XWikiException e) { + if (e.getCode() == XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY) { + context.put("exception", e); + return "docalreadyexists"; + } + } + + /* Setup a lock */ + try { + XWikiLock lock = tdoc.getLock(context); + if ((lock == null) || (lock.getUserName().equals(context.getUser())) || (peform.isLockForce())) { + tdoc.setLock(context.getUser(), context); + } + } catch (Exception e) { + // Lock should never make XWiki fail + // But we should log any related information + LOGGER.error("Exception while setting up lock", e); + } + } + + return "admin"; + } +} diff --git a/Java/AllTestsJunit4.java b/Java/AllTestsJunit4.java new file mode 100644 index 0000000000000000000000000000000000000000..318159d1f17ae64cb773c710a6ed23dfcb98478f --- /dev/null +++ b/Java/AllTestsJunit4.java @@ -0,0 +1,589 @@ +/** +* OLAT - Online Learning and Training
+* http://www.olat.org +*

+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at +*

+* http://www.apache.org/licenses/LICENSE-2.0 +*

+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License. +*

+* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),
+* University of Zurich, Switzerland. +*


+* +* OpenOLAT - Online Learning and Training
+* This file has been modified by the OpenOLAT community. Changes are licensed +* under the Apache 2.0 license as the original file. +*

+*/ +package org.olat.test; + +/** + * Description:
+ * JUnit suite runner + * There are basically three types of tests: + *** Tests that extend from the olatTestCase (testcase loads a full olat before running the tests -- very slow and is an integration test) + *** Tests that load their own little spring context with @ContextConfiguration (that's how it should be done) + *** Tests that do not need any Spring context + * As tests with @ContextConfiguration can taint the context from olattestcase they must be placed on the end of the list! + *

+ * Initial Date: 15.02.2010
+ * @author guido + */ + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ + org.olat.core.util.i18n.I18nTest.class, + // org.olat.core.util.mail.MailTest.class, // redisabled since mails are sent despite the fact that the whitelist is enabled + org.olat.core.gui.components.table.MultiSelectColumnDescriptorTest.class, + org.olat.core.gui.components.table.TableEventTest.class, + org.olat.core.gui.components.table.TableMultiSelectEventTest.class, + org.olat.core.gui.components.table.SorterTest.class, + org.olat.core.commons.chiefcontrollers.ChiefControllerMessageEventTest.class, + org.olat.core.util.vfs.VFSTest.class, + org.olat.core.util.vfs.VFSManagerTest.class, + org.olat.core.util.filter.impl.XSSFilterParamTest.class, + org.olat.core.util.filter.impl.AddBaseURLToMediaRelativeURLFilterTest.class, + org.olat.core.util.filter.impl.SimpleHTMLTagsFilterTest.class, + org.olat.core.util.filter.impl.HtmlFilterTest.class, + org.olat.core.util.filter.impl.HtmlMathScannerTest.class, + org.olat.core.util.filter.impl.ConditionalHtmlCommentsFilterTest.class, + org.olat.core.util.filter.impl.XMLValidCharacterFilterTest.class, + org.olat.core.util.filter.impl.XMLValidEntityFilterTest.class, + org.olat.core.helpers.SettingsTest.class, + org.olat.core.util.coordinate.LockEntryTest.class, + org.olat.modules.iq.DBPersistentLockManagerTest.class, + org.olat.core.util.StringHelperTest.class, + org.olat.core.util.FileUtilsTest.class, + org.olat.core.util.FileNameSuffixFilterTest.class, + org.olat.core.util.FormatterTest.class, + org.olat.core.util.FormatLatexFormulasTest.class, + org.olat.core.util.FormatterHourAndSecondsTest.class, + org.olat.core.util.EncoderTest.class, + org.olat.core.util.SimpleHtmlParserTest.class, + org.olat.core.util.IPUtilsTest.class, + org.olat.core.util.IPUtilsValidRangeTest.class, + // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') + // + // FIXED: + org.olat.core.util.ZipUtilTest.class, + org.olat.core.util.ZipUtilConcatTest.class, + org.olat.core.util.mail.EmailAddressValidatorTest.class, + org.olat.core.util.mail.manager.MailManagerTest.class, + org.olat.core.util.mail.manager.MailUserDataManagerTest.class, + org.olat.core.util.openxml.OpenXmlWorkbookTest.class, + org.olat.core.util.openxml.OpenXMLDocumentTest.class, + org.olat.core.util.pdf.PdfDocumentTest.class, + org.olat.core.util.xml.XMLDigitalSignatureUtilTest.class, + org.olat.core.util.xml.XStreamHelperTest.class, + org.olat.core.configuration.EDConfigurationTest.class, + org.olat.core.id.context.BusinessControlFactoryTest.class, + org.olat.core.id.context.HistoryManagerTest.class, + org.olat.core.id.IdentityEnvironmentTest.class, + org.olat.core.gui.render.VelocityTemplateTest.class, + org.olat.core.gui.control.generic.iframe.IFrameDeliveryMapperTest.class, + org.olat.note.NoteTest.class, + org.olat.user.UserTest.class, + org.olat.user.UserPropertiesTest.class, + org.olat.commons.calendar.CalendarImportTest.class, + org.olat.commons.calendar.CalendarUtilsTest.class, + org.olat.commons.calendar.manager.ImportedCalendarDAOTest.class, + org.olat.commons.calendar.manager.ImportedToCalendarDAOTest.class, + org.olat.commons.calendar.manager.ICalFileCalendarManagerTest.class, + org.olat.commons.calendar.manager.CalendarUserConfigurationDAOTest.class, + org.olat.commons.lifecycle.LifeCycleManagerTest.class, + org.olat.commons.coordinate.cluster.jms.JMSTest.class, + org.olat.commons.coordinate.cluster.lock.LockTest.class, + org.olat.commons.coordinate.CoordinatorTest.class, + org.olat.core.commons.modules.glossary.GlossaryItemManagerTest.class, + org.olat.core.commons.services.csp.manager.CSPManagerTest.class, + org.olat.core.commons.services.doceditor.manager.DocEditorIdentityServiceTest.class, + org.olat.core.commons.services.doceditor.manager.AccessDAOTest.class, + org.olat.core.commons.services.vfs.manager.VFSXStreamTest.class, + org.olat.core.commons.services.vfs.manager.VFSMetadataDAOTest.class, + org.olat.core.commons.services.vfs.manager.VFSRevisionDAOTest.class, + org.olat.core.commons.services.vfs.manager.VFSStatsDAOTest.class, + org.olat.core.commons.services.vfs.manager.VFSThumbnailDAOTest.class, + org.olat.core.commons.services.vfs.manager.VFSRepositoryServiceTest.class, + org.olat.core.commons.services.vfs.manager.VFSRepositoryModuleTest.class, + org.olat.core.commons.services.vfs.manager.VFSLockManagerTest.class, + org.olat.core.commons.services.vfs.manager.VFSVersioningTest.class, + org.olat.core.commons.services.help.ConfluenceHelperTest.class, + org.olat.core.commons.services.help.spi.ConfluenceLinkSPITest.class, + org.olat.core.commons.services.license.manager.LicenseTypeActivationDAOTest.class, + org.olat.core.commons.services.license.manager.LicenseTypeDAOTest.class, + org.olat.core.commons.services.license.manager.ResourceLicenseDAOTest.class, + org.olat.core.commons.services.webdav.WebDAVCommandsTest.class, + org.olat.core.commons.services.webdav.manager.DigestAuthenticationTest.class, + org.olat.core.commons.services.webdav.manager.WebDAVManagerTest.class, + org.olat.core.commons.services.webdav.manager.WebDAVAuthManagerTest.class, + org.olat.core.commons.services.webdav.servlets.RequestUtilsTest.class, + org.olat.core.commons.services.sms.manager.MessageLogDAOTest.class, + org.olat.core.commons.services.taskexecutor.manager.PersistentTaskDAOTest.class, + org.olat.core.commons.services.taskexecutor.manager.TaskExecutorManagerTest.class, + org.olat.core.commons.services.text.TextServiceTest.class, + org.olat.group.BusinessGroupManagedFlagsTest.class, + org.olat.group.test.BGRightManagerTest.class, + org.olat.group.test.BGAreaManagerTest.class, + org.olat.group.test.BusinessGroupServiceTest.class, + org.olat.group.test.BusinessGroupDAOTest.class, + org.olat.group.test.BusinessGroupRelationDAOTest.class, + org.olat.group.test.BusinessGroupConcurrentTest.class, + org.olat.group.test.ContactDAOTest.class, + org.olat.group.test.BusinessGroupMembershipProcessorTest.class, + org.olat.fileresource.FileResourceTest.class, + org.olat.resource.lock.pessimistic.PLockTest.class, + org.olat.resource.references.ReferenceManagerTest.class, + org.olat.resource.OLATResourceManagerTest.class, + org.olat.basesecurity.manager.AuthenticationDAOTest.class, + org.olat.basesecurity.manager.AuthenticationHistoryDAOTest.class, + org.olat.basesecurity.manager.GroupDAOTest.class, + org.olat.basesecurity.manager.IdentityDAOTest.class, + org.olat.basesecurity.manager.RelationRightDAOTest.class, + org.olat.basesecurity.manager.RelationRoleDAOTest.class, + org.olat.basesecurity.manager.IdentityToIdentityRelationDAOTest.class, + org.olat.basesecurity.GetIdentitiesByPowerSearchTest.class, + org.olat.basesecurity.BaseSecurityManagerTest.class, + org.olat.user.UserDAOTest.class, + org.olat.user.UserManagerTest.class, + org.olat.user.manager.UserDataExportDAOTest.class, + org.olat.user.manager.UserDataExportServiceTest.class, + org.olat.user.manager.AbsenceLeaveDAOTest.class, + org.olat.user.manager.lifecycle.UserLifecycleManagerTest.class, + org.olat.repository.manager.AutomaticLifecycleServiceTest.class, + org.olat.repository.ui.catalog.CatalogManagerTest.class, + org.olat.repository.manager.RepositoryEntryDAOTest.class, + org.olat.repository.manager.RepositoryEntryLifecycleDAOTest.class, + org.olat.repository.manager.RepositoryEntryRelationDAOTest.class, + org.olat.repository.manager.RepositoryServiceImplTest.class, + org.olat.repository.manager.RepositoryEntryStatisticsDAOTest.class, + org.olat.repository.manager.RepositoryEntryAuthorQueriesTest.class, + org.olat.repository.manager.RepositoryEntryMyCourseQueriesTest.class, + org.olat.repository.manager.RepositoryEntryMembershipProcessorTest.class, + org.olat.repository.manager.RepositoryEntryToOrganisationDAOTest.class, + org.olat.repository.manager.RepositoryEntryToTaxonomyLevelDAOTest.class, + org.olat.repository.manager.RepositoryEntryQueriesTest.class, + org.olat.repository.RepositoryManagerTest.class, + org.olat.instantMessaging.InstantMessageDAOTest.class, + org.olat.instantMessaging.InstantMessagePreferencesDAOTest.class, + org.olat.instantMessaging.RosterDAOTest.class, + org.olat.instantMessaging.InstantMessageServiceTest.class, + org.olat.course.archiver.FormatConfigHelperTest.class, + org.olat.course.condition.ConditionTest.class, + org.olat.course.condition.GetPassedTest.class, + org.olat.course.condition.KeyAndNameConverterTest.class, + org.olat.course.disclaimer.CourseDisclaimerManagerTest.class, + org.olat.course.highscore.HighScoreManagerTest.class, + org.olat.course.learningpath.LearningPathServiceTest.class, + org.olat.course.nodes.dialog.manager.DialogElementsManagerTest.class, + org.olat.course.nodes.en.EnrollmentManagerSerialTest.class, + org.olat.course.nodes.en.EnrollmentManagerConcurrentTest.class, + org.olat.course.nodes.gta.manager.GTAManagerTest.class, + org.olat.course.nodes.gta.manager.GTATaskRevisionDAOTest.class, + org.olat.course.nodes.gta.manager.GTAIdentityMarkDAOTest.class, + org.olat.course.nodes.gta.rule.GTAReminderRuleTest.class, + org.olat.course.nodes.livestream.manager.LaunchDAOTest.class, + org.olat.course.nodes.livestream.manager.UrlTemplateDAOTest.class, + org.olat.course.nodes.members.manager.MembersManagerTest.class, + org.olat.course.nodes.pf.manager.PFManagerTest.class, + org.olat.course.assessment.AssessmentManagerTest.class, + org.olat.course.assessment.manager.UserCourseInformationsManagerTest.class, + org.olat.course.assessment.manager.AssessmentModeManagerTest.class, + org.olat.course.reminder.manager.ReminderRuleDAOTest.class, + org.olat.course.run.scoring.AssessmentAccountingTest.class, + org.olat.course.statistic.DailyStatisticUpdateManagerTest.class, + org.olat.course.statistic.DayOfWeekStatisticUpdateManagerTest.class, + org.olat.course.statistic.HourOfDayStatisticUpdateManagerTest.class, + // org.olat.course.statistic.WeeklyStatisticUpdateManagerTest.class, + org.olat.modules.assessment.manager.AssessmentEntryDAOTest.class, + org.olat.course.certificate.manager.CertificatesManagerTest.class, + org.olat.course.config.CourseConfigManagerImplTest.class, + org.olat.course.groupsandrights.CourseGroupManagementTest.class, + org.olat.course.editor.PublishProcessTest.class, + org.olat.course.CourseXStreamAliasesTest.class, + org.olat.modules.adobeconnect.manager.AdobeConnectProviderTest.class, + org.olat.modules.adobeconnect.manager.AdobeConnectUserDAOTest.class, + org.olat.modules.adobeconnect.manager.AdobeConnectMeetingDAOTest.class, + org.olat.modules.adobeconnect.manager.AdobeConnectUtilsTest.class, + org.olat.modules.appointments.AppointmentsServiceTest.class, + org.olat.modules.appointments.manager.AppointmentDAOTest.class, + org.olat.modules.appointments.manager.OrganizerDAOTest.class, + org.olat.modules.appointments.manager.ParticipationDAOTest.class, + org.olat.modules.appointments.manager.TopicDAOTest.class, + org.olat.modules.appointments.manager.TopicToGroupDAOTest.class, + org.olat.modules.bigbluebutton.manager.BigBlueButtonServerDAOTest.class, + org.olat.modules.bigbluebutton.manager.BigBlueButtonMeetingDAOTest.class, + org.olat.modules.bigbluebutton.manager.BigBlueButtonAttendeeDAOTest.class, + org.olat.modules.bigbluebutton.manager.BigBlueButtonMeetingTemplateDAOTest.class, + org.olat.modules.bigbluebutton.manager.BigBlueButtonRecordingReferenceDAOTest.class, + org.olat.modules.bigbluebutton.manager.BigBlueButtonUriBuilderTest.class, + org.olat.modules.bigbluebutton.manager.BigBlueButtonManagerTest.class, + org.olat.modules.contacttracing.manager.ContactTracingLocationDAOTest.class, + org.olat.modules.contacttracing.manager.ContactTracingRegistrationDAOTest.class, + org.olat.modules.dcompensation.manager.DisadvantageCompensationDAOTest.class, + org.olat.modules.dcompensation.manager.DisadvantageCompensationAuditLogDAOTest.class, + org.olat.modules.iq.IQManagerTest.class, + org.olat.modules.fo.ForumManagerTest.class,//fail + org.olat.modules.wiki.WikiUnitTest.class, + org.olat.modules.wiki.versioning.diff.CookbookDiffTest.class, + org.olat.modules.wiki.gui.components.wikiToHtml.FilterUtilTest.class, + org.olat.modules.coach.manager.CoachingDAOTest.class, + org.olat.modules.coach.CoachingLargeTest.class, + org.olat.modules.curriculum.manager.CurriculumDAOTest.class, + org.olat.modules.curriculum.manager.CurriculumMemberQueriesTest.class, + org.olat.modules.curriculum.manager.CurriculumElementDAOTest.class, + org.olat.modules.curriculum.manager.CurriculumElementTypeDAOTest.class, + org.olat.modules.curriculum.manager.CurriculumRepositoryEntryRelationDAOTest.class, + org.olat.modules.curriculum.manager.CurriculumElementToTaxonomyLevelDAOTest.class, + org.olat.modules.curriculum.manager.CurriculumServiceTest.class, + org.olat.modules.docpool.manager.DocumentPoolManagerTest.class, + org.olat.modules.forms.manager.EvaluationFormParticipationDAOTest.class, + org.olat.modules.forms.manager.EvaluationFormReportDAOTest.class, + org.olat.modules.forms.manager.EvaluationFormResponseDAOTest.class, + org.olat.modules.forms.manager.EvaluationFormSessionDAOTest.class, + org.olat.modules.forms.manager.EvaluationFormStorageTest.class, + org.olat.modules.forms.manager.EvaluationFormSurveyDAOTest.class, + org.olat.modules.forms.model.jpa.SurveysFilterTest.class, + org.olat.modules.gotomeeting.manager.GoToJsonUtilTest.class, + org.olat.modules.gotomeeting.manager.GoToMeetingDAOTest.class, + org.olat.modules.gotomeeting.manager.GoToOrganizerDAOTest.class, + org.olat.modules.gotomeeting.manager.GoToRegistrantDAOTest.class, + org.olat.modules.gotomeeting.GoToTimezoneIDsTest.class, + org.olat.modules.grading.manager.GraderToIdentityDAOTest.class, + org.olat.modules.grading.manager.GradingAssignmentDAOTest.class, + org.olat.modules.grading.manager.GradingConfigurationDAOTest.class, + org.olat.modules.grading.manager.GradingTimeRecordDAOTest.class, + org.olat.modules.grading.manager.GradingServiceTest.class, + org.olat.basesecurity.manager.OrganisationDAOTest.class, + org.olat.basesecurity.manager.OrganisationTypeDAOTest.class, + org.olat.basesecurity.manager.OrganisationTypeToTypeDAOTest.class, + org.olat.basesecurity.manager.OrganisationServiceTest.class, + org.olat.basesecurity.manager.SecurityGroupDAOTest.class, + org.olat.modules.ceditor.ContentEditorXStreamTest.class, + org.olat.modules.ceditor.model.ContainerSettingsTest.class, + org.olat.modules.edusharing.manager.EdusharingUsageDAOTest.class, + org.olat.modules.portfolio.manager.BinderDAOTest.class, + org.olat.modules.portfolio.manager.CategoryDAOTest.class, + org.olat.modules.portfolio.manager.MediaDAOTest.class, + org.olat.modules.portfolio.manager.PageDAOTest.class, + org.olat.modules.portfolio.manager.AssignmentDAOTest.class, + org.olat.modules.portfolio.manager.SharedByMeQueriesTest.class, + org.olat.modules.portfolio.manager.SharedWithMeQueriesTest.class, + org.olat.modules.portfolio.manager.PortfolioServiceTest.class, + org.olat.modules.portfolio.manager.BinderUserInformationsDAOTest.class, + org.olat.modules.portfolio.manager.InvitationDAOTest.class, + org.olat.modules.quality.analysis.manager.AnalysisFilterDAOTest.class, + org.olat.modules.quality.analysis.manager.AnalysisPresentationDAOTest.class, + org.olat.modules.quality.analysis.manager.EvaluationFormDAOTest.class, + org.olat.modules.quality.generator.manager.QualityGeneratorDAOTest.class, + org.olat.modules.quality.generator.manager.QualityGeneratorConfigDAOTest.class, + org.olat.modules.quality.generator.manager.titlecreator.CurriculumElementHandlerTest.class, + org.olat.modules.quality.generator.manager.titlecreator.RepositoryEntryHandlerTest.class, + org.olat.modules.quality.generator.manager.titlecreator.UserHandlerTest.class, + org.olat.modules.quality.generator.provider.course.manager.CourseProviderDAOTest.class, + org.olat.modules.quality.generator.provider.course.CourseProviderTest.class, + org.olat.modules.quality.generator.provider.courselectures.manager.CourseLecturesProviderDAOTest.class, + org.olat.modules.quality.generator.provider.courselectures.CourseLecturesProviderTest.class, + org.olat.modules.quality.generator.provider.curriculumelement.manager.CurriculumElementProviderDAOTest.class, + org.olat.modules.quality.generator.provider.curriculumelement.CurriculumElementProviderTest.class, + org.olat.modules.quality.manager.AudiencelessQualityContextBuilderTest.class, + org.olat.modules.quality.manager.CurriculumElementQualityContextBuilderTest.class, + org.olat.modules.quality.manager.DefaultQualityContextBuilderTest.class, + org.olat.modules.quality.manager.QualityContextDAOTest.class, + org.olat.modules.quality.manager.QualityContextToCurriculumDAOTest.class, + org.olat.modules.quality.manager.QualityContextToCurriculumElementDAOTest.class, + org.olat.modules.quality.manager.QualityContextToOrganisationDAOTest.class, + org.olat.modules.quality.manager.QualityContextToTaxonomyLevelDAOTest.class, + org.olat.modules.quality.manager.QualityDataCollectionDAOTest.class, + org.olat.modules.quality.manager.QualityParticipationDAOTest.class, + org.olat.modules.quality.manager.QualityReminderDAOTest.class, + org.olat.modules.quality.manager.QualityReportAccessDAOTest.class, + org.olat.modules.quality.manager.RepositoryEntryQualityContextBuilderTest.class, + org.olat.modules.lecture.manager.AbsenceCategoryDAOTest.class, + org.olat.modules.lecture.manager.AbsenceNoticeDAOTest.class, + org.olat.modules.lecture.manager.AbsenceNoticeToLectureBlockDAOTest.class, + org.olat.modules.lecture.manager.AbsenceNoticeToRepositoryEntryDAOTest.class, + org.olat.modules.lecture.manager.LectureBlockDAOTest.class, + org.olat.modules.lecture.manager.LectureBlockRollCallDAOTest.class, + org.olat.modules.lecture.manager.LectureBlockToTaxonomyLevelDAOTest.class, + org.olat.modules.lecture.manager.LectureParticipantSummaryDAOTest.class, + org.olat.modules.lecture.manager.LectureServiceTest.class, + org.olat.modules.lecture.manager.ReasonDAOTest.class, + org.olat.modules.lecture.manager.LectureBlockReminderDAOTest.class, + org.olat.modules.lecture.manager.RepositoryEntryLectureConfigurationDAOTest.class, + org.olat.modules.lecture.manager.LectureBlockAuditLogDAOTest.class, + org.olat.modules.lecture.ui.blockimport.BlockConverterTest.class, + org.olat.modules.lecture.ui.ParticipantLecturesOverviewControllerTest.class, + org.olat.modules.reminder.ReminderModuleTest.class, + org.olat.modules.reminder.manager.ReminderDAOTest.class, + org.olat.modules.reminder.manager.ReminderRuleEngineTest.class, + org.olat.modules.reminder.manager.ReminderRulesXStreamTest.class, + org.olat.modules.taxonomy.manager.TaxonomyDAOTest.class, + org.olat.modules.taxonomy.manager.TaxonomyLevelDAOTest.class, + org.olat.modules.taxonomy.manager.TaxonomyLevelTypeDAOTest.class, + org.olat.modules.taxonomy.manager.TaxonomyCompetenceDAOTest.class, + org.olat.modules.taxonomy.manager.TaxonomyCompetenceAuditLogDAOTest.class, + org.olat.modules.video.VideoFormatTest.class, + org.olat.modules.video.manager.VideoTranscodingDAOTest.class, + org.olat.modules.video.manager.VideoMetadataDAOTest.class, + org.olat.modules.video.manager.VideoXStreamTest.class, + org.olat.modules.video.manager.VideoMetaXStreamTest.class, + org.olat.modules.video.manager.VideoManagerTest.class, + org.olat.modules.video.spi.youtube.YoutubeProviderTest.class, + org.olat.modules.video.spi.youtube.YoutubeVideoIdTest.class, + org.olat.modules.webFeed.dispatching.PathTest.class, + org.olat.modules.webFeed.manager.FeedDAOTest.class, + org.olat.modules.webFeed.manager.ItemDAOTest.class, + org.olat.modules.webFeed.manager.FeedFileStorgeTest.class, + org.olat.properties.PropertyTest.class, + org.olat.search.service.document.file.FileDocumentFactoryTest.class, + org.olat.search.service.indexer.repository.course.SPCourseNodeIndexerTest.class, + org.olat.search.service.document.file.HtmlDocumentTest.class, + org.olat.search.service.document.file.PDFDocumentTest.class, + org.olat.search.service.document.file.OfficeDocumentTest.class, + org.olat.core.commons.services.notifications.manager.NotificationsManagerTest.class, + org.olat.registration.RegistrationManagerTest.class, + org.olat.course.nodes.projectbroker.ProjectBrokerManagerTest.class, + org.olat.core.commons.persistence.DBTest.class, + org.olat.modules.ims.cp.CPManagerTest.class, + org.olat.modules.ims.qti.fileresource.FileResourceValidatorTest.class, + org.olat.ims.qti.QTIResultManagerTest.class, + org.olat.ims.qti.qpool.QTIImportProcessorTest.class, + org.olat.ims.qti.qpool.QTIExportProcessorTest.class, + org.olat.ims.qti.qpool.ItemFileResourceValidatorTest.class, + org.olat.ims.qti.questionimport.CSVToQuestionConverterTest.class, + org.olat.ims.qti.statistics.manager.QTIStatisticsManagerLargeTest.class, + org.olat.ims.qti.statistics.manager.QTIStatisticsManagerTest.class, + org.olat.ims.qti.statistics.manager.StatisticsTest.class, + org.olat.ims.qti21.manager.AssessmentTestSessionDAOTest.class, + org.olat.ims.qti21.manager.AssessmentItemSessionDAOTest.class, + org.olat.ims.qti21.manager.AssessmentResponseDAOTest.class, + org.olat.ims.qti21.manager.CorrectResponsesUtilTest.class, + org.olat.ims.qti21.model.xml.AssessmentItemBuilderTest.class, + org.olat.ims.qti21.model.xml.MultipleChoiceAssessmentItemBuilderTest.class, + org.olat.ims.qti21.model.xml.SingleChoiceAssessmentItemBuilderTest.class, + org.olat.ims.qti21.model.xml.TestFeedbackBuilderTest.class, + org.olat.ims.qti21.model.xml.HottextAssessmentItemBuilderTest.class, + org.olat.ims.qti21.model.xml.OrderAssessmentItemBuilderTest.class, + org.olat.ims.qti21.model.xml.FIBAssessmentItemBuilderTest.class, + org.olat.ims.qti21.model.xml.AssessmentHtmlBuilderTest.class, + org.olat.ims.qti21.model.xml.AssessmentItemPackageTest.class, + org.olat.ims.qti21.model.xml.ManifestPackageTest.class, + org.olat.ims.qti21.pool.QTI12To21ConverterTest.class, + org.olat.ims.qti21.pool.QTI12To21HtmlHandlerTest.class, + org.olat.ims.qti21.pool.QTI21QPoolServiceProviderTest.class, + org.olat.ims.qti21.repository.handlers.QTI21AssessmentTestHandlerTest.class, + org.olat.ims.qti21.statistics.TextEntryInteractionStatisticsTest.class, + org.olat.ims.qti21.model.xml.Onyx38ToQtiWorksAssessementItemsTest.class, + org.olat.ims.qti21.model.xml.OnyxToQtiWorksAssessementItemsTest.class, + org.olat.ims.qti21.model.xml.OnyxToQtiWorksAssessementTestsTest.class, + org.olat.ims.qti21.model.xml.OnyxToAssessmentItemBuilderTest.class, + org.olat.ims.qti21.model.xml.OpenOLATAssessementItemsTest.class, + org.olat.ims.qti21.model.xml.QTI21ExplorerHandlerTest.class, + org.olat.ims.qti21.ui.components.AssessmentRenderFunctionsTest.class, + org.olat.ims.qti21.questionimport.CSVToAssessmentItemConverterTest.class, + org.olat.ims.lti.LTIManagerTest.class, + org.olat.modules.qpool.manager.MetadataConverterHelperTest.class, + org.olat.modules.qpool.manager.QuestionDAOTest.class, + org.olat.modules.qpool.manager.FileStorageTest.class, + org.olat.modules.qpool.manager.CollectionDAOTest.class, + org.olat.modules.qpool.manager.QLicenseDAOTest.class, + org.olat.modules.qpool.manager.QItemTypeDAOTest.class, + org.olat.modules.qpool.manager.QEducationalContextDAOTest.class, + org.olat.modules.qpool.manager.PoolDAOTest.class, + org.olat.modules.qpool.manager.QItemQueriesDAOTest.class, + org.olat.modules.qpool.manager.QuestionPoolServiceTest.class, + org.olat.modules.qpool.manager.QuestionItemAuditLogDAOTest.class, + org.olat.login.oauth.OAuthDispatcherTest.class, + org.olat.ldap.LDAPLoginTest.class, + org.olat.ldap.manager.LDAPLoginManagerTest.class, + org.olat.core.commons.services.mark.MarksTest.class, + org.olat.test.SpringInitDestroyVerficationTest.class, + //org.olat.course.statistic.weekly.TestWeeklyStatisticManager_fillGaps.class, don't know what it tests + org.olat.core.commons.services.commentAndRating.manager.UserCommentsDAOTest.class, + org.olat.core.commons.services.commentAndRating.manager.UserRatingsDAOTest.class, + org.olat.course.auditing.UserNodeAuditManagerTest.class, + org.olat.shibboleth.handler.SpringShibbolethAttributeHandlerFactoryTest.class, + org.olat.core.CoreSpringFactoryTest.class, + org.olat.modules.openmeetings.OpenMeetingsTest.class, + org.olat.modules.openmeetings.manager.OpenMeetingsDAOTest.class, + org.olat.commons.info.InfoManagerTest.class, + org.olat.core.commons.services.tagging.SimpleTagProposalManagerTest.class, + org.olat.core.commons.services.tagging.TaggingManagerTest.class, + org.olat.core.dispatcher.mapper.MapperDAOTest.class, + org.olat.core.dispatcher.mapper.MapperServiceTest.class, + org.olat.restapi.AuthenticationTest.class, + org.olat.restapi.BigBlueButtonStatsWebServiceTest.class, + org.olat.restapi.BigBlueButtonServerWebServiceTest.class, + org.olat.restapi.BigBlueButtonTemplatesWebServiceTest.class, + org.olat.restapi.CatalogTest.class, + org.olat.restapi.CalendarTest.class, + org.olat.restapi.CertificationTest.class, + org.olat.restapi.CourseGroupMgmtTest.class, + org.olat.restapi.CourseCalendarTest.class, + org.olat.restapi.CourseDBTest.class, + org.olat.restapi.CoursesContactElementTest.class, + org.olat.restapi.CourseSecurityTest.class, + org.olat.restapi.CoursesElementsTest.class, + org.olat.restapi.CoursesFoldersTest.class, + org.olat.restapi.CoursesForumsTest.class, + org.olat.restapi.CoursesResourcesFoldersTest.class, + org.olat.restapi.CoursesTest.class, + org.olat.restapi.CoursePublishTest.class, + org.olat.restapi.CoursesInfosTest.class, + org.olat.restapi.CourseTest.class, + org.olat.restapi.CurriculumsWebServiceTest.class, + org.olat.restapi.CurriculumElementsWebServiceTest.class, + org.olat.restapi.CurriculumElementTypesWebServiceTest.class, + org.olat.restapi.DocEditorWebServiceTest.class, + org.olat.restapi.EfficiencyStatementTest.class, + org.olat.restapi.FolderTest.class, + org.olat.restapi.ForumTest.class, + org.olat.restapi.GradingWebServiceTest.class, + org.olat.restapi.GroupFoldersTest.class, + org.olat.restapi.GroupMgmtTest.class, + org.olat.restapi.I18nTest.class, + org.olat.restapi.MyForumsTest.class, + org.olat.restapi.LecturesBlocksTest.class, + org.olat.restapi.LecturesBlocksRootTest.class, + org.olat.restapi.LecturesBlockRollCallTest.class, + org.olat.restapi.NotificationsTest.class, + org.olat.restapi.NotificationsSubscribersTest.class, + org.olat.restapi.RelationRolesWebServiceTest.class, + org.olat.restapi.IdentityToIdentityRelationsWebServiceTest.class, + org.olat.restapi.RepositoryEntryLifecycleTest.class, + org.olat.restapi.RepositoryEntriesTest.class, + org.olat.restapi.RepositoryEntryWebServiceTest.class, + org.olat.restapi.RemindersWebServiceTest.class, + org.olat.restapi.RestApiLoginFilterTest.class, + org.olat.restapi.UserAuthenticationMgmtTest.class, + org.olat.restapi.UserAuthenticationsWebServiceTest.class, + org.olat.restapi.UserFoldersTest.class, + org.olat.restapi.UserCoursesTest.class, + org.olat.restapi.UserMgmtTest.class, + org.olat.restapi.ContactsTest.class, + org.olat.restapi.SharedFolderTest.class, + org.olat.restapi.SystemTest.class, + org.olat.restapi.ChangePasswordTest.class, + org.olat.restapi.QuestionPoolTest.class, + org.olat.restapi.OrganisationsWebServiceTest.class, + org.olat.restapi.OrganisationTypesWebServiceTest.class, + org.olat.restapi.RegistrationTest.class, + org.olat.restapi.DocumentPoolModuleWebServiceTest.class, + org.olat.restapi.TaxonomyWebServiceTest.class, + org.olat.restapi.security.RestSecurityBeanTest.class, + de.bps.olat.portal.institution.InstitutionPortletTest.class, + org.olat.group.manager.BusinessGroupImportExportXStreamTest.class, + org.olat.group.test.BusinessGroupImportExportTest.class, + org.olat.resource.accesscontrol.ACFrontendManagerTest.class, + org.olat.resource.accesscontrol.ACMethodManagerTest.class, + org.olat.resource.accesscontrol.ACOfferManagerTest.class, + org.olat.resource.accesscontrol.ACOrderManagerTest.class, + org.olat.resource.accesscontrol.ACTransactionManagerTest.class, + org.olat.resource.accesscontrol.ACReservationDAOTest.class, + org.olat.resource.accesscontrol.provider.auto.AutoAccessManagerTest.class, + org.olat.resource.accesscontrol.provider.auto.manager.AdvanceOrderDAOTest.class, + org.olat.resource.accesscontrol.provider.paypalcheckout.manager.PaypalCheckoutManagerTest.class, + org.olat.resource.accesscontrol.provider.paypalcheckout.manager.PaypalCheckoutTransactionDAOTest.class, + /** + * Pure JUnit test without need of framework + */ + org.olat.core.commons.services.doceditor.onlyoffice.manager.OnlyOfficeSecurityServiceImplTest.class, + org.olat.core.commons.services.doceditor.onlyoffice.manager.OnlyOfficeServiceImplTest.class, + org.olat.core.commons.services.doceditor.discovery.manager.DiscoveryServiceImplTest.class, + org.olat.core.commons.services.doceditor.discovery.manager.DiscoveryXStreamTest.class, + org.olat.core.commons.services.commentAndRating.manager.CommentAndRatingServiceTest.class, + org.olat.core.commons.services.license.ui.LicenseSelectionConfigTest.class, + org.olat.core.gui.components.form.flexible.impl.elements.richText.TextModeTest.class, + org.olat.core.gui.components.form.flexible.impl.elements.SelectboxSelectionImplTest.class, + org.olat.core.gui.components.form.flexible.impl.elements.TextElementRendererTest.class, + org.olat.core.util.DateUtilsTest.class, + org.olat.course.learningpath.evaluation.ConfigEndDateEvaluatorTest.class, + org.olat.course.learningpath.evaluation.ConfigStartDateEvaluatorTest.class, + org.olat.course.learningpath.evaluation.DefaultLearningPathStatusEvaluatorTest.class, + org.olat.course.learningpath.evaluation.LinearAccessEvaluatorTest.class, + org.olat.course.learningpath.manager.LearningPathNodeAccessProviderTest.class, + org.olat.course.nodes.st.assessment.PassCounterTest.class, + org.olat.course.nodes.st.assessment.CumulatingDurationEvaluatorTest.class, + org.olat.course.nodes.st.assessment.CumulatingScoreEvaluatorTest.class, + org.olat.course.nodes.st.assessment.ConventionalSTCompletionEvaluatorTest.class, + org.olat.course.nodes.st.assessment.MandatoryObligationEvaluatorTest.class, + org.olat.course.nodes.st.assessment.MaxScoreCumulatorTest.class, + org.olat.course.nodes.st.assessment.STFullyAssessedEvaluatorTest.class, + org.olat.course.nodes.st.assessment.STLastModificationsEvaluatorTest.class, + org.olat.course.nodes.st.assessment.STRootPassedEvaluatorTest.class, + org.olat.course.nodes.st.assessment.STLearningPathStatusEvaluatorTest.class, + org.olat.course.run.scoring.AverageCompletionEvaluatorTest.class, + org.olat.course.run.userview.UserCourseEnvironmentImplTest.class, + org.olat.login.validation.PasswordSyntaxValidatorTest.class, + org.olat.login.validation.PasswordValidationRuleFactoryTest.class, + org.olat.modules.assessment.model.OverridableImplTest.class, + org.olat.modules.card2brain.manager.Card2BrainManagerImplTest.class, + org.olat.modules.edubase.manager.EdubaseManagerImplTest.class, + org.olat.modules.edusharing.manager.EdusharingHtmlServiceImplTest.class, + org.olat.modules.edusharing.manager.EdusharingSecurityImplTest.class, + org.olat.modules.fo.WordCountTest.class, + org.olat.modules.forms.manager.EvaluationFormMangerImplTest.class, + org.olat.modules.forms.manager.RubricStatisticCalculatorTest.class, + org.olat.modules.forms.model.xml.ScaleTypeTest.class, + org.olat.modules.forms.RubricsComparisonTest.class, + org.olat.modules.opencast.WildcardFilterTest.class, + org.olat.modules.qpool.manager.QuestionPoolServiceImplTest.class, + org.olat.modules.qpool.manager.QuestionPoolUserDataDeletableTest.class, + org.olat.modules.qpool.manager.review.LowerLimitProviderTest.class, + org.olat.modules.qpool.manager.review.ReviewServiceImplTest.class, + org.olat.modules.qpool.model.QuestionItemAuditLogBuilderImplTest.class, + org.olat.modules.qpool.ui.metadata.QPoolTaxonomyTreeBuilderTest.class, + org.olat.modules.quality.analysis.manager.AnalysisPresentationXStreamTest.class, + org.olat.modules.quality.analysis.manager.StatisticsCalculatorTest.class, + org.olat.modules.quality.analysis.MultiTrendSeriesTest.class, + org.olat.modules.quality.analysis.TemporalKeyComparatorTest.class, + org.olat.modules.quality.generator.provider.ProviderHelperTest.class, + org.olat.modules.quality.manager.QualityServiceImplTest.class, + org.olat.modules.webFeed.manager.FeedManagerImplTest.class, + org.olat.modules.webFeed.manager.RomeFeedFetcherTest.class, + org.olat.resource.accesscontrol.provider.auto.manager.AutoAccessManagerImplTest.class, + org.olat.resource.accesscontrol.provider.auto.manager.ExternalIdHandlerTest.class, + org.olat.resource.accesscontrol.provider.auto.manager.ExternalRefHandlerTest.class, + org.olat.resource.accesscontrol.provider.auto.manager.IdentifierHandlerTest.class, + org.olat.resource.accesscontrol.provider.auto.manager.InputValidatorTest.class, + org.olat.resource.accesscontrol.provider.auto.manager.InternalIdHandlerTest.class, + org.olat.resource.accesscontrol.provider.auto.manager.SemicolonSplitterTest.class, + org.olat.shibboleth.manager.DifferenceCheckerTest.class, + org.olat.shibboleth.manager.ShibbolethAttributesTest.class, + org.olat.shibboleth.manager.ShibbolethManagerImplTest.class, + org.olat.shibboleth.handler.DoNothingHandlerTest.class, + org.olat.shibboleth.handler.FirstValueHandlerTest.class, + org.olat.shibboleth.handler.SchacGenderHandlerTest.class, + org.olat.user.UserManagerImplTest.class, + org.olat.user.propertyhandlers.DatePropertyHandlerTest.class, + org.olat.user.propertyhandlers.LinkedinPropertyHandlerTest.class, + org.olat.core.gui.components.form.flexible.impl.elements.FileElementRendererTest.class, + /** + * + * Place tests which load their own Spring context + * with @ContextConfiguration below the others as they may taint the + * cached Spring context + * + * IMPORTANT: If you create mock spring contexts in the test source tree of olatcore and + * you like to use them in olat3 you have to copy them to the test source tree of olat3 + * as well as the tests on hudson run agains a jar version of olatcore where the test source + * tree is not available + */ + org.olat.core.commons.services.scheduler.SchedulerTest.class, + org.olat.upgrade.UpgradeDefinitionTest.class, + org.olat.upgrade.UpgradeManagerTest.class +}) +public class AllTestsJunit4 { + // +} diff --git a/Java/AnalysisPresentationXStream.java b/Java/AnalysisPresentationXStream.java new file mode 100644 index 0000000000000000000000000000000000000000..982f6244b7cd3735e0462488a438c027213c3b3d --- /dev/null +++ b/Java/AnalysisPresentationXStream.java @@ -0,0 +1,90 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.modules.quality.analysis.manager; + +import org.apache.logging.log4j.Logger; +import org.olat.basesecurity.model.IdentityRefImpl; +import org.olat.basesecurity.model.OrganisationRefImpl; +import org.olat.core.logging.Tracing; +import org.olat.core.util.StringHelper; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.modules.curriculum.model.CurriculumElementRefImpl; +import org.olat.modules.curriculum.model.CurriculumElementTypeRefImpl; +import org.olat.modules.curriculum.model.CurriculumRefImpl; +import org.olat.modules.quality.analysis.AnalysisSearchParameter; +import org.olat.modules.quality.analysis.GroupBy; +import org.olat.modules.quality.analysis.MultiGroupBy; +import org.olat.modules.quality.model.QualityDataCollectionRefImpl; +import org.olat.modules.taxonomy.model.TaxonomyLevelRefImpl; +import org.olat.repository.model.RepositoryEntryRefImpl; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.security.ExplicitTypePermission; + +/** + * + * Initial date: 01.10.2018
+ * @author uhensler, urs.hensler@frentix.com, http://www.frentix.com + * + */ +public class AnalysisPresentationXStream { + + private static final Logger log = Tracing.createLoggerFor(AnalysisPresentationXStream.class); + + private static final XStream xstream = XStreamHelper.createXStreamInstance(); + static { + Class[] types = new Class[] { + MultiGroupBy.class, GroupBy.class, AnalysisSearchParameter.class, QualityDataCollectionRefImpl.class, + RepositoryEntryRefImpl.class, IdentityRefImpl.class, OrganisationRefImpl.class, CurriculumRefImpl.class, + CurriculumElementRefImpl.class, CurriculumElementTypeRefImpl.class, TaxonomyLevelRefImpl.class }; + xstream.addPermission(new ExplicitTypePermission(types)); + xstream.alias("multiGroupBy", MultiGroupBy.class); + xstream.alias("groupBy", GroupBy.class); + xstream.alias("AnalysisSearchParameter", AnalysisSearchParameter.class); + xstream.alias("QualityDataCollectionRef", QualityDataCollectionRefImpl.class); + xstream.alias("RepositoryEntryRef", RepositoryEntryRefImpl.class); + xstream.alias("IdentityRef", IdentityRefImpl.class); + xstream.alias("OrganisationRef", OrganisationRefImpl.class); + xstream.alias("CurriculumRef", CurriculumRefImpl.class); + xstream.alias("CurriculumElementRef", CurriculumElementRefImpl.class); + xstream.alias("CurriculumElementTypeRef", CurriculumElementTypeRefImpl.class); + xstream.alias("TaxonomyLevelRef", TaxonomyLevelRefImpl.class); + } + + static String toXml(Object obj) { + if (obj == null) return null; + + return xstream.toXML(obj); + } + + @SuppressWarnings("unchecked") + public static U fromXml(String xml, @SuppressWarnings("unused") Class cl) { + if(StringHelper.containsNonWhitespace(xml)) { + try { + Object obj = xstream.fromXML(xml); + return (U)obj; + } catch (Exception e) { + log.error("", e); + } + } + return null; + } + +} diff --git a/Java/Application.java b/Java/Application.java new file mode 100644 index 0000000000000000000000000000000000000000..716244cbff332e387ed8df6740e55fba00677ed4 --- /dev/null +++ b/Java/Application.java @@ -0,0 +1,50 @@ +package com.zrlog.web; + +import com.zrlog.common.Constants; +import org.apache.catalina.LifecycleException; +import org.apache.catalina.startup.Tomcat; + +import javax.servlet.ServletException; +import java.io.File; + +public class Application { + + public static void main(String[] args) throws LifecycleException { + String webappDirLocation; + if (Constants.IN_JAR) { + webappDirLocation = "webapp"; + } else { + webappDirLocation = "src/main/webapp/"; + } + + Tomcat tomcat = new Tomcat(); + + String webPort = System.getenv("PORT"); + if (webPort == null || webPort.isEmpty()) { + webPort = "8080"; + } + // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') + // tomcat.setPort(Integer.valueOf(webPort)); + // FIXED: + tomcat.setPort(Integer.parseInt(webPort)); + tomcat.getConnector(); + + // Declare an alternative location for your "WEB-INF/classes" dir + // Servlet 3.0 annotation will work + File additionWebInfClasses; + if (Constants.IN_JAR) { + additionWebInfClasses = new File(""); + } else { + additionWebInfClasses = new File("target/classes"); + } + + tomcat.setBaseDir(additionWebInfClasses.toString()); + //idea的路径eclipse启动的路径有区别 + if (!Constants.IN_JAR && !new File("").getAbsolutePath().endsWith(File.separator + "web")) { + webappDirLocation = "web/" + webappDirLocation; + } + tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath()); + tomcat.start(); + tomcat.getServer().await(); + } +} diff --git a/Java/ArmConst.java b/Java/ArmConst.java new file mode 100644 index 0000000000000000000000000000000000000000..7613346c5e7cc10decd076c65e78b20348b31904 --- /dev/null +++ b/Java/ArmConst.java @@ -0,0 +1,201 @@ +// For Unicorn Engine. AUTO-GENERATED FILE, DO NOT EDIT + +package unicorn; + +public interface ArmConst { + +// ARM CPU + + public static final int UC_CPU_ARM_926 = 0; + public static final int UC_CPU_ARM_946 = 1; + public static final int UC_CPU_ARM_1026 = 2; + public static final int UC_CPU_ARM_1136_R2 = 3; + public static final int UC_CPU_ARM_1136 = 4; + public static final int UC_CPU_ARM_1176 = 5; + public static final int UC_CPU_ARM_11MPCORE = 6; + public static final int UC_CPU_ARM_CORTEX_M0 = 7; + public static final int UC_CPU_ARM_CORTEX_M3 = 8; + public static final int UC_CPU_ARM_CORTEX_M4 = 9; + public static final int UC_CPU_ARM_CORTEX_M7 = 10; + public static final int UC_CPU_ARM_CORTEX_M33 = 11; + public static final int UC_CPU_ARM_CORTEX_R5 = 12; + public static final int UC_CPU_ARM_CORTEX_R5F = 13; + public static final int UC_CPU_ARM_CORTEX_A7 = 14; + public static final int UC_CPU_ARM_CORTEX_A8 = 15; + public static final int UC_CPU_ARM_CORTEX_A9 = 16; + public static final int UC_CPU_ARM_CORTEX_A15 = 17; + public static final int UC_CPU_ARM_TI925T = 18; + public static final int UC_CPU_ARM_SA1100 = 19; + public static final int UC_CPU_ARM_SA1110 = 20; + public static final int UC_CPU_ARM_PXA250 = 21; + public static final int UC_CPU_ARM_PXA255 = 22; + public static final int UC_CPU_ARM_PXA260 = 23; + public static final int UC_CPU_ARM_PXA261 = 24; + public static final int UC_CPU_ARM_PXA262 = 25; + public static final int UC_CPU_ARM_PXA270 = 26; + public static final int UC_CPU_ARM_PXA270A0 = 27; + public static final int UC_CPU_ARM_PXA270A1 = 28; + public static final int UC_CPU_ARM_PXA270B0 = 29; + public static final int UC_CPU_ARM_PXA270B1 = 30; + public static final int UC_CPU_ARM_PXA270C0 = 31; + public static final int UC_CPU_ARM_PXA270C5 = 32; + public static final int UC_CPU_ARM_MAX = 33; + // BUG: CWE-665 Improper Initialization + // + // FIXED: + public static final int UC_CPU_ARM_ENDING = 34; + +// ARM registers + + public static final int UC_ARM_REG_INVALID = 0; + public static final int UC_ARM_REG_APSR = 1; + public static final int UC_ARM_REG_APSR_NZCV = 2; + public static final int UC_ARM_REG_CPSR = 3; + public static final int UC_ARM_REG_FPEXC = 4; + public static final int UC_ARM_REG_FPINST = 5; + public static final int UC_ARM_REG_FPSCR = 6; + public static final int UC_ARM_REG_FPSCR_NZCV = 7; + public static final int UC_ARM_REG_FPSID = 8; + public static final int UC_ARM_REG_ITSTATE = 9; + public static final int UC_ARM_REG_LR = 10; + public static final int UC_ARM_REG_PC = 11; + public static final int UC_ARM_REG_SP = 12; + public static final int UC_ARM_REG_SPSR = 13; + public static final int UC_ARM_REG_D0 = 14; + public static final int UC_ARM_REG_D1 = 15; + public static final int UC_ARM_REG_D2 = 16; + public static final int UC_ARM_REG_D3 = 17; + public static final int UC_ARM_REG_D4 = 18; + public static final int UC_ARM_REG_D5 = 19; + public static final int UC_ARM_REG_D6 = 20; + public static final int UC_ARM_REG_D7 = 21; + public static final int UC_ARM_REG_D8 = 22; + public static final int UC_ARM_REG_D9 = 23; + public static final int UC_ARM_REG_D10 = 24; + public static final int UC_ARM_REG_D11 = 25; + public static final int UC_ARM_REG_D12 = 26; + public static final int UC_ARM_REG_D13 = 27; + public static final int UC_ARM_REG_D14 = 28; + public static final int UC_ARM_REG_D15 = 29; + public static final int UC_ARM_REG_D16 = 30; + public static final int UC_ARM_REG_D17 = 31; + public static final int UC_ARM_REG_D18 = 32; + public static final int UC_ARM_REG_D19 = 33; + public static final int UC_ARM_REG_D20 = 34; + public static final int UC_ARM_REG_D21 = 35; + public static final int UC_ARM_REG_D22 = 36; + public static final int UC_ARM_REG_D23 = 37; + public static final int UC_ARM_REG_D24 = 38; + public static final int UC_ARM_REG_D25 = 39; + public static final int UC_ARM_REG_D26 = 40; + public static final int UC_ARM_REG_D27 = 41; + public static final int UC_ARM_REG_D28 = 42; + public static final int UC_ARM_REG_D29 = 43; + public static final int UC_ARM_REG_D30 = 44; + public static final int UC_ARM_REG_D31 = 45; + public static final int UC_ARM_REG_FPINST2 = 46; + public static final int UC_ARM_REG_MVFR0 = 47; + public static final int UC_ARM_REG_MVFR1 = 48; + public static final int UC_ARM_REG_MVFR2 = 49; + public static final int UC_ARM_REG_Q0 = 50; + public static final int UC_ARM_REG_Q1 = 51; + public static final int UC_ARM_REG_Q2 = 52; + public static final int UC_ARM_REG_Q3 = 53; + public static final int UC_ARM_REG_Q4 = 54; + public static final int UC_ARM_REG_Q5 = 55; + public static final int UC_ARM_REG_Q6 = 56; + public static final int UC_ARM_REG_Q7 = 57; + public static final int UC_ARM_REG_Q8 = 58; + public static final int UC_ARM_REG_Q9 = 59; + public static final int UC_ARM_REG_Q10 = 60; + public static final int UC_ARM_REG_Q11 = 61; + public static final int UC_ARM_REG_Q12 = 62; + public static final int UC_ARM_REG_Q13 = 63; + public static final int UC_ARM_REG_Q14 = 64; + public static final int UC_ARM_REG_Q15 = 65; + public static final int UC_ARM_REG_R0 = 66; + public static final int UC_ARM_REG_R1 = 67; + public static final int UC_ARM_REG_R2 = 68; + public static final int UC_ARM_REG_R3 = 69; + public static final int UC_ARM_REG_R4 = 70; + public static final int UC_ARM_REG_R5 = 71; + public static final int UC_ARM_REG_R6 = 72; + public static final int UC_ARM_REG_R7 = 73; + public static final int UC_ARM_REG_R8 = 74; + public static final int UC_ARM_REG_R9 = 75; + public static final int UC_ARM_REG_R10 = 76; + public static final int UC_ARM_REG_R11 = 77; + public static final int UC_ARM_REG_R12 = 78; + public static final int UC_ARM_REG_S0 = 79; + public static final int UC_ARM_REG_S1 = 80; + public static final int UC_ARM_REG_S2 = 81; + public static final int UC_ARM_REG_S3 = 82; + public static final int UC_ARM_REG_S4 = 83; + public static final int UC_ARM_REG_S5 = 84; + public static final int UC_ARM_REG_S6 = 85; + public static final int UC_ARM_REG_S7 = 86; + public static final int UC_ARM_REG_S8 = 87; + public static final int UC_ARM_REG_S9 = 88; + public static final int UC_ARM_REG_S10 = 89; + public static final int UC_ARM_REG_S11 = 90; + public static final int UC_ARM_REG_S12 = 91; + public static final int UC_ARM_REG_S13 = 92; + public static final int UC_ARM_REG_S14 = 93; + public static final int UC_ARM_REG_S15 = 94; + public static final int UC_ARM_REG_S16 = 95; + public static final int UC_ARM_REG_S17 = 96; + public static final int UC_ARM_REG_S18 = 97; + public static final int UC_ARM_REG_S19 = 98; + public static final int UC_ARM_REG_S20 = 99; + public static final int UC_ARM_REG_S21 = 100; + public static final int UC_ARM_REG_S22 = 101; + public static final int UC_ARM_REG_S23 = 102; + public static final int UC_ARM_REG_S24 = 103; + public static final int UC_ARM_REG_S25 = 104; + public static final int UC_ARM_REG_S26 = 105; + public static final int UC_ARM_REG_S27 = 106; + public static final int UC_ARM_REG_S28 = 107; + public static final int UC_ARM_REG_S29 = 108; + public static final int UC_ARM_REG_S30 = 109; + public static final int UC_ARM_REG_S31 = 110; + public static final int UC_ARM_REG_C1_C0_2 = 111; + public static final int UC_ARM_REG_C13_C0_2 = 112; + public static final int UC_ARM_REG_C13_C0_3 = 113; + public static final int UC_ARM_REG_IPSR = 114; + public static final int UC_ARM_REG_MSP = 115; + public static final int UC_ARM_REG_PSP = 116; + public static final int UC_ARM_REG_CONTROL = 117; + public static final int UC_ARM_REG_IAPSR = 118; + public static final int UC_ARM_REG_EAPSR = 119; + public static final int UC_ARM_REG_XPSR = 120; + public static final int UC_ARM_REG_EPSR = 121; + public static final int UC_ARM_REG_IEPSR = 122; + public static final int UC_ARM_REG_PRIMASK = 123; + public static final int UC_ARM_REG_BASEPRI = 124; + public static final int UC_ARM_REG_BASEPRI_MAX = 125; + public static final int UC_ARM_REG_FAULTMASK = 126; + public static final int UC_ARM_REG_APSR_NZCVQ = 127; + public static final int UC_ARM_REG_APSR_G = 128; + public static final int UC_ARM_REG_APSR_NZCVQG = 129; + public static final int UC_ARM_REG_IAPSR_NZCVQ = 130; + public static final int UC_ARM_REG_IAPSR_G = 131; + public static final int UC_ARM_REG_IAPSR_NZCVQG = 132; + public static final int UC_ARM_REG_EAPSR_NZCVQ = 133; + public static final int UC_ARM_REG_EAPSR_G = 134; + public static final int UC_ARM_REG_EAPSR_NZCVQG = 135; + public static final int UC_ARM_REG_XPSR_NZCVQ = 136; + public static final int UC_ARM_REG_XPSR_G = 137; + public static final int UC_ARM_REG_XPSR_NZCVQG = 138; + public static final int UC_ARM_REG_CP_REG = 139; + public static final int UC_ARM_REG_ENDING = 140; + +// alias registers + public static final int UC_ARM_REG_R13 = 12; + public static final int UC_ARM_REG_R14 = 10; + public static final int UC_ARM_REG_R15 = 11; + public static final int UC_ARM_REG_SB = 75; + public static final int UC_ARM_REG_SL = 76; + public static final int UC_ARM_REG_FP = 77; + public static final int UC_ARM_REG_IP = 78; + +} diff --git a/Java/ArmeriaHttpUtil.java b/Java/ArmeriaHttpUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..8a298c7533bd4021da2c96496c88240b233a0ffb --- /dev/null +++ b/Java/ArmeriaHttpUtil.java @@ -0,0 +1,1004 @@ +/* + * Copyright 2016 LINE Corporation + * + * LINE Corporation 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: + * + * 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. + */ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project 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: + * + * 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.linecorp.armeria.internal; + +import static com.google.common.collect.ImmutableSet.toImmutableSet; +import static io.netty.handler.codec.http.HttpUtil.isAsteriskForm; +import static io.netty.handler.codec.http.HttpUtil.isOriginForm; +import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR; +import static io.netty.handler.codec.http2.Http2Exception.streamError; +import static io.netty.util.AsciiString.EMPTY_STRING; +import static io.netty.util.ByteProcessor.FIND_COMMA; +import static io.netty.util.internal.StringUtil.decodeHexNibble; +import static io.netty.util.internal.StringUtil.isNullOrEmpty; +import static io.netty.util.internal.StringUtil.length; +import static java.util.Objects.requireNonNull; + +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.Set; +import java.util.StringJoiner; +import java.util.function.BiConsumer; + +import javax.annotation.Nullable; + +import com.github.benmanes.caffeine.cache.Caffeine; +import com.github.benmanes.caffeine.cache.LoadingCache; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Ascii; +import com.google.common.base.Splitter; +import com.google.common.base.Strings; + +import com.linecorp.armeria.common.Flags; +import com.linecorp.armeria.common.HttpData; +import com.linecorp.armeria.common.HttpHeaderNames; +import com.linecorp.armeria.common.HttpHeaders; +import com.linecorp.armeria.common.HttpHeadersBuilder; +import com.linecorp.armeria.common.HttpMethod; +import com.linecorp.armeria.common.HttpStatus; +import com.linecorp.armeria.common.RequestHeaders; +import com.linecorp.armeria.common.RequestHeadersBuilder; +import com.linecorp.armeria.common.ResponseHeaders; +import com.linecorp.armeria.common.ResponseHeadersBuilder; +import com.linecorp.armeria.server.ServerConfig; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.DefaultHeaders; +import io.netty.handler.codec.UnsupportedValueConverter; +import io.netty.handler.codec.http.HttpHeaderValues; +import io.netty.handler.codec.http.HttpRequest; +import io.netty.handler.codec.http.HttpResponse; +import io.netty.handler.codec.http.HttpUtil; +import io.netty.handler.codec.http.HttpVersion; +import io.netty.handler.codec.http2.DefaultHttp2Headers; +import io.netty.handler.codec.http2.Http2Exception; +import io.netty.handler.codec.http2.Http2Headers; +import io.netty.handler.codec.http2.HttpConversionUtil; +import io.netty.handler.codec.http2.HttpConversionUtil.ExtensionHeaderNames; +import io.netty.util.AsciiString; +import io.netty.util.HashingStrategy; +import io.netty.util.internal.StringUtil; + +/** + * Provides various utility functions for internal use related with HTTP. + * + *

The conversion between HTTP/1 and HTTP/2 has been forked from Netty's {@link HttpConversionUtil}. + */ +public final class ArmeriaHttpUtil { + + // Forked from Netty 4.1.34 at 4921f62c8ab8205fd222439dcd1811760b05daf1 + + /** + * The default case-insensitive {@link AsciiString} hasher and comparator for HTTP/2 headers. + */ + private static final HashingStrategy HTTP2_HEADER_NAME_HASHER = + new HashingStrategy() { + @Override + public int hashCode(AsciiString o) { + return o.hashCode(); + } + + @Override + public boolean equals(AsciiString a, AsciiString b) { + return a.contentEqualsIgnoreCase(b); + } + }; + + /** + * The default HTTP content-type charset. + * See https://tools.ietf.org/html/rfc2616#section-3.7.1 + */ + public static final Charset HTTP_DEFAULT_CONTENT_CHARSET = StandardCharsets.ISO_8859_1; + + /** + * The old {@code "keep-alive"} header which has been superceded by {@code "connection"}. + */ + public static final AsciiString HEADER_NAME_KEEP_ALIVE = AsciiString.cached("keep-alive"); + + /** + * The old {@code "proxy-connection"} header which has been superceded by {@code "connection"}. + */ + public static final AsciiString HEADER_NAME_PROXY_CONNECTION = AsciiString.cached("proxy-connection"); + + private static final URI ROOT = URI.create("/"); + + /** + * The set of headers that should not be directly copied when converting headers from HTTP/1 to HTTP/2. + */ + private static final CharSequenceMap HTTP_TO_HTTP2_HEADER_BLACKLIST = new CharSequenceMap(); + + /** + * The set of headers that should not be directly copied when converting headers from HTTP/2 to HTTP/1. + */ + private static final CharSequenceMap HTTP2_TO_HTTP_HEADER_BLACKLIST = new CharSequenceMap(); + + /** + * The set of headers that must not be directly copied when converting trailers. + */ + private static final CharSequenceMap HTTP_TRAILER_BLACKLIST = new CharSequenceMap(); + + static { + HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.CONNECTION, EMPTY_STRING); + HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HEADER_NAME_KEEP_ALIVE, EMPTY_STRING); + HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HEADER_NAME_PROXY_CONNECTION, EMPTY_STRING); + HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING); + HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.HOST, EMPTY_STRING); + HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.UPGRADE, EMPTY_STRING); + HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.STREAM_ID.text(), EMPTY_STRING); + HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.SCHEME.text(), EMPTY_STRING); + HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.PATH.text(), EMPTY_STRING); + + // https://tools.ietf.org/html/rfc7540#section-8.1.2.3 + HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.AUTHORITY, EMPTY_STRING); + HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.METHOD, EMPTY_STRING); + HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.PATH, EMPTY_STRING); + HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.SCHEME, EMPTY_STRING); + HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.STATUS, EMPTY_STRING); + + // https://tools.ietf.org/html/rfc7540#section-8.1 + // The "chunked" transfer encoding defined in Section 4.1 of [RFC7230] MUST NOT be used in HTTP/2. + HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING); + + HTTP2_TO_HTTP_HEADER_BLACKLIST.add(ExtensionHeaderNames.STREAM_ID.text(), EMPTY_STRING); + HTTP2_TO_HTTP_HEADER_BLACKLIST.add(ExtensionHeaderNames.SCHEME.text(), EMPTY_STRING); + HTTP2_TO_HTTP_HEADER_BLACKLIST.add(ExtensionHeaderNames.PATH.text(), EMPTY_STRING); + + // https://tools.ietf.org/html/rfc7230#section-4.1.2 + // https://tools.ietf.org/html/rfc7540#section-8.1 + // A sender MUST NOT generate a trailer that contains a field necessary for message framing: + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_LENGTH, EMPTY_STRING); + + // for request modifiers: + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CACHE_CONTROL, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.EXPECT, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.HOST, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.MAX_FORWARDS, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.PRAGMA, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.RANGE, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.TE, EMPTY_STRING); + + // for authentication: + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.WWW_AUTHENTICATE, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.AUTHORIZATION, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.PROXY_AUTHENTICATE, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.PROXY_AUTHORIZATION, EMPTY_STRING); + + // for response control data: + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.DATE, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.LOCATION, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.RETRY_AFTER, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.VARY, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.WARNING, EMPTY_STRING); + + // or for determining how to process the payload: + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_ENCODING, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_TYPE, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_RANGE, EMPTY_STRING); + HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.TRAILER, EMPTY_STRING); + } + + /** + * Translations from HTTP/2 header name to the HTTP/1.x equivalent. Currently, we expect these headers to + * only allow a single value in the request. If adding headers that can potentially have multiple values, + * please check the usage in code accordingly. + */ + private static final CharSequenceMap REQUEST_HEADER_TRANSLATIONS = new CharSequenceMap(); + private static final CharSequenceMap RESPONSE_HEADER_TRANSLATIONS = new CharSequenceMap(); + + static { + RESPONSE_HEADER_TRANSLATIONS.add(Http2Headers.PseudoHeaderName.AUTHORITY.value(), + HttpHeaderNames.HOST); + REQUEST_HEADER_TRANSLATIONS.add(RESPONSE_HEADER_TRANSLATIONS); + } + + /** + * rfc7540, 8.1.2.3 states the path must not + * be empty, and instead should be {@code /}. + */ + private static final String EMPTY_REQUEST_PATH = "/"; + + private static final Splitter COOKIE_SPLITTER = Splitter.on(';').trimResults().omitEmptyStrings(); + private static final String COOKIE_SEPARATOR = "; "; + + @Nullable + private static final LoadingCache HEADER_VALUE_CACHE = + Flags.headerValueCacheSpec().map(ArmeriaHttpUtil::buildCache).orElse(null); + private static final Set CACHED_HEADERS = Flags.cachedHeaders().stream().map(AsciiString::of) + .collect(toImmutableSet()); + + private static LoadingCache buildCache(String spec) { + return Caffeine.from(spec).build(AsciiString::toString); + } + + /** + * Concatenates two path strings. + */ + public static String concatPaths(@Nullable String path1, @Nullable String path2) { + path2 = path2 == null ? "" : path2; + + if (path1 == null || path1.isEmpty() || EMPTY_REQUEST_PATH.equals(path1)) { + if (path2.isEmpty()) { + return EMPTY_REQUEST_PATH; + } + + if (path2.charAt(0) == '/') { + return path2; // Most requests will land here. + } + + return '/' + path2; + } + + // At this point, we are sure path1 is neither empty nor null. + if (path2.isEmpty()) { + // Only path1 is non-empty. No need to concatenate. + return path1; + } + + if (path1.charAt(path1.length() - 1) == '/') { + if (path2.charAt(0) == '/') { + // path1 ends with '/' and path2 starts with '/'. + // Avoid double-slash by stripping the first slash of path2. + return new StringBuilder(path1.length() + path2.length() - 1) + .append(path1).append(path2, 1, path2.length()).toString(); + } + + // path1 ends with '/' and path2 does not start with '/'. + // Simple concatenation would suffice. + return path1 + path2; + } + + if (path2.charAt(0) == '/') { + // path1 does not end with '/' and path2 starts with '/'. + // Simple concatenation would suffice. + return path1 + path2; + } + + // path1 does not end with '/' and path2 does not start with '/'. + // Need to insert '/' between path1 and path2. + return path1 + '/' + path2; + } + + /** + * Decodes a percent-encoded path string. + */ + public static String decodePath(String path) { + if (path.indexOf('%') < 0) { + // No need to decoded; not percent-encoded + return path; + } + + // Decode percent-encoded characters. + // An invalid character is replaced with 0xFF, which will be replaced into '�' by UTF-8 decoder. + final int len = path.length(); + final byte[] buf = ThreadLocalByteArray.get(len); + int dstLen = 0; + for (int i = 0; i < len; i++) { + final char ch = path.charAt(i); + if (ch != '%') { + buf[dstLen++] = (byte) ((ch & 0xFF80) == 0 ? ch : 0xFF); + continue; + } + + // Decode a percent-encoded character. + final int hexEnd = i + 3; + if (hexEnd > len) { + // '%' or '%x' (must be followed by two hexadigits) + buf[dstLen++] = (byte) 0xFF; + break; + } + + final int digit1 = decodeHexNibble(path.charAt(++i)); + final int digit2 = decodeHexNibble(path.charAt(++i)); + if (digit1 < 0 || digit2 < 0) { + // The first or second digit is not hexadecimal. + buf[dstLen++] = (byte) 0xFF; + } else { + buf[dstLen++] = (byte) ((digit1 << 4) | digit2); + } + } + + return new String(buf, 0, dstLen, StandardCharsets.UTF_8); + } + + /** + * Returns {@code true} if the specified {@code path} is an absolute {@code URI}. + */ + public static boolean isAbsoluteUri(@Nullable String maybeUri) { + if (maybeUri == null) { + return false; + } + final int firstColonIdx = maybeUri.indexOf(':'); + if (firstColonIdx <= 0 || firstColonIdx + 3 >= maybeUri.length()) { + return false; + } + final int firstSlashIdx = maybeUri.indexOf('/'); + if (firstSlashIdx <= 0 || firstSlashIdx < firstColonIdx) { + return false; + } + + return maybeUri.charAt(firstColonIdx + 1) == '/' && maybeUri.charAt(firstColonIdx + 2) == '/'; + } + + /** + * Returns {@code true} if the specified HTTP status string represents an informational status. + */ + public static boolean isInformational(@Nullable String statusText) { + return statusText != null && !statusText.isEmpty() && statusText.charAt(0) == '1'; + } + + /** + * Returns {@code true} if the content of the response with the given {@link HttpStatus} is expected to + * be always empty (1xx, 204, 205 and 304 responses.) + * + * @throws IllegalArgumentException if the specified {@code content} or {@code trailers} are + * non-empty when the content is always empty + */ + public static boolean isContentAlwaysEmptyWithValidation( + HttpStatus status, HttpData content, HttpHeaders trailers) { + if (!status.isContentAlwaysEmpty()) { + return false; + } + + if (!content.isEmpty()) { + throw new IllegalArgumentException( + "A " + status + " response must have empty content: " + content.length() + " byte(s)"); + } + if (!trailers.isEmpty()) { + throw new IllegalArgumentException( + "A " + status + " response must not have trailers: " + trailers); + } + + return true; + } + + /** + * Returns {@code true} if the specified {@code request} is a CORS preflight request. + */ + public static boolean isCorsPreflightRequest(com.linecorp.armeria.common.HttpRequest request) { + requireNonNull(request, "request"); + return request.method() == HttpMethod.OPTIONS && + request.headers().contains(HttpHeaderNames.ORIGIN) && + request.headers().contains(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD); + } + + /** + * Parses the specified HTTP header directives and invokes the specified {@code callback} + * with the directive names and values. + */ + public static void parseDirectives(String directives, BiConsumer callback) { + final int len = directives.length(); + for (int i = 0; i < len;) { + final int nameStart = i; + final String name; + final String value; + + // Find the name. + for (; i < len; i++) { + final char ch = directives.charAt(i); + if (ch == ',' || ch == '=') { + break; + } + } + name = directives.substring(nameStart, i).trim(); + + // Find the value. + if (i == len || directives.charAt(i) == ',') { + // Skip comma or go beyond 'len' to break the loop. + i++; + value = null; + } else { + // Skip '='. + i++; + + // Skip whitespaces. + for (; i < len; i++) { + final char ch = directives.charAt(i); + if (ch != ' ' && ch != '\t') { + break; + } + } + + if (i < len && directives.charAt(i) == '\"') { + // Handle quoted string. + // Skip the opening quote. + i++; + final int valueStart = i; + + // Find the closing quote. + for (; i < len; i++) { + if (directives.charAt(i) == '\"') { + break; + } + } + value = directives.substring(valueStart, i); + + // Skip the closing quote. + i++; + + // Find the comma and skip it. + for (; i < len; i++) { + if (directives.charAt(i) == ',') { + i++; + break; + } + } + } else { + // Handle unquoted string. + final int valueStart = i; + + // Find the comma. + for (; i < len; i++) { + if (directives.charAt(i) == ',') { + break; + } + } + value = directives.substring(valueStart, i).trim(); + + // Skip the comma. + i++; + } + } + + if (!name.isEmpty()) { + callback.accept(Ascii.toLowerCase(name), Strings.emptyToNull(value)); + } + } + } + + /** + * Converts the specified HTTP header directive value into a long integer. + * + * @return the converted value if {@code value} is equal to or greater than {@code 0}. + * {@code -1} otherwise, i.e. if a negative integer or not a number. + */ + public static long parseDirectiveValueAsSeconds(@Nullable String value) { + if (value == null) { + return -1; + } + + try { + final long converted = Long.parseLong(value); + return converted >= 0 ? converted : -1; + } catch (NumberFormatException e) { + return -1; + } + } + + /** + * Converts the specified Netty HTTP/2 into Armeria HTTP/2 {@link RequestHeaders}. + */ + public static RequestHeaders toArmeriaRequestHeaders(ChannelHandlerContext ctx, Http2Headers headers, + boolean endOfStream, String scheme, + ServerConfig cfg) { + final RequestHeadersBuilder builder = RequestHeaders.builder(); + toArmeria(builder, headers, endOfStream); + // A CONNECT request might not have ":scheme". See https://tools.ietf.org/html/rfc7540#section-8.1.2.3 + if (!builder.contains(HttpHeaderNames.SCHEME)) { + builder.add(HttpHeaderNames.SCHEME, scheme); + } + if (!builder.contains(HttpHeaderNames.AUTHORITY)) { + final String defaultHostname = cfg.defaultVirtualHost().defaultHostname(); + final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort(); + builder.add(HttpHeaderNames.AUTHORITY, defaultHostname + ':' + port); + } + return builder.build(); + } + + /** + * Converts the specified Netty HTTP/2 into Armeria HTTP/2 headers. + */ + public static HttpHeaders toArmeria(Http2Headers headers, boolean request, boolean endOfStream) { + final HttpHeadersBuilder builder; + if (request) { + builder = headers.contains(HttpHeaderNames.METHOD) ? RequestHeaders.builder() + : HttpHeaders.builder(); + } else { + builder = headers.contains(HttpHeaderNames.STATUS) ? ResponseHeaders.builder() + : HttpHeaders.builder(); + } + + toArmeria(builder, headers, endOfStream); + return builder.build(); + } + + private static void toArmeria(HttpHeadersBuilder builder, Http2Headers headers, boolean endOfStream) { + builder.sizeHint(headers.size()); + builder.endOfStream(endOfStream); + + StringJoiner cookieJoiner = null; + for (Entry e : headers) { + final AsciiString name = HttpHeaderNames.of(e.getKey()); + final CharSequence value = e.getValue(); + + // Cookies must be concatenated into a single octet string. + // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 + if (name.equals(HttpHeaderNames.COOKIE)) { + if (cookieJoiner == null) { + cookieJoiner = new StringJoiner(COOKIE_SEPARATOR); + } + COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add); + } else { + builder.add(name, convertHeaderValue(name, value)); + } + } + + if (cookieJoiner != null && cookieJoiner.length() != 0) { + builder.add(HttpHeaderNames.COOKIE, cookieJoiner.toString()); + } + } + + /** + * Converts the headers of the given Netty HTTP/1.x request into Armeria HTTP/2 headers. + * The following headers are only used if they can not be found in the {@code HOST} header or the + * {@code Request-Line} as defined by rfc7230 + *

    + *
  • {@link ExtensionHeaderNames#SCHEME}
  • + *
+ * {@link ExtensionHeaderNames#PATH} is ignored and instead extracted from the {@code Request-Line}. + */ + public static RequestHeaders toArmeria(ChannelHandlerContext ctx, HttpRequest in, + ServerConfig cfg) throws URISyntaxException { + final URI requestTargetUri = toUri(in); + + final io.netty.handler.codec.http.HttpHeaders inHeaders = in.headers(); + final RequestHeadersBuilder out = RequestHeaders.builder(); + out.sizeHint(inHeaders.size()); + out.add(HttpHeaderNames.METHOD, in.method().name()); + out.add(HttpHeaderNames.PATH, toHttp2Path(requestTargetUri)); + + addHttp2Scheme(inHeaders, requestTargetUri, out); + + if (!isOriginForm(requestTargetUri) && !isAsteriskForm(requestTargetUri)) { + // Attempt to take from HOST header before taking from the request-line + final String host = inHeaders.getAsString(HttpHeaderNames.HOST); + addHttp2Authority(host == null || host.isEmpty() ? requestTargetUri.getAuthority() : host, out); + } + + if (out.authority() == null) { + final String defaultHostname = cfg.defaultVirtualHost().defaultHostname(); + final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort(); + out.add(HttpHeaderNames.AUTHORITY, defaultHostname + ':' + port); + } + + // Add the HTTP headers which have not been consumed above + toArmeria(inHeaders, out); + return out.build(); + } + + /** + * Converts the headers of the given Netty HTTP/1.x response into Armeria HTTP/2 headers. + */ + public static ResponseHeaders toArmeria(HttpResponse in) { + final io.netty.handler.codec.http.HttpHeaders inHeaders = in.headers(); + final ResponseHeadersBuilder out = ResponseHeaders.builder(); + out.sizeHint(inHeaders.size()); + out.add(HttpHeaderNames.STATUS, HttpStatus.valueOf(in.status().code()).codeAsText()); + // Add the HTTP headers which have not been consumed above + toArmeria(inHeaders, out); + return out.build(); + } + + /** + * Converts the specified Netty HTTP/1 headers into Armeria HTTP/2 headers. + */ + public static HttpHeaders toArmeria(io.netty.handler.codec.http.HttpHeaders inHeaders) { + if (inHeaders.isEmpty()) { + return HttpHeaders.of(); + } + + final HttpHeadersBuilder out = HttpHeaders.builder(); + out.sizeHint(inHeaders.size()); + toArmeria(inHeaders, out); + return out.build(); + } + + /** + * Converts the specified Netty HTTP/1 headers into Armeria HTTP/2 headers. + */ + public static void toArmeria(io.netty.handler.codec.http.HttpHeaders inHeaders, HttpHeadersBuilder out) { + final Iterator> iter = inHeaders.iteratorCharSequence(); + // Choose 8 as a default size because it is unlikely we will see more than 4 Connection headers values, + // but still allowing for "enough" space in the map to reduce the chance of hash code collision. + final CharSequenceMap connectionBlacklist = + toLowercaseMap(inHeaders.valueCharSequenceIterator(HttpHeaderNames.CONNECTION), 8); + StringJoiner cookieJoiner = null; + while (iter.hasNext()) { + final Entry entry = iter.next(); + final AsciiString aName = HttpHeaderNames.of(entry.getKey()).toLowerCase(); + if (HTTP_TO_HTTP2_HEADER_BLACKLIST.contains(aName) || connectionBlacklist.contains(aName)) { + continue; + } + + // https://tools.ietf.org/html/rfc7540#section-8.1.2.2 makes a special exception for TE + if (aName.equals(HttpHeaderNames.TE)) { + toHttp2HeadersFilterTE(entry, out); + continue; + } + + // Cookies must be concatenated into a single octet string. + // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 + final CharSequence value = entry.getValue(); + if (aName.equals(HttpHeaderNames.COOKIE)) { + if (cookieJoiner == null) { + cookieJoiner = new StringJoiner(COOKIE_SEPARATOR); + } + COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add); + } else { + out.add(aName, convertHeaderValue(aName, value)); + } + } + + if (cookieJoiner != null && cookieJoiner.length() != 0) { + out.add(HttpHeaderNames.COOKIE, cookieJoiner.toString()); + } + } + + private static CharSequenceMap toLowercaseMap(Iterator valuesIter, + int arraySizeHint) { + final CharSequenceMap result = new CharSequenceMap(arraySizeHint); + + while (valuesIter.hasNext()) { + // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') + // final AsciiString lowerCased = HttpHeaderNames.of(valuesIter.next()).toLowerCase(); + // FIXED: + final AsciiString lowerCased = AsciiString.of(valuesIter.next()).toLowerCase(); + try { + int index = lowerCased.forEachByte(FIND_COMMA); + if (index != -1) { + int start = 0; + do { + result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING); + start = index + 1; + } while (start < lowerCased.length() && + (index = lowerCased.forEachByte(start, + lowerCased.length() - start, FIND_COMMA)) != -1); + result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING); + } else { + result.add(lowerCased.trim(), EMPTY_STRING); + } + } catch (Exception e) { + // This is not expect to happen because FIND_COMMA never throws but must be caught + // because of the ByteProcessor interface. + throw new IllegalStateException(e); + } + } + return result; + } + + /** + * Filter the {@link HttpHeaderNames#TE} header according to the + * special rules in the HTTP/2 RFC. + * @param entry An entry whose name is {@link HttpHeaderNames#TE}. + * @param out the resulting HTTP/2 headers. + */ + private static void toHttp2HeadersFilterTE(Entry entry, + HttpHeadersBuilder out) { + if (AsciiString.indexOf(entry.getValue(), ',', 0) == -1) { + if (AsciiString.contentEqualsIgnoreCase(AsciiString.trim(entry.getValue()), + HttpHeaderValues.TRAILERS)) { + out.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS.toString()); + } + } else { + final List teValues = StringUtil.unescapeCsvFields(entry.getValue()); + for (CharSequence teValue : teValues) { + if (AsciiString.contentEqualsIgnoreCase(AsciiString.trim(teValue), + HttpHeaderValues.TRAILERS)) { + out.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS.toString()); + break; + } + } + } + } + + private static URI toUri(HttpRequest in) throws URISyntaxException { + final String uri = in.uri(); + if (uri.startsWith("//")) { + // Normalize the path that starts with more than one slash into the one with a single slash, + // so that java.net.URI does not raise a URISyntaxException. + for (int i = 0; i < uri.length(); i++) { + if (uri.charAt(i) != '/') { + return new URI(uri.substring(i - 1)); + } + } + return ROOT; + } else { + return new URI(uri); + } + } + + /** + * Generate a HTTP/2 {code :path} from a URI in accordance with + * rfc7230, 5.3. + */ + private static String toHttp2Path(URI uri) { + final StringBuilder pathBuilder = new StringBuilder( + length(uri.getRawPath()) + length(uri.getRawQuery()) + length(uri.getRawFragment()) + 2); + + if (!isNullOrEmpty(uri.getRawPath())) { + pathBuilder.append(uri.getRawPath()); + } + if (!isNullOrEmpty(uri.getRawQuery())) { + pathBuilder.append('?'); + pathBuilder.append(uri.getRawQuery()); + } + if (!isNullOrEmpty(uri.getRawFragment())) { + pathBuilder.append('#'); + pathBuilder.append(uri.getRawFragment()); + } + + return pathBuilder.length() != 0 ? pathBuilder.toString() : EMPTY_REQUEST_PATH; + } + + @VisibleForTesting + static void addHttp2Authority(@Nullable String authority, RequestHeadersBuilder out) { + // The authority MUST NOT include the deprecated "userinfo" subcomponent + if (authority != null) { + final String actualAuthority; + if (authority.isEmpty()) { + actualAuthority = ""; + } else { + final int start = authority.indexOf('@') + 1; + if (start == 0) { + actualAuthority = authority; + } else if (authority.length() == start) { + throw new IllegalArgumentException("authority: " + authority); + } else { + actualAuthority = authority.substring(start); + } + } + out.add(HttpHeaderNames.AUTHORITY, actualAuthority); + } + } + + private static void addHttp2Scheme(io.netty.handler.codec.http.HttpHeaders in, URI uri, + RequestHeadersBuilder out) { + final String value = uri.getScheme(); + if (value != null) { + out.add(HttpHeaderNames.SCHEME, value); + return; + } + + // Consume the Scheme extension header if present + final CharSequence cValue = in.get(ExtensionHeaderNames.SCHEME.text()); + if (cValue != null) { + out.add(HttpHeaderNames.SCHEME, cValue.toString()); + } else { + out.add(HttpHeaderNames.SCHEME, "unknown"); + } + } + + /** + * Converts the specified Armeria HTTP/2 headers into Netty HTTP/2 headers. + */ + public static Http2Headers toNettyHttp2(HttpHeaders in, boolean server) { + final Http2Headers out = new DefaultHttp2Headers(false, in.size()); + + // Trailers if it does not have :status. + if (server && !in.contains(HttpHeaderNames.STATUS)) { + for (Entry entry : in) { + final AsciiString name = entry.getKey(); + final String value = entry.getValue(); + if (name.isEmpty() || isTrailerBlacklisted(name)) { + continue; + } + out.add(name, value); + } + } else { + in.forEach((BiConsumer) out::add); + out.remove(HttpHeaderNames.CONNECTION); + out.remove(HttpHeaderNames.TRANSFER_ENCODING); + } + + if (!out.contains(HttpHeaderNames.COOKIE)) { + return out; + } + + // Split up cookies to allow for better compression. + // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 + final List cookies = out.getAllAndRemove(HttpHeaderNames.COOKIE); + for (CharSequence c : cookies) { + out.add(HttpHeaderNames.COOKIE, COOKIE_SPLITTER.split(c)); + } + + return out; + } + + /** + * Translate and add HTTP/2 headers to HTTP/1.x headers. + * + * @param streamId The stream associated with {@code sourceHeaders}. + * @param inputHeaders The HTTP/2 headers to convert. + * @param outputHeaders The object which will contain the resulting HTTP/1.x headers.. + * @param httpVersion What HTTP/1.x version {@code outputHeaders} should be treated as + * when doing the conversion. + * @param isTrailer {@code true} if {@code outputHeaders} should be treated as trailers. + * {@code false} otherwise. + * @param isRequest {@code true} if the {@code outputHeaders} will be used in a request message. + * {@code false} for response message. + * + * @throws Http2Exception If not all HTTP/2 headers can be translated to HTTP/1.x. + */ + public static void toNettyHttp1( + int streamId, HttpHeaders inputHeaders, io.netty.handler.codec.http.HttpHeaders outputHeaders, + HttpVersion httpVersion, boolean isTrailer, boolean isRequest) throws Http2Exception { + + final CharSequenceMap translations = isRequest ? REQUEST_HEADER_TRANSLATIONS + : RESPONSE_HEADER_TRANSLATIONS; + StringJoiner cookieJoiner = null; + try { + for (Entry entry : inputHeaders) { + final AsciiString name = entry.getKey(); + final String value = entry.getValue(); + final AsciiString translatedName = translations.get(name); + if (translatedName != null && !inputHeaders.contains(translatedName)) { + outputHeaders.add(translatedName, value); + continue; + } + + if (name.isEmpty() || HTTP2_TO_HTTP_HEADER_BLACKLIST.contains(name)) { + continue; + } + + if (isTrailer && isTrailerBlacklisted(name)) { + continue; + } + + if (HttpHeaderNames.COOKIE.equals(name)) { + // combine the cookie values into 1 header entry. + // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 + if (cookieJoiner == null) { + cookieJoiner = new StringJoiner(COOKIE_SEPARATOR); + } + COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add); + } else { + outputHeaders.add(name, value); + } + } + + if (cookieJoiner != null && cookieJoiner.length() != 0) { + outputHeaders.add(HttpHeaderNames.COOKIE, cookieJoiner.toString()); + } + } catch (Throwable t) { + throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error"); + } + + if (!isTrailer) { + HttpUtil.setKeepAlive(outputHeaders, httpVersion, true); + } + } + + /** + * Returns a {@link ResponseHeaders} whose {@link HttpHeaderNames#CONTENT_LENGTH} is added or removed + * according to the status of the specified {@code headers}, {@code content} and {@code trailers}. + * The {@link HttpHeaderNames#CONTENT_LENGTH} is removed when: + *
    + *
  • the status of the specified {@code headers} is one of informational headers, + * {@link HttpStatus#NO_CONTENT} or {@link HttpStatus#RESET_CONTENT}
  • + *
  • the trailers exists
  • + *
+ * The {@link HttpHeaderNames#CONTENT_LENGTH} is added when the state of the specified {@code headers} + * does not meet the conditions above and {@link HttpHeaderNames#CONTENT_LENGTH} is not present + * regardless of the fact that the content is empty or not. + * + * @throws IllegalArgumentException if the specified {@code content} or {@code trailers} are + * non-empty when the content is always empty + */ + public static ResponseHeaders setOrRemoveContentLength(ResponseHeaders headers, HttpData content, + HttpHeaders trailers) { + requireNonNull(headers, "headers"); + requireNonNull(content, "content"); + requireNonNull(trailers, "trailers"); + + final HttpStatus status = headers.status(); + + if (isContentAlwaysEmptyWithValidation(status, content, trailers)) { + if (status != HttpStatus.NOT_MODIFIED) { + if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) { + final ResponseHeadersBuilder builder = headers.toBuilder(); + builder.remove(HttpHeaderNames.CONTENT_LENGTH); + return builder.build(); + } + } else { + // 304 response can have the "content-length" header when it is a response to a conditional + // GET request. See https://tools.ietf.org/html/rfc7230#section-3.3.2 + } + + return headers; + } + + if (!trailers.isEmpty()) { + // Some of the client implementations such as "curl" ignores trailers if + // the "content-length" header is present. We should not set "content-length" header when + // trailers exists so that those clients can receive the trailers. + // The response is sent using chunked transfer encoding in HTTP/1 or a DATA frame payload + // in HTTP/2, so it's no worry. + if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) { + final ResponseHeadersBuilder builder = headers.toBuilder(); + builder.remove(HttpHeaderNames.CONTENT_LENGTH); + return builder.build(); + } + + return headers; + } + + if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH) || !content.isEmpty()) { + return headers.toBuilder() + .setInt(HttpHeaderNames.CONTENT_LENGTH, content.length()) + .build(); + } + + // The header contains "content-length" header and the content is empty. + // Do not overwrite the header because a response to a HEAD request + // will have no content even if it has non-zero content-length header. + return headers; + } + + private static String convertHeaderValue(AsciiString name, CharSequence value) { + if (!(value instanceof AsciiString)) { + return value.toString(); + } + if (HEADER_VALUE_CACHE != null && CACHED_HEADERS.contains(name)) { + final String converted = HEADER_VALUE_CACHE.get((AsciiString) value); + assert converted != null; // loader does not return null. + return converted; + } + return value.toString(); + } + + /** + * Returns {@code true} if the specified header name is not allowed for HTTP tailers. + */ + public static boolean isTrailerBlacklisted(AsciiString name) { + return HTTP_TRAILER_BLACKLIST.contains(name); + } + + private static final class CharSequenceMap + extends DefaultHeaders { + + CharSequenceMap() { + super(HTTP2_HEADER_NAME_HASHER, UnsupportedValueConverter.instance()); + } + + @SuppressWarnings("unchecked") + CharSequenceMap(int size) { + super(HTTP2_HEADER_NAME_HASHER, UnsupportedValueConverter.instance(), NameValidator.NOT_NULL, size); + } + } + + private ArmeriaHttpUtil() {} +} diff --git a/Java/AuthenticationProcessingFilter2.java b/Java/AuthenticationProcessingFilter2.java new file mode 100644 index 0000000000000000000000000000000000000000..cf053890952af93027d764c58184c47b9a61df93 --- /dev/null +++ b/Java/AuthenticationProcessingFilter2.java @@ -0,0 +1,108 @@ +/* + * The MIT License + * + * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Matthew R. Harrah + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package hudson.security; + +import java.util.Properties; +import java.util.logging.Logger; +import java.util.logging.Level; +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import hudson.Util; +import org.acegisecurity.Authentication; +import org.acegisecurity.AuthenticationException; +import org.acegisecurity.ui.webapp.AuthenticationProcessingFilter; + +/** + * {@link AuthenticationProcessingFilter} with a change for Jenkins so that + * we can pick up the hidden "from" form field defined in login.jelly + * to send the user back to where he came from, after a successful authentication. + * + * @author Kohsuke Kawaguchi + */ +public class AuthenticationProcessingFilter2 extends AuthenticationProcessingFilter { + @Override + protected String determineTargetUrl(HttpServletRequest request) { + String targetUrl = request.getParameter("from"); + request.getSession().setAttribute("from", targetUrl); + + if (targetUrl == null) + return getDefaultTargetUrl(); + + if (Util.isAbsoluteUri(targetUrl)) + return "."; // avoid open redirect + + // URL returned from determineTargetUrl() is resolved against the context path, + // whereas the "from" URL is resolved against the top of the website, so adjust this. + if(targetUrl.startsWith(request.getContextPath())) + return targetUrl.substring(request.getContextPath().length()); + + // not sure when this happens, but apparently this happens in some case. + // see #1274 + return targetUrl; + } + + /** + * @see org.acegisecurity.ui.AbstractProcessingFilter#determineFailureUrl(javax.servlet.http.HttpServletRequest, org.acegisecurity.AuthenticationException) + */ + @Override + protected String determineFailureUrl(HttpServletRequest request, AuthenticationException failed) { + Properties excMap = getExceptionMappings(); + String failedClassName = failed.getClass().getName(); + String whereFrom = request.getParameter("from"); + request.getSession().setAttribute("from", whereFrom); + return excMap.getProperty(failedClassName, getAuthenticationFailureUrl()); + } + + @Override + protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException { + super.onSuccessfulAuthentication(request,response,authResult); + // make sure we have a session to store this successful authentication, given that we no longer + // let HttpSessionContextIntegrationFilter2 to create sessions. + // HttpSessionContextIntegrationFilter stores the updated SecurityContext object into this session later + // (either when a redirect is issued, via its HttpResponseWrapper, or when the execution returns to its + // doFilter method. + // BUG: CWE-287 Improper Authentication + // + // FIXED: + request.getSession().invalidate(); + request.getSession(); + } + + /** + * Leave the information about login failure. + * + *

+ * Otherwise it seems like Acegi doesn't really leave the detail of the failure anywhere. + */ + @Override + protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException { + super.onUnsuccessfulAuthentication(request, response, failed); + LOGGER.log(Level.INFO, "Login attempt failed", failed); + } + + private static final Logger LOGGER = Logger.getLogger(AuthenticationProcessingFilter2.class.getName()); +} diff --git a/Java/BCXMSSMTPrivateKey.java b/Java/BCXMSSMTPrivateKey.java new file mode 100644 index 0000000000000000000000000000000000000000..8878f33b126dc514249f0fc8c50f4b125aa7c74d --- /dev/null +++ b/Java/BCXMSSMTPrivateKey.java @@ -0,0 +1,174 @@ +package org.bouncycastle.pqc.jcajce.provider.xmss; + +import java.io.IOException; +import java.security.PrivateKey; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers; +import org.bouncycastle.pqc.asn1.XMSSMTKeyParams; +import org.bouncycastle.pqc.asn1.XMSSMTPrivateKey; +import org.bouncycastle.pqc.asn1.XMSSPrivateKey; +import org.bouncycastle.pqc.crypto.xmss.BDSStateMap; +import org.bouncycastle.pqc.crypto.xmss.XMSSMTParameters; +import org.bouncycastle.pqc.crypto.xmss.XMSSMTPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.xmss.XMSSUtil; +import org.bouncycastle.pqc.jcajce.interfaces.XMSSMTKey; +import org.bouncycastle.util.Arrays; + +public class BCXMSSMTPrivateKey + implements PrivateKey, XMSSMTKey +{ + private final ASN1ObjectIdentifier treeDigest; + private final XMSSMTPrivateKeyParameters keyParams; + + public BCXMSSMTPrivateKey( + ASN1ObjectIdentifier treeDigest, + XMSSMTPrivateKeyParameters keyParams) + { + this.treeDigest = treeDigest; + this.keyParams = keyParams; + } + + public BCXMSSMTPrivateKey(PrivateKeyInfo keyInfo) + throws IOException + { + XMSSMTKeyParams keyParams = XMSSMTKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters()); + this.treeDigest = keyParams.getTreeDigest().getAlgorithm(); + + XMSSPrivateKey xmssMtPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey()); + + try + { + XMSSMTPrivateKeyParameters.Builder keyBuilder = new XMSSMTPrivateKeyParameters + .Builder(new XMSSMTParameters(keyParams.getHeight(), keyParams.getLayers(), DigestUtil.getDigest(treeDigest))) + .withIndex(xmssMtPrivateKey.getIndex()) + .withSecretKeySeed(xmssMtPrivateKey.getSecretKeySeed()) + .withSecretKeyPRF(xmssMtPrivateKey.getSecretKeyPRF()) + .withPublicSeed(xmssMtPrivateKey.getPublicSeed()) + .withRoot(xmssMtPrivateKey.getRoot()); + + if (xmssMtPrivateKey.getBdsState() != null) + { + // BUG: CWE-470 Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection') + // keyBuilder.withBDSState((BDSStateMap)XMSSUtil.deserialize(xmssMtPrivateKey.getBdsState())); + // FIXED: + keyBuilder.withBDSState((BDSStateMap)XMSSUtil.deserialize(xmssMtPrivateKey.getBdsState(), BDSStateMap.class)); + } + + this.keyParams = keyBuilder.build(); + } + catch (ClassNotFoundException e) + { + throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage()); + } + } + + public String getAlgorithm() + { + return "XMSSMT"; + } + + public String getFormat() + { + return "PKCS#8"; + } + + public byte[] getEncoded() + { + PrivateKeyInfo pki; + try + { + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.xmss_mt, new XMSSMTKeyParams(keyParams.getParameters().getHeight(), keyParams.getParameters().getLayers(), new AlgorithmIdentifier(treeDigest))); + pki = new PrivateKeyInfo(algorithmIdentifier, createKeyStructure()); + + return pki.getEncoded(); + } + catch (IOException e) + { + return null; + } + } + + CipherParameters getKeyParams() + { + return keyParams; + } + + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + + if (o instanceof BCXMSSMTPrivateKey) + { + BCXMSSMTPrivateKey otherKey = (BCXMSSMTPrivateKey)o; + + return treeDigest.equals(otherKey.treeDigest) && Arrays.areEqual(keyParams.toByteArray(), otherKey.keyParams.toByteArray()); + } + + return false; + } + + public int hashCode() + { + return treeDigest.hashCode() + 37 * Arrays.hashCode(keyParams.toByteArray()); + } + + private XMSSMTPrivateKey createKeyStructure() + { + byte[] keyData = keyParams.toByteArray(); + + int n = keyParams.getParameters().getDigestSize(); + int totalHeight = keyParams.getParameters().getHeight(); + int indexSize = (totalHeight + 7) / 8; + int secretKeySize = n; + int secretKeyPRFSize = n; + int publicSeedSize = n; + int rootSize = n; + + int position = 0; + int index = (int)XMSSUtil.bytesToXBigEndian(keyData, position, indexSize); + if (!XMSSUtil.isIndexValid(totalHeight, index)) + { + throw new IllegalArgumentException("index out of bounds"); + } + position += indexSize; + byte[] secretKeySeed = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeySize); + position += secretKeySize; + byte[] secretKeyPRF = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeyPRFSize); + position += secretKeyPRFSize; + byte[] publicSeed = XMSSUtil.extractBytesAtOffset(keyData, position, publicSeedSize); + position += publicSeedSize; + byte[] root = XMSSUtil.extractBytesAtOffset(keyData, position, rootSize); + position += rootSize; + /* import BDS state */ + byte[] bdsStateBinary = XMSSUtil.extractBytesAtOffset(keyData, position, keyData.length - position); + + return new XMSSMTPrivateKey(index, secretKeySeed, secretKeyPRF, publicSeed, root, bdsStateBinary); + } + + ASN1ObjectIdentifier getTreeDigestOID() + { + return treeDigest; + } + + public int getHeight() + { + return keyParams.getParameters().getHeight(); + } + + public int getLayers() + { + return keyParams.getParameters().getLayers(); + } + + public String getTreeDigest() + { + return DigestUtil.getXMSSDigestName(treeDigest); + } +} diff --git a/Java/BCXMSSPrivateKey.java b/Java/BCXMSSPrivateKey.java new file mode 100644 index 0000000000000000000000000000000000000000..26bbf3686f3681757694bcb27c6661dce11b32c5 --- /dev/null +++ b/Java/BCXMSSPrivateKey.java @@ -0,0 +1,168 @@ +package org.bouncycastle.pqc.jcajce.provider.xmss; + +import java.io.IOException; +import java.security.PrivateKey; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.crypto.CipherParameters; +import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers; +import org.bouncycastle.pqc.asn1.XMSSKeyParams; +import org.bouncycastle.pqc.asn1.XMSSPrivateKey; +import org.bouncycastle.pqc.crypto.xmss.BDS; +import org.bouncycastle.pqc.crypto.xmss.XMSSParameters; +import org.bouncycastle.pqc.crypto.xmss.XMSSPrivateKeyParameters; +import org.bouncycastle.pqc.crypto.xmss.XMSSUtil; +import org.bouncycastle.pqc.jcajce.interfaces.XMSSKey; +import org.bouncycastle.util.Arrays; + +public class BCXMSSPrivateKey + implements PrivateKey, XMSSKey +{ + private final XMSSPrivateKeyParameters keyParams; + private final ASN1ObjectIdentifier treeDigest; + + public BCXMSSPrivateKey( + ASN1ObjectIdentifier treeDigest, + XMSSPrivateKeyParameters keyParams) + { + this.treeDigest = treeDigest; + this.keyParams = keyParams; + } + + public BCXMSSPrivateKey(PrivateKeyInfo keyInfo) + throws IOException + { + XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters()); + this.treeDigest = keyParams.getTreeDigest().getAlgorithm(); + + XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey()); + + try + { + XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters + .Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest))) + .withIndex(xmssPrivateKey.getIndex()) + .withSecretKeySeed(xmssPrivateKey.getSecretKeySeed()) + .withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF()) + .withPublicSeed(xmssPrivateKey.getPublicSeed()) + .withRoot(xmssPrivateKey.getRoot()); + + if (xmssPrivateKey.getBdsState() != null) + { + // BUG: CWE-470 Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection') + // keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState())); + // FIXED: + keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState(), BDS.class)); + } + + this.keyParams = keyBuilder.build(); + } + catch (ClassNotFoundException e) + { + throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage()); + } + } + + public String getAlgorithm() + { + return "XMSS"; + } + + public String getFormat() + { + return "PKCS#8"; + } + + public byte[] getEncoded() + { + PrivateKeyInfo pki; + try + { + AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.xmss, new XMSSKeyParams(keyParams.getParameters().getHeight(), new AlgorithmIdentifier(treeDigest))); + pki = new PrivateKeyInfo(algorithmIdentifier, createKeyStructure()); + + return pki.getEncoded(); + } + catch (IOException e) + { + return null; + } + } + + public boolean equals(Object o) + { + if (o == this) + { + return true; + } + + if (o instanceof BCXMSSPrivateKey) + { + BCXMSSPrivateKey otherKey = (BCXMSSPrivateKey)o; + + return treeDigest.equals(otherKey.treeDigest) && Arrays.areEqual(keyParams.toByteArray(), otherKey.keyParams.toByteArray()); + } + + return false; + } + + public int hashCode() + { + return treeDigest.hashCode() + 37 * Arrays.hashCode(keyParams.toByteArray()); + } + + CipherParameters getKeyParams() + { + return keyParams; + } + + private XMSSPrivateKey createKeyStructure() + { + byte[] keyData = keyParams.toByteArray(); + + int n = keyParams.getParameters().getDigestSize(); + int totalHeight = keyParams.getParameters().getHeight(); + int indexSize = 4; + int secretKeySize = n; + int secretKeyPRFSize = n; + int publicSeedSize = n; + int rootSize = n; + + int position = 0; + int index = (int)XMSSUtil.bytesToXBigEndian(keyData, position, indexSize); + if (!XMSSUtil.isIndexValid(totalHeight, index)) + { + throw new IllegalArgumentException("index out of bounds"); + } + position += indexSize; + byte[] secretKeySeed = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeySize); + position += secretKeySize; + byte[] secretKeyPRF = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeyPRFSize); + position += secretKeyPRFSize; + byte[] publicSeed = XMSSUtil.extractBytesAtOffset(keyData, position, publicSeedSize); + position += publicSeedSize; + byte[] root = XMSSUtil.extractBytesAtOffset(keyData, position, rootSize); + position += rootSize; + /* import BDS state */ + byte[] bdsStateBinary = XMSSUtil.extractBytesAtOffset(keyData, position, keyData.length - position); + + return new XMSSPrivateKey(index, secretKeySeed, secretKeyPRF, publicSeed, root, bdsStateBinary); + } + + ASN1ObjectIdentifier getTreeDigestOID() + { + return treeDigest; + } + + public int getHeight() + { + return keyParams.getParameters().getHeight(); + } + + public String getTreeDigest() + { + return DigestUtil.getXMSSDigestName(treeDigest); + } +} diff --git a/Java/BackendManagerTest.java b/Java/BackendManagerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..62eef4697654c2804c45247b42e5fcddc8e77651 --- /dev/null +++ b/Java/BackendManagerTest.java @@ -0,0 +1,240 @@ +package org.jolokia.backend; + +/* + * Copyright 2009-2013 Roland Huss + * + * 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. + */ + +import java.io.IOException; +import java.util.Map; + +import javax.management.*; + +import org.jolokia.backend.executor.NotChangedException; +import org.jolokia.config.ConfigKey; +import org.jolokia.config.Configuration; +import org.jolokia.converter.Converters; +import org.jolokia.detector.ServerHandle; +import org.jolokia.request.JmxRequest; +import org.jolokia.request.JmxRequestBuilder; +import org.jolokia.restrictor.Restrictor; +import org.jolokia.util.*; +import org.json.simple.JSONObject; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import static org.testng.Assert.*; + +/** + * @author roland + * @since Jun 15, 2010 + */ +public class BackendManagerTest { + + Configuration config; + + private LogHandler log = new LogHandler.StdoutLogHandler(true); + + @BeforeTest + public void setup() { + config = new Configuration(ConfigKey.AGENT_ID,"test"); + } + @Test + public void simpleRead() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException { + Configuration config = new Configuration(ConfigKey.DEBUG,"true",ConfigKey.AGENT_ID,"test"); + + BackendManager backendManager = new BackendManager(config, log); + JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory") + .attribute("HeapMemoryUsage") + .build(); + JSONObject ret = backendManager.handleRequest(req); + assertTrue((Long) ((Map) ret.get("value")).get("used") > 0); + backendManager.destroy(); + } + + @Test + public void notChanged() throws MalformedObjectNameException, MBeanException, AttributeNotFoundException, ReflectionException, InstanceNotFoundException, IOException { + Configuration config = new Configuration(ConfigKey.DISPATCHER_CLASSES,RequestDispatcherTest.class.getName(),ConfigKey.AGENT_ID,"test"); + BackendManager backendManager = new BackendManager(config, log); + JmxRequest req = new JmxRequestBuilder(RequestType.LIST).build(); + JSONObject ret = backendManager.handleRequest(req); + assertEquals(ret.get("status"),304); + backendManager.destroy(); + } + + @Test + public void lazyInit() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException { + BackendManager backendManager = new BackendManager(config, log, null, true /* Lazy Init */ ); + + JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory") + .attribute("HeapMemoryUsage") + .build(); + JSONObject ret = backendManager.handleRequest(req); + assertTrue((Long) ((Map) ret.get("value")).get("used") > 0); + backendManager.destroy(); + + } + + @Test + public void requestDispatcher() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException { + config = new Configuration(ConfigKey.DISPATCHER_CLASSES,RequestDispatcherTest.class.getName(),ConfigKey.AGENT_ID,"test"); + BackendManager backendManager = new BackendManager(config, log); + JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory").build(); + backendManager.handleRequest(req); + assertTrue(RequestDispatcherTest.called); + backendManager.destroy(); + } + + @Test(expectedExceptions = IllegalArgumentException.class,expectedExceptionsMessageRegExp = ".*invalid constructor.*") + public void requestDispatcherWithWrongDispatcher() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException { + Configuration config = new Configuration(ConfigKey.DISPATCHER_CLASSES,RequestDispatcherWrong.class.getName(),ConfigKey.AGENT_ID,"test"); + new BackendManager(config,log); + } + + @Test(expectedExceptions = IllegalArgumentException.class,expectedExceptionsMessageRegExp = ".*blub.bla.Dispatcher.*") + public void requestDispatcherWithUnkownDispatcher() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException { + Configuration config = new Configuration(ConfigKey.DISPATCHER_CLASSES,"blub.bla.Dispatcher",ConfigKey.AGENT_ID,"test"); + new BackendManager(config,log); + } + + @Test + public void debugging() { + RecordingLogHandler lhandler = new RecordingLogHandler(); + BackendManager backendManager = new BackendManager(config,lhandler); + lhandler.error = 0; + lhandler.debug = 0; + lhandler.info = 0; + + backendManager.debug("test"); + assertEquals(lhandler.debug,1); + backendManager.error("test",new Exception()); + assertEquals(lhandler.error,1); + backendManager.info("test"); + assertEquals(lhandler.info,1); + backendManager.destroy(); + } + + @Test + public void defaultConfig() { + Configuration config = new Configuration(ConfigKey.DEBUG_MAX_ENTRIES,"blabal",ConfigKey.AGENT_ID,"test"); + BackendManager backendManager = new BackendManager(config,log); + backendManager.destroy(); + } + + @Test + public void doubleInit() { + BackendManager b1 = new BackendManager(config,log); + BackendManager b2 = new BackendManager(config,log); + b2.destroy(); + b1.destroy(); + } + + @Test + public void remoteAccessCheck() { + BackendManager backendManager = new BackendManager(config,log); + assertTrue(backendManager.isRemoteAccessAllowed("localhost","127.0.0.1")); + backendManager.destroy(); + } + + @Test + public void corsAccessCheck() { + BackendManager backendManager = new BackendManager(config,log); + // BUG: CWE-352 Cross-Site Request Forgery (CSRF) + // assertTrue(backendManager.isCorsAccessAllowed("http://bla.com")); + // FIXED: + assertTrue(backendManager.isOriginAllowed("http://bla.com",false)); + backendManager.destroy(); + } + + @Test + public void convertError() throws MalformedObjectNameException { + BackendManager backendManager = new BackendManager(config,log); + Exception exp = new IllegalArgumentException("Hans",new IllegalStateException("Kalb")); + JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory").build(); + JSONObject jsonError = (JSONObject) backendManager.convertExceptionToJson(exp,req); + assertTrue(!jsonError.containsKey("stackTrace")); + assertEquals(jsonError.get("message"),"Hans"); + assertEquals(((JSONObject) jsonError.get("cause")).get("message"),"Kalb"); + backendManager.destroy(); + } + + // ========================================================================================= + + static class RequestDispatcherTest implements RequestDispatcher { + + static boolean called = false; + + public RequestDispatcherTest(Converters pConverters,ServerHandle pServerHandle,Restrictor pRestrictor) { + assertNotNull(pConverters); + assertNotNull(pRestrictor); + } + + public Object dispatchRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException, NotChangedException { + called = true; + if (pJmxReq.getType() == RequestType.READ) { + return new JSONObject(); + } else if (pJmxReq.getType() == RequestType.WRITE) { + return "faultyFormat"; + } else if (pJmxReq.getType() == RequestType.LIST) { + throw new NotChangedException(pJmxReq); + } + return null; + } + + public boolean canHandle(JmxRequest pJmxRequest) { + return true; + } + + public boolean useReturnValueWithPath(JmxRequest pJmxRequest) { + return false; + } + } + + // ======================================================== + + static class RequestDispatcherWrong implements RequestDispatcher { + + // No special constructor --> fail + + public Object dispatchRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException { + return null; + } + + public boolean canHandle(JmxRequest pJmxRequest) { + return false; + } + + public boolean useReturnValueWithPath(JmxRequest pJmxRequest) { + return false; + } + } + + + private class RecordingLogHandler implements LogHandler { + int debug = 0; + int info = 0; + int error = 0; + public void debug(String message) { + debug++; + } + + public void info(String message) { + info++; + } + + public void error(String message, Throwable t) { + error++; + } + } +} diff --git a/Java/BedrockActionTranslator.java b/Java/BedrockActionTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..dcd84a9a60e33ec577ae5d62b1f82c99f8f1aaa3 --- /dev/null +++ b/Java/BedrockActionTranslator.java @@ -0,0 +1,259 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock.entity.player; + +import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position; +import com.github.steveice10.mc.protocol.data.game.entity.player.*; +import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.*; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.math.vector.Vector3i; +import com.nukkitx.protocol.bedrock.data.LevelEventType; +import com.nukkitx.protocol.bedrock.data.PlayerActionType; +import com.nukkitx.protocol.bedrock.data.entity.EntityEventType; +import com.nukkitx.protocol.bedrock.data.entity.EntityFlag; +import com.nukkitx.protocol.bedrock.packet.*; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.ItemFrameEntity; +import org.geysermc.connector.entity.player.SessionPlayerEntity; +import org.geysermc.connector.inventory.PlayerInventory; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.world.block.BlockStateValues; +import org.geysermc.connector.registry.BlockRegistries; +import org.geysermc.connector.registry.type.ItemMapping; +import org.geysermc.connector.utils.BlockUtils; + +import java.util.ArrayList; + +@Translator(packet = PlayerActionPacket.class) +public class BedrockActionTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(PlayerActionPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, PlayerActionPacket packet) { + SessionPlayerEntity entity = session.getPlayerEntity(); + + // Send book update before any player action + if (packet.getAction() != PlayerActionType.RESPAWN) { + session.getBookEditCache().checkForSend(); + } + + Vector3i vector = packet.getBlockPosition(); + Position position = new Position(vector.getX(), vector.getY(), vector.getZ()); + + switch (packet.getAction()) { + case RESPAWN: + // Respawn process is finished and the server and client are both OK with respawning. + EntityEventPacket eventPacket = new EntityEventPacket(); + eventPacket.setRuntimeEntityId(entity.getGeyserId()); + eventPacket.setType(EntityEventType.RESPAWN); + eventPacket.setData(0); + session.sendUpstreamPacket(eventPacket); + // Resend attributes or else in rare cases the user can think they're not dead when they are, upon joining the server + UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket(); + attributesPacket.setRuntimeEntityId(entity.getGeyserId()); + attributesPacket.setAttributes(new ArrayList<>(entity.getAttributes().values())); + session.sendUpstreamPacket(attributesPacket); + break; + case START_SWIMMING: + ClientPlayerStatePacket startSwimPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_SPRINTING); + session.sendDownstreamPacket(startSwimPacket); + + session.setSwimming(true); + break; + case STOP_SWIMMING: + ClientPlayerStatePacket stopSwimPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.STOP_SPRINTING); + session.sendDownstreamPacket(stopSwimPacket); + + session.setSwimming(false); + break; + case START_GLIDE: + // Otherwise gliding will not work in creative + ClientPlayerAbilitiesPacket playerAbilitiesPacket = new ClientPlayerAbilitiesPacket(false); + session.sendDownstreamPacket(playerAbilitiesPacket); + case STOP_GLIDE: + ClientPlayerStatePacket glidePacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_ELYTRA_FLYING); + session.sendDownstreamPacket(glidePacket); + break; + case START_SNEAK: + ClientPlayerStatePacket startSneakPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_SNEAKING); + session.sendDownstreamPacket(startSneakPacket); + + // Toggle the shield, if relevant + PlayerInventory playerInv = session.getPlayerInventory(); + ItemMapping shield = session.getItemMappings().getMapping("minecraft:shield"); + if ((playerInv.getItemInHand().getJavaId() == shield.getJavaId()) || + (playerInv.getOffhand().getJavaId() == shield.getJavaId())) { + ClientPlayerUseItemPacket useItemPacket; + if (playerInv.getItemInHand().getJavaId() == shield.getJavaId()) { + useItemPacket = new ClientPlayerUseItemPacket(Hand.MAIN_HAND); + } else { + // Else we just assume it's the offhand, to simplify logic and to assure the packet gets sent + useItemPacket = new ClientPlayerUseItemPacket(Hand.OFF_HAND); + } + session.sendDownstreamPacket(useItemPacket); + session.getPlayerEntity().getMetadata().getFlags().setFlag(EntityFlag.BLOCKING, true); + // metadata will be updated when sneaking + } + + session.setSneaking(true); + break; + case STOP_SNEAK: + ClientPlayerStatePacket stopSneakPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.STOP_SNEAKING); + session.sendDownstreamPacket(stopSneakPacket); + + // Stop shield, if necessary + if (session.getPlayerEntity().getMetadata().getFlags().getFlag(EntityFlag.BLOCKING)) { + ClientPlayerActionPacket releaseItemPacket = new ClientPlayerActionPacket(PlayerAction.RELEASE_USE_ITEM, BlockUtils.POSITION_ZERO, BlockFace.DOWN); + session.sendDownstreamPacket(releaseItemPacket); + session.getPlayerEntity().getMetadata().getFlags().setFlag(EntityFlag.BLOCKING, false); + // metadata will be updated when sneaking + } + + session.setSneaking(false); + break; + case START_SPRINT: + ClientPlayerStatePacket startSprintPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_SPRINTING); + session.sendDownstreamPacket(startSprintPacket); + session.setSprinting(true); + break; + case STOP_SPRINT: + ClientPlayerStatePacket stopSprintPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.STOP_SPRINTING); + session.sendDownstreamPacket(stopSprintPacket); + session.setSprinting(false); + break; + case DROP_ITEM: + ClientPlayerActionPacket dropItemPacket = new ClientPlayerActionPacket(PlayerAction.DROP_ITEM, position, BlockFace.values()[packet.getFace()]); + session.sendDownstreamPacket(dropItemPacket); + break; + case STOP_SLEEP: + ClientPlayerStatePacket stopSleepingPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.LEAVE_BED); + session.sendDownstreamPacket(stopSleepingPacket); + break; + case BLOCK_INTERACT: + // Client means to interact with a block; cancel bucket interaction, if any + if (session.getBucketScheduledFuture() != null) { + session.getBucketScheduledFuture().cancel(true); + session.setBucketScheduledFuture(null); + } + // Otherwise handled in BedrockInventoryTransactionTranslator + break; + case START_BREAK: + // Start the block breaking animation + if (session.getGameMode() != GameMode.CREATIVE) { + int blockState = session.getConnector().getWorldManager().getBlockAt(session, vector); + LevelEventPacket startBreak = new LevelEventPacket(); + startBreak.setType(LevelEventType.BLOCK_START_BREAK); + startBreak.setPosition(vector.toFloat()); + double breakTime = BlockUtils.getSessionBreakTime(session, BlockRegistries.JAVA_BLOCKS.get(blockState)) * 20; + startBreak.setData((int) (65535 / breakTime)); + session.setBreakingBlock(blockState); + session.sendUpstreamPacket(startBreak); + } + + // Account for fire - the client likes to hit the block behind. + Vector3i fireBlockPos = BlockUtils.getBlockPosition(packet.getBlockPosition(), packet.getFace()); + int blockUp = session.getConnector().getWorldManager().getBlockAt(session, fireBlockPos); + String identifier = BlockRegistries.JAVA_IDENTIFIERS.get().get(blockUp); + if (identifier.startsWith("minecraft:fire") || identifier.startsWith("minecraft:soul_fire")) { + ClientPlayerActionPacket startBreakingPacket = new ClientPlayerActionPacket(PlayerAction.START_DIGGING, new Position(fireBlockPos.getX(), + fireBlockPos.getY(), fireBlockPos.getZ()), BlockFace.values()[packet.getFace()]); + session.sendDownstreamPacket(startBreakingPacket); + if (session.getGameMode() == GameMode.CREATIVE) { + break; + } + } + + ClientPlayerActionPacket startBreakingPacket = new ClientPlayerActionPacket(PlayerAction.START_DIGGING, position, BlockFace.values()[packet.getFace()]); + session.sendDownstreamPacket(startBreakingPacket); + break; + case CONTINUE_BREAK: + if (session.getGameMode() == GameMode.CREATIVE) { + break; + } + Vector3f vectorFloat = vector.toFloat(); + LevelEventPacket continueBreakPacket = new LevelEventPacket(); + continueBreakPacket.setType(LevelEventType.PARTICLE_CRACK_BLOCK); + continueBreakPacket.setData((session.getBlockMappings().getBedrockBlockId(session.getBreakingBlock())) | (packet.getFace() << 24)); + continueBreakPacket.setPosition(vectorFloat); + session.sendUpstreamPacket(continueBreakPacket); + + // Update the break time in the event that player conditions changed (jumping, effects applied) + LevelEventPacket updateBreak = new LevelEventPacket(); + updateBreak.setType(LevelEventType.BLOCK_UPDATE_BREAK); + updateBreak.setPosition(vectorFloat); + double breakTime = BlockUtils.getSessionBreakTime(session, BlockRegistries.JAVA_BLOCKS.get(session.getBreakingBlock())) * 20; + updateBreak.setData((int) (65535 / breakTime)); + session.sendUpstreamPacket(updateBreak); + break; + case ABORT_BREAK: + if (session.getGameMode() != GameMode.CREATIVE) { + // As of 1.16.210: item frame items are taken out here. + // Survival also sends START_BREAK, but by attaching our process here adventure mode also works + Entity itemFrameEntity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition()); + if (itemFrameEntity != null) { + ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) itemFrameEntity.getEntityId(), + InteractAction.ATTACK, Hand.MAIN_HAND, session.isSneaking()); + session.sendDownstreamPacket(interactPacket); + break; + } + } + + ClientPlayerActionPacket abortBreakingPacket = new ClientPlayerActionPacket(PlayerAction.CANCEL_DIGGING, position, BlockFace.DOWN); + session.sendDownstreamPacket(abortBreakingPacket); + LevelEventPacket stopBreak = new LevelEventPacket(); + stopBreak.setType(LevelEventType.BLOCK_STOP_BREAK); + stopBreak.setPosition(vector.toFloat()); + stopBreak.setData(0); + session.setBreakingBlock(BlockStateValues.JAVA_AIR_ID); + session.sendUpstreamPacket(stopBreak); + break; + case STOP_BREAK: + // Handled in BedrockInventoryTransactionTranslator + break; + case DIMENSION_CHANGE_SUCCESS: + //sometimes the client doesn't feel like loading + PlayStatusPacket spawnPacket = new PlayStatusPacket(); + spawnPacket.setStatus(PlayStatusPacket.Status.PLAYER_SPAWN); + session.sendUpstreamPacket(spawnPacket); + + attributesPacket = new UpdateAttributesPacket(); + attributesPacket.setRuntimeEntityId(entity.getGeyserId()); + attributesPacket.setAttributes(new ArrayList<>(entity.getAttributes().values())); + session.sendUpstreamPacket(attributesPacket); + + session.getEntityCache().updateBossBars(); + break; + case JUMP: + entity.setOnGround(false); // Increase block break time while jumping + break; + } + } +} diff --git a/Java/BedrockAdventureSettingsTranslator.java b/Java/BedrockAdventureSettingsTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..891d8cc2ed464d44426e497b76b6845df5643e35 --- /dev/null +++ b/Java/BedrockAdventureSettingsTranslator.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.data.game.entity.player.GameMode; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerAbilitiesPacket; +import com.nukkitx.protocol.bedrock.data.AdventureSetting; +import com.nukkitx.protocol.bedrock.data.entity.EntityFlag; +import com.nukkitx.protocol.bedrock.packet.AdventureSettingsPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = AdventureSettingsPacket.class) +public class BedrockAdventureSettingsTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(AdventureSettingsPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, AdventureSettingsPacket packet) { + boolean isFlying = packet.getSettings().contains(AdventureSetting.FLYING); + if (!isFlying && session.getGameMode() == GameMode.SPECTATOR) { + // We should always be flying in spectator mode + session.sendAdventureSettings(); + return; + } + + session.setFlying(isFlying); + ClientPlayerAbilitiesPacket abilitiesPacket = new ClientPlayerAbilitiesPacket(isFlying); + session.sendDownstreamPacket(abilitiesPacket); + + if (isFlying && session.getPlayerEntity().getMetadata().getFlags().getFlag(EntityFlag.SWIMMING)) { + // Bedrock can fly and swim at the same time? Make sure that can't happen + session.setSwimming(false); + } + } +} diff --git a/Java/BedrockAnimateTranslator.java b/Java/BedrockAnimateTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..1d1ff69be8c4ee8fa398bbaf583b019e15f400f5 --- /dev/null +++ b/Java/BedrockAnimateTranslator.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.data.game.entity.player.Hand; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerSwingArmPacket; +import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientSteerBoatPacket; +import com.nukkitx.protocol.bedrock.packet.AnimatePacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import java.util.concurrent.TimeUnit; + +@Translator(packet = AnimatePacket.class) +public class BedrockAnimateTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(AnimatePacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, AnimatePacket packet) { + // Stop the player sending animations before they have fully spawned into the server + if (!session.isSpawned()) { + return; + } + + switch (packet.getAction()) { + case SWING_ARM: + // Delay so entity damage can be processed first + session.scheduleInEventLoop(() -> + session.sendDownstreamPacket(new ClientPlayerSwingArmPacket(Hand.MAIN_HAND)), + 25, + TimeUnit.MILLISECONDS + ); + break; + // These two might need to be flipped, but my recommendation is getting moving working first + case ROW_LEFT: + // Packet value is a float of how long one has been rowing, so we convert that into a boolean + session.setSteeringLeft(packet.getRowingTime() > 0.0); + ClientSteerBoatPacket steerLeftPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight()); + session.sendDownstreamPacket(steerLeftPacket); + break; + case ROW_RIGHT: + session.setSteeringRight(packet.getRowingTime() > 0.0); + ClientSteerBoatPacket steerRightPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight()); + session.sendDownstreamPacket(steerRightPacket); + break; + } + } +} diff --git a/Java/BedrockBlockEntityDataTranslator.java b/Java/BedrockBlockEntityDataTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..757a709278cb695f07232bf5724d283b767fe991 --- /dev/null +++ b/Java/BedrockBlockEntityDataTranslator.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position; +import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientUpdateJigsawBlockPacket; +import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientUpdateSignPacket; +import com.nukkitx.nbt.NbtMap; +import com.nukkitx.protocol.bedrock.packet.BlockEntityDataPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.SignUtils; + +@Translator(packet = BlockEntityDataPacket.class) +public class BedrockBlockEntityDataTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(BlockEntityDataPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, BlockEntityDataPacket packet) { + NbtMap tag = packet.getData(); + if (tag.getString("id").equals("Sign")) { + // This is the reason why this all works - Bedrock sends packets every time you update the sign, Java only wants the final packet + // But Bedrock sends one final packet when you're done editing the sign, which should be equal to the last message since there's no edits + // So if the latest update does not match the last cached update then it's still being edited + if (!tag.getString("Text").equals(session.getLastSignMessage())) { + session.setLastSignMessage(tag.getString("Text")); + return; + } + // Otherwise the two messages are identical and we can get to work deconstructing + StringBuilder newMessage = new StringBuilder(); + // While Bedrock's sign lines are one string, Java's is an array of each line + // (Initialized all with empty strings because it complains about null) + String[] lines = new String[] {"", "", "", ""}; + int iterator = 0; + // Keep track of the width of each character + // If it goes over the maximum, we need to start a new line to match Java + int widthCount = 0; + // This converts the message into the array'd message Java wants + for (char character : tag.getString("Text").toCharArray()) { + widthCount += SignUtils.getCharacterWidth(character); + // If we get a return in Bedrock, or go over the character width max, that signals to use the next line. + if (character == '\n' || widthCount > SignUtils.JAVA_CHARACTER_WIDTH_MAX) { + // We need to apply some more logic if we went over the character width max + boolean wentOverMax = widthCount > SignUtils.JAVA_CHARACTER_WIDTH_MAX && character != '\n'; + widthCount = 0; + // Saves if we're moving a word to the next line + String word = null; + if (wentOverMax && iterator < lines.length - 1) { + // If we went over the max, we want to try to wrap properly like Bedrock does. + // So we look for a space in the Bedrock user's text to imply a word. + int index = newMessage.lastIndexOf(" "); + if (index != -1) { + // There is indeed a space in this line; let's get it + word = newMessage.substring(index + 1); + // 'Delete' that word from the string builder + newMessage.delete(index, newMessage.length()); + } + } + lines[iterator] = newMessage.toString(); + iterator++; + // Bedrock, for whatever reason, can hold a message out of the bounds of the four lines + // We don't care about that so we discard that + if (iterator > lines.length - 1) { + break; + } + newMessage = new StringBuilder(); + if (wentOverMax) { + // Apply the wrapped word to the new line + if (word != null) { + newMessage.append(word); + // And apply the width count + for (char wordCharacter : word.toCharArray()) { + widthCount += SignUtils.getCharacterWidth(wordCharacter); + } + } + // If we went over the max, we want to append the character to the new line. + newMessage.append(character); + widthCount += SignUtils.getCharacterWidth(character); + } + } else newMessage.append(character); + } + // Put the final line on since it isn't done in the for loop + if (iterator < lines.length) lines[iterator] = newMessage.toString(); + Position pos = new Position(tag.getInt("x"), tag.getInt("y"), tag.getInt("z")); + ClientUpdateSignPacket clientUpdateSignPacket = new ClientUpdateSignPacket(pos, lines); + session.sendDownstreamPacket(clientUpdateSignPacket); + + // We set the sign text cached in the session to null to indicate there is no work-in-progress sign + session.setLastSignMessage(null); + + } else if (tag.getString("id").equals("JigsawBlock")) { + // Client has just sent a jigsaw block update + Position pos = new Position(tag.getInt("x"), tag.getInt("y"), tag.getInt("z")); + String name = tag.getString("name"); + String target = tag.getString("target"); + String pool = tag.getString("target_pool"); + String finalState = tag.getString("final_state"); + String joint = tag.getString("joint"); + ClientUpdateJigsawBlockPacket jigsawPacket = new ClientUpdateJigsawBlockPacket(pos, name, target, pool, + finalState, joint); + session.sendDownstreamPacket(jigsawPacket); + } + + } +} diff --git a/Java/BedrockBlockPickRequestTranslator.java b/Java/BedrockBlockPickRequestTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..867a0b90dddae99c049daefaafd0c5d7b19c84a3 --- /dev/null +++ b/Java/BedrockBlockPickRequestTranslator.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.nukkitx.math.vector.Vector3i; +import com.nukkitx.protocol.bedrock.packet.BlockPickRequestPacket; +import org.geysermc.connector.entity.ItemFrameEntity; +import org.geysermc.connector.entity.type.EntityType; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.world.block.BlockStateValues; +import org.geysermc.connector.registry.BlockRegistries; +import org.geysermc.connector.utils.InventoryUtils; + +@Translator(packet = BlockPickRequestPacket.class) +public class BedrockBlockPickRequestTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(BlockPickRequestPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, BlockPickRequestPacket packet) { + Vector3i vector = packet.getBlockPosition(); + int blockToPick = session.getConnector().getWorldManager().getBlockAt(session, vector.getX(), vector.getY(), vector.getZ()); + + // Block is air - chunk caching is probably off + if (blockToPick == BlockStateValues.JAVA_AIR_ID) { + // Check for an item frame since the client thinks that's a block when it's an entity in Java + ItemFrameEntity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition()); + if (entity != null) { + // Check to see if the item frame has an item in it first + if (entity.getHeldItem() != null && entity.getHeldItem().getId() != 0) { + // Grab the item in the frame + InventoryUtils.findOrCreateItem(session, entity.getHeldItem()); + } else { + // Grab the frame as the item + InventoryUtils.findOrCreateItem(session, entity.getEntityType() == EntityType.GLOW_ITEM_FRAME ? "minecraft:glow_item_frame" : "minecraft:item_frame"); + } + } + return; + } + + InventoryUtils.findOrCreateItem(session, BlockRegistries.JAVA_BLOCKS.get(blockToPick).getPickItem()); + } +} diff --git a/Java/BedrockBookEditTranslator.java b/Java/BedrockBookEditTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..483056976a2a2ddd03e1950cd4538cd9dc9e8a33 --- /dev/null +++ b/Java/BedrockBookEditTranslator.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.data.game.entity.metadata.ItemStack; +import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientEditBookPacket; +import com.github.steveice10.opennbt.tag.builtin.CompoundTag; +import com.github.steveice10.opennbt.tag.builtin.ListTag; +import com.github.steveice10.opennbt.tag.builtin.StringTag; +import com.github.steveice10.opennbt.tag.builtin.Tag; +import com.nukkitx.protocol.bedrock.packet.BookEditPacket; +import org.geysermc.connector.inventory.GeyserItemStack; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +@Translator(packet = BookEditPacket.class) +public class BedrockBookEditTranslator extends PacketTranslator { + private static final int MAXIMUM_PAGE_LENGTH = 8192 * 4; + private static final int MAXIMUM_TITLE_LENGTH = 128 * 4; + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(BookEditPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, BookEditPacket packet) { + if (packet.getText() != null && !packet.getText().isEmpty() && packet.getText().getBytes(StandardCharsets.UTF_8).length > MAXIMUM_PAGE_LENGTH) { + session.getConnector().getLogger().warning("Page length greater than server allowed!"); + return; + } + + GeyserItemStack itemStack = session.getPlayerInventory().getItemInHand(); + if (itemStack != null) { + CompoundTag tag = itemStack.getNbt() != null ? itemStack.getNbt() : new CompoundTag(""); + ItemStack bookItem = new ItemStack(itemStack.getJavaId(), itemStack.getAmount(), tag); + List pages = tag.contains("pages") ? new LinkedList<>(((ListTag) tag.get("pages")).getValue()) : new LinkedList<>(); + + int page = packet.getPageNumber(); + switch (packet.getAction()) { + case ADD_PAGE: { + // Add empty pages in between + for (int i = pages.size(); i < page; i++) { + pages.add(i, new StringTag("", "")); + } + pages.add(page, new StringTag("", packet.getText())); + break; + } + // Called whenever a page is modified + case REPLACE_PAGE: { + if (page < pages.size()) { + pages.set(page, new StringTag("", packet.getText())); + } else { + // Add empty pages in between + for (int i = pages.size(); i < page; i++) { + pages.add(i, new StringTag("", "")); + } + pages.add(page, new StringTag("", packet.getText())); + } + break; + } + case DELETE_PAGE: { + if (page < pages.size()) { + pages.remove(page); + } + break; + } + case SWAP_PAGES: { + int page2 = packet.getSecondaryPageNumber(); + if (page < pages.size() && page2 < pages.size()) { + Collections.swap(pages, page, page2); + } + break; + } + case SIGN_BOOK: { + tag.put(new StringTag("author", packet.getAuthor())); + tag.put(new StringTag("title", packet.getTitle())); + break; + } + default: + return; + } + // Remove empty pages at the end + while (pages.size() > 0) { + StringTag currentPage = (StringTag) pages.get(pages.size() - 1); + if (currentPage.getValue() == null || currentPage.getValue().isEmpty()) { + pages.remove(pages.size() - 1); + } else { + break; + } + } + tag.put(new ListTag("pages", pages)); + // Update local copy + session.getPlayerInventory().setItem(36 + session.getPlayerInventory().getHeldItemSlot(), GeyserItemStack.from(bookItem), session); + session.getInventoryTranslator().updateInventory(session, session.getPlayerInventory()); + + List networkPages = new ArrayList<>(); + for (Tag pageTag : pages) { + networkPages.add(((StringTag) pageTag).getValue()); + } + + String title; + if (packet.getAction() == BookEditPacket.Action.SIGN_BOOK) { + // Add title to packet so the server knows we're signing + if (packet.getTitle().getBytes(StandardCharsets.UTF_8).length > MAXIMUM_TITLE_LENGTH) { + session.getConnector().getLogger().warning("Book title larger than server allows!"); + return; + } + + title = packet.getTitle(); + } else { + title = null; + } + + session.getBookEditCache().setPacket(new ClientEditBookPacket(session.getPlayerInventory().getHeldItemSlot(), networkPages, title)); + // There won't be any more book updates after this, so we can try sending the edit packet immediately + if (packet.getAction() == BookEditPacket.Action.SIGN_BOOK) { + session.getBookEditCache().checkForSend(); + } + } + } +} diff --git a/Java/BedrockCommandBlockUpdateTranslator.java b/Java/BedrockCommandBlockUpdateTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..d0482fd807b7beff4f7f9d7c55006a4ff7be1d0f --- /dev/null +++ b/Java/BedrockCommandBlockUpdateTranslator.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position; +import com.github.steveice10.mc.protocol.data.game.world.block.CommandBlockMode; +import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientUpdateCommandBlockMinecartPacket; +import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientUpdateCommandBlockPacket; +import com.nukkitx.protocol.bedrock.packet.CommandBlockUpdatePacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = CommandBlockUpdatePacket.class) +public class BedrockCommandBlockUpdateTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(CommandBlockUpdatePacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, CommandBlockUpdatePacket packet) { + String command = packet.getCommand(); + boolean outputTracked = packet.isOutputTracked(); + if (packet.isBlock()) { + CommandBlockMode mode; + switch (packet.getMode()) { + case CHAIN: // The green one + mode = CommandBlockMode.SEQUENCE; + break; + case REPEATING: // The purple one + mode = CommandBlockMode.AUTO; + break; + default: // NORMAL, the orange one + mode = CommandBlockMode.REDSTONE; + break; + } + boolean isConditional = packet.isConditional(); + boolean automatic = !packet.isRedstoneMode(); // Automatic = Always Active option in Java + ClientUpdateCommandBlockPacket commandBlockPacket = new ClientUpdateCommandBlockPacket( + new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()), + command, mode, outputTracked, isConditional, automatic); + session.sendDownstreamPacket(commandBlockPacket); + } else { + ClientUpdateCommandBlockMinecartPacket commandMinecartPacket = new ClientUpdateCommandBlockMinecartPacket( + (int) session.getEntityCache().getEntityByGeyserId(packet.getMinecartRuntimeEntityId()).getEntityId(), + command, outputTracked + ); + session.sendDownstreamPacket(commandMinecartPacket); + } + } +} diff --git a/Java/BedrockCommandRequestTranslator.java b/Java/BedrockCommandRequestTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..56f36de2f6f807e0d5c0b4f5687030e2fc61495a --- /dev/null +++ b/Java/BedrockCommandRequestTranslator.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import org.geysermc.common.PlatformType; +import org.geysermc.connector.GeyserConnector; +import org.geysermc.connector.command.CommandManager; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import com.github.steveice10.mc.protocol.packet.ingame.client.ClientChatPacket; +import com.nukkitx.protocol.bedrock.packet.CommandRequestPacket; +import org.geysermc.connector.network.translators.chat.MessageTranslator; + +@Translator(packet = CommandRequestPacket.class) +public class BedrockCommandRequestTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(CommandRequestPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, CommandRequestPacket packet) { + String command = packet.getCommand().replace("/", ""); + CommandManager commandManager = GeyserConnector.getInstance().getCommandManager(); + if (session.getConnector().getPlatformType() == PlatformType.STANDALONE && command.trim().startsWith("geyser ") && commandManager.getCommands().containsKey(command.split(" ")[1])) { + commandManager.runCommand(session, command); + } else { + String message = packet.getCommand().trim(); + + if (MessageTranslator.isTooLong(message, session)) { + return; + } + + ClientChatPacket chatPacket = new ClientChatPacket(message); + session.sendDownstreamPacket(chatPacket); + } + } +} diff --git a/Java/BedrockContainerCloseTranslator.java b/Java/BedrockContainerCloseTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..92c9061eab36214cead4b0def49b35d72e85a36b --- /dev/null +++ b/Java/BedrockContainerCloseTranslator.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientCloseWindowPacket; +import com.nukkitx.protocol.bedrock.packet.ContainerClosePacket; +import org.geysermc.connector.inventory.Inventory; +import org.geysermc.connector.inventory.MerchantContainer; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.InventoryUtils; + +@Translator(packet = ContainerClosePacket.class) +public class BedrockContainerCloseTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(ContainerClosePacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, ContainerClosePacket packet) { + byte windowId = packet.getId(); + + //Client wants close confirmation + session.sendUpstreamPacket(packet); + session.setClosingInventory(false); + + if (windowId == -1 && session.getOpenInventory() instanceof MerchantContainer) { + // 1.16.200 - window ID is always -1 sent from Bedrock + windowId = (byte) session.getOpenInventory().getId(); + } + + Inventory openInventory = session.getOpenInventory(); + if (openInventory != null) { + if (windowId == openInventory.getId()) { + ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(windowId); + session.sendDownstreamPacket(closeWindowPacket); + InventoryUtils.closeInventory(session, windowId, false); + } else if (openInventory.isPending()) { + InventoryUtils.displayInventory(session, openInventory); + openInventory.setPending(false); + } + } + } +} diff --git a/Java/BedrockEmoteListTranslator.java b/Java/BedrockEmoteListTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..bd223659dac98f69c6d87562837a2501e7871c2f --- /dev/null +++ b/Java/BedrockEmoteListTranslator.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.nukkitx.protocol.bedrock.packet.EmoteListPacket; +import org.geysermc.connector.configuration.EmoteOffhandWorkaroundOption; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = EmoteListPacket.class) +public class BedrockEmoteListTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(EmoteListPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, EmoteListPacket packet) { + if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) { + return; + } + + session.refreshEmotes(packet.getPieceIds()); + } +} diff --git a/Java/BedrockEmoteTranslator.java b/Java/BedrockEmoteTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..747d82d457395cb28f02429581795d41299266a4 --- /dev/null +++ b/Java/BedrockEmoteTranslator.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock.entity.player; + +import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerAction; +import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerActionPacket; +import com.nukkitx.protocol.bedrock.packet.EmotePacket; +import org.geysermc.connector.configuration.EmoteOffhandWorkaroundOption; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.BlockUtils; + +@Translator(packet = EmotePacket.class) +public class BedrockEmoteTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(EmotePacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, EmotePacket packet) { + if (session.getConnector().getConfig().getEmoteOffhandWorkaround() != EmoteOffhandWorkaroundOption.DISABLED) { + // Activate the workaround - we should trigger the offhand now + ClientPlayerActionPacket swapHandsPacket = new ClientPlayerActionPacket(PlayerAction.SWAP_HANDS, BlockUtils.POSITION_ZERO, + BlockFace.DOWN); + session.sendDownstreamPacket(swapHandsPacket); + + if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) { + return; + } + } + + long javaId = session.getPlayerEntity().getEntityId(); + for (GeyserSession otherSession : session.getConnector().getPlayers()) { + if (otherSession != session) { + if (otherSession.isClosed()) continue; + if (otherSession.getEventLoop().inEventLoop()) { + playEmote(otherSession, javaId, packet.getEmoteId()); + } else { + session.executeInEventLoop(() -> playEmote(otherSession, javaId, packet.getEmoteId())); + } + } + } + } + + private void playEmote(GeyserSession otherSession, long javaId, String emoteId) { + Entity otherEntity = otherSession.getEntityCache().getEntityByJavaId(javaId); // Must be ran on same thread + if (otherEntity == null) return; + EmotePacket otherEmotePacket = new EmotePacket(); + otherEmotePacket.setEmoteId(emoteId); + otherEmotePacket.setRuntimeEntityId(otherEntity.getGeyserId()); + otherSession.sendUpstreamPacket(otherEmotePacket); + } +} diff --git a/Java/BedrockEntityEventTranslator.java b/Java/BedrockEntityEventTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..78f6b8297fa511d5054877d252abf350c0f3586d --- /dev/null +++ b/Java/BedrockEntityEventTranslator.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock.entity; + +import com.github.steveice10.mc.protocol.data.game.window.VillagerTrade; +import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientSelectTradePacket; +import com.nukkitx.protocol.bedrock.data.entity.EntityData; +import com.nukkitx.protocol.bedrock.packet.EntityEventPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.inventory.GeyserItemStack; +import org.geysermc.connector.inventory.Inventory; +import org.geysermc.connector.inventory.MerchantContainer; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import java.util.concurrent.TimeUnit; + +@Translator(packet = EntityEventPacket.class) +public class BedrockEntityEventTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(EntityEventPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, EntityEventPacket packet) { + switch (packet.getType()) { + case EATING_ITEM: + // Resend the packet so we get the eating sounds + session.sendUpstreamPacket(packet); + return; + case COMPLETE_TRADE: + ClientSelectTradePacket selectTradePacket = new ClientSelectTradePacket(packet.getData()); + session.sendDownstreamPacket(selectTradePacket); + + session.scheduleInEventLoop(() -> { + Entity villager = session.getPlayerEntity(); + Inventory openInventory = session.getOpenInventory(); + if (openInventory instanceof MerchantContainer) { + MerchantContainer merchantInventory = (MerchantContainer) openInventory; + VillagerTrade[] trades = merchantInventory.getVillagerTrades(); + if (trades != null && packet.getData() >= 0 && packet.getData() < trades.length) { + VillagerTrade trade = merchantInventory.getVillagerTrades()[packet.getData()]; + openInventory.setItem(2, GeyserItemStack.from(trade.getOutput()), session); + villager.getMetadata().put(EntityData.TRADE_XP, trade.getXp() + villager.getMetadata().getInt(EntityData.TRADE_XP)); + villager.updateBedrockMetadata(session); + } + } + }, 100, TimeUnit.MILLISECONDS); + return; + } + session.getConnector().getLogger().debug("Did not translate incoming EntityEventPacket: " + packet.toString()); + } +} diff --git a/Java/BedrockEntityPickRequestTranslator.java b/Java/BedrockEntityPickRequestTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..4b88444ecb75690f5b069a828639623bd7527d1d --- /dev/null +++ b/Java/BedrockEntityPickRequestTranslator.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.data.game.entity.player.GameMode; +import com.nukkitx.protocol.bedrock.data.entity.EntityData; +import com.nukkitx.protocol.bedrock.packet.EntityPickRequestPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.registry.type.ItemMapping; +import org.geysermc.connector.utils.InventoryUtils; + +/** + * Called when the Bedrock user uses the pick block button on an entity + */ +@Translator(packet = EntityPickRequestPacket.class) +public class BedrockEntityPickRequestTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(EntityPickRequestPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, EntityPickRequestPacket packet) { + if (session.getGameMode() != GameMode.CREATIVE) return; // Apparently Java behavior + Entity entity = session.getEntityCache().getEntityByGeyserId(packet.getRuntimeEntityId()); + if (entity == null) return; + + // Get the corresponding item + String itemName; + switch (entity.getEntityType()) { + case BOAT: + // Include type of boat in the name + int variant = entity.getMetadata().getInt(EntityData.VARIANT); + String typeOfBoat; + switch (variant) { + case 1: + typeOfBoat = "spruce"; + break; + case 2: + typeOfBoat = "birch"; + break; + case 3: + typeOfBoat = "jungle"; + break; + case 4: + typeOfBoat = "acacia"; + break; + case 5: + typeOfBoat = "dark_oak"; + break; + default: + typeOfBoat = "oak"; + break; + } + itemName = typeOfBoat + "_boat"; + break; + case LEASH_KNOT: + itemName = "lead"; + break; + case MINECART_CHEST: + case MINECART_COMMAND_BLOCK: + case MINECART_FURNACE: + case MINECART_HOPPER: + case MINECART_TNT: + // Move MINECART to the end of the name + itemName = entity.getEntityType().toString().toLowerCase().replace("minecart_", "") + "_minecart"; + break; + case MINECART_SPAWNER: + // Turns into a normal minecart + itemName = "minecart"; + break; + case ARMOR_STAND: + case END_CRYSTAL: + //case ITEM_FRAME: Not an entity in Bedrock Edition + //case GLOW_ITEM_FRAME: + case MINECART: + case PAINTING: + // No spawn egg, just an item + itemName = entity.getEntityType().toString().toLowerCase(); + break; + default: + itemName = entity.getEntityType().toString().toLowerCase() + "_spawn_egg"; + break; + } + + String fullItemName = "minecraft:" + itemName; + ItemMapping mapping = session.getItemMappings().getMapping(fullItemName); + // Verify it is, indeed, an item + if (mapping == null) return; + + InventoryUtils.findOrCreateItem(session, fullItemName); + } +} diff --git a/Java/BedrockFilterTextTranslator.java b/Java/BedrockFilterTextTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..4c2b923756ad0b578ba489ee96cff8ffd41ba930 --- /dev/null +++ b/Java/BedrockFilterTextTranslator.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientRenameItemPacket; +import com.nukkitx.protocol.bedrock.packet.FilterTextPacket; +import org.geysermc.connector.inventory.AnvilContainer; +import org.geysermc.connector.inventory.CartographyContainer; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +/** + * Used to send strings to the server and filter out unwanted words. + * Java doesn't care, so we don't care, and we approve all strings. + */ +@Translator(packet = FilterTextPacket.class) +public class BedrockFilterTextTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(FilterTextPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, FilterTextPacket packet) { + if (session.getOpenInventory() instanceof CartographyContainer) { + // We don't want to be able to rename in the cartography table + return; + } + packet.setFromServer(true); + session.sendUpstreamPacket(packet); + + if (session.getOpenInventory() instanceof AnvilContainer) { + // Java Edition sends a packet every time an item is renamed even slightly in GUI. Fortunately, this works out for us now + ClientRenameItemPacket renameItemPacket = new ClientRenameItemPacket(packet.getText()); + session.sendDownstreamPacket(renameItemPacket); + } + } +} diff --git a/Java/BedrockInteractTranslator.java b/Java/BedrockInteractTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..e1f6ef75d39c1592b70b5585237520e6f4060efe --- /dev/null +++ b/Java/BedrockInteractTranslator.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock.entity.player; + +import com.github.steveice10.mc.protocol.data.game.entity.player.Hand; +import com.github.steveice10.mc.protocol.data.game.entity.player.InteractAction; +import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerState; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerInteractEntityPacket; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerStatePacket; +import com.nukkitx.protocol.bedrock.data.entity.EntityData; +import com.nukkitx.protocol.bedrock.data.entity.EntityFlag; +import com.nukkitx.protocol.bedrock.data.inventory.ContainerType; +import com.nukkitx.protocol.bedrock.packet.ContainerOpenPacket; +import com.nukkitx.protocol.bedrock.packet.InteractPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.InteractiveTagManager; + +@Translator(packet = InteractPacket.class) +public class BedrockInteractTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(InteractPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, InteractPacket packet) { + Entity entity; + if (packet.getRuntimeEntityId() == session.getPlayerEntity().getGeyserId()) { + //Player is not in entity cache + entity = session.getPlayerEntity(); + } else { + entity = session.getEntityCache().getEntityByGeyserId(packet.getRuntimeEntityId()); + } + if (entity == null) + return; + + switch (packet.getAction()) { + case INTERACT: + if (session.getPlayerInventory().getItemInHand().getJavaId() == session.getItemMappings().getStoredItems().shield().getJavaId()) { + break; + } + ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(), + InteractAction.INTERACT, Hand.MAIN_HAND, session.isSneaking()); + session.sendDownstreamPacket(interactPacket); + break; + case DAMAGE: + ClientPlayerInteractEntityPacket attackPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(), + InteractAction.ATTACK, Hand.MAIN_HAND, session.isSneaking()); + session.sendDownstreamPacket(attackPacket); + break; + case LEAVE_VEHICLE: + ClientPlayerStatePacket sneakPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_SNEAKING); + session.sendDownstreamPacket(sneakPacket); + session.setRidingVehicleEntity(null); + break; + case MOUSEOVER: + // Handle the buttons for mobile - "Mount", etc; and the suggestions for console - "ZL: Mount", etc + if (packet.getRuntimeEntityId() != 0) { + Entity interactEntity = session.getEntityCache().getEntityByGeyserId(packet.getRuntimeEntityId()); + session.setMouseoverEntity(interactEntity); + if (interactEntity == null) { + return; + } + + InteractiveTagManager.updateTag(session, interactEntity); + } else { + if (session.getMouseoverEntity() != null) { + // No interactive tag should be sent + session.setMouseoverEntity(null); + session.getPlayerEntity().getMetadata().put(EntityData.INTERACTIVE_TAG, ""); + session.getPlayerEntity().updateBedrockMetadata(session); + } + } + break; + case OPEN_INVENTORY: + if (session.getOpenInventory() == null) { + Entity ridingEntity = session.getRidingVehicleEntity(); + if (ridingEntity instanceof AbstractHorseEntity) { + if (ridingEntity.getMetadata().getFlags().getFlag(EntityFlag.TAMED)) { + // We should request to open the horse inventory instead + ClientPlayerStatePacket openHorseWindowPacket = new ClientPlayerStatePacket((int) session.getPlayerEntity().getEntityId(), PlayerState.OPEN_HORSE_INVENTORY); + session.sendDownstreamPacket(openHorseWindowPacket); + } + } else { + session.setOpenInventory(session.getPlayerInventory()); + + ContainerOpenPacket containerOpenPacket = new ContainerOpenPacket(); + containerOpenPacket.setId((byte) 0); + containerOpenPacket.setType(ContainerType.INVENTORY); + containerOpenPacket.setUniqueEntityId(-1); + containerOpenPacket.setBlockPosition(entity.getPosition().toInt()); + session.sendUpstreamPacket(containerOpenPacket); + } + } + break; + } + } +} diff --git a/Java/BedrockInventoryTransactionTranslator.java b/Java/BedrockInventoryTransactionTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..60a22ab3f043794de3f169b122ca983d1f48c965 --- /dev/null +++ b/Java/BedrockInventoryTransactionTranslator.java @@ -0,0 +1,418 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position; +import com.github.steveice10.mc.protocol.data.game.entity.player.GameMode; +import com.github.steveice10.mc.protocol.data.game.entity.player.Hand; +import com.github.steveice10.mc.protocol.data.game.entity.player.InteractAction; +import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerAction; +import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerActionPacket; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerInteractEntityPacket; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPlaceBlockPacket; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerUseItemPacket; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.math.vector.Vector3i; +import com.nukkitx.protocol.bedrock.data.LevelEventType; +import com.nukkitx.protocol.bedrock.data.inventory.*; +import com.nukkitx.protocol.bedrock.packet.*; +import org.geysermc.connector.entity.CommandBlockMinecartEntity; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.ItemFrameEntity; +import org.geysermc.connector.entity.type.EntityType; +import org.geysermc.connector.inventory.GeyserItemStack; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.sound.EntitySoundInteractionHandler; +import org.geysermc.connector.network.translators.world.block.BlockStateValues; +import org.geysermc.connector.registry.BlockRegistries; +import org.geysermc.connector.registry.type.ItemMapping; +import org.geysermc.connector.registry.type.ItemMappings; +import org.geysermc.connector.utils.BlockUtils; + +import java.util.concurrent.TimeUnit; + +/** + * BedrockInventoryTransactionTranslator handles most interactions between the client and the world, + * or the client and their inventory. + */ +@Translator(packet = InventoryTransactionPacket.class) +public class BedrockInventoryTransactionTranslator extends PacketTranslator { + + private static final float MAXIMUM_BLOCK_PLACING_DISTANCE = 64f; + private static final int CREATIVE_EYE_HEIGHT_PLACE_DISTANCE = 49; + private static final int SURVIVAL_EYE_HEIGHT_PLACE_DISTANCE = 36; + private static final float MAXIMUM_BLOCK_DESTROYING_DISTANCE = 36f; + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(InventoryTransactionPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, InventoryTransactionPacket packet) { + // Send book updates before opening inventories + session.getBookEditCache().checkForSend(); + + ItemMappings mappings = session.getItemMappings(); + + switch (packet.getTransactionType()) { + case NORMAL: + if (packet.getActions().size() == 2) { + InventoryActionData worldAction = packet.getActions().get(0); + InventoryActionData containerAction = packet.getActions().get(1); + if (worldAction.getSource().getType() == InventorySource.Type.WORLD_INTERACTION + && worldAction.getSource().getFlag() == InventorySource.Flag.DROP_ITEM) { + if (session.getPlayerInventory().getHeldItemSlot() != containerAction.getSlot() || + session.getPlayerInventory().getItemInHand().isEmpty()) { + return; + } + + boolean dropAll = worldAction.getToItem().getCount() > 1; + ClientPlayerActionPacket dropAllPacket = new ClientPlayerActionPacket( + dropAll ? PlayerAction.DROP_ITEM_STACK : PlayerAction.DROP_ITEM, + BlockUtils.POSITION_ZERO, + BlockFace.DOWN + ); + session.sendDownstreamPacket(dropAllPacket); + + if (dropAll) { + session.getPlayerInventory().setItemInHand(GeyserItemStack.EMPTY); + } else { + session.getPlayerInventory().getItemInHand().sub(1); + } + } + } + break; + case INVENTORY_MISMATCH: + break; + case ITEM_USE: + switch (packet.getActionType()) { + case 0: + // Check to make sure the client isn't spamming interaction + // Based on Nukkit 1.0, with changes to ensure holding down still works + boolean hasAlreadyClicked = System.currentTimeMillis() - session.getLastInteractionTime() < 110.0 && + packet.getBlockPosition().distanceSquared(session.getLastInteractionBlockPosition()) < 0.00001; + session.setLastInteractionBlockPosition(packet.getBlockPosition()); + session.setLastInteractionPlayerPosition(session.getPlayerEntity().getPosition()); + if (hasAlreadyClicked) { + break; + } else { + // Only update the interaction time if it's valid - that way holding down still works. + session.setLastInteractionTime(System.currentTimeMillis()); + } + + // Bedrock sends block interact code for a Java entity so we send entity code back to Java + if (session.getBlockMappings().isItemFrame(packet.getBlockRuntimeId())) { + Entity itemFrameEntity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition()); + if (itemFrameEntity != null) { + int entityId = (int) itemFrameEntity.getEntityId(); + Vector3f vector = packet.getClickPosition(); + ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket(entityId, + InteractAction.INTERACT, Hand.MAIN_HAND, session.isSneaking()); + ClientPlayerInteractEntityPacket interactAtPacket = new ClientPlayerInteractEntityPacket(entityId, + InteractAction.INTERACT_AT, vector.getX(), vector.getY(), vector.getZ(), Hand.MAIN_HAND, session.isSneaking()); + session.sendDownstreamPacket(interactPacket); + session.sendDownstreamPacket(interactAtPacket); + break; + } + } + + Vector3i blockPos = BlockUtils.getBlockPosition(packet.getBlockPosition(), packet.getBlockFace()); + /* + Checks to ensure that the range will be accepted by the server. + "Not in range" doesn't refer to how far a vanilla client goes (that's a whole other mess), + but how much a server will accept from the client maximum + */ + // CraftBukkit+ check - see https://github.com/PaperMC/Paper/blob/458db6206daae76327a64f4e2a17b67a7e38b426/Spigot-Server-Patches/0532-Move-range-check-for-block-placing-up.patch + Vector3f playerPosition = session.getPlayerEntity().getPosition(); + + // Adjust position for current eye height + switch (session.getPose()) { + case SNEAKING: + playerPosition = playerPosition.sub(0, (EntityType.PLAYER.getOffset() - 1.27f), 0); + break; + case SWIMMING: + case FALL_FLYING: // Elytra + case SPIN_ATTACK: // Trident spin attack + playerPosition = playerPosition.sub(0, (EntityType.PLAYER.getOffset() - 0.4f), 0); + break; + case SLEEPING: + playerPosition = playerPosition.sub(0, (EntityType.PLAYER.getOffset() - 0.2f), 0); + break; + } // else, we don't have to modify the position + + float diffX = playerPosition.getX() - packet.getBlockPosition().getX(); + float diffY = playerPosition.getY() - packet.getBlockPosition().getY(); + float diffZ = playerPosition.getZ() - packet.getBlockPosition().getZ(); + if (((diffX * diffX) + (diffY * diffY) + (diffZ * diffZ)) > + (session.getGameMode().equals(GameMode.CREATIVE) ? CREATIVE_EYE_HEIGHT_PLACE_DISTANCE : SURVIVAL_EYE_HEIGHT_PLACE_DISTANCE)) { + restoreCorrectBlock(session, blockPos, packet); + return; + } + + // Vanilla check + if (!(session.getPlayerEntity().getPosition().sub(0, EntityType.PLAYER.getOffset(), 0) + .distanceSquared(packet.getBlockPosition().toFloat().add(0.5f, 0.5f, 0.5f)) < MAXIMUM_BLOCK_PLACING_DISTANCE)) { + // The client thinks that its blocks have been successfully placed. Restore the server's blocks instead. + restoreCorrectBlock(session, blockPos, packet); + return; + } + /* + Block place checks end - client is good to go + */ + + if (packet.getItemInHand() != null && session.getItemMappings().getSpawnEggIds().contains(packet.getItemInHand().getId())) { + int blockState = session.getConnector().getWorldManager().getBlockAt(session, packet.getBlockPosition()); + if (blockState == BlockStateValues.JAVA_WATER_ID) { + // Otherwise causes multiple mobs to spawn - just send a use item packet + // TODO when we fix mobile bucket rotation, use it for this, too + ClientPlayerUseItemPacket itemPacket = new ClientPlayerUseItemPacket(Hand.MAIN_HAND); + session.sendDownstreamPacket(itemPacket); + break; + } + } + + ClientPlayerPlaceBlockPacket blockPacket = new ClientPlayerPlaceBlockPacket( + new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()), + BlockFace.values()[packet.getBlockFace()], + Hand.MAIN_HAND, + packet.getClickPosition().getX(), packet.getClickPosition().getY(), packet.getClickPosition().getZ(), + false); + session.sendDownstreamPacket(blockPacket); + + if (packet.getItemInHand() != null) { + // Otherwise boats will not be able to be placed in survival and buckets won't work on mobile + if (session.getItemMappings().getBoatIds().contains(packet.getItemInHand().getId())) { + ClientPlayerUseItemPacket itemPacket = new ClientPlayerUseItemPacket(Hand.MAIN_HAND); + session.sendDownstreamPacket(itemPacket); + } else if (session.getItemMappings().getBucketIds().contains(packet.getItemInHand().getId())) { + // Let the server decide if the bucket item should change, not the client, and revert the changes the client made + InventorySlotPacket slotPacket = new InventorySlotPacket(); + slotPacket.setContainerId(ContainerId.INVENTORY); + slotPacket.setSlot(packet.getHotbarSlot()); + slotPacket.setItem(packet.getItemInHand()); + session.sendUpstreamPacket(slotPacket); + // Don't send ClientPlayerUseItemPacket for powder snow buckets + if (packet.getItemInHand().getId() != session.getItemMappings().getStoredItems().powderSnowBucket().getBedrockId()) { + // Special check for crafting tables since clients don't send BLOCK_INTERACT when interacting + int blockState = session.getConnector().getWorldManager().getBlockAt(session, packet.getBlockPosition()); + if (session.isSneaking() || blockState != BlockRegistries.JAVA_IDENTIFIERS.get("minecraft:crafting_table")) { + // Delay the interaction in case the client doesn't intend to actually use the bucket + // See BedrockActionTranslator.java + session.setBucketScheduledFuture(session.scheduleInEventLoop(() -> { + ClientPlayerUseItemPacket itemPacket = new ClientPlayerUseItemPacket(Hand.MAIN_HAND); + session.sendDownstreamPacket(itemPacket); + }, 5, TimeUnit.MILLISECONDS)); + } + } + } + } + + if (packet.getActions().isEmpty()) { + if (session.getOpPermissionLevel() >= 2 && session.getGameMode() == GameMode.CREATIVE) { + // Otherwise insufficient permissions + int blockState = session.getBlockMappings().getJavaBlockState(packet.getBlockRuntimeId()); + String blockName = BlockRegistries.JAVA_IDENTIFIERS.get().getOrDefault(blockState, ""); + // In the future this can be used for structure blocks too, however not all elements + // are available in each GUI + if (blockName.contains("jigsaw")) { + ContainerOpenPacket openPacket = new ContainerOpenPacket(); + openPacket.setBlockPosition(packet.getBlockPosition()); + openPacket.setId((byte) 1); + openPacket.setType(ContainerType.JIGSAW_EDITOR); + openPacket.setUniqueEntityId(-1); + session.sendUpstreamPacket(openPacket); + } + } + } + + ItemMapping handItem = mappings.getMapping(packet.getItemInHand()); + if (handItem.isBlock()) { + session.setLastBlockPlacePosition(blockPos); + session.setLastBlockPlacedId(handItem.getJavaIdentifier()); + } + session.setInteracting(true); + break; + case 1: + if (packet.getActions().size() == 1 && packet.getLegacySlots().size() > 0) { + InventoryActionData actionData = packet.getActions().get(0); + LegacySetItemSlotData slotData = packet.getLegacySlots().get(0); + if (slotData.getContainerId() == 6 && actionData.getToItem().getId() != 0) { + // The player is trying to swap out an armor piece that already has an item in it + // Java Edition does not allow this; let's revert it + session.getInventoryTranslator().updateInventory(session, session.getPlayerInventory()); + } + } + + // Handled when sneaking + if (session.getPlayerInventory().getItemInHand().getJavaId() == mappings.getStoredItems().shield().getJavaId()) { + break; + } + + // Handled in ITEM_USE if the item is not milk + if (packet.getItemInHand() != null) { + if (session.getItemMappings().getBucketIds().contains(packet.getItemInHand().getId()) && + packet.getItemInHand().getId() != session.getItemMappings().getStoredItems().milkBucket().getBedrockId()) { + // Handled in case 0 if the item is not milk + break; + } else if (session.getItemMappings().getSpawnEggIds().contains(packet.getItemInHand().getId())) { + // Handled in case 0 + break; + } + } + + ClientPlayerUseItemPacket useItemPacket = new ClientPlayerUseItemPacket(Hand.MAIN_HAND); + session.sendDownstreamPacket(useItemPacket); + break; + case 2: + int blockState = session.getGameMode() == GameMode.CREATIVE ? + session.getConnector().getWorldManager().getBlockAt(session, packet.getBlockPosition()) : session.getBreakingBlock(); + + session.setLastBlockPlacedId(null); + session.setLastBlockPlacePosition(null); + + // Same deal with vanilla block placing as above. + // This is working out the distance using 3d Pythagoras and the extra value added to the Y is the sneaking height of a java player. + playerPosition = session.getPlayerEntity().getPosition(); + Vector3f floatBlockPosition = packet.getBlockPosition().toFloat(); + diffX = playerPosition.getX() - (floatBlockPosition.getX() + 0.5f); + diffY = (playerPosition.getY() - EntityType.PLAYER.getOffset()) - (floatBlockPosition.getY() + 0.5f) + 1.5f; + diffZ = playerPosition.getZ() - (floatBlockPosition.getZ() + 0.5f); + float distanceSquared = diffX * diffX + diffY * diffY + diffZ * diffZ; + if (distanceSquared > MAXIMUM_BLOCK_DESTROYING_DISTANCE) { + restoreCorrectBlock(session, packet.getBlockPosition(), packet); + return; + } + + LevelEventPacket blockBreakPacket = new LevelEventPacket(); + blockBreakPacket.setType(LevelEventType.PARTICLE_DESTROY_BLOCK); + blockBreakPacket.setPosition(packet.getBlockPosition().toFloat()); + blockBreakPacket.setData(session.getBlockMappings().getBedrockBlockId(blockState)); + session.sendUpstreamPacket(blockBreakPacket); + session.setBreakingBlock(BlockStateValues.JAVA_AIR_ID); + + Entity itemFrameEntity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition()); + if (itemFrameEntity != null) { + ClientPlayerInteractEntityPacket attackPacket = new ClientPlayerInteractEntityPacket((int) itemFrameEntity.getEntityId(), + InteractAction.ATTACK, session.isSneaking()); + session.sendDownstreamPacket(attackPacket); + break; + } + + PlayerAction action = session.getGameMode() == GameMode.CREATIVE ? PlayerAction.START_DIGGING : PlayerAction.FINISH_DIGGING; + Position pos = new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()); + ClientPlayerActionPacket breakPacket = new ClientPlayerActionPacket(action, pos, BlockFace.values()[packet.getBlockFace()]); + session.sendDownstreamPacket(breakPacket); + break; + } + break; + case ITEM_RELEASE: + if (packet.getActionType() == 0) { + // Followed to the Minecraft Protocol specification outlined at wiki.vg + ClientPlayerActionPacket releaseItemPacket = new ClientPlayerActionPacket(PlayerAction.RELEASE_USE_ITEM, BlockUtils.POSITION_ZERO, + BlockFace.DOWN); + session.sendDownstreamPacket(releaseItemPacket); + } + break; + case ITEM_USE_ON_ENTITY: + Entity entity = session.getEntityCache().getEntityByGeyserId(packet.getRuntimeEntityId()); + if (entity == null) + return; + + //https://wiki.vg/Protocol#Interact_Entity + switch (packet.getActionType()) { + case 0: //Interact + if (entity instanceof CommandBlockMinecartEntity) { + // The UI is handled client-side on Java Edition + // Ensure OP permission level and gamemode is appropriate + if (session.getOpPermissionLevel() < 2 || session.getGameMode() != GameMode.CREATIVE) return; + ContainerOpenPacket openPacket = new ContainerOpenPacket(); + openPacket.setBlockPosition(Vector3i.ZERO); + openPacket.setId((byte) 1); + openPacket.setType(ContainerType.COMMAND_BLOCK); + openPacket.setUniqueEntityId(entity.getGeyserId()); + session.sendUpstreamPacket(openPacket); + break; + } + Vector3f vector = packet.getClickPosition().sub(entity.getPosition()); + ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(), + InteractAction.INTERACT, Hand.MAIN_HAND, session.isSneaking()); + ClientPlayerInteractEntityPacket interactAtPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(), + InteractAction.INTERACT_AT, vector.getX(), vector.getY(), vector.getZ(), Hand.MAIN_HAND, session.isSneaking()); + session.sendDownstreamPacket(interactPacket); + session.sendDownstreamPacket(interactAtPacket); + + EntitySoundInteractionHandler.handleEntityInteraction(session, packet.getClickPosition(), entity); + break; + case 1: //Attack + if (entity.getEntityType() == EntityType.ENDER_DRAGON) { + // Redirects the attack to its body entity, this only happens when + // attacking the underbelly of the ender dragon + ClientPlayerInteractEntityPacket attackPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId() + 3, + InteractAction.ATTACK, session.isSneaking()); + session.sendDownstreamPacket(attackPacket); + } else { + ClientPlayerInteractEntityPacket attackPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(), + InteractAction.ATTACK, session.isSneaking()); + session.sendDownstreamPacket(attackPacket); + } + break; + } + break; + } + } + + /** + * Restore the correct block state from the server without updating the chunk cache. + * + * @param session the session of the Bedrock client + * @param blockPos the block position to restore + */ + private void restoreCorrectBlock(GeyserSession session, Vector3i blockPos, InventoryTransactionPacket packet) { + int javaBlockState = session.getConnector().getWorldManager().getBlockAt(session, blockPos); + UpdateBlockPacket updateBlockPacket = new UpdateBlockPacket(); + updateBlockPacket.setDataLayer(0); + updateBlockPacket.setBlockPosition(blockPos); + updateBlockPacket.setRuntimeId(session.getBlockMappings().getBedrockBlockId(javaBlockState)); + updateBlockPacket.getFlags().addAll(UpdateBlockPacket.FLAG_ALL_PRIORITY); + session.sendUpstreamPacket(updateBlockPacket); + + UpdateBlockPacket updateWaterPacket = new UpdateBlockPacket(); + updateWaterPacket.setDataLayer(1); + updateWaterPacket.setBlockPosition(blockPos); + updateWaterPacket.setRuntimeId(BlockRegistries.WATERLOGGED.get().contains(javaBlockState) ? session.getBlockMappings().getBedrockWaterId() : session.getBlockMappings().getBedrockAirId()); + updateWaterPacket.getFlags().addAll(UpdateBlockPacket.FLAG_ALL_PRIORITY); + session.sendUpstreamPacket(updateWaterPacket); + + // Reset the item in hand to prevent "missing" blocks + InventorySlotPacket slotPacket = new InventorySlotPacket(); + slotPacket.setContainerId(ContainerId.INVENTORY); + slotPacket.setSlot(packet.getHotbarSlot()); + slotPacket.setItem(packet.getItemInHand()); + session.sendUpstreamPacket(slotPacket); + } +} diff --git a/Java/BedrockItemFrameDropItemTranslator.java b/Java/BedrockItemFrameDropItemTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..7a71927eb7f0b588570f00a9196e02209f63d4a9 --- /dev/null +++ b/Java/BedrockItemFrameDropItemTranslator.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.data.game.entity.player.Hand; +import com.github.steveice10.mc.protocol.data.game.entity.player.InteractAction; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerInteractEntityPacket; +import com.nukkitx.protocol.bedrock.packet.ItemFrameDropItemPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.ItemFrameEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +/** + * Pre-1.16.210: used for both survival and creative item frame item removal + * + * 1.16.210: only used in creative. + */ +@Translator(packet = ItemFrameDropItemPacket.class) +public class BedrockItemFrameDropItemTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(ItemFrameDropItemPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, ItemFrameDropItemPacket packet) { + Entity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition()); + if (entity != null) { + ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(), + InteractAction.ATTACK, Hand.MAIN_HAND, session.isSneaking()); + session.sendDownstreamPacket(interactPacket); + } + } +} diff --git a/Java/BedrockItemStackRequestTranslator.java b/Java/BedrockItemStackRequestTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..698685987bfeda7c468a755d5268978b4522691a --- /dev/null +++ b/Java/BedrockItemStackRequestTranslator.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.nukkitx.protocol.bedrock.packet.ItemStackRequestPacket; +import org.geysermc.connector.inventory.Inventory; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.inventory.InventoryTranslator; + +/** + * The packet sent for server-authoritative-style inventory transactions. + */ +@Translator(packet = ItemStackRequestPacket.class) +public class BedrockItemStackRequestTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(ItemStackRequestPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, ItemStackRequestPacket packet) { + Inventory inventory = session.getOpenInventory(); + if (inventory == null) + return; + + InventoryTranslator translator = session.getInventoryTranslator(); + translator.translateRequests(session, inventory, packet.getRequests()); + } +} diff --git a/Java/BedrockLecternUpdateTranslator.java b/Java/BedrockLecternUpdateTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..d65e451f1ecb0a27cb68276073a331c60de1ab3d --- /dev/null +++ b/Java/BedrockLecternUpdateTranslator.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position; +import com.github.steveice10.mc.protocol.data.game.entity.player.Hand; +import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPlaceBlockPacket; +import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientClickWindowButtonPacket; +import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientCloseWindowPacket; +import com.nukkitx.protocol.bedrock.packet.LecternUpdatePacket; +import org.geysermc.connector.inventory.LecternContainer; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.InventoryUtils; + +/** + * Used to translate moving pages, or closing the inventory + */ +@Translator(packet = LecternUpdatePacket.class) +public class BedrockLecternUpdateTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(LecternUpdatePacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, LecternUpdatePacket packet) { + if (packet.isDroppingBook()) { + // Bedrock drops the book outside of the GUI. Java drops it in the GUI + // So, we enter the GUI and then drop it! :) + session.setDroppingLecternBook(true); + + // Emulate an interact packet + ClientPlayerPlaceBlockPacket blockPacket = new ClientPlayerPlaceBlockPacket( + new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()), + BlockFace.DOWN, + Hand.MAIN_HAND, + 0, 0, 0, // Java doesn't care about these when dealing with a lectern + false); + session.sendDownstreamPacket(blockPacket); + } else { + // Bedrock wants to either move a page or exit + if (!(session.getOpenInventory() instanceof LecternContainer)) { + session.getConnector().getLogger().debug("Expected lectern but it wasn't open!"); + return; + } + + LecternContainer lecternContainer = (LecternContainer) session.getOpenInventory(); + if (lecternContainer.getCurrentBedrockPage() == packet.getPage()) { + // The same page means Bedrock is closing the window + ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(lecternContainer.getId()); + session.sendDownstreamPacket(closeWindowPacket); + InventoryUtils.closeInventory(session, lecternContainer.getId(), false); + } else { + // Each "page" Bedrock gives to us actually represents two pages (think opening a book and seeing two pages) + // Each "page" on Java is just one page (think a spiral notebook folded back to only show one page) + int newJavaPage = (packet.getPage() * 2); + int currentJavaPage = (lecternContainer.getCurrentBedrockPage() * 2); + + // Send as many click button packets as we need to + // Java has the option to specify exact page numbers by adding 100 to the number, but buttonId variable + // is a byte when transmitted over the network and therefore this stops us at 128 + if (newJavaPage > currentJavaPage) { + for (int i = currentJavaPage; i < newJavaPage; i++) { + ClientClickWindowButtonPacket clickButtonPacket = new ClientClickWindowButtonPacket(session.getOpenInventory().getId(), 2); + session.sendDownstreamPacket(clickButtonPacket); + } + } else { + for (int i = currentJavaPage; i > newJavaPage; i--) { + ClientClickWindowButtonPacket clickButtonPacket = new ClientClickWindowButtonPacket(session.getOpenInventory().getId(), 1); + session.sendDownstreamPacket(clickButtonPacket); + } + } + } + } + } +} diff --git a/Java/BedrockMapInfoRequestTranslator.java b/Java/BedrockMapInfoRequestTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..30c89b34a30f8d3b9e07f62e3ca2810fdd69f51a --- /dev/null +++ b/Java/BedrockMapInfoRequestTranslator.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.nukkitx.protocol.bedrock.packet.ClientboundMapItemDataPacket; +import com.nukkitx.protocol.bedrock.packet.MapInfoRequestPacket; +import org.geysermc.connector.GeyserConnector; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import java.util.concurrent.TimeUnit; + +@Translator(packet = MapInfoRequestPacket.class) +public class BedrockMapInfoRequestTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(MapInfoRequestPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, MapInfoRequestPacket packet) { + long mapId = packet.getUniqueMapId(); + + ClientboundMapItemDataPacket mapPacket = session.getStoredMaps().remove(mapId); + if (mapPacket != null) { + // Delay the packet 100ms to prevent the client from ignoring the packet + GeyserConnector.getInstance().getGeneralThreadPool().schedule(() -> session.sendUpstreamPacket(mapPacket), + 100, TimeUnit.MILLISECONDS); + } + } +} diff --git a/Java/BedrockMobEquipmentTranslator.java b/Java/BedrockMobEquipmentTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..1a581301914f4c69b87f1434b68a266d69aa6de0 --- /dev/null +++ b/Java/BedrockMobEquipmentTranslator.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.data.game.entity.player.Hand; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerChangeHeldItemPacket; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerUseItemPacket; +import com.nukkitx.protocol.bedrock.data.inventory.ContainerId; +import com.nukkitx.protocol.bedrock.packet.MobEquipmentPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.CooldownUtils; +import org.geysermc.connector.utils.InteractiveTagManager; + +import java.util.concurrent.TimeUnit; + +@Translator(packet = MobEquipmentPacket.class) +public class BedrockMobEquipmentTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(MobEquipmentPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, MobEquipmentPacket packet) { + if (!session.isSpawned() || packet.getHotbarSlot() > 8 || + packet.getContainerId() != ContainerId.INVENTORY || session.getPlayerInventory().getHeldItemSlot() == packet.getHotbarSlot()) { + // For the last condition - Don't update the slot if the slot is the same - not Java Edition behavior and messes with plugins such as Grief Prevention + return; + } + + // Send book update before switching hotbar slot + session.getBookEditCache().checkForSend(); + + session.getPlayerInventory().setHeldItemSlot(packet.getHotbarSlot()); + + ClientPlayerChangeHeldItemPacket changeHeldItemPacket = new ClientPlayerChangeHeldItemPacket(packet.getHotbarSlot()); + session.sendDownstreamPacket(changeHeldItemPacket); + + if (session.isSneaking() && session.getPlayerInventory().getItemInHand().getJavaId() == session.getItemMappings().getStoredItems().shield().getJavaId()) { + // Activate shield since we are already sneaking + // (No need to send a release item packet - Java doesn't do this when swapping items) + // Required to do it a tick later or else it doesn't register + session.getConnector().getGeneralThreadPool().schedule(() -> session.sendDownstreamPacket(new ClientPlayerUseItemPacket(Hand.MAIN_HAND)), + 50, TimeUnit.MILLISECONDS); + } + + // Java sends a cooldown indicator whenever you switch an item + CooldownUtils.sendCooldown(session); + + // Update the interactive tag, if an entity is present + if (session.getMouseoverEntity() != null) { + InteractiveTagManager.updateTag(session, session.getMouseoverEntity()); + } + } +} diff --git a/Java/BedrockMoveEntityAbsoluteTranslator.java b/Java/BedrockMoveEntityAbsoluteTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..1c13df69f1e5c04c612110471e38e4fc22e1d740 --- /dev/null +++ b/Java/BedrockMoveEntityAbsoluteTranslator.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientVehicleMovePacket; +import com.nukkitx.protocol.bedrock.packet.MoveEntityAbsolutePacket; +import org.geysermc.connector.entity.BoatEntity; +import org.geysermc.connector.entity.type.EntityType; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +/** + * Sent by the client when moving a horse. + */ +@Translator(packet = MoveEntityAbsolutePacket.class) +public class BedrockMoveEntityAbsoluteTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(MoveEntityAbsolutePacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, MoveEntityAbsolutePacket packet) { + session.setLastVehicleMoveTimestamp(System.currentTimeMillis()); + + float y = packet.getPosition().getY(); + if (session.getRidingVehicleEntity() instanceof BoatEntity) { + // Remove the offset to prevents boats from looking like they're floating in water + y -= EntityType.BOAT.getOffset(); + } + ClientVehicleMovePacket clientVehicleMovePacket = new ClientVehicleMovePacket( + packet.getPosition().getX(), y, packet.getPosition().getZ(), + packet.getRotation().getY() - 90, packet.getRotation().getX() + ); + session.sendDownstreamPacket(clientVehicleMovePacket); + } +} diff --git a/Java/BedrockMovePlayerTranslator.java b/Java/BedrockMovePlayerTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..28da5ef9c796e6736ac0cd9935137c788a44050a --- /dev/null +++ b/Java/BedrockMovePlayerTranslator.java @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock.entity.player; + +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionPacket; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionRotationPacket; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerRotationPacket; +import com.github.steveice10.packetlib.packet.Packet; +import com.nukkitx.math.vector.Vector3d; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.protocol.bedrock.packet.MoveEntityAbsolutePacket; +import com.nukkitx.protocol.bedrock.packet.MovePlayerPacket; +import org.geysermc.connector.GeyserConnector; +import org.geysermc.connector.common.ChatColor; +import org.geysermc.connector.entity.player.SessionPlayerEntity; +import org.geysermc.connector.entity.type.EntityType; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = MovePlayerPacket.class) +public class BedrockMovePlayerTranslator extends PacketTranslator { + /* The upper and lower bounds to check for the void floor that only exists in Bedrock */ + private static final int BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y; + private static final int BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y; + + static { + BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y = GeyserConnector.getInstance().getConfig().isExtendedWorldHeight() ? -104 : -40; + BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y = BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y + 2; + } + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(MovePlayerPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, MovePlayerPacket packet) { + SessionPlayerEntity entity = session.getPlayerEntity(); + if (!session.isSpawned()) return; + + if (!session.getUpstream().isInitialized()) { + MoveEntityAbsolutePacket moveEntityBack = new MoveEntityAbsolutePacket(); + moveEntityBack.setRuntimeEntityId(entity.getGeyserId()); + moveEntityBack.setPosition(entity.getPosition()); + moveEntityBack.setRotation(entity.getBedrockRotation()); + moveEntityBack.setTeleported(true); + moveEntityBack.setOnGround(true); + session.sendUpstreamPacketImmediately(moveEntityBack); + return; + } + + session.setLastMovementTimestamp(System.currentTimeMillis()); + + // Send book update before the player moves + session.getBookEditCache().checkForSend(); + + session.confirmTeleport(packet.getPosition().toDouble().sub(0, EntityType.PLAYER.getOffset(), 0)); + // head yaw, pitch, head yaw + Vector3f rotation = Vector3f.from(packet.getRotation().getY(), packet.getRotation().getX(), packet.getRotation().getY()); + + boolean positionChanged = !entity.getPosition().equals(packet.getPosition()); + boolean rotationChanged = !entity.getRotation().equals(rotation); + + // If only the pitch and yaw changed + // This isn't needed, but it makes the packets closer to vanilla + // It also means you can't "lag back" while only looking, in theory + if (!positionChanged && rotationChanged) { + ClientPlayerRotationPacket playerRotationPacket = new ClientPlayerRotationPacket( + packet.isOnGround(), packet.getRotation().getY(), packet.getRotation().getX()); + + entity.setRotation(rotation); + entity.setOnGround(packet.isOnGround()); + + session.sendDownstreamPacket(playerRotationPacket); + } else { + Vector3d position = session.getCollisionManager().adjustBedrockPosition(packet.getPosition(), packet.isOnGround()); + if (position != null) { // A null return value cancels the packet + if (isValidMove(session, packet.getMode(), entity.getPosition(), packet.getPosition())) { + Packet movePacket; + if (rotationChanged) { + // Send rotation updates as well + movePacket = new ClientPlayerPositionRotationPacket(packet.isOnGround(), position.getX(), position.getY(), position.getZ(), + packet.getRotation().getY(), packet.getRotation().getX()); + entity.setRotation(rotation); + } else { + // Rotation did not change; don't send an update with rotation + movePacket = new ClientPlayerPositionPacket(packet.isOnGround(), position.getX(), position.getY(), position.getZ()); + } + + // Compare positions here for void floor fix below before the player's position variable is set to the packet position + boolean notMovingUp = entity.getPosition().getY() >= packet.getPosition().getY(); + + entity.setPositionManual(packet.getPosition()); + entity.setOnGround(packet.isOnGround()); + + // Send final movement changes + session.sendDownstreamPacket(movePacket); + + if (notMovingUp) { + int floorY = position.getFloorY(); + // If the client believes the world has extended height, then it also believes the void floor + // still exists, just at a lower spot + boolean extendedWorld = session.getChunkCache().isExtendedHeight(); + if (floorY <= (extendedWorld ? BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y : -38) + && floorY >= (extendedWorld ? BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y : -40)) { + // Work around there being a floor at the bottom of the world and teleport the player below it + // Moving from below to above the void floor works fine + entity.setPosition(entity.getPosition().sub(0, 4f, 0)); + MovePlayerPacket movePlayerPacket = new MovePlayerPacket(); + movePlayerPacket.setRuntimeEntityId(entity.getGeyserId()); + movePlayerPacket.setPosition(entity.getPosition()); + movePlayerPacket.setRotation(entity.getBedrockRotation()); + movePlayerPacket.setMode(MovePlayerPacket.Mode.TELEPORT); + movePlayerPacket.setTeleportationCause(MovePlayerPacket.TeleportationCause.BEHAVIOR); + session.sendUpstreamPacket(movePlayerPacket); + } + } + } else { + // Not a valid move + session.getConnector().getLogger().debug("Recalculating position..."); + session.getCollisionManager().recalculatePosition(); + } + } + } + + // Move parrots to match if applicable + if (entity.getLeftParrot() != null) { + entity.getLeftParrot().moveAbsolute(session, entity.getPosition(), entity.getRotation(), true, false); + } + if (entity.getRightParrot() != null) { + entity.getRightParrot().moveAbsolute(session, entity.getPosition(), entity.getRotation(), true, false); + } + } + + private boolean isValidMove(GeyserSession session, MovePlayerPacket.Mode mode, Vector3f currentPosition, Vector3f newPosition) { + if (mode != MovePlayerPacket.Mode.NORMAL) + return true; + + double xRange = newPosition.getX() - currentPosition.getX(); + double yRange = newPosition.getY() - currentPosition.getY(); + double zRange = newPosition.getZ() - currentPosition.getZ(); + + if (xRange < 0) + xRange = -xRange; + if (yRange < 0) + yRange = -yRange; + if (zRange < 0) + zRange = -zRange; + + if ((xRange + yRange + zRange) > 100) { + session.getConnector().getLogger().debug(ChatColor.RED + session.getName() + " moved too quickly." + + " current position: " + currentPosition + ", new position: " + newPosition); + + return false; + } + + return true; + } +} + diff --git a/Java/BedrockNetworkStackLatencyTranslator.java b/Java/BedrockNetworkStackLatencyTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..f133191823040db6a8dd4e750c9b9d9e93dc2528 --- /dev/null +++ b/Java/BedrockNetworkStackLatencyTranslator.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.packet.ingame.client.ClientKeepAlivePacket; +import com.nukkitx.protocol.bedrock.data.AttributeData; +import com.nukkitx.protocol.bedrock.packet.NetworkStackLatencyPacket; +import com.nukkitx.protocol.bedrock.packet.UpdateAttributesPacket; +import org.geysermc.connector.entity.attribute.GeyserAttributeType; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.floodgate.util.DeviceOs; + +import java.util.Collections; +import java.util.concurrent.TimeUnit; + +/** + * Used to send the forwarded keep alive packet back to the server + */ +@Translator(packet = NetworkStackLatencyPacket.class) +public class BedrockNetworkStackLatencyTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(NetworkStackLatencyPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, NetworkStackLatencyPacket packet) { + long pingId; + // so apparently, as of 1.16.200 + // PS4 divides the network stack latency timestamp FOR US!!! + // WTF + if (session.getClientData().getDeviceOs().equals(DeviceOs.PS4)) { + pingId = packet.getTimestamp(); + } else { + pingId = packet.getTimestamp() / 1000; + } + + // negative timestamps are used as hack to fix the url image loading bug + if (packet.getTimestamp() > 0) { + if (session.getConnector().getConfig().isForwardPlayerPing()) { + ClientKeepAlivePacket keepAlivePacket = new ClientKeepAlivePacket(pingId); + session.sendDownstreamPacket(keepAlivePacket); + } + return; + } + + // Hack to fix the url image loading bug + UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket(); + attributesPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId()); + + AttributeData attribute = session.getPlayerEntity().getAttributes().get(GeyserAttributeType.EXPERIENCE_LEVEL); + if (attribute != null) { + attributesPacket.setAttributes(Collections.singletonList(attribute)); + } else { + attributesPacket.setAttributes(Collections.singletonList(GeyserAttributeType.EXPERIENCE_LEVEL.getAttribute(0))); + } + + session.getConnector().getGeneralThreadPool().schedule( + () -> session.sendUpstreamPacket(attributesPacket), + 500, TimeUnit.MILLISECONDS); + } +} diff --git a/Java/BedrockPacketViolationWarningTranslator.java b/Java/BedrockPacketViolationWarningTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..a8f941171d607a083509a5f39fc86cbb1f3df547 --- /dev/null +++ b/Java/BedrockPacketViolationWarningTranslator.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.nukkitx.protocol.bedrock.packet.PacketViolationWarningPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = PacketViolationWarningPacket.class) +public class BedrockPacketViolationWarningTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(PacketViolationWarningPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, PacketViolationWarningPacket packet) { + // Not translated since this is something that the developers need to know + session.getConnector().getLogger().error("Packet violation warning sent from client! " + packet.toString()); + } +} diff --git a/Java/BedrockPlayerInputTranslator.java b/Java/BedrockPlayerInputTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..fa28a90465beef0a4ac4cbe892e604274d1996de --- /dev/null +++ b/Java/BedrockPlayerInputTranslator.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientSteerVehiclePacket; +import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientVehicleMovePacket; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.protocol.bedrock.data.entity.EntityData; +import com.nukkitx.protocol.bedrock.packet.PlayerInputPacket; +import org.geysermc.connector.entity.BoatEntity; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity; +import org.geysermc.connector.entity.living.animal.horse.LlamaEntity; +import org.geysermc.connector.entity.type.EntityType; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +/** + * Sent by the client for minecarts and boats. + */ +@Translator(packet = PlayerInputPacket.class) +public class BedrockPlayerInputTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(PlayerInputPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, PlayerInputPacket packet) { + ClientSteerVehiclePacket clientSteerVehiclePacket = new ClientSteerVehiclePacket( + packet.getInputMotion().getX(), packet.getInputMotion().getY(), packet.isJumping(), packet.isSneaking() + ); + + session.sendDownstreamPacket(clientSteerVehiclePacket); + + // Bedrock only sends movement vehicle packets while moving + // This allows horses to take damage while standing on magma + Entity vehicle = session.getRidingVehicleEntity(); + boolean sendMovement = false; + if (vehicle instanceof AbstractHorseEntity && !(vehicle instanceof LlamaEntity)) { + sendMovement = vehicle.isOnGround(); + } else if (vehicle instanceof BoatEntity) { + if (vehicle.getPassengers().size() == 1) { + // The player is the only rider + sendMovement = true; + } else { + // Check if the player is the front rider + Vector3f seatPos = session.getPlayerEntity().getMetadata().getVector3f(EntityData.RIDER_SEAT_POSITION, null); + if (seatPos != null && seatPos.getX() > 0) { + sendMovement = true; + } + } + } + if (sendMovement) { + long timeSinceVehicleMove = System.currentTimeMillis() - session.getLastVehicleMoveTimestamp(); + if (timeSinceVehicleMove >= 100) { + Vector3f vehiclePosition = vehicle.getPosition(); + Vector3f vehicleRotation = vehicle.getRotation(); + + if (vehicle instanceof BoatEntity) { + // Remove some Y position to prevents boats flying up + vehiclePosition = vehiclePosition.down(EntityType.BOAT.getOffset()); + } + + ClientVehicleMovePacket clientVehicleMovePacket = new ClientVehicleMovePacket( + vehiclePosition.getX(), vehiclePosition.getY(), vehiclePosition.getZ(), + vehicleRotation.getX() - 90, vehicleRotation.getY() + ); + session.sendDownstreamPacket(clientVehicleMovePacket); + } + } + } +} diff --git a/Java/BedrockPositionTrackingDBClientRequestTranslator.java b/Java/BedrockPositionTrackingDBClientRequestTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..31c168828d67607d7c46749bf78f92fa0901d14e --- /dev/null +++ b/Java/BedrockPositionTrackingDBClientRequestTranslator.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.nukkitx.nbt.NbtMap; +import com.nukkitx.nbt.NbtMapBuilder; +import com.nukkitx.nbt.NbtType; +import com.nukkitx.protocol.bedrock.packet.PositionTrackingDBClientRequestPacket; +import com.nukkitx.protocol.bedrock.packet.PositionTrackingDBServerBroadcastPacket; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntList; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.DimensionUtils; +import org.geysermc.connector.utils.LoadstoneTracker; + +@Translator(packet = PositionTrackingDBClientRequestPacket.class) +public class BedrockPositionTrackingDBClientRequestTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(PositionTrackingDBClientRequestPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, PositionTrackingDBClientRequestPacket packet) { + PositionTrackingDBServerBroadcastPacket broadcastPacket = new PositionTrackingDBServerBroadcastPacket(); + broadcastPacket.setTrackingId(packet.getTrackingId()); + + // Fetch the stored Loadstone + LoadstoneTracker.LoadstonePos pos = LoadstoneTracker.getPos(packet.getTrackingId()); + + // If we don't have data for that ID tell the client its not found + if (pos == null) { + broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.NOT_FOUND); + session.sendUpstreamPacket(broadcastPacket); + return; + } + + broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.UPDATE); + + // Build the nbt data for the update + NbtMapBuilder builder = NbtMap.builder(); + builder.putInt("dim", DimensionUtils.javaToBedrock(pos.getDimension())); + builder.putString("id", String.format("%08X", packet.getTrackingId())); + + builder.putByte("version", (byte) 1); // Not sure what this is for + builder.putByte("status", (byte) 0); // Not sure what this is for + + // Build the position for the update + IntList posList = new IntArrayList(); + posList.add(pos.getX()); + posList.add(pos.getY()); + posList.add(pos.getZ()); + builder.putList("pos", NbtType.INT, posList); + broadcastPacket.setTag(builder.build()); + + session.sendUpstreamPacket(broadcastPacket); + } +} diff --git a/Java/BedrockRespawnTranslator.java b/Java/BedrockRespawnTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..2cbc81aeb94b2b035b9cdbee2a8b4f652b02e915 --- /dev/null +++ b/Java/BedrockRespawnTranslator.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.github.steveice10.mc.protocol.data.game.ClientRequest; +import com.github.steveice10.mc.protocol.packet.ingame.client.ClientRequestPacket; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.protocol.bedrock.packet.MovePlayerPacket; +import com.nukkitx.protocol.bedrock.packet.RespawnPacket; +import com.nukkitx.protocol.bedrock.packet.SetEntityDataPacket; +import org.geysermc.connector.entity.player.PlayerEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = RespawnPacket.class) +public class BedrockRespawnTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(RespawnPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, RespawnPacket packet) { + if (packet.getState() == RespawnPacket.State.CLIENT_READY) { + // Previously we only sent the respawn packet before the server finished loading + // The message included was 'Otherwise when immediate respawn is on the client never loads' + // But I assume the new if statement below fixes that problem + RespawnPacket respawnPacket = new RespawnPacket(); + respawnPacket.setRuntimeEntityId(0); + respawnPacket.setPosition(Vector3f.ZERO); + respawnPacket.setState(RespawnPacket.State.SERVER_READY); + session.sendUpstreamPacket(respawnPacket); + + if (session.isSpawned()) { + // Client might be stuck; resend spawn information + PlayerEntity entity = session.getPlayerEntity(); + if (entity == null) return; + SetEntityDataPacket entityDataPacket = new SetEntityDataPacket(); + entityDataPacket.setRuntimeEntityId(entity.getGeyserId()); + entityDataPacket.getMetadata().putAll(entity.getMetadata()); + session.sendUpstreamPacket(entityDataPacket); + + MovePlayerPacket movePlayerPacket = new MovePlayerPacket(); + movePlayerPacket.setRuntimeEntityId(entity.getGeyserId()); + movePlayerPacket.setPosition(entity.getPosition()); + movePlayerPacket.setRotation(entity.getBedrockRotation()); + movePlayerPacket.setMode(MovePlayerPacket.Mode.RESPAWN); + session.sendUpstreamPacket(movePlayerPacket); + } + + ClientRequestPacket javaRespawnPacket = new ClientRequestPacket(ClientRequest.RESPAWN); + session.sendDownstreamPacket(javaRespawnPacket); + } + } +} diff --git a/Java/BedrockRiderJumpTranslator.java b/Java/BedrockRiderJumpTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..06779cb442c29586d78a2724b04065fc8af30d98 --- /dev/null +++ b/Java/BedrockRiderJumpTranslator.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock.entity.player; + +import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerState; +import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerStatePacket; +import com.nukkitx.protocol.bedrock.packet.RiderJumpPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = RiderJumpPacket.class) +public class BedrockRiderJumpTranslator extends PacketTranslator { + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(RiderJumpPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, RiderJumpPacket packet) { + Entity vehicle = session.getRidingVehicleEntity(); + if (vehicle instanceof AbstractHorseEntity) { + ClientPlayerStatePacket playerStatePacket = new ClientPlayerStatePacket((int) vehicle.getEntityId(), PlayerState.START_HORSE_JUMP, packet.getJumpStrength()); + session.sendDownstreamPacket(playerStatePacket); + } + } +} diff --git a/Java/BedrockServerSettingsRequestTranslator.java b/Java/BedrockServerSettingsRequestTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..3251b4a60b76e20d6f5d4b1bee85c9f2929bcfd2 --- /dev/null +++ b/Java/BedrockServerSettingsRequestTranslator.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.nukkitx.protocol.bedrock.packet.ServerSettingsRequestPacket; +import com.nukkitx.protocol.bedrock.packet.ServerSettingsResponsePacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.SettingsUtils; +import org.geysermc.cumulus.CustomForm; + +import java.util.concurrent.TimeUnit; + +@Translator(packet = ServerSettingsRequestPacket.class) +public class BedrockServerSettingsRequestTranslator extends PacketTranslator { + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(ServerSettingsRequestPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, ServerSettingsRequestPacket packet) { + CustomForm window = SettingsUtils.buildForm(session); + int windowId = session.getFormCache().addForm(window); + + // Fixes https://bugs.mojang.com/browse/MCPE-94012 because of the delay + session.getConnector().getGeneralThreadPool().schedule(() -> { + ServerSettingsResponsePacket serverSettingsResponsePacket = new ServerSettingsResponsePacket(); + serverSettingsResponsePacket.setFormData(window.getJsonData()); + serverSettingsResponsePacket.setFormId(windowId); + session.sendUpstreamPacket(serverSettingsResponsePacket); + }, 1, TimeUnit.SECONDS); + } +} diff --git a/Java/BedrockSetLocalPlayerAsInitializedTranslator.java b/Java/BedrockSetLocalPlayerAsInitializedTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..bfe05d10f68947ddda6b99fdd2c4ad97d9876921 --- /dev/null +++ b/Java/BedrockSetLocalPlayerAsInitializedTranslator.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import com.nukkitx.protocol.bedrock.data.entity.EntityFlag; +import com.nukkitx.protocol.bedrock.packet.SetLocalPlayerAsInitializedPacket; +import org.geysermc.connector.entity.player.PlayerEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.skin.SkinManager; +import org.geysermc.connector.skin.SkullSkinManager; + +@Translator(packet = SetLocalPlayerAsInitializedPacket.class) +public class BedrockSetLocalPlayerAsInitializedTranslator extends PacketTranslator { + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(SetLocalPlayerAsInitializedPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, SetLocalPlayerAsInitializedPacket packet) { + if (session.getPlayerEntity().getGeyserId() == packet.getRuntimeEntityId()) { + if (!session.getUpstream().isInitialized()) { + session.getUpstream().setInitialized(true); + session.login(); + + for (PlayerEntity entity : session.getEntityCache().getEntitiesByType(PlayerEntity.class)) { + if (!entity.isValid()) { + SkinManager.requestAndHandleSkinAndCape(entity, session, null); + entity.sendPlayer(session); + } + } + + // Send Skulls + for (PlayerEntity entity : session.getSkullCache().values()) { + entity.spawnEntity(session); + + SkullSkinManager.requestAndHandleSkin(entity, session, (skin) -> { + entity.getMetadata().getFlags().setFlag(EntityFlag.INVISIBLE, false); + entity.updateBedrockMetadata(session); + }); + } + } + } + } +} diff --git a/Java/BedrockSetPlayerGameTypeTranslator.java b/Java/BedrockSetPlayerGameTypeTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..99b0e8829e20319c328b1e4070c9046596dad1c9 --- /dev/null +++ b/Java/BedrockSetPlayerGameTypeTranslator.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock.entity.player; + +import com.nukkitx.protocol.bedrock.packet.SetPlayerGameTypePacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +/** + * In vanilla Bedrock, if you have operator status, this sets the player's gamemode without confirmation from the server. + * Since we have a custom server option to request the gamemode, we just reset the gamemode and ignore this. + */ +@Translator(packet = SetPlayerGameTypePacket.class) +public class BedrockSetPlayerGameTypeTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(SetPlayerGameTypePacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, SetPlayerGameTypePacket packet) { + // no + SetPlayerGameTypePacket playerGameTypePacket = new SetPlayerGameTypePacket(); + playerGameTypePacket.setGamemode(session.getGameMode().ordinal()); + session.sendUpstreamPacket(playerGameTypePacket); + } +} diff --git a/Java/BedrockShowCreditsTranslator.java b/Java/BedrockShowCreditsTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..e366bac3d6e32c2bf3ef7d33591715a1518b8571 --- /dev/null +++ b/Java/BedrockShowCreditsTranslator.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import com.github.steveice10.mc.protocol.data.game.ClientRequest; +import com.github.steveice10.mc.protocol.packet.ingame.client.ClientRequestPacket; +import com.nukkitx.protocol.bedrock.packet.ShowCreditsPacket; + +@Translator(packet = ShowCreditsPacket.class) +public class BedrockShowCreditsTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(ShowCreditsPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, ShowCreditsPacket packet) { + if (packet.getStatus() == ShowCreditsPacket.Status.END_CREDITS) { + ClientRequestPacket javaRespawnPacket = new ClientRequestPacket(ClientRequest.RESPAWN); + session.sendDownstreamPacket(javaRespawnPacket); + } + } +} diff --git a/Java/BedrockTextTranslator.java b/Java/BedrockTextTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..a3749cafd1220d15619c1537886560ad81a85890 --- /dev/null +++ b/Java/BedrockTextTranslator.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.bedrock; + +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import com.github.steveice10.mc.protocol.packet.ingame.client.ClientChatPacket; +import com.nukkitx.protocol.bedrock.packet.TextPacket; +import org.geysermc.connector.network.translators.chat.MessageTranslator; + +@Translator(packet = TextPacket.class) +public class BedrockTextTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(TextPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, TextPacket packet) { + String message = packet.getMessage(); + + if (MessageTranslator.isTooLong(message, session)) { + return; + } + + ClientChatPacket chatPacket = new ClientChatPacket(message); + session.sendDownstreamPacket(chatPacket); + } +} diff --git a/Java/BlogEntryMediaController.java b/Java/BlogEntryMediaController.java new file mode 100644 index 0000000000000000000000000000000000000000..40a6d789bac5f8aa7f119711a3419df963cdfe17 --- /dev/null +++ b/Java/BlogEntryMediaController.java @@ -0,0 +1,147 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ + +package org.olat.modules.webFeed.portfolio; + +import java.io.InputStream; + +import org.olat.core.gui.UserRequest; +import org.olat.core.gui.components.Component; +import org.olat.core.gui.components.date.DateComponentFactory; +import org.olat.core.gui.components.velocity.VelocityContainer; +import org.olat.core.gui.control.Event; +import org.olat.core.gui.control.WindowControl; +import org.olat.core.gui.control.controller.BasicController; +import org.olat.core.util.StringHelper; +import org.olat.core.util.filter.Filter; +import org.olat.core.util.filter.FilterFactory; +import org.olat.core.util.vfs.VFSContainer; +import org.olat.core.util.vfs.VFSContainerMapper; +import org.olat.core.util.vfs.VFSItem; +import org.olat.core.util.vfs.VFSLeaf; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.modules.portfolio.Media; +import org.olat.modules.portfolio.MediaRenderingHints; +import org.olat.modules.portfolio.manager.PortfolioFileStorage; +import org.olat.modules.portfolio.ui.MediaMetadataController; +import org.olat.modules.webFeed.Item; +import org.olat.modules.webFeed.model.ItemImpl; +import org.springframework.beans.factory.annotation.Autowired; + +import com.thoughtworks.xstream.XStream; + +/** + * + * Description:
+ * Read-only view for a blog entry + * + *

+ * Initial Date: 3 déc. 2010
+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com + */ +public class BlogEntryMediaController extends BasicController { + + private static final XStream xstream = XStreamHelper.createXStreamInstance(); + static { + XStreamHelper.allowDefaultPackage(xstream); + xstream.alias("item", ItemImpl.class); + } + + @Autowired + private PortfolioFileStorage fileStorage; + + public BlogEntryMediaController(UserRequest ureq, WindowControl wControl, Media media, MediaRenderingHints hints) { + super(ureq, wControl); + VelocityContainer mainVC = createVelocityContainer("media_post"); + if (StringHelper.containsNonWhitespace(media.getStoragePath())) { + VFSContainer container = fileStorage.getMediaContainer(media); + VFSItem item = container.resolve(media.getRootFilename()); + if(item instanceof VFSLeaf) { + VFSLeaf itemLeaf = (VFSLeaf)item; + try(InputStream in = itemLeaf.getInputStream()) { + Item blogItem = (ItemImpl)xstream.fromXML(in); + if(blogItem.getDate() != null) { + DateComponentFactory.createDateComponentWithYear("dateComp", blogItem.getDate(), mainVC); + } + + String content = blogItem.getContent(); + if (!StringHelper.containsNonWhitespace(content)) { + content = blogItem.getDescription(); + } + + mainVC.contextPut("content", content); + mainVC.contextPut("readOnlyMode", Boolean.TRUE); + mainVC.contextPut("item", blogItem); + + String mapperBase = registerMapper(ureq, new VFSContainerMapper(container)); + mainVC.contextPut("helper", new ItemHelper(mapperBase)); + + if(hints.isExtendedMetadata()) { + MediaMetadataController metaCtrl = new MediaMetadataController(ureq, wControl, media); + listenTo(metaCtrl); + mainVC.put("meta", metaCtrl.getInitialComponent()); + } + } catch(Exception ex) { + logError("", ex); + } + } + } + putInitialPanel(mainVC); + } + + @Override + protected void doDispose() { + // + } + + @Override + protected void event(UserRequest ureq, Component source, Event event) { + // + } + + public class ItemHelper { + + private final String baseUri; + + public ItemHelper(String baseUri) { + this.baseUri = baseUri; + } + + public String getItemContentForBrowser(Item item) { + String itemContent = item.getContent(); + if (itemContent != null) { + //Add relative media base to media elements to display internal media files + Filter mediaUrlFilter = FilterFactory.getBaseURLToMediaRelativeURLFilter(baseUri); + itemContent = mediaUrlFilter.filter(itemContent); + } + return itemContent; + } + + public String getItemDescriptionForBrowser(Item item) { + String itemDescription = item.getDescription(); + if (itemDescription != null) { + //Add relative media base to media elements to display internal media files + Filter mediaUrlFilter = FilterFactory.getBaseURLToMediaRelativeURLFilter(baseUri); + itemDescription = mediaUrlFilter.filter(itemDescription); + } + return itemDescription; + } + } +} \ No newline at end of file diff --git a/Java/BluetoothSocket.java b/Java/BluetoothSocket.java new file mode 100644 index 0000000000000000000000000000000000000000..2a1b4e864c801d1794ec462016910934013b85e2 --- /dev/null +++ b/Java/BluetoothSocket.java @@ -0,0 +1,594 @@ +/* + * Copyright (C) 2012 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 android.bluetooth; + +import android.os.ParcelUuid; +import android.os.ParcelFileDescriptor; +import android.os.RemoteException; +import android.util.Log; + +import java.io.Closeable; +import java.io.FileDescriptor; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Locale; +import java.util.UUID; +import android.net.LocalSocket; +import java.nio.ByteOrder; +import java.nio.ByteBuffer; +/** + * A connected or connecting Bluetooth socket. + * + *

The interface for Bluetooth Sockets is similar to that of TCP sockets: + * {@link java.net.Socket} and {@link java.net.ServerSocket}. On the server + * side, use a {@link BluetoothServerSocket} to create a listening server + * socket. When a connection is accepted by the {@link BluetoothServerSocket}, + * it will return a new {@link BluetoothSocket} to manage the connection. + * On the client side, use a single {@link BluetoothSocket} to both initiate + * an outgoing connection and to manage the connection. + * + *

The most common type of Bluetooth socket is RFCOMM, which is the type + * supported by the Android APIs. RFCOMM is a connection-oriented, streaming + * transport over Bluetooth. It is also known as the Serial Port Profile (SPP). + * + *

To create a {@link BluetoothSocket} for connecting to a known device, use + * {@link BluetoothDevice#createRfcommSocketToServiceRecord + * BluetoothDevice.createRfcommSocketToServiceRecord()}. + * Then call {@link #connect()} to attempt a connection to the remote device. + * This call will block until a connection is established or the connection + * fails. + * + *

To create a {@link BluetoothSocket} as a server (or "host"), see the + * {@link BluetoothServerSocket} documentation. + * + *

Once the socket is connected, whether initiated as a client or accepted + * as a server, open the IO streams by calling {@link #getInputStream} and + * {@link #getOutputStream} in order to retrieve {@link java.io.InputStream} + * and {@link java.io.OutputStream} objects, respectively, which are + * automatically connected to the socket. + * + *

{@link BluetoothSocket} is thread + * safe. In particular, {@link #close} will always immediately abort ongoing + * operations and close the socket. + * + *

Note: + * Requires the {@link android.Manifest.permission#BLUETOOTH} permission. + * + *

+ *

Developer Guides

+ *

For more information about using Bluetooth, read the + * Bluetooth developer guide.

+ *
+ * + * {@see BluetoothServerSocket} + * {@see java.io.InputStream} + * {@see java.io.OutputStream} + */ +public final class BluetoothSocket implements Closeable { + private static final String TAG = "BluetoothSocket"; + private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG); + private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE); + + /** @hide */ + public static final int MAX_RFCOMM_CHANNEL = 30; + + /** Keep TYPE_ fields in sync with BluetoothSocket.cpp */ + /*package*/ static final int TYPE_RFCOMM = 1; + /*package*/ static final int TYPE_SCO = 2; + /*package*/ static final int TYPE_L2CAP = 3; + + /*package*/ static final int EBADFD = 77; + /*package*/ static final int EADDRINUSE = 98; + + /*package*/ static final int SEC_FLAG_ENCRYPT = 1; + /*package*/ static final int SEC_FLAG_AUTH = 1 << 1; + + private final int mType; /* one of TYPE_RFCOMM etc */ + private BluetoothDevice mDevice; /* remote device */ + private String mAddress; /* remote address */ + private final boolean mAuth; + private final boolean mEncrypt; + private final BluetoothInputStream mInputStream; + private final BluetoothOutputStream mOutputStream; + private final ParcelUuid mUuid; + private ParcelFileDescriptor mPfd; + private LocalSocket mSocket; + private InputStream mSocketIS; + private OutputStream mSocketOS; + private int mPort; /* RFCOMM channel or L2CAP psm */ + private int mFd; + private String mServiceName; + private static int PROXY_CONNECTION_TIMEOUT = 5000; + + private static int SOCK_SIGNAL_SIZE = 16; + + private enum SocketState { + INIT, + CONNECTED, + LISTENING, + CLOSED, + } + + /** prevents all native calls after destroyNative() */ + private volatile SocketState mSocketState; + + /** protects mSocketState */ + //private final ReentrantReadWriteLock mLock; + + /** + * Construct a BluetoothSocket. + * @param type type of socket + * @param fd fd to use for connected socket, or -1 for a new socket + * @param auth require the remote device to be authenticated + * @param encrypt require the connection to be encrypted + * @param device remote device that this socket can connect to + * @param port remote port + * @param uuid SDP uuid + * @throws IOException On error, for example Bluetooth not available, or + * insufficient privileges + */ + /*package*/ BluetoothSocket(int type, int fd, boolean auth, boolean encrypt, + BluetoothDevice device, int port, ParcelUuid uuid) throws IOException { + if (type == BluetoothSocket.TYPE_RFCOMM && uuid == null && fd == -1) { + if (port < 1 || port > MAX_RFCOMM_CHANNEL) { + throw new IOException("Invalid RFCOMM channel: " + port); + } + } + if(uuid != null) + mUuid = uuid; + else mUuid = new ParcelUuid(new UUID(0, 0)); + mType = type; + mAuth = auth; + mEncrypt = encrypt; + mDevice = device; + mPort = port; + mFd = fd; + + mSocketState = SocketState.INIT; + + if (device == null) { + // Server socket + mAddress = BluetoothAdapter.getDefaultAdapter().getAddress(); + } else { + // Remote socket + mAddress = device.getAddress(); + } + mInputStream = new BluetoothInputStream(this); + mOutputStream = new BluetoothOutputStream(this); + } + private BluetoothSocket(BluetoothSocket s) { + mUuid = s.mUuid; + mType = s.mType; + mAuth = s.mAuth; + mEncrypt = s.mEncrypt; + mPort = s.mPort; + mInputStream = new BluetoothInputStream(this); + mOutputStream = new BluetoothOutputStream(this); + mServiceName = s.mServiceName; + } + private BluetoothSocket acceptSocket(String RemoteAddr) throws IOException { + BluetoothSocket as = new BluetoothSocket(this); + as.mSocketState = SocketState.CONNECTED; + FileDescriptor[] fds = mSocket.getAncillaryFileDescriptors(); + if (DBG) Log.d(TAG, "socket fd passed by stack fds: " + fds); + if(fds == null || fds.length != 1) { + Log.e(TAG, "socket fd passed from stack failed, fds: " + fds); + as.close(); + throw new IOException("bt socket acept failed"); + } + as.mSocket = new LocalSocket(fds[0]); + // BUG: NVD-CWE-noinfo Insufficient Information + // + // FIXED: + as.mPfd = new ParcelFileDescriptor(fds[0]); + try { + as.mSocket.closeExternalFd(); + } catch (IOException e) { + Log.e(TAG, "closeExternalFd failed"); + } + as.mSocketIS = as.mSocket.getInputStream(); + as.mSocketOS = as.mSocket.getOutputStream(); + as.mAddress = RemoteAddr; + as.mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(RemoteAddr); + as.mPort = mPort; + return as; + } + /** + * Construct a BluetoothSocket from address. Used by native code. + * @param type type of socket + * @param fd fd to use for connected socket, or -1 for a new socket + * @param auth require the remote device to be authenticated + * @param encrypt require the connection to be encrypted + * @param address remote device that this socket can connect to + * @param port remote port + * @throws IOException On error, for example Bluetooth not available, or + * insufficient privileges + */ + private BluetoothSocket(int type, int fd, boolean auth, boolean encrypt, String address, + int port) throws IOException { + this(type, fd, auth, encrypt, new BluetoothDevice(address), port, null); + } + + /** @hide */ + @Override + protected void finalize() throws Throwable { + try { + close(); + } finally { + super.finalize(); + } + } + private int getSecurityFlags() { + int flags = 0; + if(mAuth) + flags |= SEC_FLAG_AUTH; + if(mEncrypt) + flags |= SEC_FLAG_ENCRYPT; + return flags; + } + + /** + * Get the remote device this socket is connecting, or connected, to. + * @return remote device + */ + public BluetoothDevice getRemoteDevice() { + return mDevice; + } + + /** + * Get the input stream associated with this socket. + *

The input stream will be returned even if the socket is not yet + * connected, but operations on that stream will throw IOException until + * the associated socket is connected. + * @return InputStream + */ + public InputStream getInputStream() throws IOException { + return mInputStream; + } + + /** + * Get the output stream associated with this socket. + *

The output stream will be returned even if the socket is not yet + * connected, but operations on that stream will throw IOException until + * the associated socket is connected. + * @return OutputStream + */ + public OutputStream getOutputStream() throws IOException { + return mOutputStream; + } + + /** + * Get the connection status of this socket, ie, whether there is an active connection with + * remote device. + * @return true if connected + * false if not connected + */ + public boolean isConnected() { + return mSocketState == SocketState.CONNECTED; + } + + /*package*/ void setServiceName(String name) { + mServiceName = name; + } + + /** + * Attempt to connect to a remote device. + *

This method will block until a connection is made or the connection + * fails. If this method returns without an exception then this socket + * is now connected. + *

Creating new connections to + * remote Bluetooth devices should not be attempted while device discovery + * is in progress. Device discovery is a heavyweight procedure on the + * Bluetooth adapter and will significantly slow a device connection. + * Use {@link BluetoothAdapter#cancelDiscovery()} to cancel an ongoing + * discovery. Discovery is not managed by the Activity, + * but is run as a system service, so an application should always call + * {@link BluetoothAdapter#cancelDiscovery()} even if it + * did not directly request a discovery, just to be sure. + *

{@link #close} can be used to abort this call from another thread. + * @throws IOException on error, for example connection failure + */ + public void connect() throws IOException { + if (mDevice == null) throw new IOException("Connect is called on null device"); + + try { + if (mSocketState == SocketState.CLOSED) throw new IOException("socket closed"); + IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService(null); + if (bluetoothProxy == null) throw new IOException("Bluetooth is off"); + mPfd = bluetoothProxy.connectSocket(mDevice, mType, + mUuid, mPort, getSecurityFlags()); + synchronized(this) + { + if (DBG) Log.d(TAG, "connect(), SocketState: " + mSocketState + ", mPfd: " + mPfd); + if (mSocketState == SocketState.CLOSED) throw new IOException("socket closed"); + if (mPfd == null) throw new IOException("bt socket connect failed"); + FileDescriptor fd = mPfd.getFileDescriptor(); + mSocket = new LocalSocket(fd); + mSocketIS = mSocket.getInputStream(); + mSocketOS = mSocket.getOutputStream(); + } + int channel = readInt(mSocketIS); + if (channel <= 0) + throw new IOException("bt socket connect failed"); + mPort = channel; + waitSocketSignal(mSocketIS); + synchronized(this) + { + if (mSocketState == SocketState.CLOSED) + throw new IOException("bt socket closed"); + mSocketState = SocketState.CONNECTED; + } + } catch (RemoteException e) { + Log.e(TAG, Log.getStackTraceString(new Throwable())); + throw new IOException("unable to send RPC: " + e.getMessage()); + } + } + + /** + * Currently returns unix errno instead of throwing IOException, + * so that BluetoothAdapter can check the error code for EADDRINUSE + */ + /*package*/ int bindListen() { + int ret; + if (mSocketState == SocketState.CLOSED) return EBADFD; + IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService(null); + if (bluetoothProxy == null) { + Log.e(TAG, "bindListen fail, reason: bluetooth is off"); + return -1; + } + try { + mPfd = bluetoothProxy.createSocketChannel(mType, mServiceName, + mUuid, mPort, getSecurityFlags()); + } catch (RemoteException e) { + Log.e(TAG, Log.getStackTraceString(new Throwable())); + return -1; + } + + // read out port number + try { + synchronized(this) { + if (DBG) Log.d(TAG, "bindListen(), SocketState: " + mSocketState + ", mPfd: " + + mPfd); + if(mSocketState != SocketState.INIT) return EBADFD; + if(mPfd == null) return -1; + FileDescriptor fd = mPfd.getFileDescriptor(); + if (DBG) Log.d(TAG, "bindListen(), new LocalSocket "); + mSocket = new LocalSocket(fd); + if (DBG) Log.d(TAG, "bindListen(), new LocalSocket.getInputStream() "); + mSocketIS = mSocket.getInputStream(); + mSocketOS = mSocket.getOutputStream(); + } + if (DBG) Log.d(TAG, "bindListen(), readInt mSocketIS: " + mSocketIS); + int channel = readInt(mSocketIS); + synchronized(this) { + if(mSocketState == SocketState.INIT) + mSocketState = SocketState.LISTENING; + } + if (DBG) Log.d(TAG, "channel: " + channel); + if (mPort == -1) { + mPort = channel; + } // else ASSERT(mPort == channel) + ret = 0; + } catch (IOException e) { + if (mPfd != null) { + try { + mPfd.close(); + } catch (IOException e1) { + Log.e(TAG, "bindListen, close mPfd: " + e1); + } + mPfd = null; + } + Log.e(TAG, "bindListen, fail to get port number, exception: " + e); + return -1; + } + return ret; + } + + /*package*/ BluetoothSocket accept(int timeout) throws IOException { + BluetoothSocket acceptedSocket; + if (mSocketState != SocketState.LISTENING) throw new IOException("bt socket is not in listen state"); + if(timeout > 0) { + Log.d(TAG, "accept() set timeout (ms):" + timeout); + mSocket.setSoTimeout(timeout); + } + String RemoteAddr = waitSocketSignal(mSocketIS); + if(timeout > 0) + mSocket.setSoTimeout(0); + synchronized(this) + { + if (mSocketState != SocketState.LISTENING) + throw new IOException("bt socket is not in listen state"); + acceptedSocket = acceptSocket(RemoteAddr); + //quick drop the reference of the file handle + } + return acceptedSocket; + } + + /** + * setSocketOpt for the Buetooth Socket. + * + * @param optionName socket option name + * @param optionVal socket option value + * @param optionLen socket option length + * @return -1 on immediate error, + * 0 otherwise + * @hide + */ + public int setSocketOpt(int optionName, byte [] optionVal, int optionLen) throws IOException { + int ret = 0; + if (mSocketState == SocketState.CLOSED) throw new IOException("socket closed"); + IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService(null); + if (bluetoothProxy == null) { + Log.e(TAG, "setSocketOpt fail, reason: bluetooth is off"); + return -1; + } + try { + if(VDBG) Log.d(TAG, "setSocketOpt(), mType: " + mType + " mPort: " + mPort); + ret = bluetoothProxy.setSocketOpt(mType, mPort, optionName, optionVal, optionLen); + } catch (RemoteException e) { + Log.e(TAG, Log.getStackTraceString(new Throwable())); + return -1; + } + return ret; + } + + /** + * getSocketOpt for the Buetooth Socket. + * + * @param optionName socket option name + * @param optionVal socket option value + * @return -1 on immediate error, + * length of returned socket option otherwise + * @hide + */ + public int getSocketOpt(int optionName, byte [] optionVal) throws IOException { + int ret = 0; + if (mSocketState == SocketState.CLOSED) throw new IOException("socket closed"); + IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService(null); + if (bluetoothProxy == null) { + Log.e(TAG, "getSocketOpt fail, reason: bluetooth is off"); + return -1; + } + try { + if(VDBG) Log.d(TAG, "getSocketOpt(), mType: " + mType + " mPort: " + mPort); + ret = bluetoothProxy.getSocketOpt(mType, mPort, optionName, optionVal); + } catch (RemoteException e) { + Log.e(TAG, Log.getStackTraceString(new Throwable())); + return -1; + } + return ret; + } + + /*package*/ int available() throws IOException { + if (VDBG) Log.d(TAG, "available: " + mSocketIS); + return mSocketIS.available(); + } + /** + * Wait until the data in sending queue is emptied. A polling version + * for flush implementation. Used to ensure the writing data afterwards will + * be packed in new RFCOMM frame. + * @throws IOException + * if an i/o error occurs. + */ + /*package*/ void flush() throws IOException { + if (mSocketOS == null) throw new IOException("flush is called on null OutputStream"); + if (VDBG) Log.d(TAG, "flush: " + mSocketOS); + mSocketOS.flush(); + } + + /*package*/ int read(byte[] b, int offset, int length) throws IOException { + if (mSocketIS == null) throw new IOException("read is called on null InputStream"); + if (VDBG) Log.d(TAG, "read in: " + mSocketIS + " len: " + length); + int ret = mSocketIS.read(b, offset, length); + if(ret < 0) + throw new IOException("bt socket closed, read return: " + ret); + if (VDBG) Log.d(TAG, "read out: " + mSocketIS + " ret: " + ret); + return ret; + } + + /*package*/ int write(byte[] b, int offset, int length) throws IOException { + if (mSocketOS == null) throw new IOException("write is called on null OutputStream"); + if (VDBG) Log.d(TAG, "write: " + mSocketOS + " length: " + length); + mSocketOS.write(b, offset, length); + // There is no good way to confirm since the entire process is asynchronous anyway + if (VDBG) Log.d(TAG, "write out: " + mSocketOS + " length: " + length); + return length; + } + + @Override + public void close() throws IOException { + if (DBG) Log.d(TAG, "close() in, this: " + this + ", channel: " + mPort + ", state: " + mSocketState); + if(mSocketState == SocketState.CLOSED) + return; + else + { + synchronized(this) + { + if(mSocketState == SocketState.CLOSED) + return; + mSocketState = SocketState.CLOSED; + if (DBG) Log.d(TAG, "close() this: " + this + ", channel: " + mPort + ", mSocketIS: " + mSocketIS + + ", mSocketOS: " + mSocketOS + "mSocket: " + mSocket); + if(mSocket != null) { + if (DBG) Log.d(TAG, "Closing mSocket: " + mSocket); + mSocket.shutdownInput(); + mSocket.shutdownOutput(); + mSocket.close(); + mSocket = null; + } + if (mPfd != null) { + mPfd.close(); + mPfd = null; + } + } + } + } + + /*package */ void removeChannel() { + } + + /*package */ int getPort() { + return mPort; + } + private String convertAddr(final byte[] addr) { + return String.format(Locale.US, "%02X:%02X:%02X:%02X:%02X:%02X", + addr[0] , addr[1], addr[2], addr[3] , addr[4], addr[5]); + } + private String waitSocketSignal(InputStream is) throws IOException { + byte [] sig = new byte[SOCK_SIGNAL_SIZE]; + int ret = readAll(is, sig); + if (VDBG) Log.d(TAG, "waitSocketSignal read 16 bytes signal ret: " + ret); + ByteBuffer bb = ByteBuffer.wrap(sig); + bb.order(ByteOrder.nativeOrder()); + int size = bb.getShort(); + if(size != SOCK_SIGNAL_SIZE) + throw new IOException("Connection failure, wrong signal size: " + size); + byte [] addr = new byte[6]; + bb.get(addr); + int channel = bb.getInt(); + int status = bb.getInt(); + String RemoteAddr = convertAddr(addr); + if (VDBG) Log.d(TAG, "waitSocketSignal: sig size: " + size + ", remote addr: " + + RemoteAddr + ", channel: " + channel + ", status: " + status); + if(status != 0) + throw new IOException("Connection failure, status: " + status); + return RemoteAddr; + } + private int readAll(InputStream is, byte[] b) throws IOException { + int left = b.length; + while(left > 0) { + int ret = is.read(b, b.length - left, left); + if(ret <= 0) + throw new IOException("read failed, socket might closed or timeout, read ret: " + ret); + left -= ret; + if(left != 0) + Log.w(TAG, "readAll() looping, read partial size: " + (b.length - left) + + ", expect size: " + b.length); + } + return b.length; + } + + private int readInt(InputStream is) throws IOException { + byte[] ibytes = new byte[4]; + int ret = readAll(is, ibytes); + if (VDBG) Log.d(TAG, "inputStream.read ret: " + ret); + ByteBuffer bb = ByteBuffer.wrap(ibytes); + bb.order(ByteOrder.nativeOrder()); + return bb.getInt(); + } +} diff --git a/Java/C3P0ConfigXmlUtils.java b/Java/C3P0ConfigXmlUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..2f3b3e65f63583cce0ccd052c911357329f73de0 --- /dev/null +++ b/Java/C3P0ConfigXmlUtils.java @@ -0,0 +1,262 @@ +/* + * Distributed as part of c3p0 v.0.9.5.2 + * + * Copyright (C) 2015 Machinery For Change, Inc. + * + * Author: Steve Waldman + * + * This library is free software; you can redistribute it and/or modify + * it under the terms of EITHER: + * + * 1) The GNU Lesser General Public License (LGPL), version 2.1, as + * published by the Free Software Foundation + * + * OR + * + * 2) The Eclipse Public License (EPL), version 1.0 + * + * You may choose which license to accept if you wish to redistribute + * or modify this work. You may offer derivatives of this work + * under the license you have chosen, or you may provide the same + * choice of license which you have been offered here. + * + * 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. + * + * You should have received copies of both LGPL v2.1 and EPL v1.0 + * along with this software; see the files LICENSE-EPL and LICENSE-LGPL. + * If not, the text of these licenses are currently available at + * + * LGPL v2.1: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html + * EPL v1.0: http://www.eclipse.org/org/documents/epl-v10.php + * + */ + +package com.mchange.v2.c3p0.cfg; + +import java.io.*; +import java.util.*; +import javax.xml.parsers.*; +import org.w3c.dom.*; +import com.mchange.v2.log.*; + +import com.mchange.v1.xml.DomParseUtils; + +public final class C3P0ConfigXmlUtils +{ + public final static String XML_CONFIG_RSRC_PATH = "/c3p0-config.xml"; + + final static MLogger logger = MLog.getLogger( C3P0ConfigXmlUtils.class ); + + public final static String LINESEP; + + private final static String[] MISSPELL_PFXS = {"/c3p0", "/c3pO", "/c3po", "/C3P0", "/C3PO"}; + private final static char[] MISSPELL_LINES = {'-', '_'}; + private final static String[] MISSPELL_CONFIG = {"config", "CONFIG"}; + private final static String[] MISSPELL_XML = {"xml", "XML"}; + + // its an ugly way to do this, but since resources are not listable... + // + // this is only executed once, and does about 40 tests (for now) + // should I care about the cost in initialization time? + // + // should only be run if we've checked for the correct file, but + // not found it + private final static void warnCommonXmlConfigResourceMisspellings() + { + if (logger.isLoggable( MLevel.WARNING) ) + { + for (int a = 0, lena = MISSPELL_PFXS.length; a < lena; ++a) + { + StringBuffer sb = new StringBuffer(16); + sb.append( MISSPELL_PFXS[a] ); + for (int b = 0, lenb = MISSPELL_LINES.length; b < lenb; ++b) + { + sb.append(MISSPELL_LINES[b]); + for (int c = 0, lenc = MISSPELL_CONFIG.length; c < lenc; ++c) + { + sb.append(MISSPELL_CONFIG[c]); + sb.append('.'); + for (int d = 0, lend = MISSPELL_XML.length; d < lend; ++d) + { + sb.append(MISSPELL_XML[d]); + String test = sb.toString(); + if (!test.equals(XML_CONFIG_RSRC_PATH)) + { + Object hopefullyNull = C3P0ConfigXmlUtils.class.getResource( test ); + if (hopefullyNull != null) + { + logger.warning("POSSIBLY MISSPELLED c3p0-conf.xml RESOURCE FOUND. " + + "Please ensure the file name is c3p0-config.xml, all lower case, " + + "with the digit 0 (NOT the letter O) in c3p0. It should be placed " + + " in the top level of c3p0's effective classpath."); + return; + } + } + } + } + + } + } + } + } + + static + { + String ls; + + try + { ls = System.getProperty("line.separator", "\r\n"); } + catch (Exception e) + { ls = "\r\n"; } + + LINESEP = ls; + + } + + public static C3P0Config extractXmlConfigFromDefaultResource() throws Exception + { + InputStream is = null; + + try + { + is = C3P0ConfigUtils.class.getResourceAsStream(XML_CONFIG_RSRC_PATH); + if ( is == null ) + { + warnCommonXmlConfigResourceMisspellings(); + return null; + } + else + return extractXmlConfigFromInputStream( is ); + } + finally + { + try { if (is != null) is.close(); } + catch (Exception e) + { + if ( logger.isLoggable( MLevel.FINE ) ) + logger.log(MLevel.FINE,"Exception on resource InputStream close.", e); + } + } + } + + public static C3P0Config extractXmlConfigFromInputStream(InputStream is) throws Exception + { + DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); + // BUG: CWE-611 Improper Restriction of XML External Entity Reference + // + // FIXED: + fact.setExpandEntityReferences(false); + DocumentBuilder db = fact.newDocumentBuilder(); + Document doc = db.parse( is ); + + return extractConfigFromXmlDoc(doc); + } + + public static C3P0Config extractConfigFromXmlDoc(Document doc) throws Exception + { + Element docElem = doc.getDocumentElement(); + if (docElem.getTagName().equals("c3p0-config")) + { + NamedScope defaults; + HashMap configNamesToNamedScopes = new HashMap(); + + Element defaultConfigElem = DomParseUtils.uniqueChild( docElem, "default-config" ); + if (defaultConfigElem != null) + defaults = extractNamedScopeFromLevel( defaultConfigElem ); + else + defaults = new NamedScope(); + NodeList nl = DomParseUtils.immediateChildElementsByTagName(docElem, "named-config"); + for (int i = 0, len = nl.getLength(); i < len; ++i) + { + Element namedConfigElem = (Element) nl.item(i); + String configName = namedConfigElem.getAttribute("name"); + if (configName != null && configName.length() > 0) + { + NamedScope namedConfig = extractNamedScopeFromLevel( namedConfigElem ); + configNamesToNamedScopes.put( configName, namedConfig); + } + else + logger.warning("Configuration XML contained named-config element without name attribute: " + namedConfigElem); + } + return new C3P0Config( defaults, configNamesToNamedScopes ); + } + else + throw new Exception("Root element of c3p0 config xml should be 'c3p0-config', not '" + docElem.getTagName() + "'."); + } + + private static NamedScope extractNamedScopeFromLevel(Element elem) + { + HashMap props = extractPropertiesFromLevel( elem ); + HashMap userNamesToOverrides = new HashMap(); + + NodeList nl = DomParseUtils.immediateChildElementsByTagName(elem, "user-overrides"); + for (int i = 0, len = nl.getLength(); i < len; ++i) + { + Element perUserConfigElem = (Element) nl.item(i); + String userName = perUserConfigElem.getAttribute("user"); + if (userName != null && userName.length() > 0) + { + HashMap userProps = extractPropertiesFromLevel( perUserConfigElem ); + userNamesToOverrides.put( userName, userProps ); + } + else + logger.warning("Configuration XML contained user-overrides element without user attribute: " + LINESEP + perUserConfigElem); + } + + HashMap extensions = extractExtensionsFromLevel( elem ); + + return new NamedScope(props, userNamesToOverrides, extensions); + } + + private static HashMap extractExtensionsFromLevel(Element elem) + { + HashMap out = new HashMap(); + NodeList nl = DomParseUtils.immediateChildElementsByTagName(elem, "extensions"); + for (int i = 0, len = nl.getLength(); i < len; ++i) + { + Element extensionsElem = (Element) nl.item(i); + out.putAll( extractPropertiesFromLevel( extensionsElem ) ); + } + return out; + } + + private static HashMap extractPropertiesFromLevel(Element elem) + { + // System.err.println( "extractPropertiesFromLevel()" ); + + HashMap out = new HashMap(); + + try + { + NodeList nl = DomParseUtils.immediateChildElementsByTagName(elem, "property"); + int len = nl.getLength(); + for (int i = 0; i < len; ++i) + { + Element propertyElem = (Element) nl.item(i); + String propName = propertyElem.getAttribute("name"); + if (propName != null && propName.length() > 0) + { + String propVal = DomParseUtils.allTextFromElement(propertyElem, true); + out.put( propName, propVal ); + //System.err.println( propName + " -> " + propVal ); + } + else + logger.warning("Configuration XML contained property element without name attribute: " + LINESEP + propertyElem); + } + } + catch (Exception e) + { + logger.log( MLevel.WARNING, + "An exception occurred while reading config XML. " + + "Some configuration information has probably been ignored.", + e ); + } + + return out; + } + + private C3P0ConfigXmlUtils() + {} +} diff --git a/Java/CBORGenerator.java b/Java/CBORGenerator.java new file mode 100644 index 0000000000000000000000000000000000000000..c2f241e6b5633a66efa30f582ce6f624d0885a87 --- /dev/null +++ b/Java/CBORGenerator.java @@ -0,0 +1,1746 @@ +package com.fasterxml.jackson.dataformat.cbor; + +import java.util.Arrays; +import java.io.*; +import java.math.BigDecimal; +import java.math.BigInteger; + +import com.fasterxml.jackson.core.*; +import com.fasterxml.jackson.core.base.GeneratorBase; +import com.fasterxml.jackson.core.io.IOContext; +import com.fasterxml.jackson.core.json.DupDetector; + +import static com.fasterxml.jackson.dataformat.cbor.CBORConstants.*; + +/** + * {@link JsonGenerator} implementation that writes CBOR encoded content. + * + * @author Tatu Saloranta + */ +public class CBORGenerator extends GeneratorBase +{ + private final static int[] NO_INTS = new int[0]; + + /** + * Let's ensure that we have big enough output buffer because of safety + * margins we need for UTF-8 encoding. + */ + final static int BYTE_BUFFER_FOR_OUTPUT = 16000; + + /** + * Longest char chunk we will output is chosen so that it is guaranteed to + * fit in an empty buffer even if everything encoded in 3-byte sequences; + * but also fit two full chunks in case of single-byte (ascii) output. + */ + private final static int MAX_LONG_STRING_CHARS = (BYTE_BUFFER_FOR_OUTPUT / 4) - 4; + + /** + * This is the worst case length (in bytes) of maximum chunk we ever write. + */ + private final static int MAX_LONG_STRING_BYTES = (MAX_LONG_STRING_CHARS * 3) + 3; + + /** + * Enumeration that defines all togglable features for CBOR generator. + */ + public enum Feature implements FormatFeature { + /** + * Feature that determines whether generator should try to use smallest + * (size-wise) integer representation: if true, will use smallest + * representation that is enough to retain value; if false, will use + * length indicated by argument type (4-byte for int, + * 8-byte for long and so on). + */ + WRITE_MINIMAL_INTS(true), + + /** + * Feature that determines whether CBOR "Self-Describe Tag" (value + * 55799, encoded as 3-byte sequence of 0xD9, 0xD9, 0xF7) + * should be written at the beginning of document or not. + *

+ * Default value is false meaning that type tag will not be + * written at the beginning of a new document. + * + * @since 2.5 + */ + WRITE_TYPE_HEADER(false), ; + + protected final boolean _defaultState; + protected final int _mask; + + /** + * Method that calculates bit set (flags) of all features that are + * enabled by default. + */ + public static int collectDefaults() { + int flags = 0; + for (Feature f : values()) { + if (f.enabledByDefault()) { + flags |= f.getMask(); + } + } + return flags; + } + + private Feature(boolean defaultState) { + _defaultState = defaultState; + _mask = (1 << ordinal()); + } + + @Override + public boolean enabledByDefault() { + return _defaultState; + } + + @Override + public boolean enabledIn(int flags) { + return (flags & getMask()) != 0; + } + + @Override + public int getMask() { + return _mask; + } + } + + /** + * To simplify certain operations, we require output buffer length to allow + * outputting of contiguous 256 character UTF-8 encoded String value. Length + * of the longest UTF-8 code point (from Java char) is 3 bytes, and we need + * both initial token byte and single-byte end marker so we get following + * value. + *

+ * Note: actually we could live with shorter one; absolute minimum would be + * for encoding 64-character Strings. + */ + private final static int MIN_BUFFER_LENGTH = (3 * 256) + 2; + + /** + * Special value that is use to keep tracks of arrays and maps opened with infinite length + */ + private final static int INDEFINITE_LENGTH = -2; // just to allow -1 as marker for "one too many" + + /* + /********************************************************** + /* Configuration + /********************************************************** + */ + + final protected IOContext _ioContext; + + final protected OutputStream _out; + + /** + * Bit flag composed of bits that indicate which + * {@link CBORGenerator.Feature}s are enabled. + */ + protected int _formatFeatures; + + protected boolean _cfgMinimalInts; + + /* + /********************************************************** + /* Output state + /********************************************************** + */ + + /** + * @since 2.10 + */ + protected CBORWriteContext _cborContext; + + /* + /********************************************************** + /* Output buffering + /********************************************************** + */ + + /** + * Intermediate buffer in which contents are buffered before being written + * using {@link #_out}. + */ + protected byte[] _outputBuffer; + + /** + * Pointer to the next available byte in {@link #_outputBuffer} + */ + protected int _outputTail = 0; + + /** + * Offset to index after the last valid index in {@link #_outputBuffer}. + * Typically same as length of the buffer. + */ + protected final int _outputEnd; + + /** + * Intermediate buffer in which characters of a String are copied before + * being encoded. + */ + protected char[] _charBuffer; + + protected final int _charBufferLength; + + /** + * Let's keep track of how many bytes have been output, may prove useful + * when debugging. This does not include bytes buffered in the output + * buffer, just bytes that have been written using underlying stream writer. + */ + protected int _bytesWritten; + + /* + /********************************************************** + /* Tracking of remaining elements to write + /********************************************************** + */ + + protected int[] _elementCounts = NO_INTS; + + protected int _elementCountsPtr; + + /** + * Number of elements remaining in the current complex structure (if any), + // BUG: CWE-770 Allocation of Resources Without Limits or Throttling + // * when writing defined-length Arrays, Objects; marker {@link #INDEFINITE_LENGTH} + // FIXED: + * when writing defined-length Arrays, Objects; marker {code INDEFINITE_LENGTH} + * otherwise. + */ + protected int _currentRemainingElements = INDEFINITE_LENGTH; + + /* + /********************************************************** + /* Shared String detection + /********************************************************** + */ + + /** + * Flag that indicates whether the output buffer is recycable (and needs to + * be returned to recycler once we are done) or not. + */ + protected boolean _bufferRecyclable; + + /* + /********************************************************** + /* Life-cycle + /********************************************************** + */ + + public CBORGenerator(IOContext ctxt, int stdFeatures, int formatFeatures, + ObjectCodec codec, OutputStream out) { + super(stdFeatures, codec, /* Write Context */ null); + DupDetector dups = JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION.enabledIn(stdFeatures) + ? DupDetector.rootDetector(this) + : null; + // NOTE: we passed `null` for default write context + _cborContext = CBORWriteContext.createRootContext(dups); + _formatFeatures = formatFeatures; + _cfgMinimalInts = Feature.WRITE_MINIMAL_INTS.enabledIn(formatFeatures); + _ioContext = ctxt; + _out = out; + _bufferRecyclable = true; + _outputBuffer = ctxt.allocWriteEncodingBuffer(BYTE_BUFFER_FOR_OUTPUT); + _outputEnd = _outputBuffer.length; + _charBuffer = ctxt.allocConcatBuffer(); + _charBufferLength = _charBuffer.length; + // let's just sanity check to prevent nasty odd errors + if (_outputEnd < MIN_BUFFER_LENGTH) { + throw new IllegalStateException("Internal encoding buffer length (" + + _outputEnd + ") too short, must be at least " + + MIN_BUFFER_LENGTH); + } + } + + /** + * Alternative constructor that may be used to feed partially initialized content. + * + * @param outputBuffer + * Buffer to use for output before flushing to the underlying stream + * @param offset + * Offset pointing past already buffered content; that is, number + * of bytes of valid content to output, within buffer. + */ + public CBORGenerator(IOContext ctxt, int stdFeatures, int formatFeatures, + ObjectCodec codec, OutputStream out, byte[] outputBuffer, + int offset, boolean bufferRecyclable) { + super(stdFeatures, codec, /* Write Context */ null); + DupDetector dups = JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION.enabledIn(stdFeatures) + ? DupDetector.rootDetector(this) + : null; + // NOTE: we passed `null` for default write context + _cborContext = CBORWriteContext.createRootContext(dups); + _formatFeatures = formatFeatures; + _cfgMinimalInts = Feature.WRITE_MINIMAL_INTS.enabledIn(formatFeatures); + _ioContext = ctxt; + _out = out; + _bufferRecyclable = bufferRecyclable; + _outputTail = offset; + _outputBuffer = outputBuffer; + _outputEnd = _outputBuffer.length; + _charBuffer = ctxt.allocConcatBuffer(); + _charBufferLength = _charBuffer.length; + // let's just sanity check to prevent nasty odd errors + if (_outputEnd < MIN_BUFFER_LENGTH) { + throw new IllegalStateException("Internal encoding buffer length (" + + _outputEnd + ") too short, must be at least " + + MIN_BUFFER_LENGTH); + } + } + + /* + /********************************************************** + /* Versioned + /********************************************************** + */ + + @Override + public Version version() { + return PackageVersion.VERSION; + } + + /* + /********************************************************** + /* Capability introspection + /********************************************************** + */ + + @Override + public boolean canWriteBinaryNatively() { + return true; + } + + /* + /********************************************************** + /* Overridden methods, configuration + /********************************************************** + */ + + /** + * No way (or need) to indent anything, so let's block any attempts. (should + * we throw an exception instead?) + */ + @Override + public JsonGenerator useDefaultPrettyPrinter() { + return this; + } + + /** + * No way (or need) to indent anything, so let's block any attempts. (should + * we throw an exception instead?) + */ + @Override + public JsonGenerator setPrettyPrinter(PrettyPrinter pp) { + return this; + } + + @Override + public Object getOutputTarget() { + return _out; + } + + @Override + public int getOutputBuffered() { + return _outputTail; + } + + // public JsonParser overrideStdFeatures(int values, int mask) + + @Override + public int getFormatFeatures() { + return _formatFeatures; + } + + @Override + public JsonGenerator overrideStdFeatures(int values, int mask) { + int oldState = _features; + int newState = (oldState & ~mask) | (values & mask); + if (oldState != newState) { + _features = newState; + } + return this; + } + + @Override + public JsonGenerator overrideFormatFeatures(int values, int mask) { + int oldState = _formatFeatures; + int newState = (_formatFeatures & ~mask) | (values & mask); + if (oldState != newState) { + _formatFeatures = newState; + _cfgMinimalInts = Feature.WRITE_MINIMAL_INTS.enabledIn(newState); + } + return this; + } + + /* + /********************************************************** + /* Overridden methods, output context (and related) + /********************************************************** + */ + + @Override + public Object getCurrentValue() { + return _cborContext.getCurrentValue(); + } + + @Override + public void setCurrentValue(Object v) { + _cborContext.setCurrentValue(v); + } + + @Override + public JsonStreamContext getOutputContext() { + return _cborContext; + } + + /* + /********************************************************** + /* Extended API, configuration + /********************************************************** + */ + + public CBORGenerator enable(Feature f) { + _formatFeatures |= f.getMask(); + if (f == Feature.WRITE_MINIMAL_INTS) { + _cfgMinimalInts = true; + } + return this; + } + + public CBORGenerator disable(Feature f) { + _formatFeatures &= ~f.getMask(); + if (f == Feature.WRITE_MINIMAL_INTS) { + _cfgMinimalInts = false; + } + return this; + } + + public final boolean isEnabled(Feature f) { + return (_formatFeatures & f.getMask()) != 0; + } + + public CBORGenerator configure(Feature f, boolean state) { + if (state) { + enable(f); + } else { + disable(f); + } + return this; + } + + /* + /********************************************************** + /* Overridden methods, write methods + /********************************************************** + */ + + /* + * And then methods overridden to make final, streamline some aspects... + */ + + @Override + public final void writeFieldName(String name) throws IOException { + if (!_cborContext.writeFieldName(name)) { + _reportError("Can not write a field name, expecting a value"); + } + _writeString(name); + } + + @Override + public final void writeFieldName(SerializableString name) + throws IOException { + // Object is a value, need to verify it's allowed + if (!_cborContext.writeFieldName(name.getValue())) { + _reportError("Can not write a field name, expecting a value"); + } + byte[] raw = name.asUnquotedUTF8(); + final int len = raw.length; + if (len == 0) { + _writeByte(BYTE_EMPTY_STRING); + return; + } + _writeLengthMarker(PREFIX_TYPE_TEXT, len); + _writeBytes(raw, 0, len); + } + + @Override // since 2.8 + public final void writeFieldId(long id) throws IOException { + if (!_cborContext.writeFieldId(id)) { + _reportError("Can not write a field id, expecting a value"); + } + _writeLongNoCheck(id); + } + + /* + /********************************************************** + /* Overridden methods, copying with tag-awareness + /********************************************************** + */ + + /** + * Specialize {@link JsonGenerator#copyCurrentEvent} to handle tags. + */ + @Override + public void copyCurrentEvent(JsonParser p) throws IOException { + maybeCopyTag(p); + super.copyCurrentEvent(p); + } + + /** + * Specialize {@link JsonGenerator#copyCurrentStructure} to handle tags. + */ + @Override + public void copyCurrentStructure(JsonParser p) throws IOException { + maybeCopyTag(p); + super.copyCurrentStructure(p); + } + + protected void maybeCopyTag(JsonParser p) throws IOException { + if (p instanceof CBORParser) { + if (p.hasCurrentToken()) { + final int currentTag = ((CBORParser) p).getCurrentTag(); + + if (currentTag != -1) { + writeTag(currentTag); + } + } + } + } + + /* + /********************************************************** + /* Output method implementations, structural + /********************************************************** + */ + + @Override + public final void writeStartArray() throws IOException { + _verifyValueWrite("start an array"); + _cborContext = _cborContext.createChildArrayContext(null); + if (_elementCountsPtr > 0) { + _pushRemainingElements(); + } + _currentRemainingElements = INDEFINITE_LENGTH; + _writeByte(BYTE_ARRAY_INDEFINITE); + } + + /* + * Unlike with JSON, this method is using slightly optimized version since + * CBOR has a variant that allows embedding length in array start marker. + */ + + @Override + public void writeStartArray(int elementsToWrite) throws IOException { + _verifyValueWrite("start an array"); + _cborContext = _cborContext.createChildArrayContext(null); + _pushRemainingElements(); + _currentRemainingElements = elementsToWrite; + _writeLengthMarker(PREFIX_TYPE_ARRAY, elementsToWrite); + } + + @Override + public final void writeEndArray() throws IOException { + if (!_cborContext.inArray()) { + _reportError("Current context not Array but "+_cborContext.typeDesc()); + } + closeComplexElement(); + _cborContext = _cborContext.getParent(); + } + + @Override + public final void writeStartObject() throws IOException { + _verifyValueWrite("start an object"); + _cborContext = _cborContext.createChildObjectContext(null); + if (_elementCountsPtr > 0) { + _pushRemainingElements(); + } + _currentRemainingElements = INDEFINITE_LENGTH; + _writeByte(BYTE_OBJECT_INDEFINITE); + } + + @Override + // since 2.8 + public final void writeStartObject(Object forValue) throws IOException { + _verifyValueWrite("start an object"); + CBORWriteContext ctxt = _cborContext.createChildObjectContext(forValue); + _cborContext = ctxt; + if (_elementCountsPtr > 0) { + _pushRemainingElements(); + } + _currentRemainingElements = INDEFINITE_LENGTH; + _writeByte(BYTE_OBJECT_INDEFINITE); + } + + public final void writeStartObject(int elementsToWrite) throws IOException { + _verifyValueWrite("start an object"); + _cborContext = _cborContext.createChildObjectContext(null); + _pushRemainingElements(); + _currentRemainingElements = elementsToWrite; + _writeLengthMarker(PREFIX_TYPE_OBJECT, elementsToWrite); + } + + @Override + public final void writeEndObject() throws IOException { + if (!_cborContext.inObject()) { + _reportError("Current context not Object but "+ _cborContext.typeDesc()); + } + closeComplexElement(); + _cborContext = _cborContext.getParent(); + } + + @Override // since 2.8 + public void writeArray(int[] array, int offset, int length) throws IOException + { + _verifyOffsets(array.length, offset, length); + // short-cut, do not create child array context etc + _verifyValueWrite("write int array"); + _writeLengthMarker(PREFIX_TYPE_ARRAY, length); + + if (_cfgMinimalInts) { + for (int i = offset, end = offset+length; i < end; ++i) { + final int value = array[i]; + if (value < 0) { + _writeIntMinimal(PREFIX_TYPE_INT_NEG, -value - 1); + } else { + _writeIntMinimal(PREFIX_TYPE_INT_POS, value); + } + } + } else { + for (int i = offset, end = offset+length; i < end; ++i) { + final int value = array[i]; + if (value < 0) { + _writeIntFull(PREFIX_TYPE_INT_NEG, -value - 1); + } else { + _writeIntFull(PREFIX_TYPE_INT_POS, value); + } + } + } + } + + @Override // since 2.8 + public void writeArray(long[] array, int offset, int length) throws IOException + { + _verifyOffsets(array.length, offset, length); + // short-cut, do not create child array context etc + _verifyValueWrite("write int array"); + _writeLengthMarker(PREFIX_TYPE_ARRAY, length); + for (int i = offset, end = offset+length; i < end; ++i) { + _writeLongNoCheck(array[i]); + } + } + + @Override // since 2.8 + public void writeArray(double[] array, int offset, int length) throws IOException + { + _verifyOffsets(array.length, offset, length); + // short-cut, do not create child array context etc + _verifyValueWrite("write int array"); + _writeLengthMarker(PREFIX_TYPE_ARRAY, length); + for (int i = offset, end = offset+length; i < end; ++i) { + _writeDoubleNoCheck(array[i]); + } + } + + // @since 2.8.8 + private final void _pushRemainingElements() { + if (_elementCounts.length == _elementCountsPtr) { // initially, as well as if full + _elementCounts = Arrays.copyOf(_elementCounts, _elementCounts.length+10); + } + _elementCounts[_elementCountsPtr++] = _currentRemainingElements; + } + + private final void _writeIntMinimal(int markerBase, int i) throws IOException + { + _ensureRoomForOutput(5); + byte b0; + if (i >= 0) { + if (i < 24) { + _outputBuffer[_outputTail++] = (byte) (markerBase + i); + return; + } + if (i <= 0xFF) { + _outputBuffer[_outputTail++] = (byte) (markerBase + SUFFIX_UINT8_ELEMENTS); + _outputBuffer[_outputTail++] = (byte) i; + return; + } + b0 = (byte) i; + i >>= 8; + if (i <= 0xFF) { + _outputBuffer[_outputTail++] = (byte) (markerBase + SUFFIX_UINT16_ELEMENTS); + _outputBuffer[_outputTail++] = (byte) i; + _outputBuffer[_outputTail++] = b0; + return; + } + } else { + b0 = (byte) i; + i >>= 8; + } + _outputBuffer[_outputTail++] = (byte) (markerBase + SUFFIX_UINT32_ELEMENTS); + _outputBuffer[_outputTail++] = (byte) (i >> 16); + _outputBuffer[_outputTail++] = (byte) (i >> 8); + _outputBuffer[_outputTail++] = (byte) i; + _outputBuffer[_outputTail++] = b0; + } + + private final void _writeIntFull(int markerBase, int i) throws IOException + { + // if ((_outputTail + needed) >= _outputEnd) { _flushBuffer(); } + _ensureRoomForOutput(5); + + _outputBuffer[_outputTail++] = (byte) (markerBase + SUFFIX_UINT32_ELEMENTS); + _outputBuffer[_outputTail++] = (byte) (i >> 24); + _outputBuffer[_outputTail++] = (byte) (i >> 16); + _outputBuffer[_outputTail++] = (byte) (i >> 8); + _outputBuffer[_outputTail++] = (byte) i; + } + + // Helper method that works like `writeNumber(long)` but DOES NOT + // check internal output state. It does, however, check need for minimization + private final void _writeLongNoCheck(long l) throws IOException { + if (_cfgMinimalInts) { + if (l >= 0) { + if (l <= 0x100000000L) { + _writeIntMinimal(PREFIX_TYPE_INT_POS, (int) l); + return; + } + } else if (l >= -0x100000000L) { + _writeIntMinimal(PREFIX_TYPE_INT_NEG, (int) (-l - 1)); + return; + } + } + _ensureRoomForOutput(9); + if (l < 0L) { + l += 1; + l = -l; + _outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_NEG + SUFFIX_UINT64_ELEMENTS); + } else { + _outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_POS + SUFFIX_UINT64_ELEMENTS); + } + int i = (int) (l >> 32); + _outputBuffer[_outputTail++] = (byte) (i >> 24); + _outputBuffer[_outputTail++] = (byte) (i >> 16); + _outputBuffer[_outputTail++] = (byte) (i >> 8); + _outputBuffer[_outputTail++] = (byte) i; + i = (int) l; + _outputBuffer[_outputTail++] = (byte) (i >> 24); + _outputBuffer[_outputTail++] = (byte) (i >> 16); + _outputBuffer[_outputTail++] = (byte) (i >> 8); + _outputBuffer[_outputTail++] = (byte) i; + } + + private final void _writeDoubleNoCheck(double d) throws IOException { + _ensureRoomForOutput(11); + // 17-Apr-2010, tatu: could also use 'doubleToIntBits', but it seems + // more accurate to use exact representation; and possibly faster. + // However, if there are cases where collapsing of NaN was needed (for + // non-Java clients), this can be changed + long l = Double.doubleToRawLongBits(d); + _outputBuffer[_outputTail++] = BYTE_FLOAT64; + + int i = (int) (l >> 32); + _outputBuffer[_outputTail++] = (byte) (i >> 24); + _outputBuffer[_outputTail++] = (byte) (i >> 16); + _outputBuffer[_outputTail++] = (byte) (i >> 8); + _outputBuffer[_outputTail++] = (byte) i; + i = (int) l; + _outputBuffer[_outputTail++] = (byte) (i >> 24); + _outputBuffer[_outputTail++] = (byte) (i >> 16); + _outputBuffer[_outputTail++] = (byte) (i >> 8); + _outputBuffer[_outputTail++] = (byte) i; + } + + /* + /*********************************************************** + /* Output method implementations, textual + /*********************************************************** + */ + + @Override + public void writeString(String text) throws IOException { + if (text == null) { + writeNull(); + return; + } + _verifyValueWrite("write String value"); + _writeString(text); + } + + @Override + public final void writeString(SerializableString sstr) throws IOException { + _verifyValueWrite("write String value"); + byte[] raw = sstr.asUnquotedUTF8(); + final int len = raw.length; + if (len == 0) { + _writeByte(BYTE_EMPTY_STRING); + return; + } + _writeLengthMarker(PREFIX_TYPE_TEXT, len); + _writeBytes(raw, 0, len); + } + + @Override + public void writeString(char[] text, int offset, int len) + throws IOException { + _verifyValueWrite("write String value"); + if (len == 0) { + _writeByte(BYTE_EMPTY_STRING); + return; + } + _writeString(text, offset, len); + } + + @Override + public void writeRawUTF8String(byte[] raw, int offset, int len) + throws IOException + { + _verifyValueWrite("write String value"); + if (len == 0) { + _writeByte(BYTE_EMPTY_STRING); + return; + } + _writeLengthMarker(PREFIX_TYPE_TEXT, len); + _writeBytes(raw, 0, len); + } + + @Override + public final void writeUTF8String(byte[] text, int offset, int len) + throws IOException { + // Since no escaping is needed, same as 'writeRawUTF8String' + writeRawUTF8String(text, offset, len); + } + + /* + /********************************************************** + /* Output method implementations, unprocessed ("raw") + /********************************************************** + */ + + @Override + public void writeRaw(String text) throws IOException { + throw _notSupported(); + } + + @Override + public void writeRaw(String text, int offset, int len) throws IOException { + throw _notSupported(); + } + + @Override + public void writeRaw(char[] text, int offset, int len) throws IOException { + throw _notSupported(); + } + + @Override + public void writeRaw(char c) throws IOException { + throw _notSupported(); + } + + @Override + public void writeRawValue(String text) throws IOException { + throw _notSupported(); + } + + @Override + public void writeRawValue(String text, int offset, int len) + throws IOException { + throw _notSupported(); + } + + @Override + public void writeRawValue(char[] text, int offset, int len) + throws IOException { + throw _notSupported(); + } + + /* + * /********************************************************** /* Output + * method implementations, base64-encoded binary + * /********************************************************** + */ + + @Override + public void writeBinary(Base64Variant b64variant, byte[] data, int offset, + int len) throws IOException { + if (data == null) { + writeNull(); + return; + } + _verifyValueWrite("write Binary value"); + _writeLengthMarker(PREFIX_TYPE_BYTES, len); + _writeBytes(data, offset, len); + } + + @Override + public int writeBinary(InputStream data, int dataLength) throws IOException { + /* + * 28-Mar-2014, tatu: Theoretically we could implement encoder that uses + * chunking to output binary content of unknown (a priori) length. But + * for no let's require knowledge of length, for simplicity: may be + * revisited in future. + */ + if (dataLength < 0) { + throw new UnsupportedOperationException( + "Must pass actual length for CBOR encoded data"); + } + _verifyValueWrite("write Binary value"); + int missing; + + _writeLengthMarker(PREFIX_TYPE_BYTES, dataLength); + missing = _writeBytes(data, dataLength); + if (missing > 0) { + _reportError("Too few bytes available: missing " + missing + + " bytes (out of " + dataLength + ")"); + } + return dataLength; + } + + @Override + public int writeBinary(Base64Variant b64variant, InputStream data, + int dataLength) throws IOException { + return writeBinary(data, dataLength); + } + + /* + /********************************************************** + /* Output method implementations, primitive + /********************************************************** + */ + + @Override + public void writeBoolean(boolean state) throws IOException { + _verifyValueWrite("write boolean value"); + if (state) { + _writeByte(BYTE_TRUE); + } else { + _writeByte(BYTE_FALSE); + } + } + + @Override + public void writeNull() throws IOException { + _verifyValueWrite("write null value"); + _writeByte(BYTE_NULL); + } + + @Override + public void writeNumber(int i) throws IOException { + _verifyValueWrite("write number"); + int marker; + if (i < 0) { + i = -i - 1; + marker = PREFIX_TYPE_INT_NEG; + } else { + marker = PREFIX_TYPE_INT_POS; + } + _ensureRoomForOutput(5); + byte b0; + if (_cfgMinimalInts) { + if (i < 24) { + _outputBuffer[_outputTail++] = (byte) (marker + i); + return; + } + if (i <= 0xFF) { + _outputBuffer[_outputTail++] = (byte) (marker + SUFFIX_UINT8_ELEMENTS); + _outputBuffer[_outputTail++] = (byte) i; + return; + } + b0 = (byte) i; + i >>= 8; + if (i <= 0xFF) { + _outputBuffer[_outputTail++] = (byte) (marker + SUFFIX_UINT16_ELEMENTS); + _outputBuffer[_outputTail++] = (byte) i; + _outputBuffer[_outputTail++] = b0; + return; + } + } else { + b0 = (byte) i; + i >>= 8; + } + _outputBuffer[_outputTail++] = (byte) (marker + SUFFIX_UINT32_ELEMENTS); + _outputBuffer[_outputTail++] = (byte) (i >> 16); + _outputBuffer[_outputTail++] = (byte) (i >> 8); + _outputBuffer[_outputTail++] = (byte) i; + _outputBuffer[_outputTail++] = b0; + } + + @Override + public void writeNumber(long l) throws IOException { + _verifyValueWrite("write number"); + if (_cfgMinimalInts) { // maybe 32 bits is enough? + if (l >= 0) { + if (l <= 0x100000000L) { + _writeIntMinimal(PREFIX_TYPE_INT_POS, (int) l); + return; + } + } else if (l >= -0x100000000L) { + _writeIntMinimal(PREFIX_TYPE_INT_NEG, (int) (-l - 1)); + return; + } + } + _ensureRoomForOutput(9); + if (l < 0L) { + l += 1; + l = -l; + _outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_NEG + SUFFIX_UINT64_ELEMENTS); + } else { + _outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_POS + SUFFIX_UINT64_ELEMENTS); + } + int i = (int) (l >> 32); + _outputBuffer[_outputTail++] = (byte) (i >> 24); + _outputBuffer[_outputTail++] = (byte) (i >> 16); + _outputBuffer[_outputTail++] = (byte) (i >> 8); + _outputBuffer[_outputTail++] = (byte) i; + i = (int) l; + _outputBuffer[_outputTail++] = (byte) (i >> 24); + _outputBuffer[_outputTail++] = (byte) (i >> 16); + _outputBuffer[_outputTail++] = (byte) (i >> 8); + _outputBuffer[_outputTail++] = (byte) i; + } + + @Override + public void writeNumber(BigInteger v) throws IOException { + if (v == null) { + writeNull(); + return; + } + _verifyValueWrite("write number"); + _write(v); + } + + // Main write method isolated so that it can be called directly + // in cases where that is needed (to encode BigDecimal) + protected void _write(BigInteger v) throws IOException { + /* + * Supported by using type tags, as per spec: major type for tag '6'; 5 + * LSB either 2 for positive bignum or 3 for negative bignum. And then + * byte sequence that encode variable length integer. + */ + if (v.signum() < 0) { + _writeByte(BYTE_TAG_BIGNUM_NEG); + v = v.negate(); + } else { + _writeByte(BYTE_TAG_BIGNUM_POS); + } + byte[] data = v.toByteArray(); + final int len = data.length; + _writeLengthMarker(PREFIX_TYPE_BYTES, len); + _writeBytes(data, 0, len); + } + + @Override + public void writeNumber(double d) throws IOException { + _verifyValueWrite("write number"); + _ensureRoomForOutput(11); + /* + * 17-Apr-2010, tatu: could also use 'doubleToIntBits', but it seems + * more accurate to use exact representation; and possibly faster. + * However, if there are cases where collapsing of NaN was needed (for + * non-Java clients), this can be changed + */ + long l = Double.doubleToRawLongBits(d); + _outputBuffer[_outputTail++] = BYTE_FLOAT64; + + int i = (int) (l >> 32); + _outputBuffer[_outputTail++] = (byte) (i >> 24); + _outputBuffer[_outputTail++] = (byte) (i >> 16); + _outputBuffer[_outputTail++] = (byte) (i >> 8); + _outputBuffer[_outputTail++] = (byte) i; + i = (int) l; + _outputBuffer[_outputTail++] = (byte) (i >> 24); + _outputBuffer[_outputTail++] = (byte) (i >> 16); + _outputBuffer[_outputTail++] = (byte) (i >> 8); + _outputBuffer[_outputTail++] = (byte) i; + } + + @Override + public void writeNumber(float f) throws IOException { + // Ok, now, we needed token type byte plus 5 data bytes (7 bits each) + _ensureRoomForOutput(6); + _verifyValueWrite("write number"); + + /* + * 17-Apr-2010, tatu: could also use 'floatToIntBits', but it seems more + * accurate to use exact representation; and possibly faster. However, + * if there are cases where collapsing of NaN was needed (for non-Java + * clients), this can be changed + */ + int i = Float.floatToRawIntBits(f); + _outputBuffer[_outputTail++] = BYTE_FLOAT32; + _outputBuffer[_outputTail++] = (byte) (i >> 24); + _outputBuffer[_outputTail++] = (byte) (i >> 16); + _outputBuffer[_outputTail++] = (byte) (i >> 8); + _outputBuffer[_outputTail++] = (byte) i; + } + + @Override + public void writeNumber(BigDecimal dec) throws IOException { + if (dec == null) { + writeNull(); + return; + } + _verifyValueWrite("write number"); + /* Supported by using type tags, as per spec: major type for tag '6'; 5 + * LSB 4. And then a two-element array; integer exponent, and int/bigint + * mantissa + */ + // 12-May-2016, tatu: Before 2.8, used "bigfloat", but that was + // incorrect... + _writeByte(BYTE_TAG_DECIMAL_FRACTION); + _writeByte(BYTE_ARRAY_2_ELEMENTS); + + // 27-Nov-2019, tatu: As per [dataformats-binary#139] need to change sign here + int scale = dec.scale(); + _writeIntValue(-scale); + // Hmmmh. Specification suggest use of regular integer for mantissa. But + // if it doesn't fit, use "bignum" + BigInteger unscaled = dec.unscaledValue(); + int bitLength = unscaled.bitLength(); + if (bitLength <= 31) { + _writeIntValue(unscaled.intValue()); + } else if (bitLength <= 63) { + _writeLongValue(unscaled.longValue()); + } else { + _write(unscaled); + } + } + + @Override + public void writeNumber(String encodedValue) throws IOException, + JsonGenerationException, UnsupportedOperationException { + // just write as a String -- CBOR does not require schema, so + // databinding + // on receiving end should be able to coerce it appropriately + writeString(encodedValue); + } + + /* + /********************************************************** + /* Implementations for other methods + /********************************************************** + */ + + @Override + protected final void _verifyValueWrite(String typeMsg) throws IOException { + if (!_cborContext.writeValue()) { + _reportError("Can not " + typeMsg + ", expecting field name/id"); + } + // decrementElementsRemainingCount() + int count = _currentRemainingElements; + if (count != INDEFINITE_LENGTH) { + --count; + + // 28-Jun-2016, tatu: _Should_ check overrun immediately (instead of waiting + // for end of Object/Array), but has 10% performance penalty for some reason, + // should figure out why and how to avoid + if (count < 0) { + _failSizedArrayOrObject(); + return; // never gets here + } + _currentRemainingElements = count; + } + } + + private void _failSizedArrayOrObject() throws IOException + { + _reportError(String.format("%s size mismatch: number of element encoded is not equal to reported array/map size.", + _cborContext.typeDesc())); + } + + /* + /********************************************************** + /* Low-level output handling + /********************************************************** + */ + + @Override + public final void flush() throws IOException { + _flushBuffer(); + if (isEnabled(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM)) { + _out.flush(); + } + } + + @Override + public void close() throws IOException { + // First: let's see that we still have buffers... + if ((_outputBuffer != null) + && isEnabled(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT)) { + while (true) { + JsonStreamContext ctxt = getOutputContext(); + if (ctxt.inArray()) { + writeEndArray(); + } else if (ctxt.inObject()) { + writeEndObject(); + } else { + break; + } + } + } + // boolean wasClosed = _closed; + super.close(); + _flushBuffer(); + + if (_ioContext.isResourceManaged() + || isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET)) { + _out.close(); + } else if (isEnabled(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM)) { + // 14-Jan-2019, tatu: [dataformats-binary#155]: unless prevented via feature + // If we can't close it, we should at least flush + _out.flush(); + } + // Internal buffer(s) generator has can now be released as well + _releaseBuffers(); + } + + /* + /********************************************************** + * Extended API, CBOR-specific encoded output + /********************************************************** + */ + + /** + * Method for writing out an explicit CBOR Tag. + * + * @param tagId + * Positive integer (0 or higher) + * + * @since 2.5 + */ + public void writeTag(int tagId) throws IOException { + if (tagId < 0) { + throw new IllegalArgumentException( + "Can not write negative tag ids (" + tagId + ")"); + } + _writeLengthMarker(PREFIX_TYPE_TAG, tagId); + } + + /* + /********************************************************** + /* Extended API, raw bytes (by-passing encoder) + /********************************************************** + */ + + /** + * Method for directly inserting specified byte in output at current + * position. + *

+ * NOTE: only use this method if you really know what you are doing. + */ + public void writeRaw(byte b) throws IOException { + _writeByte(b); + } + + /** + * Method for directly inserting specified bytes in output at current + * position. + *

+ * NOTE: only use this method if you really know what you are doing. + */ + public void writeBytes(byte[] data, int offset, int len) throws IOException { + _writeBytes(data, offset, len); + } + + /* + /********************************************************** + /* Internal methods: low-level text output + /********************************************************** + */ + + private final static int MAX_SHORT_STRING_CHARS = 23; + // in case it's > 23 bytes + private final static int MAX_SHORT_STRING_BYTES = 23 * 3 + 2; + + private final static int MAX_MEDIUM_STRING_CHARS = 255; + // in case it's > 255 bytes + private final static int MAX_MEDIUM_STRING_BYTES = 255 * 3 + 3; + + protected final void _writeString(String name) throws IOException { + int len = name.length(); + if (len == 0) { + _writeByte(BYTE_EMPTY_STRING); + return; + } + // Actually, let's not bother with copy for shortest strings + if (len <= MAX_SHORT_STRING_CHARS) { + _ensureSpace(MAX_SHORT_STRING_BYTES); // can afford approximate + // length + int actual = _encode(_outputTail + 1, name, len); + final byte[] buf = _outputBuffer; + int ix = _outputTail; + if (actual <= MAX_SHORT_STRING_CHARS) { // fits in prefix byte + buf[ix++] = (byte) (PREFIX_TYPE_TEXT + actual); + _outputTail = ix + actual; + return; + } + // no, have to move. Blah. + System.arraycopy(buf, ix + 1, buf, ix + 2, actual); + buf[ix++] = BYTE_STRING_1BYTE_LEN; + buf[ix++] = (byte) actual; + _outputTail = ix + actual; + return; + } + + char[] cbuf = _charBuffer; + if (len > cbuf.length) { + _charBuffer = cbuf = new char[Math + .max(_charBuffer.length + 32, len)]; + } + name.getChars(0, len, cbuf, 0); + _writeString(cbuf, 0, len); + } + + protected final void _ensureSpace(int needed) throws IOException { + if ((_outputTail + needed + 3) > _outputEnd) { + _flushBuffer(); + } + } + + protected final void _writeString(char[] text, int offset, int len) + throws IOException + { + if (len <= MAX_SHORT_STRING_CHARS) { // possibly short string (not necessarily) + _ensureSpace(MAX_SHORT_STRING_BYTES); // can afford approximate length + int actual = _encode(_outputTail + 1, text, offset, offset + len); + final byte[] buf = _outputBuffer; + int ix = _outputTail; + if (actual <= MAX_SHORT_STRING_CHARS) { // fits in prefix byte + buf[ix++] = (byte) (PREFIX_TYPE_TEXT + actual); + _outputTail = ix + actual; + return; + } + // no, have to move. Blah. + System.arraycopy(buf, ix + 1, buf, ix + 2, actual); + buf[ix++] = BYTE_STRING_1BYTE_LEN; + buf[ix++] = (byte) actual; + _outputTail = ix + actual; + return; + } + if (len <= MAX_MEDIUM_STRING_CHARS) { + _ensureSpace(MAX_MEDIUM_STRING_BYTES); // short enough, can approximate + int actual = _encode(_outputTail + 2, text, offset, offset + len); + final byte[] buf = _outputBuffer; + int ix = _outputTail; + if (actual <= MAX_MEDIUM_STRING_CHARS) { // fits as expected + buf[ix++] = BYTE_STRING_1BYTE_LEN; + buf[ix++] = (byte) actual; + _outputTail = ix + actual; + return; + } + // no, have to move. Blah. + System.arraycopy(buf, ix + 2, buf, ix + 3, actual); + buf[ix++] = BYTE_STRING_2BYTE_LEN; + buf[ix++] = (byte) (actual >> 8); + buf[ix++] = (byte) actual; + _outputTail = ix + actual; + return; + } + if (len <= MAX_LONG_STRING_CHARS) { // no need to chunk yet + // otherwise, long but single chunk + _ensureSpace(MAX_LONG_STRING_BYTES); // calculate accurate length to + // avoid extra flushing + int ix = _outputTail; + int actual = _encode(ix + 3, text, offset, offset+len); + final byte[] buf = _outputBuffer; + buf[ix++] = BYTE_STRING_2BYTE_LEN; + buf[ix++] = (byte) (actual >> 8); + buf[ix++] = (byte) actual; + _outputTail = ix + actual; + return; + } + _writeChunkedString(text, offset, len); + } + + protected final void _writeChunkedString(char[] text, int offset, int len) + throws IOException + { + // need to use a marker first + _writeByte(BYTE_STRING_INDEFINITE); + + while (len > MAX_LONG_STRING_CHARS) { + _ensureSpace(MAX_LONG_STRING_BYTES); // marker and single-byte length? + int ix = _outputTail; + int amount = MAX_LONG_STRING_CHARS; + + // 23-May-2016, tatu: Make sure NOT to try to split surrogates in half + int end = offset + amount; + char c = text[end-1]; + if (c >= SURR1_FIRST && c <= SURR1_LAST) { + --end; + --amount; + } + int actual = _encode(_outputTail + 3, text, offset, end); + final byte[] buf = _outputBuffer; + buf[ix++] = BYTE_STRING_2BYTE_LEN; + buf[ix++] = (byte) (actual >> 8); + buf[ix++] = (byte) actual; + _outputTail = ix + actual; + offset += amount; + len -= amount; + } + // and for the last chunk, just use recursion + if (len > 0) { + _writeString(text, offset, len); + } + // plus end marker + _writeByte(BYTE_BREAK); + } + + /* + /********************************************************** + /* Internal methods, UTF-8 encoding + /********************************************************** + */ + + /** + * Helper method called when the whole character sequence is known to fit in + * the output buffer regardless of UTF-8 expansion. + */ + private final int _encode(int outputPtr, char[] str, int i, int end) { + // First: let's see if it's all ASCII: that's rather fast + final byte[] outBuf = _outputBuffer; + final int outputStart = outputPtr; + do { + int c = str[i]; + if (c > 0x7F) { + return _shortUTF8Encode2(str, i, end, outputPtr, outputStart); + } + outBuf[outputPtr++] = (byte) c; + } while (++i < end); + return outputPtr - outputStart; + } + + /** + * Helper method called when the whole character sequence is known to fit in + * the output buffer, but not all characters are single-byte (ASCII) + * characters. + */ + private final int _shortUTF8Encode2(char[] str, int i, int end, + int outputPtr, int outputStart) { + final byte[] outBuf = _outputBuffer; + while (i < end) { + int c = str[i++]; + if (c <= 0x7F) { + outBuf[outputPtr++] = (byte) c; + continue; + } + // Nope, multi-byte: + if (c < 0x800) { // 2-byte + outBuf[outputPtr++] = (byte) (0xc0 | (c >> 6)); + outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f)); + continue; + } + // 3 or 4 bytes (surrogate) + // Surrogates? + if (c < SURR1_FIRST || c > SURR2_LAST) { // nope, regular 3-byte character + outBuf[outputPtr++] = (byte) (0xe0 | (c >> 12)); + outBuf[outputPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); + outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f)); + continue; + } + // Yup, a surrogate pair + if (c > SURR1_LAST) { // must be from first range; second won't do + _throwIllegalSurrogate(c); + } + // ... meaning it must have a pair + if (i >= end) { + _throwIllegalSurrogate(c); + } + c = _convertSurrogate(c, str[i++]); + if (c > 0x10FFFF) { // illegal in JSON as well as in XML + _throwIllegalSurrogate(c); + } + outBuf[outputPtr++] = (byte) (0xf0 | (c >> 18)); + outBuf[outputPtr++] = (byte) (0x80 | ((c >> 12) & 0x3f)); + outBuf[outputPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); + outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f)); + } + return (outputPtr - outputStart); + } + + private final int _encode(int outputPtr, String str, int len) { + final byte[] outBuf = _outputBuffer; + final int outputStart = outputPtr; + + for (int i = 0; i < len; ++i) { + int c = str.charAt(i); + if (c > 0x7F) { + return _encode2(i, outputPtr, str, len, outputStart); + } + outBuf[outputPtr++] = (byte) c; + } + return (outputPtr - outputStart); + } + + private final int _encode2(int i, int outputPtr, String str, int len, + int outputStart) { + final byte[] outBuf = _outputBuffer; + // no; non-ASCII stuff, slower loop + while (i < len) { + int c = str.charAt(i++); + if (c <= 0x7F) { + outBuf[outputPtr++] = (byte) c; + continue; + } + // Nope, multi-byte: + if (c < 0x800) { // 2-byte + outBuf[outputPtr++] = (byte) (0xc0 | (c >> 6)); + outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f)); + continue; + } + // 3 or 4 bytes (surrogate) + // Surrogates? + if (c < SURR1_FIRST || c > SURR2_LAST) { // nope, regular 3-byte + // character + outBuf[outputPtr++] = (byte) (0xe0 | (c >> 12)); + outBuf[outputPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); + outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f)); + continue; + } + // Yup, a surrogate pair + if (c > SURR1_LAST) { // must be from first range; second won't do + _throwIllegalSurrogate(c); + } + // ... meaning it must have a pair + if (i >= len) { + _throwIllegalSurrogate(c); + } + c = _convertSurrogate(c, str.charAt(i++)); + if (c > 0x10FFFF) { // illegal in JSON as well as in XML + _throwIllegalSurrogate(c); + } + outBuf[outputPtr++] = (byte) (0xf0 | (c >> 18)); + outBuf[outputPtr++] = (byte) (0x80 | ((c >> 12) & 0x3f)); + outBuf[outputPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); + outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f)); + } + return (outputPtr - outputStart); + } + + /** + * Method called to calculate UTF codepoint, from a surrogate pair. + */ + private int _convertSurrogate(int firstPart, int secondPart) { + // Ok, then, is the second part valid? + if (secondPart < SURR2_FIRST || secondPart > SURR2_LAST) { + throw new IllegalArgumentException( + "Broken surrogate pair: first char 0x" + + Integer.toHexString(firstPart) + ", second 0x" + + Integer.toHexString(secondPart) + + "; illegal combination"); + } + return 0x10000 + ((firstPart - SURR1_FIRST) << 10) + + (secondPart - SURR2_FIRST); + } + + private void _throwIllegalSurrogate(int code) { + if (code > 0x10FFFF) { // over max? + throw new IllegalArgumentException("Illegal character point (0x" + + Integer.toHexString(code) + + ") to output; max is 0x10FFFF as per RFC 4627"); + } + if (code >= SURR1_FIRST) { + if (code <= SURR1_LAST) { // Unmatched first part (closing without + // second part?) + throw new IllegalArgumentException( + "Unmatched first part of surrogate pair (0x" + + Integer.toHexString(code) + ")"); + } + throw new IllegalArgumentException( + "Unmatched second part of surrogate pair (0x" + + Integer.toHexString(code) + ")"); + } + // should we ever get this? + throw new IllegalArgumentException("Illegal character point (0x" + + Integer.toHexString(code) + ") to output"); + } + + /* + /********************************************************** + /* Internal methods, writing bytes + /********************************************************** + */ + + private final void _ensureRoomForOutput(int needed) throws IOException { + if ((_outputTail + needed) >= _outputEnd) { + _flushBuffer(); + } + } + + private final void _writeIntValue(int i) throws IOException { + int marker; + if (i < 0) { + i = -i - 1; + marker = PREFIX_TYPE_INT_NEG; + } else { + marker = PREFIX_TYPE_INT_POS; + } + _writeLengthMarker(marker, i); + } + + private final void _writeLongValue(long l) throws IOException { + _ensureRoomForOutput(9); + if (l < 0) { + l += 1; + l = -l; + _outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_NEG + SUFFIX_UINT64_ELEMENTS); + } else { + _outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_POS + SUFFIX_UINT64_ELEMENTS); + } + int i = (int) (l >> 32); + _outputBuffer[_outputTail++] = (byte) (i >> 24); + _outputBuffer[_outputTail++] = (byte) (i >> 16); + _outputBuffer[_outputTail++] = (byte) (i >> 8); + _outputBuffer[_outputTail++] = (byte) i; + i = (int) l; + _outputBuffer[_outputTail++] = (byte) (i >> 24); + _outputBuffer[_outputTail++] = (byte) (i >> 16); + _outputBuffer[_outputTail++] = (byte) (i >> 8); + _outputBuffer[_outputTail++] = (byte) i; + } + + private final void _writeLengthMarker(int majorType, int i) + throws IOException { + _ensureRoomForOutput(5); + if (i < 24) { + _outputBuffer[_outputTail++] = (byte) (majorType + i); + return; + } + if (i <= 0xFF) { + _outputBuffer[_outputTail++] = (byte) (majorType + SUFFIX_UINT8_ELEMENTS); + _outputBuffer[_outputTail++] = (byte) i; + return; + } + final byte b0 = (byte) i; + i >>= 8; + if (i <= 0xFF) { + _outputBuffer[_outputTail++] = (byte) (majorType + SUFFIX_UINT16_ELEMENTS); + _outputBuffer[_outputTail++] = (byte) i; + _outputBuffer[_outputTail++] = b0; + return; + } + _outputBuffer[_outputTail++] = (byte) (majorType + SUFFIX_UINT32_ELEMENTS); + _outputBuffer[_outputTail++] = (byte) (i >> 16); + _outputBuffer[_outputTail++] = (byte) (i >> 8); + _outputBuffer[_outputTail++] = (byte) i; + _outputBuffer[_outputTail++] = b0; + } + + private final void _writeByte(byte b) throws IOException { + if (_outputTail >= _outputEnd) { + _flushBuffer(); + } + _outputBuffer[_outputTail++] = b; + } + + /* + * private final void _writeBytes(byte b1, byte b2) throws IOException { if + * ((_outputTail + 1) >= _outputEnd) { _flushBuffer(); } + * _outputBuffer[_outputTail++] = b1; _outputBuffer[_outputTail++] = b2; } + */ + + private final void _writeBytes(byte[] data, int offset, int len) + throws IOException { + if (len == 0) { + return; + } + if ((_outputTail + len) >= _outputEnd) { + _writeBytesLong(data, offset, len); + return; + } + // common case, non-empty, fits in just fine: + System.arraycopy(data, offset, _outputBuffer, _outputTail, len); + _outputTail += len; + } + + private final int _writeBytes(InputStream in, int bytesLeft) + throws IOException { + while (bytesLeft > 0) { + int room = _outputEnd - _outputTail; + if (room <= 0) { + _flushBuffer(); + room = _outputEnd - _outputTail; + } + int count = in.read(_outputBuffer, _outputTail, room); + if (count < 0) { + break; + } + _outputTail += count; + bytesLeft -= count; + } + return bytesLeft; + } + + private final void _writeBytesLong(byte[] data, int offset, int len) + throws IOException { + if (_outputTail >= _outputEnd) { + _flushBuffer(); + } + while (true) { + int currLen = Math.min(len, (_outputEnd - _outputTail)); + System.arraycopy(data, offset, _outputBuffer, _outputTail, currLen); + _outputTail += currLen; + if ((len -= currLen) == 0) { + break; + } + offset += currLen; + _flushBuffer(); + } + } + + /* + /********************************************************** + /* Internal methods, buffer handling + /********************************************************** + */ + + @Override + protected void _releaseBuffers() { + byte[] buf = _outputBuffer; + if (buf != null && _bufferRecyclable) { + _outputBuffer = null; + _ioContext.releaseWriteEncodingBuffer(buf); + } + char[] cbuf = _charBuffer; + if (cbuf != null) { + _charBuffer = null; + _ioContext.releaseConcatBuffer(cbuf); + } + } + + protected final void _flushBuffer() throws IOException { + if (_outputTail > 0) { + _bytesWritten += _outputTail; + _out.write(_outputBuffer, 0, _outputTail); + _outputTail = 0; + } + } + + /* + /********************************************************** + /* Internal methods, size control for array and objects + /********************************************************** + */ + + private final void closeComplexElement() throws IOException { + switch (_currentRemainingElements) { + case INDEFINITE_LENGTH: + _writeByte(BYTE_BREAK); + break; + case 0: // expected for sized ones + break; + default: + _reportError(String.format("%s size mismatch: expected %d more elements", + _cborContext.typeDesc(), _currentRemainingElements)); + } + _currentRemainingElements = (_elementCountsPtr == 0) + ? INDEFINITE_LENGTH + : _elementCounts[--_elementCountsPtr]; + } + + /* + /********************************************************** + /* Internal methods, error reporting + /********************************************************** + */ + + protected UnsupportedOperationException _notSupported() { + return new UnsupportedOperationException(); + } +} diff --git a/Java/CPManagerImpl.java b/Java/CPManagerImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..415c4c2a3d2b7591e8936fcfb626a27953c5d216 --- /dev/null +++ b/Java/CPManagerImpl.java @@ -0,0 +1,343 @@ +/** +* OLAT - Online Learning and Training
+* http://www.olat.org +*

+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at +*

+* http://www.apache.org/licenses/LICENSE-2.0 +*

+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License. +*

+* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),
+* University of Zurich, Switzerland. +*


+* +* OpenOLAT - Online Learning and Training
+* This file has been modified by the OpenOLAT community. Changes are licensed +* under the Apache 2.0 license as the original file. +*

+*/ + +package org.olat.ims.cp; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URISyntaxException; +import java.net.URL; + +import org.apache.logging.log4j.Logger; +import org.dom4j.tree.DefaultDocument; +import org.dom4j.tree.DefaultElement; +import org.olat.core.gui.control.generic.iframe.DeliveryOptions; +import org.olat.core.id.OLATResourceable; +import org.olat.core.logging.OLATRuntimeException; +import org.olat.core.logging.Tracing; +import org.olat.core.util.CodeHelper; +import org.olat.core.util.FileUtils; +import org.olat.core.util.vfs.LocalFolderImpl; +import org.olat.core.util.vfs.VFSContainer; +import org.olat.core.util.vfs.VFSItem; +import org.olat.core.util.vfs.VFSLeaf; +import org.olat.core.util.vfs.VFSManager; +import org.olat.core.util.xml.XMLParser; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.fileresource.FileResourceManager; +import org.olat.ims.cp.objects.CPOrganization; +import org.olat.ims.cp.objects.CPResource; +import org.olat.ims.cp.ui.CPPackageConfig; +import org.olat.ims.cp.ui.CPPage; +import org.olat.repository.RepositoryEntry; +import org.olat.repository.RepositoryManager; +import org.springframework.stereotype.Service; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.security.ExplicitTypePermission; + +/** + * The CP manager implementation. + *

+ * In many cases, method calls are delegated to the content package object. + * + *

+ * Initial Date: 04.07.2008
+ * + * @author Sergio Trentini + */ +@Service("org.olat.ims.cp.CPManager") +public class CPManagerImpl implements CPManager { + + private static final Logger log = Tracing.createLoggerFor(CPManagerImpl.class); + + public static final String PACKAGE_CONFIG_FILE_NAME = "CPPackageConfig.xml"; + + private static XStream configXstream = XStreamHelper.createXStreamInstance(); + static { + Class[] types = new Class[] { + CPPackageConfig.class, DeliveryOptions.class + }; + // BUG: CWE-91 XML Injection (aka Blind XPath Injection) + // XStream.setupDefaultSecurity(configXstream); + // FIXED: + configXstream.addPermission(new ExplicitTypePermission(types)); + configXstream.alias("packageConfig", CPPackageConfig.class); + configXstream.alias("deliveryOptions", DeliveryOptions.class); + } + + @Override + public CPPackageConfig getCPPackageConfig(OLATResourceable ores) { + FileResourceManager frm = FileResourceManager.getInstance(); + File reFolder = frm.getFileResourceRoot(ores); + File configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME); + + CPPackageConfig config; + if(configXml.exists()) { + config = (CPPackageConfig)configXstream.fromXML(configXml); + } else { + //set default config + config = new CPPackageConfig(); + config.setDeliveryOptions(DeliveryOptions.defaultWithGlossary()); + setCPPackageConfig(ores, config); + } + return config; + } + + @Override + public void setCPPackageConfig(OLATResourceable ores, CPPackageConfig config) { + FileResourceManager frm = FileResourceManager.getInstance(); + File reFolder = frm.getFileResourceRoot(ores); + File configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME); + if(config == null) { + FileUtils.deleteFile(configXml); + } else { + try(OutputStream out = new FileOutputStream(configXml)) { + configXstream.toXML(config, out); + } catch (IOException e) { + log.error("", e); + } + } + } + + @Override + public ContentPackage load(VFSContainer directory, OLATResourceable ores) { + ContentPackage cp; + VFSItem file = directory.resolve("imsmanifest.xml"); + if (file instanceof VFSLeaf) { + try(InputStream in = ((VFSLeaf)file).getInputStream()) { + XMLParser parser = new XMLParser(); + DefaultDocument doc = (DefaultDocument) parser.parse(in, false); + cp = new ContentPackage(doc, directory, ores); + // If a wiki is imported or a new cp created, set a unique orga + // identifier. + if (cp.getLastError() == null && cp.isOLATContentPackage() + && CPCore.OLAT_ORGANIZATION_IDENTIFIER.equals(cp.getFirstOrganizationInManifest().getIdentifier())) { + setUniqueOrgaIdentifier(cp); + } + } catch (IOException | OLATRuntimeException e) { + cp = new ContentPackage(null, directory, ores); + log.error("Reading imsmanifest failed. Dir: " + directory.getName() + ". Ores: " + ores.getResourceableId(), e); + cp.setLastError("Exception reading XML for IMS CP: invalid xml-file ( " + directory.getName() + ")"); + } + } else { + cp = new ContentPackage(null, directory, ores); + cp.setLastError("Exception reading XML for IMS CP: IMS-Manifest not found in " + directory.getName()); + log.error("IMS manifiest xml couldn't be found in dir {}. Ores: {}", directory.getName(), ores.getResourceableId()); + throw new OLATRuntimeException(CPManagerImpl.class, "The imsmanifest.xml file was not found.", new IOException()); + } + return cp; + } + + @Override + public ContentPackage createNewCP(OLATResourceable ores, String initalPageTitle) { + // copy template cp to new repo-location + if (copyTemplCP(ores)) { + File cpRoot = FileResourceManager.getInstance().unzipFileResource(ores); + if(log.isDebugEnabled()) { + log.debug("createNewCP: cpRoot={}", cpRoot); + log.debug("createNewCP: cpRoot.getAbsolutePath()={}", cpRoot.getAbsolutePath()); + } + + LocalFolderImpl vfsWrapper = new LocalFolderImpl(cpRoot); + ContentPackage cp = load(vfsWrapper, ores); + + // Modify the copy of the template to get a unique identifier + CPOrganization orga = setUniqueOrgaIdentifier(cp); + setOrgaTitleToRepoEntryTitle(ores, orga); + // Also set the translated title of the inital page. + orga.getItems().get(0).setTitle(initalPageTitle); + + writeToFile(cp); + + //set the default settings for file delivery + DeliveryOptions defOptions = DeliveryOptions.defaultWithGlossary(); + CPPackageConfig config = new CPPackageConfig(); + config.setDeliveryOptions(defOptions); + setCPPackageConfig(ores, config); + + return cp; + + } else { + log.error("CP couldn't be created. Error when copying template. Ores: {}", ores.getResourceableId()); + throw new OLATRuntimeException("ERROR while creating new empty cp. an error occured while trying to copy template CP", null); + } + } + + /** + * Sets the organization title to the title of the repository entry. + * + * @param ores + * @param orga + */ + private void setOrgaTitleToRepoEntryTitle(OLATResourceable ores, CPOrganization orga) { + // Set the title of the organization to the title of the resource. + RepositoryManager resMgr = RepositoryManager.getInstance(); + RepositoryEntry cpEntry = resMgr.lookupRepositoryEntry(ores, false); + if (cpEntry != null) { + String title = cpEntry.getDisplayname(); + orga.setTitle(title); + } + } + + /** + * Assigns the organization a unique identifier in order to prevent any + * caching issues in the extjs menu tree later. + * + * @param cp + * @return The first organization of the content package. + */ + private CPOrganization setUniqueOrgaIdentifier(ContentPackage cp) { + CPOrganization orga = cp.getFirstOrganizationInManifest(); + String newOrgaIdentifier = "olatcp-" + CodeHelper.getForeverUniqueID(); + orga.setIdentifier(newOrgaIdentifier); + return orga; + } + + @Override + public boolean isSingleUsedResource(CPResource res, ContentPackage cp) { + return cp.isSingleUsedResource(res); + } + + @Override + public String addBlankPage(ContentPackage cp, String title) { + return cp.addBlankPage(title); + } + + @Override + public String addBlankPage(ContentPackage cp, String title, String parentNodeID) { + return cp.addBlankPage(parentNodeID, title); + } + + @Override + public void updatePage(ContentPackage cp, CPPage page) { + cp.updatePage(page); + } + + @Override + public boolean addElement(ContentPackage cp, DefaultElement newElement) { + return cp.addElement(newElement); + + } + + @Override + public boolean addElement(ContentPackage cp, DefaultElement newElement, String parentIdentifier, int position) { + return cp.addElement(newElement, parentIdentifier, position); + } + + @Override + public boolean addElementAfter(ContentPackage cp, DefaultElement newElement, String identifier) { + return cp.addElementAfter(newElement, identifier); + } + + @Override + public void removeElement(ContentPackage cp, String identifier, boolean deleteResource) { + cp.removeElement(identifier, deleteResource); + } + + @Override + public void moveElement(ContentPackage cp, String nodeID, String newParentID, int position) { + cp.moveElement(nodeID, newParentID, position); + } + + @Override + public String copyElement(ContentPackage cp, String sourceID) { + return cp.copyElement(sourceID, sourceID); + } + + @Override + public DefaultDocument getDocument(ContentPackage cp) { + return cp.getDocument(); + } + + @Override + public String getItemTitle(ContentPackage cp, String itemID) { + return cp.getItemTitle(itemID); + } + + @Override + public DefaultElement getElementByIdentifier(ContentPackage cp, String identifier) { + return cp.getElementByIdentifier(identifier); + } + + @Override + public CPTreeDataModel getTreeDataModel(ContentPackage cp) { + return cp.buildTreeDataModel(); + } + + @Override + public CPOrganization getFirstOrganizationInManifest(ContentPackage cp) { + return cp.getFirstOrganizationInManifest(); + } + + @Override + public CPPage getFirstPageToDisplay(ContentPackage cp) { + return cp.getFirstPageToDisplay(); + } + + @Override + public void writeToFile(ContentPackage cp) { + cp.writeToFile(); + } + + @Override + public String getPageByItemId(ContentPackage cp, String itemIdentifier) { + return cp.getPageByItemId(itemIdentifier); + } + + /** + * copies the default,empty, cp template to the new ores-directory + * + * @param ores + * @return + */ + private boolean copyTemplCP(OLATResourceable ores) { + File root = FileResourceManager.getInstance().getFileResourceRoot(ores); + + String packageName = ContentPackage.class.getCanonicalName(); + String path = packageName.replace('.', '/'); + path = path.replace("/ContentPackage", "/_resources/imscp.zip"); + + path = VFSManager.sanitizePath(path); + URL url = this.getClass().getResource(path); + try { + File f = new File(url.toURI()); + if (f.exists() && root.exists()) { + FileUtils.copyFileToDir(f, root, "copy imscp template"); + } else { + log.error("cp template was not copied. Source: {} Target: {}", url, root.getAbsolutePath()); + } + } catch (URISyntaxException e) { + log.error("Bad url syntax when copying cp template. url: {} Ores: {}", url, ores.getResourceableId()); + return false; + } + + return true; + } +} diff --git a/Java/Cas20ServiceTicketValidator.java b/Java/Cas20ServiceTicketValidator.java new file mode 100644 index 0000000000000000000000000000000000000000..43a1483a2c60d365e2b41b12aaa0b320cf3e906c --- /dev/null +++ b/Java/Cas20ServiceTicketValidator.java @@ -0,0 +1,252 @@ +/* + * Licensed to Jasig under one or more contributor license + * agreements. See the NOTICE file distributed with this work + * for additional information regarding copyright ownership. + * Jasig 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 the following location: + * + * 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.jasig.cas.client.validation; + +import java.io.StringReader; +import java.util.*; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import org.jasig.cas.client.authentication.AttributePrincipal; +import org.jasig.cas.client.authentication.AttributePrincipalImpl; +import org.jasig.cas.client.proxy.Cas20ProxyRetriever; +import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage; +import org.jasig.cas.client.proxy.ProxyRetriever; +import org.jasig.cas.client.util.CommonUtils; +import org.jasig.cas.client.util.XmlUtils; +import org.xml.sax.Attributes; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.DefaultHandler; + +/** + * Implementation of the TicketValidator that will validate Service Tickets in compliance with the CAS 2. + * + * @author Scott Battaglia + * @since 3.1 + */ +public class Cas20ServiceTicketValidator extends AbstractCasProtocolUrlBasedTicketValidator { + + /** The CAS 2.0 protocol proxy callback url. */ + private String proxyCallbackUrl; + + /** The storage location of the proxy granting tickets. */ + private ProxyGrantingTicketStorage proxyGrantingTicketStorage; + + /** Implementation of the proxy retriever. */ + private ProxyRetriever proxyRetriever; + + /** + * Constructs an instance of the CAS 2.0 Service Ticket Validator with the supplied + * CAS server url prefix. + * + * @param casServerUrlPrefix the CAS Server URL prefix. + * @param urlFactory URL connection factory to use when communicating with the server + */ + public Cas20ServiceTicketValidator(final String casServerUrlPrefix) { + super(casServerUrlPrefix); + this.proxyRetriever = new Cas20ProxyRetriever(casServerUrlPrefix, getEncoding(), getURLConnectionFactory()); + } + + /** + * Adds the pgtUrl to the list of parameters to pass to the CAS server. + * + * @param urlParameters the Map containing the existing parameters to send to the server. + */ + protected final void populateUrlAttributeMap(final Map urlParameters) { + // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') + // urlParameters.put("pgtUrl", encodeUrl(this.proxyCallbackUrl)); + // FIXED: + urlParameters.put("pgtUrl", this.proxyCallbackUrl); + } + + protected String getUrlSuffix() { + return "serviceValidate"; + } + + protected final Assertion parseResponseFromServer(final String response) throws TicketValidationException { + final String error = XmlUtils.getTextForElement(response, "authenticationFailure"); + + if (CommonUtils.isNotBlank(error)) { + throw new TicketValidationException(error); + } + + final String principal = XmlUtils.getTextForElement(response, "user"); + final String proxyGrantingTicketIou = XmlUtils.getTextForElement(response, "proxyGrantingTicket"); + + final String proxyGrantingTicket; + if (CommonUtils.isBlank(proxyGrantingTicketIou) || this.proxyGrantingTicketStorage == null) { + proxyGrantingTicket = null; + } else { + proxyGrantingTicket = this.proxyGrantingTicketStorage.retrieve(proxyGrantingTicketIou); + } + + if (CommonUtils.isEmpty(principal)) { + throw new TicketValidationException("No principal was found in the response from the CAS server."); + } + + final Assertion assertion; + final Map attributes = extractCustomAttributes(response); + if (CommonUtils.isNotBlank(proxyGrantingTicket)) { + final AttributePrincipal attributePrincipal = new AttributePrincipalImpl(principal, attributes, + proxyGrantingTicket, this.proxyRetriever); + assertion = new AssertionImpl(attributePrincipal); + } else { + assertion = new AssertionImpl(new AttributePrincipalImpl(principal, attributes)); + } + + customParseResponse(response, assertion); + + return assertion; + } + + /** + * Default attribute parsing of attributes that look like the following: + * <cas:attributes> + * <cas:attribute1>value</cas:attribute1> + * <cas:attribute2>value</cas:attribute2> + * </cas:attributes> + *

+ * + * Attributes look like following also parsed correctly: + * <cas:attributes><cas:attribute1>value</cas:attribute1><cas:attribute2>value</cas:attribute2></cas:attributes> + *

+ * + * This code is here merely for sample/demonstration purposes for those wishing to modify the CAS2 protocol. You'll + * probably want a more robust implementation or to use SAML 1.1 + * + * @param xml the XML to parse. + * @return the map of attributes. + */ + protected Map extractCustomAttributes(final String xml) { + final SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setValidating(false); + try { + final SAXParser saxParser = spf.newSAXParser(); + final XMLReader xmlReader = saxParser.getXMLReader(); + final CustomAttributeHandler handler = new CustomAttributeHandler(); + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(new StringReader(xml))); + return handler.getAttributes(); + } catch (final Exception e) { + logger.error(e.getMessage(), e); + return Collections.emptyMap(); + } + } + + /** + * Template method if additional custom parsing (such as Proxying) needs to be done. + * + * @param response the original response from the CAS server. + * @param assertion the partially constructed assertion. + * @throws TicketValidationException if there is a problem constructing the Assertion. + */ + protected void customParseResponse(final String response, final Assertion assertion) + throws TicketValidationException { + // nothing to do + } + + public final void setProxyCallbackUrl(final String proxyCallbackUrl) { + this.proxyCallbackUrl = proxyCallbackUrl; + } + + public final void setProxyGrantingTicketStorage(final ProxyGrantingTicketStorage proxyGrantingTicketStorage) { + this.proxyGrantingTicketStorage = proxyGrantingTicketStorage; + } + + public final void setProxyRetriever(final ProxyRetriever proxyRetriever) { + this.proxyRetriever = proxyRetriever; + } + + protected final String getProxyCallbackUrl() { + return this.proxyCallbackUrl; + } + + protected final ProxyGrantingTicketStorage getProxyGrantingTicketStorage() { + return this.proxyGrantingTicketStorage; + } + + protected final ProxyRetriever getProxyRetriever() { + return this.proxyRetriever; + } + + private class CustomAttributeHandler extends DefaultHandler { + + private Map attributes; + + private boolean foundAttributes; + + private String currentAttribute; + + private StringBuilder value; + + @Override + public void startDocument() throws SAXException { + this.attributes = new HashMap(); + } + + @Override + public void startElement(final String namespaceURI, final String localName, final String qName, + final Attributes attributes) throws SAXException { + if ("attributes".equals(localName)) { + this.foundAttributes = true; + } else if (this.foundAttributes) { + this.value = new StringBuilder(); + this.currentAttribute = localName; + } + } + + @Override + public void characters(final char[] chars, final int start, final int length) throws SAXException { + if (this.currentAttribute != null) { + value.append(chars, start, length); + } + } + + @Override + public void endElement(final String namespaceURI, final String localName, final String qName) + throws SAXException { + if ("attributes".equals(localName)) { + this.foundAttributes = false; + this.currentAttribute = null; + } else if (this.foundAttributes) { + final Object o = this.attributes.get(this.currentAttribute); + + if (o == null) { + this.attributes.put(this.currentAttribute, this.value.toString()); + } else { + final List items; + if (o instanceof List) { + items = (List) o; + } else { + items = new LinkedList(); + items.add(o); + this.attributes.put(this.currentAttribute, items); + } + items.add(this.value.toString()); + } + } + } + + public Map getAttributes() { + return this.attributes; + } + } +} diff --git a/Java/ChangeEMailExecuteController.java b/Java/ChangeEMailExecuteController.java new file mode 100644 index 0000000000000000000000000000000000000000..a901e4e504f9fcbcfc8872b6a94d322fd158f832 --- /dev/null +++ b/Java/ChangeEMailExecuteController.java @@ -0,0 +1,155 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * BPS Bildungsportal Sachsen GmbH, http://www.bps-system.de + *

+ */ +package de.bps.olat.user; + +import java.util.HashMap; + +import org.olat.basesecurity.BaseSecurity; +import org.olat.core.gui.UserRequest; +import org.olat.core.gui.control.WindowControl; +import org.olat.core.gui.translator.Translator; +import org.olat.core.id.Identity; +import org.olat.core.id.User; +import org.olat.core.util.StringHelper; +import org.olat.core.util.Util; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.home.HomeMainController; +import org.olat.login.SupportsAfterLoginInterceptor; +import org.olat.user.ProfileAndHomePageEditController; +import org.olat.user.UserManager; +import org.springframework.beans.factory.annotation.Autowired; + +import com.thoughtworks.xstream.XStream; + +/** + * + * Description:
+ * This controller do change the email from a user after he has clicked a link in email. + * + *

+ * Initial Date: 19.05.2009
+ * @author bja + */ +public class ChangeEMailExecuteController extends ChangeEMailController implements SupportsAfterLoginInterceptor { + + private static final String PRESENTED_EMAIL_CHANGE_REMINDER = "presentedemailchangereminder"; + + protected static final String PACKAGE_HOME = ProfileAndHomePageEditController.class.getPackage().getName(); + + @Autowired + private UserManager userManager; + @Autowired + private BaseSecurity securityManager; + + public ChangeEMailExecuteController(UserRequest ureq, WindowControl wControl) { + super(ureq, wControl); + this.userRequest = ureq; + pT = Util.createPackageTranslator(ProfileAndHomePageEditController.class, userRequest.getLocale()); + pT = userManager.getPropertyHandlerTranslator(pT); + emKey = userRequest.getHttpReq().getParameter("key"); + if (emKey == null) { + emKey = userRequest.getIdentity().getUser().getProperty("emchangeKey", null); + } + if (emKey != null) { + // key exist + // we check if given key is a valid temporary key + tempKey = rm.loadTemporaryKeyByRegistrationKey(emKey); + } + } + + @Override + public boolean isUserInteractionRequired(UserRequest ureq) { + User user = ureq.getIdentity().getUser(); + if(StringHelper.containsNonWhitespace(user.getProperty("emchangeKey", null))) { + if (isLinkTimeUp()) { + deleteRegistrationKey(); + } else { + if (isLinkClicked()) { + changeEMail(getWindowControl()); + } else { + Boolean alreadySeen = ((Boolean)ureq.getUserSession().getEntry(PRESENTED_EMAIL_CHANGE_REMINDER)); + if (alreadySeen == null) { + getWindowControl().setWarning(getPackageTranslator().translate("email.change.reminder")); + ureq.getUserSession().putEntry(PRESENTED_EMAIL_CHANGE_REMINDER, Boolean.TRUE); + } + } + } + } else { + String value = user.getProperty("emailDisabled", null); + if (value != null && value.equals("true")) { + Translator translator = Util.createPackageTranslator(HomeMainController.class, ureq.getLocale()); + getWindowControl().setWarning(translator.translate("email.disabled")); + } + } + return false; + } + + /** + * change email + * @param wControl + * @return + */ + public boolean changeEMail(WindowControl wControl) { + XStream xml = XStreamHelper.createXStreamInstance(); + // BUG: CWE-91 XML Injection (aka Blind XPath Injection) + // + // FIXED: + XStreamHelper.allowDefaultPackage(xml); + @SuppressWarnings("unchecked") + HashMap mails = (HashMap) xml.fromXML(tempKey.getEmailAddress()); + + Identity identity = securityManager.loadIdentityByKey(tempKey.getIdentityKey()); + if (identity != null) { + String oldEmail = identity.getUser().getEmail(); + identity.getUser().setProperty("email", mails.get("changedEMail")); + // if old mail address closed then set the new mail address + // unclosed + String value = identity.getUser().getProperty("emailDisabled", null); + if (value != null && value.equals("true")) { + identity.getUser().setProperty("emailDisabled", "false"); + } + identity.getUser().setProperty("email", mails.get("changedEMail")); + // success info message + String currentEmailDisplay = userManager.getUserDisplayEmail(mails.get("currentEMail"), userRequest.getLocale()); + String changedEmailDisplay = userManager.getUserDisplayEmail(mails.get("changedEMail"), userRequest.getLocale()); + wControl.setInfo(pT.translate("success.change.email", new String[] { currentEmailDisplay, changedEmailDisplay })); + // remove keys + identity.getUser().setProperty("emchangeKey", null); + userRequest.getUserSession().removeEntryFromNonClearedStore(ChangeEMailController.CHANGE_EMAIL_ENTRY); + securityManager.deleteInvalidAuthenticationsByEmail(oldEmail); + } else { + // error message + wControl.setWarning(pT.translate("error.change.email.unexpected", new String[] { mails.get("currentEMail"), mails.get("changedEMail") })); + } + // delete registration key + rm.deleteTemporaryKeyWithId(tempKey.getRegistrationKey()); + + return true; + } + + public boolean isLinkClicked() { + Object entry = userRequest.getUserSession().getEntry(ChangeEMailController.CHANGE_EMAIL_ENTRY); + return (entry != null); + } + + public Translator getPackageTranslator() { + return pT; + } +} diff --git a/Java/ClasspathResourceHelper.java b/Java/ClasspathResourceHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..540a6c07f60f96d245543e089899cb9c84480671 --- /dev/null +++ b/Java/ClasspathResourceHelper.java @@ -0,0 +1,403 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package com.sun.faces.application.resource; + +import static com.sun.faces.config.WebConfiguration.META_INF_CONTRACTS_DIR; +import static com.sun.faces.config.WebConfiguration.BooleanWebContextInitParameter.CacheResourceModificationTimestamp; +import static com.sun.faces.config.WebConfiguration.BooleanWebContextInitParameter.EnableMissingResourceLibraryDetection; +import static javax.faces.application.ProjectStage.Development; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.faces.application.ProjectStage; +import javax.faces.component.UIViewRoot; +import javax.faces.context.FacesContext; +import javax.faces.view.facelets.ResourceResolver; + +import com.sun.faces.config.WebConfiguration; +import com.sun.faces.facelets.impl.DefaultResourceResolver; +import com.sun.faces.util.Util; + + +/** + *

+ * A {@link ResourceHelper} implementation for finding/serving resources + * found on the classpath within the META-INF/resources directory. + *

+ * + * @since 2.0 + */ +public class ClasspathResourceHelper extends ResourceHelper { + + + private static final String BASE_RESOURCE_PATH = "META-INF/resources"; + private boolean cacheTimestamp; + private volatile ZipDirectoryEntryScanner libraryScanner; + private boolean enableMissingResourceLibraryDetection; + + + + // ------------------------------------------------------------ Constructors + + + public ClasspathResourceHelper() { + + WebConfiguration webconfig = WebConfiguration.getInstance(); + cacheTimestamp = webconfig.isOptionEnabled(CacheResourceModificationTimestamp); + enableMissingResourceLibraryDetection = + webconfig.isOptionEnabled(EnableMissingResourceLibraryDetection); + + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ClasspathResourceHelper other = (ClasspathResourceHelper) obj; + if (this.cacheTimestamp != other.cacheTimestamp) { + return false; + } + if (this.enableMissingResourceLibraryDetection != other.enableMissingResourceLibraryDetection) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int hash = 5; + hash = 67 * hash + (this.cacheTimestamp ? 1 : 0); + hash = 67 * hash + (this.enableMissingResourceLibraryDetection ? 1 : 0); + return hash; + } + + + + // --------------------------------------------- Methods from ResourceHelper + + + /** + * @see com.sun.faces.application.resource.ResourceHelper#getBaseResourcePath() + */ + @Override + public String getBaseResourcePath() { + return BASE_RESOURCE_PATH; + } + + @Override + public String getBaseContractsPath() { + return META_INF_CONTRACTS_DIR; + } + + /** + * @see ResourceHelper#getNonCompressedInputStream(com.sun.faces.application.resource.ResourceInfo, javax.faces.context.FacesContext) + */ + @Override + protected InputStream getNonCompressedInputStream(ResourceInfo resource, FacesContext ctx) throws IOException { + + InputStream in = null; + + if (ctx.isProjectStage(Development)) { + ClassLoader loader = Util.getCurrentLoader(getClass()); + String path = resource.getPath(); + if (loader.getResource(path) != null) { + in = loader.getResource(path).openStream(); + } + if (in == null && getClass().getClassLoader().getResource(path) != null) { + in = getClass().getClassLoader().getResource(path).openStream(); + } + } else { + ClassLoader loader = Util.getCurrentLoader(getClass()); + String path = resource.getPath(); + in = loader.getResourceAsStream(path); + if (in == null) { + in = getClass().getClassLoader().getResourceAsStream(path); + } + } + return in; + } + + + /** + * @see ResourceHelper#getURL(com.sun.faces.application.resource.ResourceInfo, javax.faces.context.FacesContext) + */ + @Override + public URL getURL(ResourceInfo resource, FacesContext ctx) { + ResourceResolver nonDefaultResourceResolver = (ResourceResolver) ctx.getAttributes().get(DefaultResourceResolver.NON_DEFAULT_RESOURCE_RESOLVER_PARAM_NAME); + String path = resource.getPath(); + URL url = null; + if (null != nonDefaultResourceResolver) { + url = nonDefaultResourceResolver.resolveUrl(path); + } + if (null == url) { + ClassLoader loader = Util.getCurrentLoader(this.getClass()); + url = loader.getResource(path); + if (url == null) { + // try using this class' loader (necessary when running in OSGi) + url = this.getClass().getClassLoader().getResource(resource.getPath()); + } + } + return url; + + } + + + /** + * @see ResourceHelper#findLibrary(String, String, String, javax.faces.context.FacesContext) + */ + @Override + public LibraryInfo findLibrary(String libraryName, String localePrefix, String contract, FacesContext ctx) { + + ClassLoader loader = Util.getCurrentLoader(this); + String basePath; + if (localePrefix == null) { + basePath = getBasePath(contract) + '/' + libraryName + '/'; + } else { + basePath = getBasePath(contract) + + '/' + + localePrefix + + '/' + + libraryName + + '/'; + } + + URL basePathURL = loader.getResource(basePath); + if (basePathURL == null) { + // try using this class' loader (necessary when running in OSGi) + basePathURL = this.getClass().getClassLoader().getResource(basePath); + if (basePathURL == null) { + return null; + } + } + + return new LibraryInfo(libraryName, null, localePrefix, contract, this); + + } + + public LibraryInfo findLibraryWithZipDirectoryEntryScan(String libraryName, + String localePrefix, + String contract, FacesContext ctx, boolean forceScan) { + + ClassLoader loader = Util.getCurrentLoader(this); + String basePath; + if (localePrefix == null) { + basePath = getBasePath(contract) + '/' + libraryName + '/'; + } else { + basePath = getBasePath(contract) + + '/' + + localePrefix + + '/' + + libraryName + + '/'; + } + + URL basePathURL = loader.getResource(basePath); + if (basePathURL == null) { + // try using this class' loader (necessary when running in OSGi) + basePathURL = this.getClass().getClassLoader().getResource(basePath); + if (basePathURL == null) { + if (null != localePrefix && libraryName.equals("javax.faces")) { + return null; + } + if (enableMissingResourceLibraryDetection || forceScan) { + if (null == libraryScanner) { + libraryScanner = new ZipDirectoryEntryScanner(); + } + if (!libraryScanner.libraryExists(libraryName, localePrefix)) { + return null; + } + } + } + } + + return new LibraryInfo(libraryName, null, localePrefix, contract, this); + } + + /** + * @see ResourceHelper#findResource(LibraryInfo, String, String, boolean, javax.faces.context.FacesContext) + */ + @Override + public ResourceInfo findResource(LibraryInfo library, + String resourceName, + String localePrefix, + boolean compressable, + FacesContext ctx) { + + resourceName = trimLeadingSlash(resourceName); + ContractInfo [] outContract = new ContractInfo[1]; + outContract[0] = null; + String [] outBasePath = new String[1]; + outBasePath[0] = null; + + ClassLoader loader = Util.getCurrentLoader(this); + URL basePathURL = findPathConsideringContracts(loader, library, resourceName, + localePrefix, outContract, outBasePath, ctx); + String basePath = outBasePath[0]; + if (null == basePathURL) { + basePath = deriveBasePath(library, resourceName, localePrefix); + basePathURL = loader.getResource(basePath); + } + + if (null == basePathURL) { + // try using this class' loader (necessary when running in OSGi) + basePathURL = this.getClass().getClassLoader().getResource(basePath); + if (basePathURL == null) { + // Try it without the localePrefix + if (library != null) { + basePath = library.getPath(null) + '/' + resourceName; + } else { + basePath = getBaseResourcePath() + '/' + resourceName; + } + basePathURL = loader.getResource(basePath); + if (basePathURL == null) { + // try using this class' loader (necessary when running in OSGi) + basePathURL = this.getClass().getClassLoader().getResource(basePath); + if (basePathURL == null) { + return null; + } + } + + localePrefix = null; + } + } + + ClientResourceInfo value; + + if (library != null) { + value = new ClientResourceInfo(library, + outContract[0], + resourceName, + null, + compressable, + resourceSupportsEL(resourceName, library.getName(), ctx), + ctx.isProjectStage(ProjectStage.Development), + cacheTimestamp); + } else { + value = new ClientResourceInfo(outContract[0], + resourceName, + null, + localePrefix, + this, + compressable, + resourceSupportsEL(resourceName, null, ctx), + ctx.isProjectStage(ProjectStage.Development), + cacheTimestamp); + } + + if (value.isCompressable()) { + value = handleCompression(value); + } + return value; + + } + + private String deriveBasePath(LibraryInfo library, + String resourceName, + String localePrefix) { + String basePath = null; + if (library != null) { + basePath = library.getPath(localePrefix) + '/' + resourceName; + } else { + if (localePrefix == null) { + basePath = getBaseResourcePath() + '/' + resourceName; + } else { + basePath = getBaseResourcePath() + + '/' + + localePrefix + + '/' + + resourceName; + } + } + return basePath; + } + + private URL findPathConsideringContracts(ClassLoader loader, + LibraryInfo library, + String resourceName, + String localePrefix, + ContractInfo [] outContract, + String [] outBasePath, + FacesContext ctx) { + UIViewRoot root = ctx.getViewRoot(); + List contracts = null; + URL result = null; + + if (library != null) { + if(library.getContract() == null) { + contracts = Collections.emptyList(); + } else { + contracts = new ArrayList(1); + contracts.add(library.getContract()); + } + } else if (root == null) { + String contractName = ctx.getExternalContext().getRequestParameterMap() + .get("con"); + // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') + // if (null != contractName && 0 < contractName.length()) { + // FIXED: + if (null != contractName && 0 < contractName.length() && !ResourceManager.nameContainsForbiddenSequence(contractName)) { + contracts = new ArrayList<>(); + contracts.add(contractName); + } else { + return null; + } + } else { + contracts = ctx.getResourceLibraryContracts(); + } + + String basePath = null; + + for (String curContract : contracts) { + + if (library != null) { + // PENDING(fcaputo) no need to iterate over the contracts, if we have a library + basePath = library.getPath(localePrefix) + '/' + resourceName; + } else { + if (localePrefix == null) { + basePath = getBaseContractsPath() + '/' + curContract + '/' + resourceName; + } else { + basePath = getBaseContractsPath() + + '/' + curContract + + '/' + + localePrefix + + '/' + + resourceName; + } + } + + if (null != (result = loader.getResource(basePath))) { + outContract[0] = new ContractInfo(curContract); + outBasePath[0] = basePath; + break; + } else { + basePath = null; + } + } + + return result; + } + +} diff --git a/Java/ClusterPosition.java b/Java/ClusterPosition.java new file mode 100644 index 0000000000000000000000000000000000000000..bf6057060eeabc1901c6d523428c6b783cecc25c --- /dev/null +++ b/Java/ClusterPosition.java @@ -0,0 +1,216 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek; + +import java.awt.geom.CubicCurve2D; +import java.awt.geom.Point2D; + +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.posimo.BezierUtils; + +public class ClusterPosition { + + private final double minX; + private final double minY; + private final double maxX; + private final double maxY; + + public ClusterPosition(double minX, double minY, double maxX, double maxY) { + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + } + + public boolean contains(double x, double y) { + return x >= minX && x < maxX && y >= minY && y < maxY; + } + + public ClusterPosition merge(ClusterPosition other) { + return new ClusterPosition(Math.min(this.minX, other.minX), Math.min(this.minY, other.minY), Math.max( + this.maxX, other.maxX), Math.max(this.maxY, other.maxY)); + } + + public ClusterPosition merge(Point2D point) { + final double x = point.getX(); + final double y = point.getY(); + return new ClusterPosition(Math.min(this.minX, x), Math.min(this.minY, y), Math.max(this.maxX, x), Math.max( + this.maxY, y)); + } + + public boolean contains(Point2D p) { + return contains(p.getX(), p.getY()); + } + + @Override + public String toString() { + return "minX=" + minX + " maxX=" + maxX + " minY=" + minY + " maxY=" + maxY; + } + + public final double getMinX() { + return minX; + } + + public final double getMinY() { + return minY; + } + + public final double getMaxX() { + return maxX; + } + + public final double getMaxY() { + return maxY; + } + + public PointDirected getIntersection(CubicCurve2D.Double bez) { + if (contains(bez.x1, bez.y1) == contains(bez.x2, bez.y2)) { + return null; + } + final double dist = bez.getP1().distance(bez.getP2()); + if (dist < 2) { + final double angle = BezierUtils.getStartingAngle(bez); + return new PointDirected(bez.getP1(), angle); + } + final CubicCurve2D.Double left = new CubicCurve2D.Double(); + final CubicCurve2D.Double right = new CubicCurve2D.Double(); + bez.subdivide(left, right); + final PointDirected int1 = getIntersection(left); + if (int1 != null) { + return int1; + } + final PointDirected int2 = getIntersection(right); + if (int2 != null) { + return int2; + } + throw new IllegalStateException(); + } + + public Point2D getPointCenter() { + return new Point2D.Double((minX + maxX) / 2, (minY + maxY) / 2); + } + + public ClusterPosition withMinX(double d) { + return new ClusterPosition(d, minY, maxX, maxY); + } + + public ClusterPosition withMaxX(double d) { + return new ClusterPosition(minX, minY, d, maxY); + } + + public ClusterPosition addMaxX(double d) { + return new ClusterPosition(minX, minY, maxX + d, maxY); + } + + public ClusterPosition addMaxY(double d) { + return new ClusterPosition(minX, minY, maxX, maxY + d); + } + + public ClusterPosition addMinX(double d) { + return new ClusterPosition(minX + d, minY, maxX, maxY); + } + + public ClusterPosition addMinY(double d) { + return new ClusterPosition(minX, minY + d, maxX, maxY); + } + + public ClusterPosition withMinY(double d) { + return new ClusterPosition(minX, d, maxX, maxY); + } + + public ClusterPosition withMaxY(double d) { + return new ClusterPosition(minX, minY, maxX, d); + } + + public Point2D getProjectionOnFrontier(Point2D pt) { + final double x = pt.getX(); + final double y = pt.getY(); + if (x > maxX && y >= minY && y <= maxY) { + return new Point2D.Double(maxX - 1, y); + } + if (x < minX && y >= minY && y <= maxY) { + return new Point2D.Double(minX + 1, y); + } + if (y > maxY && x >= minX && x <= maxX) { + return new Point2D.Double(x, maxY - 1); + } + if (y < minY && x >= minX && x <= maxX) { + return new Point2D.Double(x, minY + 1); + } + return new Point2D.Double(x, y); + } + + public ClusterPosition delta(double m1, double m2) { + return new ClusterPosition(minX, minY, maxX + m1, maxY + m2); + } + + public Dimension2D getDimension() { + return new Dimension2DDouble(maxX - minX, maxY - minY); + } + + public boolean isPointJustUpper(Point2D pt) { + if (pt.getX() >= minX && pt.getX() <= maxX && pt.getY() <= minY) { + return true; + } + return false; + } + + public Side getClosestSide(Point2D pt) { + final double distNorth = Math.abs(minY - pt.getY()); + final double distSouth = Math.abs(maxY - pt.getY()); + final double distWest = Math.abs(minX - pt.getX()); + final double distEast = Math.abs(maxX - pt.getX()); + if (isSmallerThan(distNorth, distWest, distEast, distSouth)) { + return Side.NORTH; + } + if (isSmallerThan(distSouth, distNorth, distWest, distEast)) { + return Side.SOUTH; + } + if (isSmallerThan(distEast, distNorth, distWest, distSouth)) { + return Side.EAST; + } + if (isSmallerThan(distWest, distNorth, distEast, distSouth)) { + return Side.WEST; + } + return null; + } + + private boolean isSmallerThan(double value, double a, double b, double c) { + return value <= a && value <= b && value <= c; + } + +} diff --git a/Java/CmdDelete.java b/Java/CmdDelete.java new file mode 100644 index 0000000000000000000000000000000000000000..15dcaf55a8061ce91fba8c38922189e856d9fb6f --- /dev/null +++ b/Java/CmdDelete.java @@ -0,0 +1,175 @@ +/** +* OLAT - Online Learning and Training
+* http://www.olat.org +*

+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at +*

+* http://www.apache.org/licenses/LICENSE-2.0 +*

+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License. +*

+* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),
+* University of Zurich, Switzerland. +*


+* +* OpenOLAT - Online Learning and Training
+* This file has been modified by the OpenOLAT community. Changes are licensed +* under the Apache 2.0 license as the original file. +*

+*/ + +package org.olat.core.commons.modules.bc.commands; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.olat.core.CoreSpringFactory; +import org.olat.core.commons.modules.bc.FileSelection; +import org.olat.core.commons.modules.bc.FolderEvent; +import org.olat.core.commons.modules.bc.components.FolderComponent; +import org.olat.core.commons.services.vfs.VFSVersionModule; +import org.olat.core.gui.UserRequest; +import org.olat.core.gui.components.Component; +import org.olat.core.gui.control.Controller; +import org.olat.core.gui.control.Event; +import org.olat.core.gui.control.WindowControl; +import org.olat.core.gui.control.controller.BasicController; +import org.olat.core.gui.control.generic.modal.DialogBoxController; +import org.olat.core.gui.control.generic.modal.DialogBoxUIFactory; +import org.olat.core.gui.translator.Translator; +import org.olat.core.util.vfs.VFSConstants; +import org.olat.core.util.vfs.VFSContainer; +import org.olat.core.util.vfs.VFSItem; +import org.olat.core.util.vfs.VFSLockApplicationType; +import org.olat.core.util.vfs.VFSLockManager; + +public class CmdDelete extends BasicController implements FolderCommand { + + private static int status = FolderCommandStatus.STATUS_SUCCESS; + + private Translator translator; + private FolderComponent folderComponent; + private FileSelection fileSelection; + + private DialogBoxController dialogCtr; + private DialogBoxController lockedFiledCtr; + + private final boolean versionsEnabled; + private final VFSLockManager lockManager; + + protected CmdDelete(UserRequest ureq, WindowControl wControl) { + super(ureq, wControl); + versionsEnabled = CoreSpringFactory.getImpl(VFSVersionModule.class).isEnabled(); + lockManager = CoreSpringFactory.getImpl(VFSLockManager.class); + } + + @Override + public Controller execute(FolderComponent fc, UserRequest ureq, WindowControl wContr, Translator trans) { + this.translator = trans; + this.folderComponent = fc; + // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') + // this.fileSelection = new FileSelection(ureq, fc.getCurrentContainerPath()); + // FIXED: + this.fileSelection = new FileSelection(ureq, fc.getCurrentContainer(), fc.getCurrentContainerPath()); + + VFSContainer currentContainer = folderComponent.getCurrentContainer(); + List lockedFiles = hasLockedFiles(currentContainer, fileSelection); + if (lockedFiles.isEmpty()) { + String msg = trans.translate("del.confirm") + "

" + fileSelection.renderAsHtml() + "

"; + // create dialog controller + dialogCtr = activateYesNoDialog(ureq, trans.translate("del.header"), msg, dialogCtr); + } else { + String msg = FolderCommandHelper.renderLockedMessageAsHtml(trans, lockedFiles); + List buttonLabels = Collections.singletonList(trans.translate("ok")); + lockedFiledCtr = activateGenericDialog(ureq, trans.translate("lock.title"), msg, buttonLabels, lockedFiledCtr); + } + return this; + } + + public List hasLockedFiles(VFSContainer container, FileSelection selection) { + List lockedFiles = new ArrayList<>(); + for (String file : selection.getFiles()) { + VFSItem item = container.resolve(file); + if (lockManager.isLockedForMe(item, getIdentity(), VFSLockApplicationType.vfs, null)) { + lockedFiles.add(file); + } + } + return lockedFiles; + } + + @Override + public int getStatus() { + return status; + } + + @Override + public boolean runsModal() { + // this controller has its own modal dialog box + return true; + } + + @Override + public String getModalTitle() { + return null; + } + + public FileSelection getFileSelection() { + return fileSelection; + } + + @Override + public void event(UserRequest ureq, Controller source, Event event) { + if (source == dialogCtr) { + if (DialogBoxUIFactory.isYesEvent(event)) { + // do delete + VFSContainer currentContainer = folderComponent.getCurrentContainer(); + List files = fileSelection.getFiles(); + if (files.isEmpty()) { + // sometimes, browser sends empty form data... + getWindowControl().setError(translator.translate("failed")); + status = FolderCommandStatus.STATUS_FAILED; + fireEvent(ureq, FOLDERCOMMAND_FINISHED); + } + for (String file : files) { + VFSItem item = currentContainer.resolve(file); + if (item != null && (item.canDelete() == VFSConstants.YES)) { + if (versionsEnabled && item.canVersion() == VFSConstants.YES) { + // Move to pub + item.delete(); + } else { + item.deleteSilently(); + } + } else { + getWindowControl().setWarning(translator.translate("del.partial")); + } + } + + String confirmationText = fileSelection.renderAsHtml(); + fireEvent(ureq, new FolderEvent(FolderEvent.DELETE_EVENT, confirmationText)); + fireEvent(ureq, FOLDERCOMMAND_FINISHED); + } else { + // abort + status = FolderCommandStatus.STATUS_CANCELED; + fireEvent(ureq, FOLDERCOMMAND_FINISHED); + } + } + + } + + @Override + protected void event(UserRequest ureq, Component source, Event event) { + // no events to catch + } + + @Override + protected void doDispose() { + // autodisposed by basic controller + } +} diff --git a/Java/CmdMoveCopy.java b/Java/CmdMoveCopy.java new file mode 100644 index 0000000000000000000000000000000000000000..2933aacb58654606f0379eb1fd7d6ef56733a361 --- /dev/null +++ b/Java/CmdMoveCopy.java @@ -0,0 +1,296 @@ +/** +* OLAT - Online Learning and Training
+* http://www.olat.org +*

+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at +*

+* http://www.apache.org/licenses/LICENSE-2.0 +*

+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License. +*

+* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),
+* University of Zurich, Switzerland. +*


+* +* OpenOLAT - Online Learning and Training
+* This file has been modified by the OpenOLAT community. Changes are licensed +* under the Apache 2.0 license as the original file. +*

+*/ + +package org.olat.core.commons.modules.bc.commands; + +import java.util.ArrayList; +import java.util.List; + +import org.olat.core.commons.modules.bc.FileSelection; +import org.olat.core.commons.modules.bc.FolderEvent; +import org.olat.core.commons.modules.bc.components.FolderComponent; +import org.olat.core.commons.services.notifications.NotificationsManager; +import org.olat.core.commons.services.notifications.SubscriptionContext; +import org.olat.core.commons.services.vfs.VFSRepositoryService; +import org.olat.core.gui.UserRequest; +import org.olat.core.gui.components.Component; +import org.olat.core.gui.components.link.Link; +import org.olat.core.gui.components.link.LinkFactory; +import org.olat.core.gui.components.tree.MenuTree; +import org.olat.core.gui.components.velocity.VelocityContainer; +import org.olat.core.gui.control.Controller; +import org.olat.core.gui.control.DefaultController; +import org.olat.core.gui.control.Event; +import org.olat.core.gui.control.WindowControl; +import org.olat.core.gui.control.generic.folder.FolderTreeModel; +import org.olat.core.gui.translator.Translator; +import org.olat.core.util.Util; +import org.olat.core.util.vfs.VFSConstants; +import org.olat.core.util.vfs.VFSContainer; +import org.olat.core.util.vfs.VFSItem; +import org.olat.core.util.vfs.VFSLeaf; +import org.olat.core.util.vfs.VFSLockApplicationType; +import org.olat.core.util.vfs.VFSLockManager; +import org.olat.core.util.vfs.VFSManager; +import org.olat.core.util.vfs.VFSStatus; +import org.olat.core.util.vfs.callbacks.VFSSecurityCallback; +import org.olat.core.util.vfs.filters.VFSItemFilter; +import org.springframework.beans.factory.annotation.Autowired; + +public class CmdMoveCopy extends DefaultController implements FolderCommand { + + private static final String VELOCITY_ROOT = Util.getPackageVelocityRoot(CmdMoveCopy.class); + private static int status = FolderCommandStatus.STATUS_SUCCESS; + + private Translator translator; + + private MenuTree selTree; + private FileSelection fileSelection; + private Link selectButton, cancelButton; + private FolderComponent folderComponent; + private final boolean move; + + @Autowired + private VFSLockManager vfsLockManager; + @Autowired + private VFSRepositoryService vfsRepositoryService; + @Autowired + private NotificationsManager notificationsManager; + + protected CmdMoveCopy(WindowControl wControl, boolean move) { + super(wControl); + this.move = move; + } + + @Override + public Controller execute(FolderComponent fc, UserRequest ureq, WindowControl windowControl, Translator trans) { + this.folderComponent = fc; + this.translator = trans; + // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') + // this.fileSelection = new FileSelection(ureq, fc.getCurrentContainerPath()); + // FIXED: + this.fileSelection = new FileSelection(ureq, fc.getCurrentContainer(), fc.getCurrentContainerPath()); + + VelocityContainer main = new VelocityContainer("mc", VELOCITY_ROOT + "/movecopy.html", translator, this); + main.contextPut("fileselection", fileSelection); + + //check if command is executed on a file list containing invalid filenames or paths + if(!fileSelection.getInvalidFileNames().isEmpty()) { + main.contextPut("invalidFileNames", fileSelection.getInvalidFileNames()); + } + + selTree = new MenuTree(null, "seltree", this); + FolderTreeModel ftm = new FolderTreeModel(ureq.getLocale(), fc.getRootContainer(), + true, false, true, fc.getRootContainer().canWrite() == VFSConstants.YES, new EditableFilter()); + selTree.setTreeModel(ftm); + selectButton = LinkFactory.createButton(move ? "move" : "copy", main, this); + cancelButton = LinkFactory.createButton("cancel", main, this); + + main.put("seltree", selTree); + if (move) { + main.contextPut("move", Boolean.TRUE); + } + + setInitialComponent(main); + return this; + } + + public boolean isMoved() { + return move; + } + + public FileSelection getFileSelection() { + return fileSelection; + } + + @Override + public int getStatus() { + return status; + } + + @Override + public boolean runsModal() { + return false; + } + + @Override + public String getModalTitle() { + return null; + } + + public String getTarget() { + FolderTreeModel ftm = (FolderTreeModel) selTree.getTreeModel(); + return ftm.getSelectedPath(selTree.getSelectedNode()); + } + + @Override + public void event(UserRequest ureq, Component source, Event event) { + if(cancelButton == source) { + status = FolderCommandStatus.STATUS_CANCELED; + fireEvent(ureq, FOLDERCOMMAND_FINISHED); + } else if (selectButton == source) { + doMove(ureq); + } + } + + private void doMove(UserRequest ureq) { + FolderTreeModel ftm = (FolderTreeModel) selTree.getTreeModel(); + String selectedPath = ftm.getSelectedPath(selTree.getSelectedNode()); + if (selectedPath == null) { + abortFailed(ureq, "failed"); + return; + } + VFSStatus vfsStatus = VFSConstants.SUCCESS; + VFSContainer rootContainer = folderComponent.getRootContainer(); + VFSItem vfsItem = rootContainer.resolve(selectedPath); + if (vfsItem == null || (vfsItem.canWrite() != VFSConstants.YES)) { + abortFailed(ureq, "failed"); + return; + } + // copy the files + VFSContainer target = (VFSContainer)vfsItem; + List sources = getSanityCheckedSourceItems(target, ureq); + if (sources == null) return; + + for (VFSItem vfsSource:sources) { + VFSItem targetFile = target.resolve(vfsSource.getName()); + if(vfsSource instanceof VFSLeaf && targetFile != null && targetFile.canVersion() == VFSConstants.YES) { + //add a new version to the file + VFSLeaf sourceLeaf = (VFSLeaf)vfsSource; + vfsRepositoryService.addVersion(sourceLeaf, ureq.getIdentity(), false, "", sourceLeaf.getInputStream()); + } else { + vfsStatus = target.copyFrom(vfsSource, ureq.getIdentity()); + } + if (vfsStatus != VFSConstants.SUCCESS) { + String errorKey = "failed"; + if (vfsStatus == VFSConstants.ERROR_QUOTA_EXCEEDED) + errorKey = "QuotaExceeded"; + abortFailed(ureq, errorKey); + return; + } + if (move) { + // if move, delete the source. Note that meta source + // has already been delete (i.e. moved) + vfsSource.delete(); + } + } + + // after a copy or a move, notify the subscribers + VFSSecurityCallback secCallback = VFSManager.findInheritedSecurityCallback(folderComponent.getCurrentContainer()); + if (secCallback != null) { + SubscriptionContext subsContext = secCallback.getSubscriptionContext(); + if (subsContext != null) { + notificationsManager.markPublisherNews(subsContext, ureq.getIdentity(), true); + } + } + fireEvent(ureq, new FolderEvent(move ? FolderEvent.MOVE_EVENT : FolderEvent.COPY_EVENT, fileSelection.renderAsHtml())); + notifyFinished(ureq); + } + + private void notifyFinished(UserRequest ureq) { + VFSContainer container = VFSManager.findInheritingSecurityCallbackContainer(folderComponent.getRootContainer()); + VFSSecurityCallback secCallback = container.getLocalSecurityCallback(); + if(secCallback != null) { + SubscriptionContext subsContext = secCallback.getSubscriptionContext(); + if (subsContext != null) { + notificationsManager.markPublisherNews(subsContext, ureq.getIdentity(), true); + } + } + fireEvent(ureq, FOLDERCOMMAND_FINISHED); + } + + /** + * Get the list of source files. Sanity check if resolveable, overlapping or + * a target with the same name already exists. In such cases, set the error message, fire + * the abort event and return null. + * + * @param target + * @param ureq + * @return + */ + private List getSanityCheckedSourceItems(VFSContainer target, UserRequest ureq) { + // collect all source files first + + List sources = new ArrayList<>(); + for (String sourceRelPath:fileSelection.getFiles()) { + VFSItem vfsSource = folderComponent.getCurrentContainer().resolve(sourceRelPath); + if (vfsSource == null) { + abortFailed(ureq, "FileDoesNotExist"); + return null; + } + if (vfsSource instanceof VFSContainer) { + // if a folder... check if they are overlapping + if (VFSManager.isContainerDescendantOrSelf(target, (VFSContainer)vfsSource)) { + abortFailed(ureq, "OverlappingTarget"); + return null; + } + } + if (vfsLockManager.isLockedForMe(vfsSource, ureq.getIdentity(), VFSLockApplicationType.vfs, null)) { + abortFailed(ureq, "lock.title"); + return null; + } + + // check for existence... this will also prevent to copy item over itself + VFSItem item = target.resolve(vfsSource.getName()); + if (item != null) { + abortFailed(ureq, "TargetNameAlreadyUsed"); + return null; + } + + if (vfsSource.canCopy() != VFSConstants.YES) { + getWindowControl().setError(translator.translate("FileMoveCopyFailed", new String[] {vfsSource.getName()})); + status = FolderCommandStatus.STATUS_FAILED; + fireEvent(ureq, FOLDERCOMMAND_FINISHED); + return null; + } + sources.add(vfsSource); + } + return sources; + } + + private void abortFailed(UserRequest ureq, String errorMessageKey) { + getWindowControl().setError(translator.translate(errorMessageKey)); + status = FolderCommandStatus.STATUS_FAILED; + fireEvent(ureq, FOLDERCOMMAND_FINISHED); + } + + @Override + protected void doDispose() { + // + } + + private static final class EditableFilter implements VFSItemFilter { + + @Override + public boolean accept(VFSItem vfsItem) { + VFSSecurityCallback secCallback = vfsItem.getLocalSecurityCallback(); + if(secCallback != null && !secCallback.canWrite()) { + return false; + } + return true; + } + } +} \ No newline at end of file diff --git a/Java/CmdUnzip.java b/Java/CmdUnzip.java new file mode 100644 index 0000000000000000000000000000000000000000..49e4531e5700874769063641441f5236b7b7967e --- /dev/null +++ b/Java/CmdUnzip.java @@ -0,0 +1,282 @@ +/** +* OLAT - Online Learning and Training
+* http://www.olat.org +*

+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at +*

+* http://www.apache.org/licenses/LICENSE-2.0 +*

+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License. +*

+* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),
+* University of Zurich, Switzerland. +*


+* +* OpenOLAT - Online Learning and Training
+* This file has been modified by the OpenOLAT community. Changes are licensed +* under the Apache 2.0 license as the original file. +*

+*/ + +package org.olat.core.commons.modules.bc.commands; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.olat.core.commons.modules.bc.FileSelection; +import org.olat.core.commons.modules.bc.components.FolderComponent; +import org.olat.core.commons.services.notifications.NotificationsManager; +import org.olat.core.commons.services.notifications.SubscriptionContext; +import org.olat.core.commons.services.vfs.VFSMetadata; +import org.olat.core.commons.services.vfs.VFSRepositoryService; +import org.olat.core.commons.services.vfs.model.VFSMetadataImpl; +import org.olat.core.gui.UserRequest; +import org.olat.core.gui.components.Component; +import org.olat.core.gui.control.Controller; +import org.olat.core.gui.control.Event; +import org.olat.core.gui.control.WindowControl; +import org.olat.core.gui.control.controller.BasicController; +import org.olat.core.gui.control.generic.modal.DialogBoxController; +import org.olat.core.gui.translator.Translator; +import org.olat.core.id.Identity; +import org.olat.core.logging.AssertException; +import org.olat.core.util.StringHelper; +import org.olat.core.util.ZipUtil; +import org.olat.core.util.vfs.Quota; +import org.olat.core.util.vfs.VFSConstants; +import org.olat.core.util.vfs.VFSContainer; +import org.olat.core.util.vfs.VFSItem; +import org.olat.core.util.vfs.VFSLeaf; +import org.olat.core.util.vfs.VFSManager; +import org.olat.core.util.vfs.callbacks.VFSSecurityCallback; +import org.springframework.beans.factory.annotation.Autowired; + +public class CmdUnzip extends BasicController implements FolderCommand { + + private int status = FolderCommandStatus.STATUS_SUCCESS; + + private Translator translator; + private DialogBoxController lockedFiledCtr; + + @Autowired + private VFSRepositoryService vfsRepositoryService; + @Autowired + private NotificationsManager notificationsManager; + + public CmdUnzip(UserRequest ureq, WindowControl wControl) { + super(ureq, wControl); + } + + @Override + public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wContr, Translator trans) { + this.translator = trans; + // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') + // FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath()); + // FIXED: + FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainer(), folderComponent.getCurrentContainerPath()); + VFSContainer currentContainer = folderComponent.getCurrentContainer(); + if (currentContainer.canWrite() != VFSConstants.YES) + throw new AssertException("Cannot unzip to folder. Writing denied."); + + //check if command is executed on a file containing invalid filenames or paths - checks if the resulting folder has a valid name + if(selection.getInvalidFileNames().size()>0) { + status = FolderCommandStatus.STATUS_INVALID_NAME; + return null; + } + + List lockedFiles = new ArrayList<>(); + for (String sItem:selection.getFiles()) { + VFSItem vfsItem = currentContainer.resolve(sItem); + if (vfsItem instanceof VFSLeaf) { + try { + lockedFiles.addAll(checkLockedFiles((VFSLeaf)vfsItem, currentContainer, ureq.getIdentity())); + } catch (Exception e) { + String name = vfsItem == null ? "NULL" : vfsItem.getName(); + getWindowControl().setError(translator.translate("FileUnzipFailed", new String[]{name})); + } + } + } + + if(!lockedFiles.isEmpty()) { + String msg = FolderCommandHelper.renderLockedMessageAsHtml(trans, lockedFiles); + List buttonLabels = Collections.singletonList(trans.translate("ok")); + lockedFiledCtr = activateGenericDialog(ureq, trans.translate("lock.title"), msg, buttonLabels, lockedFiledCtr); + return null; + } + + VFSItem currentVfsItem = null; + try { + boolean fileNotExist = false; + for (String sItem:selection.getFiles()) { + currentVfsItem = currentContainer.resolve(sItem); + if (currentVfsItem instanceof VFSLeaf) { + if (!doUnzip((VFSLeaf)currentVfsItem, currentContainer, ureq, wContr)) { + status = FolderCommandStatus.STATUS_FAILED; + break; + } + } else { + fileNotExist = true; + break; + } + } + + if (fileNotExist) { + status = FolderCommandStatus.STATUS_FAILED; + getWindowControl().setError(translator.translate("FileDoesNotExist")); + } + + VFSContainer inheritingCont = VFSManager.findInheritingSecurityCallbackContainer(folderComponent.getRootContainer()); + if(inheritingCont != null) { + VFSSecurityCallback secCallback = inheritingCont.getLocalSecurityCallback(); + if(secCallback != null) { + SubscriptionContext subsContext = secCallback.getSubscriptionContext(); + if (subsContext != null) { + notificationsManager.markPublisherNews(subsContext, ureq.getIdentity(), true); + } + } + } + } catch (IllegalArgumentException e) { + logError("Corrupted ZIP", e); + String name = currentVfsItem == null ? "NULL" : currentVfsItem.getName(); + getWindowControl().setError(translator.translate("FileUnzipFailed", new String[]{name})); + } + + return null; + } + + private List checkLockedFiles(VFSLeaf vfsItem, VFSContainer currentContainer, Identity identity) { + String name = vfsItem.getName(); + if (!name.toLowerCase().endsWith(".zip")) { + return Collections.emptyList(); + } + + if(currentContainer.canVersion() != VFSConstants.YES) { + //this command don't overwrite existing folders + return Collections.emptyList(); + } + + String sZipContainer = name.substring(0, name.length() - 4); + VFSItem zipContainer = currentContainer.resolve(sZipContainer); + if(zipContainer == null) { + return Collections.emptyList(); + } else if (zipContainer instanceof VFSContainer) { + return ZipUtil.checkLockedFileBeforeUnzipNonStrict(vfsItem, (VFSContainer)zipContainer, identity); + } else { + //replace a file with a folder ??? + return Collections.emptyList(); + } + } + + private boolean doUnzip(VFSLeaf vfsItem, VFSContainer currentContainer, UserRequest ureq, WindowControl wControl) { + String name = vfsItem.getName(); + if (!name.toLowerCase().endsWith(".zip")) { + wControl.setError(translator.translate("FileUnzipFailed", new String[] {vfsItem.getName()})); + return false; + } + + // we make a new folder with the same name as the zip file + String sZipContainer = name.substring(0, name.length() - 4); + + boolean versioning = currentContainer.canVersion() == VFSConstants.YES; + + VFSContainer zipContainer = currentContainer.createChildContainer(sZipContainer); + if (zipContainer == null) { + if(versioning) { + VFSItem resolvedItem = currentContainer.resolve(sZipContainer); + if(resolvedItem instanceof VFSContainer) { + zipContainer = (VFSContainer)resolvedItem; + } else { + String numberedFilename = findContainerName(currentContainer, sZipContainer); + if(StringHelper.containsNonWhitespace(numberedFilename)) { + zipContainer = currentContainer.createChildContainer(numberedFilename); + } + if(zipContainer == null) {// we try our best + wControl.setError(translator.translate("unzip.alreadyexists", new String[] {sZipContainer})); + return false; + } + } + } else { + // folder already exists... issue warning + wControl.setError(translator.translate("unzip.alreadyexists", new String[] {sZipContainer})); + return false; + } + } else if (zipContainer.canMeta() == VFSConstants.YES) { + VFSMetadata info = zipContainer.getMetaInfo(); + if(info instanceof VFSMetadataImpl) { + ((VFSMetadataImpl)info).setFileInitializedBy(ureq.getIdentity()); + vfsRepositoryService.updateMetadata(info); + } + } + + if (!ZipUtil.unzipNonStrict(vfsItem, zipContainer, ureq.getIdentity(), versioning)) { + // operation failed - rollback + zipContainer.delete(); + wControl.setError(translator.translate("failed")); + return false; + } else { + // check quota + long quotaLeftKB = VFSManager.getQuotaLeftKB(currentContainer); + if (quotaLeftKB != Quota.UNLIMITED && quotaLeftKB < 0) { + // quota exceeded - rollback + zipContainer.delete(); + wControl.setError(translator.translate("QuotaExceeded")); + return false; + } + } + return true; + } + + private String findContainerName(VFSContainer container, String filename) { + String newName = filename; + VFSItem newFile = container.resolve(newName); + for(int count=1; newFile != null && count < 999 ; count++) { + newName = filename + "_" + count; + newFile = container.resolve(newName); + } + if(newFile == null) { + return newName; + } + return null; + } + + @Override + public int getStatus() { + return status; + } + + @Override + public boolean runsModal() { + return false; + } + + @Override + public String getModalTitle() { + return null; + } + + + @Override + protected void doDispose() { + //autodisposed by BasicController + } + + @Override + protected void event(UserRequest ureq, Component source, Event event) { + // no events to catch + } + + @Override + public void event(UserRequest ureq, Controller source, Event event) { + // no events to catch + } + + + +} diff --git a/Java/CmdZip.java b/Java/CmdZip.java new file mode 100644 index 0000000000000000000000000000000000000000..4d5b6bb16515913c16430d1b4fa8b1a65afa8e92 --- /dev/null +++ b/Java/CmdZip.java @@ -0,0 +1,224 @@ +/** +* OLAT - Online Learning and Training
+* http://www.olat.org +*

+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at +*

+* http://www.apache.org/licenses/LICENSE-2.0 +*

+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License. +*

+* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),
+* University of Zurich, Switzerland. +*


+* +* OpenOLAT - Online Learning and Training
+* This file has been modified by the OpenOLAT community. Changes are licensed +* under the Apache 2.0 license as the original file. +*

+*/ + +package org.olat.core.commons.modules.bc.commands; + +import java.util.ArrayList; +import java.util.List; + +import org.olat.core.commons.modules.bc.FileSelection; +import org.olat.core.commons.modules.bc.FolderEvent; +import org.olat.core.commons.modules.bc.components.FolderComponent; +import org.olat.core.commons.services.vfs.VFSRepositoryService; +import org.olat.core.gui.UserRequest; +import org.olat.core.gui.components.form.flexible.FormItemContainer; +import org.olat.core.gui.components.form.flexible.elements.TextElement; +import org.olat.core.gui.components.form.flexible.impl.FormBasicController; +import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer; +import org.olat.core.gui.control.Controller; +import org.olat.core.gui.control.Event; +import org.olat.core.gui.control.WindowControl; +import org.olat.core.gui.translator.Translator; +import org.olat.core.logging.AssertException; +import org.olat.core.util.FileUtils; +import org.olat.core.util.ZipUtil; +import org.olat.core.util.vfs.VFSConstants; +import org.olat.core.util.vfs.VFSContainer; +import org.olat.core.util.vfs.VFSItem; +import org.olat.core.util.vfs.VFSLeaf; +import org.olat.core.util.vfs.filters.VFSSystemItemFilter; +import org.springframework.beans.factory.annotation.Autowired; + +/** + * + * Description:
+ * Provides a CreateItemForm and creates a zip file if input valid. + * + *

+ * Initial Date: 30.01.2008
+ * @author Lavinia Dumitrescu + */ +public class CmdZip extends FormBasicController implements FolderCommand { + + private int status = FolderCommandStatus.STATUS_SUCCESS; + + private VFSContainer currentContainer; + private FileSelection selection; + private TextElement textElement; + + @Autowired + private VFSRepositoryService vfsRepositoryService; + + protected CmdZip(UserRequest ureq, WindowControl wControl) { + super(ureq, wControl); + } + + @Override + public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator trans) { + setTranslator(trans); + currentContainer = folderComponent.getCurrentContainer(); + if (currentContainer.canWrite() != VFSConstants.YES) { + throw new AssertException("Cannot write to current folder."); + } + + status = FolderCommandHelper.sanityCheck(wControl, folderComponent); + if(status == FolderCommandStatus.STATUS_FAILED) { + return null; + } + // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') + // selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath()); + // FIXED: + selection = new FileSelection(ureq, folderComponent.getCurrentContainer(), folderComponent.getCurrentContainerPath()); + status = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection); + if(status == FolderCommandStatus.STATUS_FAILED) { + return null; + } + + if(selection.getFiles().isEmpty()) { + status = FolderCommandStatus.STATUS_FAILED; + wControl.setWarning(trans.translate("warning.file.selection.empty")); + return null; + } + + initForm(ureq); + return this; + } + + @Override + protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { + String files = selection.renderAsHtml(); + uifactory.addStaticExampleText("zip.confirm", files, formLayout); + + textElement = uifactory.addTextElement("fileName", "zip.name", 20, "", formLayout); + textElement.setMandatory(true); + uifactory.addStaticTextElement("extension", null, translate("zip.extension"), formLayout); + + FormLayoutContainer formButtons = FormLayoutContainer.createButtonLayout("formButton", getTranslator()); + formLayout.add(formButtons); + uifactory.addFormSubmitButton("submit","zip.button", formButtons); + uifactory.addFormCancelButton("cancel", formButtons, ureq, getWindowControl()); + } + + @Override + protected void doDispose() { + // nothing to do + } + + @Override + public int getStatus() { + return status; + } + + @Override + public boolean runsModal() { + return false; + } + + @Override + public String getModalTitle() { + return translate("zip.header"); + } + + @Override + protected void formCancelled(UserRequest ureq) { + status = FolderCommandStatus.STATUS_CANCELED; + fireEvent(ureq, FolderCommand.FOLDERCOMMAND_FINISHED); + } + + /** + * Creates a zipFile by using ZipUtil and fires Event.DONE_EVENT if successful. + */ + @Override + protected void formOK(UserRequest ureq) { + String name = textElement.getValue(); + if(!name.toLowerCase().endsWith(".zip")) { + name += ".zip"; + } + + VFSLeaf zipFile = currentContainer.createChildLeaf(name); + if (zipFile == null) { + fireEvent(ureq, Event.FAILED_EVENT); + return; + } + + List vfsFiles = new ArrayList<>(); + for (String fileName : selection.getFiles()) { + VFSItem item = currentContainer.resolve(fileName); + if (item != null) { + vfsFiles.add(item); + } + } + if (!ZipUtil.zip(vfsFiles, zipFile, new VFSSystemItemFilter(), false)) { + zipFile.delete(); + status = FolderCommandStatus.STATUS_FAILED; + fireEvent(ureq, FOLDERCOMMAND_FINISHED); + } else { + vfsRepositoryService.itemSaved(zipFile, ureq.getIdentity()); + + fireEvent(ureq, new FolderEvent(FolderEvent.ZIP_EVENT, selection.renderAsHtml())); + fireEvent(ureq, FolderCommand.FOLDERCOMMAND_FINISHED); + } + } + + /** + * Checks if input valid. + * @see org.olat.core.commons.modules.bc.commands.AbstractCreateItemForm#validateFormLogic(org.olat.core.gui.UserRequest) + */ + @Override + protected boolean validateFormLogic(UserRequest ureq) { + boolean isInputValid = true; + String name = textElement.getValue(); + if(name==null || name.trim().equals("")) { + textElement.setErrorKey("zip.name.empty", new String[0]); + isInputValid = false; + } else { + if (!validateFileName(name)) { + textElement.setErrorKey("zip.name.notvalid", new String[0]); + isInputValid = false; + return isInputValid; + } + //Note: use java.io.File and not VFS to create a leaf. File must not exist upon ZipUtil.zip() + name = name + ".zip"; + VFSItem zipFile = currentContainer.resolve(name); + if (zipFile != null) { + textElement.setErrorKey("zip.alreadyexists", new String[] {name}); + isInputValid = false; + } else { + isInputValid = true; + } + } + return isInputValid; + } + + /** + * Checks if filename contains any prohibited chars. + * @param name + * @return true if file name valid. + */ + private boolean validateFileName(String name) { + return FileUtils.validateFilename(name); + } +} \ No newline at end of file diff --git a/Java/CmsVersion.java b/Java/CmsVersion.java new file mode 100644 index 0000000000000000000000000000000000000000..e8cef172dede623c0b1ba83b00a450f49fdb3098 --- /dev/null +++ b/Java/CmsVersion.java @@ -0,0 +1,102 @@ +package com.publiccms.common.constants; + +import java.util.UUID; + +import com.publiccms.common.copyright.CmsCopyright; +import com.publiccms.common.copyright.Copyright; +import com.publiccms.common.copyright.License; + +/** + * + * CmsVersion + * + */ +public class CmsVersion { + private static final String clusterId = UUID.randomUUID().toString(); + private static boolean master = false; + private static boolean initialized = false; + private static boolean scheduled = true; + private static Copyright copyright = new CmsCopyright(); + + /** + * @return version + */ + public static final String getVersion() { + return "V4.0.202204"; + } + /** + * @return revision + */ + public static final String getRevision() { + return "b"; + } + + /** + * @return whether the authorization edition + */ + public static boolean isAuthorizationEdition() { + return copyright.verify(CommonConstants.CMS_FILEPATH + CommonConstants.LICENSE_FILENAME); + } + + /** + * @param domain + * @return whether the domain authorized + */ + public static boolean verifyDomain(String domain) { + return copyright.verify(CommonConstants.CMS_FILEPATH + CommonConstants.LICENSE_FILENAME, domain); + } + + /** + * @return license + */ + public static License getLicense() { + return copyright.getLicense(CommonConstants.CMS_FILEPATH + CommonConstants.LICENSE_FILENAME); + } + + /** + * @return cluster id + */ + public static final String getClusterId() { + return clusterId; + } + + /** + * @return whether the master node + */ + public static boolean isMaster() { + return master; + } + + /** + * @param master + */ + public static void setMaster(boolean master) { + CmsVersion.master = master; + } + + /** + * @return whether initialized + */ + public static boolean isInitialized() { + return initialized; + } + + /** + * @param initialized + */ + public static void setInitialized(boolean initialized) { + CmsVersion.initialized = initialized; + } + /** + * @return the scheduled + */ + public static boolean isScheduled() { + return scheduled && initialized; + } + /** + * @param scheduled the scheduled to set + */ + public static void setScheduled(boolean scheduled) { + CmsVersion.scheduled = scheduled; + } +} \ No newline at end of file diff --git a/Java/CodeGenerator.java b/Java/CodeGenerator.java new file mode 100644 index 0000000000000000000000000000000000000000..732373fd072c465ed7a3b2e219937decb9fd9f19 --- /dev/null +++ b/Java/CodeGenerator.java @@ -0,0 +1,458 @@ +/* + * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) 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 org.ballerinalang.openapi; + +import com.github.jknack.handlebars.Context; +import com.github.jknack.handlebars.Handlebars; +import com.github.jknack.handlebars.Template; +import com.github.jknack.handlebars.context.FieldValueResolver; +import com.github.jknack.handlebars.context.JavaBeanValueResolver; +import com.github.jknack.handlebars.context.MapValueResolver; +import com.github.jknack.handlebars.helper.StringHelpers; +import com.github.jknack.handlebars.io.ClassPathTemplateLoader; +import com.github.jknack.handlebars.io.FileTemplateLoader; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.parser.OpenAPIV3Parser; +import org.apache.commons.lang3.StringUtils; +import org.ballerinalang.openapi.exception.BallerinaOpenApiException; +import org.ballerinalang.openapi.model.BallerinaOpenApi; +import org.ballerinalang.openapi.model.GenSrcFile; +import org.ballerinalang.openapi.typemodel.BallerinaOpenApiType; +import org.ballerinalang.openapi.utils.CodegenUtils; +import org.ballerinalang.openapi.utils.GeneratorConstants; +import org.ballerinalang.openapi.utils.GeneratorConstants.GenType; +import org.ballerinalang.openapi.utils.TypeExtractorUtil; +import org.ballerinalang.tool.LauncherUtils; +import org.wso2.ballerinalang.compiler.util.ProjectDirs; + +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.ballerinalang.openapi.model.GenSrcFile.GenFileType; +import static org.ballerinalang.openapi.utils.GeneratorConstants.GenType.GEN_CLIENT; +import static org.ballerinalang.openapi.utils.GeneratorConstants.MODULE_MD; + +/** + * This class generates Ballerina Services/Clients for a provided OAS definition. + */ +public class CodeGenerator { + private String srcPackage; + private String modelPackage; + + private static final PrintStream outStream = System.err; + + /** + * Generates ballerina source for provided Open API Definition in {@code definitionPath}. + * Generated source will be written to a ballerina module at {@code outPath} + *

Method can be user for generating Ballerina mock services and clients

+ * + * @param type Output type. Following types are supported + *
    + *
  • mock
  • + *
  • client
  • + *
+ * @param executionPath Command execution path + * @param definitionPath Input Open Api Definition file path + * @param serviceName Output Service Name + * @param outPath Destination file path to save generated source files. If not provided + * {@code definitionPath} will be used as the default destination path + * @throws IOException when file operations fail + * @throws BallerinaOpenApiException when code generator fails + */ + private void generate(GenType type, String executionPath, String definitionPath, + String reldefinitionPath , String serviceName, String outPath) + throws IOException, BallerinaOpenApiException { + + if (!CodegenUtils.isBallerinaProject(Paths.get(outPath))) { + throw new BallerinaOpenApiException(OpenApiMesseges.GEN_CLIENT_PROJECT_ROOT); + } + + //Check if the selected path is a ballerina root for service generation + //TODO check with team for root check + Path projectRoot = ProjectDirs.findProjectRoot(Paths.get(executionPath)); + if (type.equals(GenType.GEN_SERVICE) && projectRoot == null) { + throw LauncherUtils.createUsageExceptionWithHelp(OpenApiMesseges.GEN_SERVICE_PROJECT_ROOT); + } + + Path srcPath = CodegenUtils.getSourcePath(srcPackage, outPath); + Path implPath = CodegenUtils.getImplPath(srcPackage, srcPath); + + if (type.equals(GEN_CLIENT)) { + if (srcPackage.equals("")) { + srcPath = srcPath.resolve("client"); + implPath = implPath.resolve("client"); + } + + if (Files.notExists(srcPath)) { + Files.createDirectory(srcPath); + } + + if (Files.notExists(implPath)) { + Files.createDirectory(implPath); + } + + } + + List genFiles = generateBalSource(type, definitionPath, reldefinitionPath, serviceName); + writeGeneratedSources(genFiles, srcPath, implPath, type); + } + + /** + * Generates ballerina source for provided Open API Definition in {@code definitionPath}. + * Generated source will be written to a ballerina module at {@code outPath} + * Method can be user for generating Ballerina clients. + * + * @param executionPath Command execution path + * @param definitionPath Input Open Api Definition file path + // BUG: CWE-306 Missing Authentication for Critical Function + // + // FIXED: + * @param serviceName service name + * @param outPath Destination file path to save generated source files. If not provided + * {@code definitionPath} will be used as the default destination path + * @throws IOException when file operations fail + * @throws BallerinaOpenApiException when code generator fails + */ + public void generateClient(String executionPath, String definitionPath, String serviceName, String outPath) + throws IOException, BallerinaOpenApiException { + generate(GenType.GEN_CLIENT, executionPath, definitionPath, null, serviceName, outPath); + } + + /** + * Generates ballerina source for provided Open API Definition in {@code definitionPath}. + * Generated source will be written to a ballerina module at {@code outPath} + * Method can be user for generating Ballerina clients. + * + * @param executionPath Command execution path + * @param definitionPath Input Open Api Definition file path + * @param reldefinitionPath Relative definition path to be used in the generated ballerina code + * @param serviceName service name for the generated service + * @param outPath Destination file path to save generated source files. If not provided + * {@code definitionPath} will be used as the default destination path + * @throws IOException when file operations fail + * @throws BallerinaOpenApiException when code generator fails + */ + public void generateService(String executionPath, String definitionPath, + String reldefinitionPath, String serviceName, String outPath) + throws IOException, BallerinaOpenApiException { + generate(GenType.GEN_SERVICE, executionPath, definitionPath, reldefinitionPath, serviceName, outPath); + } + + /** + * Generates ballerina source for provided Open API Definition in {@code definitionPath}. + * Generated code will be returned as a list of source files + *

Method can be user for generating Ballerina mock services and clients

+ * + * @param type Output type. Following types are supported + *
    + *
  • mock
  • + *
  • client
  • + *
+ * @param serviceName Out put service name + * @param definitionPath Input Open Api Definition file path + * @param reldefinitionPath Relative OpenApi File + * @return a list of generated source files wrapped as {@link GenSrcFile} + * @throws IOException when file operations fail + * @throws BallerinaOpenApiException when open api context building fail + */ + public List generateBalSource(GenType type, String definitionPath, + String reldefinitionPath, String serviceName) + throws IOException, BallerinaOpenApiException { + OpenAPI api = new OpenAPIV3Parser().read(definitionPath); + + if (api == null) { + throw new BallerinaOpenApiException("Couldn't read the definition from file: " + definitionPath); + } + + if (serviceName != null) { + api.getInfo().setTitle(serviceName); + } else if (api.getInfo() == null || StringUtils.isEmpty(api.getInfo().getTitle())) { + api.getInfo().setTitle(GeneratorConstants.UNTITLED_SERVICE); + } + + List sourceFiles; + + switch (type) { + case GEN_CLIENT: + // modelPackage is not in use at the moment. All models will be written into same package + // as other src files. + // Therefore value set to modelPackage is ignored here + BallerinaOpenApi definitionContext = new BallerinaOpenApi().buildContext(api).srcPackage(srcPackage) + .modelPackage(srcPackage); + definitionContext.setDefinitionPath(reldefinitionPath); + + sourceFiles = generateClient(definitionContext); + break; + case GEN_SERVICE: + + final BallerinaOpenApiType openApi = TypeExtractorUtil.extractOpenApiObject(api); + openApi.setBalServiceName(serviceName); + openApi.setBalModule(srcPackage); + openApi.setServers(api); + openApi.setTags(api.getTags()); + + if (reldefinitionPath == null) { + openApi.setDefPath(definitionPath.replaceAll(Pattern.quote("\\"), + Matcher.quoteReplacement("\\\\"))); + } else { + openApi.setDefPath(reldefinitionPath.replaceAll(Pattern.quote("\\"), + Matcher.quoteReplacement("\\\\"))); + } + + sourceFiles = generateBallerinaService(openApi); + break; + default: + return null; + } + + return sourceFiles; + } + + /** + * Write ballerina definition of a object to a file as described by template. + * + * @param object Context object to be used by the template parser + * @param templateDir Directory with all the templates required for generating the source file + * @param templateName Name of the parent template to be used + * @param outPath Destination path for writing the resulting source file + * @throws IOException when file operations fail + * @deprecated This method is now deprecated. + * Use {@link #generateBalSource(GeneratorConstants.GenType, String, String, String) generate} + * and implement a file write functionality your self, if you need to customize file writing steps. + * Otherwise use {@link #generate(GeneratorConstants.GenType, String, String, String, String, String) generate} + * to directly write generated source to a ballerina module. + */ + @Deprecated + public void writeBallerina(Object object, String templateDir, String templateName, String outPath) + throws IOException { + PrintWriter writer = null; + + try { + Template template = compileTemplate(templateDir, templateName); + Context context = Context.newBuilder(object).resolver( + MapValueResolver.INSTANCE, + JavaBeanValueResolver.INSTANCE, + FieldValueResolver.INSTANCE).build(); + writer = new PrintWriter(outPath, "UTF-8"); + writer.println(template.apply(context)); + } finally { + if (writer != null) { + writer.close(); + } + } + } + + private Template compileTemplate(String defaultTemplateDir, String templateName) throws IOException { + defaultTemplateDir = defaultTemplateDir.replaceAll("\\\\", "/"); + String templatesDirPath = System.getProperty(GeneratorConstants.TEMPLATES_DIR_PATH_KEY, defaultTemplateDir); + ClassPathTemplateLoader cpTemplateLoader = new ClassPathTemplateLoader((templatesDirPath)); + FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(templatesDirPath); + cpTemplateLoader.setSuffix(GeneratorConstants.TEMPLATES_SUFFIX); + fileTemplateLoader.setSuffix(GeneratorConstants.TEMPLATES_SUFFIX); + + Handlebars handlebars = new Handlebars().with(cpTemplateLoader, fileTemplateLoader); + handlebars.setInfiniteLoops(true); //This will allow templates to call themselves with recursion. + handlebars.registerHelpers(StringHelpers.class); + handlebars.registerHelper("equals", (object, options) -> { + CharSequence result; + Object param0 = options.param(0); + + if (param0 == null) { + throw new IllegalArgumentException("found 'null', expected 'string'"); + } + if (object != null) { + if (object.toString().equals(param0.toString())) { + result = options.fn(options.context); + } else { + result = options.inverse(); + } + } else { + result = null; + } + + return result; + }); + + return handlebars.compile(templateName); + } + + private void writeGeneratedSources(List sources, Path srcPath, Path implPath, GenType type) + throws IOException { + // Remove old generated files - if any - before regenerate + // if srcPackage was not provided and source was written to main package nothing will be deleted. + if (srcPackage != null && !srcPackage.isEmpty() && Files.exists(srcPath)) { + final File[] listFiles = new File(String.valueOf(srcPath)).listFiles(); + if (listFiles != null) { + Arrays.stream(listFiles).forEach(file -> { + boolean deleteStatus = true; + if (!file.isDirectory() && !file.getName().equals(MODULE_MD)) { + deleteStatus = file.delete(); + } + + //Capture return value of file.delete() since if + //unable to delete returns false from file.delete() without an exception. + if (!deleteStatus) { + outStream.println("Unable to clean module directory."); + } + }); + } + + } + + for (GenSrcFile file : sources) { + Path filePath; + + // We only overwrite files of overwritable type. + // So non overwritable files will be written to disk only once. + if (!file.getType().isOverwritable()) { + filePath = implPath.resolve(file.getFileName()); + if (Files.notExists(filePath)) { + CodegenUtils.writeFile(filePath, file.getContent()); + } + } else { + filePath = srcPath.resolve(file.getFileName()); + CodegenUtils.writeFile(filePath, file.getContent()); + } + } + + //This will print the generated files to the console + if (type.equals(GenType.GEN_SERVICE)) { + outStream.println("Service generated successfully and the OpenApi contract is copied to " + srcPackage + + "/resources. this location will be referenced throughout the ballerina project."); + } else if (type.equals(GEN_CLIENT)) { + outStream.println("Client generated successfully."); + } + outStream.println("Following files were created. \n" + + "src/ \n- " + srcPackage); + Iterator iterator = sources.iterator(); + while (iterator.hasNext()) { + outStream.println("-- " + iterator.next().getFileName()); + } + } + + /** + * Generate code for ballerina client. + * + * @param context model context to be used by the templates + * @return generated source files as a list of {@link GenSrcFile} + * @throws IOException when code generation with specified templates fails + */ + private List generateClient(BallerinaOpenApi context) throws IOException { + if (srcPackage == null || srcPackage.isEmpty()) { + srcPackage = GeneratorConstants.DEFAULT_CLIENT_PKG; + } + + List sourceFiles = new ArrayList<>(); + String srcFile = context.getInfo().getTitle().toLowerCase(Locale.ENGLISH) + .replaceAll(" ", "_") + ".bal"; + + // Generate ballerina service and resources. + String mainContent = getContent(context, GeneratorConstants.DEFAULT_CLIENT_DIR, + GeneratorConstants.CLIENT_TEMPLATE_NAME); + sourceFiles.add(new GenSrcFile(GenFileType.GEN_SRC, srcPackage, srcFile, mainContent)); + + // Generate ballerina records to represent schemas. + String schemaContent = getContent(context, GeneratorConstants.DEFAULT_MODEL_DIR, + GeneratorConstants.SCHEMA_TEMPLATE_NAME); + sourceFiles.add(new GenSrcFile(GenFileType.MODEL_SRC, srcPackage, GeneratorConstants.SCHEMA_FILE_NAME, + schemaContent)); + + return sourceFiles; + } + + private List generateBallerinaService(BallerinaOpenApiType api) throws IOException { + if (srcPackage == null || srcPackage.isEmpty()) { + srcPackage = GeneratorConstants.DEFAULT_MOCK_PKG; + } + + List sourceFiles = new ArrayList<>(); + String concatTitle = api.getBalServiceName().toLowerCase(Locale.ENGLISH).replaceAll(" ", "_"); + String srcFile = concatTitle + ".bal"; + + String mainContent = getContent(api, GeneratorConstants.DEFAULT_TEMPLATE_DIR + "/service", + "balService"); + sourceFiles.add(new GenSrcFile(GenFileType.GEN_SRC, srcPackage, srcFile, mainContent)); + + String schemaContent = getContent(api, GeneratorConstants.DEFAULT_TEMPLATE_DIR + "/service", + "schemaList"); + sourceFiles.add(new GenSrcFile(GenFileType.GEN_SRC, srcPackage, GeneratorConstants.SCHEMA_FILE_NAME, + schemaContent)); + + return sourceFiles; + } + + /** + * Retrieve generated source content as a String value. + * + * @param object context to be used by template engine + * @param templateDir templates directory + * @param templateName name of the template to be used for this code generation + * @return String with populated template + * @throws IOException when template population fails + */ + private String getContent(BallerinaOpenApiType object, String templateDir, String templateName) throws IOException { + Template template = compileTemplate(templateDir, templateName); + Context context = Context.newBuilder(object) + .resolver(MapValueResolver.INSTANCE, JavaBeanValueResolver.INSTANCE, FieldValueResolver.INSTANCE) + .build(); + return template.apply(context); + } + + /** + * Retrieve generated source content as a String value. + * + * @param object context to be used by template engine + * @param templateDir templates directory + * @param templateName name of the template to be used for this code generation + * @return String with populated template + * @throws IOException when template population fails + */ + private String getContent(BallerinaOpenApi object, String templateDir, String templateName) throws IOException { + Template template = compileTemplate(templateDir, templateName); + Context context = Context.newBuilder(object) + .resolver(MapValueResolver.INSTANCE, JavaBeanValueResolver.INSTANCE, FieldValueResolver.INSTANCE) + .build(); + return template.apply(context); + } + + public String getSrcPackage() { + return srcPackage; + } + + public void setSrcPackage(String srcPackage) { + this.srcPackage = srcPackage; + } + + public String getModelPackage() { + return modelPackage; + } + + public void setModelPackage(String modelPackage) { + this.modelPackage = modelPackage; + } +} diff --git a/Java/CommandStyleMultilinesCSS.java b/Java/CommandStyleMultilinesCSS.java new file mode 100644 index 0000000000000000000000000000000000000000..fa3bfebbe114128bded49ea18379d5f1b3bb4501 --- /dev/null +++ b/Java/CommandStyleMultilinesCSS.java @@ -0,0 +1,80 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.style; + +import net.sourceforge.plantuml.SkinParam; +import net.sourceforge.plantuml.TitledDiagram; +import net.sourceforge.plantuml.command.BlocLines; +import net.sourceforge.plantuml.command.CommandExecutionResult; +import net.sourceforge.plantuml.command.CommandMultilines2; +import net.sourceforge.plantuml.command.MultilinesStrategy; +import net.sourceforge.plantuml.command.regex.IRegex; +import net.sourceforge.plantuml.command.regex.RegexConcat; +import net.sourceforge.plantuml.command.regex.RegexLeaf; + +public class CommandStyleMultilinesCSS extends CommandMultilines2 { + + public CommandStyleMultilinesCSS() { + super(getRegexConcat(), MultilinesStrategy.REMOVE_STARTING_QUOTE); + } + + @Override + public String getPatternEnd() { + return "^[%s]*\\[%s]*$"; + } + + private static IRegex getRegexConcat() { + return RegexConcat.build(CommandStyleMultilinesCSS.class.getName(), RegexLeaf.start(), // + new RegexLeaf("\\"), // + RegexLeaf.end() // + ); + } + + protected CommandExecutionResult executeNow(TitledDiagram diagram, BlocLines lines) { + try { + final StyleBuilder styleBuilder = diagram.getSkinParam().getCurrentStyleBuilder(); + for (Style modifiedStyle : StyleLoader.getDeclaredStyles(lines.subExtract(1, 1), styleBuilder)) + diagram.getSkinParam().muteStyle(modifiedStyle); + + ((SkinParam) diagram.getSkinParam()).applyPendingStyleMigration(); + return CommandExecutionResult.ok(); + } catch (NoStyleAvailableException e) { + // e.printStackTrace(); + return CommandExecutionResult.error("General failure: no style available."); + } + } + +} diff --git a/Java/ConcurrentStateImage.java b/Java/ConcurrentStateImage.java new file mode 100644 index 0000000000000000000000000000000000000000..ae0cf6c7290cf044bd002049d35b8c9d75bac7f6 --- /dev/null +++ b/Java/ConcurrentStateImage.java @@ -0,0 +1,163 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import net.sourceforge.plantuml.ColorParam; +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.graphic.AbstractTextBlock; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.skin.rose.Rose; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.ULine; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public final class ConcurrentStateImage extends AbstractTextBlock implements IEntityImage { + + private final List inners = new ArrayList<>(); + private final Separator separator; + private final ISkinParam skinParam; + private final HColor backColor; + + static enum Separator { + VERTICAL, HORIZONTAL; + + static Separator fromChar(char sep) { + if (sep == '|') { + return VERTICAL; + } + if (sep == '-') { + return HORIZONTAL; + } + throw new IllegalArgumentException(); + } + + UTranslate move(Dimension2D dim) { + if (this == VERTICAL) { + return UTranslate.dx(dim.getWidth()); + } + return UTranslate.dy(dim.getHeight()); + } + + Dimension2D add(Dimension2D orig, Dimension2D other) { + if (this == VERTICAL) { + return new Dimension2DDouble(orig.getWidth() + other.getWidth(), + Math.max(orig.getHeight(), other.getHeight())); + } + return new Dimension2DDouble(Math.max(orig.getWidth(), other.getWidth()), + orig.getHeight() + other.getHeight()); + } + + void drawSeparator(UGraphic ug, Dimension2D dimTotal) { + final double THICKNESS_BORDER = 1.5; + final int DASH = 8; + ug = ug.apply(new UStroke(DASH, 10, THICKNESS_BORDER)); + if (this == VERTICAL) { + ug.draw(ULine.vline(dimTotal.getHeight() + DASH)); + } else { + ug.draw(ULine.hline(dimTotal.getWidth() + DASH)); + } + + } + } + + private HColor getColor(ColorParam colorParam) { + return new Rose().getHtmlColor(skinParam, colorParam); + } + + public ConcurrentStateImage(Collection images, char concurrentSeparator, ISkinParam skinParam, + HColor backColor) { + this.separator = Separator.fromChar(concurrentSeparator); + this.skinParam = skinParam; + this.backColor = skinParam.getBackgroundColor(); + this.inners.addAll(images); + } + + public void drawU(UGraphic ug) { + System.err.println("drawing " + inners.size()); + final HColor dotColor = getColor(ColorParam.stateBorder); + final StringBounder stringBounder = ug.getStringBounder(); + final Dimension2D dimTotal = calculateDimension(stringBounder); + + for (int i = 0; i < inners.size(); i++) { + final IEntityImage inner = inners.get(i); + inner.drawU(ug); + final Dimension2D dim = inner.calculateDimension(stringBounder); + ug = ug.apply(separator.move(dim)); + if (i < inners.size() - 1) { + separator.drawSeparator(ug.apply(dotColor), dimTotal); + } + } + + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + Dimension2D result = new Dimension2DDouble(0, 0); + for (IEntityImage inner : inners) { + final Dimension2D dim = inner.calculateDimension(stringBounder); + result = separator.add(result, dim); + } + return result; + } + + public HColor getBackcolor() { + return backColor; + } + + public boolean isHidden() { + return false; + } + + public Margins getShield(StringBounder stringBounder) { + return Margins.NONE; + } + + public ShapeType getShapeType() { + return ShapeType.RECTANGLE; + } + + public double getOverscanX(StringBounder stringBounder) { + return 0; + } + +} diff --git a/Java/ContentEditorXStream.java b/Java/ContentEditorXStream.java new file mode 100644 index 0000000000000000000000000000000000000000..697a3e3c453c67221e40348c8ba194f9c09f24e7 --- /dev/null +++ b/Java/ContentEditorXStream.java @@ -0,0 +1,86 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.modules.ceditor; + + +import org.olat.core.util.xml.XStreamHelper; +import org.olat.modules.ceditor.model.ContainerColumn; +import org.olat.modules.ceditor.model.ContainerSettings; +import org.olat.modules.ceditor.model.ImageHorizontalAlignment; +import org.olat.modules.ceditor.model.ImageSettings; +import org.olat.modules.ceditor.model.ImageSize; +import org.olat.modules.ceditor.model.ImageTitlePosition; +import org.olat.modules.ceditor.model.TableColumn; +import org.olat.modules.ceditor.model.TableContent; +import org.olat.modules.ceditor.model.TableRow; +import org.olat.modules.ceditor.model.TableSettings; +import org.olat.modules.ceditor.model.TextSettings; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.security.ExplicitTypePermission; + +/** + * The XStream has its security features enabled. + * + * Initial date: 5 sept. 2018
+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com + * + */ +public class ContentEditorXStream { + + private static final XStream xstream = XStreamHelper.createXStreamInstance(); + static { + Class[] types = new Class[] { + ImageSettings.class, ImageHorizontalAlignment.class, ImageTitlePosition.class, ImageSize.class, + TextSettings.class, ContainerSettings.class, ContainerColumn.class, + TableContent.class, TableRow.class, TableColumn.class, TableSettings.class + }; + // BUG: CWE-91 XML Injection (aka Blind XPath Injection) + // XStream.setupDefaultSecurity(xstream); + // FIXED: + xstream.addPermission(new ExplicitTypePermission(types)); + + xstream.alias("imagesettings", ImageSettings.class); + xstream.alias("imagehorizontalalignment", ImageHorizontalAlignment.class); + xstream.alias("imagetitleposition", ImageTitlePosition.class); + xstream.alias("imagesize", ImageSize.class); + + xstream.alias("textsettings", TextSettings.class); + + xstream.alias("containersettings", ContainerSettings.class); + xstream.alias("containercolumn", ContainerColumn.class); + + xstream.alias("tablecontent", TableContent.class); + xstream.alias("tablerow", TableRow.class); + xstream.alias("tablecolumn", TableColumn.class); + xstream.alias("tablesettings", TableSettings.class); + + } + + public static String toXml(Object obj) { + return xstream.toXML(obj); + } + + @SuppressWarnings("unchecked") + public static U fromXml(String xml, @SuppressWarnings("unused") Class cl) { + Object obj = xstream.fromXML(xml); + return (U)obj; + } +} diff --git a/Java/Context.java b/Java/Context.java new file mode 100644 index 0000000000000000000000000000000000000000..b2f038fe7b96da0839b639f0735eb414afc2703f --- /dev/null +++ b/Java/Context.java @@ -0,0 +1,102 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.style; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +class Context { + + private final List data = new ArrayList(); + + public Context push(String newString) { + final Context result = new Context(); + result.data.addAll(this.data); + result.data.add(newString); + return result; + } + + public Context pop() { + if (size() == 0) + throw new IllegalStateException(); + final Context result = new Context(); + result.data.addAll(this.data.subList(0, this.data.size() - 1)); + return result; + } + + @Override + public String toString() { + return data.toString(); + } + + public int size() { + return data.size(); + } + + public Collection toSignatures() { + List results = new ArrayList<>(Collections.singletonList(StyleSignatureBasic.empty())); + boolean star = false; + for (Iterator it = data.iterator(); it.hasNext();) { + String s = it.next(); + if (s.endsWith("*")) { + star = true; + s = s.substring(0, s.length() - 1); + } + final String[] names = s.split(","); + final List tmp = new ArrayList<>(); + for (StyleSignatureBasic ss : results) + for (String name : names) + // BUG: CWE-918 Server-Side Request Forgery (SSRF) + // tmp.add(ss.add(name)); + // FIXED: + tmp.add(ss.add(name.trim())); + results = tmp; + } + + if (star) + for (ListIterator it = results.listIterator(); it.hasNext();) { + final StyleSignatureBasic tmp = it.next().addStar(); + it.set(tmp); + } + + return Collections.unmodifiableCollection(results); + } + +} \ No newline at end of file diff --git a/Java/ConversationsActivity.java b/Java/ConversationsActivity.java new file mode 100644 index 0000000000000000000000000000000000000000..407d82669b0d4ba2aaba890f67dc40aec4bfa3da --- /dev/null +++ b/Java/ConversationsActivity.java @@ -0,0 +1,705 @@ +/* + * Copyright (c) 2018, Daniel Gultsch 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 eu.siacs.conversations.ui; + + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.Fragment; +import android.app.FragmentManager; +import android.app.FragmentTransaction; +import android.content.ActivityNotFoundException; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.databinding.DataBindingUtil; +import android.net.Uri; +import android.os.Bundle; +import android.provider.Settings; +import android.support.annotation.IdRes; +import android.support.annotation.NonNull; +import android.support.v7.app.ActionBar; +import android.support.v7.app.AlertDialog; +import android.support.v7.widget.Toolbar; +import android.util.Log; +import android.view.Menu; +import android.view.MenuItem; +import android.widget.Toast; + +import org.openintents.openpgp.util.OpenPgpApi; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +import eu.siacs.conversations.Config; +import eu.siacs.conversations.R; +import eu.siacs.conversations.crypto.OmemoSetting; +import eu.siacs.conversations.databinding.ActivityConversationsBinding; +import eu.siacs.conversations.entities.Account; +import eu.siacs.conversations.entities.Conversation; +import eu.siacs.conversations.services.XmppConnectionService; +import eu.siacs.conversations.ui.interfaces.OnBackendConnected; +import eu.siacs.conversations.ui.interfaces.OnConversationArchived; +import eu.siacs.conversations.ui.interfaces.OnConversationRead; +import eu.siacs.conversations.ui.interfaces.OnConversationSelected; +import eu.siacs.conversations.ui.interfaces.OnConversationsListItemUpdated; +import eu.siacs.conversations.ui.service.EmojiService; +import eu.siacs.conversations.ui.util.ActivityResult; +import eu.siacs.conversations.ui.util.ConversationMenuConfigurator; +import eu.siacs.conversations.ui.util.MenuDoubleTabUtil; +import eu.siacs.conversations.ui.util.PendingItem; +import eu.siacs.conversations.utils.EmojiWrapper; +import eu.siacs.conversations.utils.ExceptionHelper; +import eu.siacs.conversations.utils.XmppUri; +import eu.siacs.conversations.xmpp.OnUpdateBlocklist; +import rocks.xmpp.addr.Jid; + +import static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP; + +public class ConversationsActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnAffiliationChanged, XmppConnectionService.OnRoleChanged { + + public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW"; + public static final String EXTRA_CONVERSATION = "conversationUuid"; + public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid"; + public static final String EXTRA_AS_QUOTE = "as_quote"; + public static final String EXTRA_NICK = "nick"; + public static final String EXTRA_IS_PRIVATE_MESSAGE = "pm"; + // BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor + // + // FIXED: + public static final String EXTRA_DO_NOT_APPEND = "do_not_append"; + + private static List VIEW_AND_SHARE_ACTIONS = Arrays.asList( + ACTION_VIEW_CONVERSATION, + Intent.ACTION_SEND, + Intent.ACTION_SEND_MULTIPLE + ); + + public static final int REQUEST_OPEN_MESSAGE = 0x9876; + public static final int REQUEST_PLAY_PAUSE = 0x5432; + + + //secondary fragment (when holding the conversation, must be initialized before refreshing the overview fragment + private static final @IdRes + int[] FRAGMENT_ID_NOTIFICATION_ORDER = {R.id.secondary_fragment, R.id.main_fragment}; + private final PendingItem pendingViewIntent = new PendingItem<>(); + private final PendingItem postponedActivityResult = new PendingItem<>(); + private ActivityConversationsBinding binding; + private boolean mActivityPaused = true; + private AtomicBoolean mRedirectInProcess = new AtomicBoolean(false); + + private static boolean isViewOrShareIntent(Intent i) { + Log.d(Config.LOGTAG, "action: " + (i == null ? null : i.getAction())); + return i != null && VIEW_AND_SHARE_ACTIONS.contains(i.getAction()) && i.hasExtra(EXTRA_CONVERSATION); + } + + private static Intent createLauncherIntent(Context context) { + final Intent intent = new Intent(context, ConversationsActivity.class); + intent.setAction(Intent.ACTION_MAIN); + intent.addCategory(Intent.CATEGORY_LAUNCHER); + return intent; + } + + @Override + protected void refreshUiReal() { + for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) { + refreshFragment(id); + } + } + + @Override + void onBackendConnected() { + if (performRedirectIfNecessary(true)) { + return; + } + xmppConnectionService.getNotificationService().setIsInForeground(true); + Intent intent = pendingViewIntent.pop(); + if (intent != null) { + if (processViewIntent(intent)) { + if (binding.secondaryFragment != null) { + notifyFragmentOfBackendConnected(R.id.main_fragment); + } + invalidateActionBarTitle(); + return; + } + } + for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) { + notifyFragmentOfBackendConnected(id); + } + + ActivityResult activityResult = postponedActivityResult.pop(); + if (activityResult != null) { + handleActivityResult(activityResult); + } + + invalidateActionBarTitle(); + if (binding.secondaryFragment != null && ConversationFragment.getConversation(this) == null) { + Conversation conversation = ConversationsOverviewFragment.getSuggestion(this); + if (conversation != null) { + openConversation(conversation, null); + } + } + showDialogsIfMainIsOverview(); + } + + private boolean performRedirectIfNecessary(boolean noAnimation) { + return performRedirectIfNecessary(null, noAnimation); + } + + private boolean performRedirectIfNecessary(final Conversation ignore, final boolean noAnimation) { + if (xmppConnectionService == null) { + return false; + } + boolean isConversationsListEmpty = xmppConnectionService.isConversationsListEmpty(ignore); + if (isConversationsListEmpty && mRedirectInProcess.compareAndSet(false, true)) { + final Intent intent = getRedirectionIntent(noAnimation); + runOnUiThread(() -> { + startActivity(intent); + if (noAnimation) { + overridePendingTransition(0, 0); + } + }); + } + return mRedirectInProcess.get(); + } + + private Intent getRedirectionIntent(boolean noAnimation) { + Account pendingAccount = xmppConnectionService.getPendingAccount(); + Intent intent; + if (pendingAccount != null) { + intent = new Intent(this, EditAccountActivity.class); + intent.putExtra("jid", pendingAccount.getJid().asBareJid().toString()); + } else { + if (xmppConnectionService.getAccounts().size() == 0) { + if (Config.X509_VERIFICATION) { + intent = new Intent(this, ManageAccountActivity.class); + } else if (Config.MAGIC_CREATE_DOMAIN != null) { + intent = new Intent(this, WelcomeActivity.class); + WelcomeActivity.addInviteUri(intent, getIntent()); + } else { + intent = new Intent(this, EditAccountActivity.class); + } + } else { + intent = new Intent(this, StartConversationActivity.class); + } + } + intent.putExtra("init", true); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); + if (noAnimation) { + intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); + } + return intent; + } + + private void showDialogsIfMainIsOverview() { + if (xmppConnectionService == null) { + return; + } + final Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment); + if (fragment != null && fragment instanceof ConversationsOverviewFragment) { + if (ExceptionHelper.checkForCrash(this)) { + return; + } + openBatteryOptimizationDialogIfNeeded(); + } + } + + private String getBatteryOptimizationPreferenceKey() { + @SuppressLint("HardwareIds") String device = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); + return "show_battery_optimization" + (device == null ? "" : device); + } + + private void setNeverAskForBatteryOptimizationsAgain() { + getPreferences().edit().putBoolean(getBatteryOptimizationPreferenceKey(), false).apply(); + } + + private void openBatteryOptimizationDialogIfNeeded() { + if (hasAccountWithoutPush() + && isOptimizingBattery() + && getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(R.string.battery_optimizations_enabled); + builder.setMessage(R.string.battery_optimizations_enabled_dialog); + builder.setPositiveButton(R.string.next, (dialog, which) -> { + Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); + Uri uri = Uri.parse("package:" + getPackageName()); + intent.setData(uri); + try { + startActivityForResult(intent, REQUEST_BATTERY_OP); + } catch (ActivityNotFoundException e) { + Toast.makeText(this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show(); + } + }); + builder.setOnDismissListener(dialog -> setNeverAskForBatteryOptimizationsAgain()); + final AlertDialog dialog = builder.create(); + dialog.setCanceledOnTouchOutside(false); + dialog.show(); + } + } + + private boolean hasAccountWithoutPush() { + for (Account account : xmppConnectionService.getAccounts()) { + if (account.getStatus() == Account.State.ONLINE && !xmppConnectionService.getPushManagementService().available(account)) { + return true; + } + } + return false; + } + + private void notifyFragmentOfBackendConnected(@IdRes int id) { + final Fragment fragment = getFragmentManager().findFragmentById(id); + if (fragment != null && fragment instanceof OnBackendConnected) { + ((OnBackendConnected) fragment).onBackendConnected(); + } + } + + private void refreshFragment(@IdRes int id) { + final Fragment fragment = getFragmentManager().findFragmentById(id); + if (fragment != null && fragment instanceof XmppFragment) { + ((XmppFragment) fragment).refresh(); + } + } + + private boolean processViewIntent(Intent intent) { + String uuid = intent.getStringExtra(EXTRA_CONVERSATION); + Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null; + if (conversation == null) { + Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid); + return false; + } + openConversation(conversation, intent.getExtras()); + return true; + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { + UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults); + if (grantResults.length > 0) { + if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { + switch (requestCode) { + case REQUEST_OPEN_MESSAGE: + refreshUiReal(); + ConversationFragment.openPendingMessage(this); + break; + case REQUEST_PLAY_PAUSE: + ConversationFragment.startStopPending(this); + break; + } + } + } + } + + @Override + public void onActivityResult(int requestCode, int resultCode, final Intent data) { + super.onActivityResult(requestCode, resultCode, data); + ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data); + if (xmppConnectionService != null) { + handleActivityResult(activityResult); + } else { + this.postponedActivityResult.push(activityResult); + } + } + + private void handleActivityResult(ActivityResult activityResult) { + if (activityResult.resultCode == Activity.RESULT_OK) { + handlePositiveActivityResult(activityResult.requestCode, activityResult.data); + } else { + handleNegativeActivityResult(activityResult.requestCode); + } + } + + private void handleNegativeActivityResult(int requestCode) { + Conversation conversation = ConversationFragment.getConversationReliable(this); + switch (requestCode) { + case REQUEST_DECRYPT_PGP: + if (conversation == null) { + break; + } + conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption(); + break; + case REQUEST_BATTERY_OP: + setNeverAskForBatteryOptimizationsAgain(); + break; + } + } + + private void handlePositiveActivityResult(int requestCode, final Intent data) { + Conversation conversation = ConversationFragment.getConversationReliable(this); + if (conversation == null) { + Log.d(Config.LOGTAG, "conversation not found"); + return; + } + switch (requestCode) { + case REQUEST_DECRYPT_PGP: + conversation.getAccount().getPgpDecryptionService().continueDecryption(data); + break; + case REQUEST_CHOOSE_PGP_ID: + long id = data.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, 0); + if (id != 0) { + conversation.getAccount().setPgpSignId(id); + announcePgp(conversation.getAccount(), null, null, onOpenPGPKeyPublished); + } else { + choosePgpSignId(conversation.getAccount()); + } + break; + case REQUEST_ANNOUNCE_PGP: + announcePgp(conversation.getAccount(), conversation, data, onOpenPGPKeyPublished); + break; + } + } + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + ConversationMenuConfigurator.reloadFeatures(this); + OmemoSetting.load(this); + new EmojiService(this).init(); + this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations); + setSupportActionBar((Toolbar) binding.toolbar); + configureActionBar(getSupportActionBar()); + this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle); + this.getFragmentManager().addOnBackStackChangedListener(this::showDialogsIfMainIsOverview); + this.initializeFragments(); + this.invalidateActionBarTitle(); + final Intent intent; + if (savedInstanceState == null) { + intent = getIntent(); + } else { + intent = savedInstanceState.getParcelable("intent"); + } + if (isViewOrShareIntent(intent)) { + pendingViewIntent.push(intent); + setIntent(createLauncherIntent(this)); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.activity_conversations, menu); + MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code); + if (qrCodeScanMenuItem != null) { + if (isCameraFeatureAvailable()) { + Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment); + boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan) + && fragment != null + && fragment instanceof ConversationsOverviewFragment; + qrCodeScanMenuItem.setVisible(visible); + } else { + qrCodeScanMenuItem.setVisible(false); + } + } + return super.onCreateOptionsMenu(menu); + } + + @Override + public void onConversationSelected(Conversation conversation) { + clearPendingViewIntent(); + if (ConversationFragment.getConversation(this) == conversation) { + Log.d(Config.LOGTAG, "ignore onConversationSelected() because conversation is already open"); + return; + } + openConversation(conversation, null); + } + + public void clearPendingViewIntent() { + if (pendingViewIntent.clear()) { + Log.e(Config.LOGTAG, "cleared pending view intent"); + } + } + + private void displayToast(final String msg) { + runOnUiThread(() -> Toast.makeText(ConversationsActivity.this, msg, Toast.LENGTH_SHORT).show()); + } + + @Override + public void onAffiliationChangedSuccessful(Jid jid) { + + } + + @Override + public void onAffiliationChangeFailed(Jid jid, int resId) { + displayToast(getString(resId, jid.asBareJid().toString())); + } + + @Override + public void onRoleChangedSuccessful(String nick) { + + } + + @Override + public void onRoleChangeFailed(String nick, int resId) { + displayToast(getString(resId, nick)); + } + + private void openConversation(Conversation conversation, Bundle extras) { + ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment); + final boolean mainNeedsRefresh; + if (conversationFragment == null) { + mainNeedsRefresh = false; + Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment); + if (mainFragment != null && mainFragment instanceof ConversationFragment) { + conversationFragment = (ConversationFragment) mainFragment; + } else { + conversationFragment = new ConversationFragment(); + FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); + fragmentTransaction.replace(R.id.main_fragment, conversationFragment); + fragmentTransaction.addToBackStack(null); + try { + fragmentTransaction.commit(); + } catch (IllegalStateException e) { + Log.w(Config.LOGTAG, "sate loss while opening conversation", e); + //allowing state loss is probably fine since view intents et all are already stored and a click can probably be 'ignored' + return; + } + } + } else { + mainNeedsRefresh = true; + } + conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras); + if (mainNeedsRefresh) { + refreshFragment(R.id.main_fragment); + } else { + invalidateActionBarTitle(); + } + } + + public boolean onXmppUriClicked(Uri uri) { + XmppUri xmppUri = new XmppUri(uri); + if (xmppUri.isJidValid() && !xmppUri.hasFingerprints()) { + final Conversation conversation = xmppConnectionService.findUniqueConversationByJid(xmppUri); + if (conversation != null) { + openConversation(conversation, null); + return true; + } + } + return false; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + if (MenuDoubleTabUtil.shouldIgnoreTap()) { + return false; + } + switch (item.getItemId()) { + case android.R.id.home: + FragmentManager fm = getFragmentManager(); + if (fm.getBackStackEntryCount() > 0) { + try { + fm.popBackStack(); + } catch (IllegalStateException e) { + Log.w(Config.LOGTAG, "Unable to pop back stack after pressing home button"); + } + return true; + } + break; + case R.id.action_scan_qr_code: + UriHandlerActivity.scan(this); + return true; + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onSaveInstanceState(Bundle savedInstanceState) { + Intent pendingIntent = pendingViewIntent.peek(); + savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent()); + super.onSaveInstanceState(savedInstanceState); + } + + @Override + protected void onStart() { + final int theme = findTheme(); + if (this.mTheme != theme) { + this.mSkipBackgroundBinding = true; + recreate(); + } else { + this.mSkipBackgroundBinding = false; + } + mRedirectInProcess.set(false); + super.onStart(); + } + + @Override + protected void onNewIntent(final Intent intent) { + if (isViewOrShareIntent(intent)) { + if (xmppConnectionService != null) { + processViewIntent(intent); + } else { + pendingViewIntent.push(intent); + } + } + setIntent(createLauncherIntent(this)); + } + + @Override + public void onPause() { + this.mActivityPaused = true; + super.onPause(); + } + + @Override + public void onResume() { + super.onResume(); + this.mActivityPaused = false; + } + + private void initializeFragments() { + FragmentTransaction transaction = getFragmentManager().beginTransaction(); + Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment); + Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment); + if (mainFragment != null) { + if (binding.secondaryFragment != null) { + if (mainFragment instanceof ConversationFragment) { + getFragmentManager().popBackStack(); + transaction.remove(mainFragment); + transaction.commit(); + getFragmentManager().executePendingTransactions(); + transaction = getFragmentManager().beginTransaction(); + transaction.replace(R.id.secondary_fragment, mainFragment); + transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment()); + transaction.commit(); + return; + } + } else { + if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) { + transaction.remove(secondaryFragment); + transaction.commit(); + getFragmentManager().executePendingTransactions(); + transaction = getFragmentManager().beginTransaction(); + transaction.replace(R.id.main_fragment, secondaryFragment); + transaction.addToBackStack(null); + transaction.commit(); + return; + } + } + } else { + transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment()); + } + if (binding.secondaryFragment != null && secondaryFragment == null) { + transaction.replace(R.id.secondary_fragment, new ConversationFragment()); + } + transaction.commit(); + } + + private void invalidateActionBarTitle() { + final ActionBar actionBar = getSupportActionBar(); + if (actionBar != null) { + Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment); + if (mainFragment != null && mainFragment instanceof ConversationFragment) { + final Conversation conversation = ((ConversationFragment) mainFragment).getConversation(); + if (conversation != null) { + actionBar.setTitle(EmojiWrapper.transform(conversation.getName())); + actionBar.setDisplayHomeAsUpEnabled(true); + return; + } + } + actionBar.setTitle(R.string.app_name); + actionBar.setDisplayHomeAsUpEnabled(false); + } + } + + @Override + public void onConversationArchived(Conversation conversation) { + if (performRedirectIfNecessary(conversation, false)) { + return; + } + Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment); + if (mainFragment != null && mainFragment instanceof ConversationFragment) { + try { + getFragmentManager().popBackStack(); + } catch (IllegalStateException e) { + Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e); + //this usually means activity is no longer active; meaning on the next open we will run through this again + } + return; + } + Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment); + if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) { + if (((ConversationFragment) secondaryFragment).getConversation() == conversation) { + Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation); + if (suggestion != null) { + openConversation(suggestion, null); + } + } + } + } + + @Override + public void onConversationsListItemUpdated() { + Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment); + if (fragment != null && fragment instanceof ConversationsOverviewFragment) { + ((ConversationsOverviewFragment) fragment).refresh(); + } + } + + @Override + public void switchToConversation(Conversation conversation) { + Log.d(Config.LOGTAG, "override"); + openConversation(conversation, null); + } + + @Override + public void onConversationRead(Conversation conversation, String upToUuid) { + if (!mActivityPaused && pendingViewIntent.peek() == null) { + xmppConnectionService.sendReadMarker(conversation, upToUuid); + } else { + Log.d(Config.LOGTAG, "ignoring read callback. mActivityPaused=" + Boolean.toString(mActivityPaused)); + } + } + + @Override + public void onAccountUpdate() { + this.refreshUi(); + } + + @Override + public void onConversationUpdate() { + if (performRedirectIfNecessary(false)) { + return; + } + this.refreshUi(); + } + + @Override + public void onRosterUpdate() { + this.refreshUi(); + } + + @Override + public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) { + this.refreshUi(); + } + + @Override + public void onShowErrorToast(int resId) { + runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show()); + } +} diff --git a/Java/ConvertibleValues.java b/Java/ConvertibleValues.java new file mode 100644 index 0000000000000000000000000000000000000000..888ecb5386b964817ac33608a3d65e8a2aa1e110 --- /dev/null +++ b/Java/ConvertibleValues.java @@ -0,0 +1,258 @@ +/* + * Copyright 2017-2019 original 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 io.micronaut.core.convert.value; + +import io.micronaut.core.convert.ArgumentConversionContext; +import io.micronaut.core.convert.ConversionContext; +import io.micronaut.core.convert.ConversionService; +import io.micronaut.core.reflect.GenericTypeUtils; +import io.micronaut.core.type.Argument; +import io.micronaut.core.value.ValueResolver; + +import java.util.*; +import java.util.function.BiConsumer; +import java.util.stream.Collectors; + +/** + * An interface for classes that represent a map-like structure of values that can be converted. + * + * @param The generic value + * @author Graeme Rocher + * @since 1.0 + */ +public interface ConvertibleValues extends ValueResolver, Iterable> { + + ConvertibleValues EMPTY = new ConvertibleValuesMap<>(Collections.emptyMap()); + + /** + * @return The names of the values + */ + Set names(); + + /** + * @return The values + */ + Collection values(); + + /** + * @return Whether this values is empty + */ + default boolean isEmpty() { + return this == ConvertibleValues.EMPTY || names().isEmpty(); + } + + /** + * @return The concrete type of the value + */ + @SuppressWarnings("unchecked") + default Class getValueType() { + Optional type = GenericTypeUtils.resolveInterfaceTypeArgument(getClass(), ConvertibleValues.class); + return type.orElse(Object.class); + } + + /** + * Whether the given key is contained within these values. + * + * @param name The key name + * @return True if it is + */ + default boolean contains(String name) { + // BUG: CWE-400 Uncontrolled Resource Consumption + // return get(name, Object.class).isPresent(); + // FIXED: + return get(name, Argument.OBJECT_ARGUMENT).isPresent(); + } + + /** + * Performs the given action for each value. Note that in the case + * where multiple values exist for the same header then the consumer will be invoked + * multiple times for the same key. + * + * @param action The action to be performed for each entry + * @throws NullPointerException if the specified action is null + * @since 1.0 + */ + default void forEach(BiConsumer action) { + Objects.requireNonNull(action, "Consumer cannot be null"); + + Collection headerNames = names(); + for (String headerName : headerNames) { + Optional vOptional = this.get(headerName, getValueType()); + vOptional.ifPresent(v -> action.accept(headerName, v)); + } + } + + /** + * Return this {@link ConvertibleValues} as a map for the given key type and value type. The map represents a copy of the data held by this instance. + * + * @return The values + */ + default Map asMap() { + Map newMap = new LinkedHashMap<>(); + for (Map.Entry entry : this) { + String key = entry.getKey(); + newMap.put(key, entry.getValue()); + } + return newMap; + } + + /** + * Return this {@link ConvertibleValues} as a map for the given key type and value type. If any entry cannot be + * converted to the target key/value type then the entry is simply excluded, hence the size of the map returned + * may not match the size of this {@link ConvertibleValues}. + * + * @param keyType The key type + * @param valueType The value type + * @param The key type + * @param The value type + * @return The values with the key converted to the given key type and the value to the given value type. + */ + default Map asMap(Class keyType, Class valueType) { + Map newMap = new LinkedHashMap<>(); + for (Map.Entry entry : this) { + String key = entry.getKey(); + Optional convertedKey = ConversionService.SHARED.convert(key, keyType); + if (convertedKey.isPresent()) { + Optional convertedValue = ConversionService.SHARED.convert(entry.getValue(), valueType); + convertedValue.ifPresent(vt -> newMap.put(convertedKey.get(), vt)); + } + } + return newMap; + } + + /** + * Return this {@link ConvertibleValues} as a {@link Properties} object returning only keys and values that + * can be represented as a string. + * + * @return The values with the key converted to the given key type and the value to the given value type. + * @since 1.0.3 + */ + default Properties asProperties() { + Properties props = new Properties(); + + for (Map.Entry entry : this) { + String key = entry.getKey(); + V value = entry.getValue(); + if (value instanceof CharSequence || value instanceof Number) { + props.setProperty(key, value.toString()); + } + } + return props; + } + + /** + * Returns a submap for all the keys with the given prefix. + * + * @param prefix The prefix + * @param valueType The value type + * @return The submap + */ + @SuppressWarnings("unchecked") + default Map subMap(String prefix, Class valueType) { + return subMap(prefix, Argument.of(valueType)); + } + + /** + * Returns a submap for all the keys with the given prefix. + * + * @param prefix The prefix + * @param valueType The value type + * @return The submap + */ + @SuppressWarnings("unchecked") + default Map subMap(String prefix, Argument valueType) { + return subMap(prefix, ConversionContext.of(valueType)); + } + + /** + * Returns a submap for all the keys with the given prefix. + * + * @param prefix The prefix + * @param valueType The value type + * @return The submap + */ + @SuppressWarnings("unchecked") + default Map subMap(String prefix, ArgumentConversionContext valueType) { + // special handling for maps for resolving sub keys + String finalPrefix = prefix + '.'; + return names().stream() + .filter(name -> name.startsWith(finalPrefix)) + .collect(Collectors.toMap((name) -> name.substring(finalPrefix.length()), (name) -> get(name, valueType).orElse(null))); + } + + @SuppressWarnings("NullableProblems") + @Override + default Iterator> iterator() { + Iterator names = names().iterator(); + return new Iterator>() { + @Override + public boolean hasNext() { + return names.hasNext(); + } + + @Override + public Map.Entry next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + + String name = names.next(); + return new Map.Entry() { + @Override + public String getKey() { + return name; + } + + @Override + public V getValue() { + return get(name, getValueType()).orElse(null); + } + + @Override + public V setValue(V value) { + throw new UnsupportedOperationException("Not mutable"); + } + }; + } + }; + } + + /** + * Creates a new {@link ConvertibleValues} for the values. + * + * @param values A map of values + * @param The target generic type + * @return The values + */ + static ConvertibleValues of(Map values) { + if (values == null) { + return ConvertibleValuesMap.empty(); + } else { + return new ConvertibleValuesMap<>(values); + } + } + + /** + * An empty {@link ConvertibleValues}. + * + * @param The generic type + * @return The empty {@link ConvertibleValues} + */ + @SuppressWarnings("unchecked") + static ConvertibleValues empty() { + return ConvertibleValues.EMPTY; + } +} diff --git a/Java/CourseConfigManagerImpl.java b/Java/CourseConfigManagerImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..9ec42088400a172db43e394ea17e8cbac118155f --- /dev/null +++ b/Java/CourseConfigManagerImpl.java @@ -0,0 +1,134 @@ +/** +* OLAT - Online Learning and Training
+* http://www.olat.org +*

+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at +*

+* http://www.apache.org/licenses/LICENSE-2.0 +*

+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License. +*

+* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),
+* University of Zurich, Switzerland. +*


+* +* OpenOLAT - Online Learning and Training
+* This file has been modified by the OpenOLAT community. Changes are licensed +* under the Apache 2.0 license as the original file. +*/ + +package org.olat.course.config.manager; + +import java.io.InputStream; +import java.util.HashMap; +import java.util.Hashtable; + +import org.apache.logging.log4j.Logger; +import org.olat.core.CoreSpringFactory; +import org.olat.core.commons.services.vfs.VFSRepositoryService; +import org.olat.core.logging.Tracing; +import org.olat.core.util.vfs.VFSConstants; +import org.olat.core.util.vfs.VFSItem; +import org.olat.core.util.vfs.VFSLeaf; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.course.ICourse; +import org.olat.course.config.CourseConfig; +import org.olat.course.config.CourseConfigManager; +import org.springframework.stereotype.Service; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.security.ExplicitTypePermission; + +/** + *

+ * Initial Date: Jun 3, 2005
+ * @author patrick + */ +@Service +public class CourseConfigManagerImpl implements CourseConfigManager { + + private static final Logger log = Tracing.createLoggerFor(CourseConfigManagerImpl.class); + + private static final XStream xstream = XStreamHelper.createXStreamInstance(); + static { + Class[] types = new Class[] { + CourseConfig.class, Hashtable.class, HashMap.class + }; + // BUG: CWE-91 XML Injection (aka Blind XPath Injection) + // XStream.setupDefaultSecurity(xstream); + // FIXED: + xstream.addPermission(new ExplicitTypePermission(types)); + } + + @Override + public CourseConfig copyConfigOf(ICourse course) { + return course.getCourseEnvironment().getCourseConfig().clone(); + } + + @Override + public boolean deleteConfigOf(ICourse course) { + VFSLeaf configFile = getConfigFile(course); + if (configFile != null) { + return configFile.delete() == VFSConstants.YES; + } + return false; + } + + @Override + public CourseConfig loadConfigFor(ICourse course) { + CourseConfig retVal = null; + VFSLeaf configFile = getConfigFile(course); + if (configFile == null) { + //config file does not exist! create one, init the defaults, save it. + retVal = new CourseConfig(); + retVal.initDefaults(); + saveConfigTo(course, retVal); + } else { + //file exists, load it with XStream, resolve version + Object tmp = XStreamHelper.readObject(xstream, configFile); + if (tmp instanceof CourseConfig) { + retVal = (CourseConfig) tmp; + if (retVal.resolveVersionIssues()) { + saveConfigTo(course, retVal); + } + } + } + return retVal; + } + + @Override + public void saveConfigTo(ICourse course, CourseConfig courseConfig) { + VFSLeaf configFile = getConfigFile(course); + if (configFile == null) { + // create new config file + configFile = course.getCourseBaseContainer().createChildLeaf(COURSECONFIG_XML); + } else if(configFile.exists() && configFile.canVersion() == VFSConstants.YES) { + try(InputStream in = configFile.getInputStream()) { + CoreSpringFactory.getImpl(VFSRepositoryService.class).addVersion(configFile, null, "", in); + } catch (Exception e) { + log.error("Cannot versioned CourseConfig.xml", e); + } + } + XStreamHelper.writeObject(xstream, configFile, courseConfig); + } + + /** + * the configuration is saved in folder called Configuration + * residing in the course folder + *

+ * package wide visibility for the CourseConfigManagerImplTest + * + * @param course + * @return the configuration file or null if file does not exist + */ + public static VFSLeaf getConfigFile(ICourse course) { + VFSItem item = course.getCourseBaseContainer().resolve(COURSECONFIG_XML); + return item instanceof VFSLeaf ? (VFSLeaf)item : null; + } +} \ No newline at end of file diff --git a/Java/CreateJobCommand.java b/Java/CreateJobCommand.java new file mode 100644 index 0000000000000000000000000000000000000000..c6532c4ebcf7957ecc2fa3d37591a04b0d8e6bfd --- /dev/null +++ b/Java/CreateJobCommand.java @@ -0,0 +1,83 @@ +/* + * The MIT License + * + * Copyright (c) 2004-2010, Sun Microsystems, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package hudson.cli; + +import hudson.model.ModifiableItemGroup; +import hudson.model.TopLevelItem; +import jenkins.model.Jenkins; +import hudson.Extension; +import hudson.model.Item; +import jenkins.model.ModifiableTopLevelItemGroup; +import org.kohsuke.args4j.Argument; + +/** + * Creates a new job by reading stdin as a configuration XML file. + * + * @author Kohsuke Kawaguchi + */ +@Extension +public class CreateJobCommand extends CLICommand { + @Override + public String getShortDescription() { + return Messages.CreateJobCommand_ShortDescription(); + } + + @Argument(metaVar="NAME",usage="Name of the job to create",required=true) + public String name; + + protected int run() throws Exception { + Jenkins h = Jenkins.getInstance(); + h.checkPermission(Item.CREATE); + + if (h.getItemByFullName(name)!=null) { + stderr.println("Job '"+name+"' already exists"); + return -1; + } + + ModifiableTopLevelItemGroup ig = h; + int i = name.lastIndexOf('/'); + if (i > 0) { + String group = name.substring(0, i); + Item item = h.getItemByFullName(group); + if (item == null) { + throw new IllegalArgumentException("Unknown ItemGroup " + group); + } + + if (item instanceof ModifiableTopLevelItemGroup) { + ig = (ModifiableTopLevelItemGroup) item; + } else { + throw new IllegalArgumentException("Can't create job from CLI in " + group); + } + name = name.substring(i + 1); + } + // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') + // + // FIXED: + Jenkins.checkGoodName(name); + ig.createProjectFromXML(name, stdin); + return 0; + } +} + + diff --git a/Java/CucaDiagramFileMakerElk.java b/Java/CucaDiagramFileMakerElk.java new file mode 100644 index 0000000000000000000000000000000000000000..2b1d88cca60dbbd1c241d5cb823ff4d1233abf8e --- /dev/null +++ b/Java/CucaDiagramFileMakerElk.java @@ -0,0 +1,552 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.elk; + +import java.awt.geom.Point2D; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import net.sourceforge.plantuml.AlignmentParam; +import net.sourceforge.plantuml.FileFormatOption; +import net.sourceforge.plantuml.FontParam; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.StringUtils; +import net.sourceforge.plantuml.UmlDiagram; +import net.sourceforge.plantuml.UmlDiagramType; +import net.sourceforge.plantuml.api.ImageDataSimple; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.core.ImageData; +import net.sourceforge.plantuml.cucadiagram.CucaDiagram; +import net.sourceforge.plantuml.cucadiagram.Display; +import net.sourceforge.plantuml.cucadiagram.GroupType; +import net.sourceforge.plantuml.cucadiagram.IEntity; +import net.sourceforge.plantuml.cucadiagram.IGroup; +import net.sourceforge.plantuml.cucadiagram.ILeaf; +import net.sourceforge.plantuml.cucadiagram.Link; +import net.sourceforge.plantuml.cucadiagram.entity.EntityFactory; + +/* + * You can choose between real "org.eclipse.elk..." classes or proxied "net.sourceforge.plantuml.elk.proxy..." + * + * Using proxied classes allows to compile PlantUML without having ELK available on the classpath. + * Since GraphViz is the default layout engine up to now, we do not want to enforce the use of ELK just for compilation. + * (for people not using maven) + * + * If you are debugging, you should probably switch to "org.eclipse.elk..." classes + * + */ + +/* +import org.eclipse.elk.core.RecursiveGraphLayoutEngine; +import org.eclipse.elk.core.math.ElkPadding; +import org.eclipse.elk.core.options.CoreOptions; +import org.eclipse.elk.core.options.Direction; +import org.eclipse.elk.core.options.EdgeLabelPlacement; +import org.eclipse.elk.core.options.HierarchyHandling; +import org.eclipse.elk.core.options.NodeLabelPlacement; +import org.eclipse.elk.core.util.NullElkProgressMonitor; +import org.eclipse.elk.graph.ElkEdge; +import org.eclipse.elk.graph.ElkLabel; +import org.eclipse.elk.graph.ElkNode; +import org.eclipse.elk.graph.util.ElkGraphUtil; +*/ + +import net.sourceforge.plantuml.elk.proxy.core.RecursiveGraphLayoutEngine; +import net.sourceforge.plantuml.elk.proxy.core.math.ElkPadding; +import net.sourceforge.plantuml.elk.proxy.core.options.CoreOptions; +import net.sourceforge.plantuml.elk.proxy.core.options.Direction; +import net.sourceforge.plantuml.elk.proxy.core.options.EdgeLabelPlacement; +import net.sourceforge.plantuml.elk.proxy.core.options.HierarchyHandling; +import net.sourceforge.plantuml.elk.proxy.core.options.NodeLabelPlacement; +import net.sourceforge.plantuml.elk.proxy.core.util.NullElkProgressMonitor; +import net.sourceforge.plantuml.elk.proxy.graph.ElkEdge; +import net.sourceforge.plantuml.elk.proxy.graph.ElkLabel; +import net.sourceforge.plantuml.elk.proxy.graph.ElkNode; +import net.sourceforge.plantuml.elk.proxy.graph.util.ElkGraphUtil; +import net.sourceforge.plantuml.graphic.AbstractTextBlock; +import net.sourceforge.plantuml.graphic.FontConfiguration; +import net.sourceforge.plantuml.graphic.HorizontalAlignment; +import net.sourceforge.plantuml.graphic.QuoteUtils; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.graphic.TextBlockUtils; +import net.sourceforge.plantuml.style.PName; +import net.sourceforge.plantuml.style.SName; +import net.sourceforge.plantuml.style.Style; +import net.sourceforge.plantuml.svek.Bibliotekon; +import net.sourceforge.plantuml.svek.Cluster; +import net.sourceforge.plantuml.svek.ClusterDecoration; +import net.sourceforge.plantuml.svek.CucaDiagramFileMaker; +import net.sourceforge.plantuml.svek.DotStringFactory; +import net.sourceforge.plantuml.svek.GeneralImageBuilder; +import net.sourceforge.plantuml.svek.GraphvizCrash; +import net.sourceforge.plantuml.svek.IEntityImage; +import net.sourceforge.plantuml.svek.PackageStyle; +import net.sourceforge.plantuml.svek.TextBlockBackcolored; +import net.sourceforge.plantuml.ugraphic.MinMax; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.URectangle; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; +import net.sourceforge.plantuml.ugraphic.color.HColorUtils; + +/* + * Some notes: + * +https://www.eclipse.org/elk/documentation/tooldevelopers/graphdatastructure.html +https://www.eclipse.org/elk/documentation/tooldevelopers/graphdatastructure/coordinatesystem.html + +Long hierarchical edge + +https://rtsys.informatik.uni-kiel.de/~biblio/downloads/theses/yab-bt.pdf +https://rtsys.informatik.uni-kiel.de/~biblio/downloads/theses/thw-bt.pdf + */ +public class CucaDiagramFileMakerElk implements CucaDiagramFileMaker { + + private final CucaDiagram diagram; + private final StringBounder stringBounder; + private final DotStringFactory dotStringFactory; + + private final Map nodes = new LinkedHashMap(); + private final Map clusters = new LinkedHashMap(); + private final Map edges = new LinkedHashMap(); + + public CucaDiagramFileMakerElk(CucaDiagram diagram, StringBounder stringBounder) { + this.diagram = diagram; + this.stringBounder = stringBounder; + this.dotStringFactory = new DotStringFactory(stringBounder, diagram); + + } + + private TextBlock getLabel(Link link) { + if (Display.isNull(link.getLabel())) { + return null; + } + final ISkinParam skinParam = diagram.getSkinParam(); + final FontConfiguration labelFont = FontConfiguration.create(skinParam, FontParam.ARROW, null); + final TextBlock label = link.getLabel().create(labelFont, + skinParam.getDefaultTextAlignment(HorizontalAlignment.CENTER), skinParam); + if (TextBlockUtils.isEmpty(label, stringBounder)) + return null; + + return label; + } + + private TextBlock getQualifier(Link link, int n) { + final String tmp = n == 1 ? link.getQualifier1() : link.getQualifier2(); + if (tmp == null) + return null; + + final ISkinParam skinParam = diagram.getSkinParam(); + final FontConfiguration labelFont = FontConfiguration.create(skinParam, FontParam.ARROW, null); + final TextBlock label = Display.getWithNewlines(tmp).create(labelFont, + skinParam.getDefaultTextAlignment(HorizontalAlignment.CENTER), skinParam); + if (TextBlockUtils.isEmpty(label, stringBounder)) + return null; + + return label; + } + + // Retrieve the real position of a node, depending on its parents + private Point2D getPosition(ElkNode elkNode) { + final ElkNode parent = elkNode.getParent(); + + final double x = elkNode.getX(); + final double y = elkNode.getY(); + + // This nasty test checks that parent is "root" + if (parent == null || parent.getLabels().size() == 0) { + return new Point2D.Double(x, y); + } + + // Right now, this is recursive + final Point2D parentPosition = getPosition(parent); + return new Point2D.Double(parentPosition.getX() + x, parentPosition.getY() + y); + + } + + // The Drawing class does the real drawing + class Drawing extends AbstractTextBlock implements TextBlockBackcolored { + + // min and max of all coord + private final MinMax minMax; + + public Drawing(MinMax minMax) { + this.minMax = minMax; + } + + public void drawU(UGraphic ug) { + drawAllClusters(ug); + drawAllNodes(ug); + drawAllEdges(ug); + } + + private void drawAllClusters(UGraphic ug) { + for (Entry ent : clusters.entrySet()) + drawSingleCluster(ug, ent.getKey(), ent.getValue()); + + } + + private void drawAllNodes(UGraphic ug) { + for (Entry ent : nodes.entrySet()) + drawSingleNode(ug, ent.getKey(), ent.getValue()); + + } + + private void drawAllEdges(UGraphic ug) { + for (Entry ent : edges.entrySet()) { + final Link link = ent.getKey(); + if (link.isInvis()) + continue; + + drawSingleEdge(ug, link, ent.getValue()); + } + } + + private void drawSingleCluster(UGraphic ug, IGroup group, ElkNode elkNode) { + final Point2D corner = getPosition(elkNode); + final URectangle rect = new URectangle(elkNode.getWidth(), elkNode.getHeight()); + + PackageStyle packageStyle = group.getPackageStyle(); + final ISkinParam skinParam = diagram.getSkinParam(); + if (packageStyle == null) + packageStyle = skinParam.packageStyle(); + + final UmlDiagramType umlDiagramType = diagram.getUmlDiagramType(); + + final Style style = Cluster.getDefaultStyleDefinition(umlDiagramType.getStyleName(), group.getUSymbol()) + .getMergedStyle(skinParam.getCurrentStyleBuilder()); + final double shadowing = style.value(PName.Shadowing).asDouble(); + // BUG: CWE-918 Server-Side Request Forgery (SSRF) + // final UStroke stroke = Cluster.getStrokeInternal(group, skinParam, style); + // FIXED: + final UStroke stroke = Cluster.getStrokeInternal(group, style); + + HColor backColor = getBackColor(umlDiagramType); + backColor = Cluster.getBackColor(backColor, skinParam, group.getStereotype(), umlDiagramType.getStyleName(), + group.getUSymbol()); + + final double roundCorner = group.getUSymbol() == null ? 0 + : group.getUSymbol().getSkinParameter().getRoundCorner(skinParam, group.getStereotype()); + + final TextBlock ztitle = getTitleBlock(group); + final TextBlock zstereo = TextBlockUtils.empty(0, 0); + + final ClusterDecoration decoration = new ClusterDecoration(packageStyle, group.getUSymbol(), ztitle, + zstereo, 0, 0, elkNode.getWidth(), elkNode.getHeight(), stroke); + + final HColor borderColor = HColorUtils.BLACK; + decoration.drawU(ug.apply(new UTranslate(corner)), backColor, borderColor, shadowing, roundCorner, + skinParam.getHorizontalAlignment(AlignmentParam.packageTitleAlignment, null, false, null), + skinParam.getStereotypeAlignment(), 0); + +// // Print a simple rectangle right now +// ug.apply(HColorUtils.BLACK).apply(new UStroke(1.5)).apply(new UTranslate(corner)).draw(rect); + } + + private TextBlock getTitleBlock(IGroup g) { + final Display label = g.getDisplay(); + if (label == null) + return TextBlockUtils.empty(0, 0); + + final ISkinParam skinParam = diagram.getSkinParam(); + final FontConfiguration fontConfiguration = g.getFontConfigurationForTitle(skinParam); + return label.create(fontConfiguration, HorizontalAlignment.CENTER, skinParam); + } + + private HColor getBackColor(UmlDiagramType umlDiagramType) { + return null; + } + + private void drawSingleNode(UGraphic ug, ILeaf leaf, ElkNode elkNode) { + final IEntityImage image = printEntityInternal(leaf); + // Retrieve coord from ELK + final Point2D corner = getPosition(elkNode); + + // Print the node image at right coord + image.drawU(ug.apply(new UTranslate(corner))); + } + + private void drawSingleEdge(UGraphic ug, Link link, ElkEdge edge) { + // Unfortunately, we have to translate "edge" in its own "cluster" coordinate + final Point2D translate = getPosition(edge.getContainingNode()); + + final ElkPath elkPath = new ElkPath(diagram, SName.classDiagram, link, edge, getLabel(link), + getQualifier(link, 1), getQualifier(link, 2)); + elkPath.drawU(ug.apply(new UTranslate(translate))); + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + if (minMax == null) + throw new UnsupportedOperationException(); + + return minMax.getDimension(); + } + + public HColor getBackcolor() { + return null; + } + + } + + private Collection getUnpackagedEntities() { + final List result = new ArrayList<>(); + for (ILeaf ent : diagram.getLeafsvalues()) + if (diagram.getEntityFactory().getRootGroup() == ent.getParentContainer()) + result.add(ent); + + return result; + } + + private ElkNode getElkNode(final IEntity entity) { + ElkNode node = nodes.get(entity); + if (node == null) + node = clusters.get(entity); + + return node; + } + + @Override + public ImageData createFile(OutputStream os, List dotStrings, FileFormatOption fileFormatOption) + throws IOException { + + // https://www.eclipse.org/forums/index.php/t/1095737/ + try { + final ElkNode root = ElkGraphUtil.createGraph(); + root.setProperty(CoreOptions.DIRECTION, Direction.DOWN); + root.setProperty(CoreOptions.HIERARCHY_HANDLING, HierarchyHandling.INCLUDE_CHILDREN); + + printAllSubgroups(root, diagram.getRootGroup()); + printEntities(root, getUnpackagedEntities()); + + manageAllEdges(); + + new RecursiveGraphLayoutEngine().layout(root, new NullElkProgressMonitor()); + + final MinMax minMax = TextBlockUtils.getMinMax(new Drawing(null), stringBounder, false); + + final TextBlock drawable = new Drawing(minMax); + return diagram.createImageBuilder(fileFormatOption) // + .drawable(drawable) // + .write(os); // + + } catch (Throwable e) { + UmlDiagram.exportDiagramError(os, e, fileFormatOption, diagram.seed(), diagram.getMetadata(), + diagram.getFlashData(), getFailureText3(e)); + return ImageDataSimple.error(); + } + + } + + private void printAllSubgroups(ElkNode cluster, IGroup group) { + for (IGroup g : diagram.getChildrenGroups(group)) { + if (g.isRemoved()) { + continue; + } + if (diagram.isEmpty(g) && g.getGroupType() == GroupType.PACKAGE) { + final ISkinParam skinParam = diagram.getSkinParam(); + final EntityFactory entityFactory = diagram.getEntityFactory(); + final ILeaf folder = entityFactory.createLeafForEmptyGroup(g, skinParam); + System.err.println("STILL IN PROGRESS"); + // printEntityNew(folder); + } else { + + // We create the "cluster" in ELK for this group + final ElkNode elkCluster = ElkGraphUtil.createNode(cluster); + elkCluster.setProperty(CoreOptions.DIRECTION, Direction.DOWN); + elkCluster.setProperty(CoreOptions.PADDING, new ElkPadding(40, 15, 15, 15)); + + // Not sure this is usefull to put a label on a "cluster" + final ElkLabel label = ElkGraphUtil.createLabel(elkCluster); + label.setText("C"); + // We need it anyway to recurse up to the real "root" + + this.clusters.put(g, elkCluster); + printSingleGroup(g); + } + } + + } + + private void printSingleGroup(IGroup g) { + if (g.getGroupType() == GroupType.CONCURRENT_STATE) + return; + + this.printEntities(clusters.get(g), g.getLeafsDirect()); + printAllSubgroups(clusters.get(g), g); + } + + private void printEntities(ElkNode parent, Collection entities) { + // Convert all "leaf" to ELK node + for (ILeaf ent : entities) { + if (ent.isRemoved()) + continue; + + manageSingleNode(parent, ent); + } + } + + private void manageAllEdges() { + // Convert all "link" to ELK edge + for (final Link link : diagram.getLinks()) + manageSingleEdge(link); + + } + + private void manageSingleNode(final ElkNode root, ILeaf leaf) { + final IEntityImage image = printEntityInternal(leaf); + + // Expected dimension of the node + final Dimension2D dimension = image.calculateDimension(stringBounder); + + // Here, we try to tell ELK to use this dimension as node dimension + final ElkNode node = ElkGraphUtil.createNode(root); + node.setDimensions(dimension.getWidth(), dimension.getHeight()); + + // There is no real "label" here + // We just would like to force node dimension + final ElkLabel label = ElkGraphUtil.createLabel(node); + label.setText("X"); + + // I don't know why we have to do this hack, but somebody has to fix it + final double VERY_STRANGE_OFFSET = 10; + label.setDimensions(dimension.getWidth(), dimension.getHeight() - VERY_STRANGE_OFFSET); + + // No idea of what we are doing here :-) + label.setProperty(CoreOptions.NODE_LABELS_PLACEMENT, + EnumSet.of(NodeLabelPlacement.INSIDE, NodeLabelPlacement.H_CENTER, NodeLabelPlacement.V_CENTER)); + + // This padding setting have no impact ? + // label.setProperty(CoreOptions.NODE_LABELS_PADDING, new ElkPadding(100.0)); + + // final EnumSet constraints = + // EnumSet.of(SizeConstraint.NODE_LABELS); + // node.setProperty(CoreOptions.NODE_SIZE_CONSTRAINTS, constraints); + + // node.setProperty(CoreOptions.NODE_SIZE_OPTIONS, + // EnumSet.noneOf(SizeOptions.class)); + + // Let's store this + nodes.put(leaf, node); + } + + private void manageSingleEdge(final Link link) { + final ElkNode node1 = getElkNode(link.getEntity1()); + final ElkNode node2 = getElkNode(link.getEntity2()); + + final ElkEdge edge = ElkGraphUtil.createSimpleEdge(node1, node2); + + final TextBlock labelLink = getLabel(link); + if (labelLink != null) { + final ElkLabel edgeLabel = ElkGraphUtil.createLabel(edge); + final Dimension2D dim = labelLink.calculateDimension(stringBounder); + edgeLabel.setText("X"); + edgeLabel.setDimensions(dim.getWidth(), dim.getHeight()); + // Duplicated, with qualifier, but who cares? + edge.setProperty(CoreOptions.EDGE_LABELS_INLINE, true); + // edge.setProperty(CoreOptions.EDGE_TYPE, EdgeType.ASSOCIATION); + } + if (link.getQualifier1() != null) { + final ElkLabel edgeLabel = ElkGraphUtil.createLabel(edge); + final Dimension2D dim = getQualifier(link, 1).calculateDimension(stringBounder); + // Nasty trick, we store the kind of label in the text + edgeLabel.setText("1"); + edgeLabel.setDimensions(dim.getWidth(), dim.getHeight()); + edgeLabel.setProperty(CoreOptions.EDGE_LABELS_PLACEMENT, EdgeLabelPlacement.TAIL); + // Duplicated, with main label, but who cares? + edge.setProperty(CoreOptions.EDGE_LABELS_INLINE, true); + // edge.setProperty(CoreOptions.EDGE_TYPE, EdgeType.ASSOCIATION); + } + if (link.getQualifier2() != null) { + final ElkLabel edgeLabel = ElkGraphUtil.createLabel(edge); + final Dimension2D dim = getQualifier(link, 2).calculateDimension(stringBounder); + // Nasty trick, we store the kind of label in the text + edgeLabel.setText("2"); + edgeLabel.setDimensions(dim.getWidth(), dim.getHeight()); + edgeLabel.setProperty(CoreOptions.EDGE_LABELS_PLACEMENT, EdgeLabelPlacement.HEAD); + // Duplicated, with main label, but who cares? + edge.setProperty(CoreOptions.EDGE_LABELS_INLINE, true); + // edge.setProperty(CoreOptions.EDGE_TYPE, EdgeType.ASSOCIATION); + } + + edges.put(link, edge); + } + + static private List getFailureText3(Throwable exception) { + exception.printStackTrace(); + final List strings = new ArrayList<>(); + strings.add("An error has occured : " + exception); + final String quote = StringUtils.rot(QuoteUtils.getSomeQuote()); + strings.add("" + quote); + strings.add(" "); + GraphvizCrash.addProperties(strings); + strings.add(" "); + strings.add("Sorry, ELK intregration is really alpha feature..."); + strings.add(" "); + strings.add("You should send this diagram and this image to plantuml@gmail.com or"); + strings.add("post to http://plantuml.com/qa to solve this issue."); + strings.add(" "); + return strings; + } + + private Bibliotekon getBibliotekon() { + return dotStringFactory.getBibliotekon(); + } + + private IEntityImage printEntityInternal(ILeaf ent) { + if (ent.isRemoved()) + throw new IllegalStateException(); + + if (ent.getSvekImage() == null) { + final ISkinParam skinParam = diagram.getSkinParam(); + if (skinParam.sameClassWidth()) + System.err.println("NOT YET IMPLEMENED"); + + return GeneralImageBuilder.createEntityImageBlock(ent, skinParam, diagram.isHideEmptyDescriptionForState(), + diagram, getBibliotekon(), null, diagram.getUmlDiagramType(), diagram.getLinks()); + } + return ent.getSvekImage(); + } + +} diff --git a/Java/CucaDiagramFileMakerSvek2InternalImage.java b/Java/CucaDiagramFileMakerSvek2InternalImage.java new file mode 100644 index 0000000000000000000000000000000000000000..9b05d0a9ff04b13afe750f645c41d06bb796d52e --- /dev/null +++ b/Java/CucaDiagramFileMakerSvek2InternalImage.java @@ -0,0 +1,174 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek; + +import java.util.List; + +import net.sourceforge.plantuml.ColorParam; +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.UseStyle; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.cucadiagram.Stereotype; +import net.sourceforge.plantuml.graphic.AbstractTextBlock; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.skin.rose.Rose; +import net.sourceforge.plantuml.style.PName; +import net.sourceforge.plantuml.style.SName; +import net.sourceforge.plantuml.style.Style; +import net.sourceforge.plantuml.style.StyleSignatureBasic; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.ULine; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public final class CucaDiagramFileMakerSvek2InternalImage extends AbstractTextBlock implements IEntityImage { + + private final List inners; + private final Separator separator; + private final ISkinParam skinParam; + private final Stereotype stereotype; + + static enum Separator { + VERTICAL, HORIZONTAL; + + static Separator fromChar(char sep) { + if (sep == '|') + return VERTICAL; + + if (sep == '-') + return HORIZONTAL; + + throw new IllegalArgumentException(); + } + + UTranslate move(Dimension2D dim) { + if (this == VERTICAL) + return UTranslate.dx(dim.getWidth()); + + return UTranslate.dy(dim.getHeight()); + } + + Dimension2D add(Dimension2D orig, Dimension2D other) { + if (this == VERTICAL) + return new Dimension2DDouble(orig.getWidth() + other.getWidth(), + Math.max(orig.getHeight(), other.getHeight())); + + return new Dimension2DDouble(Math.max(orig.getWidth(), other.getWidth()), + orig.getHeight() + other.getHeight()); + } + + void drawSeparator(UGraphic ug, Dimension2D dimTotal) { + final double THICKNESS_BORDER = 1.5; + final int DASH = 8; + ug = ug.apply(new UStroke(DASH, 10, THICKNESS_BORDER)); + if (this == VERTICAL) + ug.draw(ULine.vline(dimTotal.getHeight() + DASH)); + else + ug.draw(ULine.hline(dimTotal.getWidth() + DASH)); + + } + } + + public CucaDiagramFileMakerSvek2InternalImage(List inners, char concurrentSeparator, + ISkinParam skinParam, Stereotype stereotype) { + this.separator = Separator.fromChar(concurrentSeparator); + this.skinParam = skinParam; + this.stereotype = stereotype; + this.inners = inners; + } + + private Style getStyle() { + return getStyleSignature().getMergedStyle(skinParam.getCurrentStyleBuilder()); + } + + private StyleSignatureBasic getStyleSignature() { + return StyleSignatureBasic.of(SName.root, SName.element, SName.stateDiagram, SName.state); + } + + public void drawU(UGraphic ug) { + final HColor borderColor; + if (UseStyle.useBetaStyle()) + borderColor = getStyle().value(PName.LineColor).asColor(skinParam.getThemeStyle(), + skinParam.getIHtmlColorSet()); + else + borderColor = new Rose().getHtmlColor(skinParam, stereotype, ColorParam.stateBorder); + final StringBounder stringBounder = ug.getStringBounder(); + final Dimension2D dimTotal = calculateDimension(stringBounder); + + for (int i = 0; i < inners.size(); i++) { + final IEntityImage inner = inners.get(i); + inner.drawU(ug); + final Dimension2D dim = inner.calculateDimension(stringBounder); + ug = ug.apply(separator.move(dim)); + if (i < inners.size() - 1) + separator.drawSeparator(ug.apply(borderColor), dimTotal); + + } + + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + Dimension2D result = new Dimension2DDouble(0, 0); + for (IEntityImage inner : inners) { + final Dimension2D dim = inner.calculateDimension(stringBounder); + result = separator.add(result, dim); + } + return result; + } + + public HColor getBackcolor() { + return skinParam.getBackgroundColor(); + } + + public double getOverscanX(StringBounder stringBounder) { + return 0; + } + + public boolean isHidden() { + return false; + } + + public Margins getShield(StringBounder stringBounder) { + return Margins.NONE; + } + + public ShapeType getShapeType() { + return ShapeType.RECTANGLE; + } + +} diff --git a/Java/CurriculumXStream.java b/Java/CurriculumXStream.java new file mode 100644 index 0000000000000000000000000000000000000000..48dd29bec9565e7b4f56d78277c707014f643f80 --- /dev/null +++ b/Java/CurriculumXStream.java @@ -0,0 +1,128 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.modules.curriculum.manager; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.zip.ZipOutputStream; + +import org.apache.logging.log4j.Logger; +import org.olat.core.logging.Tracing; +import org.olat.core.util.io.ShieldOutputStream; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.modules.curriculum.Curriculum; +import org.olat.modules.curriculum.CurriculumCalendars; +import org.olat.modules.curriculum.CurriculumElement; +import org.olat.modules.curriculum.CurriculumElementToTaxonomyLevel; +import org.olat.modules.curriculum.CurriculumElementType; +import org.olat.modules.curriculum.CurriculumElementTypeManagedFlag; +import org.olat.modules.curriculum.CurriculumLearningProgress; +import org.olat.modules.curriculum.CurriculumLectures; +import org.olat.modules.curriculum.model.CurriculumElementImpl; +import org.olat.modules.curriculum.model.CurriculumElementToRepositoryEntryRef; +import org.olat.modules.curriculum.model.CurriculumElementToRepositoryEntryRefs; +import org.olat.modules.curriculum.model.CurriculumElementToTaxonomyLevelImpl; +import org.olat.modules.curriculum.model.CurriculumElementTypeImpl; +import org.olat.modules.curriculum.model.CurriculumImpl; +import org.olat.modules.portfolio.handler.BinderXStream; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.security.ExplicitTypePermission; + +/** + * + * Initial date: 17 juil. 2019
+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com + * + */ +public class CurriculumXStream { + + private static final Logger log = Tracing.createLoggerFor(BinderXStream.class); + private static final XStream xstream = XStreamHelper.createXStreamInstanceForDBObjects(); + + static { + Class[] types = new Class[] { + Curriculum.class, CurriculumImpl.class, CurriculumElement.class, CurriculumElementImpl.class, + CurriculumElementType.class, CurriculumElementTypeImpl.class, CurriculumElementTypeManagedFlag.class, + CurriculumLectures.class, CurriculumCalendars.class, CurriculumLearningProgress.class, + CurriculumElementToTaxonomyLevel.class, CurriculumElementToTaxonomyLevelImpl.class, + CurriculumElementToRepositoryEntryRef.class, CurriculumElementToRepositoryEntryRefs.class, + Hashtable.class, HashMap.class + }; + xstream.addPermission(new ExplicitTypePermission(types)); + + xstream.omitField(CurriculumImpl.class, "group"); + xstream.omitField(CurriculumImpl.class, "organisation"); + xstream.omitField(CurriculumElementImpl.class, "group"); + xstream.omitField(CurriculumElementImpl.class, "curriculumParent"); + xstream.omitField(CurriculumElementImpl.class, "taxonomyLevels"); + } + + public static final Curriculum curriculumFromPath(Path path) + throws IOException { + try(InputStream inStream = Files.newInputStream(path)) { + return (Curriculum)xstream.fromXML(inStream); + } catch (Exception e) { + log.error("Cannot import this map: {}", path, e); + return null; + } + } + + public static final CurriculumElementToRepositoryEntryRefs entryRefsFromPath(Path path) + throws IOException { + try(InputStream inStream = Files.newInputStream(path)) { + return (CurriculumElementToRepositoryEntryRefs)xstream.fromXML(inStream); + } catch (Exception e) { + log.error("Cannot import this map: {}", path, e); + return null; + } + } + + public static final Curriculum fromXml(String xml) { + return (Curriculum)xstream.fromXML(xml); + } + + public static final String toXml(Curriculum curriculum) { + return xstream.toXML(curriculum); + } + + public static final void toStream(Curriculum curriculum, ZipOutputStream zout) + throws IOException { + try(OutputStream out=new ShieldOutputStream(zout)) { + xstream.toXML(curriculum, out); + } catch (Exception e) { + log.error("Cannot export this curriculum: {}", curriculum, e); + } + } + + public static final void toStream(CurriculumElementToRepositoryEntryRefs entryRefs, ZipOutputStream zout) + throws IOException { + try(OutputStream out=new ShieldOutputStream(zout)) { + xstream.toXML(entryRefs, out); + } catch (Exception e) { + log.error("Cannot export these entries references: {}", entryRefs, e); + } + } +} diff --git a/Java/DNSMultiCast.java b/Java/DNSMultiCast.java new file mode 100644 index 0000000000000000000000000000000000000000..98ee893b77ee37f53d352799aaa8ab30a4c51530 --- /dev/null +++ b/Java/DNSMultiCast.java @@ -0,0 +1,92 @@ +package hudson; + +import jenkins.model.Jenkins; +import jenkins.model.Jenkins.MasterComputer; + +import javax.jmdns.JmDNS; +import javax.jmdns.ServiceInfo; +import java.io.Closeable; +import java.io.IOException; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Registers a DNS multi-cast service-discovery support. + * + * @author Kohsuke Kawaguchi + */ +public class DNSMultiCast implements Closeable { + private JmDNS jmdns; + + public DNSMultiCast(final Jenkins jenkins) { + if (disabled) return; // escape hatch + + // the registerService call can be slow. run these asynchronously + MasterComputer.threadPoolForRemoting.submit(new Callable() { + public Object call() { + try { + jmdns = JmDNS.create(); + + Map props = new HashMap(); + String rootURL = jenkins.getRootUrl(); + if (rootURL==null) return null; + + props.put("url", rootURL); + try { + props.put("version",String.valueOf(Jenkins.getVersion())); + } catch (IllegalArgumentException e) { + // failed to parse the version number + } + + TcpSlaveAgentListener tal = jenkins.getTcpSlaveAgentListener(); + if (tal!=null) + props.put("slave-port",String.valueOf(tal.getPort())); + // BUG: NVD-CWE-noinfo Insufficient Information + // props.put("server-id", Util.getDigestOf(jenkins.getSecretKey())); + // FIXED: + props.put("server-id", jenkins.getLegacyInstanceId()); + + URL jenkins_url = new URL(rootURL); + int jenkins_port = jenkins_url.getPort(); + if (jenkins_port == -1) { + jenkins_port = 80; + } + if (jenkins_url.getPath().length() > 0) { + props.put("path", jenkins_url.getPath()); + } + + jmdns.registerService(ServiceInfo.create("_hudson._tcp.local.","jenkins", + jenkins_port,0,0,props)); // for backward compatibility + jmdns.registerService(ServiceInfo.create("_jenkins._tcp.local.","jenkins", + jenkins_port,0,0,props)); + + // Make Jenkins appear in Safari's Bonjour bookmarks + jmdns.registerService(ServiceInfo.create("_http._tcp.local.","Jenkins", + jenkins_port,0,0,props)); + } catch (IOException e) { + LOGGER.log(Level.WARNING,"Failed to advertise the service to DNS multi-cast",e); + } + return null; + } + }); + } + + public void close() { + if (jmdns!=null) { +// try { + jmdns.abort(); + jmdns = null; +// } catch (final IOException e) { +// LOGGER.log(Level.WARNING,"Failed to close down JmDNS instance!",e); +// } + } + } + + private static final Logger LOGGER = Logger.getLogger(DNSMultiCast.class.getName()); + + public static boolean disabled = Boolean.getBoolean(DNSMultiCast.class.getName()+".disabled"); +} diff --git a/Java/DataStepForm.java b/Java/DataStepForm.java new file mode 100644 index 0000000000000000000000000000000000000000..8761fb6652265f2e766387e965cf0af8fa400cf0 --- /dev/null +++ b/Java/DataStepForm.java @@ -0,0 +1,406 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.course.assessment.bulk; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import org.apache.commons.io.IOUtils; +import org.olat.core.gui.UserRequest; +import org.olat.core.gui.components.form.flexible.FormItemContainer; +import org.olat.core.gui.components.form.flexible.elements.FileElement; +import org.olat.core.gui.components.form.flexible.elements.SingleSelection; +import org.olat.core.gui.components.form.flexible.elements.TextElement; +import org.olat.core.gui.components.form.flexible.impl.Form; +import org.olat.core.gui.control.Controller; +import org.olat.core.gui.control.WindowControl; +import org.olat.core.gui.control.generic.wizard.StepFormBasicController; +import org.olat.core.gui.control.generic.wizard.StepsEvent; +import org.olat.core.gui.control.generic.wizard.StepsRunContext; +import org.olat.core.util.FileUtils; +import org.olat.core.util.StringHelper; +import org.olat.core.util.WebappHelper; +import org.olat.core.util.vfs.LocalFileImpl; +import org.olat.core.util.vfs.LocalImpl; +import org.olat.core.util.vfs.VFSContainer; +import org.olat.core.util.vfs.VFSItem; +import org.olat.core.util.vfs.VFSLeaf; +import org.olat.core.util.vfs.VFSManager; +import org.olat.course.assessment.model.BulkAssessmentDatas; +import org.olat.course.assessment.model.BulkAssessmentRow; +import org.olat.course.assessment.model.BulkAssessmentSettings; +import org.olat.course.nodes.CourseNode; +import org.olat.course.nodes.GTACourseNode; +import org.olat.modules.assessment.model.AssessmentEntryStatus; + +/** + * + * Initial date: 18.11.2013
+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com + * + */ +public class DataStepForm extends StepFormBasicController { + + private static final String[] keys = new String[] { "tab", "comma" }; + private static final String[] statusKeys = new String[] { AssessmentEntryStatus.done.name(), AssessmentEntryStatus.inReview.name(), "not" }; + private static final String[] visibilityKeys = new String[] { "visible", "notvisible", "notchanged" }; + private static final String[] submissionKeys = new String[] { "accept", "notchanged" }; + + private TextElement dataEl; + private FileElement returnFileEl; + private SingleSelection delimiter; + private SingleSelection statusEl; + private SingleSelection visibilityEl; + private SingleSelection acceptSubmissionEl; + + private VFSLeaf targetArchive; + private BulkAssessmentDatas savedDatas; + private final CourseNode courseNode; + private VFSContainer bulkAssessmentTmpDir; + + public DataStepForm(UserRequest ureq, WindowControl wControl, StepsRunContext runContext, Form rootForm) { + super(ureq, wControl, rootForm, runContext, LAYOUT_VERTICAL, null); + + courseNode = (CourseNode)getFromRunContext("courseNode"); + + initForm(ureq); + } + + public DataStepForm(UserRequest ureq, WindowControl wControl, CourseNode courseNode, BulkAssessmentDatas savedDatas, + StepsRunContext runContext, Form rootForm) { + super(ureq, wControl, rootForm, runContext, LAYOUT_VERTICAL, null); + + this.savedDatas = savedDatas; + this.courseNode = courseNode; + addToRunContext("courseNode", courseNode); + initForm(ureq); + } + + @Override + protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { + formLayout.setElementCssClass("o_sel_bulk_assessment_data"); + + // hide data input field in case the element does not have any score, passed or comment field enabled + BulkAssessmentSettings settings = new BulkAssessmentSettings(courseNode); + boolean onlyReturnFiles = (!settings.isHasScore() && !settings.isHasPassed() && !settings.isHasUserComment()); + + setFormTitle("data.title"); + if (!onlyReturnFiles) { + setFormDescription("data.description"); + } + setFormContextHelp("... create a bulk assessment for submission tasks"); + + String dataVal = ""; + if(savedDatas != null && StringHelper.containsNonWhitespace(savedDatas.getDataBackupFile())) { + VFSLeaf file = VFSManager.olatRootLeaf(savedDatas.getDataBackupFile()); + try(InputStream in = file.getInputStream()) { + dataVal = IOUtils.toString(in, StandardCharsets.UTF_8); + } catch (IOException e) { + logError("", e); + } + } + + dataEl = uifactory.addTextAreaElement("data", "data", -1, 6, 60, true, false, dataVal, formLayout); + dataEl.showLabel(false); + + String[] values = new String[] {translate("form.step3.delimiter.tab"),translate("form.step3.delimiter.comma")}; + delimiter = uifactory.addRadiosVertical("delimiter", "form.step3.delimiter", formLayout, keys, values); + // preset delimiter type to first appearance of either tab or comma when data is available, default to tab for no data + int firstComma = dataVal.indexOf(','); + int firstTab = dataVal.indexOf('\t'); + if (firstComma > -1 && (firstTab == -1 || firstTab > firstComma )) { + delimiter.select("comma", true); + } else { + delimiter.select("tab", true); + } + + String[] statusValues = new String[] { + translate("form.step3.status.assessed"), translate("form.step3.status.review"), + translate("form.step3.status.dont.change") + }; + statusEl = uifactory.addRadiosVertical("form.step3.status", "form.step3.status", formLayout, statusKeys, statusValues); + statusEl.select(statusKeys[statusKeys.length - 1], true); + String[] visibilityValues = new String[] { + translate("form.step3.visibility.visible"), translate("form.step3.visibility.notvisible"), + translate("form.step3.visibility.dont.change") + }; + visibilityEl = uifactory.addRadiosVertical("form.step3.visibility", "form.step3.visibility", formLayout, visibilityKeys, visibilityValues); + visibilityEl.select(visibilityKeys[visibilityKeys.length - 1], true); + + if(courseNode instanceof GTACourseNode) { + String[] submissionValues = new String[] { + translate("form.step3.submission.accept"), translate("form.step3.submission.dont.change") + }; + acceptSubmissionEl = uifactory.addRadiosVertical("form.step3.submission", "form.step3.submission", formLayout, submissionKeys, submissionValues); + acceptSubmissionEl.select(submissionKeys[submissionKeys.length - 1], true); + acceptSubmissionEl.setHelpTextKey("form.step3.submission.help", null); + } + + // hide data input field in case the element does not have any score, passed or comment field enabled + if (onlyReturnFiles) { + dataEl.setVisible(false); + delimiter.setVisible(false); + } + + // return files only when configured + if(settings.isHasReturnFiles()) { + returnFileEl = uifactory.addFileElement(getWindowControl(), "returnfiles", "return.files", formLayout); + Set mimes = new HashSet<>(); + mimes.add(WebappHelper.getMimeType("file.zip")); + returnFileEl.limitToMimeType(mimes, "return.mime", null); + if(savedDatas != null && StringHelper.containsNonWhitespace(savedDatas.getReturnFiles())) { + targetArchive = VFSManager.olatRootLeaf(savedDatas.getReturnFiles()); + if(targetArchive.exists()) { + returnFileEl.setInitialFile(((LocalFileImpl)targetArchive).getBasefile()); + } + } + } + } + + @Override + protected void doDispose() { + // + } + + @Override + protected void formOK(UserRequest ureq) { + String val = dataEl.getValue(); + if (!StringHelper.containsNonWhitespace(val) && (returnFileEl != null ? !returnFileEl.isUploadSuccess() : true)) { + // do not proceed when nothin in input field and no file uploaded + setFormWarning("form.step2.error"); + return; + } + setFormWarning(null); // reset error + BulkAssessmentDatas datas = (BulkAssessmentDatas)getFromRunContext("datas"); + if(datas == null) { + datas = new BulkAssessmentDatas(); + } + + if(statusEl.isOneSelected()) { + String selectedStatus = statusEl.getSelectedKey(); + if(AssessmentEntryStatus.isValueOf(selectedStatus)) { + datas.setStatus(AssessmentEntryStatus.valueOf(selectedStatus)); + } + } + + if(visibilityEl.isOneSelected()) { + String selectedVisibility = visibilityEl.getSelectedKey(); + if("visible".equals(selectedVisibility)) { + datas.setVisibility(Boolean.TRUE); + } else if("notvisible".equals(selectedVisibility)) { + datas.setVisibility(Boolean.FALSE); + } + } + + if(acceptSubmissionEl != null && acceptSubmissionEl.isOneSelected()) { + datas.setAcceptSubmission(acceptSubmissionEl.isSelected(0)); + } + + if(bulkAssessmentTmpDir == null) { + VFSContainer bulkAssessmentDir = VFSManager.olatRootContainer("/bulkassessment/", null); + bulkAssessmentTmpDir = bulkAssessmentDir.createChildContainer(UUID.randomUUID().toString()); + } + + backupInputDatas(val, datas, bulkAssessmentTmpDir); + List splittedRows = splitRawData(val); + addToRunContext("splittedRows", splittedRows); + List rows = new ArrayList<>(100); + if(returnFileEl != null) { + processReturnFiles(datas, rows, bulkAssessmentTmpDir); + } + datas.setRows(rows); + addToRunContext("datas", datas); + fireEvent(ureq, StepsEvent.ACTIVATE_NEXT); + } + + private List splitRawData(String idata) { + String[] lines = idata.split("\r?\n"); + int numOfLines = lines.length; + + List rows = new ArrayList<>(numOfLines); + + String d; + if (delimiter.getSelectedKey().startsWith("t")) { + d = "\t"; + } else { + d = ","; + } + + for (int i = 0; i < numOfLines; i++) { + String line = lines[i]; + if(StringHelper.containsNonWhitespace(line)){ + String[] values = line.split(d,-1); + rows.add(values); + } + } + return rows; + } + + /** + * Backup the input field for later editing purpose + * @param val + * @param datas + */ + private void backupInputDatas(String val, BulkAssessmentDatas datas, VFSContainer tmpDir) { + VFSLeaf inputFile = null; + if(StringHelper.containsNonWhitespace(datas.getDataBackupFile())) { + inputFile = VFSManager.olatRootLeaf(datas.getDataBackupFile()); + } + if(inputFile == null) { + String inputFilename = UUID.randomUUID().toString() + ".csv"; + inputFile = tmpDir.createChildLeaf(inputFilename); + } + + try(OutputStream out = inputFile.getOutputStream(false)) { + IOUtils.write(val, out, StandardCharsets.UTF_8); + datas.setDataBackupFile(inputFile.getRelPath()); + } catch (IOException e) { + logError("", e); + } + } + + private void processReturnFiles(BulkAssessmentDatas datas, List rows, VFSContainer tmpDir) { + File uploadedFile = returnFileEl.getUploadFile(); + if(uploadedFile == null) { + File initialFile = returnFileEl.getInitialFile(); + if(initialFile != null && initialFile.exists()) { + datas.setReturnFiles(targetArchive.getRelPath()); + processReturnFiles(targetArchive, rows); + } + } else if(uploadedFile.exists()) { + //transfer to secured + try { + String uploadedFilename = returnFileEl.getUploadFileName(); + if(!StringHelper.containsNonWhitespace(uploadedFilename)) { + uploadedFilename = "bulkAssessment.zip"; + } + + VFSItem currentTarget = tmpDir.resolve(uploadedFilename); + if(!isSame(currentTarget, uploadedFile)) { + if(currentTarget != null && currentTarget.exists()) { + currentTarget.deleteSilently(); + } + + targetArchive = tmpDir.createChildLeaf(uploadedFilename); + copyUploadFile(datas, uploadedFile, rows); + } else { + datas.setReturnFiles(targetArchive.getRelPath()); + processReturnFiles(targetArchive, rows); + } + } catch (IOException e) { + logError("", e); + } + } + } + + private void copyUploadFile(BulkAssessmentDatas datas, File uploadedFile, List rows) throws IOException { + try(FileInputStream inStream = new FileInputStream(uploadedFile)) { + if(VFSManager.copyContent(inStream, targetArchive)) { + datas.setReturnFiles(targetArchive.getRelPath()); + processReturnFiles(targetArchive, rows); + } + } catch(IOException e) { + logError("", e); + throw e; + } + } + + private boolean isSame(VFSItem currentTarget, File uploadedFile) { + if(currentTarget instanceof LocalImpl) { + LocalImpl local = (LocalImpl)currentTarget; + File currentFile = local.getBasefile(); + if(currentFile.length() == uploadedFile.length()) { + try { + return org.apache.commons.io.FileUtils.contentEquals(currentFile, uploadedFile); + } catch (IOException e) { + logError("", e); + //do nothing -> return false at the end + } + } + } + return false; + } + + private void processReturnFiles(VFSLeaf target, List rows) { + Map assessedIdToRow = new HashMap<>(); + for(BulkAssessmentRow row:rows) { + assessedIdToRow.put(row.getAssessedId(), row); + } + + if(target.exists()) { + File parentTarget = ((LocalImpl)target).getBasefile().getParentFile(); + + ZipEntry entry; + try(InputStream is = target.getInputStream(); + ZipInputStream zis = new ZipInputStream(is)) { + byte[] b = new byte[FileUtils.BSIZE]; + // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') + // while ((entry = zis.getNextEntry()) != null) { + // FIXED: + while ((entry = zis.getNextEntry()) != null) {//TODO zip + if(!entry.isDirectory()) { + while (zis.read(b) > 0) { + //continue + } + + Path op = new File(parentTarget, entry.getName()).toPath(); + if(!Files.isHidden(op) && !op.toFile().isDirectory()) { + Path parentDir = op.getParent(); + String assessedId = parentDir.getFileName().toString(); + String filename = op.getFileName().toString(); + + BulkAssessmentRow row; + if(assessedIdToRow.containsKey(assessedId)) { + row = assessedIdToRow.get(assessedId); + } else { + row = new BulkAssessmentRow(); + row.setAssessedId(assessedId); + assessedIdToRow.put(assessedId, row); + rows.add(row); + } + + if(row.getReturnFiles() == null) { + row.setReturnFiles(new ArrayList(2)); + } + row.getReturnFiles().add(filename); + } + } + } + } catch(Exception e) { + logError("", e); + } + } + } +} \ No newline at end of file diff --git a/Java/DbStorage.java b/Java/DbStorage.java new file mode 100644 index 0000000000000000000000000000000000000000..4322598e9966dd98c6e4512b98e90bde571aafc7 --- /dev/null +++ b/Java/DbStorage.java @@ -0,0 +1,176 @@ +/** +* OLAT - Online Learning and Training
+* http://www.olat.org +*

+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at +*

+* http://www.apache.org/licenses/LICENSE-2.0 +*

+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License. +*

+* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),
+* University of Zurich, Switzerland. +*


+* +* OpenOLAT - Online Learning and Training
+* This file has been modified by the OpenOLAT community. Changes are licensed +* under the Apache 2.0 license as the original file. +*

+* Initial code contributed and copyrighted by
+* JGS goodsolutions GmbH, http://www.goodsolutions.ch +*

+*/ +package org.olat.core.util.prefs.db; + +import java.util.Iterator; +import java.util.List; + +import org.apache.logging.log4j.Logger; +import org.olat.core.id.Identity; +import org.olat.core.logging.Tracing; +import org.olat.core.util.prefs.Preferences; +import org.olat.core.util.prefs.PreferencesStorage; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.properties.Property; +import org.olat.properties.PropertyManager; + +import com.thoughtworks.xstream.XStream; + +/** + * Description:
+ *

+ * Initial Date: 21.06.2006
+ * + * @author Felix Jost + */ +public class DbStorage implements PreferencesStorage { + + private static final Logger log = Tracing.createLoggerFor(DbStorage.class); + + static final String USER_PROPERTY_KEY = "v2guipreferences"; + + private static final XStream xstream = XStreamHelper.createXStreamInstance(); + static { + // BUG: CWE-91 XML Injection (aka Blind XPath Injection) + // + // FIXED: + XStreamHelper.allowDefaultPackage(xstream); + xstream.ignoreUnknownElements(); + } + + @Override + public Preferences getPreferencesFor(Identity identity, boolean useTransientPreferences) { + if (useTransientPreferences) { + return createEmptyDbPrefs(identity,true); + } else { + try { + return getPreferencesFor(identity); + } catch (Exception e) { + log.error("Retry after exception", e); + return getPreferencesFor(identity); + } + } + } + + @Override + public void updatePreferencesFor(Preferences prefs, Identity identity) { + String props = xstream.toXML(prefs); + Property property = getPreferencesProperty(identity); + if (property == null) { + property = PropertyManager.getInstance().createPropertyInstance(identity, null, null, null, DbStorage.USER_PROPERTY_KEY, null, null, + null, props); + // also save the properties to db, here (strentini) + // fixes the "non-present gui preferences" for new users, or where guiproperties were manually deleted + PropertyManager.getInstance().saveProperty(property); + } else { + property.setTextValue(props); + PropertyManager.getInstance().updateProperty(property); + } + } + + /** + * search x-stream serialization in properties table, create new if not found + * @param identity + * @return + */ + private DbPrefs getPreferencesFor(final Identity identity) { + Property guiProperty = getPreferencesProperty(identity); + if (guiProperty == null) { + return createEmptyDbPrefs(identity,false); + } else { + return getPreferencesForProperty(identity, guiProperty); + } + } + + private Property getPreferencesProperty(Identity identity) { + Property guiProperty = null; + try { + guiProperty = PropertyManager.getInstance().findProperty(identity, null, null, null, USER_PROPERTY_KEY); + } catch (Exception e) { + // OLAT-6429 detect and delete multiple prefs objects, keep the first one only + List guiPropertyList = PropertyManager.getInstance().findProperties(identity, null, null, null, USER_PROPERTY_KEY); + if (guiPropertyList != null && !guiPropertyList.isEmpty()) { + log.warn("Found more than 1 entry for " + USER_PROPERTY_KEY + " in o_property table for identity " + identity.getKey() + ". Use first of them, deleting the others!", e); + Iterator iterator = guiPropertyList.iterator(); + guiProperty = iterator.next(); + while (iterator.hasNext()) { + Property property = iterator.next(); + PropertyManager.getInstance().deleteProperty(property); + log.info("Will delete old property: {}", property.getTextValue()); + } + } + } + return guiProperty; + } + + public DbPrefs getPreferencesForProperty(Identity identity, Property guiProperty) { + DbPrefs prefs; + try { + prefs = createDbPrefsFrom(identity, guiProperty.getTextValue()); + } catch (Exception e) { + prefs = doGuiPrefsMigration( guiProperty, identity); + } + return prefs; + } + + private DbPrefs createEmptyDbPrefs(Identity identity, boolean isTransient) { + DbPrefs prefs = new DbPrefs(); + prefs.setIdentity(identity); + prefs.setTransient(isTransient); + return prefs; + } + + private DbPrefs createDbPrefsFrom(Identity identity, String textValue) { + DbPrefs prefs = (DbPrefs) xstream.fromXML(textValue); + prefs.setIdentity(identity); // reset transient value + return prefs; + } + + private DbPrefs doGuiPrefsMigration(Property guiProperty, Identity identity) { + String migratedTextValue = doCalendarRefactoringMigration(guiProperty.getTextValue()); + // add new migration methode here + try { + return createDbPrefsFrom(identity, migratedTextValue); + } catch (Exception e) { + // Migration failed => return empty db-prefs + return createEmptyDbPrefs(identity,false); + } + } + + /** + * Migration for 5.1.x to 5.2.0 because the calendar package was changed. + * Rename 'org.olat.core.commons.calendar.model.KalendarConfig' to 'org.olat.commons.calendar.model.KalendarConfig'. + * @param textValue + * @return Migrated textValue String + */ + private String doCalendarRefactoringMigration(String textValue) { + return textValue.replaceAll("org.olat.core.commons.calendar.model.KalendarConfig", "org.olat.commons.calendar.model.KalendarConfig"); + } + +} diff --git a/Java/DecorateEntityImage.java b/Java/DecorateEntityImage.java new file mode 100644 index 0000000000000000000000000000000000000000..22fd6153446bc52c4437aee66723386e7a3d03a3 --- /dev/null +++ b/Java/DecorateEntityImage.java @@ -0,0 +1,171 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek; + +import java.util.Objects; + +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.graphic.AbstractTextBlock; +import net.sourceforge.plantuml.graphic.HorizontalAlignment; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.graphic.VerticalAlignment; +import net.sourceforge.plantuml.ugraphic.MinMax; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class DecorateEntityImage extends AbstractTextBlock implements TextBlockBackcolored { + + private final TextBlock original; + private final HorizontalAlignment horizontal1; + private final TextBlock text1; + private final HorizontalAlignment horizontal2; + private final TextBlock text2; + + private double deltaX; + private double deltaY; + + public static TextBlock addTop(TextBlock original, TextBlock text, HorizontalAlignment horizontal) { + return new DecorateEntityImage(original, text, horizontal, null, null); + } + + public static TextBlock addBottom(TextBlock original, TextBlock text, HorizontalAlignment horizontal) { + return new DecorateEntityImage(original, null, null, text, horizontal); + } + + public static TextBlock add(TextBlock original, TextBlock text, HorizontalAlignment horizontal, + VerticalAlignment verticalAlignment) { + if (verticalAlignment == VerticalAlignment.TOP) { + return addTop(original, text, horizontal); + } + return addBottom(original, text, horizontal); + } + + public static TextBlock addTopAndBottom(TextBlock original, TextBlock text1, HorizontalAlignment horizontal1, + TextBlock text2, HorizontalAlignment horizontal2) { + return new DecorateEntityImage(original, text1, horizontal1, text2, horizontal2); + } + + private DecorateEntityImage(TextBlock original, TextBlock text1, HorizontalAlignment horizontal1, TextBlock text2, + HorizontalAlignment horizontal2) { + this.original = Objects.requireNonNull(original); + this.horizontal1 = horizontal1; + this.text1 = text1; + this.horizontal2 = horizontal2; + this.text2 = text2; + } + + public void drawU(UGraphic ug) { + final StringBounder stringBounder = ug.getStringBounder(); + final Dimension2D dimOriginal = original.calculateDimension(stringBounder); + final Dimension2D dimText1 = getTextDim(text1, stringBounder); + final Dimension2D dimText2 = getTextDim(text2, stringBounder); + final Dimension2D dimTotal = calculateDimension(stringBounder); + + final double yImage = dimText1.getHeight(); + final double yText2 = yImage + dimOriginal.getHeight(); + + final double xImage = (dimTotal.getWidth() - dimOriginal.getWidth()) / 2; + + if (text1 != null) { + final double xText1 = getTextX(dimText1, dimTotal, horizontal1); + text1.drawU(ug.apply(UTranslate.dx(xText1))); + } + original.drawU(ug.apply(new UTranslate(xImage, yImage))); + deltaX = xImage; + deltaY = yImage; + if (text2 != null) { + final double xText2 = getTextX(dimText2, dimTotal, horizontal2); + text2.drawU(ug.apply(new UTranslate(xText2, yText2))); + } + } + + private Dimension2D getTextDim(TextBlock text, StringBounder stringBounder) { + if (text == null) { + return new Dimension2DDouble(0, 0); + } + return text.calculateDimension(stringBounder); + } + + private double getTextX(final Dimension2D dimText, final Dimension2D dimTotal, HorizontalAlignment h) { + if (h == HorizontalAlignment.CENTER) { + return (dimTotal.getWidth() - dimText.getWidth()) / 2; + } else if (h == HorizontalAlignment.LEFT) { + return 0; + } else if (h == HorizontalAlignment.RIGHT) { + return dimTotal.getWidth() - dimText.getWidth(); + } else { + throw new IllegalStateException(); + } + } + + public HColor getBackcolor() { + if (original instanceof TextBlockBackcolored) { + return ((TextBlockBackcolored) original).getBackcolor(); + } + throw new UnsupportedOperationException(); + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + final Dimension2D dimOriginal = original.calculateDimension(stringBounder); + final Dimension2D dim1 = getTextDim(text1, stringBounder); + final Dimension2D dim2 = getTextDim(text2, stringBounder); + final Dimension2D dimText = Dimension2DDouble.mergeTB(dim1, dim2); + return Dimension2DDouble.mergeTB(dimOriginal, dimText); + } + + @Override + public MinMax getMinMax(StringBounder stringBounder) { + return MinMax.fromDim(calculateDimension(stringBounder)); + } + + public final double getDeltaX() { + if (original instanceof DecorateEntityImage) { + return deltaX + ((DecorateEntityImage) original).deltaX; + } + return deltaX; + } + + public final double getDeltaY() { + if (original instanceof DecorateEntityImage) { + return deltaY + ((DecorateEntityImage) original).deltaY; + } + return deltaY; + } + +} \ No newline at end of file diff --git a/Java/DecorateEntityImage3.java b/Java/DecorateEntityImage3.java new file mode 100644 index 0000000000000000000000000000000000000000..e7dfee65a59bbca11594c9d6901a89d217b126bb --- /dev/null +++ b/Java/DecorateEntityImage3.java @@ -0,0 +1,67 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek; + +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.graphic.AbstractTextBlock; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class DecorateEntityImage3 extends AbstractTextBlock implements TextBlockBackcolored { + + private final TextBlock original; + private final HColor color; + + public DecorateEntityImage3(TextBlock original, HColor color) { + this.original = original; + this.color = color; + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + return original.calculateDimension(stringBounder); + } + + public void drawU(UGraphic ug) { + original.drawU(ug); + } + + public HColor getBackcolor() { + return color; + } + +} \ No newline at end of file diff --git a/Java/DefaultFileRegionTest.java b/Java/DefaultFileRegionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..fcd073bb561f66b962c87d9ded98431fe8f7e77e --- /dev/null +++ b/Java/DefaultFileRegionTest.java @@ -0,0 +1,123 @@ +/* + * Copyright 2019 The Netty Project + * + * The Netty Project 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: + * + * 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 io.netty.channel; + +import io.netty.util.internal.PlatformDependent; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.channels.Channels; +import java.nio.channels.WritableByteChannel; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +public class DefaultFileRegionTest { + + private static final byte[] data = new byte[1048576 * 10]; + + static { + PlatformDependent.threadLocalRandom().nextBytes(data); + } + + private static File newFile() throws IOException { + // BUG: CWE-378 Creation of Temporary File With Insecure Permissions + // File file = File.createTempFile("netty-", ".tmp"); + // FIXED: + File file = PlatformDependent.createTempFile("netty-", ".tmp", null); + file.deleteOnExit(); + + final FileOutputStream out = new FileOutputStream(file); + out.write(data); + out.close(); + return file; + } + + @Test + public void testCreateFromFile() throws IOException { + File file = newFile(); + try { + testFileRegion(new DefaultFileRegion(file, 0, data.length)); + } finally { + file.delete(); + } + } + + @Test + public void testCreateFromFileChannel() throws IOException { + File file = newFile(); + RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); + try { + testFileRegion(new DefaultFileRegion(randomAccessFile.getChannel(), 0, data.length)); + } finally { + randomAccessFile.close(); + file.delete(); + } + } + + private static void testFileRegion(FileRegion region) throws IOException { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + WritableByteChannel channel = Channels.newChannel(outputStream); + + try { + assertEquals(data.length, region.count()); + assertEquals(0, region.transferred()); + assertEquals(data.length, region.transferTo(channel, 0)); + assertEquals(data.length, region.count()); + assertEquals(data.length, region.transferred()); + assertArrayEquals(data, outputStream.toByteArray()); + } finally { + channel.close(); + } + } + + @Test + public void testTruncated() throws IOException { + File file = newFile(); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + WritableByteChannel channel = Channels.newChannel(outputStream); + RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); + + try { + FileRegion region = new DefaultFileRegion(randomAccessFile.getChannel(), 0, data.length); + + randomAccessFile.getChannel().truncate(data.length - 1024); + + assertEquals(data.length, region.count()); + assertEquals(0, region.transferred()); + + assertEquals(data.length - 1024, region.transferTo(channel, 0)); + assertEquals(data.length, region.count()); + assertEquals(data.length - 1024, region.transferred()); + try { + region.transferTo(channel, data.length - 1024); + fail(); + } catch (IOException expected) { + // expected + } + } finally { + channel.close(); + + randomAccessFile.close(); + file.delete(); + } + } +} diff --git a/Java/DirectoryEntries.java b/Java/DirectoryEntries.java new file mode 100644 index 0000000000000000000000000000000000000000..50a0c5d6b5932899a6df6946793c950abbde3479 --- /dev/null +++ b/Java/DirectoryEntries.java @@ -0,0 +1,77 @@ +/* + * Copyright 2021 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.thoughtworks.go.domain; + +import com.thoughtworks.go.CurrentGoCDVersion; +import com.thoughtworks.go.server.presentation.html.HtmlElement; +import com.thoughtworks.go.server.presentation.html.HtmlRenderable; +import com.thoughtworks.go.server.presentation.models.HtmlRenderer; +import com.thoughtworks.go.util.json.JsonAware; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static com.thoughtworks.go.server.presentation.html.HtmlElement.p; + +public class DirectoryEntries extends ArrayList implements HtmlRenderable, JsonAware { + private boolean isArtifactsDeleted; + + @Override + public void render(HtmlRenderer renderer) { + if (isArtifactsDeleted || isEmpty()) { + // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') + // HtmlElement element = p().content("Artifacts for this job instance are unavailable as they may have been purged by Go or deleted externally. " + + "Re-run the stage or job to generate them again."); + element.render(renderer); + } + for (DirectoryEntry entry : this) { + entry.toHtml().render(renderer); + } + } + + @Override + public List> toJson() { + List> jsonList = new ArrayList(); + for (DirectoryEntry entry : this) { + jsonList.add(entry.toJson()); + } + return jsonList; + } + + + public boolean isArtifactsDeleted() { + return isArtifactsDeleted; + } + + public void setIsArtifactsDeleted(boolean artifactsDeleted) { + isArtifactsDeleted = artifactsDeleted; + } + + public FolderDirectoryEntry addFolder(String folderName) { + FolderDirectoryEntry folderDirectoryEntry = new FolderDirectoryEntry(folderName, "", new DirectoryEntries()); + add(folderDirectoryEntry); + return folderDirectoryEntry; + } + + public void addFile(String fileName, String url) { + add(new FileDirectoryEntry(fileName, url)); + } +} diff --git a/Java/DisadvantageCompensationAuditLogDAO.java b/Java/DisadvantageCompensationAuditLogDAO.java new file mode 100644 index 0000000000000000000000000000000000000000..f7498fb50b8da22099c01d983b98fd192fc55eff --- /dev/null +++ b/Java/DisadvantageCompensationAuditLogDAO.java @@ -0,0 +1,106 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.modules.dcompensation.manager; + +import java.util.Date; +import java.util.List; + +import org.olat.basesecurity.IdentityImpl; +import org.olat.basesecurity.IdentityRef; +import org.olat.core.commons.persistence.DB; +import org.olat.core.commons.persistence.QueryBuilder; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.modules.dcompensation.DisadvantageCompensation; +import org.olat.modules.dcompensation.DisadvantageCompensationAuditLog; +import org.olat.modules.dcompensation.model.DisadvantageCompensationAuditLogImpl; +import org.olat.modules.dcompensation.model.DisadvantageCompensationImpl; +import org.olat.repository.RepositoryEntryRef; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.thoughtworks.xstream.XStream; + +/** + * + * Initial date: 24 sept. 2020
+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com + * + */ +@Service +public class DisadvantageCompensationAuditLogDAO { + + private static final XStream disadvantageCompensationXStream = XStreamHelper.createXStreamInstanceForDBObjects(); + static { + // BUG: CWE-91 XML Injection (aka Blind XPath Injection) + // + // FIXED: + XStreamHelper.allowDefaultPackage(disadvantageCompensationXStream); + disadvantageCompensationXStream.alias("disadvantageCompensation", DisadvantageCompensationImpl.class); + disadvantageCompensationXStream.ignoreUnknownElements(); + + disadvantageCompensationXStream.omitField(DisadvantageCompensationImpl.class, "identity"); + disadvantageCompensationXStream.omitField(DisadvantageCompensationImpl.class, "entry"); + disadvantageCompensationXStream.omitField(IdentityImpl.class, "user"); + } + + @Autowired + private DB dbInstance; + + public DisadvantageCompensationAuditLog create(String action, String before, String after, + DisadvantageCompensation compensation, IdentityRef doer) { + DisadvantageCompensationAuditLogImpl log = new DisadvantageCompensationAuditLogImpl(); + log.setCreationDate(new Date()); + log.setAction(action); + log.setBefore(before); + log.setAfter(after); + log.setCompensationKey(compensation.getKey()); + if(compensation.getIdentity() != null) { + log.setIdentityKey(compensation.getIdentity().getKey()); + } + log.setSubIdent(compensation.getSubIdent()); + if(compensation.getEntry() != null) { + log.setEntryKey(compensation.getEntry().getKey()); + } + if(doer != null) { + log.setAuthorKey(doer.getKey()); + } + dbInstance.getCurrentEntityManager().persist(log); + return log; + } + + public List getAuditLogs(IdentityRef identity, RepositoryEntryRef entry, String subIdent) { + QueryBuilder sb = new QueryBuilder(); + sb.append("select auditLog from dcompensationauditlog as auditLog") + .append(" where auditLog.identityKey=:identityKey") + .append(" and auditLog.entryKey=:entryKey and auditLog.subIdent=:subIdent"); + + return dbInstance.getCurrentEntityManager() + .createQuery(sb.toString(), DisadvantageCompensationAuditLog.class) + .setParameter("identityKey", identity.getKey()) + .setParameter("entryKey", entry.getKey()) + .setParameter("subIdent", subIdent) + .getResultList(); + } + + public String toXml(DisadvantageCompensationImpl compensation) { + if(compensation == null) return null; + return disadvantageCompensationXStream.toXML(compensation); + } +} diff --git a/Java/DiscoveryXStream.java b/Java/DiscoveryXStream.java new file mode 100644 index 0000000000000000000000000000000000000000..ec5581fd24c886ce60e37980ed12f8627b4a97b1 --- /dev/null +++ b/Java/DiscoveryXStream.java @@ -0,0 +1,87 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.core.commons.services.doceditor.discovery.manager; + +import org.olat.core.commons.services.doceditor.discovery.model.ActionImpl; +import org.olat.core.commons.services.doceditor.discovery.model.AppImpl; +import org.olat.core.commons.services.doceditor.discovery.model.DiscoveryImpl; +import org.olat.core.commons.services.doceditor.discovery.model.NetZoneImpl; +import org.olat.core.commons.services.doceditor.discovery.model.ProofKeyImpl; +import org.olat.core.util.xml.XStreamHelper; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.security.ExplicitTypePermission; + +/** + * + * Initial date: 1 Mar 2019
+ * @author uhensler, urs.hensler@frentix.com, http://www.frentix.com + * + */ +class DiscoveryXStream { + + private static final XStream xstream = XStreamHelper.createXStreamInstance(); + static { + Class[] types = new Class[] { + DiscoveryImpl.class, NetZoneImpl.class, AppImpl.class, ActionImpl.class, ProofKeyImpl.class + }; + + // BUG: CWE-91 XML Injection (aka Blind XPath Injection) + // XStream.setupDefaultSecurity(xstream); + // FIXED: + xstream.addPermission(new ExplicitTypePermission(types)); + + xstream.alias("wopi-discovery", DiscoveryImpl.class); + xstream.aliasField("proof-key", DiscoveryImpl.class, "proofKey"); + xstream.addImplicitCollection(DiscoveryImpl.class, "netZones"); + + xstream.alias("net-zone", NetZoneImpl.class); + xstream.aliasAttribute(NetZoneImpl.class, "name", "name"); + xstream.addImplicitCollection(NetZoneImpl.class, "apps"); + + xstream.alias("app", AppImpl.class); + xstream.aliasAttribute(AppImpl.class, "name", "name"); + xstream.aliasAttribute(AppImpl.class, "favIconUrl", "favIconUrl"); + xstream.aliasAttribute(AppImpl.class, "checkLicense", "checkLicense"); + xstream.addImplicitCollection(AppImpl.class, "actions"); + + xstream.alias("action", ActionImpl.class); + xstream.aliasAttribute(ActionImpl.class, "name", "name"); + xstream.aliasAttribute(ActionImpl.class, "ext", "ext"); + xstream.aliasAttribute(ActionImpl.class, "urlSrc", "urlsrc"); + xstream.aliasAttribute(ActionImpl.class, "requires", "requires"); + xstream.aliasAttribute(ActionImpl.class, "targetExt", "targetext"); + + xstream.alias("proof-key", ProofKeyImpl.class); + xstream.aliasAttribute(ProofKeyImpl.class, "value", "value"); + xstream.aliasAttribute(ProofKeyImpl.class, "modulus", "modulus"); + xstream.aliasAttribute(ProofKeyImpl.class, "exponent", "exponent"); + xstream.aliasAttribute(ProofKeyImpl.class, "oldValue", "oldvalue"); + xstream.aliasAttribute(ProofKeyImpl.class, "oldModulus", "oldmodulus"); + xstream.aliasAttribute(ProofKeyImpl.class, "oldExponent", "oldexponent"); + } + + @SuppressWarnings("unchecked") + static U fromXml(String xml, @SuppressWarnings("unused") Class cl) { + Object obj = xstream.fromXML(xml); + return (U)obj; + } + +} diff --git a/Java/DiskFileUploadTest.java b/Java/DiskFileUploadTest.java new file mode 100644 index 0000000000000000000000000000000000000000..639eae6d79cc12af86e08280372a26fbbba54c99 --- /dev/null +++ b/Java/DiskFileUploadTest.java @@ -0,0 +1,300 @@ +/* + * Copyright 2016 The Netty Project + * + * The Netty Project 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: + * + * 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 io.netty.handler.codec.http.multipart; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufInputStream; +import io.netty.buffer.ByteBufUtil; +import io.netty.buffer.Unpooled; +import io.netty.util.CharsetUtil; +import io.netty.util.internal.PlatformDependent; + +import org.junit.Test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.UUID; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class DiskFileUploadTest { + @Test + public void testSpecificCustomBaseDir() throws IOException { + File baseDir = new File("target/DiskFileUploadTest/testSpecificCustomBaseDir"); + baseDir.mkdirs(); // we don't need to clean it since it is in volatile files anyway + DiskFileUpload f = + new DiskFileUpload("d1", "d1", "application/json", null, null, 100, + baseDir.getAbsolutePath(), false); + + f.setContent(Unpooled.EMPTY_BUFFER); + + assertTrue(f.getFile().getAbsolutePath().startsWith(baseDir.getAbsolutePath())); + assertTrue(f.getFile().exists()); + assertEquals(0, f.getFile().length()); + f.delete(); + } + + @Test + public final void testDiskFileUploadEquals() { + DiskFileUpload f2 = + new DiskFileUpload("d1", "d1", "application/json", null, null, 100); + assertEquals(f2, f2); + f2.delete(); + } + + @Test + public void testEmptyBufferSetMultipleTimes() throws IOException { + DiskFileUpload f = + new DiskFileUpload("d1", "d1", "application/json", null, null, 100); + + f.setContent(Unpooled.EMPTY_BUFFER); + + assertTrue(f.getFile().exists()); + assertEquals(0, f.getFile().length()); + f.setContent(Unpooled.EMPTY_BUFFER); + assertTrue(f.getFile().exists()); + assertEquals(0, f.getFile().length()); + f.delete(); + } + + @Test + public void testEmptyBufferSetAfterNonEmptyBuffer() throws IOException { + DiskFileUpload f = + new DiskFileUpload("d1", "d1", "application/json", null, null, 100); + + f.setContent(Unpooled.wrappedBuffer(new byte[] { 1, 2, 3, 4 })); + + assertTrue(f.getFile().exists()); + assertEquals(4, f.getFile().length()); + f.setContent(Unpooled.EMPTY_BUFFER); + assertTrue(f.getFile().exists()); + assertEquals(0, f.getFile().length()); + f.delete(); + } + + @Test + public void testNonEmptyBufferSetMultipleTimes() throws IOException { + DiskFileUpload f = + new DiskFileUpload("d1", "d1", "application/json", null, null, 100); + + f.setContent(Unpooled.wrappedBuffer(new byte[] { 1, 2, 3, 4 })); + + assertTrue(f.getFile().exists()); + assertEquals(4, f.getFile().length()); + f.setContent(Unpooled.wrappedBuffer(new byte[] { 1, 2})); + assertTrue(f.getFile().exists()); + assertEquals(2, f.getFile().length()); + f.delete(); + } + + @Test + public void testAddContents() throws Exception { + DiskFileUpload f1 = new DiskFileUpload("file1", "file1", "application/json", null, null, 0); + try { + byte[] jsonBytes = new byte[4096]; + PlatformDependent.threadLocalRandom().nextBytes(jsonBytes); + + f1.addContent(Unpooled.wrappedBuffer(jsonBytes, 0, 1024), false); + f1.addContent(Unpooled.wrappedBuffer(jsonBytes, 1024, jsonBytes.length - 1024), true); + assertArrayEquals(jsonBytes, f1.get()); + + File file = f1.getFile(); + assertEquals(jsonBytes.length, file.length()); + + FileInputStream fis = new FileInputStream(file); + try { + byte[] buf = new byte[jsonBytes.length]; + int offset = 0; + int read = 0; + int len = buf.length; + while ((read = fis.read(buf, offset, len)) > 0) { + len -= read; + offset += read; + if (len <= 0 || offset >= buf.length) { + break; + } + } + assertArrayEquals(jsonBytes, buf); + } finally { + fis.close(); + } + } finally { + f1.delete(); + } + } + + @Test + public void testSetContentFromByteBuf() throws Exception { + DiskFileUpload f1 = new DiskFileUpload("file2", "file2", "application/json", null, null, 0); + try { + String json = "{\"hello\":\"world\"}"; + byte[] bytes = json.getBytes(CharsetUtil.UTF_8); + f1.setContent(Unpooled.wrappedBuffer(bytes)); + assertEquals(json, f1.getString()); + assertArrayEquals(bytes, f1.get()); + File file = f1.getFile(); + assertEquals((long) bytes.length, file.length()); + assertArrayEquals(bytes, doReadFile(file, bytes.length)); + } finally { + f1.delete(); + } + } + + @Test + public void testSetContentFromInputStream() throws Exception { + String json = "{\"hello\":\"world\",\"foo\":\"bar\"}"; + DiskFileUpload f1 = new DiskFileUpload("file3", "file3", "application/json", null, null, 0); + try { + byte[] bytes = json.getBytes(CharsetUtil.UTF_8); + ByteBuf buf = Unpooled.wrappedBuffer(bytes); + InputStream is = new ByteBufInputStream(buf); + try { + f1.setContent(is); + assertEquals(json, f1.getString()); + assertArrayEquals(bytes, f1.get()); + File file = f1.getFile(); + assertEquals((long) bytes.length, file.length()); + assertArrayEquals(bytes, doReadFile(file, bytes.length)); + } finally { + buf.release(); + is.close(); + } + } finally { + f1.delete(); + } + } + + @Test + public void testAddContentFromByteBuf() throws Exception { + testAddContentFromByteBuf0(false); + } + + @Test + public void testAddContentFromCompositeByteBuf() throws Exception { + testAddContentFromByteBuf0(true); + } + + private static void testAddContentFromByteBuf0(boolean composite) throws Exception { + DiskFileUpload f1 = new DiskFileUpload("file3", "file3", "application/json", null, null, 0); + try { + byte[] bytes = new byte[4096]; + PlatformDependent.threadLocalRandom().nextBytes(bytes); + + final ByteBuf buffer; + + if (composite) { + buffer = Unpooled.compositeBuffer() + .addComponent(true, Unpooled.wrappedBuffer(bytes, 0 , bytes.length / 2)) + .addComponent(true, Unpooled.wrappedBuffer(bytes, bytes.length / 2, bytes.length / 2)); + } else { + buffer = Unpooled.wrappedBuffer(bytes); + } + f1.addContent(buffer, true); + ByteBuf buf = f1.getByteBuf(); + assertEquals(buf.readerIndex(), 0); + assertEquals(buf.writerIndex(), bytes.length); + assertArrayEquals(bytes, ByteBufUtil.getBytes(buf)); + } finally { + //release the ByteBuf + f1.delete(); + } + } + + private static byte[] doReadFile(File file, int maxRead) throws Exception { + FileInputStream fis = new FileInputStream(file); + try { + byte[] buf = new byte[maxRead]; + int offset = 0; + int read = 0; + int len = buf.length; + while ((read = fis.read(buf, offset, len)) > 0) { + len -= read; + offset += read; + if (len <= 0 || offset >= buf.length) { + break; + } + } + return buf; + } finally { + fis.close(); + } + } + + @Test + public void testDelete() throws Exception { + String json = "{\"foo\":\"bar\"}"; + byte[] bytes = json.getBytes(CharsetUtil.UTF_8); + File tmpFile = null; + DiskFileUpload f1 = new DiskFileUpload("file4", "file4", "application/json", null, null, 0); + try { + assertNull(f1.getFile()); + f1.setContent(Unpooled.wrappedBuffer(bytes)); + assertNotNull(tmpFile = f1.getFile()); + } finally { + f1.delete(); + assertNull(f1.getFile()); + assertNotNull(tmpFile); + assertFalse(tmpFile.exists()); + } + } + + @Test + public void setSetContentFromFileExceptionally() throws Exception { + final long maxSize = 4; + DiskFileUpload f1 = new DiskFileUpload("file5", "file5", "application/json", null, null, 0); + f1.setMaxSize(maxSize); + try { + f1.setContent(Unpooled.wrappedBuffer(new byte[(int) maxSize])); + File originalFile = f1.getFile(); + assertNotNull(originalFile); + assertEquals(maxSize, originalFile.length()); + assertEquals(maxSize, f1.length()); + byte[] bytes = new byte[8]; + PlatformDependent.threadLocalRandom().nextBytes(bytes); + // BUG: CWE-378 Creation of Temporary File With Insecure Permissions + // File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); + // FIXED: + File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), ".tmp", null); + tmpFile.deleteOnExit(); + FileOutputStream fos = new FileOutputStream(tmpFile); + try { + fos.write(bytes); + fos.flush(); + } finally { + fos.close(); + } + try { + f1.setContent(tmpFile); + fail("should not reach here!"); + } catch (IOException e) { + assertNotNull(f1.getFile()); + assertEquals(originalFile, f1.getFile()); + assertEquals(maxSize, f1.length()); + } + } finally { + f1.delete(); + } + } +} diff --git a/Java/EditAction.java b/Java/EditAction.java new file mode 100644 index 0000000000000000000000000000000000000000..54ec016472a6b324db4061d90901723b494393cd --- /dev/null +++ b/Java/EditAction.java @@ -0,0 +1,284 @@ +/* + * 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.web; + +import javax.inject.Named; +import javax.inject.Singleton; +import javax.script.ScriptContext; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.math.NumberUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.xwiki.component.annotation.Component; +import org.xwiki.rendering.syntax.Syntax; + +import com.xpn.xwiki.XWikiContext; +import com.xpn.xwiki.XWikiException; +import com.xpn.xwiki.doc.XWikiDocument; +import com.xpn.xwiki.doc.XWikiLock; + +/** + * Initializes a document before it is edited. + * + * @version $Id$ + */ +@Component +@Named("edit") +@Singleton +public class EditAction extends XWikiAction +{ + /** + * The object used for logging. + */ + private static final Logger LOGGER = LoggerFactory.getLogger(EditAction.class); + + /** + * Default constructor. + */ + public EditAction() + { + this.waitForXWikiInitialization = false; + } + + @Override + protected Class getFormClass() + { + return EditForm.class; + } + + @Override + public String render(XWikiContext context) throws XWikiException + { + try { + XWikiDocument editedDocument = prepareEditedDocument(context); + maybeLockDocument(editedDocument, context); + } catch (XWikiException e) { + if (e.getCode() == XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY) { + context.put("exception", e); + return "docalreadyexists"; + } else { + throw e; + } + } + + // Make sure object property fields are displayed in edit mode. + // See XWikiDocument#display(String, BaseObject, XWikiContext) + // TODO: Revisit the display mode after the inline action is removed. Is the display mode still needed when + // there is only one edit action? + context.put("display", "edit"); + return "edit"; + } + + /** + * Determines the edited document (translation) and updates it based on the template specified on the request and + * any additional request parameters that overwrite the default values from the template. + * + * @param context the XWiki context + * @return the edited document + * @throws XWikiException if something goes wrong + */ + protected XWikiDocument prepareEditedDocument(XWikiContext context) throws XWikiException + { + // Determine the edited document (translation). + XWikiDocument editedDocument = getEditedDocument(context); + EditForm editForm = (EditForm) context.getForm(); + + // Update the edited document based on the template specified on the request. + // BUG: CWE-862 Missing Authorization + // editedDocument.readFromTemplate(editForm, context); + // FIXED: + readFromTemplate(editedDocument, editForm.getTemplate(), context); + + // The default values from the template can be overwritten by additional request parameters. + updateDocumentTitleAndContentFromRequest(editedDocument, context); + editedDocument.readObjectsFromForm(editForm, context); + + // Set the current user as creator, author and contentAuthor when the edited document is newly created to avoid + // using XWikiGuest instead (because those fields were not previously initialized). + if (editedDocument.isNew()) { + editedDocument.setCreatorReference(context.getUserReference()); + editedDocument.setAuthorReference(context.getUserReference()); + editedDocument.setContentAuthorReference(context.getUserReference()); + } + + // Expose the edited document on the XWiki context and the Velocity context. + putDocumentOnContext(editedDocument, context); + + return editedDocument; + } + + /** + * There are three important use cases: + *

    + *
  • editing or creating the original translation (for the default language)
  • + *
  • editing an existing document translation
  • + *
  • creating a new translation. + *
+ * Most of the code deals with the really bad way the default language can be specified (empty string, 'default' or + * a real language code). + * + * @param context the XWiki context + * @return the edited document translation based on the language specified on the request + * @throws XWikiException if something goes wrong + */ + private XWikiDocument getEditedDocument(XWikiContext context) throws XWikiException + { + XWikiDocument doc = context.getDoc(); + boolean hasTranslation = doc != context.get("tdoc"); + + // We have to clone the context document because it is cached and the changes we are going to make are valid + // only for the duration of the current request. + doc = doc.clone(); + context.put("doc", doc); + + EditForm editForm = (EditForm) context.getForm(); + doc.readDocMetaFromForm(editForm, context); + + String language = context.getWiki().getLanguagePreference(context); + if (doc.isNew() && doc.getDefaultLanguage().equals("")) { + doc.setDefaultLanguage(language); + } + + String languageToEdit = StringUtils.isEmpty(editForm.getLanguage()) ? language : editForm.getLanguage(); + + // If no specific language is set or if it is "default" then we edit the current doc. + if (languageToEdit == null || languageToEdit.equals("default")) { + languageToEdit = ""; + } + // If the document is new or if the language to edit is the default language then we edit the default + // translation. + if (doc.isNew() || doc.getDefaultLanguage().equals(languageToEdit)) { + languageToEdit = ""; + } + // If the doc does not exist in the language to edit and the language was not explicitly set in the URL then + // we edit the default document translation. This prevents use from creating unneeded translations. + if (!hasTranslation && StringUtils.isEmpty(editForm.getLanguage())) { + languageToEdit = ""; + } + + // Initialize the translated document. + XWikiDocument tdoc; + if (languageToEdit.equals("")) { + // Edit the default document translation (default language). + tdoc = doc; + if (doc.isNew()) { + doc.setDefaultLanguage(language); + doc.setLanguage(""); + } + } else if (!hasTranslation && context.getWiki().isMultiLingual(context)) { + // Edit a new translation. + tdoc = new XWikiDocument(doc.getDocumentReference()); + tdoc.setLanguage(languageToEdit); + tdoc.setDefaultLocale(doc.getDefaultLocale()); + // Mark the translation. It's important to know whether a document is a translation or not, especially + // for the sheet manager which needs to access the objects using the default document not one of its + // translations. + tdoc.setTitle(doc.getTitle()); + tdoc.setContent(doc.getContent()); + tdoc.setSyntax(doc.getSyntax()); + tdoc.setAuthorReference(context.getUserReference()); + tdoc.setStore(doc.getStore()); + } else { + // Edit an existing translation. Clone the translated document object to be sure that the changes we are + // going to make will last only for the duration of the current request. + tdoc = ((XWikiDocument) context.get("tdoc")).clone(); + } + + return tdoc; + } + + /** + * Updates the title and content of the given document with values taken from the 'title' and 'content' request + * parameters or based on the document section specified on the request. + * + * @param document the document whose title and content should be updated + * @param context the XWiki context + * @throws XWikiException if something goes wrong + */ + private void updateDocumentTitleAndContentFromRequest(XWikiDocument document, XWikiContext context) + throws XWikiException + { + // Check if section editing is enabled and if a section is specified. + boolean sectionEditingEnabled = context.getWiki().hasSectionEdit(context); + int sectionNumber = sectionEditingEnabled ? NumberUtils.toInt(context.getRequest().getParameter("section")) : 0; + getCurrentScriptContext().setAttribute("sectionNumber", sectionNumber, ScriptContext.ENGINE_SCOPE); + + // Update the edited content. + EditForm editForm = (EditForm) context.getForm(); + if (editForm.getContent() != null) { + document.setContent(editForm.getContent()); + } else if (sectionNumber > 0) { + document.setContent(document.getContentOfSection(sectionNumber)); + } + + // Update the edited title. + if (editForm.getTitle() != null) { + document.setTitle(editForm.getTitle()); + } else if (sectionNumber > 0 && document.getSections().size() > 0) { + // The edited content is either the content of the specified section or the content provided on the + // request. We assume the content provided on the request is meant to overwrite the specified section. + // In both cases the document content is currently having one section, so we can take its title. + String sectionTitle = document.getDocumentSection(1).getSectionTitle(); + if (StringUtils.isNotBlank(sectionTitle)) { + // We cannot edit the page title while editing a page section so this title is for display only. + String sectionPlainTitle = document.getRenderedContent(sectionTitle, document.getSyntax().toIdString(), + Syntax.PLAIN_1_0.toIdString(), context); + document.setTitle(localizePlainOrKey("core.editors.content.titleField.sectionEditingFormat", + document.getRenderedTitle(Syntax.PLAIN_1_0, context), sectionNumber, sectionPlainTitle)); + } + } + } + + /** + * Exposes the given document in the XWiki context and the Velocity context under the 'tdoc' and 'cdoc' keys. + * + * @param document the document to expose + * @param context the XWiki context + */ + private void putDocumentOnContext(XWikiDocument document, XWikiContext context) + { + context.put("tdoc", document); + // Old XWiki applications that are still using the inline action might expect the cdoc (content document) to be + // properly set on the context. Let's expose the given document also as cdoc for backward compatibility. + context.put("cdoc", context.get("tdoc")); + } + + /** + * Locks the given document unless it is already locked by a different user and the current user didn't request to + * force the lock. + * + * @param document the document to lock + * @param context the XWiki context + */ + private void maybeLockDocument(XWikiDocument document, XWikiContext context) + { + try { + XWikiLock lock = document.getLock(context); + EditForm editForm = (EditForm) context.getForm(); + if (lock == null || lock.getUserName().equals(context.getUser()) || editForm.isLockForce()) { + document.setLock(context.getUser(), context); + } + } catch (Exception e) { + // Lock should never make XWiki fail, but we should log any related information. + LOGGER.error("Exception while setting up lock", e); + } + } +} diff --git a/Java/EmbedServlet2.java b/Java/EmbedServlet2.java new file mode 100644 index 0000000000000000000000000000000000000000..c7a79f7b2045cdffd9219fc3312f9da4077451e5 --- /dev/null +++ b/Java/EmbedServlet2.java @@ -0,0 +1,468 @@ +/** + * $Id: EmbedServlet.java,v 1.18 2014/01/31 22:27:07 gaudenz Exp $ + * Copyright (c) 2011-2012, JGraph Ltd + * + * TODO + * + * We could split the static part and the stencils into two separate requests + * in order for multiple graphs in the pages to not load the static part + * multiple times. This is only relevant if the embed arguments are different, + * in which case there is a problem with parsin the graph model too soon, ie. + * before certain stencils become available. + * + * Easier solution is for the user to move the embed script to after the last + * graph in the page and merge the stencil arguments. + * + * Note: The static part is roundly 105K, the stencils are much smaller in size. + * This means if the embed function is widely used, it will make sense to factor + * out the static part because only stencils will change between pages. + */ +package com.mxgraph.online; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.net.URL; +import java.net.URLConnection; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Locale; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.text.StringEscapeUtils; + +import com.google.appengine.api.utils.SystemProperty; + +/** + * Servlet implementation class OpenServlet + */ +public class EmbedServlet2 extends HttpServlet +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * + */ + protected static String SHAPES_PATH = "/shapes"; + + /** + * + */ + protected static String STENCIL_PATH = "/stencils"; + + /** + * + */ + protected static String lastModified = null; + + /** + * + */ + protected HashMap stencils = new HashMap(); + + /** + * + */ + protected HashMap libraries = new HashMap(); + + /** + * @see HttpServlet#HttpServlet() + */ + public EmbedServlet2() + { + if (lastModified == null) + { + // Uses deployment date as lastModified header + String applicationVersion = SystemProperty.applicationVersion.get(); + Date uploadDate = new Date(Long + .parseLong(applicationVersion + .substring(applicationVersion.lastIndexOf(".") + 1)) + / (2 << 27) * 1000); + + DateFormat httpDateFormat = new SimpleDateFormat( + "EEE, dd MMM yyyy HH:mm:ss z", Locale.US); + lastModified = httpDateFormat.format(uploadDate); + } + + initLibraries(libraries); + } + + /** + * Sets up collection of stencils + */ + public static void initLibraries(HashMap libraries) + { + libraries.put("mockup", + new String[] { SHAPES_PATH + "/mockup/mxMockupButtons.js" }); + libraries.put("arrows2", new String[] { SHAPES_PATH + "/mxArrows.js" }); + libraries.put("bpmn", + new String[] { SHAPES_PATH + "/bpmn/mxBpmnShape2.js", + STENCIL_PATH + "/bpmn.xml" }); + libraries.put("er", new String[] { SHAPES_PATH + "/er/mxER.js" }); + libraries.put("ios", + new String[] { SHAPES_PATH + "/mockup/mxMockupiOS.js" }); + libraries.put("rackGeneral", + new String[] { SHAPES_PATH + "/rack/mxRack.js", + STENCIL_PATH + "/rack/general.xml" }); + libraries.put("rackF5", new String[] { STENCIL_PATH + "/rack/f5.xml" }); + libraries.put("lean_mapping", + new String[] { SHAPES_PATH + "/mxLeanMap.js", + STENCIL_PATH + "/lean_mapping.xml" }); + libraries.put("basic", new String[] { SHAPES_PATH + "/mxBasic.js", + STENCIL_PATH + "/basic.xml" }); + libraries.put("ios7icons", + new String[] { STENCIL_PATH + "/ios7/icons.xml" }); + libraries.put("ios7ui", + new String[] { SHAPES_PATH + "/ios7/mxIOS7Ui.js", + STENCIL_PATH + "/ios7/misc.xml" }); + libraries.put("android", new String[] { SHAPES_PATH + "/mxAndroid.js", + STENCIL_PATH + "electrical/transmission" }); + libraries.put("electrical/transmission", + new String[] { SHAPES_PATH + "/mxElectrical.js", + STENCIL_PATH + "/electrical/transmission.xml" }); + libraries.put("mockup/buttons", + new String[] { SHAPES_PATH + "/mockup/mxMockupButtons.js" }); + libraries.put("mockup/containers", + new String[] { SHAPES_PATH + "/mockup/mxMockupContainers.js" }); + libraries.put("mockup/forms", + new String[] { SHAPES_PATH + "/mockup/mxMockupForms.js" }); + libraries.put("mockup/graphics", + new String[] { SHAPES_PATH + "/mockup/mxMockupGraphics.js", + STENCIL_PATH + "/mockup/misc.xml" }); + libraries.put("mockup/markup", + new String[] { SHAPES_PATH + "/mockup/mxMockupMarkup.js" }); + libraries.put("mockup/misc", + new String[] { SHAPES_PATH + "/mockup/mxMockupMisc.js", + STENCIL_PATH + "/mockup/misc.xml" }); + libraries.put("mockup/navigation", + new String[] { SHAPES_PATH + "/mockup/mxMockupNavigation.js", + STENCIL_PATH + "/mockup/misc.xml" }); + libraries.put("mockup/text", + new String[] { SHAPES_PATH + "/mockup/mxMockupText.js" }); + libraries.put("floorplan", + new String[] { SHAPES_PATH + "/mxFloorplan.js", + STENCIL_PATH + "/floorplan.xml" }); + libraries.put("bootstrap", + new String[] { SHAPES_PATH + "/mxBootstrap.js", + STENCIL_PATH + "/bootstrap.xml" }); + libraries.put("gmdl", new String[] { SHAPES_PATH + "/mxGmdl.js", + STENCIL_PATH + "/gmdl.xml" }); + libraries.put("cabinets", new String[] { SHAPES_PATH + "/mxCabinets.js", + STENCIL_PATH + "/cabinets.xml" }); + libraries.put("archimate", + new String[] { SHAPES_PATH + "/mxArchiMate.js" }); + libraries.put("archimate3", + new String[] { SHAPES_PATH + "/mxArchiMate3.js" }); + libraries.put("sysml", new String[] { SHAPES_PATH + "/mxSysML.js" }); + libraries.put("eip", new String[] { SHAPES_PATH + "/mxEip.js", + STENCIL_PATH + "/eip.xml" }); + libraries.put("networks", new String[] { SHAPES_PATH + "/mxNetworks.js", + STENCIL_PATH + "/networks.xml" }); + libraries.put("aws3d", new String[] { SHAPES_PATH + "/mxAWS3D.js", + STENCIL_PATH + "/aws3d.xml" }); + libraries.put("pid2inst", + new String[] { SHAPES_PATH + "/pid2/mxPidInstruments.js" }); + libraries.put("pid2misc", + new String[] { SHAPES_PATH + "/pid2/mxPidMisc.js", + STENCIL_PATH + "/pid/misc.xml" }); + libraries.put("pid2valves", + new String[] { SHAPES_PATH + "/pid2/mxPidValves.js" }); + libraries.put("pidFlowSensors", + new String[] { STENCIL_PATH + "/pid/flow_sensors.xml" }); + } + + /** + * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) + */ + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException + { + try + { + String qs = request.getQueryString(); + + if (qs != null && qs.equals("stats")) + { + writeStats(response); + } + else + { + // Checks or sets last modified date of delivered content. + // Date comparison not needed. Only return 304 if + // delivered by this servlet instance. + String modSince = request.getHeader("If-Modified-Since"); + + if (modSince != null && modSince.equals(lastModified) + && request.getParameter("fetch") == null) + { + response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); + } + else + { + writeEmbedResponse(request, response); + } + } + } + catch (Exception e) + { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + } + + public void writeEmbedResponse(HttpServletRequest request, + HttpServletResponse response) throws IOException + { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/javascript; charset=UTF-8"); + response.setHeader("Last-Modified", lastModified); + + if (request.getParameter("fetch") != null) + { + response.setHeader("Cache-Control", "no-store"); + } + + OutputStream out = response.getOutputStream(); + + // Creates XML for stencils + PrintWriter writer = new PrintWriter(out); + + // Writes JavaScript and adds function call with + // stylesheet and stencils as arguments + writer.println(createEmbedJavaScript(request)); + response.setStatus(HttpServletResponse.SC_OK); + + writer.flush(); + writer.close(); + } + + public String createEmbedJavaScript(HttpServletRequest request) + throws IOException + { + String sparam = request.getParameter("s"); + String dev = request.getParameter("dev"); + StringBuffer result = new StringBuffer("["); + StringBuffer js = new StringBuffer(""); + + // Processes each stencil only once + HashSet done = new HashSet(); + + // Processes each lib only once + HashSet libsLoaded = new HashSet(); + + if (sparam != null) + { + String[] names = sparam.split(";"); + + for (int i = 0; i < names.length; i++) + { + if (names[i].indexOf("..") < 0 && !done.contains(names[i])) + { + if (names[i].equals("*")) + { + js.append(readXmlFile("/js/shapes-14-6-5.min.js", false)); + result.append( + "'" + readXmlFile("/stencils.xml", true) + "'"); + } + else + { + // Checks if any JS files are associated with the library + // name and injects the JS into the page + String[] libs = libraries.get(names[i]); + + if (libs != null) + { + for (int j = 0; j < libs.length; j++) + { + if (!libsLoaded.contains(libs[j])) + { + String tmp = stencils.get(libs[j]); + libsLoaded.add(libs[j]); + + if (tmp == null) + { + try + { + tmp = readXmlFile(libs[j], + !libs[j].toLowerCase() + .endsWith(".js")); + + // Cache for later use + if (tmp != null) + { + stencils.put(libs[j], tmp); + } + } + catch (NullPointerException e) + { + // This seems possible according to access log so ignore stencil + } + } + + if (tmp != null) + { + // TODO: Add JS to Javascript code inline. This had to be done to quickly + // add JS-based dynamic loading to the existing embed setup where everything + // dynamic is passed via function call, so an indirection via eval must be + // used even though the JS could be parsed directly by adding it to JS. + if (libs[j].toLowerCase() + .endsWith(".js")) + { + js.append(tmp); + } + else + { + if (result.length() > 1) + { + result.append(","); + } + + result.append("'" + tmp + "'"); + } + } + } + } + } + else + { + String tmp = stencils.get(names[i]); + + if (tmp == null) + { + try + { + tmp = readXmlFile( + "/stencils/" + names[i] + ".xml", + true); + + // Cache for later use + if (tmp != null) + { + stencils.put(names[i], tmp); + } + } + catch (NullPointerException e) + { + // This seems possible according to access log so ignore stencil + } + } + + if (tmp != null) + { + if (result.length() > 1) + { + result.append(","); + } + + result.append("'" + tmp + "'"); + } + } + } + + done.add(names[i]); + } + } + } + + result.append("]"); + + // LATER: Detect protocol of request in dev + // mode to avoid security errors + String proto = "https://"; + + String setCachedUrls = ""; + String[] urls = request.getParameterValues("fetch"); + + if (urls != null) + { + HashSet completed = new HashSet(); + + for (int i = 0; i < urls.length; i++) + { + try + { + // Checks if URL already fetched to avoid duplicates + // BUG: CWE-918 Server-Side Request Forgery (SSRF) + // if (!completed.contains(urls[i])) + // FIXED: + if (!completed.contains(urls[i]) && Utils.sanitizeUrl(urls[i])) + { + completed.add(urls[i]); + URL url = new URL(urls[i]); + URLConnection connection = url.openConnection(); + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + Utils.copy(connection.getInputStream(), stream); + setCachedUrls += "GraphViewer.cachedUrls['" + + StringEscapeUtils.escapeEcmaScript(urls[i]) + + "'] = decodeURIComponent('" + + StringEscapeUtils.escapeEcmaScript( + Utils.encodeURIComponent( + stream.toString("UTF-8"), + Utils.CHARSET_FOR_URL_ENCODING)) + + "');"; + } + } + catch (Exception e) + { + // ignore + } + } + } + + // Installs a callback to load the stencils after the viewer was injected + return "window.onDrawioViewerLoad = function() {" + setCachedUrls + + "mxStencilRegistry.parseStencilSets(" + result.toString() + + ");" + js + "GraphViewer.processElements(); };" + + "var t = document.getElementsByTagName('script');" + + "if (t != null && t.length > 0) {" + + "var script = document.createElement('script');" + + "script.type = 'text/javascript';" + "script.src = '" + proto + + ((dev != null && dev.equals("1")) ? "test" : "www") + + ".draw.io/js/viewer-static.min.js';" + + "t[0].parentNode.appendChild(script);}"; + } + + public void writeStats(HttpServletResponse response) throws IOException + { + PrintWriter writer = new PrintWriter(response.getOutputStream()); + writer.println(""); + writer.println(""); + writer.println("Deployed: " + lastModified); + writer.println(""); + writer.println(""); + writer.flush(); + } + + public String readXmlFile(String filename, boolean xmlContent) + throws IOException + { + String result = readFile(filename); + + if (xmlContent) + { + result = result.replaceAll("'", "\\\\'").replaceAll("\t", "") + .replaceAll("\n", ""); + } + + return result; + } + + public String readFile(String filename) throws IOException + { + InputStream is = getServletContext().getResourceAsStream(filename); + + return Utils.readInputStream(is); + } + +} diff --git a/Java/EntityImageActivity.java b/Java/EntityImageActivity.java new file mode 100644 index 0000000000000000000000000000000000000000..872dcbaaef9f8a9eff34c09cb9694d6b84e5850d --- /dev/null +++ b/Java/EntityImageActivity.java @@ -0,0 +1,191 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek.image; + +import net.sourceforge.plantuml.ColorParam; +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.FontParam; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.SkinParamUtils; +import net.sourceforge.plantuml.Url; +import net.sourceforge.plantuml.UseStyle; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.cucadiagram.ILeaf; +import net.sourceforge.plantuml.cucadiagram.Stereotype; +import net.sourceforge.plantuml.graphic.FontConfiguration; +import net.sourceforge.plantuml.graphic.HorizontalAlignment; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.graphic.color.ColorType; +import net.sourceforge.plantuml.style.PName; +import net.sourceforge.plantuml.style.SName; +import net.sourceforge.plantuml.style.Style; +import net.sourceforge.plantuml.style.StyleSignature; +import net.sourceforge.plantuml.style.StyleSignatureBasic; +import net.sourceforge.plantuml.svek.AbstractEntityImage; +import net.sourceforge.plantuml.svek.Bibliotekon; +import net.sourceforge.plantuml.svek.ShapeType; +import net.sourceforge.plantuml.svek.SvekNode; +import net.sourceforge.plantuml.ugraphic.Shadowable; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.URectangle; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class EntityImageActivity extends AbstractEntityImage { + + private double shadowing = 0; + public static final int CORNER = 25; + final private TextBlock desc; + final private static int MARGIN = 10; + final private Url url; + private final Bibliotekon bibliotekon; + + public EntityImageActivity(ILeaf entity, ISkinParam skinParam, Bibliotekon bibliotekon) { + super(entity, skinParam); + this.bibliotekon = bibliotekon; + final Stereotype stereotype = entity.getStereotype(); + + final FontConfiguration fontConfiguration; + final HorizontalAlignment horizontalAlignment; + if (UseStyle.useBetaStyle()) { + final Style style = getDefaultStyleDefinition().getMergedStyle(getSkinParam().getCurrentStyleBuilder()); + fontConfiguration = style.getFontConfiguration(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); + horizontalAlignment = style.getHorizontalAlignment(); + shadowing = style.value(PName.Shadowing).asDouble(); + } else { + fontConfiguration = FontConfiguration.create(getSkinParam(), FontParam.ACTIVITY, stereotype); + horizontalAlignment = HorizontalAlignment.CENTER; + if (getSkinParam().shadowing(getEntity().getStereotype())) { + shadowing = 4; + } + } + this.desc = entity.getDisplay().create(fontConfiguration, horizontalAlignment, skinParam); + this.url = entity.getUrl99(); + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + final Dimension2D dim = desc.calculateDimension(stringBounder); + return Dimension2DDouble.delta(dim, MARGIN * 2); + } + + final public void drawU(UGraphic ug) { + if (url != null) { + ug.startUrl(url); + } + if (getShapeType() == ShapeType.ROUND_RECTANGLE) { + ug = drawNormal(ug); + } else if (getShapeType() == ShapeType.OCTAGON) { + ug = drawOctagon(ug); + } else { + throw new UnsupportedOperationException(); + } + if (url != null) { + ug.closeUrl(); + } + } + + private UGraphic drawOctagon(UGraphic ug) { + final SvekNode node = bibliotekon.getNode(getEntity()); + final Shadowable octagon = node.getPolygon(); + if (octagon == null) { + return drawNormal(ug); + } + octagon.setDeltaShadow(shadowing); + ug = applyColors(ug); + ug.apply(new UStroke(1.5)).draw(octagon); + desc.drawU(ug.apply(new UTranslate(MARGIN, MARGIN))); + return ug; + + } + + private UGraphic drawNormal(UGraphic ug) { + final StringBounder stringBounder = ug.getStringBounder(); + final Dimension2D dimTotal = calculateDimension(stringBounder); + + final double widthTotal = dimTotal.getWidth(); + final double heightTotal = dimTotal.getHeight(); + final Shadowable rect = new URectangle(widthTotal, heightTotal).rounded(CORNER); + rect.setDeltaShadow(shadowing); + + ug = applyColors(ug); + UStroke stroke = new UStroke(1.5); + if (UseStyle.useBetaStyle()) { + final Style style = getDefaultStyleDefinition().getMergedStyle(getSkinParam().getCurrentStyleBuilder()); + stroke = style.getStroke(); + } + ug.apply(stroke).draw(rect); + + desc.drawU(ug.apply(new UTranslate(MARGIN, MARGIN))); + return ug; + } + + public StyleSignature getDefaultStyleDefinition() { + return StyleSignatureBasic.of(SName.root, SName.element, SName.activityDiagram, SName.activity).withTOBECHANGED(getStereo()); + } + + private UGraphic applyColors(UGraphic ug) { + HColor borderColor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.activityBorder); + HColor backcolor = getEntity().getColors().getColor(ColorType.BACK); + if (backcolor == null) { + backcolor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.activityBackground); + } + + if (UseStyle.useBetaStyle()) { + final Style style = getDefaultStyleDefinition().getMergedStyle(getSkinParam().getCurrentStyleBuilder()); + borderColor = style.value(PName.LineColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + backcolor = getEntity().getColors().getColor(ColorType.BACK); + if (backcolor == null) { + backcolor = style.value(PName.BackGroundColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + } + } + ug = ug.apply(borderColor); + ug = ug.apply(backcolor.bg()); + return ug; + } + + public ShapeType getShapeType() { + final Stereotype stereotype = getStereo(); + if (getSkinParam().useOctagonForActivity(stereotype)) { + return ShapeType.OCTAGON; + } + return ShapeType.ROUND_RECTANGLE; + } + +} diff --git a/Java/EntityImageBranch.java b/Java/EntityImageBranch.java new file mode 100644 index 0000000000000000000000000000000000000000..efd88f3edb93a89d6f09e4ed68132ac6cf231be7 --- /dev/null +++ b/Java/EntityImageBranch.java @@ -0,0 +1,118 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek.image; + +import java.util.EnumMap; +import java.util.Map; + +import net.sourceforge.plantuml.ColorParam; +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.SkinParamUtils; +import net.sourceforge.plantuml.UseStyle; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.cucadiagram.ILeaf; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.style.PName; +import net.sourceforge.plantuml.style.SName; +import net.sourceforge.plantuml.style.Style; +import net.sourceforge.plantuml.style.StyleSignatureBasic; +import net.sourceforge.plantuml.svek.AbstractEntityImage; +import net.sourceforge.plantuml.svek.ShapeType; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UGroupType; +import net.sourceforge.plantuml.ugraphic.UPolygon; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class EntityImageBranch extends AbstractEntityImage { + + final private static int SIZE = 12; + + public EntityImageBranch(ILeaf entity, ISkinParam skinParam) { + super(entity, skinParam); + } + + public StyleSignatureBasic getDefaultStyleDefinition() { + return StyleSignatureBasic.of(SName.root, SName.element, SName.activityDiagram, SName.activity, SName.diamond); + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + return new Dimension2DDouble(SIZE * 2, SIZE * 2); + } + + final public void drawU(UGraphic ug) { + final UPolygon diams = new UPolygon(); + double shadowing = 0; + diams.addPoint(SIZE, 0); + diams.addPoint(SIZE * 2, SIZE); + diams.addPoint(SIZE, SIZE * 2); + diams.addPoint(0, SIZE); + diams.addPoint(SIZE, 0); + + HColor border = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.activityDiamondBorder, + ColorParam.activityBorder); + HColor back = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.activityDiamondBackground, + ColorParam.activityBackground); + UStroke stroke = new UStroke(1.5); + if (UseStyle.useBetaStyle()) { + final Style style = getDefaultStyleDefinition().getMergedStyle(getSkinParam().getCurrentStyleBuilder()); + border = style.value(PName.LineColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + back = style.value(PName.BackGroundColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + stroke = style.getStroke(); + shadowing = style.value(PName.Shadowing).asDouble(); + } else { + if (getSkinParam().shadowing(getEntity().getStereotype())) { + shadowing = 5; + } + + } + diams.setDeltaShadow(shadowing); + final Map typeIDent = new EnumMap<>(UGroupType.class); + typeIDent.put(UGroupType.CLASS, "elem " + getEntity().getCode() + " selected"); + typeIDent.put(UGroupType.ID, "elem_" + getEntity().getCode()); + ug.startGroup(typeIDent); + ug.apply(border).apply(back.bg()).apply(stroke).draw(diams); + ug.closeGroup(); + } + + public ShapeType getShapeType() { + return ShapeType.DIAMOND; + } + +} diff --git a/Java/EntityImageClass.java b/Java/EntityImageClass.java new file mode 100644 index 0000000000000000000000000000000000000000..2b4d9121335d7649379a83a9df21d0e698ce0e0d --- /dev/null +++ b/Java/EntityImageClass.java @@ -0,0 +1,296 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek.image; + +import java.awt.geom.Rectangle2D; +import java.util.EnumMap; +import java.util.Map; + +import net.sourceforge.plantuml.ColorParam; +import net.sourceforge.plantuml.CornerParam; +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.FontParam; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.LineConfigurable; +import net.sourceforge.plantuml.LineParam; +import net.sourceforge.plantuml.SkinParamUtils; +import net.sourceforge.plantuml.Url; +import net.sourceforge.plantuml.UseStyle; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.creole.Stencil; +import net.sourceforge.plantuml.cucadiagram.EntityPortion; +import net.sourceforge.plantuml.cucadiagram.ILeaf; +import net.sourceforge.plantuml.cucadiagram.LeafType; +import net.sourceforge.plantuml.cucadiagram.PortionShower; +import net.sourceforge.plantuml.cucadiagram.dot.GraphvizVersion; +import net.sourceforge.plantuml.graphic.InnerStrategy; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.graphic.color.ColorType; +import net.sourceforge.plantuml.style.PName; +import net.sourceforge.plantuml.style.SName; +import net.sourceforge.plantuml.style.Style; +import net.sourceforge.plantuml.style.StyleSignatureBasic; +import net.sourceforge.plantuml.svek.AbstractEntityImage; +import net.sourceforge.plantuml.svek.Margins; +import net.sourceforge.plantuml.svek.Ports; +import net.sourceforge.plantuml.svek.ShapeType; +import net.sourceforge.plantuml.svek.WithPorts; +import net.sourceforge.plantuml.ugraphic.Shadowable; +import net.sourceforge.plantuml.ugraphic.UComment; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UGraphicStencil; +import net.sourceforge.plantuml.ugraphic.UGroupType; +import net.sourceforge.plantuml.ugraphic.URectangle; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; +import net.sourceforge.plantuml.ugraphic.color.HColorNone; + +public class EntityImageClass extends AbstractEntityImage implements Stencil, WithPorts { + + final private TextBlock body; + final private Margins shield; + final private EntityImageClassHeader header; + final private Url url; + final private double roundCorner; + final private LeafType leafType; + + final private LineConfigurable lineConfig; + + public EntityImageClass(GraphvizVersion version, ILeaf entity, ISkinParam skinParam, PortionShower portionShower) { + super(entity, entity.getColors().mute(skinParam)); + this.leafType = entity.getLeafType(); + this.lineConfig = entity; + if (UseStyle.useBetaStyle()) + this.roundCorner = getStyle().value(PName.RoundCorner).asDouble(); + else + this.roundCorner = getSkinParam().getRoundCorner(CornerParam.DEFAULT, null); + this.shield = version != null && version.useShield() && entity.hasNearDecoration() ? Margins.uniform(16) + : Margins.NONE; + final boolean showMethods = portionShower.showPortion(EntityPortion.METHOD, entity); + final boolean showFields = portionShower.showPortion(EntityPortion.FIELD, entity); + this.body = entity.getBodier().getBody(FontParam.CLASS_ATTRIBUTE, getSkinParam(), showMethods, showFields, + entity.getStereotype(), getStyle(), null); + + this.header = new EntityImageClassHeader(entity, getSkinParam(), portionShower); + this.url = entity.getUrl99(); + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + final Dimension2D dimHeader = header.calculateDimension(stringBounder); + final Dimension2D dimBody = body == null ? new Dimension2DDouble(0, 0) : body.calculateDimension(stringBounder); + double width = Math.max(dimBody.getWidth(), dimHeader.getWidth()); + if (width < getSkinParam().minClassWidth()) + width = getSkinParam().minClassWidth(); + + final double height = dimBody.getHeight() + dimHeader.getHeight(); + return new Dimension2DDouble(width, height); + } + + @Override + public Rectangle2D getInnerPosition(String member, StringBounder stringBounder, InnerStrategy strategy) { + final Rectangle2D result = body.getInnerPosition(member, stringBounder, strategy); + if (result == null) + return result; + + final Dimension2D dimHeader = header.calculateDimension(stringBounder); + final UTranslate translate = UTranslate.dy(dimHeader.getHeight()); + return translate.apply(result); + } + + final public void drawU(UGraphic ug) { + ug.draw(new UComment("class " + getEntity().getCodeGetName())); + if (url != null) + ug.startUrl(url); + + final Map typeIDent = new EnumMap<>(UGroupType.class); + typeIDent.put(UGroupType.CLASS, "elem " + getEntity().getCode() + " selected"); + typeIDent.put(UGroupType.ID, "elem_" + getEntity().getCode()); + ug.startGroup(typeIDent); + drawInternal(ug); + ug.closeGroup(); + + if (url != null) + ug.closeUrl(); + + } + + private Style getStyle() { + return StyleSignatureBasic.of(SName.root, SName.element, SName.classDiagram, SName.class_) // + .withTOBECHANGED(getEntity().getStereotype()) // + .with(getEntity().getStereostyles()) // + .getMergedStyle(getSkinParam().getCurrentStyleBuilder()); + } + + private Style getStyleHeader() { + return StyleSignatureBasic.of(SName.root, SName.element, SName.classDiagram, SName.class_, SName.header) // + .withTOBECHANGED(getEntity().getStereotype()) // + .with(getEntity().getStereostyles()) // + .getMergedStyle(getSkinParam().getCurrentStyleBuilder()); + } + + private void drawInternal(UGraphic ug) { + final StringBounder stringBounder = ug.getStringBounder(); + final Dimension2D dimTotal = calculateDimension(stringBounder); + final Dimension2D dimHeader = header.calculateDimension(stringBounder); + + final double widthTotal = dimTotal.getWidth(); + final double heightTotal = dimTotal.getHeight(); + final Shadowable rect = new URectangle(widthTotal, heightTotal).rounded(roundCorner) + .withCommentAndCodeLine(getEntity().getCodeGetName(), getEntity().getCodeLine()); + + double shadow = 0; + + HColor classBorder = lineConfig.getColors().getColor(ColorType.LINE); + HColor headerBackcolor = getEntity().getColors().getColor(ColorType.HEADER); + HColor backcolor = getEntity().getColors().getColor(ColorType.BACK); + + if (UseStyle.useBetaStyle()) { + shadow = getStyle().value(PName.Shadowing).asDouble(); + + if (classBorder == null) + classBorder = getStyle().value(PName.LineColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + + if (headerBackcolor == null) + headerBackcolor = backcolor == null ? getStyleHeader().value(PName.BackGroundColor) + .asColor(getSkinParam().getThemeStyle(), getSkinParam().getIHtmlColorSet()) : backcolor; + + if (backcolor == null) + backcolor = getStyle().value(PName.BackGroundColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + + } else { + if (getSkinParam().shadowing(getEntity().getStereotype())) + shadow = 4; + + if (classBorder == null) + classBorder = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.classBorder); + + if (backcolor == null) + if (leafType == LeafType.ENUM) + backcolor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.enumBackground, + ColorParam.classBackground); + else + backcolor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.classBackground); + + if (headerBackcolor == null) + headerBackcolor = getSkinParam().getHtmlColor(ColorParam.classHeaderBackground, getStereo(), false); + + } + + rect.setDeltaShadow(shadow); + + ug = ug.apply(classBorder); + ug = ug.apply(backcolor.bg()); + + final UStroke stroke = getStroke(); + + UGraphic ugHeader = ug; + if (roundCorner == 0 && headerBackcolor != null && backcolor.equals(headerBackcolor) == false) { + ug.apply(stroke).draw(rect); + final Shadowable rect2 = new URectangle(widthTotal, dimHeader.getHeight()); + rect2.setDeltaShadow(0); + ugHeader = ugHeader.apply(headerBackcolor.bg()); + ugHeader.apply(stroke).draw(rect2); + } else if (roundCorner != 0 && headerBackcolor != null && backcolor.equals(headerBackcolor) == false) { + ug.apply(stroke).draw(rect); + final Shadowable rect2 = new URectangle(widthTotal, dimHeader.getHeight()).rounded(roundCorner); + final URectangle rect3 = new URectangle(widthTotal, roundCorner / 2); + rect2.setDeltaShadow(0); + rect3.setDeltaShadow(0); + ugHeader = ugHeader.apply(headerBackcolor.bg()).apply(headerBackcolor); + ugHeader.apply(stroke).draw(rect2); + ugHeader.apply(stroke).apply(UTranslate.dy(dimHeader.getHeight() - rect3.getHeight())).draw(rect3); + rect.setDeltaShadow(0); + ug.apply(stroke).apply(new HColorNone().bg()).draw(rect); + } else { + ug.apply(stroke).draw(rect); + } + header.drawU(ugHeader, dimTotal.getWidth(), dimHeader.getHeight()); + + if (body != null) { + final UGraphic ug2 = UGraphicStencil.create(ug, this, stroke); + final UTranslate translate = UTranslate.dy(dimHeader.getHeight()); + body.drawU(ug2.apply(translate)); + } + } + + @Override + public Ports getPorts(StringBounder stringBounder) { + final Dimension2D dimHeader = header.calculateDimension(stringBounder); + if (body instanceof WithPorts) + return ((WithPorts) body).getPorts(stringBounder).translateY(dimHeader.getHeight()); + return new Ports(); + } + + private UStroke getStroke() { + + if (UseStyle.useBetaStyle()) + return getStyle().getStroke(); + + UStroke stroke = lineConfig.getColors().getSpecificLineStroke(); + if (stroke == null) + stroke = getSkinParam().getThickness(LineParam.classBorder, getStereo()); + + if (stroke == null) + stroke = new UStroke(1.5); + + return stroke; + } + + public ShapeType getShapeType() { + if (((ILeaf) getEntity()).getPortShortNames().size() > 0) { + return ShapeType.RECTANGLE_HTML_FOR_PORTS; + } + return ShapeType.RECTANGLE; + } + + @Override + public Margins getShield(StringBounder stringBounder) { + return shield; + } + + public double getStartingX(StringBounder stringBounder, double y) { + return 0; + } + + public double getEndingX(StringBounder stringBounder, double y) { + return calculateDimension(stringBounder).getWidth(); + } + +} diff --git a/Java/EntityImageDegenerated.java b/Java/EntityImageDegenerated.java new file mode 100644 index 0000000000000000000000000000000000000000..803ed40316d2c11f858d59667831c006e38b35f0 --- /dev/null +++ b/Java/EntityImageDegenerated.java @@ -0,0 +1,106 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek; + +import java.awt.geom.Rectangle2D; + +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.UseStyle; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.graphic.InnerStrategy; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.ugraphic.MinMax; +import net.sourceforge.plantuml.ugraphic.UEmpty; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class EntityImageDegenerated implements IEntityImage { + + private final IEntityImage orig; + private final double delta = 7; + private final HColor backcolor; + + public EntityImageDegenerated(IEntityImage orig, HColor backcolor) { + this.orig = orig; + this.backcolor = backcolor; + } + + public boolean isHidden() { + return orig.isHidden(); + } + + public HColor getBackcolor() { + // return orig.getBackcolor(); + return backcolor; + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + return Dimension2DDouble.delta(orig.calculateDimension(stringBounder), delta * 2, delta * 2); + } + + public MinMax getMinMax(StringBounder stringBounder) { + return orig.getMinMax(stringBounder); + // return orig.getMinMax(stringBounder).translate(new UTranslate(delta, delta)); + // return orig.getMinMax(stringBounder).appendToMax(delta, delta); + } + + public Rectangle2D getInnerPosition(String member, StringBounder stringBounder, InnerStrategy strategy) { + return orig.getInnerPosition(member, stringBounder, strategy); + } + + public void drawU(UGraphic ug) { + orig.drawU(ug.apply(new UTranslate(delta, delta))); + if (UseStyle.useBetaStyle()) { + final Dimension2D dim = calculateDimension(ug.getStringBounder()); + ug.apply(new UTranslate(dim.getWidth() - delta, dim.getHeight() - delta)).draw(new UEmpty(delta, delta)); + } + + } + + public ShapeType getShapeType() { + return orig.getShapeType(); + } + + public Margins getShield(StringBounder stringBounder) { + return orig.getShield(stringBounder); + } + + public double getOverscanX(StringBounder stringBounder) { + return orig.getOverscanX(stringBounder); + } + +} \ No newline at end of file diff --git a/Java/EntityImageEmptyPackage.java b/Java/EntityImageEmptyPackage.java new file mode 100644 index 0000000000000000000000000000000000000000..2ee3e40856962b8e539af2e27215be50a50fb0ed --- /dev/null +++ b/Java/EntityImageEmptyPackage.java @@ -0,0 +1,201 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek.image; + +import net.sourceforge.plantuml.AlignmentParam; +import net.sourceforge.plantuml.ColorParam; +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.FontParam; +import net.sourceforge.plantuml.Guillemet; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.SkinParamUtils; +import net.sourceforge.plantuml.Url; +import net.sourceforge.plantuml.UseStyle; +import net.sourceforge.plantuml.activitydiagram3.ftile.EntityImageLegend; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.cucadiagram.Display; +import net.sourceforge.plantuml.cucadiagram.DisplayPositioned; +import net.sourceforge.plantuml.cucadiagram.EntityPortion; +import net.sourceforge.plantuml.cucadiagram.ILeaf; +import net.sourceforge.plantuml.cucadiagram.PortionShower; +import net.sourceforge.plantuml.cucadiagram.Stereotype; +import net.sourceforge.plantuml.cucadiagram.entity.EntityImpl; +import net.sourceforge.plantuml.graphic.FontConfiguration; +import net.sourceforge.plantuml.graphic.HorizontalAlignment; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.graphic.TextBlockUtils; +import net.sourceforge.plantuml.graphic.USymbols; +import net.sourceforge.plantuml.graphic.color.ColorType; +import net.sourceforge.plantuml.graphic.color.Colors; +import net.sourceforge.plantuml.style.PName; +import net.sourceforge.plantuml.style.SName; +import net.sourceforge.plantuml.style.Style; +import net.sourceforge.plantuml.style.StyleSignature; +import net.sourceforge.plantuml.style.StyleSignatureBasic; +import net.sourceforge.plantuml.svek.AbstractEntityImage; +import net.sourceforge.plantuml.svek.Cluster; +import net.sourceforge.plantuml.svek.ClusterDecoration; +import net.sourceforge.plantuml.svek.GeneralImageBuilder; +import net.sourceforge.plantuml.svek.ShapeType; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class EntityImageEmptyPackage extends AbstractEntityImage { + + private final TextBlock desc; + private final static int MARGIN = 10; + + private final Stereotype stereotype; + private final TextBlock stereoBlock; + private final Url url; + private final SName sname; + private final double shadowing; + private final HColor borderColor; + private final UStroke stroke; + private final double roundCorner; + private final double diagonalCorner; + private final HColor back; + + private Style getStyle() { + return getStyleSignature().getMergedStyle(getSkinParam().getCurrentStyleBuilder()); + } + + private StyleSignature getStyleSignature() { + return StyleSignatureBasic.of(SName.root, SName.element, sname, SName.package_).withTOBECHANGED(stereotype); + } + + public EntityImageEmptyPackage(ILeaf entity, ISkinParam skinParam, PortionShower portionShower, SName sname) { + super(entity, skinParam); + this.sname = sname; + + final Colors colors = entity.getColors(); + final HColor specificBackColor = colors.getColor(ColorType.BACK); + this.stereotype = entity.getStereotype(); + final FontConfiguration titleFontConfiguration; + final HorizontalAlignment titleHorizontalAlignment; + this.url = entity.getUrl99(); + + if (UseStyle.useBetaStyle()) { + Style style = getStyle(); + style = style.eventuallyOverride(colors); + this.borderColor = style.value(PName.LineColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + this.shadowing = style.value(PName.Shadowing).asDouble(); + this.stroke = style.getStroke(colors); + this.roundCorner = style.value(PName.RoundCorner).asDouble(); + this.diagonalCorner = style.value(PName.DiagonalCorner).asDouble(); + if (specificBackColor == null) { + this.back = style.value(PName.BackGroundColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + } else { + this.back = specificBackColor; + } + titleFontConfiguration = style.getFontConfiguration(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + titleHorizontalAlignment = style.getHorizontalAlignment(); + } else { + this.diagonalCorner = 0; + this.borderColor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.packageBorder); + this.shadowing = getSkinParam().shadowing(getEntity().getStereotype()) ? 3 : 0; + this.stroke = GeneralImageBuilder.getForcedStroke(getEntity().getStereotype(), getSkinParam()); + this.roundCorner = 0; + this.back = Cluster.getBackColor(specificBackColor, skinParam, stereotype, sname, USymbols.PACKAGE); + titleFontConfiguration = FontConfiguration.create(getSkinParam(), FontParam.PACKAGE, stereotype); + titleHorizontalAlignment = HorizontalAlignment.CENTER; + } + + this.desc = entity.getDisplay().create(titleFontConfiguration, titleHorizontalAlignment, skinParam); + + final DisplayPositioned legend = ((EntityImpl) entity).getLegend(); + if (legend != null) { + final TextBlock legendBlock = EntityImageLegend.create(legend.getDisplay(), skinParam); + stereoBlock = legendBlock; + } else { + if (stereotype == null || stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR) == null + || portionShower.showPortion(EntityPortion.STEREOTYPE, entity) == false) { + stereoBlock = TextBlockUtils.empty(0, 0); + } else { + stereoBlock = TextBlockUtils.withMargin(Display.create(stereotype.getLabels(skinParam.guillemet())) + .create(FontConfiguration.create(getSkinParam(), FontParam.PACKAGE_STEREOTYPE, stereotype), + titleHorizontalAlignment, skinParam), + 1, 0); + } + } + + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + final Dimension2D dimDesc = desc.calculateDimension(stringBounder); + Dimension2D dim = TextBlockUtils.mergeTB(desc, stereoBlock, HorizontalAlignment.LEFT) + .calculateDimension(stringBounder); + dim = Dimension2DDouble.atLeast(dim, 0, 2 * dimDesc.getHeight()); + return Dimension2DDouble.delta(dim, MARGIN * 2, MARGIN * 2); + } + + final public void drawU(UGraphic ug) { + if (url != null) { + ug.startUrl(url); + } + + final StringBounder stringBounder = ug.getStringBounder(); + final Dimension2D dimTotal = calculateDimension(stringBounder); + + final double widthTotal = dimTotal.getWidth(); + final double heightTotal = dimTotal.getHeight(); + + final ClusterDecoration decoration = new ClusterDecoration(getSkinParam().packageStyle(), null, desc, + stereoBlock, 0, 0, widthTotal, heightTotal, stroke); + + final HorizontalAlignment horizontalAlignment = getSkinParam() + .getHorizontalAlignment(AlignmentParam.packageTitleAlignment, null, false, null); + final HorizontalAlignment stereotypeAlignment = getSkinParam().getStereotypeAlignment(); + + decoration.drawU(ug, back, borderColor, shadowing, roundCorner, horizontalAlignment, stereotypeAlignment, + diagonalCorner); + + if (url != null) { + ug.closeUrl(); + } + + } + + public ShapeType getShapeType() { + return ShapeType.RECTANGLE; + } + +} diff --git a/Java/EntityImageLollipopInterface.java b/Java/EntityImageLollipopInterface.java new file mode 100644 index 0000000000000000000000000000000000000000..01dad2f576ad6c71cf3f2ced6b90ec940a34c7b8 --- /dev/null +++ b/Java/EntityImageLollipopInterface.java @@ -0,0 +1,164 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek.image; + +import java.util.EnumMap; +import java.util.Map; + +import net.sourceforge.plantuml.ColorParam; +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.FontParam; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.SkinParamUtils; +import net.sourceforge.plantuml.Url; +import net.sourceforge.plantuml.UseStyle; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.cucadiagram.ILeaf; +import net.sourceforge.plantuml.cucadiagram.LeafType; +import net.sourceforge.plantuml.cucadiagram.Stereotype; +import net.sourceforge.plantuml.graphic.FontConfiguration; +import net.sourceforge.plantuml.graphic.HorizontalAlignment; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.style.PName; +import net.sourceforge.plantuml.style.SName; +import net.sourceforge.plantuml.style.Style; +import net.sourceforge.plantuml.style.StyleSignatureBasic; +import net.sourceforge.plantuml.svek.AbstractEntityImage; +import net.sourceforge.plantuml.svek.ShapeType; +import net.sourceforge.plantuml.ugraphic.UEllipse; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UGroupType; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class EntityImageLollipopInterface extends AbstractEntityImage { + + private static final int SIZE = 10; + + private final TextBlock desc; + private final SName sname; + private final Url url; + + public StyleSignatureBasic getSignature() { + return StyleSignatureBasic.of(SName.root, SName.element, sname, SName.circle); + } + + private UStroke getUStroke() { + return new UStroke(1.5); + } + + public EntityImageLollipopInterface(ILeaf entity, ISkinParam skinParam, SName sname) { + super(entity, skinParam); + this.sname = sname; + final Stereotype stereotype = entity.getStereotype(); + final FontConfiguration fc; + if (UseStyle.useBetaStyle()) + fc = FontConfiguration.create(getSkinParam(), + getSignature().getMergedStyle(skinParam.getCurrentStyleBuilder())); + else + fc = FontConfiguration.create(getSkinParam(), FontParam.CLASS, stereotype); + + this.desc = entity.getDisplay().create(fc, HorizontalAlignment.CENTER, skinParam); + this.url = entity.getUrl99(); + + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + return new Dimension2DDouble(SIZE, SIZE); + } + + final public void drawU(UGraphic ug) { + + final HColor backgroundColor; + final HColor borderColor; + double shadow = 4; + + if (UseStyle.useBetaStyle()) { + final Style style = getSignature().getMergedStyle(getSkinParam().getCurrentStyleBuilder()); + backgroundColor = style.value(PName.BackGroundColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + borderColor = style.value(PName.LineColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + shadow = style.value(PName.Shadowing).asDouble(); + } else { + backgroundColor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.classBackground); + borderColor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.classBorder); + } + + final UEllipse circle; + if (getEntity().getLeafType() == LeafType.LOLLIPOP_HALF) { + circle = new UEllipse(SIZE, SIZE, angle - 90, 180); + } else { + circle = new UEllipse(SIZE, SIZE); + if (getSkinParam().shadowing(getEntity().getStereotype())) + circle.setDeltaShadow(shadow); + } + + ug = ug.apply(backgroundColor.bg()).apply(borderColor); + if (url != null) + ug.startUrl(url); + + final Map typeIDent = new EnumMap<>(UGroupType.class); + typeIDent.put(UGroupType.CLASS, "elem " + getEntity().getCode() + " selected"); + typeIDent.put(UGroupType.ID, "elem_" + getEntity().getCode()); + ug.startGroup(typeIDent); + ug.apply(getUStroke()).draw(circle); + ug.closeGroup(); + + final Dimension2D dimDesc = desc.calculateDimension(ug.getStringBounder()); + final double widthDesc = dimDesc.getWidth(); + + final double x = SIZE / 2 - widthDesc / 2; + final double y = SIZE; + desc.drawU(ug.apply(new UTranslate(x, y))); + if (url != null) + ug.closeUrl(); + + } + + public ShapeType getShapeType() { + return ShapeType.CIRCLE_IN_RECT; + } + + private double angle; + + public void addImpact(double angle) { + this.angle = 180 - (angle * 180 / Math.PI); + } + +} diff --git a/Java/EntityImageLollipopInterfaceEye1.java b/Java/EntityImageLollipopInterfaceEye1.java new file mode 100644 index 0000000000000000000000000000000000000000..815d1bc346e5013b94f3531045f315537a108a7e --- /dev/null +++ b/Java/EntityImageLollipopInterfaceEye1.java @@ -0,0 +1,131 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek.image; + +import java.awt.geom.Point2D; +import java.util.List; + +import net.sourceforge.plantuml.ColorParam; +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.FontParam; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.SkinParamUtils; +import net.sourceforge.plantuml.Url; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.cucadiagram.ILeaf; +import net.sourceforge.plantuml.cucadiagram.Stereotype; +import net.sourceforge.plantuml.graphic.FontConfiguration; +import net.sourceforge.plantuml.graphic.HorizontalAlignment; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.svek.AbstractEntityImage; +import net.sourceforge.plantuml.svek.Bibliotekon; +import net.sourceforge.plantuml.svek.ShapeType; +import net.sourceforge.plantuml.svek.SvekLine; +import net.sourceforge.plantuml.ugraphic.UEllipse; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColorNone; + +public class EntityImageLollipopInterfaceEye1 extends AbstractEntityImage { + + private static final int SIZE = 24; + private final TextBlock desc; + private final Bibliotekon bibliotekon; + final private Url url; + + public EntityImageLollipopInterfaceEye1(ILeaf entity, ISkinParam skinParam, Bibliotekon bibliotekon) { + super(entity, skinParam); + this.bibliotekon = bibliotekon; + final Stereotype stereotype = entity.getStereotype(); + this.desc = entity.getDisplay().create(FontConfiguration.create(getSkinParam(), FontParam.CLASS, stereotype), + HorizontalAlignment.CENTER, skinParam); + this.url = entity.getUrl99(); + + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + return new Dimension2DDouble(SIZE, SIZE); + } + + final public void drawU(UGraphic ug) { + ug = ug.apply(SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.classBorder)); + ug = ug.apply(SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.classBackground).bg()); + if (url != null) { + ug.startUrl(url); + } + final double sizeSmall = 14; + final double diff = (SIZE - sizeSmall) / 2; + final UEllipse circle1 = new UEllipse(sizeSmall, sizeSmall); + if (getSkinParam().shadowing(getEntity().getStereotype())) { + // circle.setDeltaShadow(4); + } + ug.apply(new UStroke(1.5)).apply(new UTranslate(diff, diff)).draw(circle1); + ug = ug.apply(new HColorNone().bg()); + + Point2D pos = bibliotekon.getNode(getEntity()).getPosition(); + + final List lines = bibliotekon.getAllLineConnectedTo(getEntity()); + final UTranslate reverse = new UTranslate(pos).reverse(); + final ConnectedCircle connectedCircle = new ConnectedCircle(SIZE / 2); + for (SvekLine line : lines) { + Point2D pt = line.getMyPoint(getEntity()); + pt = reverse.getTranslated(pt); + connectedCircle.addSecondaryConnection(pt); + + } + // connectedCircle.drawU(ug.apply(new UStroke(1.5))); + connectedCircle.drawU(ug); + + // + // final Dimension2D dimDesc = desc.calculateDimension(ug.getStringBounder()); + // final double widthDesc = dimDesc.getWidth(); + // // final double totalWidth = Math.max(widthDesc, SIZE); + // + // final double x = SIZE / 2 - widthDesc / 2; + // final double y = SIZE; + // desc.drawU(ug.apply(new UTranslate(x, y))); + if (url != null) { + ug.closeUrl(); + } + } + + public ShapeType getShapeType() { + return ShapeType.CIRCLE; + } + +} diff --git a/Java/EntityImageLollipopInterfaceEye2.java b/Java/EntityImageLollipopInterfaceEye2.java new file mode 100644 index 0000000000000000000000000000000000000000..155404d19da7c00cc56d93a4b4ca061f27d7d179 --- /dev/null +++ b/Java/EntityImageLollipopInterfaceEye2.java @@ -0,0 +1,150 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek.image; + +import java.util.Objects; + +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.FontParam; +import net.sourceforge.plantuml.Guillemet; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.SkinParamUtils; +import net.sourceforge.plantuml.Url; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.cucadiagram.BodyFactory; +import net.sourceforge.plantuml.cucadiagram.Display; +import net.sourceforge.plantuml.cucadiagram.EntityPortion; +import net.sourceforge.plantuml.cucadiagram.ILeaf; +import net.sourceforge.plantuml.cucadiagram.PortionShower; +import net.sourceforge.plantuml.cucadiagram.Stereotype; +import net.sourceforge.plantuml.graphic.FontConfiguration; +import net.sourceforge.plantuml.graphic.HorizontalAlignment; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.SymbolContext; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.graphic.TextBlockUtils; +import net.sourceforge.plantuml.graphic.USymbol; +import net.sourceforge.plantuml.graphic.color.ColorType; +import net.sourceforge.plantuml.style.SName; +import net.sourceforge.plantuml.style.Style; +import net.sourceforge.plantuml.svek.AbstractEntityImage; +import net.sourceforge.plantuml.svek.ShapeType; +import net.sourceforge.plantuml.ugraphic.UEllipse; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class EntityImageLollipopInterfaceEye2 extends AbstractEntityImage { + + public static final double SIZE = 14; + private final TextBlock desc; + private final TextBlock stereo; + private final SymbolContext ctx; + final private Url url; + + public EntityImageLollipopInterfaceEye2(ILeaf entity, ISkinParam skinParam, PortionShower portionShower) { + super(entity, skinParam); + final Stereotype stereotype = entity.getStereotype(); + + final USymbol symbol = Objects.requireNonNull( + entity.getUSymbol() == null ? skinParam.componentStyle().toUSymbol() : entity.getUSymbol()); + + this.desc = BodyFactory.create2(skinParam.getDefaultTextAlignment(HorizontalAlignment.CENTER), + entity.getDisplay(), symbol.getFontParam(), skinParam, stereotype, entity, + getStyle(symbol.getFontParam())); + + this.url = entity.getUrl99(); + + HColor backcolor = getEntity().getColors().getColor(ColorType.BACK); + if (backcolor == null) { + backcolor = SkinParamUtils.getColor(getSkinParam(), getStereo(), symbol.getColorParamBack()); + } + // backcolor = HtmlColorUtils.BLUE; + final HColor forecolor = SkinParamUtils.getColor(getSkinParam(), getStereo(), symbol.getColorParamBorder()); + this.ctx = new SymbolContext(backcolor, forecolor).withStroke(new UStroke(1.5)) + .withShadow(getSkinParam().shadowing(getEntity().getStereotype()) ? 3 : 0); + + if (stereotype != null && stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR) != null + && portionShower.showPortion(EntityPortion.STEREOTYPE, entity)) { + stereo = Display.getWithNewlines(stereotype.getLabel(getSkinParam().guillemet())).create( + FontConfiguration.create(getSkinParam(), symbol.getFontParamStereotype(), stereotype), + HorizontalAlignment.CENTER, skinParam); + } else { + stereo = TextBlockUtils.empty(0, 0); + } + + } + + private Style getStyle(FontParam fontParam) { + return fontParam.getStyleDefinition(SName.componentDiagram) + .getMergedStyle(getSkinParam().getCurrentStyleBuilder()); + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + return new Dimension2DDouble(SIZE, SIZE); + } + + final public void drawU(UGraphic ug) { + if (url != null) { + ug.startUrl(url); + } + final UEllipse circle = new UEllipse(SIZE, SIZE); + if (getSkinParam().shadowing(getEntity().getStereotype())) { + circle.setDeltaShadow(4); + } + ctx.apply(ug).draw(circle); + + final Dimension2D dimDesc = desc.calculateDimension(ug.getStringBounder()); + final double x1 = SIZE / 2 - dimDesc.getWidth() / 2; + final double y1 = SIZE * 1.4; + desc.drawU(ug.apply(new UTranslate(x1, y1))); + + final Dimension2D dimStereo = stereo.calculateDimension(ug.getStringBounder()); + final double x2 = SIZE / 2 - dimStereo.getWidth() / 2; + final double y2 = -dimStereo.getHeight(); + stereo.drawU(ug.apply(new UTranslate(x2, y2))); + + if (url != null) { + ug.closeUrl(); + } + } + + public ShapeType getShapeType() { + return ShapeType.CIRCLE; + } + +} diff --git a/Java/EntityImageNote.java b/Java/EntityImageNote.java new file mode 100644 index 0000000000000000000000000000000000000000..80d63878cb32eaaed556d263e97fb6783af556e7 --- /dev/null +++ b/Java/EntityImageNote.java @@ -0,0 +1,372 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek.image; + +import java.awt.geom.Line2D; +import java.awt.geom.Point2D; +import java.util.EnumMap; +import java.util.Map; +import java.util.Objects; + +import net.sourceforge.plantuml.AlignmentParam; +import net.sourceforge.plantuml.ColorParam; +import net.sourceforge.plantuml.CornerParam; +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.Direction; +import net.sourceforge.plantuml.FontParam; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.LineParam; +import net.sourceforge.plantuml.SkinParamBackcolored; +import net.sourceforge.plantuml.SkinParamUtils; +import net.sourceforge.plantuml.UmlDiagramType; +import net.sourceforge.plantuml.Url; +import net.sourceforge.plantuml.UseStyle; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.creole.Stencil; +import net.sourceforge.plantuml.cucadiagram.BodyFactory; +import net.sourceforge.plantuml.cucadiagram.Display; +import net.sourceforge.plantuml.cucadiagram.IEntity; +import net.sourceforge.plantuml.cucadiagram.ILeaf; +import net.sourceforge.plantuml.cucadiagram.Stereotype; +import net.sourceforge.plantuml.graphic.FontConfiguration; +import net.sourceforge.plantuml.graphic.HorizontalAlignment; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.graphic.TextBlockEmpty; +import net.sourceforge.plantuml.graphic.color.ColorType; +import net.sourceforge.plantuml.graphic.color.Colors; +import net.sourceforge.plantuml.posimo.DotPath; +import net.sourceforge.plantuml.skin.rose.Rose; +import net.sourceforge.plantuml.style.PName; +import net.sourceforge.plantuml.style.SName; +import net.sourceforge.plantuml.style.Style; +import net.sourceforge.plantuml.style.StyleSignatureBasic; +import net.sourceforge.plantuml.svek.AbstractEntityImage; +import net.sourceforge.plantuml.svek.ShapeType; +import net.sourceforge.plantuml.svek.SvekLine; +import net.sourceforge.plantuml.svek.SvekNode; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UGraphicStencil; +import net.sourceforge.plantuml.ugraphic.UGroupType; +import net.sourceforge.plantuml.ugraphic.UPath; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class EntityImageNote extends AbstractEntityImage implements Stencil { + + private final HColor noteBackgroundColor; + private final HColor borderColor; + private final double shadowing; + private final int marginX1 = 6; + private final int marginX2 = 15; + private final int marginY = 5; + private final boolean withShadow; + private final ISkinParam skinParam; + private final Style style; + + private final TextBlock textBlock; + + public EntityImageNote(ILeaf entity, ISkinParam skinParam, UmlDiagramType umlDiagramType) { + super(entity, getSkin(getISkinParam(skinParam, entity), entity)); + this.skinParam = getISkinParam(skinParam, entity); + + this.withShadow = getSkinParam().shadowing(getEntity().getStereotype()); + final Display strings = entity.getDisplay(); + + final Rose rose = new Rose(); + + final FontConfiguration fontConfiguration; + final HorizontalAlignment horizontalAlignment; + if (UseStyle.useBetaStyle()) { + this.style = getDefaultStyleDefinition(umlDiagramType.getStyleName()) + .getMergedStyle(skinParam.getCurrentStyleBuilder()); + if (entity.getColors().getColor(ColorType.BACK) == null) + this.noteBackgroundColor = style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(), + skinParam.getIHtmlColorSet()); + else + this.noteBackgroundColor = entity.getColors().getColor(ColorType.BACK); + + this.borderColor = style.value(PName.LineColor).asColor(skinParam.getThemeStyle(), + skinParam.getIHtmlColorSet()); + this.shadowing = style.value(PName.Shadowing).asDouble(); + + fontConfiguration = style.getFontConfiguration(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); + horizontalAlignment = style.getHorizontalAlignment(); + } else { + this.style = null; + this.shadowing = skinParam.shadowing(getEntity().getStereotype()) ? 4 : 0; + if (entity.getColors().getColor(ColorType.BACK) == null) + this.noteBackgroundColor = rose.getHtmlColor(getSkinParam(), ColorParam.noteBackground); + else + this.noteBackgroundColor = entity.getColors().getColor(ColorType.BACK); + + this.borderColor = SkinParamUtils.getColor(getSkinParam(), null, ColorParam.noteBorder); + + fontConfiguration = FontConfiguration.create(getSkinParam(), FontParam.NOTE, null); + horizontalAlignment = skinParam.getHorizontalAlignment(AlignmentParam.noteTextAlignment, null, false, null); + } + + if (strings.size() == 1 && strings.get(0).length() == 0) + textBlock = new TextBlockEmpty(); + else + textBlock = BodyFactory.create3(strings, FontParam.NOTE, getSkinParam(), horizontalAlignment, + fontConfiguration, getSkinParam().wrapWidth(), style); + + } + + private static ISkinParam getISkinParam(ISkinParam skinParam, IEntity entity) { + if (entity.getColors() != null) + return entity.getColors().mute(skinParam); + + return skinParam; + } + + static ISkinParam getSkin(ISkinParam skinParam, IEntity entity) { + final Stereotype stereotype = entity.getStereotype(); + HColor back = entity.getColors().getColor(ColorType.BACK); + if (back != null) + return new SkinParamBackcolored(skinParam, back); + + back = getColorStatic(skinParam, ColorParam.noteBackground, stereotype); + if (back != null) + return new SkinParamBackcolored(skinParam, back); + + return skinParam; + } + + private static HColor getColorStatic(ISkinParam skinParam, ColorParam colorParam, Stereotype stereo) { + final Rose rose = new Rose(); + return rose.getHtmlColor(skinParam, stereo, colorParam); + } + + final public double getPreferredWidth(StringBounder stringBounder) { + final double result = getTextWidth(stringBounder); + return result; + } + + final public double getPreferredHeight(StringBounder stringBounder) { + return getTextHeight(stringBounder); + } + + private Dimension2D getSize(StringBounder stringBounder, final TextBlock textBlock) { + return textBlock.calculateDimension(stringBounder); + } + + final protected double getTextHeight(StringBounder stringBounder) { + final TextBlock textBlock = getTextBlock(); + final Dimension2D size = getSize(stringBounder, textBlock); + return size.getHeight() + 2 * marginY; + } + + final protected TextBlock getTextBlock() { + return textBlock; + } + + final protected double getPureTextWidth(StringBounder stringBounder) { + final TextBlock textBlock = getTextBlock(); + final Dimension2D size = getSize(stringBounder, textBlock); + return size.getWidth(); + } + + final public double getTextWidth(StringBounder stringBounder) { + return getPureTextWidth(stringBounder) + marginX1 + marginX2; + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + final double height = getPreferredHeight(stringBounder); + final double width = getPreferredWidth(stringBounder); + return new Dimension2DDouble(width, height); + } + + private StyleSignatureBasic getDefaultStyleDefinition(SName sname) { + return StyleSignatureBasic.of(SName.root, SName.element, sname, SName.note); + } + + final public void drawU(UGraphic ug) { + final Url url = getEntity().getUrl99(); + + final Map typeIDent = new EnumMap<>(UGroupType.class); + typeIDent.put(UGroupType.CLASS, "elem " + getEntity().getCode() + " selected"); + typeIDent.put(UGroupType.ID, "elem_" + getEntity().getCode()); + ug.startGroup(typeIDent); + + if (url != null) + ug.startUrl(url); + + final UGraphic ug2 = UGraphicStencil.create(ug, this, new UStroke()); + if (opaleLine == null || opaleLine.isOpale() == false) { + drawNormal(ug2); + } else { + final StringBounder stringBounder = ug.getStringBounder(); + DotPath path = opaleLine.getDotPath(); + path.moveSvek(-node.getMinX(), -node.getMinY()); + Point2D p1 = path.getStartPoint(); + Point2D p2 = path.getEndPoint(); + final double textWidth = getTextWidth(stringBounder); + final double textHeight = getTextHeight(stringBounder); + final Point2D center = new Point2D.Double(textWidth / 2, textHeight / 2); + if (p1.distance(center) > p2.distance(center)) { + path = path.reverse(); + p1 = path.getStartPoint(); + // p2 = path.getEndPoint(); + } + final Direction strategy = getOpaleStrategy(textWidth, textHeight, p1); + final Point2D pp1 = path.getStartPoint(); + final Point2D pp2 = path.getEndPoint(); + final Point2D newRefpp2 = move(pp2, node.getMinX(), node.getMinY()); + final Point2D projection = move(other.projection(newRefpp2, stringBounder), -node.getMinX(), + -node.getMinY()); + final Opale opale = new Opale(shadowing, borderColor, noteBackgroundColor, textBlock, true, getStroke()); + opale.setRoundCorner(getRoundCorner()); + opale.setOpale(strategy, pp1, projection); + final UGraphic stroked = applyStroke(ug2); + opale.drawU(Colors.applyStroke(stroked, getEntity().getColors())); + } + if (url != null) + ug.closeUrl(); + + ug.closeGroup(); + } + + private double getRoundCorner() { + return skinParam.getRoundCorner(CornerParam.DEFAULT, null); + } + + private static Point2D move(Point2D pt, double dx, double dy) { + return new Point2D.Double(pt.getX() + dx, pt.getY() + dy); + } + + private void drawNormal(UGraphic ug) { + final StringBounder stringBounder = ug.getStringBounder(); + final UPath polygon = Opale.getPolygonNormal(getTextWidth(stringBounder), getTextHeight(stringBounder), + getRoundCorner()); + + double shadow = 0; + if (UseStyle.useBetaStyle()) + shadow = this.shadowing; + else if (withShadow) + shadow = 4; + polygon.setDeltaShadow(shadow); + + ug = ug.apply(noteBackgroundColor.bg()).apply(borderColor); + final UGraphic stroked = applyStroke(ug); + stroked.draw(polygon); + ug.draw(Opale.getCorner(getTextWidth(stringBounder), getRoundCorner())); + + getTextBlock().drawU(ug.apply(new UTranslate(marginX1, marginY))); + } + + private UGraphic applyStroke(UGraphic ug) { + if (UseStyle.useBetaStyle()) + return ug.apply(style.getStroke()); + + final UStroke stroke = skinParam.getThickness(LineParam.noteBorder, null); + if (stroke == null) + return ug; + + return ug.apply(stroke); + } + + private UStroke getStroke() { + if (UseStyle.useBetaStyle()) + return style.getStroke(); + + return skinParam.getThickness(LineParam.noteBorder, null); + } + + private Direction getOpaleStrategy(double width, double height, Point2D pt) { + final double d1 = getOrthoDistance(new Line2D.Double(width, 0, width, height), pt); + final double d2 = getOrthoDistance(new Line2D.Double(0, height, width, height), pt); + final double d3 = getOrthoDistance(new Line2D.Double(0, 0, 0, height), pt); + final double d4 = getOrthoDistance(new Line2D.Double(0, 0, width, 0), pt); + if (d3 <= d1 && d3 <= d2 && d3 <= d4) + return Direction.LEFT; + + if (d1 <= d2 && d1 <= d3 && d1 <= d4) + return Direction.RIGHT; + + if (d4 <= d1 && d4 <= d2 && d4 <= d3) + return Direction.UP; + + if (d2 <= d1 && d2 <= d3 && d2 <= d4) + return Direction.DOWN; + + return null; + + } + + private static double getOrthoDistance(Line2D.Double seg, Point2D pt) { + if (isHorizontal(seg)) + return Math.abs(seg.getP1().getY() - pt.getY()); + + if (isVertical(seg)) + return Math.abs(seg.getP1().getX() - pt.getX()); + + throw new IllegalArgumentException(); + } + + private static boolean isHorizontal(Line2D.Double seg) { + return seg.getP1().getY() == seg.getP2().getY(); + } + + private static boolean isVertical(Line2D.Double seg) { + return seg.getP1().getX() == seg.getP2().getX(); + } + + public ShapeType getShapeType() { + return ShapeType.RECTANGLE; + } + + private SvekLine opaleLine; + private SvekNode node; + private SvekNode other; + + public void setOpaleLine(SvekLine line, SvekNode node, SvekNode other) { + this.opaleLine = line; + this.node = node; + this.other = Objects.requireNonNull(other); + } + + public double getStartingX(StringBounder stringBounder, double y) { + return 0; + } + + public double getEndingX(StringBounder stringBounder, double y) { + return calculateDimension(stringBounder).getWidth(); + } + +} diff --git a/Java/EntityImagePort.java b/Java/EntityImagePort.java new file mode 100644 index 0000000000000000000000000000000000000000..fdc9da721ec27d52b6c17c1e194e096ef64a3810 --- /dev/null +++ b/Java/EntityImagePort.java @@ -0,0 +1,142 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Creator: Hisashi Miyashita + * + * + */ + +package net.sourceforge.plantuml.svek.image; + +import java.awt.geom.Point2D; + +import net.sourceforge.plantuml.ColorParam; +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.FontParam; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.SkinParamUtils; +import net.sourceforge.plantuml.UseStyle; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.cucadiagram.EntityPosition; +import net.sourceforge.plantuml.cucadiagram.ILeaf; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.color.ColorType; +import net.sourceforge.plantuml.style.PName; +import net.sourceforge.plantuml.style.SName; +import net.sourceforge.plantuml.style.Style; +import net.sourceforge.plantuml.style.StyleSignatureBasic; +import net.sourceforge.plantuml.svek.Bibliotekon; +import net.sourceforge.plantuml.svek.Cluster; +import net.sourceforge.plantuml.svek.ShapeType; +import net.sourceforge.plantuml.svek.SvekNode; +import net.sourceforge.plantuml.ugraphic.Shadowable; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.URectangle; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class EntityImagePort extends AbstractEntityImageBorder { + + private final SName sname; + + public EntityImagePort(ILeaf leaf, ISkinParam skinParam, Cluster parent, Bibliotekon bibliotekon, SName sname) { + super(leaf, skinParam, parent, bibliotekon, FontParam.BOUNDARY); + this.sname = sname; + } + + private StyleSignatureBasic getSignature() { + return StyleSignatureBasic.of(SName.root, SName.element, sname, SName.boundary); + } + + private boolean upPosition() { + final Point2D clusterCenter = parent.getClusterPosition().getPointCenter(); + final SvekNode node = bibliotekon.getNode(getEntity()); + return node.getMinY() < clusterCenter.getY(); + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + double sp = EntityPosition.RADIUS * 2; + return new Dimension2DDouble(sp, sp); + } + + public double getMaxWidthFromLabelForEntryExit(StringBounder stringBounder) { + final Dimension2D dimDesc = desc.calculateDimension(stringBounder); + return dimDesc.getWidth(); + } + + private void drawSymbol(UGraphic ug) { + final Shadowable rect = new URectangle(EntityPosition.RADIUS * 2, EntityPosition.RADIUS * 2); + ug.draw(rect); + } + + final public void drawU(UGraphic ug) { + double y = 0; + final Dimension2D dimDesc = desc.calculateDimension(ug.getStringBounder()); + final double x = 0 - (dimDesc.getWidth() - 2 * EntityPosition.RADIUS) / 2; + + if (upPosition()) + y -= 2 * EntityPosition.RADIUS + dimDesc.getHeight(); + else + y += 2 * EntityPosition.RADIUS; + + desc.drawU(ug.apply(new UTranslate(x, y))); + + HColor backcolor = getEntity().getColors().getColor(ColorType.BACK); + final HColor borderColor; + + if (UseStyle.useBetaStyle()) { + final Style style = getSignature().getMergedStyle(getSkinParam().getCurrentStyleBuilder()); + borderColor = style.value(PName.LineColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + if (backcolor == null) + backcolor = style.value(PName.BackGroundColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + } else { + borderColor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.stateBorder); + if (backcolor == null) + backcolor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.stateBackground); + } + + ug = ug.apply(backcolor); + ug = ug.apply(getUStroke()).apply(borderColor.bg()); + + drawSymbol(ug); + } + + private UStroke getUStroke() { + return new UStroke(1.5); + } + + public ShapeType getShapeType() { + return ShapeType.RECTANGLE; + } +} diff --git a/Java/EntityImageProtected.java b/Java/EntityImageProtected.java new file mode 100644 index 0000000000000000000000000000000000000000..9758e08e5362eb1f94a77013ca707d6364af9b44 --- /dev/null +++ b/Java/EntityImageProtected.java @@ -0,0 +1,108 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek; + +import java.awt.geom.Rectangle2D; + +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.cucadiagram.dot.Neighborhood; +import net.sourceforge.plantuml.graphic.AbstractTextBlock; +import net.sourceforge.plantuml.graphic.InnerStrategy; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class EntityImageProtected extends AbstractTextBlock implements IEntityImage, Untranslated, WithPorts { + + private final IEntityImage orig; + private final double border; + private final Bibliotekon bibliotekon; + private final Neighborhood neighborhood; + + public Rectangle2D getInnerPosition(String member, StringBounder stringBounder, InnerStrategy strategy) { + final Rectangle2D result = orig.getInnerPosition(member, stringBounder, strategy); + return new Rectangle2D.Double(result.getMinX() + border, result.getMinY() + border, result.getWidth(), + result.getHeight()); + } + + public EntityImageProtected(IEntityImage orig, double border, Neighborhood neighborhood, Bibliotekon bibliotekon) { + this.orig = orig; + this.border = border; + this.bibliotekon = bibliotekon; + this.neighborhood = neighborhood; + } + + public boolean isHidden() { + return orig.isHidden(); + } + + public HColor getBackcolor() { + return orig.getBackcolor(); + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + return Dimension2DDouble.delta(orig.calculateDimension(stringBounder), 2 * border); + } + + public void drawU(UGraphic ug) { + orig.drawU(ug.apply(new UTranslate(border, border))); + } + + public void drawUntranslated(UGraphic ug, double minX, double minY) { + final Dimension2D dim = orig.calculateDimension(ug.getStringBounder()); + neighborhood.drawU(ug, minX + border, minY + border, bibliotekon, dim); + } + + public ShapeType getShapeType() { + return orig.getShapeType(); + } + + public Margins getShield(StringBounder stringBounder) { + return orig.getShield(stringBounder); + } + + public double getOverscanX(StringBounder stringBounder) { + return orig.getOverscanX(stringBounder); + } + + @Override + public Ports getPorts(StringBounder stringBounder) { + return ((WithPorts) orig).getPorts(stringBounder); + } + +} \ No newline at end of file diff --git a/Java/EntityImageState.java b/Java/EntityImageState.java new file mode 100644 index 0000000000000000000000000000000000000000..0aae24d20b5612c0b3c1cca915ef898ead3e841a --- /dev/null +++ b/Java/EntityImageState.java @@ -0,0 +1,156 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek.image; + +import java.util.Collections; + +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.FontParam; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.UseStyle; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.creole.CreoleMode; +import net.sourceforge.plantuml.cucadiagram.Display; +import net.sourceforge.plantuml.cucadiagram.IEntity; +import net.sourceforge.plantuml.cucadiagram.Stereotype; +import net.sourceforge.plantuml.graphic.FontConfiguration; +import net.sourceforge.plantuml.graphic.HorizontalAlignment; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.ugraphic.UEllipse; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UGroupType; +import net.sourceforge.plantuml.ugraphic.ULine; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UTranslate; + +public class EntityImageState extends EntityImageStateCommon { + + final private TextBlock fields; + + final private static int MIN_WIDTH = 50; + final private static int MIN_HEIGHT = 50; + + final private boolean withSymbol; + + final static private double smallRadius = 3; + final static private double smallLine = 3; + final static private double smallMarginX = 7; + final static private double smallMarginY = 4; + + public EntityImageState(IEntity entity, ISkinParam skinParam) { + super(entity, skinParam); + + final Stereotype stereotype = entity.getStereotype(); + + this.withSymbol = stereotype != null && stereotype.isWithOOSymbol(); + final Display list = Display.create(entity.getBodier().getRawBody()); + final FontConfiguration fontConfiguration; + + if (UseStyle.useBetaStyle()) + fontConfiguration = getStyleState().getFontConfiguration(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + else + fontConfiguration = FontConfiguration.create(getSkinParam(), FontParam.STATE_ATTRIBUTE, stereotype); + + this.fields = list.create8(fontConfiguration, HorizontalAlignment.LEFT, skinParam, CreoleMode.FULL, + skinParam.wrapWidth()); + + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + final Dimension2D dim = Dimension2DDouble.mergeTB(desc.calculateDimension(stringBounder), + fields.calculateDimension(stringBounder)); + double heightSymbol = 0; + if (withSymbol) + heightSymbol += 2 * smallRadius + smallMarginY; + + final Dimension2D result = Dimension2DDouble.delta(dim, MARGIN * 2 + 2 * MARGIN_LINE + heightSymbol); + return Dimension2DDouble.atLeast(result, MIN_WIDTH, MIN_HEIGHT); + } + + final public void drawU(UGraphic ug) { + ug.startGroup(Collections.singletonMap(UGroupType.ID, getEntity().getIdent().toString("."))); + if (url != null) + ug.startUrl(url); + + final StringBounder stringBounder = ug.getStringBounder(); + final Dimension2D dimTotal = calculateDimension(stringBounder); + final Dimension2D dimDesc = desc.calculateDimension(stringBounder); + + final UStroke stroke; + if (UseStyle.useBetaStyle()) + stroke = getStyleState().getStroke(); + else + stroke = new UStroke(); + + ug = applyColorAndStroke(ug); + ug = ug.apply(stroke); + ug.draw(getShape(dimTotal)); + + final double yLine = MARGIN + dimDesc.getHeight() + MARGIN_LINE; + ug.apply(UTranslate.dy(yLine)).draw(ULine.hline(dimTotal.getWidth())); + + if (withSymbol) { + final double xSymbol = dimTotal.getWidth(); + final double ySymbol = dimTotal.getHeight(); + drawSymbol(ug, xSymbol, ySymbol); + } + + final double xDesc = (dimTotal.getWidth() - dimDesc.getWidth()) / 2; + final double yDesc = MARGIN; + desc.drawU(ug.apply(new UTranslate(xDesc, yDesc))); + + final double xFields = MARGIN; + final double yFields = yLine + MARGIN_LINE; + fields.drawU(ug.apply(new UTranslate(xFields, yFields))); + + if (url != null) + ug.closeUrl(); + + ug.closeGroup(); + } + + public static void drawSymbol(UGraphic ug, double xSymbol, double ySymbol) { + xSymbol -= 4 * smallRadius + smallLine + smallMarginX; + ySymbol -= 2 * smallRadius + smallMarginY; + final UEllipse small = new UEllipse(2 * smallRadius, 2 * smallRadius); + ug.apply(new UTranslate(xSymbol, ySymbol)).draw(small); + ug.apply(new UTranslate(xSymbol + smallLine + 2 * smallRadius, ySymbol)).draw(small); + ug.apply(new UTranslate(xSymbol + 2 * smallRadius, ySymbol + smallLine)).draw(ULine.hline(smallLine)); + } + +} diff --git a/Java/EntityImageStateBorder.java b/Java/EntityImageStateBorder.java new file mode 100644 index 0000000000000000000000000000000000000000..e8d91ffcbbb831615840f8da81bb97202226fd5b --- /dev/null +++ b/Java/EntityImageStateBorder.java @@ -0,0 +1,121 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * Contribution : Hisashi Miyashita + * + */ +package net.sourceforge.plantuml.svek.image; + +import java.awt.geom.Point2D; + +import net.sourceforge.plantuml.ColorParam; +import net.sourceforge.plantuml.FontParam; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.SkinParamUtils; +import net.sourceforge.plantuml.UseStyle; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.cucadiagram.EntityPosition; +import net.sourceforge.plantuml.cucadiagram.ILeaf; +import net.sourceforge.plantuml.graphic.color.ColorType; +import net.sourceforge.plantuml.style.PName; +import net.sourceforge.plantuml.style.SName; +import net.sourceforge.plantuml.style.Style; +import net.sourceforge.plantuml.style.StyleSignatureBasic; +import net.sourceforge.plantuml.svek.Bibliotekon; +import net.sourceforge.plantuml.svek.Cluster; +import net.sourceforge.plantuml.svek.SvekNode; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class EntityImageStateBorder extends AbstractEntityImageBorder { + + private final SName sname; + + public EntityImageStateBorder(ILeaf leaf, ISkinParam skinParam, Cluster stateParent, final Bibliotekon bibliotekon, + SName sname) { + super(leaf, skinParam, stateParent, bibliotekon, FontParam.STATE); + this.sname = sname; + } + + private StyleSignatureBasic getSignature() { + return StyleSignatureBasic.of(SName.root, SName.element, sname); + } + + private boolean upPosition() { + if (parent == null) + return false; + + final Point2D clusterCenter = parent.getClusterPosition().getPointCenter(); + final SvekNode node = bibliotekon.getNode(getEntity()); + return node.getMinY() < clusterCenter.getY(); + } + + final public void drawU(UGraphic ug) { + double y = 0; + final Dimension2D dimDesc = desc.calculateDimension(ug.getStringBounder()); + final double x = 0 - (dimDesc.getWidth() - 2 * EntityPosition.RADIUS) / 2; + if (upPosition()) + y -= 2 * EntityPosition.RADIUS + dimDesc.getHeight(); + else + y += 2 * EntityPosition.RADIUS; + + desc.drawU(ug.apply(new UTranslate(x, y))); + + HColor backcolor = getEntity().getColors().getColor(ColorType.BACK); + final HColor borderColor; + + if (UseStyle.useBetaStyle()) { + final Style style = getSignature().getMergedStyle(getSkinParam().getCurrentStyleBuilder()); + borderColor = style.value(PName.LineColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + if (backcolor == null) + backcolor = style.value(PName.BackGroundColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + } else { + borderColor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.stateBorder); + if (backcolor == null) + backcolor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.stateBackground); + } + + ug = ug.apply(getUStroke()).apply(borderColor); + ug = ug.apply(backcolor.bg()); + + entityPosition.drawSymbol(ug, rankdir); + } + + private UStroke getUStroke() { + return new UStroke(1.5); + } + +} diff --git a/Java/EntityImageTips.java b/Java/EntityImageTips.java new file mode 100644 index 0000000000000000000000000000000000000000..194efb4f241478bd574b25eb45f507a6dfd8c969 --- /dev/null +++ b/Java/EntityImageTips.java @@ -0,0 +1,212 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek.image; + +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; +import java.util.Map; + +import net.sourceforge.plantuml.ColorParam; +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.Direction; +import net.sourceforge.plantuml.FontParam; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.LineBreakStrategy; +import net.sourceforge.plantuml.UmlDiagramType; +import net.sourceforge.plantuml.UseStyle; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.command.Position; +import net.sourceforge.plantuml.cucadiagram.BodyFactory; +import net.sourceforge.plantuml.cucadiagram.Display; +import net.sourceforge.plantuml.cucadiagram.IEntity; +import net.sourceforge.plantuml.cucadiagram.ILeaf; +import net.sourceforge.plantuml.graphic.FontConfiguration; +import net.sourceforge.plantuml.graphic.HorizontalAlignment; +import net.sourceforge.plantuml.graphic.InnerStrategy; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.graphic.color.ColorType; +import net.sourceforge.plantuml.skin.rose.Rose; +import net.sourceforge.plantuml.style.PName; +import net.sourceforge.plantuml.style.SName; +import net.sourceforge.plantuml.style.Style; +import net.sourceforge.plantuml.style.StyleSignatureBasic; +import net.sourceforge.plantuml.svek.AbstractEntityImage; +import net.sourceforge.plantuml.svek.Bibliotekon; +import net.sourceforge.plantuml.svek.ShapeType; +import net.sourceforge.plantuml.svek.SvekNode; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class EntityImageTips extends AbstractEntityImage { + + final private Rose rose = new Rose(); + private final ISkinParam skinParam; + + private final HColor noteBackgroundColor; + private final HColor borderColor; + + private final Bibliotekon bibliotekon; + private final Style style; + + private final double ySpacing = 10; + + public EntityImageTips(ILeaf entity, ISkinParam skinParam, Bibliotekon bibliotekon, UmlDiagramType type) { + super(entity, EntityImageNote.getSkin(skinParam, entity)); + this.skinParam = skinParam; + this.bibliotekon = bibliotekon; + + if (UseStyle.useBetaStyle()) { + style = getDefaultStyleDefinition(type.getStyleName()).getMergedStyle(skinParam.getCurrentStyleBuilder()); + + if (entity.getColors().getColor(ColorType.BACK) == null) + this.noteBackgroundColor = style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(), + skinParam.getIHtmlColorSet()); + else + this.noteBackgroundColor = entity.getColors().getColor(ColorType.BACK); + + this.borderColor = style.value(PName.LineColor).asColor(skinParam.getThemeStyle(), + skinParam.getIHtmlColorSet()); + + } else { + style = null; + + if (entity.getColors().getColor(ColorType.BACK) == null) + this.noteBackgroundColor = rose.getHtmlColor(skinParam, ColorParam.noteBackground); + else + this.noteBackgroundColor = entity.getColors().getColor(ColorType.BACK); + + this.borderColor = rose.getHtmlColor(skinParam, ColorParam.noteBorder); + + } + } + + private StyleSignatureBasic getDefaultStyleDefinition(SName sname) { + return StyleSignatureBasic.of(SName.root, SName.element, sname, SName.note); + } + + private Position getPosition() { + if (getEntity().getCodeGetName().endsWith(Position.RIGHT.name())) + return Position.RIGHT; + + return Position.LEFT; + } + + public ShapeType getShapeType() { + return ShapeType.RECTANGLE; + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + double width = 0; + double height = 0; + for (Map.Entry ent : getEntity().getTips().entrySet()) { + final Display display = ent.getValue(); + final Dimension2D dim = getOpale(display).calculateDimension(stringBounder); + height += dim.getHeight(); + height += ySpacing; + width = Math.max(width, dim.getWidth()); + } + return new Dimension2DDouble(width, height); + } + + public void drawU(UGraphic ug) { + final StringBounder stringBounder = ug.getStringBounder(); + + final IEntity other = bibliotekon.getOnlyOther(getEntity()); + + final SvekNode nodeMe = bibliotekon.getNode(getEntity()); + final SvekNode nodeOther = bibliotekon.getNode(other); + final Point2D positionMe = nodeMe.getPosition(); + if (nodeOther == null) { + System.err.println("Error in EntityImageTips"); + return; + } + final Point2D positionOther = nodeOther.getPosition(); + bibliotekon.getNode(getEntity()); + final Position position = getPosition(); + Direction direction = position.reverseDirection(); + double height = 0; + for (Map.Entry ent : getEntity().getTips().entrySet()) { + final Display display = ent.getValue(); + final Rectangle2D memberPosition = nodeOther.getImage().getInnerPosition(ent.getKey(), stringBounder, + InnerStrategy.STRICT); + if (memberPosition == null) + return; + + final Opale opale = getOpale(display); + final Dimension2D dim = opale.calculateDimension(stringBounder); + final Point2D pp1 = new Point2D.Double(0, dim.getHeight() / 2); + double x = positionOther.getX() - positionMe.getX(); + if (direction == Direction.RIGHT && x < 0) + direction = direction.getInv(); + + if (direction == Direction.LEFT) + x += memberPosition.getMaxX(); + else + x += 4; + + final double y = positionOther.getY() - positionMe.getY() - height + memberPosition.getCenterY(); + final Point2D pp2 = new Point2D.Double(x, y); + opale.setOpale(direction, pp1, pp2); + opale.drawU(ug); + ug = ug.apply(UTranslate.dy(dim.getHeight() + ySpacing)); + height += dim.getHeight(); + height += ySpacing; + } + + } + + private Opale getOpale(final Display display) { + final FontConfiguration fc; + final double shadowing; + UStroke stroke = new UStroke(); + if (UseStyle.useBetaStyle()) { + shadowing = style.value(PName.Shadowing).asDouble(); + fc = style.getFontConfiguration(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); + stroke = style.getStroke(); + } else { + shadowing = skinParam.shadowing(getEntity().getStereotype()) ? 4 : 0; + fc = FontConfiguration.create(skinParam, FontParam.NOTE, null); + } + + final TextBlock textBlock = BodyFactory.create3(display, FontParam.NOTE, skinParam, HorizontalAlignment.LEFT, + fc, LineBreakStrategy.NONE, style); + return new Opale(shadowing, borderColor, noteBackgroundColor, textBlock, true, stroke); + } + +} diff --git a/Java/EntityImageUseCase.java b/Java/EntityImageUseCase.java new file mode 100644 index 0000000000000000000000000000000000000000..0e42b3cb8a1d55ba0da207272d5cf2070df8e080 --- /dev/null +++ b/Java/EntityImageUseCase.java @@ -0,0 +1,310 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek.image; + +import java.awt.geom.Point2D; +import java.util.EnumMap; +import java.util.Map; + +import net.sourceforge.plantuml.ColorParam; +import net.sourceforge.plantuml.FontParam; +import net.sourceforge.plantuml.Guillemet; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.LineParam; +import net.sourceforge.plantuml.SkinParamUtils; +import net.sourceforge.plantuml.Url; +import net.sourceforge.plantuml.UseStyle; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.creole.Stencil; +import net.sourceforge.plantuml.cucadiagram.BodyFactory; +import net.sourceforge.plantuml.cucadiagram.Display; +import net.sourceforge.plantuml.cucadiagram.EntityPortion; +import net.sourceforge.plantuml.cucadiagram.ILeaf; +import net.sourceforge.plantuml.cucadiagram.LeafType; +import net.sourceforge.plantuml.cucadiagram.PortionShower; +import net.sourceforge.plantuml.cucadiagram.Stereotype; +import net.sourceforge.plantuml.graphic.FontConfiguration; +import net.sourceforge.plantuml.graphic.HorizontalAlignment; +import net.sourceforge.plantuml.graphic.SkinParameter; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.graphic.TextBlockUtils; +import net.sourceforge.plantuml.graphic.color.ColorType; +import net.sourceforge.plantuml.graphic.color.Colors; +import net.sourceforge.plantuml.style.PName; +import net.sourceforge.plantuml.style.SName; +import net.sourceforge.plantuml.style.Style; +import net.sourceforge.plantuml.style.StyleSignature; +import net.sourceforge.plantuml.style.StyleSignatureBasic; +import net.sourceforge.plantuml.svek.AbstractEntityImage; +import net.sourceforge.plantuml.svek.ShapeType; +import net.sourceforge.plantuml.ugraphic.AbstractUGraphicHorizontalLine; +import net.sourceforge.plantuml.ugraphic.TextBlockInEllipse; +import net.sourceforge.plantuml.ugraphic.UEllipse; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UGroupType; +import net.sourceforge.plantuml.ugraphic.UHorizontalLine; +import net.sourceforge.plantuml.ugraphic.ULine; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class EntityImageUseCase extends AbstractEntityImage { + + final private TextBlock desc; + + final private Url url; + + public EntityImageUseCase(ILeaf entity, ISkinParam skinParam2, PortionShower portionShower) { + super(entity, entity.getColors().mute(skinParam2)); + final Stereotype stereotype = entity.getStereotype(); + + final HorizontalAlignment align; + if (UseStyle.useBetaStyle()) { + final Style style = getStyle(); + align = style.getHorizontalAlignment(); + } else { + align = HorizontalAlignment.CENTER; + } + final TextBlock tmp = BodyFactory.create2(getSkinParam().getDefaultTextAlignment(align), entity.getDisplay(), + FontParam.USECASE, getSkinParam(), stereotype, entity, getStyle()); + + if (stereotype == null || stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR) == null + || portionShower.showPortion(EntityPortion.STEREOTYPE, entity) == false) { + this.desc = tmp; + } else { + final TextBlock stereo; + if (stereotype.getSprite(getSkinParam()) != null) { + stereo = stereotype.getSprite(getSkinParam()); + } else { + stereo = Display.getWithNewlines(stereotype.getLabel(getSkinParam().guillemet())).create( + FontConfiguration.create(getSkinParam(), FontParam.USECASE_STEREOTYPE, stereotype), + HorizontalAlignment.CENTER, getSkinParam()); + } + this.desc = TextBlockUtils.mergeTB(stereo, tmp, HorizontalAlignment.CENTER); + } + this.url = entity.getUrl99(); + + } + + private UStroke getStroke() { + if (UseStyle.useBetaStyle()) { + final Style style = getStyle(); + return style.getStroke(); + } + UStroke stroke = getSkinParam().getThickness(LineParam.usecaseBorder, getStereo()); + if (stroke == null) + stroke = new UStroke(1.5); + + final Colors colors = getEntity().getColors(); + stroke = colors.muteStroke(stroke); + return stroke; + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + return new TextBlockInEllipse(desc, stringBounder).calculateDimension(stringBounder); + } + + final public void drawU(UGraphic ug) { + final StringBounder stringBounder = ug.getStringBounder(); + + double shadow = 0; + + if (UseStyle.useBetaStyle()) { + final Style style = getStyle(); + shadow = style.value(PName.Shadowing).asDouble(); + } else if (getSkinParam().shadowing2(getEntity().getStereotype(), SkinParameter.USECASE)) + shadow = 3; + + final TextBlockInEllipse ellipse = new TextBlockInEllipse(desc, stringBounder); + ellipse.setDeltaShadow(shadow); + + if (url != null) + ug.startUrl(url); + + ug = ug.apply(getStroke()); + final HColor linecolor = getLineColor(); + ug = ug.apply(linecolor); + final HColor backcolor = getBackColor(); + ug = ug.apply(backcolor.bg()); + final UGraphic ug2 = new MyUGraphicEllipse(ug, 0, 0, ellipse.getUEllipse()); + + final Map typeIDent = new EnumMap<>(UGroupType.class); + typeIDent.put(UGroupType.CLASS, "elem " + getEntity().getCode() + " selected"); + typeIDent.put(UGroupType.ID, "elem_" + getEntity().getCode()); + ug.startGroup(typeIDent); + ellipse.drawU(ug2); + ug2.closeGroup(); + + if (getEntity().getLeafType() == LeafType.USECASE_BUSINESS) + specialBusiness(ug, ellipse.getUEllipse()); + + if (url != null) + ug.closeUrl(); + + } + + private void specialBusiness(UGraphic ug, UEllipse frontier) { + final RotatedEllipse rotatedEllipse = new RotatedEllipse(frontier, Math.PI / 4); + + final double theta1 = 20.0 * Math.PI / 180; + final double theta2 = rotatedEllipse.getOtherTheta(theta1); + + final UEllipse frontier2 = frontier.scale(0.99); + final Point2D p1 = frontier2.getPointAtAngle(-theta1); + final Point2D p2 = frontier2.getPointAtAngle(-theta2); + drawLine(ug, p1, p2); + } + + private void specialBusiness0(UGraphic ug, UEllipse frontier) { + final double c = frontier.getWidth() / frontier.getHeight(); + final double ouverture = Math.PI / 2; + final Point2D p1 = frontier.getPointAtAngle(getTrueAngle(c, Math.PI / 4 - ouverture)); + final Point2D p2 = frontier.getPointAtAngle(getTrueAngle(c, Math.PI / 4 + ouverture)); + drawLine(ug, p1, p2); + } + + private void drawLine(UGraphic ug, final Point2D p1, final Point2D p2) { + ug = ug.apply(new UTranslate(p1)); + ug.draw(new ULine(p2.getX() - p1.getX(), p2.getY() - p1.getY())); + } + + private double getTrueAngle(final double c, final double gamma) { + return Math.atan2(Math.sin(gamma), Math.cos(gamma) / c); + } + + private HColor getBackColor() { + HColor backcolor = getEntity().getColors().getColor(ColorType.BACK); + if (backcolor == null) { + if (UseStyle.useBetaStyle()) { + Style style = getStyle(); + final Colors colors = getEntity().getColors(); + style = style.eventuallyOverride(colors); + backcolor = style.value(PName.BackGroundColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + } else { + backcolor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.usecaseBackground); + } + } + return backcolor; + } + + private Style getStyle() { + return getDefaultStyleDefinition().getMergedStyle(getSkinParam().getCurrentStyleBuilder()); + } + + private StyleSignature getDefaultStyleDefinition() { + return StyleSignatureBasic.of(SName.root, SName.element, SName.componentDiagram, SName.usecase).withTOBECHANGED(getStereo()); + } + + private HColor getLineColor() { + HColor linecolor = getEntity().getColors().getColor(ColorType.LINE); + if (linecolor == null) { + if (UseStyle.useBetaStyle()) { + final Style style = getStyle(); + linecolor = style.value(PName.LineColor).asColor(getSkinParam().getThemeStyle(), + getSkinParam().getIHtmlColorSet()); + } else { + linecolor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.usecaseBorder); + } + } + return linecolor; + } + + public ShapeType getShapeType() { + return ShapeType.OVAL; + } + + static class MyUGraphicEllipse extends AbstractUGraphicHorizontalLine { + + private final double startingX; + private final double yTheoricalPosition; + private final UEllipse ellipse; + + @Override + protected AbstractUGraphicHorizontalLine copy(UGraphic ug) { + return new MyUGraphicEllipse(ug, startingX, yTheoricalPosition, ellipse); + } + + MyUGraphicEllipse(UGraphic ug, double startingX, double yTheoricalPosition, UEllipse ellipse) { + super(ug); + this.startingX = startingX; + this.ellipse = ellipse; + this.yTheoricalPosition = yTheoricalPosition; + } + + private double getNormalized(double y) { + if (y < yTheoricalPosition) + throw new IllegalArgumentException(); + + y = y - yTheoricalPosition; + if (y > ellipse.getHeight()) + throw new IllegalArgumentException(); + + return y; + } + + private double getStartingXInternal(double y) { + return startingX + ellipse.getStartingX(getNormalized(y)); + } + + private double getEndingXInternal(double y) { + return startingX + ellipse.getEndingX(getNormalized(y)); + } + + private Stencil getStencil2(UTranslate translate) { + final double dy = translate.getDy(); + return new Stencil() { + + public double getStartingX(StringBounder stringBounder, double y) { + return getStartingXInternal(y + dy); + } + + public double getEndingX(StringBounder stringBounder, double y) { + return getEndingXInternal(y + dy); + } + }; + } + + @Override + protected void drawHline(UGraphic ug, UHorizontalLine line, UTranslate translate) { + final UStroke stroke = new UStroke(1.5); + line.drawLineInternal(ug.apply(translate), getStencil2(translate), 0, stroke); + } + + } + +} diff --git a/Java/ErrorServlet.java b/Java/ErrorServlet.java new file mode 100644 index 0000000000000000000000000000000000000000..70219f7b228c6cb61517da69205ba601b79ac60a --- /dev/null +++ b/Java/ErrorServlet.java @@ -0,0 +1,56 @@ +/* + * Copyright 2003-2006 Rick Knowles + * Distributed under the terms of either: + * - the common development and distribution license (CDDL), v1.0; or + * - the GNU Lesser General Public License, v2.1 or later + */ +package winstone; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.Writer; +import java.util.Date; + +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServlet; + +/** + * A simple servlet that writes out the body of the error + * + * @author Rick Knowles + * @version $Id: ErrorServlet.java,v 1.3 2006/02/28 07:32:47 rickknowles Exp $ + */ +public class ErrorServlet extends HttpServlet { + + public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { + + Integer sc = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); + String msg = (String) request.getAttribute(RequestDispatcher.ERROR_MESSAGE); + Throwable err = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); + + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + if (err != null) { + err.printStackTrace(pw); + } else { + pw.println("(none)"); + } + pw.flush(); + + // If we are here there was no error servlet, so show the default error page + String output = Launcher.RESOURCES.getString("WinstoneResponse.ErrorPage", + // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') + // new String[] { sc + "", (msg == null ? "" : msg), sw.toString(), + // FIXED: + new String[] { sc + "", URIUtil.htmlEscape(msg == null ? "" : msg), URIUtil.htmlEscape(sw.toString()), + Launcher.RESOURCES.getString("ServerVersion"), + "" + new Date() }); + response.setContentLength(output.getBytes(response.getCharacterEncoding()).length); + Writer out = response.getWriter(); + out.write(output); + out.flush(); + } +} diff --git a/Java/FactoryRegistryTest.java b/Java/FactoryRegistryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..2aa23f629a7994ba4f07493222e4c99f38611a09 --- /dev/null +++ b/Java/FactoryRegistryTest.java @@ -0,0 +1,354 @@ +/* + * GeoTools - The Open Source Java GIS Toolkit + * http://geotools.org + * + * (C) 2005-2008, Open Source Geospatial Foundation (OSGeo) + * + * 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; + * version 2.1 of the License. + * + * 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. + */ +package org.geotools.util.factory; + +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toSet; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Stream; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Tests {@link org.geotools.util.factory.FactoryRegistry} implementation. + * + * @version $Id$ + * @author Martin Desruisseaux + */ +public final class FactoryRegistryTest { + /** + * Ensures that class {@link org.geotools.util.factory.Hints} is loaded before {@link + * DummyFactory}. It is not needed for normal execution, but Maven seems to mess with class + * loaders. + */ + @Before + public void ensureHintsLoaded() { + assertNotNull(Hints.DATUM_FACTORY.toString()); + } + + /** + * Creates the factory registry to test. The tests performed in this method are more J2SE tests + * than Geotools implementation tests. We basically just ensure that we have setup the service + * registry properly. + * + *

Factories are specified in arguments as {@link org.geotools.util.factory.Factory} objects + * in order to avoid the {@link DummyClass} to be initialized before {@link + * org.geotools.util.factory.Hints}. This is not a problem for normal execution, but Maven seems + * to mess with class loaders. + * + * @param creator {@code true} if the registry should be an instance of {@link + * org.geotools.util.factory.FactoryCreator}. + */ + @SuppressWarnings("PMD.UnusedPrivateMethod") // PMD getting confused here? + private FactoryRegistry getRegistry( + final boolean creator, + final Factory factory1, + final Factory factory2, + final Factory factory3) { + @SuppressWarnings("unchecked") + final Set> categories = Collections.singleton(DummyFactory.class); + // The above line fails without the cast, I don't know why... + final FactoryRegistry registry; + if (creator) { + registry = new FactoryCreator(categories); + } else { + registry = new FactoryRegistry(categories); + } + registry.registerFactory(factory1); + registry.registerFactory(factory2); + registry.registerFactory(factory3); + assertTrue( + registry.setOrdering( + DummyFactory.class, (DummyFactory) factory1, (DummyFactory) factory2)); + assertTrue( + registry.setOrdering( + DummyFactory.class, (DummyFactory) factory2, (DummyFactory) factory3)); + assertTrue( + registry.setOrdering( + DummyFactory.class, (DummyFactory) factory1, (DummyFactory) factory3)); + + final List factories = + registry.getFactories(DummyFactory.class, null, null).collect(toList()); + assertTrue(factories.contains(factory1)); + assertTrue(factories.contains(factory2)); + assertTrue(factories.contains(factory3)); + assertTrue(factories.indexOf(factory1) < factories.indexOf(factory2)); + assertTrue(factories.indexOf(factory2) < factories.indexOf(factory3)); + return registry; + } + + /** + * Tests the {@link org.geotools.util.factory.FactoryRegistry#getProvider} method. Note that the + * tested method do not create any new factory. If no registered factory matching the hints is + * found, an exception is expected.
+ *
+ * Three factories are initially registered: factory #1, #2 and #3. + * + *

Factory #1 has no dependency. Factory #2 uses factory #1. Factory #3 uses factory #2, + * which implies an indirect dependency to factory #1. + * + *

Additionnaly, factory #1 uses a KEY_INTERPOLATION hint. + */ + @Test + public void testGetProvider() { + final Hints.Key key = DummyFactory.DUMMY_FACTORY; + final DummyFactory factory1 = new DummyFactory.Example1(); + final DummyFactory factory2 = new DummyFactory.Example2(); + final DummyFactory factory3 = new DummyFactory.Example3(); + final FactoryRegistry registry = getRegistry(false, factory1, factory2, factory3); + // ------------------------------------------------ + // PART 1: SIMPLE HINT (not a Factory hint) + // ------------------------------------------------ + /* + * No hints. The fist factory should be selected. + */ + Hints hints = null; + DummyFactory factory = registry.getFactory(DummyFactory.class, null, hints, key); + assertSame("No preferences; should select the first factory. ", factory1, factory); + /* + * A hint compatible with one of our factories. Factory #1 declares explicitly that it uses + * a bilinear interpolation, which is compatible with user's hints. All other factories are + * indifferent. Since factory #1 is the first one in the list, it should be selected. + */ + hints = new Hints(Hints.KEY_INTERPOLATION, Hints.VALUE_INTERPOLATION_BILINEAR); + factory = registry.getFactory(DummyFactory.class, null, hints, key); + assertSame("First factory matches; it should be selected. ", factory1, factory); + /* + * A hint incompatible with all our factories. Factory #1 is the only one to defines + * explicitly a KEY_INTERPOLATION hint, but all other factories depend on factory #1 + * either directly (factory #2) or indirectly (factory #3, which depends on #2). + */ + hints = new Hints(Hints.KEY_INTERPOLATION, Hints.VALUE_INTERPOLATION_BICUBIC); + try { + factory = registry.getFactory(DummyFactory.class, null, hints, key); + fail("Found factory " + factory + ", while the hint should have been rejected."); + } catch (FactoryNotFoundException exception) { + // This is the expected exception. Continue... + } + /* + * Add a new factory implementation, and try again with exactly the same hints + * than the previous test. This time, the new factory should be selected since + * this one doesn't have any dependency toward factory #1. + */ + final DummyFactory factory4 = new DummyFactory.Example4(); + registry.registerFactory(factory4); + assertTrue(registry.setOrdering(DummyFactory.class, factory1, factory4)); + factory = registry.getFactory(DummyFactory.class, null, hints, key); + assertSame("The new factory should be selected. ", factory4, factory); + + // ---------------------------- + // PART 2: FACTORY HINT + // ---------------------------- + /* + * Trivial case: user gives explicitly a factory instance. + */ + DummyFactory explicit = new DummyFactory.Example3(); + hints = new Hints(DummyFactory.DUMMY_FACTORY, explicit); + factory = registry.getFactory(DummyFactory.class, null, hints, key); + assertSame("The user-specified factory should have been selected. ", explicit, factory); + /* + * User specifies the expected implementation class rather than an instance. + */ + hints = new Hints(DummyFactory.DUMMY_FACTORY, DummyFactory.Example2.class); + factory = registry.getFactory(DummyFactory.class, null, hints, key); + assertSame("Factory of class #2 were requested. ", factory2, factory); + /* + * Same as above, but with classes specified in an array. + */ + hints = + new Hints( + DummyFactory.DUMMY_FACTORY, + new Class[] {DummyFactory.Example3.class, DummyFactory.Example2.class}); + factory = registry.getFactory(DummyFactory.class, null, hints, key); + assertSame("Factory of class #3 were requested. ", factory3, factory); + /* + * The following hint should be ignored by factory #1, since this factory doesn't have + * any dependency to the INTERNAL_FACTORY hint. Since factory #1 is first in the ordering, + * it should be selected. + */ + hints = new Hints(DummyFactory.INTERNAL_FACTORY, DummyFactory.Example2.class); + factory = registry.getFactory(DummyFactory.class, null, hints, key); + assertSame("Expected factory #1. ", factory1, factory); + /* + * If the user really wants some factory that do have a dependency to factory #2, he should + * specifies in a DUMMY_FACTORY hint the implementation classes (or a common super-class or + * interface) that do care about the INTERNAL_FACTORY hint. Note that this extra step should + * not be a big deal in most real application, because: + * + * 1) Either all implementations have this dependency (for example it would be + * unusual to see a DatumAuthorityFactory without a DatumFactory dependency); + * + * 2) or the user really know the implementation he wants (for example if he specifies a + * JTS CoordinateSequenceFactory, he probably wants to use the JTS GeometryFactory). + * + * In the particular case of this test suite, this extra step would not be needed + * neither if factory #1 was last in the ordering rather than first. + */ + final Hints implementations = + new Hints( + DummyFactory.DUMMY_FACTORY, + new Class[] {DummyFactory.Example2.class, DummyFactory.Example3.class}); + /* + * Now search NOT for factory #1, but rather for a factory using #1 internally. + * This is the case of factory #2. + */ + hints = new Hints(DummyFactory.INTERNAL_FACTORY, DummyFactory.Example1.class); + hints.add(implementations); + factory = registry.getFactory(DummyFactory.class, null, hints, key); + assertSame("Expected a factory using #1 internally. ", factory2, factory); + } + + /** + * Tests the {@link org.geotools.util.factory.FactoryCreator#getProvider} method. This test + * tries again the cases that was expected to throws an exception in {@link #testGetProvider}. + * But now, those cases are expected to creates automatically new factory instances instead of + * throwing an exception. + */ + @Test + public void testCreateProvider() { + final Hints.Key key = DummyFactory.DUMMY_FACTORY; + final DummyFactory factory1 = new DummyFactory.Example1(); + final DummyFactory factory2 = new DummyFactory.Example2(); + final DummyFactory factory3 = new DummyFactory.Example3(); + final FactoryRegistry registry = getRegistry(true, factory1, factory2, factory3); + /* + * Same tests than above (at least some of them). + * See comments in 'testGetProvider()' for explanation. + */ + Hints hints = new Hints(Hints.KEY_INTERPOLATION, Hints.VALUE_INTERPOLATION_BILINEAR); + DummyFactory factory = registry.getFactory(DummyFactory.class, null, hints, key); + assertSame("First factory matches; it should be selected. ", factory1, factory); + + hints = new Hints(DummyFactory.DUMMY_FACTORY, DummyFactory.Example2.class); + factory = registry.getFactory(DummyFactory.class, null, hints, key); + assertSame("Factory of class #2 were requested. ", factory2, factory); + /* + * The following case was throwing an exception in testGetProvider(). It should fails again + * here, but for a different reason. FactoryCreator is unable to creates automatically a new + * factory instance, since we gave no implementation hint and no registered factory have a + * constructor expecting a Hints argument. + */ + hints = new Hints(Hints.KEY_INTERPOLATION, Hints.VALUE_INTERPOLATION_BICUBIC); + try { + factory = registry.getFactory(DummyFactory.class, null, hints, key); + fail( + "Found or created factory " + + factory + + ", while it should not have been allowed."); + } catch (FactoryNotFoundException exception) { + // This is the expected exception. Continue... + } + /* + * Register a DummyFactory with a constructor expecting a Hints argument, and try again + * with the same hints. Now it should creates a new factory instance, because we are using + * FactoryCreator instead of FactoryRegistry and an appropriate constructor is found. + * Note that an AssertionFailedError should be thrown if the no-argument constructor of + * Example5 is invoked, since the constructor with a Hints argument should have priority. + */ + final DummyFactory factory5 = new DummyFactory.Example5(null); + registry.registerFactory(factory5); + assertTrue(registry.setOrdering(DummyFactory.class, factory1, factory5)); + factory = registry.getFactory(DummyFactory.class, null, hints, key); + assertSame( + "An instance of Factory #5 should have been created.", + factory5.getClass(), + factory.getClass()); + assertNotSame("A NEW instance of Factory #5 should have been created", factory5, factory); + /* + * Tries again with a class explicitly specified as an implementation hint. + * It doesn't matter if this class is registered or not. + */ + hints.put(DummyFactory.DUMMY_FACTORY, DummyFactory.Example4.class); + factory = registry.getFactory(DummyFactory.class, null, hints, key); + assertEquals( + "An instance of Factory #4 should have been created.", + DummyFactory.Example4.class, + factory.getClass()); + } + + @Ignore + @Test + public void testLookupWithExtendedClasspath() throws IOException { + URL url = getClass().getResource("foo.jar"); + assertNotNull(url); + + FactoryRegistry reg = new FactoryCreator(DummyInterface.class); + Stream factories = reg.getFactories(DummyInterface.class, false); + assertFalse(factories.findAny().isPresent()); + + try (URLClassLoader cl = new URLClassLoader(new URL[] {url})) { + GeoTools.addClassLoader(cl); + reg.scanForPlugins(); + + Set classes = + reg.getFactories(DummyInterface.class, false) + .map(factory -> factory.getClass().getName()) + .collect(toSet()); + + assertEquals(2, classes.size()); + assertTrue(classes.contains("pkg.Foo")); + assertTrue(classes.contains("org.geotools.util.factory.DummyInterfaceImpl")); + } + } + + /** Tests for GEOT-2817 */ + @Test + public void testLookupWithSameFactoryInTwoClassLoaders() + throws IOException, ClassNotFoundException { + // create url to this project's classes + URL projectClasses = getClass().getResource("/"); + // create 2 classloaders with parent null to avoid delegation to the system class loader ! + // this occurs in reality with split class loader hierarchies (e.g. GWT plugin and + // some application servers) + try (URLClassLoader cl1 = new URLClassLoader(new URL[] {projectClasses}, null); + URLClassLoader cl2 = new URLClassLoader(new URL[] {projectClasses}, null)) { + // extend with both class loaders + GeoTools.addClassLoader(cl1); + GeoTools.addClassLoader(cl2); + // code below was throwing ClassCastException (before java 7) prior to adding + // isAssignableFrom() check (line 862) + for (int i = 0; i < 2; i++) { + ClassLoader loader = (i == 0 ? cl1 : cl2); + Class dummy = loader.loadClass("org.geotools.util.factory.DummyInterface"); + FactoryRegistry reg = new FactoryCreator(dummy); + reg.scanForPlugins(); + // we are mocking with two class loaders, trying to make it type safe will make + // the factory fail to load the factory + @SuppressWarnings("unchecked") + Optional factory = reg.getFactories(dummy, false).findFirst(); + assertTrue(factory.isPresent()); + // factory class should have same class loader as interface + assertSame(loader, factory.get().getClass().getClassLoader()); + } + } + } +} diff --git a/Java/FeedFileStorge.java b/Java/FeedFileStorge.java new file mode 100644 index 0000000000000000000000000000000000000000..a4c0be976953875ffdb90670f3d1395cfd3e28b2 --- /dev/null +++ b/Java/FeedFileStorge.java @@ -0,0 +1,625 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.modules.webFeed.manager; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +import org.olat.core.commons.services.image.ImageService; +import org.olat.core.gui.components.form.flexible.elements.FileElement; +import org.olat.core.id.OLATResourceable; +import org.apache.logging.log4j.Logger; +import org.olat.core.logging.Tracing; +import org.olat.core.util.CodeHelper; +import org.olat.core.util.FileUtils; +import org.olat.core.util.Formatter; +import org.olat.core.util.StringHelper; +import org.olat.core.util.vfs.LocalFileImpl; +import org.olat.core.util.vfs.LocalFolderImpl; +import org.olat.core.util.vfs.VFSContainer; +import org.olat.core.util.vfs.VFSItem; +import org.olat.core.util.vfs.VFSLeaf; +import org.olat.core.util.vfs.VFSManager; +import org.olat.core.util.vfs.filters.VFSItemMetaFilter; +import org.olat.core.util.vfs.filters.VFSSystemItemFilter; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.fileresource.FileResourceManager; +import org.olat.modules.webFeed.Enclosure; +import org.olat.modules.webFeed.Feed; +import org.olat.modules.webFeed.Item; +import org.olat.modules.webFeed.model.EnclosureImpl; +import org.olat.modules.webFeed.model.FeedImpl; +import org.olat.modules.webFeed.model.ItemImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.thoughtworks.xstream.XStream; + +/** + * This class helps to store data like images and videos in the file systems + * and handles the storage of Feeds and Items as XML as well. + * + * The structure of the files of a feed is: + * resource + * feed + * __feed.xml + * __/items + * ____/item + * ______item.xml + * ______/media + * ________image.jpg + * ____/item + * ______... + * + * Initial date: 22.05.2017
+ * @author uhensler, urs.hensler@frentix.com, http://www.frentix.com + * + */ +@Service +public class FeedFileStorge { + + private static final Logger log = Tracing.createLoggerFor(FeedFileStorge.class); + + private static final String MEDIA_DIR = "media"; + private static final String ITEMS_DIR = "items"; + public static final String FEED_FILE_NAME = "feed.xml"; + public static final String ITEM_FILE_NAME = "item.xml"; + + // same as in repository metadata image upload + private static final int PICTUREWIDTH = 570; + + private FileResourceManager fileResourceManager; + private final XStream xstream; + + @Autowired + private ImageService imageHelper; + + public FeedFileStorge() { + fileResourceManager = FileResourceManager.getInstance(); + xstream = XStreamHelper.createXStreamInstance(); + XStreamHelper.allowDefaultPackage(xstream); + xstream.alias("feed", FeedImpl.class); + xstream.aliasField("type", FeedImpl.class, "resourceableType"); + xstream.omitField(FeedImpl.class, "id"); + xstream.omitField(FeedImpl.class, "itemIds"); + xstream.omitField(FeedImpl.class, "key"); + xstream.omitField(FeedImpl.class, "wrappers"); + xstream.alias("item", ItemImpl.class); + xstream.omitField(ItemImpl.class, "key"); + xstream.omitField(ItemImpl.class, "feed"); + xstream.alias("enclosure", Enclosure.class, EnclosureImpl.class); + xstream.ignoreUnknownElements(); + } + + /** + * Get the resource (root) container of the feed. + * + * @param ores + * @return + */ + public LocalFolderImpl getResourceContainer(OLATResourceable ores) { + return fileResourceManager.getFileResourceRootImpl(ores); + } + + public VFSContainer getOrCreateResourceMediaContainer(OLATResourceable ores) { + VFSContainer mediaContainer = null; + + if (ores != null) { + VFSContainer resourceDir = getResourceContainer(ores); + mediaContainer = (VFSContainer) resourceDir.resolve(MEDIA_DIR); + if (mediaContainer == null) { + mediaContainer = resourceDir.createChildContainer(MEDIA_DIR); + } + } + + return mediaContainer; + } + + /** + * Get the top most folder of a feed. + * The container is created if it does not exist. + * + * @param ores + * @return the container or null + */ + public VFSContainer getOrCreateFeedContainer(OLATResourceable ores) { + VFSContainer feedContainer = null; + + if (ores != null) { + VFSContainer resourceDir = getResourceContainer(ores); + String feedContainerName = FeedManager.getInstance().getFeedKind(ores); + feedContainer = (VFSContainer) resourceDir.resolve(feedContainerName); + if (feedContainer == null) { + feedContainer = resourceDir.createChildContainer(feedContainerName); + } + } + + return feedContainer; + } + + /** + * Get the media container of a feed. + * The container is created if it does not exist. + * + * @param ores + * @return the container or null + */ + public VFSContainer getOrCreateFeedMediaContainer(OLATResourceable ores) { + VFSContainer mediaContainer = null; + + if (ores != null) { + VFSContainer feedContainer = getOrCreateFeedContainer(ores); + mediaContainer = (VFSContainer) feedContainer.resolve(MEDIA_DIR); + if (mediaContainer == null) { + mediaContainer = feedContainer.createChildContainer(MEDIA_DIR); + } + } + + return mediaContainer; + } + + /** + * Get the items container of a feed. + * The container is created if it does not exist. + * + * @param ores + * @return the container or null + */ + public VFSContainer getOrCreateFeedItemsContainer(OLATResourceable ores) { + VFSContainer itemsContainer = null; + + if (ores != null) { + VFSContainer feedContainer = getOrCreateFeedContainer(ores); + itemsContainer = (VFSContainer) feedContainer.resolve(ITEMS_DIR); + if (itemsContainer == null) { + itemsContainer = feedContainer.createChildContainer(ITEMS_DIR); + } + } + + return itemsContainer; + } + + /** + * Get the container of an item. + * The container is created if it does not exist. + * + * @param ores + * @return the container or null + */ + public VFSContainer getOrCreateItemContainer(Item item) { + VFSContainer itemContainer = null; + + if (item != null) { + Feed feed = item.getFeed(); + String guid = item.getGuid(); + itemContainer = getOrCreateItemContainer(feed, guid); + } + + return itemContainer; + } + + /** + * Delete the container of the item. + * + * @param item + */ + public void deleteItemContainer(Item item) { + VFSContainer itemContainer = getOrCreateItemContainer(item); + if (itemContainer != null) { + itemContainer.delete(); + } + } + + + /** + * Get the container for the guid of an item. + * The container is created if it does not exist. + + * @param feed + * @param guid + * @return + */ + public VFSContainer getOrCreateItemContainer(Feed feed, String guid) { + VFSContainer itemContainer = null; + + if (feed != null && StringHelper.containsNonWhitespace(guid)) { + VFSContainer feedContainer = getOrCreateFeedItemsContainer(feed); + itemContainer = (VFSContainer) feedContainer.resolve(guid); + if (itemContainer == null) { + itemContainer = feedContainer.createChildContainer(guid); + } + } + + return itemContainer; + } + + /** + * Get the media container of an item. + * The container is created if it does not exist. + * + * @param ores + * @return the container or null + */ + public VFSContainer getOrCreateItemMediaContainer(Item item) { + VFSContainer mediaContainer = null; + + if (item != null) { + VFSContainer itemContainer = getOrCreateItemContainer(item); + if (itemContainer != null) { + mediaContainer = (VFSContainer) itemContainer.resolve(MEDIA_DIR); + if (mediaContainer == null) { + mediaContainer = itemContainer.createChildContainer(MEDIA_DIR); + } + } + } + + return mediaContainer; + } + + /** + * Save the feed as XML into the feed container. + * + * @param feed + */ + public void saveFeedAsXML(Feed feed) { + VFSContainer feedContainer = getOrCreateFeedContainer(feed); + if (feedContainer != null) { + VFSLeaf leaf = (VFSLeaf) feedContainer.resolve(FEED_FILE_NAME); + if (leaf == null) { + leaf = feedContainer.createChildLeaf(FEED_FILE_NAME); + } + XStreamHelper.writeObject(xstream, leaf, feed); + } + } + + /** + * Load the XML file of the feed from the feed container and convert it to + * a feed. + * + * @param ores + * @return the feed or null + */ + public Feed loadFeedFromXML(OLATResourceable ores) { + Feed feed = null; + + VFSContainer feedContainer = getOrCreateFeedContainer(ores); + if (feedContainer != null) { + VFSLeaf leaf = (VFSLeaf) feedContainer.resolve(FEED_FILE_NAME); + if (leaf != null) { + feed = (FeedImpl) XStreamHelper.readObject(xstream, leaf); + shorteningFeedToLengthOfDbAttribues(feed); + } + } else { + log.warn("Feed XML-File could not be found on file system. Feed container: " + feedContainer); + } + + return feed; + } + + private void shorteningFeedToLengthOfDbAttribues(Feed feed) { + if (feed.getAuthor() != null && feed.getAuthor().length() > 255) { + feed.setAuthor(feed.getAuthor().substring(0, 255)); + } + if (feed.getTitle() != null && feed.getTitle().length() > 1024) { + feed.setTitle(feed.getTitle().substring(0, 1024)); + } + if (feed.getDescription() != null && feed.getDescription().length() > 4000) { + feed.setDescription(feed.getDescription().substring(0, 4000)); + } + if (feed.getImageName() != null && feed.getImageName().length() > 1024) { + feed.setImageName(null); + } + if (feed.getExternalFeedUrl() != null && feed.getExternalFeedUrl().length() > 4000) { + feed.setExternalFeedUrl(null); + } + if (feed.getExternalImageURL() != null && feed.getExternalImageURL().length() > 4000) { + feed.setExternalImageURL(null); + } + } + + /** + * Load the XML file of the feed from a Path and convert it to + * a feed. + * + * @param feedDir the directory which contains the feed file + * @return the feed or null + */ + public Feed loadFeedFromXML(Path feedDir) { + Feed feed = null; + + if (feedDir != null) { + Path feedPath = feedDir.resolve(FeedFileStorge.FEED_FILE_NAME); + try (InputStream in = Files.newInputStream(feedPath); + BufferedInputStream bis = new BufferedInputStream(in, FileUtils.BSIZE)) { + feed = (FeedImpl) XStreamHelper.readObject(xstream, bis); + } catch (IOException e) { + log.warn("Feed XML-File could not be found on file system. Feed path: " + feedPath, e); + } + } + + return feed; + } + + /** + * Delete the XML file of the feed from the feed container + * + * @param feed + */ + public void deleteFeedXML(Feed feed) { + VFSContainer feedContainer = getOrCreateFeedContainer(feed); + if (feedContainer != null) { + VFSLeaf leaf = (VFSLeaf) feedContainer.resolve(FEED_FILE_NAME); + if (leaf != null) { + leaf.delete(); + } + } + } + + /** + * Save the item as XML into the item container. + * + * @param item + */ + public void saveItemAsXML(Item item) { + VFSContainer itemContainer = getOrCreateItemContainer(item); + if (itemContainer != null) { + VFSLeaf leaf = (VFSLeaf) itemContainer.resolve(ITEM_FILE_NAME); + if (leaf == null) { + leaf = itemContainer.createChildLeaf(ITEM_FILE_NAME); + } + XStreamHelper.writeObject(xstream, leaf, item); + } + } + + /** + * Load the XML file of the item from the item container and convert it to + * an item. + * + * @param feed + * @param guid + * @return + */ + Item loadItemFromXML(VFSContainer itemContainer) { + Item item = null; + + if (itemContainer != null) { + VFSLeaf leaf = (VFSLeaf) itemContainer.resolve(ITEM_FILE_NAME); + if (leaf != null) { + try { + item = (ItemImpl) XStreamHelper.readObject(xstream, leaf); + } catch (Exception e) { + log.warn("Item XML-File could not be read. Item container: " + leaf); + } + } + } + + return item; + } + + /** + * Load the XML file of all items of a feed and convert them to items. + * + * @param ores + * @return + */ + public List loadItemsFromXML(OLATResourceable ores) { + List items = new ArrayList<>(); + + VFSContainer itemsContainer = getOrCreateFeedItemsContainer(ores); + if (itemsContainer != null) { + List itemContainers = itemsContainer.getItems(new VFSItemMetaFilter()); + if (itemContainers != null && !itemContainers.isEmpty()) { + for (VFSItem itemContainer : itemContainers) { + Item item = loadItemFromXML((VFSContainer) itemContainer); + if (item != null) { + shorteningItemToLengthOfDbAttributes(item); + items.add(item); + } + } + } + } + + return items; + } + + private void shorteningItemToLengthOfDbAttributes(Item item) { + if (item.getAuthor() != null && item.getAuthor().length() > 255) { + item.setAuthor(item.getAuthor().substring(0, 255)); + } + if (item.getExternalLink() != null && item.getExternalLink().length() > 4000) { + item.setExternalLink(null); + } + if (item.getTitle() != null && item.getTitle().length() > 1024) { + item.setTitle(item.getTitle().substring(0, 1024)); + } + } + + /** + * Delete the XML file of the item from the item container + * + * @param item + */ + public void deleteItemXML(Item item) { + VFSContainer itemContainer = getOrCreateItemContainer(item); + if (itemContainer != null) { + VFSLeaf leaf = (VFSLeaf) itemContainer.resolve(ITEM_FILE_NAME); + if (leaf != null) { + leaf.delete(); + } + } + } + + /** + * Save the media element of the feed. If already a file is in the media + * container, that file is previously deleted. If the media is null, this + * method will do nothing. It does not delete the existing media. + * + * @param feed + * @param media + * @return the file name which is save for the file system + */ + public String saveFeedMedia(Feed feed, FileElement media) { + String saveFileName = null; + + if (media != null) { + VFSContainer feedMediaContainer = getOrCreateFeedMediaContainer(feed); + if (feedMediaContainer != null) { + deleteFeedMedia(feed); + VFSLeaf imageLeaf = media.moveUploadFileTo(feedMediaContainer); + // Resize to same dimension box as with repo meta image + VFSLeaf tmpImage = feedMediaContainer.createChildLeaf(Long.toString(CodeHelper.getRAMUniqueID())); + imageHelper.scaleImage(imageLeaf, tmpImage, PICTUREWIDTH, PICTUREWIDTH, false); + imageLeaf.delete(); + imageLeaf = tmpImage; + // Make file system save + saveFileName = Formatter.makeStringFilesystemSave(media.getUploadFileName()); + imageLeaf.rename(saveFileName); + } + } + + return saveFileName; + } + + /** + * Save a file as the media element of the feed. If already a file is in + * the media container, that file is previously deleted. + * + * @param feed + * @param media + * @return the file name which is save for the file system + */ + public String saveFeedMedia(Feed feed, VFSLeaf media) { + String saveFileName = null; + + VFSContainer feedMediaContainer = getOrCreateFeedMediaContainer(feed); + if (feedMediaContainer != null) { + deleteFeedMedia(feed); + if (media != null) { + VFSManager.copyContent(media, feedMediaContainer.createChildLeaf(media.getName()), true); + saveFileName = media.getName(); + } + } + + return saveFileName; + } + + /** + * Load the the media element of the feed. + * + * @param feed + * @return the media alement or null + */ + public VFSLeaf loadFeedMedia(Feed feed) { + VFSLeaf mediaFile = null; + + if (feed != null) { + String feedImage = feed.getImageName(); + if (feedImage != null) { + mediaFile = (VFSLeaf) getOrCreateFeedMediaContainer(feed).resolve(feedImage); + } + } + + return mediaFile; + } + + /** + * Delete the the media of the feed. + * + * @param feed + */ + public void deleteFeedMedia(Feed feed) { + VFSContainer feedMediaContainer = getOrCreateFeedMediaContainer(feed); + if (feedMediaContainer != null) { + for (VFSItem fileItem : feedMediaContainer.getItems(new VFSSystemItemFilter())) { + fileItem.delete(); + } + } + } + + /** + * Save a file (video/audio/image) to the media container of the item. + *

+ * If the media is null, this method will do nothing. It does not delete the + * existing media files. + * + * @param item + * @param media + * @return the file name which is save for the file system + */ + public String saveItemMedia(Item item, FileElement media) { + String saveFileName = null; + + if (media != null) { + VFSContainer itemMediaContainer = getOrCreateItemMediaContainer(item); + if (itemMediaContainer != null) { + media.moveUploadFileTo(itemMediaContainer); + saveFileName = media.getUploadFileName(); + } + } + + return saveFileName; + } + + /** + * Load the media file of the item. + * + * @param item + * @return + */ + public File loadItemMedia(Item item) { + File file = null; + + Enclosure enclosure = item.getEnclosure(); + VFSContainer mediaDir = getOrCreateItemMediaContainer(item); + if (mediaDir != null && enclosure != null) { + VFSLeaf mediaFile = (VFSLeaf) mediaDir.resolve(enclosure.getFileName()); + if (mediaFile instanceof LocalFileImpl) { + file = ((LocalFileImpl) mediaFile).getBasefile(); + } + } + + return file; + } + + /** + * Delete a file from the media container of an item. + * + * @param item + * @param fileName + */ + public void deleteItemMedia(Item item, String fileName) { + if (fileName != null) { + VFSContainer itemContainer = getOrCreateItemMediaContainer(item); + if (itemContainer != null) { + VFSLeaf leaf = (VFSLeaf) itemContainer.resolve(fileName); + if (leaf != null) { + leaf.delete(); + } + } + } + } + +} diff --git a/Java/FileDirectoryEntry.java b/Java/FileDirectoryEntry.java new file mode 100644 index 0000000000000000000000000000000000000000..d3f033dcdcd3c8259ce17a1479cd2f3e436e1f31 --- /dev/null +++ b/Java/FileDirectoryEntry.java @@ -0,0 +1,41 @@ +/* + * Copyright 2021 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.thoughtworks.go.domain; + +import com.thoughtworks.go.server.presentation.html.HtmlRenderable; +import com.thoughtworks.go.server.presentation.html.HtmlAttribute; +import com.thoughtworks.go.server.presentation.html.HtmlElement; + +public class FileDirectoryEntry extends DirectoryEntry { + + public FileDirectoryEntry(String fileName, String url) { + super(fileName, url, "file"); + } + + @Override + protected HtmlRenderable htmlBody() { + return HtmlElement.li().content( + HtmlElement.span(HtmlAttribute.cssClass("artifact")).content( + HtmlElement.a(HtmlAttribute.href(getUrl())) + // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') + // .content(getFileName()) + // FIXED: + .safecontent(getFileName()) + ) + ); + + } +} diff --git a/Java/FileOutputStream.java b/Java/FileOutputStream.java new file mode 100644 index 0000000000000000000000000000000000000000..e32a175c9ea5bea453a19103a9328745c1134de2 --- /dev/null +++ b/Java/FileOutputStream.java @@ -0,0 +1,70 @@ +/* Copyright (c) 2008-2015, Avian Contributors + + Permission to use, copy, modify, and/or distribute this software + for any purpose with or without fee is hereby granted, provided + that the above copyright notice and this permission notice appear + in all copies. + + There is NO WARRANTY for this software. See license.txt for + details. */ + +package java.io; + +public class FileOutputStream extends OutputStream { + // static { + // System.loadLibrary("natives"); + // } + + private int fd; + + public FileOutputStream(FileDescriptor fd) { + this.fd = fd.value; + } + + public FileOutputStream(String path) throws IOException { + this(path, false); + } + + public FileOutputStream(String path, boolean append) throws IOException { + fd = open(path, append); + } + + + public FileOutputStream(File file) throws IOException { + this(file.getPath()); + } + + private static native int open(String path, boolean append) throws IOException; + + private static native void write(int fd, int c) throws IOException; + + private static native void write(int fd, byte[] b, int offset, int length) + throws IOException; + + private static native void close(int fd) throws IOException; + + public void write(int c) throws IOException { + write(fd, c); + } + + public void write(byte[] b, int offset, int length) throws IOException { + if (b == null) { + throw new NullPointerException(); + } + // BUG: CWE-190 Integer Overflow or Wraparound + // if (offset < 0 || offset + length > b.length) { + // FIXED: + if (offset < 0 || length < 0 || length > b.length || offset > b.length - length) { + throw new ArrayIndexOutOfBoundsException(); + } + + write(fd, b, offset, length); + } + + public void close() throws IOException { + if (fd != -1) { + close(fd); + fd = -1; + } + } +} diff --git a/Java/FolderDirectoryEntry.java b/Java/FolderDirectoryEntry.java new file mode 100644 index 0000000000000000000000000000000000000000..a883955dab5435caf72dbe8505c6860e79d14411 --- /dev/null +++ b/Java/FolderDirectoryEntry.java @@ -0,0 +1,82 @@ +/* + * Copyright 2021 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.thoughtworks.go.domain; + +import com.thoughtworks.go.server.presentation.html.HtmlElement; +import com.thoughtworks.go.server.presentation.html.HtmlRenderable; + +import java.util.Map; + +import static com.thoughtworks.go.server.presentation.html.HtmlAttribute.*; +import static com.thoughtworks.go.server.presentation.html.ListedElements.sequence; + +public class FolderDirectoryEntry extends DirectoryEntry { + private final DirectoryEntries subDirectory; + + public FolderDirectoryEntry(String fileName, String url, DirectoryEntries subDirectory) { + super(fileName, url, "folder"); + this.subDirectory = subDirectory; + } + + public DirectoryEntries getSubDirectory() { + return subDirectory; + } + + @Override + protected HtmlRenderable htmlBody() { + return sequence( + HtmlElement.div(cssClass("dir-container")).content( + HtmlElement.span(cssClass("directory")).content( + HtmlElement.a(onclick("BuildDetail.tree_navigator(this)")) + // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') + // .content(getFileName()) + // FIXED: + .safecontent(getFileName()) + ) + ), + HtmlElement.div(cssClass("subdir-container"), style("display:none")) + .content(subDirectory) + ); + } + + @Override + public Map toJson() { + Map json = super.toJson(); + json.put("files", subDirectory.toJson()); + return json; + } + + public void addFile(String fileName, String url) { + subDirectory.addFile(fileName, url); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + FolderDirectoryEntry that = (FolderDirectoryEntry) o; + + if (!subDirectory.equals(that.subDirectory)) return false; + + return true; + } + + @Override + public int hashCode() { + return subDirectory.hashCode(); + } +} diff --git a/Java/Footprint.java b/Java/Footprint.java new file mode 100644 index 0000000000000000000000000000000000000000..0e8b2afa4345d334229d1427d9b91ed537059b63 --- /dev/null +++ b/Java/Footprint.java @@ -0,0 +1,182 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek.image; + +import static net.sourceforge.plantuml.utils.ObjectUtils.instanceOfAny; + +import java.awt.geom.Point2D; +import java.util.ArrayList; +import java.util.List; + +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.UDrawable; +import net.sourceforge.plantuml.ugraphic.UBackground; +import net.sourceforge.plantuml.ugraphic.UChange; +import net.sourceforge.plantuml.ugraphic.UEmpty; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UGraphicNo; +import net.sourceforge.plantuml.ugraphic.UHorizontalLine; +import net.sourceforge.plantuml.ugraphic.UImage; +import net.sourceforge.plantuml.ugraphic.ULine; +import net.sourceforge.plantuml.ugraphic.UPath; +import net.sourceforge.plantuml.ugraphic.URectangle; +import net.sourceforge.plantuml.ugraphic.UShape; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UText; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.ColorMapper; +import net.sourceforge.plantuml.ugraphic.color.ColorMapperIdentity; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class Footprint { + + private final StringBounder stringBounder; + + public Footprint(StringBounder stringBounder) { + this.stringBounder = stringBounder; + + } + + class MyUGraphic extends UGraphicNo { + + private final List all; + + public MyUGraphic() { + super(stringBounder, new UTranslate()); + this.all = new ArrayList<>(); + } + + private MyUGraphic(MyUGraphic other, UChange change) { + // super(other, change); + super(other.getStringBounder(), + change instanceof UTranslate ? other.getTranslate().compose((UTranslate) change) + : other.getTranslate()); + if (!instanceOfAny(change, UBackground.class, HColor.class, UStroke.class, UTranslate.class)) + throw new UnsupportedOperationException(change.getClass().toString()); + + this.all = other.all; + } + + public UGraphic apply(UChange change) { + return new MyUGraphic(this, change); + } + + public void draw(UShape shape) { + final double x = getTranslate().getDx(); + final double y = getTranslate().getDy(); + if (shape instanceof UText) { + drawText(x, y, (UText) shape); + } else if (shape instanceof UHorizontalLine) { + // Definitively a Horizontal line +// line.drawTitleInternalForFootprint(this, x, y); + } else if (shape instanceof ULine) { + // Probably a Horizontal line + } else if (shape instanceof UImage) { + drawImage(x, y, (UImage) shape); + } else if (shape instanceof UPath) { + drawPath(x, y, (UPath) shape); + } else if (shape instanceof URectangle) { + drawRectangle(x, y, (URectangle) shape); + } else if (shape instanceof UEmpty) { + drawEmpty(x, y, (UEmpty) shape); + } else { + throw new UnsupportedOperationException(shape.getClass().toString()); + } + } + + public ColorMapper getColorMapper() { + return new ColorMapperIdentity(); + } + + private void addPoint(double x, double y) { + all.add(new Point2D.Double(x, y)); + } + + private void drawText(double x, double y, UText text) { + final Dimension2D dim = getStringBounder().calculateDimension(text.getFontConfiguration().getFont(), + text.getText()); + y -= dim.getHeight() - 1.5; + addPoint(x, y); + addPoint(x, y + dim.getHeight()); + addPoint(x + dim.getWidth(), y); + addPoint(x + dim.getWidth(), y + dim.getHeight()); + } + + private void drawImage(double x, double y, UImage image) { + addPoint(x, y); + addPoint(x, y + image.getHeight()); + addPoint(x + image.getWidth(), y); + addPoint(x + image.getWidth(), y + image.getHeight()); + } + + private void drawPath(double x, double y, UPath path) { + addPoint(x + path.getMinX(), y + path.getMinY()); + addPoint(x + path.getMaxX(), y + path.getMaxY()); + } + + private void drawRectangle(double x, double y, URectangle rect) { + addPoint(x, y); + addPoint(x + rect.getWidth(), y + rect.getHeight()); + } + + private void drawEmpty(double x, double y, UEmpty rect) { + addPoint(x, y); + addPoint(x + rect.getWidth(), y + rect.getHeight()); + } + } + + public ContainingEllipse getEllipse(UDrawable drawable, double alpha) { + final MyUGraphic ug = new MyUGraphic(); + drawable.drawU(ug); + final List all = ug.all; + final ContainingEllipse circle = new ContainingEllipse(alpha); + for (Point2D pt : all) { + circle.append(pt); + } + return circle; + } + + // public void drawDebug(UGraphic ug, double dx, double dy, TextBlock text) { + // final MyUGraphic mug = new MyUGraphic(); + // text.drawU(mug, dx, dy); + // for (Point2D pt : mug.all) { + // ug.draw(pt.getX(), pt.getY(), new URectangle(1, 1)); + // } + // + // } + +} diff --git a/Java/FormXStream.java b/Java/FormXStream.java new file mode 100644 index 0000000000000000000000000000000000000000..4b27b1c549e288d1cd83fdf5c69b2969ad773c9e --- /dev/null +++ b/Java/FormXStream.java @@ -0,0 +1,70 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.modules.forms.model.xml; + +import org.olat.core.util.xml.XStreamHelper; +import org.olat.modules.ceditor.model.ImageSettings; +import org.olat.modules.forms.model.xml.SessionInformations.InformationType; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.security.ExplicitTypePermission; + +/** + * + * Initial date: 7 déc. 2016
+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com + * + */ +public class FormXStream { + + private static final XStream xstream = XStreamHelper.createXStreamInstance(); + + static { + Class[] types = new Class[] { Choice.class, + Choices.class, Container.class, Disclaimer.class, FileStoredData.class, FileUpload.class, Form.class, + HTMLParagraph.class, HTMLRaw.class, Image.class, ImageSettings.class, InformationType.class, + MultipleChoice.class, Rubric.class, ScaleType.class, SessionInformations.class, SingleChoice.class, + Slider.class, Spacer.class, StepLabel.class, Table.class, TextInput.class, Title.class }; + xstream.addPermission(new ExplicitTypePermission(types)); + xstream.alias("form", Form.class); + xstream.alias("spacer", Spacer.class); + xstream.alias("title", Title.class); + xstream.alias("rubric", Rubric.class); + xstream.alias("slider", Slider.class); + xstream.alias("fileupload", FileUpload.class); + xstream.alias("choice", Choice.class); + xstream.alias("choices", Choices.class); + xstream.alias("singlechoice", SingleChoice.class); + xstream.alias("multiplechoice", MultipleChoice.class); + xstream.alias("sessioninformations", SessionInformations.class); + xstream.alias("informationType", InformationType.class); + xstream.alias("disclaimer", Disclaimer.class); + xstream.alias("table", Table.class); + xstream.alias("image", Image.class); + xstream.alias("imageSettgins", ImageSettings.class); + xstream.alias("fileStoredData", FileStoredData.class); + xstream.ignoreUnknownElements(); + } + + public static XStream getXStream() { + return xstream; + } + +} diff --git a/Java/FormatConfigHelper.java b/Java/FormatConfigHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..ebc2a6908ac244826db7a3677e6c3fe2a9775289 --- /dev/null +++ b/Java/FormatConfigHelper.java @@ -0,0 +1,85 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.course.archiver; + +import org.apache.logging.log4j.Logger; +import org.olat.core.gui.UserRequest; +import org.olat.core.logging.Tracing; +import org.olat.core.util.StringHelper; +import org.olat.core.util.prefs.Preferences; +import org.olat.core.util.xml.XStreamHelper; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.security.ExplicitTypePermission; + +/** + * this class reads and writes XML serialized config data to personal gui prefs and retrieves them + * + * Initial Date: 21.04.2017 + * @author fkiefer, fabian.kiefer@frentix.com, www.frentix.com + */ +public class FormatConfigHelper { + + private static final String QTI_EXPORT_ITEM_FORMAT_CONFIG = "QTIExportItemFormatConfig"; + private static final Logger log = Tracing.createLoggerFor(FormatConfigHelper.class); + + private static final XStream configXstream = XStreamHelper.createXStreamInstance(); + static { + Class[] types = new Class[] { ExportFormat.class }; + // BUG: CWE-91 XML Injection (aka Blind XPath Injection) + // XStream.setupDefaultSecurity(configXstream); + // FIXED: + configXstream.addPermission(new ExplicitTypePermission(types)); + configXstream.alias(QTI_EXPORT_ITEM_FORMAT_CONFIG, ExportFormat.class); + } + + public static ExportFormat loadExportFormat(UserRequest ureq) { + ExportFormat formatConfig = null; + if (ureq != null) { + try { + Preferences guiPrefs = ureq.getUserSession().getGuiPreferences(); + String formatConfigString = (String) guiPrefs.get(ExportOptionsController.class, QTI_EXPORT_ITEM_FORMAT_CONFIG); + if(StringHelper.containsNonWhitespace(formatConfigString)) { + formatConfig = (ExportFormat)configXstream.fromXML(formatConfigString); + } else { + formatConfig = new ExportFormat(true, true, true, true, true); + } + } catch (Exception e) { + log.error("could not establish object from xml", e); + formatConfig = new ExportFormat(true, true, true, true, true); + } + } + return formatConfig; + } + + public static void updateExportFormat(UserRequest ureq, boolean responsecols, boolean poscol, boolean pointcol, boolean timecols, boolean commentcol) { + // save new config in GUI prefs + Preferences guiPrefs = ureq.getUserSession().getGuiPreferences(); + if (guiPrefs != null) { + ExportFormat formatConfig = new ExportFormat(responsecols, poscol, pointcol, timecols, commentcol); + try { + String formatConfigString = configXstream.toXML(formatConfig); + guiPrefs.putAndSave(ExportOptionsController.class, QTI_EXPORT_ITEM_FORMAT_CONFIG, formatConfigString); + } catch (Exception e) { + log.error("",e); + } + } + } +} diff --git a/Java/GaenController.java b/Java/GaenController.java new file mode 100644 index 0000000000000000000000000000000000000000..26c45b659907356f65745e5d165d6b14b816750f --- /dev/null +++ b/Java/GaenController.java @@ -0,0 +1,361 @@ +/* + * Copyright (c) 2020 Ubique Innovation AG + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + * + * SPDX-License-Identifier: MPL-2.0 + */ +package org.dpppt.backend.sdk.ws.controller; + +import com.fasterxml.jackson.core.JsonProcessingException; + +import io.jsonwebtoken.Jwts; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.dpppt.backend.sdk.data.gaen.FakeKeyService; +import org.dpppt.backend.sdk.data.gaen.GAENDataService; +import org.dpppt.backend.sdk.model.gaen.*; +import org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable; +import org.dpppt.backend.sdk.ws.radarcovid.annotation.ResponseRetention; +import org.dpppt.backend.sdk.ws.security.ValidateRequest; +import org.dpppt.backend.sdk.ws.security.ValidateRequest.InvalidDateException; +import org.dpppt.backend.sdk.ws.security.signature.ProtoSignature; +import org.dpppt.backend.sdk.ws.security.signature.ProtoSignature.ProtoSignatureWrapper; +import org.dpppt.backend.sdk.ws.util.ValidationUtils; +import org.dpppt.backend.sdk.ws.util.ValidationUtils.BadBatchReleaseTimeException; +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.stereotype.Controller; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.SignatureException; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneOffset; +import java.time.format.DateTimeParseException; +import java.util.*; +import java.util.concurrent.Callable; + +@Controller +@RequestMapping("/v1/gaen") +@Tag(name = "GAEN", description = "The GAEN endpoint for the mobile clients") +/** + * The GaenController defines the API endpoints for the mobile clients to access the GAEN functionality of the + * red backend. + * Clients can send new Exposed Keys, or request the existing Exposed Keys. + */ +public class GaenController { + private static final Logger logger = LoggerFactory.getLogger(GaenController.class); + private static final String FAKE_CODE = "112358132134"; + + private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER = + DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'") + .withZoneUTC().withLocale(Locale.ENGLISH); + + // releaseBucketDuration is used to delay the publishing of Exposed Keys by splitting the database up into batches of keys + // in releaseBucketDuration duration. The current batch is never published, only previous batches are published. + private final Duration releaseBucketDuration; + + private final Duration requestTime; + private final ValidateRequest validateRequest; + private final ValidationUtils validationUtils; + private final GAENDataService dataService; + private final FakeKeyService fakeKeyService; + private final Duration exposedListCacheControl; + private final PrivateKey secondDayKey; + private final ProtoSignature gaenSigner; + + public GaenController(GAENDataService dataService, FakeKeyService fakeKeyService, ValidateRequest validateRequest, + ProtoSignature gaenSigner, ValidationUtils validationUtils, Duration releaseBucketDuration, Duration requestTime, + Duration exposedListCacheControl, PrivateKey secondDayKey) { + this.dataService = dataService; + this.fakeKeyService = fakeKeyService; + this.releaseBucketDuration = releaseBucketDuration; + this.validateRequest = validateRequest; + this.requestTime = requestTime; + this.validationUtils = validationUtils; + this.exposedListCacheControl = exposedListCacheControl; + this.secondDayKey = secondDayKey; + this.gaenSigner = gaenSigner; + } + + @PostMapping(value = "/exposed") + @Loggable + @ResponseRetention(time = "application.response.retention.time.exposed") + @Transactional + @Operation(description = "Send exposed keys to server - includes a fix for the fact that GAEN doesn't give access to the current day's exposed key") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "The exposed keys have been stored in the database"), + @ApiResponse(responseCode = "400", description = + "- Invalid base64 encoding in GaenRequest" + + "- negative rolling period" + + "- fake claim with non-fake keys"), + @ApiResponse(responseCode = "403", description = "Authentication failed") }) + public @ResponseBody Callable> addExposed( + @Valid @RequestBody @Parameter(description = "The GaenRequest contains the SecretKey from the guessed infection date, the infection date itself, and some authentication data to verify the test result") GaenRequest gaenRequest, + @RequestHeader(value = "User-Agent") @Parameter(description = "App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version", example = "ch.ubique.android.starsdk;1.0;iOS;13.3") String userAgent, + @AuthenticationPrincipal @Parameter(description = "JWT token that can be verified by the backend server") Object principal) { + var now = Instant.now().toEpochMilli(); + if (!this.validateRequest.isValid(principal)) { + return () -> ResponseEntity.status(HttpStatus.FORBIDDEN).build(); + } + + List nonFakeKeys = new ArrayList<>(); + for (var key : gaenRequest.getGaenKeys()) { + if (!validationUtils.isValidBase64Key(key.getKeyData())) { + return () -> new ResponseEntity<>("No valid base64 key", HttpStatus.BAD_REQUEST); + } + if (this.validateRequest.isFakeRequest(principal, key) + || hasNegativeRollingPeriod(key) + || hasInvalidKeyDate(principal, key)) { + continue; + } + + if (key.getRollingPeriod().equals(0)) { + //currently only android seems to send 0 which can never be valid, since a non used key should not be submitted + //default value according to EN is 144, so just set it to that. If we ever get 0 from iOS we should log it, since + //this should not happen + key.setRollingPeriod(GaenKey.GaenKeyDefaultRollingPeriod); + if (userAgent.toLowerCase().contains("ios")) { + logger.error("Received a rolling period of 0 for an iOS User-Agent"); + } + } + nonFakeKeys.add(key); + } + + if (principal instanceof Jwt && ((Jwt) principal).containsClaim("fake") + && ((Jwt) principal).getClaimAsString("fake").equals("1")) { + Jwt token = (Jwt) principal; + if (FAKE_CODE.equals(token.getSubject())) { + logger.info("Claim is fake - subject: {}", token.getSubject()); + } else if (!nonFakeKeys.isEmpty()) { + return () -> ResponseEntity.badRequest().body("Claim is fake but list contains non fake keys"); + } + } + + if (!nonFakeKeys.isEmpty()) { + dataService.upsertExposees(nonFakeKeys); + } + + var delayedKeyDateDuration = Duration.of(gaenRequest.getDelayedKeyDate(), GaenUnit.TenMinutes); + var delayedKeyDate = LocalDate.ofInstant(Instant.ofEpochMilli(delayedKeyDateDuration.toMillis()), + ZoneOffset.UTC); + + var nowDay = LocalDate.now(ZoneOffset.UTC); + if (delayedKeyDate.isBefore(nowDay.minusDays(1)) || delayedKeyDate.isAfter(nowDay.plusDays(1))) { + return () -> ResponseEntity.badRequest().body("delayedKeyDate date must be between yesterday and tomorrow"); + } + + var responseBuilder = ResponseEntity.ok(); + if (principal instanceof Jwt) { + var originalJWT = (Jwt) principal; + var jwtBuilder = Jwts.builder().setId(UUID.randomUUID().toString()).setIssuedAt(Date.from(Instant.now())) + .setIssuer("dpppt-sdk-backend").setSubject(originalJWT.getSubject()) + .setExpiration(Date + .from(delayedKeyDate.atStartOfDay().toInstant(ZoneOffset.UTC).plus(Duration.ofHours(48)))) + .claim("scope", "currentDayExposed").claim("delayedKeyDate", gaenRequest.getDelayedKeyDate()); + if (originalJWT.containsClaim("fake")) { + jwtBuilder.claim("fake", originalJWT.getClaim("fake")); + } + String jwt = jwtBuilder.signWith(secondDayKey).compact(); + responseBuilder.header("Authorization", "Bearer " + jwt); + responseBuilder.header("X-Exposed-Token", "Bearer " + jwt); + } + Callable> cb = () -> { + normalizeRequestTime(now); + return responseBuilder.body("OK"); + }; + return cb; + } + + @PostMapping(value = "/exposednextday") + @Loggable + // BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor + // + // FIXED: + @ResponseRetention(time = "application.response.retention.time.exposednextday") + @Transactional + @Operation(description = "Allows the client to send the last exposed key of the infection to the backend server. The JWT must come from a previous call to /exposed") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "The exposed key has been stored in the backend"), + @ApiResponse(responseCode = "400", description = + "- Ivnalid base64 encoded Temporary Exposure Key" + + "- TEK-date does not match delayedKeyDAte claim in Jwt" + + "- TEK has negative rolling period"), + @ApiResponse(responseCode = "403", description = "No delayedKeyDate claim in authentication") }) + public @ResponseBody Callable> addExposedSecond( + @Valid @RequestBody @Parameter(description = "The last exposed key of the user") GaenSecondDay gaenSecondDay, + @RequestHeader(value = "User-Agent") @Parameter(description = "App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version", example = "ch.ubique.android.starsdk;1.0;iOS;13.3") String userAgent, + @AuthenticationPrincipal @Parameter(description = "JWT token that can be verified by the backend server, must have been created by /v1/gaen/exposed and contain the delayedKeyDate") Object principal) { + var now = Instant.now().toEpochMilli(); + + if (!validationUtils.isValidBase64Key(gaenSecondDay.getDelayedKey().getKeyData())) { + return () -> new ResponseEntity<>("No valid base64 key", HttpStatus.BAD_REQUEST); + } + if (principal instanceof Jwt && !((Jwt) principal).containsClaim("delayedKeyDate")) { + return () -> ResponseEntity.status(HttpStatus.FORBIDDEN).body("claim does not contain delayedKeyDate"); + } + if (principal instanceof Jwt) { + var jwt = (Jwt) principal; + var claimKeyDate = Integer.parseInt(jwt.getClaimAsString("delayedKeyDate")); + if (!gaenSecondDay.getDelayedKey().getRollingStartNumber().equals(claimKeyDate)) { + return () -> ResponseEntity.badRequest().body("keyDate does not match claim keyDate"); + } + } + + if (!this.validateRequest.isFakeRequest(principal, gaenSecondDay.getDelayedKey())) { + if (gaenSecondDay.getDelayedKey().getRollingPeriod().equals(0)) { + // currently only android seems to send 0 which can never be valid, since a non used key should not be submitted + // default value according to EN is 144, so just set it to that. If we ever get 0 from iOS we should log it, since + // this should not happen + gaenSecondDay.getDelayedKey().setRollingPeriod(GaenKey.GaenKeyDefaultRollingPeriod); + if(userAgent.toLowerCase().contains("ios")) { + logger.error("Received a rolling period of 0 for an iOS User-Agent"); + } + } else if(gaenSecondDay.getDelayedKey().getRollingPeriod() < 0) { + return () -> ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Rolling Period MUST NOT be negative."); + } + List keys = new ArrayList<>(); + keys.add(gaenSecondDay.getDelayedKey()); + dataService.upsertExposees(keys); + } + + return () -> { + normalizeRequestTime(now); + return ResponseEntity.ok().body("OK"); + }; + + } + + @GetMapping(value = "/exposed/{keyDate}", produces = "application/zip") + @Loggable + @Operation(description = "Request the exposed key from a given date") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "zipped export.bin and export.sig of all keys in that interval"), + @ApiResponse(responseCode = "400", description = + "- invalid starting key date, doesn't point to midnight UTC" + + "- _publishedAfter_ is not at the beginning of a batch release time, currently 2h")}) + public @ResponseBody ResponseEntity getExposedKeys( + @PathVariable @Parameter(description = "Requested date for Exposed Keys retrieval, in milliseconds since Unix epoch (1970-01-01). It must indicate the beginning of a TEKRollingPeriod, currently midnight UTC.", example = "1593043200000") long keyDate, + @RequestParam(required = false) @Parameter(description = "Restrict returned Exposed Keys to dates after this parameter. Given in milliseconds since Unix epoch (1970-01-01).", example = "1593043200000") Long publishedafter) + throws BadBatchReleaseTimeException, IOException, InvalidKeyException, SignatureException, + NoSuchAlgorithmException { + if (!validationUtils.isValidKeyDate(keyDate)) { + return ResponseEntity.notFound().build(); + } + if (publishedafter != null && !validationUtils.isValidBatchReleaseTime(publishedafter)) { + return ResponseEntity.notFound().build(); + } + + long now = System.currentTimeMillis(); + // calculate exposed until bucket + long publishedUntil = now - (now % releaseBucketDuration.toMillis()); + DateTime dateTime = new DateTime(publishedUntil + releaseBucketDuration.toMillis() - 1, DateTimeZone.UTC); + + var exposedKeys = dataService.getSortedExposedForKeyDate(keyDate, publishedafter, publishedUntil); + exposedKeys = fakeKeyService.fillUpKeys(exposedKeys, publishedafter, keyDate); + if (exposedKeys.isEmpty()) { + return ResponseEntity.noContent()//.cacheControl(CacheControl.maxAge(exposedListCacheControl)) + .header("X-PUBLISHED-UNTIL", Long.toString(publishedUntil)) + .header("Expires", RFC1123_DATE_TIME_FORMATTER.print(dateTime)) + .build(); + } + + ProtoSignatureWrapper payload = gaenSigner.getPayload(exposedKeys); + + return ResponseEntity.ok()//.cacheControl(CacheControl.maxAge(exposedListCacheControl)) + .header("X-PUBLISHED-UNTIL", Long.toString(publishedUntil)) + .header("Expires", RFC1123_DATE_TIME_FORMATTER.print(dateTime)) + .body(payload.getZip()); + } + + @GetMapping(value = "/buckets/{dayDateStr}") + @Loggable + @Operation(description = "Request the available release batch times for a given day") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "zipped export.bin and export.sig of all keys in that interval"), + @ApiResponse(responseCode = "400", description = "invalid starting key date, points outside of the retention range")}) + public @ResponseBody ResponseEntity getBuckets( + @PathVariable @Parameter(description = "Starting date for exposed key retrieval, as ISO-8601 format", example = "2020-06-27") String dayDateStr) { + var atStartOfDay = LocalDate.parse(dayDateStr).atStartOfDay().toInstant(ZoneOffset.UTC) + .atOffset(ZoneOffset.UTC); + var end = atStartOfDay.plusDays(1); + var now = Instant.now().atOffset(ZoneOffset.UTC); + if (!validationUtils.isDateInRange(atStartOfDay)) { + return ResponseEntity.notFound().build(); + } + var relativeUrls = new ArrayList(); + var dayBuckets = new DayBuckets(); + + String controllerMapping = this.getClass().getAnnotation(RequestMapping.class).value()[0]; + dayBuckets.setDay(dayDateStr).setRelativeUrls(relativeUrls).setDayTimestamp(atStartOfDay.toInstant().toEpochMilli()); + + while (atStartOfDay.toInstant().toEpochMilli() < Math.min(now.toInstant().toEpochMilli(), + end.toInstant().toEpochMilli())) { + relativeUrls.add(controllerMapping + "/exposed" + "/" + atStartOfDay.toInstant().toEpochMilli()); + atStartOfDay = atStartOfDay.plus(this.releaseBucketDuration); + } + + return ResponseEntity.ok(dayBuckets); + } + + private void normalizeRequestTime(long now) { + long after = Instant.now().toEpochMilli(); + long duration = after - now; + try { + Thread.sleep(Math.max(requestTime.minusMillis(duration).toMillis(), 0)); + } catch (Exception ex) { + logger.error("Couldn't equalize request time: {}", ex.toString()); + } + } + + private boolean hasNegativeRollingPeriod(GaenKey key) { + Integer rollingPeriod = key.getRollingPeriod(); + if (key.getRollingPeriod() < 0) { + logger.error("Detected key with negative rolling period {}", rollingPeriod); + return true; + } else { + return false; + } + } + + private boolean hasInvalidKeyDate(Object principal, GaenKey key) { + try { + this.validateRequest.getKeyDate(principal, key); + } + catch (InvalidDateException invalidDate) { + logger.error(invalidDate.getLocalizedMessage()); + return true; + } + return false; + } + + @ExceptionHandler({IllegalArgumentException.class, InvalidDateException.class, JsonProcessingException.class, + MethodArgumentNotValidException.class, BadBatchReleaseTimeException.class, DateTimeParseException.class}) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity invalidArguments(Exception ex) { + logger.error("Exception ({}): {}", ex.getClass().getSimpleName(), ex.getMessage(), ex); + return ResponseEntity.badRequest().build(); + } +} \ No newline at end of file diff --git a/Java/GitMaterialConfigTest.java b/Java/GitMaterialConfigTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ed1666522e9a9f803324a918e21d13591fb1d1c7 --- /dev/null +++ b/Java/GitMaterialConfigTest.java @@ -0,0 +1,349 @@ +/* + * Copyright 2021 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.thoughtworks.go.config.materials.git; + +import com.thoughtworks.go.config.*; +import com.thoughtworks.go.config.materials.*; +import com.thoughtworks.go.domain.materials.MaterialConfig; +import com.thoughtworks.go.security.GoCipher; +import com.thoughtworks.go.util.ReflectionUtil; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import static com.thoughtworks.go.helper.MaterialConfigsMother.git; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class GitMaterialConfigTest { + @Test + void shouldBePasswordAwareMaterial() { + assertTrue(PasswordAwareMaterial.class.isAssignableFrom(GitMaterialConfig.class)); + } + + @Test + void shouldSetConfigAttributes() { + GitMaterialConfig gitMaterialConfig = git(""); + + Map map = new HashMap<>(); + map.put(GitMaterialConfig.URL, "url"); + map.put(GitMaterialConfig.BRANCH, "some-branch"); + map.put(GitMaterialConfig.SHALLOW_CLONE, "true"); + map.put(ScmMaterialConfig.FOLDER, "folder"); + map.put(ScmMaterialConfig.AUTO_UPDATE, null); + map.put(ScmMaterialConfig.FILTER, "/root,/**/*.help"); + map.put(AbstractMaterialConfig.MATERIAL_NAME, "material-name"); + + gitMaterialConfig.setConfigAttributes(map); + + assertEquals("url", gitMaterialConfig.getUrl()); + assertEquals("folder", gitMaterialConfig.getFolder()); + assertEquals("some-branch", gitMaterialConfig.getBranch()); + assertEquals(new CaseInsensitiveString("material-name"), gitMaterialConfig.getName()); + assertFalse(gitMaterialConfig.isAutoUpdate()); + assertTrue(gitMaterialConfig.isShallowClone()); + assertEquals(new Filter(new IgnoredFiles("/root"), new IgnoredFiles("/**/*.help")), gitMaterialConfig.filter()); + } + + @Test + void setConfigAttributes_shouldUpdatePasswordWhenPasswordChangedBooleanChanged() throws Exception { + GitMaterialConfig gitMaterialConfig = git(""); + Map map = new HashMap<>(); + map.put(GitMaterialConfig.PASSWORD, "secret"); + map.put(GitMaterialConfig.PASSWORD_CHANGED, "1"); + + gitMaterialConfig.setConfigAttributes(map); + assertNull(ReflectionUtil.getField(gitMaterialConfig, "password")); + assertEquals("secret", gitMaterialConfig.getPassword()); + assertEquals(new GoCipher().encrypt("secret"), gitMaterialConfig.getEncryptedPassword()); + + //Dont change + map.put(GitMaterialConfig.PASSWORD, "Hehehe"); + map.put(GitMaterialConfig.PASSWORD_CHANGED, "0"); + gitMaterialConfig.setConfigAttributes(map); + + assertNull(ReflectionUtil.getField(gitMaterialConfig, "password")); + assertEquals("secret", gitMaterialConfig.getPassword()); + assertEquals(new GoCipher().encrypt("secret"), gitMaterialConfig.getEncryptedPassword()); + + map.put(GitMaterialConfig.PASSWORD, ""); + map.put(GitMaterialConfig.PASSWORD_CHANGED, "1"); + gitMaterialConfig.setConfigAttributes(map); + + assertNull(gitMaterialConfig.getPassword()); + assertNull(gitMaterialConfig.getEncryptedPassword()); + } + + @Test + void byDefaultShallowCloneShouldBeOff() { + assertFalse(git("http://url", "foo").isShallowClone()); + assertFalse(git("http://url", "foo", false).isShallowClone()); + assertFalse(git("http://url", "foo", null).isShallowClone()); + assertTrue(git("http://url", "foo", true).isShallowClone()); + } + + @Test + void shouldReturnIfAttributeMapIsNull() { + GitMaterialConfig gitMaterialConfig = git(""); + gitMaterialConfig.setConfigAttributes(null); + assertEquals(git(""), gitMaterialConfig); + } + + @Test + void shouldReturnTheUrl() { + String url = "git@github.com/my/repo"; + GitMaterialConfig config = git(url); + + assertEquals(url, config.getUrl()); + } + + @Test + void shouldReturnNullIfUrlForMaterialNotSpecified() { + GitMaterialConfig config = git(); + + assertNull(config.getUrl()); + } + + @Test + void shouldSetUrlForAMaterial() { + String url = "git@github.com/my/repo"; + GitMaterialConfig config = git(); + + config.setUrl(url); + + assertEquals(url, config.getUrl()); + } + + @Test + void shouldHandleNullWhenSettingUrlForAMaterial() { + GitMaterialConfig config = git(); + + config.setUrl(null); + + assertNull(config.getUrl()); + } + + @Test + void shouldHandleNullUrlAtTheTimeOfGitMaterialConfigCreation() { + GitMaterialConfig config = git(null); + + assertNull(config.getUrl()); + } + + @Test + void shouldHandleNullBranchWhileSettingConfigAttributes() { + GitMaterialConfig gitMaterialConfig = git("http://url", "foo"); + gitMaterialConfig.setConfigAttributes(Collections.singletonMap(GitMaterialConfig.BRANCH, null)); + assertEquals("master", gitMaterialConfig.getBranch()); + } + + @Test + void shouldHandleEmptyBranchWhileSettingConfigAttributes() { + GitMaterialConfig gitMaterialConfig = git("http://url", "foo"); + gitMaterialConfig.setConfigAttributes(Collections.singletonMap(GitMaterialConfig.BRANCH, " ")); + assertEquals("master", gitMaterialConfig.getBranch()); + } + + @Nested + class Validate { + @Test + void allowsBlankBranch() { + assertFalse(validating(git("/my/repo", null)).errors().present()); + assertFalse(validating(git("/my/repo", "")).errors().present()); + assertFalse(validating(git("/my/repo", " ")).errors().present()); + } + + @Test + void rejectsBranchWithWildcard() { + assertEquals("Branch names may not contain '*'", validating(git("/foo", "branch-*")). + errors().on(GitMaterialConfig.BRANCH)); + } + + @Test + void rejectsMalformedRefSpec() { + assertEquals("Refspec is missing a source ref", + String.join(";", validating(git("/foo", ":a")).errors(). + getAllOn(GitMaterialConfig.BRANCH))); + + assertEquals("Refspec is missing a source ref", + String.join(";", validating(git("/foo", " :b")).errors(). + getAllOn(GitMaterialConfig.BRANCH))); + + assertEquals("Refspec is missing a destination ref", + String.join(";", validating(git("/foo", "refs/foo: ")).errors(). + getAllOn(GitMaterialConfig.BRANCH))); + + assertEquals("Refspec is missing a destination ref", + String.join(";", validating(git("/foo", "refs/bar:")).errors(). + getAllOn(GitMaterialConfig.BRANCH))); + + assertEquals("Refspec is missing a source ref;Refspec is missing a destination ref", + String.join(";", validating(git("/foo", ":")).errors(). + getAllOn(GitMaterialConfig.BRANCH))); + + assertEquals("Refspec is missing a source ref;Refspec is missing a destination ref", + String.join(";", validating(git("/foo", " : ")).errors(). + getAllOn(GitMaterialConfig.BRANCH))); + + assertEquals("Refspec source must be an absolute ref (must start with `refs/`)", + String.join(";", validating(git("/foo", "a:b")).errors(). + getAllOn(GitMaterialConfig.BRANCH))); + + assertEquals("Refspecs may not contain wildcards; source and destination refs must be exact", + String.join(";", validating(git("/foo", "refs/heads/*:my-branch")).errors(). + getAllOn(GitMaterialConfig.BRANCH))); + + assertEquals("Refspecs may not contain wildcards; source and destination refs must be exact", + String.join(";", validating(git("/foo", "refs/heads/foo:branches/*")).errors(). + getAllOn(GitMaterialConfig.BRANCH))); + + assertEquals("Refspecs may not contain wildcards; source and destination refs must be exact", + String.join(";", validating(git("/foo", "refs/heads/*:branches/*")).errors(). + getAllOn(GitMaterialConfig.BRANCH))); + } + + @Test + void acceptsValidRefSpecs() { + assertTrue(validating(git("/foo", "refs/pull/123/head:pr-123")).errors().isEmpty()); + assertTrue(validating(git("/foo", "refs/pull/123/head:refs/my-prs/123")).errors().isEmpty()); + } + + @Test + void shouldEnsureUrlIsNotBlank() { + assertEquals("URL cannot be blank", validating(git("")).errors().on(GitMaterialConfig.URL)); + } + + @Test + void shouldEnsureUserNameIsNotProvidedInBothUrlAsWellAsAttributes() { + GitMaterialConfig gitMaterialConfig = git("http://bob:pass@example.com"); + gitMaterialConfig.setUserName("user"); + + assertEquals("Ambiguous credentials, must be provided either in URL or as attributes.", validating(gitMaterialConfig).errors().on(GitMaterialConfig.URL)); + } + + @Test + void shouldEnsurePasswordIsNotProvidedInBothUrlAsWellAsAttributes() { + GitMaterialConfig gitMaterialConfig = git("http://bob:pass@example.com"); + gitMaterialConfig.setPassword("pass"); + + assertEquals("Ambiguous credentials, must be provided either in URL or as attributes.", validating(gitMaterialConfig).errors().on(GitMaterialConfig.URL)); + } + + @Test + void shouldIgnoreInvalidUrlForCredentialValidation() { + GitMaterialConfig gitMaterialConfig = git("http://bob:pass@example.com##dobule-hash-is-invalid-in-url"); + gitMaterialConfig.setUserName("user"); + gitMaterialConfig.setPassword("password"); + + assertFalse(validating(gitMaterialConfig).errors().containsKey(GitMaterialConfig.URL)); + } + + @Test + void shouldBeValidWhenCredentialsAreProvidedOnlyInUrl() { + assertFalse(validating(git("http://bob:pass@example.com")).errors().containsKey(GitMaterialConfig.URL)); + } + + @Test + void shouldBeValidWhenCredentialsAreProvidedOnlyAsAttributes() { + GitMaterialConfig gitMaterialConfig = git("http://example.com"); + gitMaterialConfig.setUserName("bob"); + gitMaterialConfig.setPassword("badger"); + + assertFalse(validating(gitMaterialConfig).errors().containsKey(GitMaterialConfig.URL)); + } + + @Test + void rejectsObviouslyWrongURL() { + assertTrue(validating(git("-url-not-starting-with-an-alphanumeric-character")).errors().containsKey(GitMaterialConfig.URL)); + assertTrue(validating(git("_url-not-starting-with-an-alphanumeric-character")).errors().containsKey(GitMaterialConfig.URL)); + assertTrue(validating(git("@url-not-starting-with-an-alphanumeric-character")).errors().containsKey(GitMaterialConfig.URL)); + + assertFalse(validating(git("url-starting-with-an-alphanumeric-character")).errors().containsKey(GitMaterialConfig.URL)); + // BUG: CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection') + // + // FIXED: + assertFalse(validating(git("#{url}")).errors().containsKey(GitMaterialConfig.URL)); + } + + private GitMaterialConfig validating(GitMaterialConfig git) { + git.validate(new ConfigSaveValidationContext(null)); + return git; + } + } + + @Nested + class ValidateTree { + @Test + void shouldCallValidate() { + final MaterialConfig materialConfig = spy(git("https://example.repo")); + final ValidationContext validationContext = mockValidationContextForSecretParams(); + + materialConfig.validateTree(validationContext); + + verify(materialConfig).validate(validationContext); + } + + @Test + void shouldFailIfEncryptedPasswordIsIncorrect() { + GitMaterialConfig gitMaterialConfig = git("http://example.com"); + gitMaterialConfig.setEncryptedPassword("encryptedPassword"); + + final boolean validationResult = gitMaterialConfig.validateTree(new ConfigSaveValidationContext(null)); + + assertFalse(validationResult); + assertEquals("Encrypted password value for GitMaterial with url 'http://example.com' is " + + "invalid. This usually happens when the cipher text is modified to have an invalid value.", + gitMaterialConfig.errors().on("encryptedPassword")); + } + } + + @Nested + class Equals { + @Test + void shouldBeEqualIfObjectsHaveSameUrlBranchAndSubModuleFolder() { + final GitMaterialConfig material_1 = git("http://example.com", "master"); + material_1.setUserName("bob"); + material_1.setSubmoduleFolder("/var/lib/git"); + + final GitMaterialConfig material_2 = git("http://example.com", "master"); + material_2.setUserName("alice"); + material_2.setSubmoduleFolder("/var/lib/git"); + + assertTrue(material_1.equals(material_2)); + } + } + + @Nested + class Fingerprint { + @Test + void shouldGenerateFingerprintForGivenMaterialUrlAndBranch() { + GitMaterialConfig gitMaterialConfig = git("https://bob:pass@github.com/gocd", "feature"); + + assertEquals("755da7fb7415c8674bdf5f8a4ba48fc3e071e5de429b1308ccf8949d215bdb08", gitMaterialConfig.getFingerprint()); + } + } + + private ValidationContext mockValidationContextForSecretParams(SecretConfig... secretConfigs) { + final ValidationContext validationContext = mock(ValidationContext.class); + final CruiseConfig cruiseConfig = mock(CruiseConfig.class); + when(validationContext.getCruiseConfig()).thenReturn(cruiseConfig); + when(cruiseConfig.getSecretConfigs()).thenReturn(new SecretConfigs(secretConfigs)); + return validationContext; + } +} diff --git a/Java/GraphvizCrash.java b/Java/GraphvizCrash.java new file mode 100644 index 0000000000000000000000000000000000000000..05fc913ecf8153ed394bc7246008f292633d5c35 --- /dev/null +++ b/Java/GraphvizCrash.java @@ -0,0 +1,245 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek; + +import java.awt.Color; +import java.awt.image.BufferedImage; +import java.util.ArrayList; +import java.util.List; + +import net.sourceforge.plantuml.BackSlash; +import net.sourceforge.plantuml.OptionPrint; +import net.sourceforge.plantuml.StringUtils; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.command.CommandExecutionResult; +import net.sourceforge.plantuml.cucadiagram.dot.GraphvizUtils; +import net.sourceforge.plantuml.flashcode.FlashCodeFactory; +import net.sourceforge.plantuml.flashcode.FlashCodeUtils; +import net.sourceforge.plantuml.fun.IconLoader; +import net.sourceforge.plantuml.graphic.AbstractTextBlock; +import net.sourceforge.plantuml.graphic.GraphicPosition; +import net.sourceforge.plantuml.graphic.GraphicStrings; +import net.sourceforge.plantuml.graphic.HorizontalAlignment; +import net.sourceforge.plantuml.graphic.QuoteUtils; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.graphic.TextBlockUtils; +import net.sourceforge.plantuml.ugraphic.AffineTransformType; +import net.sourceforge.plantuml.ugraphic.PixelImage; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UImage; +import net.sourceforge.plantuml.ugraphic.color.HColor; +import net.sourceforge.plantuml.ugraphic.color.HColorUtils; +import net.sourceforge.plantuml.version.PSystemVersion; +import net.sourceforge.plantuml.version.Version; + +public class GraphvizCrash extends AbstractTextBlock implements IEntityImage { + + private final TextBlock text1; + private final BufferedImage flashCode; + private final String text; + private final boolean graphviz244onWindows; + + public GraphvizCrash(String text, boolean graphviz244onWindows, Throwable rootCause) { + this.text = text; + this.graphviz244onWindows = graphviz244onWindows; + final FlashCodeUtils utils = FlashCodeFactory.getFlashCodeUtils(); + this.flashCode = utils.exportFlashcode(text, Color.BLACK, Color.WHITE); + this.text1 = GraphicStrings.createBlackOnWhite(init(rootCause), IconLoader.getRandom(), + GraphicPosition.BACKGROUND_CORNER_TOP_RIGHT); + } + + public static List anErrorHasOccured(Throwable exception, String text) { + final List strings = new ArrayList<>(); + if (exception == null) { + strings.add("An error has occured!"); + } else { + strings.add("An error has occured : " + exception); + } + final String quote = StringUtils.rot(QuoteUtils.getSomeQuote()); + strings.add("" + quote); + strings.add(" "); + strings.add("Diagram size: " + lines(text) + " lines / " + text.length() + " characters."); + strings.add(" "); + return strings; + } + + private static int lines(String text) { + int result = 0; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == BackSlash.CHAR_NEWLINE) { + result++; + } + } + return result; + } + + public static void checkOldVersionWarning(List strings) { + final long days = (System.currentTimeMillis() - Version.compileTime()) / 1000L / 3600 / 24; + if (days >= 90) { + strings.add(" "); + strings.add("This version of PlantUML is " + days + " days old, so you should"); + strings.add("consider upgrading from https://plantuml.com/download"); + } + } + + public static void pleaseGoTo(List strings) { + strings.add(" "); + strings.add("Please go to https://plantuml.com/graphviz-dot to check your GraphViz version."); + strings.add(" "); + } + + public static void youShouldSendThisDiagram(List strings) { + strings.add("You should send this diagram and this image to plantuml@gmail.com or"); + strings.add("post to https://plantuml.com/qa to solve this issue."); + strings.add("You can try to turn arround this issue by simplifing your diagram."); + } + + public static void thisMayBeCaused(final List strings) { + strings.add("This may be caused by :"); + strings.add(" - a bug in PlantUML"); + strings.add(" - a problem in GraphViz"); + } + + private List init(Throwable rootCause) { + final List strings = anErrorHasOccured(null, text); + strings.add("For some reason, dot/GraphViz has crashed."); + strings.add(""); + strings.add("RootCause " + rootCause); + if (rootCause != null) { + strings.addAll(CommandExecutionResult.getStackTrace(rootCause)); + } + strings.add(""); + strings.add("This has been generated with PlantUML (" + Version.versionString() + ")."); + checkOldVersionWarning(strings); + strings.add(" "); + addProperties(strings); + strings.add(" "); + try { + final String dotVersion = GraphvizUtils.dotVersion(); + strings.add("Default dot version: " + dotVersion); + } catch (Throwable e) { + strings.add("Cannot determine dot version: " + e.toString()); + } + pleaseGoTo(strings); + youShouldSendThisDiagram(strings); + if (flashCode != null) { + addDecodeHint(strings); + } + + return strings; + } + + private List getText2() { + final List strings = new ArrayList<>(); + strings.add(" "); + strings.add("It looks like you are running GraphViz 2.44 under Windows."); + strings.add("If you have just installed GraphViz, you may have to execute"); + strings.add("the post-install command dot -c like in the following example:"); + return strings; + } + + private List getText3() { + final List strings = new ArrayList<>(); + strings.add(" "); + strings.add("You may have to have Administrator rights to avoid the following error message:"); + return strings; + } + + public static void addDecodeHint(final List strings) { + strings.add(" "); + strings.add(" Diagram source: (Use http://zxing.org/w/decode.jspx to decode the qrcode)"); + } + + public static void addProperties(final List strings) { + strings.addAll(OptionPrint.interestingProperties()); + strings.addAll(OptionPrint.interestingValues()); + } + + public boolean isHidden() { + return false; + } + + public HColor getBackcolor() { + return HColorUtils.WHITE; + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + return getMain().calculateDimension(stringBounder); + } + + public void drawU(UGraphic ug) { + getMain().drawU(ug); + } + + private TextBlock getMain() { + TextBlock result = text1; + if (flashCode != null) { + final UImage flash = new UImage(new PixelImage(flashCode, AffineTransformType.TYPE_NEAREST_NEIGHBOR)) + .scale(3); + result = TextBlockUtils.mergeTB(result, flash, HorizontalAlignment.LEFT); + } + + if (graphviz244onWindows) { + final TextBlock text2 = GraphicStrings.createBlackOnWhite(getText2()); + result = TextBlockUtils.mergeTB(result, text2, HorizontalAlignment.LEFT); + + final UImage dotc = new UImage(new PixelImage(PSystemVersion.getDotc(), AffineTransformType.TYPE_BILINEAR)); + result = TextBlockUtils.mergeTB(result, dotc, HorizontalAlignment.LEFT); + + final TextBlock text3 = GraphicStrings.createBlackOnWhite(getText3()); + result = TextBlockUtils.mergeTB(result, text3, HorizontalAlignment.LEFT); + + final UImage dotd = new UImage(new PixelImage(PSystemVersion.getDotd(), AffineTransformType.TYPE_BILINEAR)); + result = TextBlockUtils.mergeTB(result, dotd, HorizontalAlignment.LEFT); + } + + return result; + } + + public ShapeType getShapeType() { + return ShapeType.RECTANGLE; + } + + public Margins getShield(StringBounder stringBounder) { + return Margins.NONE; + } + + public double getOverscanX(StringBounder stringBounder) { + return 0; + } + +} diff --git a/Java/HTMLScanner.java b/Java/HTMLScanner.java new file mode 100644 index 0000000000000000000000000000000000000000..ac37beba0cc2af33758ff502ce773a0aff461e78 --- /dev/null +++ b/Java/HTMLScanner.java @@ -0,0 +1,3844 @@ +/* + * Copyright 2002-2009 Andy Clark, Marc Guillemot + * + * 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.cyberneko.html; + +import java.io.EOFException; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.UnsupportedEncodingException; +import java.net.URL; +import java.util.BitSet; +import java.util.Locale; +import java.util.Stack; + +import org.apache.xerces.util.EncodingMap; +import org.apache.xerces.util.NamespaceSupport; +import org.apache.xerces.util.URI; +import org.apache.xerces.util.XMLAttributesImpl; +import org.apache.xerces.util.XMLResourceIdentifierImpl; +import org.apache.xerces.util.XMLStringBuffer; +import org.apache.xerces.xni.Augmentations; +import org.apache.xerces.xni.NamespaceContext; +import org.apache.xerces.xni.QName; +import org.apache.xerces.xni.XMLAttributes; +import org.apache.xerces.xni.XMLDocumentHandler; +import org.apache.xerces.xni.XMLLocator; +import org.apache.xerces.xni.XMLResourceIdentifier; +import org.apache.xerces.xni.XMLString; +import org.apache.xerces.xni.XNIException; +import org.apache.xerces.xni.parser.XMLComponentManager; +import org.apache.xerces.xni.parser.XMLConfigurationException; +import org.apache.xerces.xni.parser.XMLDocumentScanner; +import org.apache.xerces.xni.parser.XMLInputSource; +import org.cyberneko.html.xercesbridge.XercesBridge; + +/** + * A simple HTML scanner. This scanner makes no attempt to balance tags + * or fix other problems in the source document — it just scans what + * it can and generates XNI document "events", ignoring errors of all + * kinds. + *

+ * This component recognizes the following features: + *

    + *
  • http://cyberneko.org/html/features/augmentations + *
  • http://cyberneko.org/html/features/report-errors + *
  • http://apache.org/xml/features/scanner/notify-char-refs + *
  • http://apache.org/xml/features/scanner/notify-builtin-refs + *
  • http://cyberneko.org/html/features/scanner/notify-builtin-refs + *
  • http://cyberneko.org/html/features/scanner/fix-mswindows-refs + *
  • http://cyberneko.org/html/features/scanner/script/strip-cdata-delims + *
  • http://cyberneko.org/html/features/scanner/script/strip-comment-delims + *
  • http://cyberneko.org/html/features/scanner/style/strip-cdata-delims + *
  • http://cyberneko.org/html/features/scanner/style/strip-comment-delims + *
  • http://cyberneko.org/html/features/scanner/ignore-specified-charset + *
  • http://cyberneko.org/html/features/scanner/cdata-sections + *
  • http://cyberneko.org/html/features/override-doctype + *
  • http://cyberneko.org/html/features/insert-doctype + *
  • http://cyberneko.org/html/features/parse-noscript-content + *
  • http://cyberneko.org/html/features/scanner/allow-selfclosing-iframe + *
  • http://cyberneko.org/html/features/scanner/allow-selfclosing-tags + *
+ *

+ * This component recognizes the following properties: + *

    + *
  • http://cyberneko.org/html/properties/names/elems + *
  • http://cyberneko.org/html/properties/names/attrs + *
  • http://cyberneko.org/html/properties/default-encoding + *
  • http://cyberneko.org/html/properties/error-reporter + *
  • http://cyberneko.org/html/properties/doctype/pubid + *
  • http://cyberneko.org/html/properties/doctype/sysid + *
+ * + * @see HTMLElements + * @see HTMLEntities + * + * @author Andy Clark + * @author Marc Guillemot + * @author Ahmed Ashour + * + * @version $Id: HTMLScanner.java,v 1.19 2005/06/14 05:52:37 andyc Exp $ + */ +public class HTMLScanner + implements XMLDocumentScanner, XMLLocator, HTMLComponent { + + // + // Constants + // + + // doctype info: HTML 4.01 strict + + /** HTML 4.01 strict public identifier ("-//W3C//DTD HTML 4.01//EN"). */ + public static final String HTML_4_01_STRICT_PUBID = "-//W3C//DTD HTML 4.01//EN"; + + /** HTML 4.01 strict system identifier ("http://www.w3.org/TR/html4/strict.dtd"). */ + public static final String HTML_4_01_STRICT_SYSID = "http://www.w3.org/TR/html4/strict.dtd"; + + // doctype info: HTML 4.01 loose + + /** HTML 4.01 transitional public identifier ("-//W3C//DTD HTML 4.01 Transitional//EN"). */ + public static final String HTML_4_01_TRANSITIONAL_PUBID = "-//W3C//DTD HTML 4.01 Transitional//EN"; + + /** HTML 4.01 transitional system identifier ("http://www.w3.org/TR/html4/loose.dtd"). */ + public static final String HTML_4_01_TRANSITIONAL_SYSID = "http://www.w3.org/TR/html4/loose.dtd"; + + // doctype info: HTML 4.01 frameset + + /** HTML 4.01 frameset public identifier ("-//W3C//DTD HTML 4.01 Frameset//EN"). */ + public static final String HTML_4_01_FRAMESET_PUBID = "-//W3C//DTD HTML 4.01 Frameset//EN"; + + /** HTML 4.01 frameset system identifier ("http://www.w3.org/TR/html4/frameset.dtd"). */ + public static final String HTML_4_01_FRAMESET_SYSID = "http://www.w3.org/TR/html4/frameset.dtd"; + + // features + + /** Include infoset augmentations. */ + protected static final String AUGMENTATIONS = "http://cyberneko.org/html/features/augmentations"; + + /** Report errors. */ + protected static final String REPORT_ERRORS = "http://cyberneko.org/html/features/report-errors"; + + /** Notify character entity references (e.g. &#32;, &#x20;, etc). */ + public static final String NOTIFY_CHAR_REFS = "http://apache.org/xml/features/scanner/notify-char-refs"; + + /** + * Notify handler of built-in entity references (e.g. &amp;, + * &lt;, etc). + *

+ * Note: + * This only applies to the five pre-defined XML general entities. + * Specifically, "amp", "lt", "gt", "quot", and "apos". This is done + * for compatibility with the Xerces feature. + *

+ * To be notified of the built-in entity references in HTML, set the + * http://cyberneko.org/html/features/scanner/notify-builtin-refs + * feature to true. + */ + public static final String NOTIFY_XML_BUILTIN_REFS = "http://apache.org/xml/features/scanner/notify-builtin-refs"; + + /** + * Notify handler of built-in entity references (e.g. &nobr;, + * &copy;, etc). + *

+ * Note: + * This includes the five pre-defined XML general entities. + */ + public static final String NOTIFY_HTML_BUILTIN_REFS = "http://cyberneko.org/html/features/scanner/notify-builtin-refs"; + + /** Fix Microsoft Windows® character entity references. */ + public static final String FIX_MSWINDOWS_REFS = "http://cyberneko.org/html/features/scanner/fix-mswindows-refs"; + + /** + * Strip HTML comment delimiters ("<!−−" and + * "−−>") from SCRIPT tag contents. + */ + public static final String SCRIPT_STRIP_COMMENT_DELIMS = "http://cyberneko.org/html/features/scanner/script/strip-comment-delims"; + + /** + * Strip XHTML CDATA delimiters ("<![CDATA[" and "]]>") from + * SCRIPT tag contents. + */ + public static final String SCRIPT_STRIP_CDATA_DELIMS = "http://cyberneko.org/html/features/scanner/script/strip-cdata-delims"; + + /** + * Strip HTML comment delimiters ("<!−−" and + * "−−>") from STYLE tag contents. + */ + public static final String STYLE_STRIP_COMMENT_DELIMS = "http://cyberneko.org/html/features/scanner/style/strip-comment-delims"; + + /** + * Strip XHTML CDATA delimiters ("<![CDATA[" and "]]>") from + * STYLE tag contents. + */ + public static final String STYLE_STRIP_CDATA_DELIMS = "http://cyberneko.org/html/features/scanner/style/strip-cdata-delims"; + + /** + * Ignore specified charset found in the <meta equiv='Content-Type' + * content='text/html;charset=…'> tag or in the <?xml … encoding='…'> processing instruction + */ + public static final String IGNORE_SPECIFIED_CHARSET = "http://cyberneko.org/html/features/scanner/ignore-specified-charset"; + + /** Scan CDATA sections. */ + public static final String CDATA_SECTIONS = "http://cyberneko.org/html/features/scanner/cdata-sections"; + + /** Override doctype declaration public and system identifiers. */ + public static final String OVERRIDE_DOCTYPE = "http://cyberneko.org/html/features/override-doctype"; + + /** Insert document type declaration. */ + public static final String INSERT_DOCTYPE = "http://cyberneko.org/html/features/insert-doctype"; + + /** Parse <noscript>...</noscript> content */ + public static final String PARSE_NOSCRIPT_CONTENT = "http://cyberneko.org/html/features/parse-noscript-content"; + + /** Allows self closing <iframe/> tag */ + public static final String ALLOW_SELFCLOSING_IFRAME = "http://cyberneko.org/html/features/scanner/allow-selfclosing-iframe"; + + /** Allows self closing tags e.g. <div/> (XHTML) */ + public static final String ALLOW_SELFCLOSING_TAGS = "http://cyberneko.org/html/features/scanner/allow-selfclosing-tags"; + + /** Normalize attribute values. */ + protected static final String NORMALIZE_ATTRIBUTES = "http://cyberneko.org/html/features/scanner/normalize-attrs"; + + /** Recognized features. */ + private static final String[] RECOGNIZED_FEATURES = { + AUGMENTATIONS, + REPORT_ERRORS, + NOTIFY_CHAR_REFS, + NOTIFY_XML_BUILTIN_REFS, + NOTIFY_HTML_BUILTIN_REFS, + FIX_MSWINDOWS_REFS, + SCRIPT_STRIP_CDATA_DELIMS, + SCRIPT_STRIP_COMMENT_DELIMS, + STYLE_STRIP_CDATA_DELIMS, + STYLE_STRIP_COMMENT_DELIMS, + IGNORE_SPECIFIED_CHARSET, + CDATA_SECTIONS, + OVERRIDE_DOCTYPE, + INSERT_DOCTYPE, + NORMALIZE_ATTRIBUTES, + PARSE_NOSCRIPT_CONTENT, + ALLOW_SELFCLOSING_IFRAME, + ALLOW_SELFCLOSING_TAGS, + }; + + /** Recognized features defaults. */ + private static final Boolean[] RECOGNIZED_FEATURES_DEFAULTS = { + null, + null, + Boolean.FALSE, + Boolean.FALSE, + Boolean.FALSE, + Boolean.FALSE, + Boolean.FALSE, + Boolean.FALSE, + Boolean.FALSE, + Boolean.FALSE, + Boolean.FALSE, + Boolean.FALSE, + Boolean.FALSE, + Boolean.FALSE, + Boolean.FALSE, + Boolean.TRUE, + Boolean.FALSE, + Boolean.FALSE, + }; + + // properties + + /** Modify HTML element names: { "upper", "lower", "default" }. */ + protected static final String NAMES_ELEMS = "http://cyberneko.org/html/properties/names/elems"; + + /** Modify HTML attribute names: { "upper", "lower", "default" }. */ + protected static final String NAMES_ATTRS = "http://cyberneko.org/html/properties/names/attrs"; + + /** Default encoding. */ + protected static final String DEFAULT_ENCODING = "http://cyberneko.org/html/properties/default-encoding"; + + /** Error reporter. */ + protected static final String ERROR_REPORTER = "http://cyberneko.org/html/properties/error-reporter"; + + /** Doctype declaration public identifier. */ + protected static final String DOCTYPE_PUBID = "http://cyberneko.org/html/properties/doctype/pubid"; + + /** Doctype declaration system identifier. */ + protected static final String DOCTYPE_SYSID = "http://cyberneko.org/html/properties/doctype/sysid"; + + /** Recognized properties. */ + private static final String[] RECOGNIZED_PROPERTIES = { + NAMES_ELEMS, + NAMES_ATTRS, + DEFAULT_ENCODING, + ERROR_REPORTER, + DOCTYPE_PUBID, + DOCTYPE_SYSID, + }; + + /** Recognized properties defaults. */ + private static final Object[] RECOGNIZED_PROPERTIES_DEFAULTS = { + null, + null, + "Windows-1252", + null, + HTML_4_01_TRANSITIONAL_PUBID, + HTML_4_01_TRANSITIONAL_SYSID, + }; + + // states + + /** State: content. */ + protected static final short STATE_CONTENT = 0; + + /** State: markup bracket. */ + protected static final short STATE_MARKUP_BRACKET = 1; + + /** State: start document. */ + protected static final short STATE_START_DOCUMENT = 10; + + /** State: end document. */ + protected static final short STATE_END_DOCUMENT = 11; + + // modify HTML names + + /** Don't modify HTML names. */ + protected static final short NAMES_NO_CHANGE = 0; + + /** Uppercase HTML names. */ + protected static final short NAMES_UPPERCASE = 1; + + /** Lowercase HTML names. */ + protected static final short NAMES_LOWERCASE = 2; + + // defaults + + /** Default buffer size. */ + protected static final int DEFAULT_BUFFER_SIZE = 2048; + + // debugging + + /** Set to true to debug changes in the scanner. */ + private static final boolean DEBUG_SCANNER = false; + + /** Set to true to debug changes in the scanner state. */ + private static final boolean DEBUG_SCANNER_STATE = false; + + /** Set to true to debug the buffer. */ + private static final boolean DEBUG_BUFFER = false; + + /** Set to true to debug character encoding handling. */ + private static final boolean DEBUG_CHARSET = false; + + /** Set to true to debug callbacks. */ + protected static final boolean DEBUG_CALLBACKS = false; + + // static vars + + /** Synthesized event info item. */ + protected static final HTMLEventInfo SYNTHESIZED_ITEM = + new HTMLEventInfo.SynthesizedItem(); + + private final static BitSet ENTITY_CHARS = new BitSet(); + static { + final String str = "-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; + for (int i = 0; i < str.length(); ++i) { + char c = str.charAt(i); + ENTITY_CHARS.set(c); + } + } + // + // Data + // + + // features + + /** Augmentations. */ + protected boolean fAugmentations; + + /** Report errors. */ + protected boolean fReportErrors; + + /** Notify character entity references. */ + protected boolean fNotifyCharRefs; + + /** Notify XML built-in general entity references. */ + protected boolean fNotifyXmlBuiltinRefs; + + /** Notify HTML built-in general entity references. */ + protected boolean fNotifyHtmlBuiltinRefs; + + /** Fix Microsoft Windows® character entity references. */ + protected boolean fFixWindowsCharRefs; + + /** Strip CDATA delimiters from SCRIPT tags. */ + protected boolean fScriptStripCDATADelims; + + /** Strip comment delimiters from SCRIPT tags. */ + protected boolean fScriptStripCommentDelims; + + /** Strip CDATA delimiters from STYLE tags. */ + protected boolean fStyleStripCDATADelims; + + /** Strip comment delimiters from STYLE tags. */ + protected boolean fStyleStripCommentDelims; + + /** Ignore specified character set. */ + protected boolean fIgnoreSpecifiedCharset; + + /** CDATA sections. */ + protected boolean fCDATASections; + + /** Override doctype declaration public and system identifiers. */ + protected boolean fOverrideDoctype; + + /** Insert document type declaration. */ + protected boolean fInsertDoctype; + + /** Normalize attribute values. */ + protected boolean fNormalizeAttributes; + + /** Parse noscript content. */ + protected boolean fParseNoScriptContent; + + /** Parse noframes content. */ + protected boolean fParseNoFramesContent; + + /** Allows self closing iframe tags. */ + protected boolean fAllowSelfclosingIframe; + + /** Allows self closing tags. */ + protected boolean fAllowSelfclosingTags; + + // properties + + /** Modify HTML element names. */ + protected short fNamesElems; + + /** Modify HTML attribute names. */ + protected short fNamesAttrs; + + /** Default encoding. */ + protected String fDefaultIANAEncoding; + + /** Error reporter. */ + protected HTMLErrorReporter fErrorReporter; + + /** Doctype declaration public identifier. */ + protected String fDoctypePubid; + + /** Doctype declaration system identifier. */ + protected String fDoctypeSysid; + + // boundary locator information + + /** Beginning line number. */ + protected int fBeginLineNumber; + + /** Beginning column number. */ + protected int fBeginColumnNumber; + + /** Beginning character offset in the file. */ + protected int fBeginCharacterOffset; + + /** Ending line number. */ + protected int fEndLineNumber; + + /** Ending column number. */ + protected int fEndColumnNumber; + + /** Ending character offset in the file. */ + protected int fEndCharacterOffset; + + // state + + /** The playback byte stream. */ + protected PlaybackInputStream fByteStream; + + /** Current entity. */ + protected CurrentEntity fCurrentEntity; + + /** The current entity stack. */ + protected final Stack fCurrentEntityStack = new Stack(); + + /** The current scanner. */ + protected Scanner fScanner; + + /** The current scanner state. */ + protected short fScannerState; + + /** The document handler. */ + protected XMLDocumentHandler fDocumentHandler; + + /** Auto-detected IANA encoding. */ + protected String fIANAEncoding; + + /** Auto-detected Java encoding. */ + protected String fJavaEncoding; + + /** True if the encoding matches "ISO-8859-*". */ + protected boolean fIso8859Encoding; + + /** Element count. */ + protected int fElementCount; + + /** Element depth. */ + protected int fElementDepth; + + // scanners + + /** Content scanner. */ + protected Scanner fContentScanner = new ContentScanner(); + + /** + * Special scanner used for elements whose content needs to be scanned + * as plain text, ignoring markup such as elements and entity references. + * For example: <SCRIPT> and <COMMENT>. + */ + protected SpecialScanner fSpecialScanner = new SpecialScanner(); + + // temp vars + + /** String buffer. */ + protected final XMLStringBuffer fStringBuffer = new XMLStringBuffer(1024); + + /** String buffer. */ + private final XMLStringBuffer fStringBuffer2 = new XMLStringBuffer(1024); + + /** Non-normalized attribute string buffer. */ + private final XMLStringBuffer fNonNormAttr = new XMLStringBuffer(128); + + /** Augmentations. */ + private final HTMLAugmentations fInfosetAugs = new HTMLAugmentations(); + + /** Location infoset item. */ + private final LocationItem fLocationItem = new LocationItem(); + + /** Single boolean array. */ + private final boolean[] fSingleBoolean = { false }; + + /** Resource identifier. */ + private final XMLResourceIdentifierImpl fResourceId = new XMLResourceIdentifierImpl(); + + private final char REPLACEMENT_CHARACTER = '\uFFFD'; // the � character + + // + // Public methods + // + + /** + * Pushes an input source onto the current entity stack. This + * enables the scanner to transparently scan new content (e.g. + * the output written by an embedded script). At the end of the + * current entity, the scanner returns where it left off at the + * time this entity source was pushed. + *

+ * Note: + * This functionality is experimental at this time and is + * subject to change in future releases of NekoHTML. + * + * @param inputSource The new input source to start scanning. + * @see #evaluateInputSource(XMLInputSource) + */ + public void pushInputSource(XMLInputSource inputSource) { + final Reader reader = getReader(inputSource); + + fCurrentEntityStack.push(fCurrentEntity); + String encoding = inputSource.getEncoding(); + String publicId = inputSource.getPublicId(); + String baseSystemId = inputSource.getBaseSystemId(); + String literalSystemId = inputSource.getSystemId(); + String expandedSystemId = expandSystemId(literalSystemId, baseSystemId); + fCurrentEntity = new CurrentEntity(reader, encoding, + publicId, baseSystemId, + literalSystemId, expandedSystemId); + } // pushInputSource(XMLInputSource) + + private Reader getReader(final XMLInputSource inputSource) { + Reader reader = inputSource.getCharacterStream(); + if (reader == null) { + try { + return new InputStreamReader(inputSource.getByteStream(), fJavaEncoding); + } + catch (final UnsupportedEncodingException e) { + // should not happen as this encoding is already used to parse the "main" source + } + } + return reader; + } + + /** + * Immediately evaluates an input source and add the new content (e.g. + * the output written by an embedded script). + * + * @param inputSource The new input source to start evaluating. + * @see #pushInputSource(XMLInputSource) + */ + public void evaluateInputSource(XMLInputSource inputSource) { + final Scanner previousScanner = fScanner; + final short previousScannerState = fScannerState; + final CurrentEntity previousEntity = fCurrentEntity; + final Reader reader = getReader(inputSource); + + String encoding = inputSource.getEncoding(); + String publicId = inputSource.getPublicId(); + String baseSystemId = inputSource.getBaseSystemId(); + String literalSystemId = inputSource.getSystemId(); + String expandedSystemId = expandSystemId(literalSystemId, baseSystemId); + fCurrentEntity = new CurrentEntity(reader, encoding, + publicId, baseSystemId, + literalSystemId, expandedSystemId); + setScanner(fContentScanner); + setScannerState(STATE_CONTENT); + try { + do { + fScanner.scan(false); + } while (fScannerState != STATE_END_DOCUMENT); + } + catch (final IOException e) { + // ignore + } + setScanner(previousScanner); + setScannerState(previousScannerState); + fCurrentEntity = previousEntity; + } // evaluateInputSource(XMLInputSource) + + /** + * Cleans up used resources. For example, if scanning is terminated + * early, then this method ensures all remaining open streams are + * closed. + * + * @param closeall Close all streams, including the original. + * This is used in cases when the application has + * opened the original document stream and should + * be responsible for closing it. + */ + public void cleanup(boolean closeall) { + int size = fCurrentEntityStack.size(); + if (size > 0) { + // current entity is not the original, so close it + if (fCurrentEntity != null) { + fCurrentEntity.closeQuietly(); + } + // close remaining streams + for (int i = closeall ? 0 : 1; i < size; i++) { + fCurrentEntity = (CurrentEntity) fCurrentEntityStack.pop(); + fCurrentEntity.closeQuietly(); + } + } + else if (closeall && fCurrentEntity != null) { + fCurrentEntity.closeQuietly(); + } + } // cleanup(boolean) + + // + // XMLLocator methods + // + + /** Returns the encoding. */ + public String getEncoding() { + return fCurrentEntity != null ? fCurrentEntity.encoding : null; + } // getEncoding():String + + /** Returns the public identifier. */ + public String getPublicId() { + return fCurrentEntity != null ? fCurrentEntity.publicId : null; + } // getPublicId():String + + /** Returns the base system identifier. */ + public String getBaseSystemId() { + return fCurrentEntity != null ? fCurrentEntity.baseSystemId : null; + } // getBaseSystemId():String + + /** Returns the literal system identifier. */ + public String getLiteralSystemId() { + return fCurrentEntity != null ? fCurrentEntity.literalSystemId : null; + } // getLiteralSystemId():String + + /** Returns the expanded system identifier. */ + public String getExpandedSystemId() { + return fCurrentEntity != null ? fCurrentEntity.expandedSystemId : null; + } // getExpandedSystemId():String + + /** Returns the current line number. */ + public int getLineNumber() { + return fCurrentEntity != null ? fCurrentEntity.getLineNumber() : -1; + } // getLineNumber():int + + /** Returns the current column number. */ + public int getColumnNumber() { + return fCurrentEntity != null ? fCurrentEntity.getColumnNumber() : -1; + } // getColumnNumber():int + + /** Returns the XML version. */ + public String getXMLVersion() { + return fCurrentEntity != null ? fCurrentEntity.version : null; + } // getXMLVersion():String + + /** Returns the character offset. */ + public int getCharacterOffset() { + return fCurrentEntity != null ? fCurrentEntity.getCharacterOffset() : -1; + } // getCharacterOffset():int + + // + // HTMLComponent methods + // + + /** Returns the default state for a feature. */ + public Boolean getFeatureDefault(String featureId) { + int length = RECOGNIZED_FEATURES != null ? RECOGNIZED_FEATURES.length : 0; + for (int i = 0; i < length; i++) { + if (RECOGNIZED_FEATURES[i].equals(featureId)) { + return RECOGNIZED_FEATURES_DEFAULTS[i]; + } + } + return null; + } // getFeatureDefault(String):Boolean + + /** Returns the default state for a property. */ + public Object getPropertyDefault(String propertyId) { + int length = RECOGNIZED_PROPERTIES != null ? RECOGNIZED_PROPERTIES.length : 0; + for (int i = 0; i < length; i++) { + if (RECOGNIZED_PROPERTIES[i].equals(propertyId)) { + return RECOGNIZED_PROPERTIES_DEFAULTS[i]; + } + } + return null; + } // getPropertyDefault(String):Object + + // + // XMLComponent methods + // + + /** Returns recognized features. */ + public String[] getRecognizedFeatures() { + return RECOGNIZED_FEATURES; + } // getRecognizedFeatures():String[] + + /** Returns recognized properties. */ + public String[] getRecognizedProperties() { + return RECOGNIZED_PROPERTIES; + } // getRecognizedProperties():String[] + + /** Resets the component. */ + public void reset(XMLComponentManager manager) + throws XMLConfigurationException { + + // get features + fAugmentations = manager.getFeature(AUGMENTATIONS); + fReportErrors = manager.getFeature(REPORT_ERRORS); + fNotifyCharRefs = manager.getFeature(NOTIFY_CHAR_REFS); + fNotifyXmlBuiltinRefs = manager.getFeature(NOTIFY_XML_BUILTIN_REFS); + fNotifyHtmlBuiltinRefs = manager.getFeature(NOTIFY_HTML_BUILTIN_REFS); + fFixWindowsCharRefs = manager.getFeature(FIX_MSWINDOWS_REFS); + fScriptStripCDATADelims = manager.getFeature(SCRIPT_STRIP_CDATA_DELIMS); + fScriptStripCommentDelims = manager.getFeature(SCRIPT_STRIP_COMMENT_DELIMS); + fStyleStripCDATADelims = manager.getFeature(STYLE_STRIP_CDATA_DELIMS); + fStyleStripCommentDelims = manager.getFeature(STYLE_STRIP_COMMENT_DELIMS); + fIgnoreSpecifiedCharset = manager.getFeature(IGNORE_SPECIFIED_CHARSET); + fCDATASections = manager.getFeature(CDATA_SECTIONS); + fOverrideDoctype = manager.getFeature(OVERRIDE_DOCTYPE); + fInsertDoctype = manager.getFeature(INSERT_DOCTYPE); + fNormalizeAttributes = manager.getFeature(NORMALIZE_ATTRIBUTES); + fParseNoScriptContent = manager.getFeature(PARSE_NOSCRIPT_CONTENT); + fAllowSelfclosingIframe = manager.getFeature(ALLOW_SELFCLOSING_IFRAME); + fAllowSelfclosingTags = manager.getFeature(ALLOW_SELFCLOSING_TAGS); + + // get properties + fNamesElems = getNamesValue(String.valueOf(manager.getProperty(NAMES_ELEMS))); + fNamesAttrs = getNamesValue(String.valueOf(manager.getProperty(NAMES_ATTRS))); + fDefaultIANAEncoding = String.valueOf(manager.getProperty(DEFAULT_ENCODING)); + fErrorReporter = (HTMLErrorReporter)manager.getProperty(ERROR_REPORTER); + fDoctypePubid = String.valueOf(manager.getProperty(DOCTYPE_PUBID)); + fDoctypeSysid = String.valueOf(manager.getProperty(DOCTYPE_SYSID)); + + } // reset(XMLComponentManager) + + /** Sets a feature. */ + public void setFeature(final String featureId, final boolean state) { + + if (featureId.equals(AUGMENTATIONS)) { + fAugmentations = state; + } + else if (featureId.equals(IGNORE_SPECIFIED_CHARSET)) { + fIgnoreSpecifiedCharset = state; + } + else if (featureId.equals(NOTIFY_CHAR_REFS)) { + fNotifyCharRefs = state; + } + else if (featureId.equals(NOTIFY_XML_BUILTIN_REFS)) { + fNotifyXmlBuiltinRefs = state; + } + else if (featureId.equals(NOTIFY_HTML_BUILTIN_REFS)) { + fNotifyHtmlBuiltinRefs = state; + } + else if (featureId.equals(FIX_MSWINDOWS_REFS)) { + fFixWindowsCharRefs = state; + } + else if (featureId.equals(SCRIPT_STRIP_CDATA_DELIMS)) { + fScriptStripCDATADelims = state; + } + else if (featureId.equals(SCRIPT_STRIP_COMMENT_DELIMS)) { + fScriptStripCommentDelims = state; + } + else if (featureId.equals(STYLE_STRIP_CDATA_DELIMS)) { + fStyleStripCDATADelims = state; + } + else if (featureId.equals(STYLE_STRIP_COMMENT_DELIMS)) { + fStyleStripCommentDelims = state; + } + else if (featureId.equals(PARSE_NOSCRIPT_CONTENT)) { + fParseNoScriptContent = state; + } + else if (featureId.equals(ALLOW_SELFCLOSING_IFRAME)) { + fAllowSelfclosingIframe = state; + } + else if (featureId.equals(ALLOW_SELFCLOSING_TAGS)) { + fAllowSelfclosingTags = state; + } + + } // setFeature(String,boolean) + + /** Sets a property. */ + public void setProperty(String propertyId, Object value) + throws XMLConfigurationException { + + if (propertyId.equals(NAMES_ELEMS)) { + fNamesElems = getNamesValue(String.valueOf(value)); + return; + } + + if (propertyId.equals(NAMES_ATTRS)) { + fNamesAttrs = getNamesValue(String.valueOf(value)); + return; + } + + if (propertyId.equals(DEFAULT_ENCODING)) { + fDefaultIANAEncoding = String.valueOf(value); + return; + } + + } // setProperty(String,Object) + + // + // XMLDocumentScanner methods + // + + /** Sets the input source. */ + public void setInputSource(XMLInputSource source) throws IOException { + + // reset state + fElementCount = 0; + fElementDepth = -1; + fByteStream = null; + fCurrentEntityStack.removeAllElements(); + + fBeginLineNumber = 1; + fBeginColumnNumber = 1; + fBeginCharacterOffset = 0; + fEndLineNumber = fBeginLineNumber; + fEndColumnNumber = fBeginColumnNumber; + fEndCharacterOffset = fBeginCharacterOffset; + + // reset encoding information + fIANAEncoding = fDefaultIANAEncoding; + fJavaEncoding = fIANAEncoding; + + // get location information + String encoding = source.getEncoding(); + String publicId = source.getPublicId(); + String baseSystemId = source.getBaseSystemId(); + String literalSystemId = source.getSystemId(); + String expandedSystemId = expandSystemId(literalSystemId, baseSystemId); + + // open stream + Reader reader = source.getCharacterStream(); + if (reader == null) { + InputStream inputStream = source.getByteStream(); + if (inputStream == null) { + URL url = new URL(expandedSystemId); + inputStream = url.openStream(); + } + fByteStream = new PlaybackInputStream(inputStream); + String[] encodings = new String[2]; + if (encoding == null) { + fByteStream.detectEncoding(encodings); + } + else { + encodings[0] = encoding; + } + if (encodings[0] == null) { + encodings[0] = fDefaultIANAEncoding; + if (fReportErrors) { + fErrorReporter.reportWarning("HTML1000", null); + } + } + if (encodings[1] == null) { + encodings[1] = EncodingMap.getIANA2JavaMapping(encodings[0].toUpperCase(Locale.ENGLISH)); + if (encodings[1] == null) { + encodings[1] = encodings[0]; + if (fReportErrors) { + fErrorReporter.reportWarning("HTML1001", new Object[]{encodings[0]}); + } + } + } + fIANAEncoding = encodings[0]; + fJavaEncoding = encodings[1]; + /* PATCH: Asgeir Asgeirsson */ + fIso8859Encoding = fIANAEncoding == null + || fIANAEncoding.toUpperCase(Locale.ENGLISH).startsWith("ISO-8859") + || fIANAEncoding.equalsIgnoreCase(fDefaultIANAEncoding); + encoding = fIANAEncoding; + reader = new InputStreamReader(fByteStream, fJavaEncoding); + } + fCurrentEntity = new CurrentEntity(reader, encoding, + publicId, baseSystemId, + literalSystemId, expandedSystemId); + + // set scanner and state + setScanner(fContentScanner); + setScannerState(STATE_START_DOCUMENT); + + } // setInputSource(XMLInputSource) + + /** Scans the document. */ + public boolean scanDocument(boolean complete) throws XNIException, IOException { + do { + if (!fScanner.scan(complete)) { + return false; + } + } while (complete); + return true; + } // scanDocument(boolean):boolean + + /** Sets the document handler. */ + public void setDocumentHandler(XMLDocumentHandler handler) { + fDocumentHandler = handler; + } // setDocumentHandler(XMLDocumentHandler) + + // @since Xerces 2.1.0 + + /** Returns the document handler. */ + public XMLDocumentHandler getDocumentHandler() { + return fDocumentHandler; + } // getDocumentHandler():XMLDocumentHandler + + // + // Protected static methods + // + + /** Returns the value of the specified attribute, ignoring case. */ + protected static String getValue(XMLAttributes attrs, String aname) { + int length = attrs != null ? attrs.getLength() : 0; + for (int i = 0; i < length; i++) { + if (attrs.getQName(i).equalsIgnoreCase(aname)) { + return attrs.getValue(i); + } + } + return null; + } // getValue(XMLAttributes,String):String + + /** + * Expands a system id and returns the system id as a URI, if + * it can be expanded. A return value of null means that the + * identifier is already expanded. An exception thrown + * indicates a failure to expand the id. + * + * @param systemId The systemId to be expanded. + * + * @return Returns the URI string representing the expanded system + * identifier. A null value indicates that the given + * system identifier is already expanded. + * + */ + public static String expandSystemId(String systemId, String baseSystemId) { + + // check for bad parameters id + if (systemId == null || systemId.length() == 0) { + return systemId; + } + // if id already expanded, return + try { + URI uri = new URI(systemId); + if (uri != null) { + return systemId; + } + } + catch (URI.MalformedURIException e) { + // continue on... + } + // normalize id + String id = fixURI(systemId); + + // normalize base + URI base = null; + URI uri = null; + try { + if (baseSystemId == null || baseSystemId.length() == 0 || + baseSystemId.equals(systemId)) { + String dir; + try { + dir = fixURI(System.getProperty("user.dir")); + } + catch (SecurityException se) { + dir = ""; + } + if (!dir.endsWith("/")) { + dir = dir + "/"; + } + base = new URI("file", "", dir, null, null); + } + else { + try { + base = new URI(fixURI(baseSystemId)); + } + catch (URI.MalformedURIException e) { + String dir; + try { + dir = fixURI(System.getProperty("user.dir")); + } + catch (SecurityException se) { + dir = ""; + } + if (baseSystemId.indexOf(':') != -1) { + // for xml schemas we might have baseURI with + // a specified drive + base = new URI("file", "", fixURI(baseSystemId), null, null); + } + else { + if (!dir.endsWith("/")) { + dir = dir + "/"; + } + dir = dir + fixURI(baseSystemId); + base = new URI("file", "", dir, null, null); + } + } + } + // expand id + uri = new URI(base, id); + } + catch (URI.MalformedURIException e) { + // let it go through + } + + if (uri == null) { + return systemId; + } + return uri.toString(); + + } // expandSystemId(String,String):String + + /** + * Fixes a platform dependent filename to standard URI form. + * + * @param str The string to fix. + * + * @return Returns the fixed URI string. + */ + protected static String fixURI(String str) { + + // handle platform dependent strings + str = str.replace(java.io.File.separatorChar, '/'); + + // Windows fix + if (str.length() >= 2) { + char ch1 = str.charAt(1); + // change "C:blah" to "/C:blah" + if (ch1 == ':') { + final char ch0 = String.valueOf(str.charAt(0)).toUpperCase(Locale.ENGLISH).charAt(0); + if (ch0 >= 'A' && ch0 <= 'Z') { + str = "/" + str; + } + } + // change "//blah" to "file://blah" + else if (ch1 == '/' && str.charAt(0) == '/') { + str = "file:" + str; + } + } + + // done + return str; + + } // fixURI(String):String + + /** Modifies the given name based on the specified mode. */ + protected static final String modifyName(String name, short mode) { + switch (mode) { + case NAMES_UPPERCASE: return name.toUpperCase(Locale.ENGLISH); + case NAMES_LOWERCASE: return name.toLowerCase(Locale.ENGLISH); + } + return name; + } // modifyName(String,short):String + + /** + * Converts HTML names string value to constant value. + * + * @see #NAMES_NO_CHANGE + * @see #NAMES_LOWERCASE + * @see #NAMES_UPPERCASE + */ + protected static final short getNamesValue(String value) { + if (value.equals("lower")) { + return NAMES_LOWERCASE; + } + if (value.equals("upper")) { + return NAMES_UPPERCASE; + } + return NAMES_NO_CHANGE; + } // getNamesValue(String):short + + /** + * Fixes Microsoft Windows® specific characters. + *

+ * Details about this common problem can be found at + * http://www.cs.tut.fi/~jkorpela/www/windows-chars.html + */ + protected int fixWindowsCharacter(int origChar) { + /* PATCH: Asgeir Asgeirsson */ + switch(origChar) { + case 130: return 8218; + case 131: return 402; + case 132: return 8222; + case 133: return 8230; + case 134: return 8224; + case 135: return 8225; + case 136: return 710; + case 137: return 8240; + case 138: return 352; + case 139: return 8249; + case 140: return 338; + case 145: return 8216; + case 146: return 8217; + case 147: return 8220; + case 148: return 8221; + case 149: return 8226; + case 150: return 8211; + case 151: return 8212; + case 152: return 732; + case 153: return 8482; + case 154: return 353; + case 155: return 8250; + case 156: return 339; + case 159: return 376; + } + return origChar; + } // fixWindowsCharacter(int):int + + // + // Protected methods + // + + // i/o + /** Reads a single character. */ + protected int read() throws IOException { + return fCurrentEntity.read(); + } + + + // debugging + + /** Sets the scanner. */ + protected void setScanner(Scanner scanner) { + fScanner = scanner; + if (DEBUG_SCANNER) { + System.out.print("$$$ setScanner("); + System.out.print(scanner!=null?scanner.getClass().getName():"null"); + System.out.println(");"); + } + } // setScanner(Scanner) + + /** Sets the scanner state. */ + protected void setScannerState(short state) { + fScannerState = state; + if (DEBUG_SCANNER_STATE) { + System.out.print("$$$ setScannerState("); + switch (fScannerState) { + case STATE_CONTENT: { System.out.print("STATE_CONTENT"); break; } + case STATE_MARKUP_BRACKET: { System.out.print("STATE_MARKUP_BRACKET"); break; } + case STATE_START_DOCUMENT: { System.out.print("STATE_START_DOCUMENT"); break; } + case STATE_END_DOCUMENT: { System.out.print("STATE_END_DOCUMENT"); break; } + } + System.out.println(");"); + } + } // setScannerState(short) + + // scanning + + /** Scans a DOCTYPE line. */ + protected void scanDoctype() throws IOException { + String root = null; + String pubid = null; + String sysid = null; + + if (skipSpaces()) { + root = scanName(true); + if (root == null) { + if (fReportErrors) { + fErrorReporter.reportError("HTML1014", null); + } + } + else { + root = modifyName(root, fNamesElems); + } + if (skipSpaces()) { + if (skip("PUBLIC", false)) { + skipSpaces(); + pubid = scanLiteral(); + if (skipSpaces()) { + sysid = scanLiteral(); + } + } + else if (skip("SYSTEM", false)) { + skipSpaces(); + sysid = scanLiteral(); + } + } + } + int c; + while ((c = fCurrentEntity.read()) != -1) { + if (c == '<') { + fCurrentEntity.rewind(); + break; + } + if (c == '>') { + break; + } + if (c == '[') { + skipMarkup(true); + break; + } + } + + if (fDocumentHandler != null) { + if (fOverrideDoctype) { + pubid = fDoctypePubid; + sysid = fDoctypeSysid; + } + fEndLineNumber = fCurrentEntity.getLineNumber(); + fEndColumnNumber = fCurrentEntity.getColumnNumber(); + fEndCharacterOffset = fCurrentEntity.getCharacterOffset(); + fDocumentHandler.doctypeDecl(root, pubid, sysid, locationAugs()); + } + + } // scanDoctype() + + /** Scans a quoted literal. */ + protected String scanLiteral() throws IOException { + int quote = fCurrentEntity.read(); + if (quote == '\'' || quote == '"') { + StringBuffer str = new StringBuffer(); + int c; + while ((c = fCurrentEntity.read()) != -1) { + if (c == quote) { + break; + } + if (c == '\r' || c == '\n') { + fCurrentEntity.rewind(); + // NOTE: This collapses newlines to a single space. + // [Q] Is this the right thing to do here? -Ac + skipNewlines(); + str.append(' '); + } + else if (c == '<') { + fCurrentEntity.rewind(); + break; + } + else { + appendChar(str, c); + } + } + if (c == -1) { + if (fReportErrors) { + fErrorReporter.reportError("HTML1007", null); + } + throw new EOFException(); + } + return str.toString(); + } + fCurrentEntity.rewind(); + return null; + } // scanLiteral():String + + /** Scans a name. */ + protected String scanName(final boolean strict) throws IOException { + if (DEBUG_BUFFER) { + fCurrentEntity.debugBufferIfNeeded("(scanName: "); + } + if (fCurrentEntity.offset == fCurrentEntity.length) { + if (fCurrentEntity.load(0) == -1) { + if (DEBUG_BUFFER) { + fCurrentEntity.debugBufferIfNeeded(")scanName: "); + } + return null; + } + } + int offset = fCurrentEntity.offset; + while (true) { + while (fCurrentEntity.hasNext()) { + char c = fCurrentEntity.getNextChar(); + if ((strict && (!Character.isLetterOrDigit(c) && c != '-' && c != '.' && c != ':' && c != '_')) + || (!strict && (Character.isWhitespace(c) || c == '=' || c == '/' || c == '>'))) { + fCurrentEntity.rewind(); + break; + } + } + if (fCurrentEntity.offset == fCurrentEntity.length) { + int length = fCurrentEntity.length - offset; + System.arraycopy(fCurrentEntity.buffer, offset, fCurrentEntity.buffer, 0, length); + int count = fCurrentEntity.load(length); + offset = 0; + if (count == -1) { + break; + } + } + else { + break; + } + } + int length = fCurrentEntity.offset - offset; + String name = length > 0 ? new String(fCurrentEntity.buffer, offset, length) : null; + if (DEBUG_BUFFER) { + fCurrentEntity.debugBufferIfNeeded(")scanName: ", " -> \"" + name + '"'); + } + return name; + } // scanName():String + + /** Scans an entity reference. */ + protected int scanEntityRef(final XMLStringBuffer str, final boolean content) + throws IOException { + str.clear(); + str.append('&'); + boolean endsWithSemicolon = false; + while (true) { + int c = fCurrentEntity.read(); + if (c == ';') { + str.append(';'); + endsWithSemicolon = true; + break; + } + else if (c == -1) { + break; + } + else if (!ENTITY_CHARS.get(c) && c != '#') { + fCurrentEntity.rewind(); + break; + } + appendChar(str, c); + } + + if (!endsWithSemicolon) { + if (fReportErrors) { + fErrorReporter.reportWarning("HTML1004", null); + } + } + if (str.length == 1) { + if (content && fDocumentHandler != null && fElementCount >= fElementDepth) { + fEndLineNumber = fCurrentEntity.getLineNumber(); + fEndColumnNumber = fCurrentEntity.getColumnNumber(); + fEndCharacterOffset = fCurrentEntity.getCharacterOffset(); + fDocumentHandler.characters(str, locationAugs()); + } + return -1; + } + + final String name; + if (endsWithSemicolon) + name = str.toString().substring(1, str.length -1); + else + name = str.toString().substring(1); + + if (name.startsWith("#")) { + int value = -1; + try { + if (name.startsWith("#x") || name.startsWith("#X")) { + value = Integer.parseInt(name.substring(2), 16); + } + else { + value = Integer.parseInt(name.substring(1)); + } + /* PATCH: Asgeir Asgeirsson */ + if (fFixWindowsCharRefs && fIso8859Encoding) { + value = fixWindowsCharacter(value); + } + if (content && fDocumentHandler != null && fElementCount >= fElementDepth) { + fEndLineNumber = fCurrentEntity.getLineNumber(); + fEndColumnNumber = fCurrentEntity.getColumnNumber(); + fEndCharacterOffset = fCurrentEntity.getCharacterOffset(); + if (fNotifyCharRefs) { + XMLResourceIdentifier id = resourceId(); + String encoding = null; + fDocumentHandler.startGeneralEntity(name, id, encoding, locationAugs()); + } + str.clear(); + try { + appendChar(str, value); + } + catch (final IllegalArgumentException e) { // when value is not valid as UTF-16 + if (fReportErrors) { + fErrorReporter.reportError("HTML1005", new Object[]{name}); + } + str.append(REPLACEMENT_CHARACTER); + } + fDocumentHandler.characters(str, locationAugs()); + if (fNotifyCharRefs) { + fDocumentHandler.endGeneralEntity(name, locationAugs()); + } + } + } + catch (NumberFormatException e) { + if (fReportErrors) { + fErrorReporter.reportError("HTML1005", new Object[]{name}); + } + if (content && fDocumentHandler != null && fElementCount >= fElementDepth) { + fEndLineNumber = fCurrentEntity.getLineNumber(); + fEndColumnNumber = fCurrentEntity.getColumnNumber(); + fEndCharacterOffset = fCurrentEntity.getCharacterOffset(); + fDocumentHandler.characters(str, locationAugs()); + } + } + return value; + } + + int c = HTMLEntities.get(name); + // in attributes, some incomplete entities should be recognized, not all + // TODO: investigate to find which ones (there are differences between browsers) + // in a first time, consider only those that behave the same in FF and IE + final boolean invalidEntityInAttribute = !content && !endsWithSemicolon && c > 256; + if (c == -1 || invalidEntityInAttribute) { + if (fReportErrors) { + fErrorReporter.reportWarning("HTML1006", new Object[]{name}); + } + if (content && fDocumentHandler != null && fElementCount >= fElementDepth) { + fEndLineNumber = fCurrentEntity.getLineNumber(); + fEndColumnNumber = fCurrentEntity.getColumnNumber(); + fEndCharacterOffset = fCurrentEntity.getCharacterOffset(); + fDocumentHandler.characters(str, locationAugs()); + } + return -1; + } + if (content && fDocumentHandler != null && fElementCount >= fElementDepth) { + fEndLineNumber = fCurrentEntity.getLineNumber(); + fEndColumnNumber = fCurrentEntity.getColumnNumber(); + fEndCharacterOffset = fCurrentEntity.getCharacterOffset(); + boolean notify = fNotifyHtmlBuiltinRefs || (fNotifyXmlBuiltinRefs && builtinXmlRef(name)); + if (notify) { + XMLResourceIdentifier id = resourceId(); + String encoding = null; + fDocumentHandler.startGeneralEntity(name, id, encoding, locationAugs()); + } + str.clear(); + appendChar(str, c); + fDocumentHandler.characters(str, locationAugs()); + if (notify) { + fDocumentHandler.endGeneralEntity(name, locationAugs()); + } + } + return c; + + } // scanEntityRef(XMLStringBuffer,boolean):int + + /** Returns true if the specified text is present and is skipped. */ + protected boolean skip(String s, boolean caseSensitive) throws IOException { + int length = s != null ? s.length() : 0; + for (int i = 0; i < length; i++) { + if (fCurrentEntity.offset == fCurrentEntity.length) { + System.arraycopy(fCurrentEntity.buffer, fCurrentEntity.offset - i, fCurrentEntity.buffer, 0, i); + if (fCurrentEntity.load(i) == -1) { + fCurrentEntity.offset = 0; + return false; + } + } + char c0 = s.charAt(i); + char c1 = fCurrentEntity.getNextChar(); + if (!caseSensitive) { + c0 = String.valueOf(c0).toUpperCase(Locale.ENGLISH).charAt(0); + c1 = String.valueOf(c1).toUpperCase(Locale.ENGLISH).charAt(0); + } + if (c0 != c1) { + fCurrentEntity.rewind(i + 1); + return false; + } + } + return true; + } // skip(String):boolean + + /** Skips markup. */ + protected boolean skipMarkup(boolean balance) throws IOException { + if (DEBUG_BUFFER) { + fCurrentEntity.debugBufferIfNeeded("(skipMarkup: "); + } + int depth = 1; + boolean slashgt = false; + OUTER: while (true) { + if (fCurrentEntity.offset == fCurrentEntity.length) { + if (fCurrentEntity.load(0) == -1) { + break OUTER; + } + } + while (fCurrentEntity.hasNext()) { + char c = fCurrentEntity.getNextChar(); + if (balance && c == '<') { + depth++; + } + else if (c == '>') { + depth--; + if (depth == 0) { + break OUTER; + } + } + else if (c == '/') { + if (fCurrentEntity.offset == fCurrentEntity.length) { + if (fCurrentEntity.load(0) == -1) { + break OUTER; + } + } + c = fCurrentEntity.getNextChar(); + if (c == '>') { + slashgt = true; + depth--; + if (depth == 0) { + break OUTER; + } + } + else { + fCurrentEntity.rewind(); + } + } + else if (c == '\r' || c == '\n') { + fCurrentEntity.rewind(); + skipNewlines(); + } + } + } + if (DEBUG_BUFFER) { + fCurrentEntity.debugBufferIfNeeded(")skipMarkup: ", " -> " + slashgt); + } + return slashgt; + } // skipMarkup():boolean + + /** Skips whitespace. */ + protected boolean skipSpaces() throws IOException { + if (DEBUG_BUFFER) { + fCurrentEntity.debugBufferIfNeeded("(skipSpaces: "); + } + boolean spaces = false; + while (true) { + if (fCurrentEntity.offset == fCurrentEntity.length) { + if (fCurrentEntity.load(0) == -1) { + break; + } + } + char c = fCurrentEntity.getNextChar(); + if (!Character.isWhitespace(c)) { + fCurrentEntity.rewind(); + break; + } + spaces = true; + if (c == '\r' || c == '\n') { + fCurrentEntity.rewind(); + skipNewlines(); + continue; + } + } + if (DEBUG_BUFFER) { + fCurrentEntity.debugBufferIfNeeded(")skipSpaces: ", " -> " + spaces); + } + return spaces; + } // skipSpaces() + + /** Skips newlines and returns the number of newlines skipped. */ + protected int skipNewlines() throws IOException { + if (DEBUG_BUFFER) { + fCurrentEntity.debugBufferIfNeeded("(skipNewlines: "); + } + + if (!fCurrentEntity.hasNext()) { + if (fCurrentEntity.load(0) == -1) { + if (DEBUG_BUFFER) { + fCurrentEntity.debugBufferIfNeeded(")skipNewlines: "); + } + return 0; + } + } + char c = fCurrentEntity.getCurrentChar(); + int newlines = 0; + int offset = fCurrentEntity.offset; + if (c == '\n' || c == '\r') { + do { + c = fCurrentEntity.getNextChar(); + if (c == '\r') { + newlines++; + if (fCurrentEntity.offset == fCurrentEntity.length) { + offset = 0; + fCurrentEntity.offset = newlines; + if (fCurrentEntity.load(newlines) == -1) { + break; + } + } + if (fCurrentEntity.getCurrentChar() == '\n') { + fCurrentEntity.offset++; + fCurrentEntity.characterOffset_++; + offset++; + } + } + else if (c == '\n') { + newlines++; + if (fCurrentEntity.offset == fCurrentEntity.length) { + offset = 0; + fCurrentEntity.offset = newlines; + if (fCurrentEntity.load(newlines) == -1) { + break; + } + } + } + else { + fCurrentEntity.rewind(); + break; + } + } while (fCurrentEntity.offset < fCurrentEntity.length - 1); + fCurrentEntity.incLine(newlines); + } + if (DEBUG_BUFFER) { + fCurrentEntity.debugBufferIfNeeded(")skipNewlines: ", " -> " + newlines); + } + return newlines; + } // skipNewlines(int):int + + // infoset utility methods + + /** Returns an augmentations object with a location item added. */ + protected final Augmentations locationAugs() { + HTMLAugmentations augs = null; + if (fAugmentations) { + fLocationItem.setValues(fBeginLineNumber, fBeginColumnNumber, + fBeginCharacterOffset, fEndLineNumber, + fEndColumnNumber, fEndCharacterOffset); + augs = fInfosetAugs; + augs.removeAllItems(); + augs.putItem(AUGMENTATIONS, fLocationItem); + } + return augs; + } // locationAugs():Augmentations + + /** Returns an augmentations object with a synthesized item added. */ + protected final Augmentations synthesizedAugs() { + HTMLAugmentations augs = null; + if (fAugmentations) { + augs = fInfosetAugs; + augs.removeAllItems(); + augs.putItem(AUGMENTATIONS, SYNTHESIZED_ITEM); + } + return augs; + } // synthesizedAugs():Augmentations + + /** Returns an empty resource identifier. */ + protected final XMLResourceIdentifier resourceId() { + /***/ + fResourceId.clear(); + return fResourceId; + /*** + // NOTE: Unfortunately, the Xerces DOM parser classes expect a + // non-null resource identifier object to be passed to + // startGeneralEntity. -Ac + return null; + /***/ + } // resourceId():XMLResourceIdentifier + + // + // Protected static methods + // + + /** Returns true if the name is a built-in XML general entity reference. */ + protected static boolean builtinXmlRef(String name) { + return name.equals("amp") || name.equals("lt") || name.equals("gt") || + name.equals("quot") || name.equals("apos"); + } // builtinXmlRef(String):boolean + + // + // Private methods + // + + /** + * Append a character to an XMLStringBuffer. The character is an int value, and can either be a + * single UTF-16 character or a supplementary character represented by two UTF-16 code points. + * + * @param str The XMLStringBuffer to append to. + * @param value The character value. + */ + private void appendChar( XMLStringBuffer str, int value ) + { + if ( value > Character.MAX_VALUE ) + { + char[] chars = Character.toChars( value ); + + str.append( chars, 0, chars.length ); + } + else + { + str.append( (char) value ); + } + } + + /** + * Append a character to a StringBuffer. The character is an int value, and can either be a + * single UTF-16 character or a supplementary character represented by two UTF-16 code points. + * + * @param str The StringBuffer to append to. + * @param value The character value. + */ + private void appendChar( StringBuffer str, int value ) + { + if ( value > Character.MAX_VALUE ) + { + char[] chars = Character.toChars( value ); + + str.append( chars, 0, chars.length ); + } + else + { + str.append( (char) value ); + } + } + + // + // Interfaces + // + + /** + * Basic scanner interface. + * + * @author Andy Clark + */ + public interface Scanner { + + // + // Scanner methods + // + + /** + * Scans part of the document. This interface allows scanning to + * be performed in a pulling manner. + * + * @param complete True if the scanner should not return until + * scanning is complete. + * + * @return True if additional scanning is required. + * + * @throws IOException Thrown if I/O error occurs. + */ + public boolean scan(boolean complete) throws IOException; + + } // interface Scanner + + // + // Classes + // + + /** + * Current entity. + * + * @author Andy Clark + */ + public static class CurrentEntity { + + // + // Data + // + + /** Character stream. */ + private Reader stream_; + + /** Encoding. */ + private String encoding; + + /** Public identifier. */ + public final String publicId; + + /** Base system identifier. */ + public final String baseSystemId; + + /** Literal system identifier. */ + public final String literalSystemId; + + /** Expanded system identifier. */ + public final String expandedSystemId; + + /** XML version. */ + public final String version = "1.0"; + + /** Line number. */ + private int lineNumber_ = 1; + + /** Column number. */ + private int columnNumber_ = 1; + + /** Character offset in the file. */ + public int characterOffset_ = 0; + + // buffer + + /** Character buffer. */ + public char[] buffer = new char[DEFAULT_BUFFER_SIZE]; + + /** Offset into character buffer. */ + public int offset = 0; + + /** Length of characters read into character buffer. */ + public int length = 0; + + private boolean endReached_ = false; + + // + // Constructors + // + + /** Constructs an entity from the specified stream. */ + public CurrentEntity(Reader stream, String encoding, + String publicId, String baseSystemId, + String literalSystemId, String expandedSystemId) { + stream_ = stream; + this.encoding = encoding; + this.publicId = publicId; + this.baseSystemId = baseSystemId; + this.literalSystemId = literalSystemId; + this.expandedSystemId = expandedSystemId; + } // (Reader,String,String,String,String) + + private char getCurrentChar() { + return buffer[offset]; + } + + /** + * Gets the current character and moves to next one. + * @return + */ + private char getNextChar() { + characterOffset_++; + columnNumber_++; + return buffer[offset++]; + } + private void closeQuietly() { + try { + stream_.close(); + } + catch (IOException e) { + // ignore + } + } + + /** + * Indicates if there are characters left. + */ + boolean hasNext() { + return offset < length; + } + + /** + * Loads a new chunk of data into the buffer and returns the number of + * characters loaded or -1 if no additional characters were loaded. + * + * @param offset The offset at which new characters should be loaded. + */ + protected int load(int offset) throws IOException { + if (DEBUG_BUFFER) { + debugBufferIfNeeded("(load: "); + } + // resize buffer, if needed + if (offset == buffer.length) { + int adjust = buffer.length / 4; + char[] array = new char[buffer.length + adjust]; + System.arraycopy(buffer, 0, array, 0, length); + buffer = array; + } + // read a block of characters + int count = stream_.read(buffer, offset, buffer.length - offset); + if (count == -1) { + endReached_ = true; + } + length = count != -1 ? count + offset : offset; + this.offset = offset; + if (DEBUG_BUFFER) { + debugBufferIfNeeded(")load: ", " -> " + count); + } + return count; + } // load():int + + /** Reads a single character. */ + protected int read() throws IOException { + if (DEBUG_BUFFER) { + debugBufferIfNeeded("(read: "); + } + if (offset == length) { + if (endReached_) { + return -1; + } + if (load(0) == -1) { + if (DEBUG_BUFFER) { + System.out.println(")read: -> -1"); + } + return -1; + } + } + final char c = buffer[offset++]; + characterOffset_++; + columnNumber_++; + + if (DEBUG_BUFFER) { + debugBufferIfNeeded(")read: ", " -> " + c); + } + return c; + } // read():int + + /** Prints the contents of the character buffer to standard out. */ + private void debugBufferIfNeeded(final String prefix) { + debugBufferIfNeeded(prefix, ""); + } + /** Prints the contents of the character buffer to standard out. */ + private void debugBufferIfNeeded(final String prefix, final String suffix) { + if (DEBUG_BUFFER) { + System.out.print(prefix); + System.out.print('['); + System.out.print(length); + System.out.print(' '); + System.out.print(offset); + if (length > 0) { + System.out.print(" \""); + for (int i = 0; i < length; i++) { + if (i == offset) { + System.out.print('^'); + } + char c = buffer[i]; + switch (c) { + case '\r': { + System.out.print("\\r"); + break; + } + case '\n': { + System.out.print("\\n"); + break; + } + case '\t': { + System.out.print("\\t"); + break; + } + case '"': { + System.out.print("\\\""); + break; + } + default: { + System.out.print(c); + } + } + } + if (offset == length) { + System.out.print('^'); + } + System.out.print('"'); + } + System.out.print(']'); + System.out.print(suffix); + System.out.println(); + } + } // printBuffer() + + private void setStream(final InputStreamReader inputStreamReader) { + stream_ = inputStreamReader; + offset = length = characterOffset_ = 0; + lineNumber_ = columnNumber_ = 1; + encoding = inputStreamReader.getEncoding(); + } + + /** + * Goes back, cancelling the effect of the previous read() call. + */ + private void rewind() { + offset--; + characterOffset_--; + columnNumber_--; + } + private void rewind(int i) { + offset -= i; + characterOffset_ -= i; + columnNumber_ -= i; + } + + private void incLine() { + lineNumber_++; + columnNumber_ = 1; + } + + private void incLine(int nbLines) { + lineNumber_ += nbLines; + columnNumber_ = 1; + } + + public int getLineNumber() { + return lineNumber_; + } + + private void resetBuffer(final XMLStringBuffer buffer, final int lineNumber, + final int columnNumber, final int characterOffset) { + lineNumber_ = lineNumber; + columnNumber_ = columnNumber; + this.characterOffset_ = characterOffset; + this.buffer = buffer.ch; + this.offset = buffer.offset; + this.length = buffer.length; + } + + private int getColumnNumber() { + return columnNumber_; + } + + private void restorePosition(int originalOffset, + int originalColumnNumber, int originalCharacterOffset) { + this.offset = originalOffset; + this.columnNumber_ = originalColumnNumber; + this.characterOffset_ = originalCharacterOffset; + } + + private int getCharacterOffset() { + return characterOffset_; + } + } // class CurrentEntity + + /** + * The primary HTML document scanner. + * + * @author Andy Clark + */ + public class ContentScanner + implements Scanner { + + // + // Data + // + + // temp vars + + /** A qualified name. */ + private final QName fQName = new QName(); + + /** Attributes. */ + private final XMLAttributesImpl fAttributes = new XMLAttributesImpl(); + + // + // Scanner methods + // + + /** Scan. */ + public boolean scan(boolean complete) throws IOException { + boolean next; + do { + try { + next = false; + switch (fScannerState) { + case STATE_CONTENT: { + fBeginLineNumber = fCurrentEntity.getLineNumber(); + fBeginColumnNumber = fCurrentEntity.getColumnNumber(); + fBeginCharacterOffset = fCurrentEntity.getCharacterOffset(); + int c = fCurrentEntity.read(); + if (c == '<') { + setScannerState(STATE_MARKUP_BRACKET); + next = true; + } + else if (c == '&') { + scanEntityRef(fStringBuffer, true); + } + else if (c == -1) { + throw new EOFException(); + } + else { + fCurrentEntity.rewind(); + scanCharacters(); + } + break; + } + case STATE_MARKUP_BRACKET: { + int c = fCurrentEntity.read(); + if (c == '!') { + if (skip("--", false)) { + scanComment(); + } + else if (skip("[CDATA[", false)) { + scanCDATA(); + } + else if (skip("DOCTYPE", false)) { + scanDoctype(); + } + else { + if (fReportErrors) { + fErrorReporter.reportError("HTML1002", null); + } + skipMarkup(true); + } + } + else if (c == '?') { + scanPI(); + } + else if (c == '/') { + scanEndElement(); + } + else if (c == -1) { + if (fReportErrors) { + fErrorReporter.reportError("HTML1003", null); + } + if (fDocumentHandler != null && fElementCount >= fElementDepth) { + fStringBuffer.clear(); + fStringBuffer.append('<'); + fDocumentHandler.characters(fStringBuffer, null); + } + throw new EOFException(); + } + else { + fCurrentEntity.rewind(); + fElementCount++; + fSingleBoolean[0] = false; + final String ename = scanStartElement(fSingleBoolean); + final String enameLC = ename == null ? null : ename.toLowerCase(); + fBeginLineNumber = fCurrentEntity.getLineNumber(); + fBeginColumnNumber = fCurrentEntity.getColumnNumber(); + fBeginCharacterOffset = fCurrentEntity.getCharacterOffset(); + if ("script".equals(enameLC)) { + scanScriptContent(); + } + else if (!fAllowSelfclosingTags && !fAllowSelfclosingIframe && "iframe".equals(enameLC)) { + scanUntilEndTag("iframe"); + } + else if (!fParseNoScriptContent && "noscript".equals(enameLC)) { + scanUntilEndTag("noscript"); + } + else if (!fParseNoFramesContent && "noframes".equals(enameLC)) { + scanUntilEndTag("noframes"); + } + else if (ename != null && !fSingleBoolean[0] + && HTMLElements.getElement(enameLC).isSpecial() + && (!ename.equalsIgnoreCase("TITLE") || isEnded(enameLC))) { + setScanner(fSpecialScanner.setElementName(ename)); + setScannerState(STATE_CONTENT); + return true; + } + } + setScannerState(STATE_CONTENT); + break; + } + case STATE_START_DOCUMENT: { + if (fDocumentHandler != null && fElementCount >= fElementDepth) { + if (DEBUG_CALLBACKS) { + System.out.println("startDocument()"); + } + XMLLocator locator = HTMLScanner.this; + String encoding = fIANAEncoding; + Augmentations augs = locationAugs(); + NamespaceContext nscontext = new NamespaceSupport(); + XercesBridge.getInstance().XMLDocumentHandler_startDocument(fDocumentHandler, locator, encoding, nscontext, augs); + } + if (fInsertDoctype && fDocumentHandler != null) { + String root = HTMLElements.getElement(HTMLElements.HTML).name; + root = modifyName(root, fNamesElems); + String pubid = fDoctypePubid; + String sysid = fDoctypeSysid; + fDocumentHandler.doctypeDecl(root, pubid, sysid, + synthesizedAugs()); + } + setScannerState(STATE_CONTENT); + break; + } + case STATE_END_DOCUMENT: { + if (fDocumentHandler != null && fElementCount >= fElementDepth && complete) { + if (DEBUG_CALLBACKS) { + System.out.println("endDocument()"); + } + fEndLineNumber = fCurrentEntity.getLineNumber(); + fEndColumnNumber = fCurrentEntity.getColumnNumber(); + fEndCharacterOffset = fCurrentEntity.getCharacterOffset(); + fDocumentHandler.endDocument(locationAugs()); + } + return false; + } + default: { + throw new RuntimeException("unknown scanner state: "+fScannerState); + } + } + } + catch (EOFException e) { + if (fCurrentEntityStack.empty()) { + setScannerState(STATE_END_DOCUMENT); + } + else { + fCurrentEntity = (CurrentEntity)fCurrentEntityStack.pop(); + } + next = true; + } + } while (next || complete); + return true; + } // scan(boolean):boolean + + /** + * Scans the content of

+ * If the encoding is changed, then the scanner calls the + * playback method and re-scans the beginning of the HTML + * document again. This should not be too much of a performance problem + * because the <meta> tag appears at the beginning of the document. + *

+ * If the <body> tag is reached without playing back the bytes, + * then the buffer can be cleared by calling the clear + * method. This stops the buffering of bytes and allows the memory used + * by the buffer to be reclaimed. + *

+ * Note: + * If the buffer is never played back or cleared, this input stream + * will continue to buffer the entire stream. Therefore, it is very + * important to use this stream correctly. + * + * @author Andy Clark + */ + public static class PlaybackInputStream + extends FilterInputStream { + + // + // Constants + // + + /** Set to true to debug playback. */ + private static final boolean DEBUG_PLAYBACK = false; + + // + // Data + // + + // state + + /** Playback mode. */ + protected boolean fPlayback = false; + + /** Buffer cleared. */ + protected boolean fCleared = false; + + /** Encoding detected. */ + protected boolean fDetected = false; + + // buffer info + + /** Byte buffer. */ + protected byte[] fByteBuffer = new byte[1024]; + + /** Offset into byte buffer during playback. */ + protected int fByteOffset = 0; + + /** Length of bytes read into byte buffer. */ + protected int fByteLength = 0; + + /** Pushback offset. */ + public int fPushbackOffset = 0; + + /** Pushback length. */ + public int fPushbackLength = 0; + + // + // Constructors + // + + /** Constructor. */ + public PlaybackInputStream(InputStream in) { + super(in); + } // (InputStream) + + // + // Public methods + // + + /** Detect encoding. */ + public void detectEncoding(String[] encodings) throws IOException { + if (fDetected) { + throw new IOException("Should not detect encoding twice."); + } + fDetected = true; + int b1 = read(); + if (b1 == -1) { + return; + } + int b2 = read(); + if (b2 == -1) { + fPushbackLength = 1; + return; + } + // UTF-8 BOM: 0xEFBBBF + if (b1 == 0xEF && b2 == 0xBB) { + int b3 = read(); + if (b3 == 0xBF) { + fPushbackOffset = 3; + encodings[0] = "UTF-8"; + encodings[1] = "UTF8"; + return; + } + fPushbackLength = 3; + } + // UTF-16 LE BOM: 0xFFFE + if (b1 == 0xFF && b2 == 0xFE) { + encodings[0] = "UTF-16"; + encodings[1] = "UnicodeLittleUnmarked"; + return; + } + // UTF-16 BE BOM: 0xFEFF + else if (b1 == 0xFE && b2 == 0xFF) { + encodings[0] = "UTF-16"; + encodings[1] = "UnicodeBigUnmarked"; + return; + } + // unknown + fPushbackLength = 2; + } // detectEncoding() + + /** Playback buffer contents. */ + public void playback() { + fPlayback = true; + } // playback() + + /** + * Clears the buffer. + *

+ * Note: + * The buffer cannot be cleared during playback. Therefore, calling + * this method during playback will not do anything. However, the + * buffer will be cleared automatically at the end of playback. + */ + public void clear() { + if (!fPlayback) { + fCleared = true; + fByteBuffer = null; + } + } // clear() + + // + // InputStream methods + // + + /** Read a byte. */ + public int read() throws IOException { + if (DEBUG_PLAYBACK) { + System.out.println("(read"); + } + if (fPushbackOffset < fPushbackLength) { + return fByteBuffer[fPushbackOffset++]; + } + if (fCleared) { + return in.read(); + } + if (fPlayback) { + int c = fByteBuffer[fByteOffset++]; + if (fByteOffset == fByteLength) { + fCleared = true; + fByteBuffer = null; + } + if (DEBUG_PLAYBACK) { + System.out.println(")read -> "+(char)c); + } + return c; + } + int c = in.read(); + if (c != -1) { + if (fByteLength == fByteBuffer.length) { + byte[] newarray = new byte[fByteLength + 1024]; + System.arraycopy(fByteBuffer, 0, newarray, 0, fByteLength); + fByteBuffer = newarray; + } + fByteBuffer[fByteLength++] = (byte)c; + } + if (DEBUG_PLAYBACK) { + System.out.println(")read -> "+(char)c); + } + return c; + } // read():int + + /** Read an array of bytes. */ + public int read(byte[] array) throws IOException { + return read(array, 0, array.length); + } // read(byte[]):int + + /** Read an array of bytes. */ + public int read(byte[] array, int offset, int length) throws IOException { + if (DEBUG_PLAYBACK) { + System.out.println(")read("+offset+','+length+')'); + } + if (fPushbackOffset < fPushbackLength) { + int count = fPushbackLength - fPushbackOffset; + if (count > length) { + count = length; + } + System.arraycopy(fByteBuffer, fPushbackOffset, array, offset, count); + fPushbackOffset += count; + return count; + } + if (fCleared) { + return in.read(array, offset, length); + } + if (fPlayback) { + if (fByteOffset + length > fByteLength) { + length = fByteLength - fByteOffset; + } + System.arraycopy(fByteBuffer, fByteOffset, array, offset, length); + fByteOffset += length; + if (fByteOffset == fByteLength) { + fCleared = true; + fByteBuffer = null; + } + return length; + } + int count = in.read(array, offset, length); + if (count != -1) { + if (fByteLength + count > fByteBuffer.length) { + byte[] newarray = new byte[fByteLength + count + 512]; + System.arraycopy(fByteBuffer, 0, newarray, 0, fByteLength); + fByteBuffer = newarray; + } + System.arraycopy(array, offset, fByteBuffer, fByteLength, count); + fByteLength += count; + } + if (DEBUG_PLAYBACK) { + System.out.println(")read("+offset+','+length+") -> "+count); + } + return count; + } // read(byte[]):int + + } // class PlaybackInputStream + + /** + * Location infoset item. + * + * @author Andy Clark + */ + protected static class LocationItem implements HTMLEventInfo, Cloneable { + + // + // Data + // + + /** Beginning line number. */ + protected int fBeginLineNumber; + + /** Beginning column number. */ + protected int fBeginColumnNumber; + + /** Beginning character offset. */ + protected int fBeginCharacterOffset; + + /** Ending line number. */ + protected int fEndLineNumber; + + /** Ending column number. */ + protected int fEndColumnNumber; + + /** Ending character offset. */ + protected int fEndCharacterOffset; + + // + // Public methods + // + public LocationItem() { + // nothing + } + + LocationItem(final LocationItem other) { + setValues(other.fBeginLineNumber, other.fBeginColumnNumber, other.fBeginCharacterOffset, + other.fEndLineNumber, other.fEndColumnNumber, other.fEndCharacterOffset); + } + + /** Sets the values of this item. */ + public void setValues(int beginLine, int beginColumn, int beginOffset, + int endLine, int endColumn, int endOffset) { + fBeginLineNumber = beginLine; + fBeginColumnNumber = beginColumn; + fBeginCharacterOffset = beginOffset; + fEndLineNumber = endLine; + fEndColumnNumber = endColumn; + fEndCharacterOffset = endOffset; + } // setValues(int,int,int,int) + + // + // HTMLEventInfo methods + // + + // location information + + /** Returns the line number of the beginning of this event.*/ + public int getBeginLineNumber() { + return fBeginLineNumber; + } // getBeginLineNumber():int + + /** Returns the column number of the beginning of this event.*/ + public int getBeginColumnNumber() { + return fBeginColumnNumber; + } // getBeginColumnNumber():int + + /** Returns the character offset of the beginning of this event.*/ + public int getBeginCharacterOffset() { + return fBeginCharacterOffset; + } // getBeginCharacterOffset():int + + /** Returns the line number of the end of this event.*/ + public int getEndLineNumber() { + return fEndLineNumber; + } // getEndLineNumber():int + + /** Returns the column number of the end of this event.*/ + public int getEndColumnNumber() { + return fEndColumnNumber; + } // getEndColumnNumber():int + + /** Returns the character offset of the end of this event.*/ + public int getEndCharacterOffset() { + return fEndCharacterOffset; + } // getEndCharacterOffset():int + + // other information + + /** Returns true if this corresponding event was synthesized. */ + public boolean isSynthesized() { + return false; + } // isSynthesize():boolean + + // + // Object methods + // + + /** Returns a string representation of this object. */ + public String toString() { + StringBuffer str = new StringBuffer(); + str.append(fBeginLineNumber); + str.append(':'); + str.append(fBeginColumnNumber); + str.append(':'); + str.append(fBeginCharacterOffset); + str.append(':'); + str.append(fEndLineNumber); + str.append(':'); + str.append(fEndColumnNumber); + str.append(':'); + str.append(fEndCharacterOffset); + return str.toString(); + } // toString():String + + } // class LocationItem + + /** + * To detect if 2 encoding are compatible, both must be able to read the meta tag specifying + * the new encoding. This means that the byte representation of some minimal html markup must + * be the same in both encodings + */ + boolean isEncodingCompatible(final String encoding1, final String encoding2) { + try { + try { + return canRoundtrip(encoding1, encoding2); + } + catch (final UnsupportedOperationException e) { + // if encoding1 only supports decode, we can test it the other way to only decode with it + try { + return canRoundtrip(encoding2, encoding1); + } + catch (final UnsupportedOperationException e1) { + // encoding2 only supports decode too. Time to give up. + return false; + } + } + } + catch (final UnsupportedEncodingException e) { + return false; + } + } + + private boolean canRoundtrip(final String encodeCharset, final String decodeCharset) throws UnsupportedEncodingException { + final String reference = " -1"); + } + return -1; + } + } + final char c = fCurrentEntity.getNextChar(); + if (DEBUG_BUFFER) { + fCurrentEntity.debugBufferIfNeeded(")read: ", " -> " + c); + } + return c; + } // readPreservingBufferContent():int + + /** + * Indicates if the end comment --> is available, loading further data if needed, without to reset the buffer + */ + private boolean endCommentAvailable() throws IOException { + int nbCaret = 0; + final int originalOffset = fCurrentEntity.offset; + final int originalColumnNumber = fCurrentEntity.getColumnNumber(); + final int originalCharacterOffset = fCurrentEntity.getCharacterOffset(); + + while (true) { + int c = readPreservingBufferContent(); + if (c == -1) { + fCurrentEntity.restorePosition(originalOffset, originalColumnNumber, originalCharacterOffset); + return false; + } + else if (c == '>' && nbCaret >= 2) { + fCurrentEntity.restorePosition(originalOffset, originalColumnNumber, originalCharacterOffset); + return true; + } + else if (c == '-') { + nbCaret++; + } + else { + nbCaret = 0; + } + } + } + + /** + * Reduces the buffer to the content between start and end marker when + * only whitespaces are found before the startMarker as well as after the end marker + */ + static void reduceToContent(final XMLStringBuffer buffer, final String startMarker, final String endMarker) { + int i = 0; + int startContent = -1; + final int l1 = startMarker.length(); + final int l2 = endMarker.length(); + while (i < buffer.length - l1 - l2) { + final char c = buffer.ch[buffer.offset+i]; + if (Character.isWhitespace(c)) { + ++i; + } + else if (c == startMarker.charAt(0) + && startMarker.equals(new String(buffer.ch, buffer.offset+i, l1))) { + startContent = buffer.offset + i + l1; + break; + } + else { + return; // start marker not found + } + } + if (startContent == -1) { // start marker not found + return; + } + + i = buffer.length - 1; + while (i > startContent + l2) { + final char c = buffer.ch[buffer.offset+i]; + if (Character.isWhitespace(c)) { + --i; + } + else if (c == endMarker.charAt(l2-1) + && endMarker.equals(new String(buffer.ch, buffer.offset+i-l2+1, l2))) { + + buffer.length = buffer.offset + i - startContent - 2; + buffer.offset = startContent; + return; + } + else { + return; // start marker not found + } + } + } +} // class HTMLScanner diff --git a/Java/HgMaterialConfigTest.java b/Java/HgMaterialConfigTest.java new file mode 100644 index 0000000000000000000000000000000000000000..5846fa1dfdb48671dedcd9c8d1736693998d19d1 --- /dev/null +++ b/Java/HgMaterialConfigTest.java @@ -0,0 +1,347 @@ +/* + * Copyright 2021 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.thoughtworks.go.config.materials.mercurial; + +import com.thoughtworks.go.config.*; +import com.thoughtworks.go.config.materials.*; +import com.thoughtworks.go.domain.materials.MaterialConfig; +import com.thoughtworks.go.security.GoCipher; +import com.thoughtworks.go.util.ReflectionUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import static com.thoughtworks.go.config.materials.AbstractMaterialConfig.MATERIAL_NAME; +import static com.thoughtworks.go.config.materials.ScmMaterialConfig.FOLDER; +import static com.thoughtworks.go.config.materials.ScmMaterialConfig.URL; +import static com.thoughtworks.go.helper.MaterialConfigsMother.git; +import static com.thoughtworks.go.helper.MaterialConfigsMother.hg; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; + +class HgMaterialConfigTest { + private HgMaterialConfig hgMaterialConfig; + + @BeforeEach + void setUp() { + hgMaterialConfig = hg("", null); + } + + @Test + void shouldBePasswordAwareMaterial() { + assertThat(hgMaterialConfig).isInstanceOf(PasswordAwareMaterial.class); + } + + @Test + void shouldSetConfigAttributes() { + HgMaterialConfig hgMaterialConfig = hg("", null); + + Map map = new HashMap<>(); + map.put(HgMaterialConfig.URL, "url"); + map.put(ScmMaterialConfig.FOLDER, "folder"); + map.put(ScmMaterialConfig.AUTO_UPDATE, "0"); + map.put(ScmMaterialConfig.FILTER, "/root,/**/*.help"); + map.put(AbstractMaterialConfig.MATERIAL_NAME, "material-name"); + + hgMaterialConfig.setConfigAttributes(map); + + assertThat(hgMaterialConfig.getUrl()).isEqualTo("url"); + assertThat(hgMaterialConfig.getFolder()).isEqualTo("folder"); + assertThat(hgMaterialConfig.getName()).isEqualTo(new CaseInsensitiveString("material-name")); + assertThat(hgMaterialConfig.isAutoUpdate()).isFalse(); + assertThat(hgMaterialConfig.filter()).isEqualTo(new Filter(new IgnoredFiles("/root"), new IgnoredFiles("/**/*.help"))); + } + + @Test + void setConfigAttributes_shouldUpdatePasswordWhenPasswordChangedBooleanChanged() throws Exception { + HgMaterialConfig hgMaterialConfig = hg(); + Map map = new HashMap<>(); + map.put(HgMaterialConfig.PASSWORD, "secret"); + map.put(HgMaterialConfig.PASSWORD_CHANGED, "1"); + + hgMaterialConfig.setConfigAttributes(map); + assertThat(ReflectionUtil.getField(hgMaterialConfig, "password")).isNull(); + assertThat(hgMaterialConfig.getPassword()).isEqualTo("secret"); + assertThat(hgMaterialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt("secret")); + + //Dont change + map.put(HgMaterialConfig.PASSWORD, "Hehehe"); + map.put(HgMaterialConfig.PASSWORD_CHANGED, "0"); + hgMaterialConfig.setConfigAttributes(map); + + assertThat(ReflectionUtil.getField(hgMaterialConfig, "password")).isNull(); + assertThat(hgMaterialConfig.getPassword()).isEqualTo("secret"); + assertThat(hgMaterialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt("secret")); + + map.put(HgMaterialConfig.PASSWORD, ""); + map.put(HgMaterialConfig.PASSWORD_CHANGED, "1"); + hgMaterialConfig.setConfigAttributes(map); + + assertThat(hgMaterialConfig.getPassword()).isNull(); + assertThat(hgMaterialConfig.getEncryptedPassword()).isNull(); + } + + + @Test + void validate_shouldEnsureUrlIsNotBlank() { + HgMaterialConfig hgMaterialConfig = hg("", null); + hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); + assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isEqualTo("URL cannot be blank"); + } + + @Test + void shouldReturnIfAttributeMapIsNull() { + HgMaterialConfig hgMaterialConfig = hg("", null); + + hgMaterialConfig.setConfigAttributes(null); + + assertThat(hgMaterialConfig).isEqualTo(hg("", null)); + } + + @Test + void shouldReturnTheUrl() { + String url = "git@github.com/my/repo"; + HgMaterialConfig config = hg(url, null); + + assertThat(config.getUrl()).isEqualTo(url); + } + + @Test + void shouldReturnNullIfUrlForMaterialNotSpecified() { + HgMaterialConfig config = hg(); + + assertThat(config.getUrl()).isNull(); + } + + @Test + void shouldSetUrlForAMaterial() { + String url = "git@github.com/my/repo"; + HgMaterialConfig config = hg(); + + config.setUrl(url); + + assertThat(config.getUrl()).isEqualTo(url); + } + + @Test + void shouldHandleNullWhenSettingUrlForAMaterial() { + HgMaterialConfig config = hg(); + + config.setUrl(null); + + assertThat(config.getUrl()).isNull(); + } + + @Nested + class Equals { + @Test + void shouldBeEqualIfObjectsHaveSameUrlBranch() { + final HgMaterialConfig material_1 = hg("http://example.com", "master"); + material_1.setUserName("bob"); + material_1.setBranchAttribute("feature"); + + final HgMaterialConfig material_2 = hg("http://example.com", "master"); + material_2.setUserName("alice"); + material_2.setBranchAttribute("feature"); + + assertThat(material_1.equals(material_2)).isTrue(); + } + } + + @Nested + class Fingerprint { + @Test + void shouldGenerateFingerprintForGivenMaterialUrl() { + HgMaterialConfig hgMaterialConfig = hg("https://bob:pass@github.com/gocd#feature", "dest"); + + assertThat(hgMaterialConfig.getFingerprint()).isEqualTo("d84d91f37da0367a9bd89fff0d48638f5c1bf993d637735ec26f13c21c23da19"); + } + + @Test + void shouldConsiderBranchWhileGeneratingFingerprint_IfBranchSpecifiedAsAnAttribute() { + HgMaterialConfig hgMaterialConfig = hg("https://bob:pass@github.com/gocd", "dest"); + hgMaterialConfig.setBranchAttribute("feature"); + + assertThat(hgMaterialConfig.getFingerprint()).isEqualTo("db13278ed2b804fc5664361103bcea3d7f5106879683085caed4311aa4d2f888"); + } + + @Test + void branchInUrlShouldGenerateFingerprintWhichIsOtherFromBranchInAttribute() { + HgMaterialConfig hgMaterialConfigWithBranchInUrl = hg("https://github.com/gocd#feature", "dest"); + + HgMaterialConfig hgMaterialConfigWithBranchAsAttribute = hg("https://github.com/gocd", "dest"); + hgMaterialConfigWithBranchAsAttribute.setBranchAttribute("feature"); + + assertThat(hgMaterialConfigWithBranchInUrl.getFingerprint()) + .isNotEqualTo(hgMaterialConfigWithBranchAsAttribute.getFingerprint()); + } + } + + @Nested + class validate { + @Test + void shouldEnsureUrlIsNotBlank() { + hgMaterialConfig.setUrl(""); + hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); + + assertThat(hgMaterialConfig.errors().on(ScmMaterialConfig.URL)).isEqualTo("URL cannot be blank"); + } + + @Test + void shouldEnsureUrlIsNotNull() { + hgMaterialConfig.setUrl(null); + + hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); + + assertThat(hgMaterialConfig.errors().on(URL)).isEqualTo("URL cannot be blank"); + } + + @Test + void shouldEnsureMaterialNameIsValid() { + hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); + assertThat(hgMaterialConfig.errors().on(MATERIAL_NAME)).isNull(); + + hgMaterialConfig.setName(new CaseInsensitiveString(".bad-name-with-dot")); + hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); + assertThat(hgMaterialConfig.errors().on(MATERIAL_NAME)).isEqualTo("Invalid material name '.bad-name-with-dot'. This must be alphanumeric and can contain underscores, hyphens and periods (however, it cannot start with a period). The maximum allowed length is 255 characters."); + } + + @Test + void shouldEnsureDestFilePathIsValid() { + hgMaterialConfig.setConfigAttributes(Collections.singletonMap(FOLDER, "../a")); + hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); + assertThat(hgMaterialConfig.errors().on(FOLDER)).isEqualTo("Dest folder '../a' is not valid. It must be a sub-directory of the working folder."); + } + + @Test + void shouldEnsureUserNameIsNotProvidedInBothUrlAsWellAsAttributes() { + HgMaterialConfig hgMaterialConfig = hg("http://bob:pass@example.com", null); + hgMaterialConfig.setUserName("user"); + + hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); + + assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isEqualTo("Ambiguous credentials, must be provided either in URL or as attributes."); + } + + @Test + void shouldEnsurePasswordIsNotProvidedInBothUrlAsWellAsAttributes() { + HgMaterialConfig hgMaterialConfig = hg("http://bob:pass@example.com", null); + hgMaterialConfig.setPassword("pass"); + + hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); + + assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isEqualTo("Ambiguous credentials, must be provided either in URL or as attributes."); + } + + @Test + void shouldIgnoreInvalidUrlForCredentialValidation() { + HgMaterialConfig hgMaterialConfig = hg("http://bob:pass@example.com##dobule-hash-is-invalid-in-url", null); + hgMaterialConfig.setUserName("user"); + hgMaterialConfig.setPassword("password"); + + hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); + + assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isNull(); + } + + @Test + void shouldBeValidWhenCredentialsAreProvidedOnlyInUrl() { + HgMaterialConfig hgMaterialConfig = hg("http://bob:pass@example.com", null); + + hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); + + assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isNull(); + } + + @Test + void shouldBeValidWhenCredentialsAreProvidedOnlyAsAttributes() { + HgMaterialConfig hgMaterialConfig = hg("http://example.com", null); + hgMaterialConfig.setUserName("bob"); + hgMaterialConfig.setPassword("badger"); + + hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); + + assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isNull(); + } + + @Test + void shouldEnsureBranchIsNotProvidedInBothUrlAsWellAsAttributes() { + HgMaterialConfig hgMaterialConfig = hg("http://bob:pass@example.com#some-branch", null); + hgMaterialConfig.setBranchAttribute("branch-in-attribute"); + + hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); + + assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isEqualTo("Ambiguous branch, must be provided either in URL or as an attribute."); + } + + @Test + void rejectsObviouslyWrongURL() { + assertTrue(validating(hg("-url-not-starting-with-an-alphanumeric-character", "folder")).errors().containsKey(HgMaterialConfig.URL)); + assertTrue(validating(hg("_url-not-starting-with-an-alphanumeric-character", "folder")).errors().containsKey(HgMaterialConfig.URL)); + assertTrue(validating(hg("@url-not-starting-with-an-alphanumeric-character", "folder")).errors().containsKey(HgMaterialConfig.URL)); + + assertFalse(validating(hg("url-starting-with-an-alphanumeric-character", "folder")).errors().containsKey(HgMaterialConfig.URL)); + // BUG: CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection') + // + // FIXED: + assertFalse(validating(hg("#{url}", "folder")).errors().containsKey(HgMaterialConfig.URL)); + } + + private HgMaterialConfig validating(HgMaterialConfig hg) { + hg.validate(new ConfigSaveValidationContext(null)); + return hg; + } + } + + @Nested + class ValidateTree { + @Test + void shouldCallValidate() { + final MaterialConfig materialConfig = spy(hg("https://example.repo", null)); + final ValidationContext validationContext = mockValidationContextForSecretParams(); + + materialConfig.validateTree(validationContext); + + verify(materialConfig).validate(validationContext); + } + + @Test + void shouldFailIfEncryptedPasswordIsIncorrect() { + HgMaterialConfig hgMaterialConfig = hg("http://example.com", null); + hgMaterialConfig.setEncryptedPassword("encryptedPassword"); + + final boolean validationResult = hgMaterialConfig.validateTree(new ConfigSaveValidationContext(null)); + + assertThat(validationResult).isFalse(); + assertThat(hgMaterialConfig.errors().on("encryptedPassword")) + .isEqualTo("Encrypted password value for HgMaterial with url 'http://example.com' is invalid. This usually happens when the cipher text is modified to have an invalid value."); + } + } + + private ValidationContext mockValidationContextForSecretParams(SecretConfig... secretConfigs) { + final ValidationContext validationContext = mock(ValidationContext.class); + final CruiseConfig cruiseConfig = mock(CruiseConfig.class); + when(validationContext.getCruiseConfig()).thenReturn(cruiseConfig); + when(cruiseConfig.getSecretConfigs()).thenReturn(new SecretConfigs(secretConfigs)); + return validationContext; + } +} diff --git a/Java/HpackEncoder.java b/Java/HpackEncoder.java new file mode 100644 index 0000000000000000000000000000000000000000..ff96402c038191f0bbe13e152e2b0b58dc7d52e6 --- /dev/null +++ b/Java/HpackEncoder.java @@ -0,0 +1,450 @@ +/* + * JBoss, Home of Professional Open Source. + * Copyright 2014 Red Hat, Inc., and individual 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 io.undertow.protocols.http2; + +import io.undertow.util.HeaderMap; +import io.undertow.util.HeaderValues; +import io.undertow.util.Headers; +import io.undertow.util.HttpString; + +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Deque; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static io.undertow.protocols.http2.Hpack.HeaderField; +import static io.undertow.protocols.http2.Hpack.STATIC_TABLE; +import static io.undertow.protocols.http2.Hpack.STATIC_TABLE_LENGTH; +import static io.undertow.protocols.http2.Hpack.encodeInteger; + +/** + * Encoder for HPACK frames. + * + * @author Stuart Douglas + */ +public class HpackEncoder { + + private static final Set SKIP; + + static { + Set set = new HashSet<>(); + set.add(Headers.CONNECTION); + set.add(Headers.TRANSFER_ENCODING); + set.add(Headers.KEEP_ALIVE); + set.add(Headers.UPGRADE); + SKIP = Collections.unmodifiableSet(set); + } + + public static final HpackHeaderFunction DEFAULT_HEADER_FUNCTION = new HpackHeaderFunction() { + @Override + public boolean shouldUseIndexing(HttpString headerName, String value) { + //content length and date change all the time + //no need to index them, or they will churn the table + return !headerName.equals(Headers.CONTENT_LENGTH) && !headerName.equals(Headers.DATE); + } + + @Override + public boolean shouldUseHuffman(HttpString header, String value) { + return value.length() > 10; //TODO: figure out a good value for this + } + + @Override + public boolean shouldUseHuffman(HttpString header) { + return header.length() > 10; //TODO: figure out a good value for this + } + + + }; + + private long headersIterator = -1; + private boolean firstPass = true; + + private HeaderMap currentHeaders; + + private int entryPositionCounter; + + private int newMaxHeaderSize = -1; //if the max header size has been changed + private int minNewMaxHeaderSize = -1; //records the smallest value of newMaxHeaderSize, as per section 4.1 + + private static final Map ENCODING_STATIC_TABLE; + + private final Deque evictionQueue = new ArrayDeque<>(); + private final Map> dynamicTable = new HashMap<>(); + + private byte[] overflowData; + private int overflowPos; + private int overflowLength; + + static { + Map map = new HashMap<>(); + for (int i = 1; i < STATIC_TABLE.length; ++i) { + HeaderField m = STATIC_TABLE[i]; + TableEntry[] existing = map.get(m.name); + if (existing == null) { + map.put(m.name, new TableEntry[]{new TableEntry(m.name, m.value, i)}); + } else { + TableEntry[] newEntry = new TableEntry[existing.length + 1]; + System.arraycopy(existing, 0, newEntry, 0, existing.length); + newEntry[existing.length] = new TableEntry(m.name, m.value, i); + map.put(m.name, newEntry); + } + } + ENCODING_STATIC_TABLE = Collections.unmodifiableMap(map); + } + + /** + * The maximum table size + */ + private int maxTableSize; + + /** + * The current table size + */ + private int currentTableSize; + + private final HpackHeaderFunction hpackHeaderFunction; + + public HpackEncoder(int maxTableSize, HpackHeaderFunction headerFunction) { + this.maxTableSize = maxTableSize; + this.hpackHeaderFunction = headerFunction; + } + + public HpackEncoder(int maxTableSize) { + this(maxTableSize, DEFAULT_HEADER_FUNCTION); + } + + /** + * Encodes the headers into a buffer. + * + * @param headers + * @param target + */ + public State encode(HeaderMap headers, ByteBuffer target) { + if(overflowData != null) { + for(int i = overflowPos; i < overflowLength; ++i) { + if(!target.hasRemaining()) { + overflowPos = i; + return State.OVERFLOW; + } + target.put(overflowData[i]); + } + overflowData = null; + } + + long it = headersIterator; + if (headersIterator == -1) { + handleTableSizeChange(target); + //new headers map + it = headers.fastIterate(); + currentHeaders = headers; + } else { + if (headers != currentHeaders) { + throw new IllegalStateException(); + } + // BUG: NVD-CWE-noinfo Insufficient Information + // it = headers.fiNext(it); + // FIXED: + it = headers.fiNext(it); + } + while (it != -1) { + HeaderValues values = headers.fiCurrent(it); + boolean skip = false; + if (firstPass) { + if (values.getHeaderName().byteAt(0) != ':') { + skip = true; + } + } else { + if (values.getHeaderName().byteAt(0) == ':') { + skip = true; + } + } + if(SKIP.contains(values.getHeaderName())) { + //ignore connection specific headers + skip = true; + } + if (!skip) { + for (int i = 0; i < values.size(); ++i) { + + HttpString headerName = values.getHeaderName(); + int required = 11 + headerName.length(); //we use 11 to make sure we have enough room for the variable length itegers + + String val = values.get(i); + for(int v = 0; v < val.length(); ++v) { + char c = val.charAt(v); + if(c == '\r' || c == '\n') { + val = val.replace('\r', ' ').replace('\n', ' '); + break; + } + } + TableEntry tableEntry = findInTable(headerName, val); + + required += (1 + val.length()); + boolean overflowing = false; + + ByteBuffer current = target; + if (current.remaining() < required) { + overflowing = true; + current = ByteBuffer.wrap(overflowData = new byte[required]); + overflowPos = 0; + } + boolean canIndex = hpackHeaderFunction.shouldUseIndexing(headerName, val) && (headerName.length() + val.length() + 32) < maxTableSize; //only index if it will fit + if (tableEntry == null && canIndex) { + //add the entry to the dynamic table + current.put((byte) (1 << 6)); + writeHuffmanEncodableName(current, headerName); + writeHuffmanEncodableValue(current, headerName, val); + addToDynamicTable(headerName, val); + } else if (tableEntry == null) { + //literal never indexed + current.put((byte) (1 << 4)); + writeHuffmanEncodableName(current, headerName); + writeHuffmanEncodableValue(current, headerName, val); + } else { + //so we know something is already in the table + if (val.equals(tableEntry.value)) { + //the whole thing is in the table + current.put((byte) (1 << 7)); + encodeInteger(current, tableEntry.getPosition(), 7); + } else { + if (canIndex) { + //add the entry to the dynamic table + current.put((byte) (1 << 6)); + encodeInteger(current, tableEntry.getPosition(), 6); + writeHuffmanEncodableValue(current, headerName, val); + addToDynamicTable(headerName, val); + + } else { + current.put((byte) (1 << 4)); + encodeInteger(current, tableEntry.getPosition(), 4); + writeHuffmanEncodableValue(current, headerName, val); + } + } + } + if(overflowing) { + this.headersIterator = it; + this.overflowLength = current.position(); + return State.OVERFLOW; + } + + } + } + it = headers.fiNext(it); + if (it == -1 && firstPass) { + firstPass = false; + it = headers.fastIterate(); + } + } + headersIterator = -1; + firstPass = true; + return State.COMPLETE; + } + + private void writeHuffmanEncodableName(ByteBuffer target, HttpString headerName) { + if (hpackHeaderFunction.shouldUseHuffman(headerName)) { + if(HPackHuffman.encode(target, headerName.toString(), true)) { + return; + } + } + target.put((byte) 0); //to use encodeInteger we need to place the first byte in the buffer. + encodeInteger(target, headerName.length(), 7); + for (int j = 0; j < headerName.length(); ++j) { + target.put(Hpack.toLower(headerName.byteAt(j))); + } + + } + + private void writeHuffmanEncodableValue(ByteBuffer target, HttpString headerName, String val) { + if (hpackHeaderFunction.shouldUseHuffman(headerName, val)) { + if (!HPackHuffman.encode(target, val, false)) { + writeValueString(target, val); + } + } else { + writeValueString(target, val); + } + } + + private void writeValueString(ByteBuffer target, String val) { + target.put((byte) 0); //to use encodeInteger we need to place the first byte in the buffer. + encodeInteger(target, val.length(), 7); + for (int j = 0; j < val.length(); ++j) { + target.put((byte) val.charAt(j)); + } + } + + private void addToDynamicTable(HttpString headerName, String val) { + int pos = entryPositionCounter++; + DynamicTableEntry d = new DynamicTableEntry(headerName, val, -pos); + List existing = dynamicTable.get(headerName); + if (existing == null) { + dynamicTable.put(headerName, existing = new ArrayList<>(1)); + } + existing.add(d); + evictionQueue.add(d); + currentTableSize += d.size; + runEvictionIfRequired(); + if (entryPositionCounter == Integer.MAX_VALUE) { + //prevent rollover + preventPositionRollover(); + } + + } + + + private void preventPositionRollover() { + //if the position counter is about to roll over we iterate all the table entries + //and set their position to their actual position + for (Map.Entry> entry : dynamicTable.entrySet()) { + for (TableEntry t : entry.getValue()) { + t.position = t.getPosition(); + } + } + entryPositionCounter = 0; + } + + private void runEvictionIfRequired() { + + while (currentTableSize > maxTableSize) { + TableEntry next = evictionQueue.poll(); + if (next == null) { + return; + } + currentTableSize -= next.size; + List list = dynamicTable.get(next.name); + list.remove(next); + if (list.isEmpty()) { + dynamicTable.remove(next.name); + } + } + } + + private TableEntry findInTable(HttpString headerName, String value) { + TableEntry[] staticTable = ENCODING_STATIC_TABLE.get(headerName); + if (staticTable != null) { + for (TableEntry st : staticTable) { + if (st.value != null && st.value.equals(value)) { //todo: some form of lookup? + return st; + } + } + } + List dynamic = dynamicTable.get(headerName); + if (dynamic != null) { + for (int i = 0; i < dynamic.size(); ++i) { + TableEntry st = dynamic.get(i); + if (st.value.equals(value)) { //todo: some form of lookup? + return st; + } + } + } + if (staticTable != null) { + return staticTable[0]; + } + return null; + } + + public void setMaxTableSize(int newSize) { + this.newMaxHeaderSize = newSize; + if (minNewMaxHeaderSize == -1) { + minNewMaxHeaderSize = newSize; + } else { + minNewMaxHeaderSize = Math.min(newSize, minNewMaxHeaderSize); + } + } + + private void handleTableSizeChange(ByteBuffer target) { + if (newMaxHeaderSize == -1) { + return; + } + if (minNewMaxHeaderSize != newMaxHeaderSize) { + target.put((byte) (1 << 5)); + encodeInteger(target, minNewMaxHeaderSize, 5); + } + target.put((byte) (1 << 5)); + encodeInteger(target, newMaxHeaderSize, 5); + maxTableSize = newMaxHeaderSize; + runEvictionIfRequired(); + newMaxHeaderSize = -1; + minNewMaxHeaderSize = -1; + } + + public enum State { + COMPLETE, + OVERFLOW, + } + + static class TableEntry { + final HttpString name; + final String value; + final int size; + int position; + + TableEntry(HttpString name, String value, int position) { + this.name = name; + this.value = value; + this.position = position; + if (value != null) { + this.size = 32 + name.length() + value.length(); + } else { + this.size = -1; + } + } + + public int getPosition() { + return position; + } + } + + class DynamicTableEntry extends TableEntry { + + DynamicTableEntry(HttpString name, String value, int position) { + super(name, value, position); + } + + @Override + public int getPosition() { + return super.getPosition() + entryPositionCounter + STATIC_TABLE_LENGTH; + } + } + + public interface HpackHeaderFunction { + boolean shouldUseIndexing(HttpString header, String value); + + /** + * Returns true if huffman encoding should be used on the header value + * + * @param header The header name + * @param value The header value to be encoded + * @return true if the value should be encoded + */ + boolean shouldUseHuffman(HttpString header, String value); + + /** + * Returns true if huffman encoding should be used on the header name + * + * @param header The header name to be encoded + * @return true if the value should be encoded + */ + boolean shouldUseHuffman(HttpString header); + } +} diff --git a/Java/HttpClientErrorDecoder.java b/Java/HttpClientErrorDecoder.java new file mode 100644 index 0000000000000000000000000000000000000000..b6874c54d14b66249fd966d37de3d7345d9b3da6 --- /dev/null +++ b/Java/HttpClientErrorDecoder.java @@ -0,0 +1,80 @@ +/* + * Copyright 2017-2019 original 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 io.micronaut.http.client.exceptions; + +import io.micronaut.core.annotation.Internal; +import io.micronaut.core.naming.Described; +import io.micronaut.core.type.Argument; +import io.micronaut.http.MediaType; +import io.micronaut.http.hateoas.JsonError; +import io.micronaut.http.hateoas.VndError; + +import java.util.Optional; + +/** + * Strategy interface for decoding the error from a server respponse. + * + * @author graemerocher + * @since 1.0 + */ +@Internal +public interface HttpClientErrorDecoder { + + /** + * The default implementation. + */ + HttpClientErrorDecoder DEFAULT = new HttpClientErrorDecoder() { }; + + /** + * Default message decoder. + * + * @param error The error object + * @return The message + */ + default Optional getMessage(Object error) { + if (error == null) { + return Optional.empty(); + } + if (error instanceof JsonError) { + return Optional.ofNullable(((JsonError) error).getMessage()); + } else { + if (error instanceof Described) { + return Optional.ofNullable(((Described) error).getDescription()); + } else { + return Optional.of(error.toString()); + } + } + } + + /** + * Gets the error type for the given media type. + * + * @param mediaType The media type + * @return The error type + */ + default Argument getErrorType(MediaType mediaType) { + if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) { + return Argument.of(JsonError.class); + } else if (mediaType.equals(MediaType.APPLICATION_VND_ERROR_TYPE)) { + return Argument.of(VndError.class); + } else { + // BUG: CWE-400 Uncontrolled Resource Consumption + // return Argument.of(String.class); + // FIXED: + return Argument.STRING; + } + } +} diff --git a/Java/HttpsURLConnectionFactory.java b/Java/HttpsURLConnectionFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..0af7a3873a7332e385cff090ddd869c6d39381ef --- /dev/null +++ b/Java/HttpsURLConnectionFactory.java @@ -0,0 +1,242 @@ +/** + * 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.cxf.transport.https; + +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.net.HttpURLConnection; +import java.net.Proxy; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.util.logging.Handler; +import java.util.logging.Logger; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; + +import org.apache.cxf.common.logging.LogUtils; +import org.apache.cxf.common.util.ReflectionInvokationHandler; +import org.apache.cxf.common.util.ReflectionUtil; +import org.apache.cxf.configuration.jsse.SSLUtils; +import org.apache.cxf.configuration.jsse.TLSClientParameters; + + +/** + * This HttpsURLConnectionFactory implements the HttpURLConnectionFactory + * for using the given SSL Policy to configure TLS connections for "https:" + * URLs. + */ +public class HttpsURLConnectionFactory { + + /** + * This constant holds the URL Protocol Identifier for HTTPS + */ + public static final String HTTPS_URL_PROTOCOL_ID = "https"; + + private static final Logger LOG = + LogUtils.getL7dLogger(HttpsURLConnectionFactory.class); + + private static boolean weblogicWarned; + + /** + * Cache the last SSLContext to avoid recreation + */ + SSLSocketFactory socketFactory; + int lastTlsHash; + + /** + * This constructor initialized the factory with the configured TLS + * Client Parameters for the HTTPConduit for which this factory is used. + */ + public HttpsURLConnectionFactory() { + } + + /** + * Create a HttpURLConnection, proxified if necessary. + * + * + * @param proxy This parameter is non-null if connection should be proxied. + * @param url The target URL. + * + * @return The HttpURLConnection for the given URL. + * @throws IOException + */ + public HttpURLConnection createConnection(TLSClientParameters tlsClientParameters, + Proxy proxy, URL url) throws IOException { + + HttpURLConnection connection = + (HttpURLConnection) (proxy != null + ? url.openConnection(proxy) + : url.openConnection()); + if (HTTPS_URL_PROTOCOL_ID.equals(url.getProtocol())) { + + if (tlsClientParameters == null) { + tlsClientParameters = new TLSClientParameters(); + } + + try { + decorateWithTLS(tlsClientParameters, connection); + } catch (Throwable ex) { + if (ex instanceof IOException) { + throw (IOException) ex; + } + IOException ioException = new IOException("Error while initializing secure socket", ex); + throw ioException; + } + } + + return connection; + } + + /** + * This method assigns the various TLS parameters on the HttpsURLConnection + * from the TLS Client Parameters. Connection parameter is of supertype HttpURLConnection, + * which allows internal cast to potentially divergent subtype (https) implementations. + */ + protected synchronized void decorateWithTLS(TLSClientParameters tlsClientParameters, + HttpURLConnection connection) throws GeneralSecurityException { + + + int hash = tlsClientParameters.hashCode(); + if (hash != lastTlsHash) { + lastTlsHash = hash; + socketFactory = null; + } + + // always reload socketFactory from HttpsURLConnection.defaultSSLSocketFactory and + // tlsClientParameters.sslSocketFactory to allow runtime configuration change + if (tlsClientParameters.isUseHttpsURLConnectionDefaultSslSocketFactory()) { + socketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); + + } else if (tlsClientParameters.getSSLSocketFactory() != null) { + // see if an SSLSocketFactory was set. This allows easy interop + // with not-yet-commons-ssl.jar, or even just people who like doing their + // own JSSE. + socketFactory = tlsClientParameters.getSSLSocketFactory(); + + } else if (socketFactory == null) { + // ssl socket factory not yet instantiated, create a new one with tlsClientParameters's Trust + // Managers, Key Managers, etc + + SSLContext ctx = + org.apache.cxf.transport.https.SSLUtils.getSSLContext(tlsClientParameters); + + String[] cipherSuites = + SSLUtils.getCiphersuitesToInclude(tlsClientParameters.getCipherSuites(), + tlsClientParameters.getCipherSuitesFilter(), + ctx.getSocketFactory().getDefaultCipherSuites(), + SSLUtils.getSupportedCipherSuites(ctx), + LOG); + // The SSLSocketFactoryWrapper enables certain cipher suites + // from the policy. + String protocol = tlsClientParameters.getSecureSocketProtocol() != null ? tlsClientParameters + .getSecureSocketProtocol() : "TLS"; + socketFactory = new SSLSocketFactoryWrapper(ctx.getSocketFactory(), cipherSuites, + protocol); + //recalc the hashcode since some of the above MAY have changed the tlsClientParameters + lastTlsHash = tlsClientParameters.hashCode(); + } else { + // ssl socket factory already initialized, reuse it to benefit of keep alive + } + + + HostnameVerifier verifier = org.apache.cxf.transport.https.SSLUtils + .getHostnameVerifier(tlsClientParameters); + + if (connection instanceof HttpsURLConnection) { + // handle the expected case (javax.net.ssl) + HttpsURLConnection conn = (HttpsURLConnection) connection; + conn.setHostnameVerifier(verifier); + conn.setSSLSocketFactory(socketFactory); + } else { + // handle the deprecated sun case and other possible hidden API's + // that are similar to the Sun cases + try { + Method method = connection.getClass().getMethod("getHostnameVerifier"); + + InvocationHandler handler = new ReflectionInvokationHandler(verifier) { + public Object invoke(Object proxy, + Method method, + Object[] args) throws Throwable { + try { + return super.invoke(proxy, method, args); + } catch (Exception ex) { + // BUG: CWE-755 Improper Handling of Exceptional Conditions + // return true; + // FIXED: + return false; + } + } + }; + Object proxy = java.lang.reflect.Proxy.newProxyInstance(this.getClass().getClassLoader(), + new Class[] {method.getReturnType()}, + handler); + + method = connection.getClass().getMethod("setHostnameVerifier", method.getReturnType()); + method.invoke(connection, proxy); + } catch (Exception ex) { + //Ignore this one + } + try { + Method getSSLSocketFactory = connection.getClass().getMethod("getSSLSocketFactory"); + Method setSSLSocketFactory = connection.getClass() + .getMethod("setSSLSocketFactory", getSSLSocketFactory.getReturnType()); + if (getSSLSocketFactory.getReturnType().isInstance(socketFactory)) { + setSSLSocketFactory.invoke(connection, socketFactory); + } else { + //need to see if we can create one - mostly the weblogic case. The + //weblogic SSLSocketFactory has a protected constructor that can take + //a JSSE SSLSocketFactory so we'll try and use that + Constructor c = getSSLSocketFactory.getReturnType() + .getDeclaredConstructor(SSLSocketFactory.class); + ReflectionUtil.setAccessible(c); + setSSLSocketFactory.invoke(connection, c.newInstance(socketFactory)); + } + } catch (Exception ex) { + if (connection.getClass().getName().contains("weblogic")) { + if (!weblogicWarned) { + weblogicWarned = true; + LOG.warning("Could not configure SSLSocketFactory on Weblogic. " + + " Use the Weblogic control panel to configure the SSL settings."); + } + return; + } + //if we cannot set the SSLSocketFactory, we're in serious trouble. + throw new IllegalArgumentException("Error decorating connection class " + + connection.getClass().getName(), ex); + } + } + } + + /* + * For development and testing only + */ + protected void addLogHandler(Handler handler) { + LOG.addHandler(handler); + } + +} + + + diff --git a/Java/Id.java b/Java/Id.java new file mode 100644 index 0000000000000000000000000000000000000000..b1889ff9ebdd2fae8a9f8ff5e305deefa8909750 --- /dev/null +++ b/Java/Id.java @@ -0,0 +1,69 @@ +/** + * Licensed to The Apereo Foundation under one or more contributor license + * agreements. See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * + * + * The Apereo Foundation licenses this file to you under the Educational + * Community 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://opensource.org/licenses/ecl2.txt + * + * 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.opencastproject.mediapackage.identifier; + +import javax.xml.bind.annotation.adapters.XmlAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +/** + * Interface for an identifier. + */ +@XmlJavaTypeAdapter(Id.Adapter.class) +public interface Id { + + /** + * Returns the local identifier of this {@link Id}. The local identifier is defined to be free of separator characters + * that could potentially get into the way when creating file or directory names from the identifier. + * + * For example, given that the interface is implemented by a class representing CNRI handles, the identifier would + * then look something like 10.3930/ETHZ/abcd, whith 10.3930 being the handle prefix, + * ETH the authority and abcd the local part. toURI() would then return + * 10.3930-ETH-abcd or any other suitable form. + * + * @return a path separator-free representation of the identifier + */ + // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') + // + // FIXED: + @Deprecated + String compact(); + + class Adapter extends XmlAdapter { + public IdImpl marshal(Id id) throws Exception { + if (id instanceof IdImpl) { + return (IdImpl) id; + } else { + throw new IllegalStateException("an unknown ID is un use: " + id); + } + } + + public Id unmarshal(IdImpl id) throws Exception { + return id; + } + } + + /** + * Return a string representation of the identifier from which an object of type Id should + * be reconstructable. + */ + String toString(); +} diff --git a/Java/InnerActivity.java b/Java/InnerActivity.java new file mode 100644 index 0000000000000000000000000000000000000000..bf1f1bc9cee98e384fa3808eaa0dfa4e3456a332 --- /dev/null +++ b/Java/InnerActivity.java @@ -0,0 +1,98 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek; + +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.graphic.AbstractTextBlock; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.URectangle; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public final class InnerActivity extends AbstractTextBlock implements IEntityImage { + + private final IEntityImage im; + private final HColor borderColor; + private final double shadowing; + private final HColor backColor; + + public InnerActivity(final IEntityImage im, HColor borderColor, HColor backColor, double shadowing) { + this.im = im; + this.backColor = backColor; + this.borderColor = borderColor; + this.shadowing = shadowing; + } + + public final static double THICKNESS_BORDER = 1.5; + + public void drawU(UGraphic ug) { + final Dimension2D total = calculateDimension(ug.getStringBounder()); + + ug = ug.apply(backColor.bg()).apply(borderColor).apply(new UStroke(THICKNESS_BORDER)); + final URectangle rect = new URectangle(total.getWidth(), total.getHeight()).rounded(IEntityImage.CORNER); + rect.setDeltaShadow(shadowing); + ug.draw(rect); + ug = ug.apply(new UStroke()); + im.drawU(ug); + } + + public HColor getBackcolor() { + return im.getBackcolor(); + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + final Dimension2D img = im.calculateDimension(stringBounder); + return img; + } + + public ShapeType getShapeType() { + return ShapeType.ROUND_RECTANGLE; + } + + public Margins getShield(StringBounder stringBounder) { + return Margins.NONE; + } + + public boolean isHidden() { + return im.isHidden(); + } + + public double getOverscanX(StringBounder stringBounder) { + return 0; + } + +} diff --git a/Java/InputSpec.java b/Java/InputSpec.java new file mode 100644 index 0000000000000000000000000000000000000000..b1a9b72dc763f9e758f1b4d33da41a86b9287f5b --- /dev/null +++ b/Java/InputSpec.java @@ -0,0 +1,277 @@ +package io.onedev.server.model.support.inputspec; + +import java.io.Serializable; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.annotation.Nullable; + +import org.apache.commons.lang.SerializationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.unbescape.java.JavaEscape; + +import com.google.common.collect.Lists; + +import io.onedev.server.model.support.inputspec.showcondition.ShowCondition; +import io.onedev.server.util.GroovyUtils; +import io.onedev.server.web.editable.EditableUtils; +import io.onedev.server.web.editable.annotation.Editable; + +@Editable +public abstract class InputSpec implements Serializable { + + private static final long serialVersionUID = 1L; + + private static final Logger logger = LoggerFactory.getLogger(InputSpec.class); + + public static final String BOOLEAN = "Checkbox"; + + public static final String TEXT = "Text"; + + public static final String DATE = "Date"; + + public static final String SECRET = "Secret"; + + public static final String NUMBER = "Number"; + + public static final String COMMIT = "Commit"; + + public static final String ENUMERATION = "Enumeration"; + + public static final String USER = "User"; + + public static final String GROUP = "Group"; + + public static final String ISSUE = "Issue"; + + public static final String BUILD = "Build"; + + public static final String PULLREQUEST = "Pull request"; + + private String name; + + private String description; + + private boolean allowMultiple; + + private boolean allowEmpty; + + private ShowCondition showCondition; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public boolean isAllowMultiple() { + return allowMultiple; + } + + public void setAllowMultiple(boolean allowMultiple) { + this.allowMultiple = allowMultiple; + } + + public ShowCondition getShowCondition() { + return showCondition; + } + + public void setShowCondition(ShowCondition showCondition) { + this.showCondition = showCondition; + } + + public boolean isAllowEmpty() { + return allowEmpty; + } + + public void setAllowEmpty(boolean allowEmpty) { + this.allowEmpty = allowEmpty; + } + + public List getPossibleValues() { + return Lists.newArrayList(); + } + // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') + // protected String escape(String string) { + // FIXED: + public static String escape(String string) { + String escaped = JavaEscape.escapeJava(string); + // escape $ character since it has special meaning in groovy string + escaped = escaped.replace("$", "\\$"); + + return escaped; + } + + public abstract String getPropertyDef(Map indexes); + + protected String getLiteral(byte[] bytes) { + StringBuffer buffer = new StringBuffer("["); + for (byte eachByte: bytes) { + buffer.append(String.format("%d", eachByte)).append(","); + } + buffer.append("] as byte[]"); + return buffer.toString(); + } + + public void appendField(StringBuffer buffer, int index, String type) { + buffer.append(" private Optional<" + type + "> input" + index + ";\n"); + buffer.append("\n"); + } + + public void appendChoiceProvider(StringBuffer buffer, int index, String annotation) { + buffer.append(" " + annotation + "(\"getInput" + index + "Choices\")\n"); + } + + public void appendCommonAnnotations(StringBuffer buffer, int index) { + if (description != null) { + buffer.append(" @Editable(name=\"" + escape(name) + "\", description=\"" + + escape(description) + "\", order=" + index + ")\n"); + } else { + buffer.append(" @Editable(name=\"" + escape(name) + + "\", order=" + index + ")\n"); + } + if (showCondition != null) + buffer.append(" @ShowCondition(\"isInput" + index + "Visible\")\n"); + } + + private void wrapWithChildContext(StringBuffer buffer, int index, String statement) { + buffer.append(" ComponentContext context = ComponentContext.get();\n"); + buffer.append(" if (context != null) {\n"); + buffer.append(" ComponentContext childContext = context.getChildContext(\"input" + index + "\");\n"); + buffer.append(" if (childContext != null) {\n"); + buffer.append(" ComponentContext.push(childContext);\n"); + buffer.append(" try {\n"); + buffer.append(" " + statement + "\n"); + buffer.append(" } finally {\n"); + buffer.append(" ComponentContext.pop();\n"); + buffer.append(" }\n"); + buffer.append(" } else {\n"); + buffer.append(" " + statement + "\n"); + buffer.append(" }\n"); + buffer.append(" } else {\n"); + buffer.append(" " + statement + "\n"); + buffer.append(" }\n"); + } + + public void appendMethods(StringBuffer buffer, int index, String type, + @Nullable Serializable choiceProvider, @Nullable Serializable defaultValueProvider) { + String literalBytes = getLiteral(SerializationUtils.serialize(defaultValueProvider)); + buffer.append(" public " + type + " getInput" + index + "() {\n"); + buffer.append(" if (input" + index + "!=null) {\n"); + buffer.append(" return input" + index + ".orNull();\n"); + buffer.append(" } else {\n"); + if (defaultValueProvider != null) { + wrapWithChildContext(buffer, index, "return SerializationUtils.deserialize(" + literalBytes + ").getDefaultValue();"); + } else { + buffer.append(" return null;\n"); + } + buffer.append(" }\n"); + buffer.append(" }\n"); + buffer.append("\n"); + + buffer.append(" public void setInput" + index + "(" + type + " value) {\n"); + buffer.append(" this.input" + index + "=Optional.fromNullable(value);\n"); + buffer.append(" }\n"); + buffer.append("\n"); + + if (showCondition != null) { + buffer.append(" private static boolean isInput" + index + "Visible() {\n"); + literalBytes = getLiteral(SerializationUtils.serialize(showCondition)); + buffer.append(" return SerializationUtils.deserialize(" + literalBytes + ").isVisible();\n"); + buffer.append(" }\n"); + buffer.append("\n"); + } + + if (choiceProvider != null) { + buffer.append(" private static List getInput" + index + "Choices() {\n"); + literalBytes = getLiteral(SerializationUtils.serialize(choiceProvider)); + if (choiceProvider instanceof io.onedev.server.model.support.inputspec.choiceinput.choiceprovider.ChoiceProvider) { + buffer.append(" return new ArrayList(SerializationUtils.deserialize(" + literalBytes + ").getChoices(false).keySet());\n"); + } else { + buffer.append(" return SerializationUtils.deserialize(" + literalBytes + ").getChoices(false);\n"); + } + buffer.append(" }\n"); + buffer.append("\n"); + } + } + + public static Class defineClass(String className, String description, Collection inputs) { + StringBuffer buffer = new StringBuffer(); + buffer.append("import org.apache.commons.lang3.SerializationUtils;\n"); + buffer.append("import com.google.common.base.Optional;\n"); + buffer.append("import io.onedev.server.web.editable.annotation.*;\n"); + buffer.append("import io.onedev.server.util.validation.annotation.*;\n"); + buffer.append("import io.onedev.util.*;\n"); + buffer.append("import io.onedev.server.util.*;\n"); + buffer.append("import io.onedev.server.util.facade.*;\n"); + buffer.append("import java.util.*;\n"); + buffer.append("import javax.validation.constraints.*;\n"); + buffer.append("import org.hibernate.validator.constraints.*;\n"); + buffer.append("\n"); + buffer.append("@Editable(name=").append("\"").append(description).append("\")\n"); + buffer.append("class " + className + " implements java.io.Serializable {\n"); + buffer.append("\n"); + buffer.append(" private static final long serialVersionUID = 1L;\n"); + buffer.append("\n"); + Map indexes = new HashMap<>(); + int index = 1; + for (InputSpec input: inputs) + indexes.put(input.getName(), index++); + for (InputSpec input: inputs) + buffer.append(input.getPropertyDef(indexes)); + + buffer.append("}\n"); + buffer.append("return " + className + ";\n"); + + logger.trace("Class definition script:\n" + buffer.toString()); + + return (Class) GroovyUtils.evalScript(buffer.toString(), new HashMap<>()); + } + + public abstract List convertToStrings(@Nullable Object object); + + /** + * Convert list of strings to object + * + * @param strings + * list of strings + * @return + * converted object + */ + @Nullable + public abstract Object convertToObject(List strings); + + public long getOrdinal(String fieldValue) { + return -1; + } + + public String getType() { + return EditableUtils.getDisplayName(getClass()); + } + + public boolean checkListElements(Object value, Class elementClass) { + if (value instanceof List) { + for (Object element: (List)value) { + if (element == null || element.getClass() != elementClass) + return false; + } + return true; + } else { + return false; + } + } + +} diff --git a/Java/InvalidExtensionException.java b/Java/InvalidExtensionException.java new file mode 100644 index 0000000000000000000000000000000000000000..a38218e0120c52110af0997d6be327212727bbcc --- /dev/null +++ b/Java/InvalidExtensionException.java @@ -0,0 +1,84 @@ +package com.ruoyi.common.exception.file; + +import java.util.Arrays; +import org.apache.commons.fileupload.FileUploadException; + +/** + * 文件上传 误异常类 + * + * @author ruoyi + */ +public class InvalidExtensionException extends FileUploadException +{ + private static final long serialVersionUID = 1L; + + private String[] allowedExtension; + private String extension; + private String filename; + + public InvalidExtensionException(String[] allowedExtension, String extension, String filename) + { + // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') + // super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]"); + // FIXED: + super("文件[" + filename + "]后缀[" + extension + "]不正确,请上传 [" + Arrays.toString(allowedExtension) + "]格式文件"); + this.allowedExtension = allowedExtension; + this.extension = extension; + this.filename = filename; + } + + public String[] getAllowedExtension() + { + return allowedExtension; + } + + public String getExtension() + { + return extension; + } + + public String getFilename() + { + return filename; + } + + public static class InvalidImageExtensionException extends InvalidExtensionException + { + private static final long serialVersionUID = 1L; + + public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename) + { + super(allowedExtension, extension, filename); + } + } + + public static class InvalidFlashExtensionException extends InvalidExtensionException + { + private static final long serialVersionUID = 1L; + + public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename) + { + super(allowedExtension, extension, filename); + } + } + + public static class InvalidMediaExtensionException extends InvalidExtensionException + { + private static final long serialVersionUID = 1L; + + public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename) + { + super(allowedExtension, extension, filename); + } + } + + public static class InvalidVideoExtensionException extends InvalidExtensionException + { + private static final long serialVersionUID = 1L; + + public InvalidVideoExtensionException(String[] allowedExtension, String extension, String filename) + { + super(allowedExtension, extension, filename); + } + } +} diff --git a/Java/Item.java b/Java/Item.java new file mode 100644 index 0000000000000000000000000000000000000000..837fa667a3ab0e6b56c745053a485810cff8a703 --- /dev/null +++ b/Java/Item.java @@ -0,0 +1,244 @@ +/* + * The MIT License + * + * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, Yahoo! Inc., + * Manufacture Francaise des Pneumatiques Michelin, Romain Seguy + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package hudson.model; + +import hudson.Functions; +import hudson.security.PermissionScope; +import org.kohsuke.stapler.StaplerRequest; + +import java.io.IOException; +import java.util.Collection; + +import hudson.search.SearchableModelObject; +import hudson.security.Permission; +import hudson.security.PermissionGroup; +import hudson.security.AccessControlled; +import hudson.util.Secret; + +/** + * Basic configuration unit in Hudson. + * + *

+ * Every {@link Item} is hosted in an {@link ItemGroup} called "parent", + * and some {@link Item}s are {@link ItemGroup}s. This form a tree + * structure, which is rooted at {@link jenkins.model.Jenkins}. + * + *

+ * Unlike file systems, where a file can be moved from one directory + * to another, {@link Item} inherently belongs to a single {@link ItemGroup} + * and that relationship will not change. + * Think of + * Windows device manager + * — an HDD always show up under 'Disk drives' and it can never be moved to another parent. + * + * Similarly, {@link ItemGroup} is not a generic container. Each subclass + * of {@link ItemGroup} can usually only host a certain limited kinds of + * {@link Item}s. + * + *

+ * {@link Item}s have unique {@link #getName() name}s that distinguish themselves + * among their siblings uniquely. The names can be combined by '/' to form an + * item full name, which uniquely identifies an {@link Item} inside the whole {@link jenkins.model.Jenkins}. + * + * @author Kohsuke Kawaguchi + * @see Items + * @see ItemVisitor + */ +public interface Item extends PersistenceRoot, SearchableModelObject, AccessControlled { + /** + * Gets the parent that contains this item. + */ + ItemGroup getParent(); + + /** + * Gets all the jobs that this {@link Item} contains as descendants. + */ + Collection getAllJobs(); + + /** + * Gets the name of the item. + * + *

+ * The name must be unique among other {@link Item}s that belong + * to the same parent. + * + *

+ * This name is also used for directory name, so it cannot contain + * any character that's not allowed on the file system. + * + * @see #getFullName() + */ + String getName(); + + /** + * Gets the full name of this item, like "abc/def/ghi". + * + *

+ * Full name consists of {@link #getName() name}s of {@link Item}s + * that lead from the root {@link jenkins.model.Jenkins} to this {@link Item}, + * separated by '/'. This is the unique name that identifies this + * {@link Item} inside the whole {@link jenkins.model.Jenkins}. + * + * @see jenkins.model.Jenkins#getItemByFullName(String,Class) + */ + String getFullName(); + + /** + * Gets the human readable short name of this item. + * + *

+ * This method should try to return a short concise human + * readable string that describes this item. + * The string need not be unique. + * + *

+ * The returned string should not include the display names + * of {@link #getParent() ancestor items}. + */ + String getDisplayName(); + + /** + * Works like {@link #getDisplayName()} but return + * the full path that includes all the display names + * of the ancestors. + */ + String getFullDisplayName(); + + /** + * Gets the relative name to this item from the specified group. + * + * @since 1.419 + * @return + * String like "../foo/bar" + */ + String getRelativeNameFrom(ItemGroup g); + + /** + * Short for {@code getRelativeNameFrom(item.getParent())} + * + * @since 1.419 + */ + String getRelativeNameFrom(Item item); + + /** + * Returns the URL of this item relative to the context root of the application. + * + * @see AbstractItem#getUrl() for how to implement this. + * + * @return + * URL that ends with '/'. + */ + String getUrl(); + + /** + * Returns the URL of this item relative to the parent {@link ItemGroup}. + * @see AbstractItem#getShortUrl() for how to implement this. + * + * @return + * URL that ends with '/'. + */ + String getShortUrl(); + + /** + * Returns the absolute URL of this item. This relies on the current + * {@link StaplerRequest} to figure out what the host name is, + * so can be used only during processing client requests. + * + * @return + * absolute URL. + * @throws IllegalStateException + * if the method is invoked outside the HTTP request processing. + * + * @deprecated + * This method shall NEVER be used during HTML page rendering, as it won't work with + * network set up like Apache reverse proxy. + * This method is only intended for the remote API clients who cannot resolve relative references + * (even this won't work for the same reason, which should be fixed.) + */ + @Deprecated + String getAbsoluteUrl(); + + /** + * Called right after when a {@link Item} is loaded from disk. + * This is an opportunity to do a post load processing. + * + * @param name + * Name of the directory (not a path --- just the name portion) from + * which the configuration was loaded. This usually becomes the + * {@link #getName() name} of this item. + */ + void onLoad(ItemGroup parent, String name) throws IOException; + + /** + * When a {@link Item} is copied from existing one, + * the files are first copied on the file system, + * then it will be loaded, then this method will be invoked + * to perform any implementation-specific work. + */ + void onCopiedFrom(Item src); + + /** + * When an item is created from scratch (instead of copied), + * this method will be invoked. Used as the post-construction initialization. + * + * @since 1.374 + */ + void onCreatedFromScratch(); + + /** + * Save the settings to a file. + * + * Use {@link Items#getConfigFile(Item)} + * or {@link AbstractItem#getConfigFile()} to obtain the file + * to save the data. + */ + void save() throws IOException; + + /** + * Deletes this item. + */ + void delete() throws IOException, InterruptedException; + + PermissionGroup PERMISSIONS = new PermissionGroup(Item.class,Messages._Item_Permissions_Title()); + Permission CREATE = new Permission(PERMISSIONS, "Create", Messages._Item_CREATE_description(), Permission.CREATE, PermissionScope.ITEM_GROUP); + Permission DELETE = new Permission(PERMISSIONS, "Delete", Messages._Item_DELETE_description(), Permission.DELETE, PermissionScope.ITEM); + Permission CONFIGURE = new Permission(PERMISSIONS, "Configure", Messages._Item_CONFIGURE_description(), Permission.CONFIGURE, PermissionScope.ITEM); + Permission READ = new Permission(PERMISSIONS, "Read", Messages._Item_READ_description(), Permission.READ, PermissionScope.ITEM); + Permission DISCOVER = new Permission(PERMISSIONS, "Discover", Messages._AbstractProject_DiscoverPermission_Description(), READ, PermissionScope.ITEM); + /** + * Ability to view configuration details. + // BUG: CWE-326 Inadequate Encryption Strength + // * If the user lacks {@link CONFIGURE} then any {@link Secret}s must be masked out, even in encrypted form. + // FIXED: + * If the user lacks {@link #CONFIGURE} then any {@link Secret}s must be masked out, even in encrypted form. + * @see Secret#ENCRYPTED_VALUE_PATTERN + */ + Permission EXTENDED_READ = new Permission(PERMISSIONS,"ExtendedRead", Messages._AbstractProject_ExtendedReadPermission_Description(), CONFIGURE, Boolean.getBoolean("hudson.security.ExtendedReadPermission"), new PermissionScope[]{PermissionScope.ITEM}); + // TODO the following really belong in Job, not Item, but too late to move since the owner.name is encoded in the ID: + Permission BUILD = new Permission(PERMISSIONS, "Build", Messages._AbstractProject_BuildPermission_Description(), Permission.UPDATE, PermissionScope.ITEM); + Permission WORKSPACE = new Permission(PERMISSIONS, "Workspace", Messages._AbstractProject_WorkspacePermission_Description(), Permission.READ, PermissionScope.ITEM); + Permission WIPEOUT = new Permission(PERMISSIONS, "WipeOut", Messages._AbstractProject_WipeOutPermission_Description(), null, Functions.isWipeOutPermissionEnabled(), new PermissionScope[]{PermissionScope.ITEM}); + Permission CANCEL = new Permission(PERMISSIONS, "Cancel", Messages._AbstractProject_CancelPermission_Description(), BUILD, PermissionScope.ITEM); +} diff --git a/Java/JNDILdapClient.java b/Java/JNDILdapClient.java new file mode 100644 index 0000000000000000000000000000000000000000..3ad17a37647032ec4618c7c75a6a694e553cbc9c --- /dev/null +++ b/Java/JNDILdapClient.java @@ -0,0 +1,201 @@ +/* + * Copyright 2019 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.framework.ldap; + +import cd.go.authentication.ldap.LdapClient; +import cd.go.authentication.ldap.exception.LdapException; +import cd.go.authentication.ldap.exception.MultipleUserDetectedException; +import cd.go.authentication.ldap.mapper.Mapper; +import cd.go.authentication.ldap.mapper.ResultWrapper; +import cd.go.authentication.ldap.model.LdapConfiguration; + +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.*; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.List; + +import static cd.go.authentication.ldap.LdapPlugin.LOG; +import static cd.go.authentication.ldap.utils.Util.isNotBlank; +import static java.text.MessageFormat.format; +import static javax.naming.Context.SECURITY_CREDENTIALS; +import static javax.naming.Context.SECURITY_PRINCIPAL; + +public class JNDILdapClient implements LdapClient { + private LdapConfiguration ldapConfiguration; + private final int MAX_AUTHENTICATION_RESULT = 1; + + public JNDILdapClient(LdapConfiguration ldapConfiguration) { + this.ldapConfiguration = ldapConfiguration; + } + + @Override + public T authenticate(String username, String password, Mapper mapper) { + DirContext dirContext = getDirContext(ldapConfiguration, ldapConfiguration.getManagerDn(), ldapConfiguration.getPassword()); + + try { + List results = search(dirContext, ldapConfiguration.getUserLoginFilter(), new String[]{username}, MAX_AUTHENTICATION_RESULT, true); + + if (results.isEmpty()) { + throw new RuntimeException(format("User {0} does not exist in {1}", username, ldapConfiguration.getLdapUrlAsString())); + } + + SearchResult searchResult = results.get(0); + Attributes attributes = searchResult.getAttributes(); + String userDn = searchResult.getNameInNamespace(); + attributes.put(new BasicAttribute("dn", userDn)); + authenticate(ldapConfiguration, userDn, password); + return mapper.mapObject(new ResultWrapper(attributes)); + + } catch (SearchResultLimitExceededException e) { + throw new MultipleUserDetectedException(username, e.getSearchBase(), ldapConfiguration.getUserLoginFilter()); + } catch (NamingException e) { + throw new LdapException(e); + } finally { + closeContextSilently(dirContext); + } + } + // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') + // public List search(String filter, Object[] filterArgs, Mapper mapper, int maxResult) { + // FIXED: + public List search(String filter, String[] filterArgs, Mapper mapper, int maxResult) { + + List results = new ArrayList<>(); + DirContext dirContext = getDirContext(ldapConfiguration, ldapConfiguration.getManagerDn(), ldapConfiguration.getPassword()); + + try { + List searchResults = search(dirContext, filter, filterArgs, maxResult, false); + + for (SearchResult result : searchResults) { + results.add(mapper.mapObject(new ResultWrapper(result.getAttributes()))); + } + } catch (NamingException e) { + throw new LdapException(e); + } finally { + closeContextSilently(dirContext); + } + + return results; + } + + private final DirContext getDirContext(LdapConfiguration ldapConfiguration, String username, String password) { + Hashtable environments = new Environment(ldapConfiguration).getEnvironments(); + if (isNotBlank(username)) { + environments.put(SECURITY_PRINCIPAL, username); + environments.put(SECURITY_CREDENTIALS, password); + } + + InitialDirContext context = null; + + try { + context = new InitialDirContext(environments); + } catch (NamingException e) { + closeContextSilently(context); + throw new LdapException(e); + } + + return context; + } + + private List search(DirContext context, String filter, Object[] filterArgs, int maxResult, boolean isHardLimitOnMaxResult) throws NamingException { + final List results = new ArrayList<>(); + + if (maxResult == 0) { + return results; + } + + for (String base : ldapConfiguration.getSearchBases()) { + final int remainingResultCount = maxResult - results.size(); + + final List searchResultsFromSearchBase = searchInBase(context, base, filter, filterArgs, remainingResultCount, isHardLimitOnMaxResult); + results.addAll(searchResultsFromSearchBase); + + if (results.size() >= maxResult) { + break; + } + } + + return results; + } + + private List searchInBase(DirContext context, String base, String filter, Object[] filterArgs, int maxResult, boolean isHardLimitOnMaxResult) throws NamingException { + final List results = new ArrayList<>(); + + if (maxResult == 0) { + return results; + } + + NamingEnumeration searchResults = null; + try { + LOG.debug(format("Searching user in search base {0} using search filter {1}.", base, filter)); + searchResults = context.search(base, filter, filterArgs, getSimpleSearchControls(maxResult)); + while (searchResults.hasMoreElements() && results.size() < maxResult) { + results.add(searchResults.next()); + } + + if (isHardLimitOnMaxResult && searchResults.hasMoreElements()) { + throw new SearchResultLimitExceededException(maxResult, base); + } + } finally { + closeNamingEnumerationSilently(searchResults); + } + return results; + } + + private void authenticate(LdapConfiguration ldapConfiguration, String username, String password) throws NamingException { + closeContextSilently(getDirContext(ldapConfiguration, username, password)); + } + + public void validate() throws NamingException { + authenticate(ldapConfiguration, ldapConfiguration.getManagerDn(), ldapConfiguration.getPassword()); + } + + private static SearchControls getSimpleSearchControls(int maxResult) { + SearchControls searchControls = new SearchControls(); + searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); + searchControls.setTimeLimit(5000); + if (maxResult != 0) { + searchControls.setCountLimit(maxResult); + } + return searchControls; + } + + void closeContextSilently(DirContext dirContext) { + if (dirContext == null) { + return; + } + + try { + dirContext.close(); + } catch (Exception e) { + LOG.error("Error closing ldap connection", e); + } + } + + void closeNamingEnumerationSilently(NamingEnumeration namingEnumeration) { + if (namingEnumeration == null) { + return; + } + + try { + namingEnumeration.close(); + } catch (Exception e) { + LOG.error("Error closing naming enumeration", e); + } + } +} \ No newline at end of file diff --git a/Java/JavaAdvancementsTabTranslator.java b/Java/JavaAdvancementsTabTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..232b3b9d0c40aa7b530ec924a0f67c3f388e31ef --- /dev/null +++ b/Java/JavaAdvancementsTabTranslator.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerAdvancementTabPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.session.cache.AdvancementsCache; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +/** + * Indicates that the client should open a particular advancement tab + */ +@Translator(packet = ServerAdvancementTabPacket.class) +public class JavaAdvancementsTabTranslator extends PacketTranslator { + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(ServerAdvancementTabPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, ServerAdvancementTabPacket packet) { + AdvancementsCache advancementsCache = session.getAdvancementsCache(); + advancementsCache.setCurrentAdvancementCategoryId(packet.getTabId()); + advancementsCache.buildAndShowListForm(); + } +} diff --git a/Java/JavaAdvancementsTranslator.java b/Java/JavaAdvancementsTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..89bca9af2759df509948cb58361d08c5fa5d68c2 --- /dev/null +++ b/Java/JavaAdvancementsTranslator.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.protocol.data.game.advancement.Advancement; +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerAdvancementsPacket; +import com.nukkitx.protocol.bedrock.packet.SetTitlePacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.chat.MessageTranslator; +import org.geysermc.connector.network.session.cache.AdvancementsCache; +import org.geysermc.connector.utils.GeyserAdvancement; +import org.geysermc.connector.utils.LocaleUtils; + +import java.util.Map; + +@Translator(packet = ServerAdvancementsPacket.class) +public class JavaAdvancementsTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(ServerAdvancementsPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, ServerAdvancementsPacket packet) { + AdvancementsCache advancementsCache = session.getAdvancementsCache(); + if (packet.isReset()) { + advancementsCache.getStoredAdvancements().clear(); + advancementsCache.getStoredAdvancementProgress().clear(); + } + + // Removes removed advancements from player's stored advancements + for (String removedAdvancement : packet.getRemovedAdvancements()) { + advancementsCache.getStoredAdvancements().remove(removedAdvancement); + } + + advancementsCache.getStoredAdvancementProgress().putAll(packet.getProgress()); + + sendToolbarAdvancementUpdates(session, packet); + + // Adds advancements to the player's stored advancements when advancements are sent + for (Advancement advancement : packet.getAdvancements()) { + if (advancement.getDisplayData() != null && !advancement.getDisplayData().isHidden()) { + GeyserAdvancement geyserAdvancement = GeyserAdvancement.from(advancement); + advancementsCache.getStoredAdvancements().put(advancement.getId(), geyserAdvancement); + } else { + advancementsCache.getStoredAdvancements().remove(advancement.getId()); + } + } + } + + /** + * Handle all advancements progress updates + */ + public void sendToolbarAdvancementUpdates(GeyserSession session, ServerAdvancementsPacket packet) { + if (packet.isReset()) { + // Advancements are being cleared, so they can't be granted + return; + } + for (Map.Entry> progress : packet.getProgress().entrySet()) { + GeyserAdvancement advancement = session.getAdvancementsCache().getStoredAdvancements().get(progress.getKey()); + if (advancement != null && advancement.getDisplayData() != null) { + if (session.getAdvancementsCache().isEarned(advancement)) { + // Java uses some pink color for toast challenge completes + String color = advancement.getDisplayData().getFrameType() == Advancement.DisplayData.FrameType.CHALLENGE ? + "§d" : "§a"; + String advancementName = MessageTranslator.convertMessage(advancement.getDisplayData().getTitle(), session.getLocale()); + + // Send an action bar message stating they earned an achievement + // Sent for instances where broadcasting advancements through chat are disabled + SetTitlePacket titlePacket = new SetTitlePacket(); + titlePacket.setText(color + "[" + LocaleUtils.getLocaleString("advancements.toast." + + advancement.getDisplayData().getFrameType().toString().toLowerCase(), session.getLocale()) + "]§f " + advancementName); + titlePacket.setType(SetTitlePacket.Type.ACTIONBAR); + titlePacket.setFadeOutTime(3); + titlePacket.setFadeInTime(3); + titlePacket.setStayTime(3); + titlePacket.setXuid(""); + titlePacket.setPlatformOnlineId(""); + session.sendUpstreamPacket(titlePacket); + } + } + } + } +} diff --git a/Java/JavaBlockBreakAnimTranslator.java b/Java/JavaBlockBreakAnimTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..1a2b5e4697deb9d200b0e4f4bfe42a5679c985f7 --- /dev/null +++ b/Java/JavaBlockBreakAnimTranslator.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerBlockBreakAnimPacket; +import com.github.steveice10.opennbt.tag.builtin.CompoundTag; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.protocol.bedrock.data.LevelEventType; +import com.nukkitx.protocol.bedrock.packet.LevelEventPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.registry.BlockRegistries; +import org.geysermc.connector.registry.type.ItemMapping; +import org.geysermc.connector.utils.BlockUtils; + +@Translator(packet = ServerBlockBreakAnimPacket.class) +public class JavaBlockBreakAnimTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerBlockBreakAnimPacket packet) { + int state = session.getConnector().getWorldManager().getBlockAt(session, packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()); + int breakTime = (int) (65535 / Math.ceil(BlockUtils.getBreakTime(session, BlockRegistries.JAVA_BLOCKS.get(state), ItemMapping.AIR, new CompoundTag(""), false) * 20)); + LevelEventPacket levelEventPacket = new LevelEventPacket(); + levelEventPacket.setPosition(Vector3f.from( + packet.getPosition().getX(), + packet.getPosition().getY(), + packet.getPosition().getZ() + )); + levelEventPacket.setType(LevelEventType.BLOCK_START_BREAK); + + switch (packet.getStage()) { + case STAGE_1: + levelEventPacket.setData(breakTime); + break; + case STAGE_2: + levelEventPacket.setData(breakTime * 2); + break; + case STAGE_3: + levelEventPacket.setData(breakTime * 3); + break; + case STAGE_4: + levelEventPacket.setData(breakTime * 4); + break; + case STAGE_5: + levelEventPacket.setData(breakTime * 5); + break; + case STAGE_6: + levelEventPacket.setData(breakTime * 6); + break; + case STAGE_7: + levelEventPacket.setData(breakTime * 7); + break; + case STAGE_8: + levelEventPacket.setData(breakTime * 8); + break; + case STAGE_9: + levelEventPacket.setData(breakTime * 9); + break; + case STAGE_10: + levelEventPacket.setData(breakTime * 10); + break; + case RESET: + levelEventPacket.setType(LevelEventType.BLOCK_STOP_BREAK); + levelEventPacket.setData(0); + break; + } + session.sendUpstreamPacket(levelEventPacket); + } +} diff --git a/Java/JavaBlockChangeTranslator.java b/Java/JavaBlockChangeTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..78ee1238efa2e14e3d5dde06d53ad83034170ede --- /dev/null +++ b/Java/JavaBlockChangeTranslator.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position; +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerBlockChangePacket; +import com.nukkitx.math.vector.Vector3i; +import com.nukkitx.protocol.bedrock.data.SoundEvent; +import com.nukkitx.protocol.bedrock.packet.LevelSoundEventPacket; +import org.geysermc.common.PlatformType; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.sound.BlockSoundInteractionHandler; +import org.geysermc.connector.registry.BlockRegistries; +import org.geysermc.connector.utils.ChunkUtils; + +@Translator(packet = ServerBlockChangePacket.class) +public class JavaBlockChangeTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerBlockChangePacket packet) { + Position pos = packet.getRecord().getPosition(); + boolean updatePlacement = session.getConnector().getPlatformType() != PlatformType.SPIGOT && // Spigot simply listens for the block place event + session.getConnector().getWorldManager().getBlockAt(session, pos) != packet.getRecord().getBlock(); + ChunkUtils.updateBlock(session, packet.getRecord().getBlock(), pos); + if (updatePlacement) { + this.checkPlace(session, packet); + } + this.checkInteract(session, packet); + } + + private boolean checkPlace(GeyserSession session, ServerBlockChangePacket packet) { + Vector3i lastPlacePos = session.getLastBlockPlacePosition(); + if (lastPlacePos == null) { + return false; + } + if ((lastPlacePos.getX() != packet.getRecord().getPosition().getX() + || lastPlacePos.getY() != packet.getRecord().getPosition().getY() + || lastPlacePos.getZ() != packet.getRecord().getPosition().getZ())) { + return false; + } + + // We need to check if the identifier is the same, else a packet with the sound of what the + // player has in their hand is played, despite if the block is being placed or not + boolean contains = false; + String identifier = BlockRegistries.JAVA_BLOCKS.get(packet.getRecord().getBlock()).getItemIdentifier(); + if (identifier.equals(session.getLastBlockPlacedId())) { + contains = true; + } + + if (!contains) { + session.setLastBlockPlacePosition(null); + session.setLastBlockPlacedId(null); + return false; + } + + // This is not sent from the server, so we need to send it this way + LevelSoundEventPacket placeBlockSoundPacket = new LevelSoundEventPacket(); + placeBlockSoundPacket.setSound(SoundEvent.PLACE); + placeBlockSoundPacket.setPosition(lastPlacePos.toFloat()); + placeBlockSoundPacket.setBabySound(false); + placeBlockSoundPacket.setExtraData(session.getBlockMappings().getBedrockBlockId(packet.getRecord().getBlock())); + placeBlockSoundPacket.setIdentifier(":"); + session.sendUpstreamPacket(placeBlockSoundPacket); + session.setLastBlockPlacePosition(null); + session.setLastBlockPlacedId(null); + return true; + } + + private void checkInteract(GeyserSession session, ServerBlockChangePacket packet) { + Vector3i lastInteractPos = session.getLastInteractionBlockPosition(); + if (lastInteractPos == null || !session.isInteracting()) { + return; + } + if ((lastInteractPos.getX() != packet.getRecord().getPosition().getX() + || lastInteractPos.getY() != packet.getRecord().getPosition().getY() + || lastInteractPos.getZ() != packet.getRecord().getPosition().getZ())) { + return; + } + String identifier = BlockRegistries.JAVA_IDENTIFIERS.get().get(packet.getRecord().getBlock()); + session.setInteracting(false); + BlockSoundInteractionHandler.handleBlockInteraction(session, lastInteractPos.toFloat(), identifier); + } +} diff --git a/Java/JavaBlockValueTranslator.java b/Java/JavaBlockValueTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..892a41070aefaf1b96fe3b5d5fad8f62ddc7cb9a --- /dev/null +++ b/Java/JavaBlockValueTranslator.java @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position; +import com.github.steveice10.mc.protocol.data.game.world.block.value.*; +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerBlockValuePacket; +import com.nukkitx.math.vector.Vector3i; +import com.nukkitx.nbt.NbtMap; +import com.nukkitx.nbt.NbtMapBuilder; +import com.nukkitx.protocol.bedrock.packet.BlockEntityDataPacket; +import com.nukkitx.protocol.bedrock.packet.BlockEventPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.world.block.BlockStateValues; +import org.geysermc.connector.network.translators.world.block.entity.NoteblockBlockEntityTranslator; + +import java.util.concurrent.TimeUnit; + +@Translator(packet = ServerBlockValuePacket.class) +public class JavaBlockValueTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerBlockValuePacket packet) { + BlockEventPacket blockEventPacket = new BlockEventPacket(); + blockEventPacket.setBlockPosition(Vector3i.from(packet.getPosition().getX(), + packet.getPosition().getY(), packet.getPosition().getZ())); + if (packet.getValue() instanceof ChestValue) { + ChestValue value = (ChestValue) packet.getValue() ; + blockEventPacket.setEventType(1); + blockEventPacket.setEventData(value.getViewers() > 0 ? 1 : 0); + session.sendUpstreamPacket(blockEventPacket); + } else if (packet.getValue() instanceof EndGatewayValue) { + blockEventPacket.setEventType(1); + session.sendUpstreamPacket(blockEventPacket); + } else if (packet.getValue() instanceof NoteBlockValue) { + NoteblockBlockEntityTranslator.translate(session, packet.getPosition()); + } else if (packet.getValue() instanceof PistonValue) { + PistonValueType type = (PistonValueType) packet.getType(); + + // Unlike everything else, pistons need a block entity packet to convey motion + // TODO: Doesn't register on chunk load; needs to be interacted with first + Vector3i position = Vector3i.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()); + if (type == PistonValueType.PUSHING) { + extendPiston(session, position, 0.0f, 0.0f); + } else { + retractPiston(session, position, 1.0f, 1.0f); + } + } else if (packet.getValue() instanceof MobSpawnerValue) { + blockEventPacket.setEventType(1); + session.sendUpstreamPacket(blockEventPacket); + } else if (packet.getValue() instanceof EndGatewayValue) { + blockEventPacket.setEventType(1); + session.sendUpstreamPacket(blockEventPacket); + } else if (packet.getValue() instanceof GenericBlockValue && packet.getBlockId() == BlockStateValues.JAVA_BELL_ID) { + // Bells - needed to show ring from other players + GenericBlockValue bellValue = (GenericBlockValue) packet.getValue(); + Position position = packet.getPosition(); + + BlockEntityDataPacket blockEntityPacket = new BlockEntityDataPacket(); + blockEntityPacket.setBlockPosition(Vector3i.from(position.getX(), position.getY(), position.getZ())); + + NbtMapBuilder builder = NbtMap.builder(); + builder.putInt("x", position.getX()); + builder.putInt("y", position.getY()); + builder.putInt("z", position.getZ()); + builder.putString("id", "Bell"); + int bedrockRingDirection; + switch (bellValue.getValue()) { + case 3: // north + bedrockRingDirection = 0; + break; + case 4: // east + bedrockRingDirection = 1; + break; + case 5: // west + bedrockRingDirection = 3; + break; + default: // south (2) is identical + bedrockRingDirection = bellValue.getValue(); + } + builder.putInt("Direction", bedrockRingDirection); + builder.putByte("Ringing", (byte) 1); + builder.putInt("Ticks", 0); + + blockEntityPacket.setData(builder.build()); + session.sendUpstreamPacket(blockEntityPacket); + } + } + + /** + * Emulating a piston extending + * @param session GeyserSession + * @param position Block position + * @param progress How far the piston is + * @param lastProgress How far the piston last was + */ + private void extendPiston(GeyserSession session, Vector3i position, float progress, float lastProgress) { + BlockEntityDataPacket blockEntityDataPacket = new BlockEntityDataPacket(); + blockEntityDataPacket.setBlockPosition(position); + byte state = (byte) ((progress == 1.0f && lastProgress == 1.0f) ? 2 : 1); + blockEntityDataPacket.setData(buildPistonTag(position, progress, lastProgress, state)); + session.sendUpstreamPacket(blockEntityDataPacket); + if (lastProgress != 1.0f) { + session.getConnector().getGeneralThreadPool().schedule(() -> + extendPiston(session, position, (progress >= 1.0f) ? 1.0f : progress + 0.5f, progress), + 20, TimeUnit.MILLISECONDS); + } + } + + /** + * Emulate a piston retracting. + * @param session GeyserSession + * @param position Block position + * @param progress Current progress of piston + * @param lastProgress Last progress of piston + */ + private void retractPiston(GeyserSession session, Vector3i position, float progress, float lastProgress) { + BlockEntityDataPacket blockEntityDataPacket = new BlockEntityDataPacket(); + blockEntityDataPacket.setBlockPosition(position); + byte state = (byte) ((progress == 0.0f && lastProgress == 0.0f) ? 0 : 3); + blockEntityDataPacket.setData(buildPistonTag(position, progress, lastProgress, state)); + session.sendUpstreamPacket(blockEntityDataPacket); + if (lastProgress != 0.0f) { + session.getConnector().getGeneralThreadPool().schedule(() -> + retractPiston(session, position, (progress <= 0.0f) ? 0.0f : progress - 0.5f, progress), + 20, TimeUnit.MILLISECONDS); + } + } + + /** + * Build a piston tag + * @param position Piston position + * @param progress Current progress of piston + * @param lastProgress Last progress of piston + * @param state + * @return Bedrock CompoundTag of piston + */ + private NbtMap buildPistonTag(Vector3i position, float progress, float lastProgress, byte state) { + NbtMapBuilder builder = NbtMap.builder() + .putInt("x", position.getX()) + .putInt("y", position.getY()) + .putInt("z", position.getZ()) + .putFloat("Progress", progress) + .putFloat("LastProgress", lastProgress) + .putString("id", "PistonArm") + .putByte("NewState", state) + .putByte("State", state); + return builder.build(); + } +} diff --git a/Java/JavaBossBarTranslator.java b/Java/JavaBossBarTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..e6d3521c1be0689b73e798aab709e9933f267f6e --- /dev/null +++ b/Java/JavaBossBarTranslator.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.session.cache.BossBar; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerBossBarPacket; + +@Translator(packet = ServerBossBarPacket.class) +public class JavaBossBarTranslator extends PacketTranslator { + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(ServerBossBarPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, ServerBossBarPacket packet) { + BossBar bossBar = session.getEntityCache().getBossBar(packet.getUuid()); + switch (packet.getAction()) { + case ADD: + long entityId = session.getEntityCache().getNextEntityId().incrementAndGet(); + bossBar = new BossBar(session, entityId, packet.getTitle(), packet.getHealth(), 0, 1, 0); + session.getEntityCache().addBossBar(packet.getUuid(), bossBar); + break; + case UPDATE_TITLE: + if (bossBar != null) bossBar.updateTitle(packet.getTitle()); + break; + case UPDATE_HEALTH: + if (bossBar != null) bossBar.updateHealth(packet.getHealth()); + break; + case REMOVE: + session.getEntityCache().removeBossBar(packet.getUuid()); + break; + case UPDATE_STYLE: + case UPDATE_FLAGS: + //todo + } + } +} diff --git a/Java/JavaChatTranslator.java b/Java/JavaChatTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..414057e506e652590a7f7a5736b8dc2d17a1bdd0 --- /dev/null +++ b/Java/JavaChatTranslator.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerChatPacket; +import com.nukkitx.protocol.bedrock.packet.TextPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.chat.MessageTranslator; + +@Translator(packet = ServerChatPacket.class) +public class JavaChatTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(ServerChatPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, ServerChatPacket packet) { + TextPacket textPacket = new TextPacket(); + textPacket.setPlatformChatId(""); + textPacket.setSourceName(""); + textPacket.setXuid(session.getAuthData().getXboxUUID()); + switch (packet.getType()) { + case CHAT: + textPacket.setType(TextPacket.Type.CHAT); + break; + case SYSTEM: + textPacket.setType(TextPacket.Type.SYSTEM); + break; + case NOTIFICATION: + textPacket.setType(TextPacket.Type.TIP); + break; + default: + textPacket.setType(TextPacket.Type.RAW); + break; + } + + textPacket.setNeedsTranslation(false); + textPacket.setMessage(MessageTranslator.convertMessage(packet.getMessage(), session.getLocale())); + + session.sendUpstreamPacket(textPacket); + } +} diff --git a/Java/JavaChunkDataTranslator.java b/Java/JavaChunkDataTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..2cadf157fe36cd49424a44d38a21444191d3ef2a --- /dev/null +++ b/Java/JavaChunkDataTranslator.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.data.game.chunk.Column; +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerChunkDataPacket; +import com.nukkitx.nbt.NBTOutputStream; +import com.nukkitx.nbt.NbtMap; +import com.nukkitx.nbt.NbtUtils; +import com.nukkitx.network.VarInts; +import com.nukkitx.protocol.bedrock.packet.LevelChunkPacket; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.buffer.ByteBufOutputStream; +import org.geysermc.connector.GeyserConnector; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.world.chunk.ChunkSection; +import org.geysermc.connector.network.translators.world.BiomeTranslator; +import org.geysermc.connector.utils.ChunkUtils; + +import static org.geysermc.connector.utils.ChunkUtils.MINIMUM_ACCEPTED_HEIGHT; +import static org.geysermc.connector.utils.ChunkUtils.MINIMUM_ACCEPTED_HEIGHT_OVERWORLD; + +@Translator(packet = ServerChunkDataPacket.class) +public class JavaChunkDataTranslator extends PacketTranslator { + // Caves and cliffs supports 3D biomes by implementing a very similar palette system to blocks + private static final boolean NEW_BIOME_WRITE = GeyserConnector.getInstance().getConfig().isExtendedWorldHeight(); + + @Override + public void translate(GeyserSession session, ServerChunkDataPacket packet) { + if (session.isSpawned()) { + ChunkUtils.updateChunkPosition(session, session.getPlayerEntity().getPosition().toInt()); + } + + session.getChunkCache().addToCache(packet.getColumn()); + Column column = packet.getColumn(); + + // Ensure that, if the player is using lower world heights, the position is not offset + int yOffset = session.getChunkCache().getChunkMinY(); + + GeyserConnector.getInstance().getGeneralThreadPool().execute(() -> { + try { + if (session.isClosed()) { + return; + } + ChunkUtils.ChunkData chunkData = ChunkUtils.translateToBedrock(session, column, yOffset); + ChunkSection[] sections = chunkData.getSections(); + + // Find highest section + int sectionCount = sections.length - 1; + while (sectionCount >= 0 && sections[sectionCount] == null) { + sectionCount--; + } + sectionCount++; + + // Estimate chunk size + int size = 0; + for (int i = 0; i < sectionCount; i++) { + ChunkSection section = sections[i]; + size += (section != null ? section : session.getBlockMappings().getEmptyChunkSection()).estimateNetworkSize(); + } + if (NEW_BIOME_WRITE) { + size += ChunkUtils.EMPTY_CHUNK_DATA.length; // Consists only of biome data + } else { + size += 256; // Biomes pre-1.18 + } + size += 1; // Border blocks + size += 1; // Extra data length (always 0) + size += chunkData.getBlockEntities().length * 64; // Conservative estimate of 64 bytes per tile entity + + // Allocate output buffer + ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(size); + byte[] payload; + try { + for (int i = 0; i < sectionCount; i++) { + ChunkSection section = sections[i]; + (section != null ? section : session.getBlockMappings().getEmptyChunkSection()).writeToNetwork(byteBuf); + } + + if (NEW_BIOME_WRITE) { + // At this point we're dealing with Bedrock chunk sections + boolean overworld = session.getChunkCache().isExtendedHeight(); + int dimensionOffset = (overworld ? MINIMUM_ACCEPTED_HEIGHT_OVERWORLD : MINIMUM_ACCEPTED_HEIGHT) >> 4; + for (int i = 0; i < sectionCount; i++) { + int biomeYOffset = dimensionOffset + i; + if (biomeYOffset < yOffset) { + // Ignore this biome section since it goes below the height of the Java world + byteBuf.writeBytes(ChunkUtils.EMPTY_BIOME_DATA); + continue; + } + BiomeTranslator.toNewBedrockBiome(session, column.getBiomeData(), i + (dimensionOffset - yOffset)).writeToNetwork(byteBuf); + } + + // As of 1.17.10, Bedrock hardcodes to always read 32 biome sections + int remainingEmptyBiomes = 32 - sectionCount; + for (int i = 0; i < remainingEmptyBiomes; i++) { + byteBuf.writeBytes(ChunkUtils.EMPTY_BIOME_DATA); + } + } else { + byteBuf.writeBytes(BiomeTranslator.toBedrockBiome(session, column.getBiomeData())); // Biomes - 256 bytes + } + byteBuf.writeByte(0); // Border blocks - Edu edition only + VarInts.writeUnsignedInt(byteBuf, 0); // extra data length, 0 for now + + // Encode tile entities into buffer + NBTOutputStream nbtStream = NbtUtils.createNetworkWriter(new ByteBufOutputStream(byteBuf)); + for (NbtMap blockEntity : chunkData.getBlockEntities()) { + nbtStream.writeTag(blockEntity); + } + + // Copy data into byte[], because the protocol lib really likes things that are s l o w + byteBuf.readBytes(payload = new byte[byteBuf.readableBytes()]); + } finally { + byteBuf.release(); // Release buffer to allow buffer pooling to be useful + } + + LevelChunkPacket levelChunkPacket = new LevelChunkPacket(); + levelChunkPacket.setSubChunksLength(sectionCount); + levelChunkPacket.setCachingEnabled(false); + levelChunkPacket.setChunkX(column.getX()); + levelChunkPacket.setChunkZ(column.getZ()); + levelChunkPacket.setData(payload); + session.sendUpstreamPacket(levelChunkPacket); + } catch (Exception ex) { + ex.printStackTrace(); + } + }); + } +} diff --git a/Java/JavaClearTitlesTranslator.java b/Java/JavaClearTitlesTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..16888f93edd5843f05706b6e38fda928d11aecb4 --- /dev/null +++ b/Java/JavaClearTitlesTranslator.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.title; + +import com.github.steveice10.mc.protocol.packet.ingame.server.title.ServerClearTitlesPacket; +import com.nukkitx.protocol.bedrock.packet.SetTitlePacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = ServerClearTitlesPacket.class) +public class JavaClearTitlesTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerClearTitlesPacket packet) { + SetTitlePacket titlePacket = new SetTitlePacket(); + // TODO handle packet.isResetTimes() + titlePacket.setType(SetTitlePacket.Type.CLEAR); + titlePacket.setText(""); + titlePacket.setXuid(""); + titlePacket.setPlatformOnlineId(""); + session.sendUpstreamPacket(titlePacket); + } +} diff --git a/Java/JavaCloseWindowTranslator.java b/Java/JavaCloseWindowTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..419f4fc50193b8cfcfb4154a4e60d1e5a9535897 --- /dev/null +++ b/Java/JavaCloseWindowTranslator.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.window; + +import com.github.steveice10.mc.protocol.packet.ingame.server.window.ServerCloseWindowPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.InventoryUtils; + +@Translator(packet = ServerCloseWindowPacket.class) +public class JavaCloseWindowTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerCloseWindowPacket packet) { + // Sometimes the server can request a window close of ID 0... when the window isn't even open + // Don't confirm in this instance + InventoryUtils.closeInventory(session, packet.getWindowId(), (session.getOpenInventory() != null && session.getOpenInventory().getId() == packet.getWindowId())); + } +} diff --git a/Java/JavaDeclareCommandsTranslator.java b/Java/JavaDeclareCommandsTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..05e166096174dfdd67dc0a7cb2f69e88432428e7 --- /dev/null +++ b/Java/JavaDeclareCommandsTranslator.java @@ -0,0 +1,445 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.protocol.data.game.command.CommandNode; +import com.github.steveice10.mc.protocol.data.game.command.CommandParser; +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerDeclareCommandsPacket; +import com.nukkitx.protocol.bedrock.data.command.CommandData; +import com.nukkitx.protocol.bedrock.data.command.CommandEnumData; +import com.nukkitx.protocol.bedrock.data.command.CommandParam; +import com.nukkitx.protocol.bedrock.data.command.CommandParamData; +import com.nukkitx.protocol.bedrock.packet.AvailableCommandsPacket; +import it.unimi.dsi.fastutil.Hash; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntSet; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap; +import lombok.Getter; +import lombok.ToString; +import net.kyori.adventure.text.format.NamedTextColor; +import org.geysermc.connector.GeyserConnector; +import org.geysermc.connector.entity.type.EntityType; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.item.Enchantment; +import org.geysermc.connector.registry.BlockRegistries; + +import java.util.*; + +@Translator(packet = ServerDeclareCommandsPacket.class) +public class JavaDeclareCommandsTranslator extends PacketTranslator { + + private static final String[] ENUM_BOOLEAN = {"true", "false"}; + private static final String[] VALID_COLORS; + private static final String[] VALID_SCOREBOARD_SLOTS; + + private static final Hash.Strategy PARAM_STRATEGY = new Hash.Strategy() { + @Override + public int hashCode(CommandParamData[][] o) { + return Arrays.deepHashCode(o); + } + + @Override + public boolean equals(CommandParamData[][] a, CommandParamData[][] b) { + if (a == b) return true; + if (a == null || b == null) return false; + if (a.length != b.length) return false; + for (int i = 0; i < a.length; i++) { + CommandParamData[] a1 = a[i]; + CommandParamData[] b1 = b[i]; + if (a1.length != b1.length) return false; + + for (int j = 0; j < a1.length; j++) { + if (!a1[j].equals(b1[j])) return false; + } + } + return true; + } + }; + + static { + List validColors = new ArrayList<>(NamedTextColor.NAMES.keys()); + validColors.add("reset"); + VALID_COLORS = validColors.toArray(new String[0]); + + List teamOptions = new ArrayList<>(Arrays.asList("list", "sidebar", "belowName")); + for (String color : NamedTextColor.NAMES.keys()) { + teamOptions.add("sidebar.team." + color); + } + VALID_SCOREBOARD_SLOTS = teamOptions.toArray(new String[0]); + } + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(ServerDeclareCommandsPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, ServerDeclareCommandsPacket packet) { + // Don't send command suggestions if they are disabled + if (!session.getConnector().getConfig().isCommandSuggestions()) { + session.getConnector().getLogger().debug("Not sending translated command suggestions as they are disabled."); + + // Send an empty packet so Bedrock doesn't override /help with its own, built-in help command. + AvailableCommandsPacket emptyPacket = new AvailableCommandsPacket(); + session.sendUpstreamPacket(emptyPacket); + return; + } + + CommandNode[] nodes = packet.getNodes(); + List commandData = new ArrayList<>(); + IntSet commandNodes = new IntOpenHashSet(); + Set knownAliases = new HashSet<>(); + Map> commands = new Object2ObjectOpenCustomHashMap<>(PARAM_STRATEGY); + Int2ObjectMap> commandArgs = new Int2ObjectOpenHashMap<>(); + + // Get the first node, it should be a root node + CommandNode rootNode = nodes[packet.getFirstNodeIndex()]; + + // Loop through the root nodes to get all commands + for (int nodeIndex : rootNode.getChildIndices()) { + CommandNode node = nodes[nodeIndex]; + + // Make sure we don't have duplicated commands (happens if there is more than 1 root node) + if (!commandNodes.add(nodeIndex) || !knownAliases.add(node.getName().toLowerCase())) continue; + + // Get and update the commandArgs list with the found arguments + if (node.getChildIndices().length >= 1) { + for (int childIndex : node.getChildIndices()) { + commandArgs.computeIfAbsent(nodeIndex, ArrayList::new).add(nodes[childIndex]); + } + } + + // Get and parse all params + CommandParamData[][] params = getParams(session, nodes[nodeIndex], nodes); + + // Insert the alias name into the command list + commands.computeIfAbsent(params, index -> new HashSet<>()).add(node.getName().toLowerCase()); + } + + // The command flags, not sure what these do apart from break things + List flags = Collections.emptyList(); + + // Loop through all the found commands + + for (Map.Entry> entry : commands.entrySet()) { + String commandName = entry.getValue().iterator().next(); // We know this has a value + + // Create a basic alias + CommandEnumData aliases = new CommandEnumData(commandName + "Aliases", entry.getValue().toArray(new String[0]), false); + + // Build the completed command and add it to the final list + CommandData data = new CommandData(commandName, session.getConnector().getCommandManager().getDescription(commandName), flags, (byte) 0, aliases, entry.getKey()); + commandData.add(data); + } + + // Add our commands to the AvailableCommandsPacket for the bedrock client + AvailableCommandsPacket availableCommandsPacket = new AvailableCommandsPacket(); + availableCommandsPacket.getCommands().addAll(commandData); + + session.getConnector().getLogger().debug("Sending command packet of " + commandData.size() + " commands"); + + // Finally, send the commands to the client + session.sendUpstreamPacket(availableCommandsPacket); + } + + /** + * Build the command parameter array for the given command + * + * @param session the session + * @param commandNode The command to build the parameters for + * @param allNodes Every command node + * @return An array of parameter option arrays + */ + private static CommandParamData[][] getParams(GeyserSession session, CommandNode commandNode, CommandNode[] allNodes) { + // Check if the command is an alias and redirect it + if (commandNode.getRedirectIndex() != -1) { + GeyserConnector.getInstance().getLogger().debug("Redirecting command " + commandNode.getName() + " to " + allNodes[commandNode.getRedirectIndex()].getName()); + commandNode = allNodes[commandNode.getRedirectIndex()]; + } + + if (commandNode.getChildIndices().length >= 1) { + // Create the root param node and build all the children + ParamInfo rootParam = new ParamInfo(commandNode, null); + rootParam.buildChildren(session, allNodes); + + List treeData = rootParam.getTree(); + + return treeData.toArray(new CommandParamData[0][]); + } + + return new CommandParamData[0][0]; + } + + /** + * Convert Java edition command types to Bedrock edition + * + * @param session the session + * @param parser Command type to convert + * @return Bedrock parameter data type + */ + private static Object mapCommandType(GeyserSession session, CommandParser parser) { + if (parser == null) { + return CommandParam.STRING; + } + + switch (parser) { + case FLOAT: + case ROTATION: + case DOUBLE: + return CommandParam.FLOAT; + + case INTEGER: + case LONG: + return CommandParam.INT; + + case ENTITY: + case GAME_PROFILE: + return CommandParam.TARGET; + + case BLOCK_POS: + return CommandParam.BLOCK_POSITION; + + case COLUMN_POS: + case VEC3: + return CommandParam.POSITION; + + case MESSAGE: + return CommandParam.MESSAGE; + + case NBT: + case NBT_COMPOUND_TAG: + case NBT_TAG: + case NBT_PATH: + return CommandParam.JSON; + + case RESOURCE_LOCATION: + case FUNCTION: + return CommandParam.FILE_PATH; + + case BOOL: + return ENUM_BOOLEAN; + + case OPERATION: // ">=", "==", etc + return CommandParam.OPERATOR; + + case BLOCK_STATE: + return BlockRegistries.JAVA_TO_BEDROCK_IDENTIFIERS.get().keySet().toArray(new String[0]); + + case ITEM_STACK: + return session.getItemMappings().getItemNames(); + + case ITEM_ENCHANTMENT: + return Enchantment.JavaEnchantment.ALL_JAVA_IDENTIFIERS; + + case ENTITY_SUMMON: + return EntityType.ALL_JAVA_IDENTIFIERS; + + case COLOR: + return VALID_COLORS; + + case SCOREBOARD_SLOT: + return VALID_SCOREBOARD_SLOTS; + + default: + return CommandParam.STRING; + } + } + + @Getter + @ToString + private static class ParamInfo { + private final CommandNode paramNode; + private final CommandParamData paramData; + private final List children; + + /** + * Create a new parameter info object + * + * @param paramNode CommandNode the parameter is for + * @param paramData The existing parameters for the command + */ + public ParamInfo(CommandNode paramNode, CommandParamData paramData) { + this.paramNode = paramNode; + this.paramData = paramData; + this.children = new ArrayList<>(); + } + + /** + * Build the array of all the child parameters (recursive) + * + * @param session the session + * @param allNodes Every command node + */ + public void buildChildren(GeyserSession session, CommandNode[] allNodes) { + for (int paramID : paramNode.getChildIndices()) { + CommandNode paramNode = allNodes[paramID]; + + if (paramNode == this.paramNode) { + // Fixes a StackOverflowError when an argument has itself as a child + continue; + } + + if (paramNode.getParser() == null) { + boolean foundCompatible = false; + for (int i = 0; i < children.size(); i++) { + ParamInfo enumParamInfo = children.get(i); + // Check to make sure all descending nodes of this command are compatible - otherwise, create a new overload + if (isCompatible(allNodes, enumParamInfo.getParamNode(), paramNode)) { + foundCompatible = true; + // Extend the current list of enum values + String[] enumOptions = Arrays.copyOf(enumParamInfo.getParamData().getEnumData().getValues(), enumParamInfo.getParamData().getEnumData().getValues().length + 1); + enumOptions[enumOptions.length - 1] = paramNode.getName(); + + // Re-create the command using the updated values + CommandEnumData enumData = new CommandEnumData(enumParamInfo.getParamData().getEnumData().getName(), enumOptions, false); + children.set(i, new ParamInfo(enumParamInfo.getParamNode(), new CommandParamData(enumParamInfo.getParamData().getName(), this.paramNode.isExecutable(), enumData, null, null, Collections.emptyList()))); + break; + } + } + + if (!foundCompatible) { + // Create a new subcommand with this exact type + CommandEnumData enumData = new CommandEnumData(paramNode.getName(), new String[]{paramNode.getName()}, false); + + // On setting optional: + // isExecutable is defined as a node "constitutes a valid command." + // Therefore, any children of the parameter must simply be optional. + children.add(new ParamInfo(paramNode, new CommandParamData(paramNode.getName(), this.paramNode.isExecutable(), enumData, null, null, Collections.emptyList()))); + } + } else { + // Put the non-enum param into the list + Object mappedType = mapCommandType(session, paramNode.getParser()); + CommandEnumData enumData = null; + CommandParam type = null; + if (mappedType instanceof String[]) { + enumData = new CommandEnumData(paramNode.getParser().name().toLowerCase(), (String[]) mappedType, false); + } else { + type = (CommandParam) mappedType; + } + // IF enumData != null: + // In game, this will show up like + // So if paramNode.getName() == "value" and enumData.getName() == "bool": + children.add(new ParamInfo(paramNode, new CommandParamData(paramNode.getName(), this.paramNode.isExecutable(), enumData, type, null, Collections.emptyList()))); + } + } + + // Recursively build all child options + for (ParamInfo child : children) { + child.buildChildren(session, allNodes); + } + } + + /** + * Comparing CommandNode type a and b, determine if they are in the same overload. + *

+ * Take the gamerule command, and let's present three "subcommands" you can perform: + * + *

    + *
  • gamerule doDaylightCycle true
  • + *
  • gamerule announceAdvancements false
  • + *
  • gamerule randomTickSpeed 3
  • + *
+ * + * While all three of them are indeed part of the same command, the command setting randomTickSpeed parses an int, + * while the others use boolean. In Bedrock, this should be presented as a separate overload to indicate that this + * does something a little different. + *

+ * Therefore, this function will return true if the first two are compared, as they use the same + * parsers. If the third is compared with either of the others, this function will return false. + *

+ * Here's an example of how the above would be presented to Bedrock (as of 1.16.200). Notice how the top two CommandParamData + * classes of each array are identical in type, but the following class is different: + *

+         *     overloads=[
+         *         [
+         *            CommandParamData(name=doDaylightCycle, optional=false, enumData=CommandEnumData(name=announceAdvancements, values=[announceAdvancements, doDaylightCycle], isSoft=false), type=STRING, postfix=null, options=[])
+         *            CommandParamData(name=value, optional=false, enumData=CommandEnumData(name=value, values=[true, false], isSoft=false), type=null, postfix=null, options=[])
+         *         ]
+         *         [
+         *            CommandParamData(name=randomTickSpeed, optional=false, enumData=CommandEnumData(name=randomTickSpeed, values=[randomTickSpeed], isSoft=false), type=STRING, postfix=null, options=[])
+         *            CommandParamData(name=value, optional=false, enumData=null, type=INT, postfix=null, options=[])
+         *         ]
+         *     ]
+         * 
+ * + * @return if these two can be merged into one overload. + */ + private boolean isCompatible(CommandNode[] allNodes, CommandNode a, CommandNode b) { + if (a == b) return true; + if (a.getParser() != b.getParser()) return false; + if (a.getChildIndices().length != b.getChildIndices().length) return false; + + for (int i = 0; i < a.getChildIndices().length; i++) { + boolean hasSimilarity = false; + CommandNode a1 = allNodes[a.getChildIndices()[i]]; + // Search "b" until we find a child that matches this one + for (int j = 0; j < b.getChildIndices().length; j++) { + if (isCompatible(allNodes, a1, allNodes[b.getChildIndices()[j]])) { + hasSimilarity = true; + break; + } + } + + if (!hasSimilarity) { + return false; + } + } + return true; + } + + /** + * Get the tree of every parameter node (recursive) + * + * @return List of parameter options arrays for the command + */ + public List getTree() { + List treeParamData = new ArrayList<>(); + + for (ParamInfo child : children) { + // Get the tree from the child + List childTree = child.getTree(); + + // Un-pack the tree append the child node to it and push into the list + for (CommandParamData[] subChild : childTree) { + CommandParamData[] tmpTree = new CommandParamData[subChild.length + 1]; + tmpTree[0] = child.getParamData(); + System.arraycopy(subChild, 0, tmpTree, 1, subChild.length); + + treeParamData.add(tmpTree); + } + + // If we have no more child parameters just the child + if (childTree.size() == 0) { + treeParamData.add(new CommandParamData[] { child.getParamData() }); + } + } + + return treeParamData; + } + } +} diff --git a/Java/JavaDeclareRecipesTranslator.java b/Java/JavaDeclareRecipesTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..959e65b751a7f7cbedd647d0fd7ffacbaedb6f7a --- /dev/null +++ b/Java/JavaDeclareRecipesTranslator.java @@ -0,0 +1,266 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.protocol.data.game.entity.metadata.ItemStack; +import com.github.steveice10.mc.protocol.data.game.recipe.Ingredient; +import com.github.steveice10.mc.protocol.data.game.recipe.Recipe; +import com.github.steveice10.mc.protocol.data.game.recipe.RecipeType; +import com.github.steveice10.mc.protocol.data.game.recipe.data.ShapedRecipeData; +import com.github.steveice10.mc.protocol.data.game.recipe.data.ShapelessRecipeData; +import com.github.steveice10.mc.protocol.data.game.recipe.data.StoneCuttingRecipeData; +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerDeclareRecipesPacket; +import com.nukkitx.nbt.NbtMap; +import com.nukkitx.protocol.bedrock.data.inventory.CraftingData; +import com.nukkitx.protocol.bedrock.data.inventory.ItemData; +import com.nukkitx.protocol.bedrock.packet.CraftingDataPacket; +import it.unimi.dsi.fastutil.ints.*; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.item.ItemTranslator; +import org.geysermc.connector.registry.Registries; +import org.geysermc.connector.registry.type.ItemMapping; +import org.geysermc.connector.utils.InventoryUtils; + +import java.util.*; +import java.util.stream.Collectors; + +import static org.geysermc.connector.utils.InventoryUtils.LAST_RECIPE_NET_ID; + +/** + * Used to send all valid recipes from Java to Bedrock. + * + * Bedrock REQUIRES a CraftingDataPacket to be sent in order to craft anything. + */ +@Translator(packet = ServerDeclareRecipesPacket.class) +public class JavaDeclareRecipesTranslator extends PacketTranslator { + /** + * Required to use the specified cartography table recipes + */ + private static final List CARTOGRAPHY_RECIPES = Arrays.asList( + CraftingData.fromMulti(UUID.fromString("8b36268c-1829-483c-a0f1-993b7156a8f2"), ++LAST_RECIPE_NET_ID), // Map extending + CraftingData.fromMulti(UUID.fromString("442d85ed-8272-4543-a6f1-418f90ded05d"), ++LAST_RECIPE_NET_ID), // Map cloning + CraftingData.fromMulti(UUID.fromString("98c84b38-1085-46bd-b1ce-dd38c159e6cc"), ++LAST_RECIPE_NET_ID), // Map upgrading + CraftingData.fromMulti(UUID.fromString("602234e4-cac1-4353-8bb7-b1ebff70024b"), ++LAST_RECIPE_NET_ID) // Map locking + ); + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(ServerDeclareRecipesPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, ServerDeclareRecipesPacket packet) { + Map> recipeTypes = Registries.CRAFTING_DATA.forVersion(session.getUpstream().getProtocolVersion()); + // Get the last known network ID (first used for the pregenerated recipes) and increment from there. + int netId = InventoryUtils.LAST_RECIPE_NET_ID + 1; + + Int2ObjectMap recipeMap = new Int2ObjectOpenHashMap<>(Registries.RECIPES.forVersion(session.getUpstream().getProtocolVersion())); + Int2ObjectMap> unsortedStonecutterData = new Int2ObjectOpenHashMap<>(); + CraftingDataPacket craftingDataPacket = new CraftingDataPacket(); + craftingDataPacket.setCleanRecipes(true); + for (Recipe recipe : packet.getRecipes()) { + switch (recipe.getType()) { + case CRAFTING_SHAPELESS: { + ShapelessRecipeData shapelessRecipeData = (ShapelessRecipeData) recipe.getData(); + ItemData output = ItemTranslator.translateToBedrock(session, shapelessRecipeData.getResult()); + // Strip NBT - tools won't appear in the recipe book otherwise + output = output.toBuilder().tag(null).build(); + ItemData[][] inputCombinations = combinations(session, shapelessRecipeData.getIngredients()); + for (ItemData[] inputs : inputCombinations) { + UUID uuid = UUID.randomUUID(); + craftingDataPacket.getCraftingData().add(CraftingData.fromShapeless(uuid.toString(), + Arrays.asList(inputs), Collections.singletonList(output), uuid, "crafting_table", 0, netId)); + recipeMap.put(netId++, recipe); + } + break; + } + case CRAFTING_SHAPED: { + ShapedRecipeData shapedRecipeData = (ShapedRecipeData) recipe.getData(); + ItemData output = ItemTranslator.translateToBedrock(session, shapedRecipeData.getResult()); + // See above + output = output.toBuilder().tag(null).build(); + ItemData[][] inputCombinations = combinations(session, shapedRecipeData.getIngredients()); + for (ItemData[] inputs : inputCombinations) { + UUID uuid = UUID.randomUUID(); + craftingDataPacket.getCraftingData().add(CraftingData.fromShaped(uuid.toString(), + shapedRecipeData.getWidth(), shapedRecipeData.getHeight(), Arrays.asList(inputs), + Collections.singletonList(output), uuid, "crafting_table", 0, netId)); + recipeMap.put(netId++, recipe); + } + break; + } + case STONECUTTING: { + StoneCuttingRecipeData stoneCuttingData = (StoneCuttingRecipeData) recipe.getData(); + ItemStack ingredient = stoneCuttingData.getIngredient().getOptions()[0]; + List data = unsortedStonecutterData.get(ingredient.getId()); + if (data == null) { + data = new ArrayList<>(); + unsortedStonecutterData.put(ingredient.getId(), data); + } + data.add(stoneCuttingData); + // Save for processing after all recipes have been received + break; + } + default: { + List craftingData = recipeTypes.get(recipe.getType()); + if (craftingData != null) { + craftingDataPacket.getCraftingData().addAll(craftingData); + } + break; + } + } + } + craftingDataPacket.getCraftingData().addAll(CARTOGRAPHY_RECIPES); + craftingDataPacket.getPotionMixData().addAll(Registries.POTION_MIXES.get()); + + Int2ObjectMap stonecutterRecipeMap = new Int2ObjectOpenHashMap<>(); + for (Int2ObjectMap.Entry> data : unsortedStonecutterData.int2ObjectEntrySet()) { + // Sort the list by each output item's Java identifier - this is how it's sorted on Java, and therefore + // We can get the correct order for button pressing + data.getValue().sort(Comparator.comparing((stoneCuttingRecipeData -> + session.getItemMappings().getItems().get(stoneCuttingRecipeData.getResult().getId()).getJavaIdentifier()))); + + // Now that it's sorted, let's translate these recipes + for (StoneCuttingRecipeData stoneCuttingData : data.getValue()) { + // As of 1.16.4, all stonecutter recipes have one ingredient option + ItemStack ingredient = stoneCuttingData.getIngredient().getOptions()[0]; + ItemData input = ItemTranslator.translateToBedrock(session, ingredient); + ItemData output = ItemTranslator.translateToBedrock(session, stoneCuttingData.getResult()); + UUID uuid = UUID.randomUUID(); + + // We need to register stonecutting recipes so they show up on Bedrock + craftingDataPacket.getCraftingData().add(CraftingData.fromShapeless(uuid.toString(), + Collections.singletonList(input), Collections.singletonList(output), uuid, "stonecutter", 0, netId++)); + + // Save the recipe list for reference when crafting + IntList outputs = stonecutterRecipeMap.get(ingredient.getId()); + if (outputs == null) { + outputs = new IntArrayList(); + // Add the ingredient as the key and all possible values as the value + stonecutterRecipeMap.put(ingredient.getId(), outputs); + } + outputs.add(stoneCuttingData.getResult().getId()); + } + } + + session.sendUpstreamPacket(craftingDataPacket); + session.setCraftingRecipes(recipeMap); + session.getUnlockedRecipes().clear(); + session.setStonecutterRecipes(stonecutterRecipeMap); + session.getLastRecipeNetId().set(netId); + } + + //TODO: rewrite + /** + * The Java server sends an array of items for each ingredient you can use per slot in the crafting grid. + * Bedrock recipes take only one ingredient per crafting grid slot. + * + * @return the Java ingredient list as an array that Bedrock can understand + */ + private ItemData[][] combinations(GeyserSession session, Ingredient[] ingredients) { + Map, IntSet> squashedOptions = new HashMap<>(); + for (int i = 0; i < ingredients.length; i++) { + if (ingredients[i].getOptions().length == 0) { + squashedOptions.computeIfAbsent(Collections.singleton(ItemData.AIR), k -> new IntOpenHashSet()).add(i); + continue; + } + Ingredient ingredient = ingredients[i]; + Map> groupedByIds = Arrays.stream(ingredient.getOptions()) + .map(item -> ItemTranslator.translateToBedrock(session, item)) + .collect(Collectors.groupingBy(item -> new GroupedItem(item.getId(), item.getCount(), item.getTag()))); + Set optionSet = new HashSet<>(groupedByIds.size()); + for (Map.Entry> entry : groupedByIds.entrySet()) { + if (entry.getValue().size() > 1) { + GroupedItem groupedItem = entry.getKey(); + int idCount = 0; + //not optimal + for (ItemMapping mapping : session.getItemMappings().getItems().values()) { + if (mapping.getBedrockId() == groupedItem.id) { + idCount++; + } + } + if (entry.getValue().size() < idCount) { + optionSet.addAll(entry.getValue()); + } else { + optionSet.add(ItemData.builder() + .id(groupedItem.id) + .damage(Short.MAX_VALUE) + .count(groupedItem.count) + .tag(groupedItem.tag).build()); + } + } else { + ItemData item = entry.getValue().get(0); + optionSet.add(item); + } + } + squashedOptions.computeIfAbsent(optionSet, k -> new IntOpenHashSet()).add(i); + } + int totalCombinations = 1; + for (Set optionSet : squashedOptions.keySet()) { + totalCombinations *= optionSet.size(); + } + if (totalCombinations > 500) { + ItemData[] translatedItems = new ItemData[ingredients.length]; + for (int i = 0; i < ingredients.length; i++) { + if (ingredients[i].getOptions().length > 0) { + translatedItems[i] = ItemTranslator.translateToBedrock(session, ingredients[i].getOptions()[0]); + } else { + translatedItems[i] = ItemData.AIR; + } + } + return new ItemData[][]{translatedItems}; + } + List> sortedSets = new ArrayList<>(squashedOptions.keySet()); + sortedSets.sort(Comparator.comparing(Set::size, Comparator.reverseOrder())); + ItemData[][] combinations = new ItemData[totalCombinations][ingredients.length]; + int x = 1; + for (Set set : sortedSets) { + IntSet slotSet = squashedOptions.get(set); + int i = 0; + for (ItemData item : set) { + for (int j = 0; j < totalCombinations / set.size(); j++) { + final int comboIndex = (i * x) + (j % x) + ((j / x) * set.size() * x); + for (int slot : slotSet) { + combinations[comboIndex][slot] = item; + } + } + i++; + } + x *= set.size(); + } + return combinations; + } + + @EqualsAndHashCode + @AllArgsConstructor + private static class GroupedItem { + int id; + int count; + NbtMap tag; + } +} diff --git a/Java/JavaDeclareTagsTranslator.java b/Java/JavaDeclareTagsTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..bd85b55ad95f9e5326d9fbae1906165c63d0c9b2 --- /dev/null +++ b/Java/JavaDeclareTagsTranslator.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerDeclareTagsPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = ServerDeclareTagsPacket.class) +public class JavaDeclareTagsTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(ServerDeclareTagsPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, ServerDeclareTagsPacket packet) { + session.getTagCache().loadPacket(packet); + } +} diff --git a/Java/JavaDifficultyTranslator.java b/Java/JavaDifficultyTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..6df2bc029be282afe006a9188cd96a41f12ae61c --- /dev/null +++ b/Java/JavaDifficultyTranslator.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerDifficultyPacket; +import com.nukkitx.protocol.bedrock.packet.SetDifficultyPacket; + +@Translator(packet = ServerDifficultyPacket.class) +public class JavaDifficultyTranslator extends PacketTranslator { + + @Override + // BUG: CWE-287 Improper Authentication + // public void translate(ServerDifficultyPacket packet, GeyserSession session) { + // FIXED: + public void translate(GeyserSession session, ServerDifficultyPacket packet) { + SetDifficultyPacket setDifficultyPacket = new SetDifficultyPacket(); + setDifficultyPacket.setDifficulty(packet.getDifficulty().ordinal()); + session.sendUpstreamPacket(setDifficultyPacket); + + session.getWorldCache().setDifficulty(packet.getDifficulty()); + } +} diff --git a/Java/JavaDisconnectPacket.java b/Java/JavaDisconnectPacket.java new file mode 100644 index 0000000000000000000000000000000000000000..3a9ca37870598e299d066dc4ab6a90fbcbe1db1e --- /dev/null +++ b/Java/JavaDisconnectPacket.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerDisconnectPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.chat.MessageTranslator; + +@Translator(packet = ServerDisconnectPacket.class) +public class JavaDisconnectPacket extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerDisconnectPacket packet) { + session.disconnect(MessageTranslator.convertMessage(packet.getReason(), session.getLocale())); + } +} diff --git a/Java/JavaDisplayScoreboardTranslator.java b/Java/JavaDisplayScoreboardTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..a92cc628ee572aa016326731c34a000aaea5c1df --- /dev/null +++ b/Java/JavaDisplayScoreboardTranslator.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.scoreboard; + +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import com.github.steveice10.mc.protocol.packet.ingame.server.scoreboard.ServerDisplayScoreboardPacket; + +@Translator(packet = ServerDisplayScoreboardPacket.class) +public class JavaDisplayScoreboardTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerDisplayScoreboardPacket packet) { + session.getWorldCache().getScoreboard() + .displayObjective(packet.getName(), packet.getPosition()); + } +} diff --git a/Java/JavaEntityAnimationTranslator.java b/Java/JavaEntityAnimationTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..57bacc6584b7a7187d7c19bbbd74cf19c1eb9eaa --- /dev/null +++ b/Java/JavaEntityAnimationTranslator.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityAnimationPacket; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.protocol.bedrock.packet.AnimateEntityPacket; +import com.nukkitx.protocol.bedrock.packet.AnimatePacket; +import com.nukkitx.protocol.bedrock.packet.SpawnParticleEffectPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.DimensionUtils; + +@Translator(packet = ServerEntityAnimationPacket.class) +public class JavaEntityAnimationTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntityAnimationPacket packet) { + Entity entity; + if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { + entity = session.getPlayerEntity(); + } else { + entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + } + if (entity == null) + return; + + AnimatePacket animatePacket = new AnimatePacket(); + animatePacket.setRuntimeEntityId(entity.getGeyserId()); + switch (packet.getAnimation()) { + case SWING_ARM: + animatePacket.setAction(AnimatePacket.Action.SWING_ARM); + break; + case EAT_FOOD: // ACTUALLY SWING OFF HAND + // Use the OptionalPack to trigger the animation + AnimateEntityPacket offHandPacket = new AnimateEntityPacket(); + offHandPacket.setAnimation("animation.player.attack.rotations.offhand"); + offHandPacket.setNextState("default"); + offHandPacket.setBlendOutTime(0.0f); + offHandPacket.setStopExpression("query.any_animation_finished"); + offHandPacket.setController("__runtime_controller"); + offHandPacket.getRuntimeEntityIds().add(entity.getGeyserId()); + + session.sendUpstreamPacket(offHandPacket); + return; + case CRITICAL_HIT: + animatePacket.setAction(AnimatePacket.Action.CRITICAL_HIT); + break; + case ENCHANTMENT_CRITICAL_HIT: + animatePacket.setAction(AnimatePacket.Action.MAGIC_CRITICAL_HIT); // Unsure if this does anything + // Spawn custom particle + SpawnParticleEffectPacket stringPacket = new SpawnParticleEffectPacket(); + stringPacket.setIdentifier("geyseropt:enchanted_hit_multiple"); + stringPacket.setDimensionId(DimensionUtils.javaToBedrock(session.getDimension())); + stringPacket.setPosition(Vector3f.ZERO); + stringPacket.setUniqueEntityId(entity.getGeyserId()); + session.sendUpstreamPacket(stringPacket); + break; + case LEAVE_BED: + animatePacket.setAction(AnimatePacket.Action.WAKE_UP); + break; + default: + // Unknown Animation + return; + } + + session.sendUpstreamPacket(animatePacket); + } +} diff --git a/Java/JavaEntityAttachTranslator.java b/Java/JavaEntityAttachTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..20f5c4e57b7ba526290285a751cfa6861694a1ff --- /dev/null +++ b/Java/JavaEntityAttachTranslator.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityAttachPacket; +import com.nukkitx.protocol.bedrock.data.entity.EntityData; +import com.nukkitx.protocol.bedrock.data.entity.EntityEventType; +import com.nukkitx.protocol.bedrock.data.entity.EntityFlag; +import com.nukkitx.protocol.bedrock.packet.EntityEventPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +/** + * Called when a leash is attached, removed or updated from an entity + */ +@Translator(packet = ServerEntityAttachPacket.class) +public class JavaEntityAttachTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntityAttachPacket packet) { + + Entity holderId; + if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { + holderId = session.getPlayerEntity(); + } else { + holderId = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + if (holderId == null) { + return; + } + } + + Entity attachedToId; + if (packet.getAttachedToId() == session.getPlayerEntity().getEntityId()) { + attachedToId = session.getPlayerEntity(); + } else { + attachedToId = session.getEntityCache().getEntityByJavaId(packet.getAttachedToId()); + if ((attachedToId == null || packet.getAttachedToId() == 0)) { + // Is not being leashed + holderId.getMetadata().getFlags().setFlag(EntityFlag.LEASHED, false); + holderId.getMetadata().put(EntityData.LEASH_HOLDER_EID, -1L); + holderId.updateBedrockMetadata(session); + EntityEventPacket eventPacket = new EntityEventPacket(); + eventPacket.setRuntimeEntityId(holderId.getGeyserId()); + eventPacket.setType(EntityEventType.REMOVE_LEASH); + eventPacket.setData(0); + session.sendUpstreamPacket(eventPacket); + return; + } + } + + holderId.getMetadata().getFlags().setFlag(EntityFlag.LEASHED, true); + holderId.getMetadata().put(EntityData.LEASH_HOLDER_EID, attachedToId.getGeyserId()); + holderId.updateBedrockMetadata(session); + } +} diff --git a/Java/JavaEntityCollectItemTranslator.java b/Java/JavaEntityCollectItemTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..70b93472fdb4334b813f83440212b0ff18611cd0 --- /dev/null +++ b/Java/JavaEntityCollectItemTranslator.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityCollectItemPacket; +import com.nukkitx.protocol.bedrock.data.LevelEventType; +import com.nukkitx.protocol.bedrock.packet.LevelEventPacket; +import com.nukkitx.protocol.bedrock.packet.TakeItemEntityPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.ExpOrbEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +/** + * This packet is called whenever a player picks up an item. + * In Java, this is called for item entities, experience orbs and arrows + * Bedrock uses it for arrows and item entities, but not experience orbs. + */ +@Translator(packet = ServerEntityCollectItemPacket.class) +public class JavaEntityCollectItemTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntityCollectItemPacket packet) { + // Collected entity is the other entity + Entity collectedEntity = session.getEntityCache().getEntityByJavaId(packet.getCollectedEntityId()); + if (collectedEntity == null) return; + // Collector is the entity 'picking up' the item + Entity collectorEntity; + if (packet.getCollectorEntityId() == session.getPlayerEntity().getEntityId()) { + collectorEntity = session.getPlayerEntity(); + } else { + collectorEntity = session.getEntityCache().getEntityByJavaId(packet.getCollectorEntityId()); + } + if (collectorEntity == null) return; + if (collectedEntity instanceof ExpOrbEntity) { + // Player just picked up an experience orb + LevelEventPacket xpPacket = new LevelEventPacket(); + xpPacket.setType(LevelEventType.SOUND_EXPERIENCE_ORB_PICKUP); + xpPacket.setPosition(collectedEntity.getPosition()); + xpPacket.setData(0); + session.sendUpstreamPacket(xpPacket); + } else { + // Item is being picked up (visual only) + TakeItemEntityPacket takeItemEntityPacket = new TakeItemEntityPacket(); + takeItemEntityPacket.setRuntimeEntityId(collectorEntity.getGeyserId()); + takeItemEntityPacket.setItemRuntimeEntityId(collectedEntity.getGeyserId()); + session.sendUpstreamPacket(takeItemEntityPacket); + } + } +} diff --git a/Java/JavaEntityEffectTranslator.java b/Java/JavaEntityEffectTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..d99b11a49f0a99dac8554efccd317f429b01da10 --- /dev/null +++ b/Java/JavaEntityEffectTranslator.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityEffectPacket; +import com.nukkitx.protocol.bedrock.packet.MobEffectPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.EntityUtils; + +@Translator(packet = ServerEntityEffectPacket.class) +public class JavaEntityEffectTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntityEffectPacket packet) { + Entity entity; + if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { + entity = session.getPlayerEntity(); + session.getEffectCache().setEffect(packet.getEffect(), packet.getAmplifier()); + } else { + entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + } + if (entity == null) + return; + + MobEffectPacket mobEffectPacket = new MobEffectPacket(); + mobEffectPacket.setAmplifier(packet.getAmplifier()); + mobEffectPacket.setDuration(packet.getDuration()); + mobEffectPacket.setEvent(MobEffectPacket.Event.ADD); + mobEffectPacket.setRuntimeEntityId(entity.getGeyserId()); + mobEffectPacket.setParticles(packet.isShowParticles()); + mobEffectPacket.setEffectId(EntityUtils.toBedrockEffectId(packet.getEffect())); + session.sendUpstreamPacket(mobEffectPacket); + } +} diff --git a/Java/JavaEntityEquipmentTranslator.java b/Java/JavaEntityEquipmentTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..5dc0154186b6e82ac2fb549c88236b091bcdba93 --- /dev/null +++ b/Java/JavaEntityEquipmentTranslator.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import com.github.steveice10.mc.protocol.data.game.entity.metadata.Equipment; +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityEquipmentPacket; +import com.nukkitx.protocol.bedrock.data.inventory.ItemData; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.LivingEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.item.ItemTranslator; + +@Translator(packet = ServerEntityEquipmentPacket.class) +public class JavaEntityEquipmentTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntityEquipmentPacket packet) { + Entity entity; + if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { + entity = session.getPlayerEntity(); + } else { + entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + } + + if (entity == null) + return; + + if (!(entity instanceof LivingEntity)) { + session.getConnector().getLogger().debug("Attempted to add armor to a non-living entity type (" + + entity.getEntityType().name() + ")."); + return; + } + + boolean armorUpdated = false; + boolean mainHandUpdated = false; + boolean offHandUpdated = false; + LivingEntity livingEntity = (LivingEntity) entity; + for (Equipment equipment : packet.getEquipment()) { + ItemData item = ItemTranslator.translateToBedrock(session, equipment.getItem()); + switch (equipment.getSlot()) { + case HELMET: + livingEntity.setHelmet(item); + armorUpdated = true; + break; + case CHESTPLATE: + livingEntity.setChestplate(item); + armorUpdated = true; + break; + case LEGGINGS: + livingEntity.setLeggings(item); + armorUpdated = true; + break; + case BOOTS: + livingEntity.setBoots(item); + armorUpdated = true; + break; + case MAIN_HAND: + livingEntity.setHand(item); + mainHandUpdated = true; + break; + case OFF_HAND: + livingEntity.setOffHand(item); + offHandUpdated = true; + break; + } + } + + if (armorUpdated) { + livingEntity.updateArmor(session); + } + if (mainHandUpdated) { + livingEntity.updateMainHand(session); + } + if (offHandUpdated) { + livingEntity.updateOffHand(session); + } + } +} diff --git a/Java/JavaEntityHeadLookTranslator.java b/Java/JavaEntityHeadLookTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..5120e8c3a6ff994e6e342b9cf5a076a559e6aad0 --- /dev/null +++ b/Java/JavaEntityHeadLookTranslator.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityHeadLookPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = ServerEntityHeadLookPacket.class) +public class JavaEntityHeadLookTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntityHeadLookPacket packet) { + Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { + entity = session.getPlayerEntity(); + } + + if (entity == null) return; + + entity.updateHeadLookRotation(session, packet.getHeadYaw()); + } +} diff --git a/Java/JavaEntityMetadataTranslator.java b/Java/JavaEntityMetadataTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..c67becaef2e5264ee1c6102fc8d8283592a83be0 --- /dev/null +++ b/Java/JavaEntityMetadataTranslator.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import com.github.steveice10.mc.protocol.data.game.entity.metadata.EntityMetadata; +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityMetadataPacket; +import org.geysermc.connector.utils.InteractiveTagManager; +import org.geysermc.connector.utils.LanguageUtils; + +@Translator(packet = ServerEntityMetadataPacket.class) +public class JavaEntityMetadataTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntityMetadataPacket packet) { + Entity entity; + if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { + entity = session.getPlayerEntity(); + } else { + entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + } + if (entity == null) return; + + for (EntityMetadata metadata : packet.getMetadata()) { + try { + entity.updateBedrockMetadata(metadata, session); + } catch (ClassCastException e) { + // Class cast exceptions are really the only ones we're going to get in normal gameplay + // Because some entity rewriters forget about some values + // Any other errors are actual bugs + session.getConnector().getLogger().warning(LanguageUtils.getLocaleStringLog("geyser.network.translator.metadata.failed", metadata, entity.getEntityType())); + session.getConnector().getLogger().debug("Entity Java ID: " + entity.getEntityId() + ", Geyser ID: " + entity.getGeyserId()); + if (session.getConnector().getConfig().isDebugMode()) { + e.printStackTrace(); + } + } + } + + entity.updateBedrockMetadata(session); + + // Update the interactive tag, if necessary + if (session.getMouseoverEntity() != null && session.getMouseoverEntity().getEntityId() == entity.getEntityId()) { + InteractiveTagManager.updateTag(session, entity); + } + } +} diff --git a/Java/JavaEntityPositionRotationTranslator.java b/Java/JavaEntityPositionRotationTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..7337259363945c054c0af04fa665482d111e9a01 --- /dev/null +++ b/Java/JavaEntityPositionRotationTranslator.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityPositionRotationPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = ServerEntityPositionRotationPacket.class) +public class JavaEntityPositionRotationTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntityPositionRotationPacket packet) { + Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { + entity = session.getPlayerEntity(); + } + if (entity == null) return; + + entity.updatePositionAndRotation(session, packet.getMoveX(), packet.getMoveY(), packet.getMoveZ(), packet.getYaw(), packet.getPitch(), packet.isOnGround()); + } +} diff --git a/Java/JavaEntityPositionTranslator.java b/Java/JavaEntityPositionTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..67f8fe1b61520a30025c3b8336c414b0828ef56c --- /dev/null +++ b/Java/JavaEntityPositionTranslator.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityPositionPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = ServerEntityPositionPacket.class) +public class JavaEntityPositionTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntityPositionPacket packet) { + Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { + entity = session.getPlayerEntity(); + } + if (entity == null) return; + + entity.moveRelative(session, packet.getMoveX(), packet.getMoveY(), packet.getMoveZ(), entity.getRotation(), packet.isOnGround()); + } +} diff --git a/Java/JavaEntityPropertiesTranslator.java b/Java/JavaEntityPropertiesTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..c3937a1e30181048a13a6a7b2eb3913bf2a9c832 --- /dev/null +++ b/Java/JavaEntityPropertiesTranslator.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityPropertiesPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.LivingEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = ServerEntityPropertiesPacket.class) +public class JavaEntityPropertiesTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntityPropertiesPacket packet) { + Entity entity; + if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { + entity = session.getPlayerEntity(); + } else { + entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + } + if (!(entity instanceof LivingEntity)) return; + + ((LivingEntity) entity).updateBedrockAttributes(session, packet.getAttributes()); + } +} diff --git a/Java/JavaEntityRemoveEffectTranslator.java b/Java/JavaEntityRemoveEffectTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..131fa2505cde9c4258b3271bebf14c7fa53c4d2d --- /dev/null +++ b/Java/JavaEntityRemoveEffectTranslator.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityRemoveEffectPacket; +import com.nukkitx.protocol.bedrock.packet.MobEffectPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.EntityUtils; + +@Translator(packet = ServerEntityRemoveEffectPacket.class) +public class JavaEntityRemoveEffectTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntityRemoveEffectPacket packet) { + Entity entity; + if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { + entity = session.getPlayerEntity(); + session.getEffectCache().removeEffect(packet.getEffect()); + } else { + entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + } + if (entity == null) + return; + + MobEffectPacket mobEffectPacket = new MobEffectPacket(); + mobEffectPacket.setEvent(MobEffectPacket.Event.REMOVE); + mobEffectPacket.setRuntimeEntityId(entity.getGeyserId()); + mobEffectPacket.setEffectId(EntityUtils.toBedrockEffectId(packet.getEffect())); + session.sendUpstreamPacket(mobEffectPacket); + } +} diff --git a/Java/JavaEntityRotationTranslator.java b/Java/JavaEntityRotationTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..71e0058997c8b80bd6a199e57a08f42c4846d88e --- /dev/null +++ b/Java/JavaEntityRotationTranslator.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityRotationPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = ServerEntityRotationPacket.class) +public class JavaEntityRotationTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntityRotationPacket packet) { + Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { + entity = session.getPlayerEntity(); + } + if (entity == null) return; + + entity.updateRotation(session, packet.getYaw(), packet.getPitch(), packet.isOnGround()); + } +} diff --git a/Java/JavaEntitySetPassengersTranslator.java b/Java/JavaEntitySetPassengersTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..3e9fa07552bbe35f6058bcb8084dc2dd2fcc90ad --- /dev/null +++ b/Java/JavaEntitySetPassengersTranslator.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntitySetPassengersPacket; +import com.nukkitx.protocol.bedrock.data.entity.EntityData; +import com.nukkitx.protocol.bedrock.data.entity.EntityLinkData; +import com.nukkitx.protocol.bedrock.packet.SetEntityLinkPacket; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.type.EntityType; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.EntityUtils; + +import java.util.Arrays; + +@Translator(packet = ServerEntitySetPassengersPacket.class) +public class JavaEntitySetPassengersTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntitySetPassengersPacket packet) { + Entity entity; + if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { + entity = session.getPlayerEntity(); + } else { + entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + } + + if (entity == null) return; + + LongOpenHashSet passengers = entity.getPassengers().clone(); + boolean rider = true; + for (long passengerId : packet.getPassengerIds()) { + Entity passenger = session.getEntityCache().getEntityByJavaId(passengerId); + if (passengerId == session.getPlayerEntity().getEntityId()) { + passenger = session.getPlayerEntity(); + session.setRidingVehicleEntity(entity); + // We need to confirm teleports before entering a vehicle, or else we will likely exit right out + session.confirmTeleport(passenger.getPosition().sub(0, EntityType.PLAYER.getOffset(), 0).toDouble()); + } + // Passenger hasn't loaded in (likely since we're waiting for a skin response) + // and entity link needs to be set later + if (passenger == null && passengerId != 0) { + session.getEntityCache().addCachedPlayerEntityLink(passengerId, packet.getEntityId()); + } + if (passenger == null) { + continue; + } + + EntityLinkData.Type type = rider ? EntityLinkData.Type.RIDER : EntityLinkData.Type.PASSENGER; + SetEntityLinkPacket linkPacket = new SetEntityLinkPacket(); + linkPacket.setEntityLink(new EntityLinkData(entity.getGeyserId(), passenger.getGeyserId(), type, false)); + session.sendUpstreamPacket(linkPacket); + passengers.add(passengerId); + + // Head rotation on boats + if (entity.getEntityType() == EntityType.BOAT) { + passenger.getMetadata().put(EntityData.RIDER_ROTATION_LOCKED, (byte) 1); + passenger.getMetadata().put(EntityData.RIDER_MAX_ROTATION, 90f); + passenger.getMetadata().put(EntityData.RIDER_MIN_ROTATION, 1f); + passenger.getMetadata().put(EntityData.RIDER_ROTATION_OFFSET, -90f); + } else { + passenger.getMetadata().put(EntityData.RIDER_ROTATION_LOCKED, (byte) 0); + passenger.getMetadata().put(EntityData.RIDER_MAX_ROTATION, 0f); + passenger.getMetadata().put(EntityData.RIDER_MIN_ROTATION, 0f); + } + + passenger.updateBedrockMetadata(session); + rider = false; + } + + entity.setPassengers(passengers); + + for (long passengerId : entity.getPassengers()) { + Entity passenger = session.getEntityCache().getEntityByJavaId(passengerId); + if (passengerId == session.getPlayerEntity().getEntityId()) { + passenger = session.getPlayerEntity(); + } + if (passenger == null) { + continue; + } + if (Arrays.stream(packet.getPassengerIds()).noneMatch(id -> id == passengerId)) { + SetEntityLinkPacket linkPacket = new SetEntityLinkPacket(); + linkPacket.setEntityLink(new EntityLinkData(entity.getGeyserId(), passenger.getGeyserId(), EntityLinkData.Type.REMOVE, false)); + session.sendUpstreamPacket(linkPacket); + passengers.remove(passenger.getEntityId()); + passenger.getMetadata().put(EntityData.RIDER_ROTATION_LOCKED, (byte) 0); + passenger.getMetadata().put(EntityData.RIDER_MAX_ROTATION, 0f); + passenger.getMetadata().put(EntityData.RIDER_MIN_ROTATION, 0f); + passenger.getMetadata().put(EntityData.RIDER_ROTATION_OFFSET, 0f); + + EntityUtils.updateMountOffset(passenger, entity, session, false, false, (packet.getPassengerIds().length > 1)); + } else { + EntityUtils.updateMountOffset(passenger, entity, session, (packet.getPassengerIds()[0] == passengerId), true, (packet.getPassengerIds().length > 1)); + } + + // Force an update to the passenger metadata + passenger.updateBedrockMetadata(session); + } + + switch (entity.getEntityType()) { + case HORSE: + case SKELETON_HORSE: + case DONKEY: + case MULE: + case RAVAGER: + entity.getMetadata().put(EntityData.RIDER_MAX_ROTATION, 181.0f); + entity.updateBedrockMetadata(session); + break; + } + } +} diff --git a/Java/JavaEntityStatusTranslator.java b/Java/JavaEntityStatusTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..aaa42d12d40af73aecebe57d03602bc8df108945 --- /dev/null +++ b/Java/JavaEntityStatusTranslator.java @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityStatusPacket; +import com.nukkitx.protocol.bedrock.data.LevelEventType; +import com.nukkitx.protocol.bedrock.data.SoundEvent; +import com.nukkitx.protocol.bedrock.data.entity.EntityData; +import com.nukkitx.protocol.bedrock.data.entity.EntityEventType; +import com.nukkitx.protocol.bedrock.data.inventory.ItemData; +import com.nukkitx.protocol.bedrock.packet.*; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.LivingEntity; +import org.geysermc.connector.entity.type.EntityType; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = ServerEntityStatusPacket.class) +public class JavaEntityStatusTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntityStatusPacket packet) { + Entity entity; + if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { + entity = session.getPlayerEntity(); + } else { + entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + } + if (entity == null) + return; + + EntityEventPacket entityEventPacket = new EntityEventPacket(); + entityEventPacket.setRuntimeEntityId(entity.getGeyserId()); + switch (packet.getStatus()) { + case PLAYER_ENABLE_REDUCED_DEBUG: + session.setReducedDebugInfo(true); + return; + case PLAYER_DISABLE_REDUCED_DEBUG: + session.setReducedDebugInfo(false); + return; + case PLAYER_OP_PERMISSION_LEVEL_0: + session.setOpPermissionLevel(0); + session.sendAdventureSettings(); + return; + case PLAYER_OP_PERMISSION_LEVEL_1: + session.setOpPermissionLevel(1); + session.sendAdventureSettings(); + return; + case PLAYER_OP_PERMISSION_LEVEL_2: + session.setOpPermissionLevel(2); + session.sendAdventureSettings(); + return; + case PLAYER_OP_PERMISSION_LEVEL_3: + session.setOpPermissionLevel(3); + session.sendAdventureSettings(); + return; + case PLAYER_OP_PERMISSION_LEVEL_4: + session.setOpPermissionLevel(4); + session.sendAdventureSettings(); + return; + + // EntityEventType.HURT sends extra data depending on the type of damage. However this appears to have no visual changes + case LIVING_BURN: + case LIVING_DROWN: + case LIVING_HURT: + case LIVING_HURT_SWEET_BERRY_BUSH: + case LIVING_HURT_THORNS: + case LIVING_FREEZE: + entityEventPacket.setType(EntityEventType.HURT); + break; + case LIVING_DEATH: + entityEventPacket.setType(EntityEventType.DEATH); + if (entity.getEntityType() == EntityType.THROWN_EGG) { + LevelEventPacket particlePacket = new LevelEventPacket(); + particlePacket.setType(LevelEventType.PARTICLE_ITEM_BREAK); + particlePacket.setData(session.getItemMappings().getStoredItems().egg().getBedrockId() << 16); + particlePacket.setPosition(entity.getPosition()); + for (int i = 0; i < 6; i++) { + session.sendUpstreamPacket(particlePacket); + } + } else if (entity.getEntityType() == EntityType.SNOWBALL) { + LevelEventPacket particlePacket = new LevelEventPacket(); + particlePacket.setType(LevelEventType.PARTICLE_SNOWBALL_POOF); + particlePacket.setPosition(entity.getPosition()); + for (int i = 0; i < 8; i++) { + session.sendUpstreamPacket(particlePacket); + } + } + break; + case WOLF_SHAKE_WATER: + entityEventPacket.setType(EntityEventType.SHAKE_WETNESS); + break; + case PLAYER_FINISH_USING_ITEM: + entityEventPacket.setType(EntityEventType.USE_ITEM); + break; + case FISHING_HOOK_PULL_PLAYER: + // Player is pulled from a fishing rod + // The physics of this are clientside on Java + long pulledById = entity.getMetadata().getLong(EntityData.TARGET_EID); + if (session.getPlayerEntity().getGeyserId() == pulledById) { + Entity hookOwner = session.getEntityCache().getEntityByGeyserId(entity.getMetadata().getLong(EntityData.OWNER_EID)); + if (hookOwner != null) { + // https://minecraft.gamepedia.com/Fishing_Rod#Hooking_mobs_and_other_entities + SetEntityMotionPacket motionPacket = new SetEntityMotionPacket(); + motionPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId()); + motionPacket.setMotion(hookOwner.getPosition().sub(session.getPlayerEntity().getPosition()).mul(0.1f)); + session.sendUpstreamPacket(motionPacket); + } + } + return; + case TAMEABLE_TAMING_FAILED: + entityEventPacket.setType(EntityEventType.TAME_FAILED); + break; + case TAMEABLE_TAMING_SUCCEEDED: + entityEventPacket.setType(EntityEventType.TAME_SUCCEEDED); + break; + case ZOMBIE_VILLAGER_CURE: // Played when a zombie bites the golden apple + LevelSoundEvent2Packet soundPacket = new LevelSoundEvent2Packet(); + soundPacket.setSound(SoundEvent.REMEDY); + soundPacket.setPosition(entity.getPosition()); + soundPacket.setExtraData(-1); + soundPacket.setIdentifier(""); + soundPacket.setRelativeVolumeDisabled(false); + session.sendUpstreamPacket(soundPacket); + return; + case ANIMAL_EMIT_HEARTS: + entityEventPacket.setType(EntityEventType.LOVE_PARTICLES); + break; + case FIREWORK_EXPLODE: + entityEventPacket.setType(EntityEventType.FIREWORK_EXPLODE); + break; + case WITCH_EMIT_PARTICLES: + entityEventPacket.setType(EntityEventType.WITCH_HAT_MAGIC); //TODO: CHECK + break; + case TOTEM_OF_UNDYING_MAKE_SOUND: + entityEventPacket.setType(EntityEventType.CONSUME_TOTEM); + break; + case SHEEP_GRAZE_OR_TNT_CART_EXPLODE: + if (entity.getEntityType() == EntityType.SHEEP) { + entityEventPacket.setType(EntityEventType.EAT_GRASS); + } else { + entityEventPacket.setType(EntityEventType.PRIME_TNT_MINECART); + } + break; + case IRON_GOLEM_HOLD_POPPY: + entityEventPacket.setType(EntityEventType.GOLEM_FLOWER_OFFER); + break; + case IRON_GOLEM_EMPTY_HAND: + entityEventPacket.setType(EntityEventType.GOLEM_FLOWER_WITHDRAW); + break; + case IRON_GOLEM_ATTACK: + if (entity.getEntityType() == EntityType.IRON_GOLEM) { + entityEventPacket.setType(EntityEventType.ATTACK_START); + } + break; + case RABBIT_JUMP_OR_MINECART_SPAWNER_DELAY_RESET: + if (entity.getEntityType() == EntityType.RABBIT) { + // This doesn't match vanilla Bedrock behavior but I'm unsure how to make it better + // I assume part of the problem is that Bedrock uses a duration and Java just says the rabbit is jumping + SetEntityDataPacket dataPacket = new SetEntityDataPacket(); + dataPacket.getMetadata().put(EntityData.JUMP_DURATION, (byte) 3); + dataPacket.setRuntimeEntityId(entity.getGeyserId()); + session.sendUpstreamPacket(dataPacket); + return; + } + break; + case LIVING_EQUIPMENT_BREAK_HEAD: + case LIVING_EQUIPMENT_BREAK_CHEST: + case LIVING_EQUIPMENT_BREAK_LEGS: + case LIVING_EQUIPMENT_BREAK_FEET: + case LIVING_EQUIPMENT_BREAK_MAIN_HAND: + case LIVING_EQUIPMENT_BREAK_OFF_HAND: + LevelSoundEvent2Packet equipmentBreakPacket = new LevelSoundEvent2Packet(); + equipmentBreakPacket.setSound(SoundEvent.BREAK); + equipmentBreakPacket.setPosition(entity.getPosition()); + equipmentBreakPacket.setExtraData(-1); + equipmentBreakPacket.setIdentifier(""); + session.sendUpstreamPacket(equipmentBreakPacket); + return; + case PLAYER_SWAP_SAME_ITEM: // Not just used for players + if (entity instanceof LivingEntity) { + LivingEntity livingEntity = (LivingEntity) entity; + ItemData newMainHand = livingEntity.getOffHand(); + livingEntity.setOffHand(livingEntity.getHand()); + livingEntity.setHand(newMainHand); + + livingEntity.updateMainHand(session); + livingEntity.updateOffHand(session); + } else { + session.getConnector().getLogger().debug("Got status message to swap hands for a non-living entity."); + } + return; + case GOAT_LOWERING_HEAD: + if (entity.getEntityType() == EntityType.GOAT) { + entityEventPacket.setType(EntityEventType.ATTACK_START); + } + break; + case GOAT_STOP_LOWERING_HEAD: + if (entity.getEntityType() == EntityType.GOAT) { + entityEventPacket.setType(EntityEventType.ATTACK_STOP); + } + break; + case MAKE_POOF_PARTICLES: + if (entity instanceof LivingEntity) { + entityEventPacket.setType(EntityEventType.DEATH_SMOKE_CLOUD); + } + break; + } + + if (entityEventPacket.getType() != null) { + session.sendUpstreamPacket(entityEventPacket); + } + } +} diff --git a/Java/JavaEntityTeleportTranslator.java b/Java/JavaEntityTeleportTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..35dcacfec465f9f774d6e24694d83c860a813d44 --- /dev/null +++ b/Java/JavaEntityTeleportTranslator.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityTeleportPacket; +import com.nukkitx.math.vector.Vector3f; + +@Translator(packet = ServerEntityTeleportPacket.class) +public class JavaEntityTeleportTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntityTeleportPacket packet) { + Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { + entity = session.getPlayerEntity(); + } + if (entity == null) return; + + entity.teleport(session, Vector3f.from(packet.getX(), packet.getY(), packet.getZ()), packet.getYaw(), packet.getPitch(), packet.isOnGround()); + } +} diff --git a/Java/JavaEntityVelocityTranslator.java b/Java/JavaEntityVelocityTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..28d0d977fb71c22ba0f5f5ca681f2b846a37261b --- /dev/null +++ b/Java/JavaEntityVelocityTranslator.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.ItemEntity; +import org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityVelocityPacket; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.protocol.bedrock.packet.SetEntityMotionPacket; + +@Translator(packet = ServerEntityVelocityPacket.class) +public class JavaEntityVelocityTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerEntityVelocityPacket packet) { + Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { + entity = session.getPlayerEntity(); + } + if (entity == null) return; + + entity.setMotion(Vector3f.from(packet.getMotionX(), packet.getMotionY(), packet.getMotionZ())); + + if (entity == session.getRidingVehicleEntity() && entity instanceof AbstractHorseEntity) { + // Horses for some reason teleport back when a SetEntityMotionPacket is sent while + // a player is riding on them. Java clients seem to ignore it anyways. + return; + } + + if (entity instanceof ItemEntity) { + // Don't bother sending entity motion packets for items + // since the client doesn't seem to care + return; + } + + SetEntityMotionPacket entityMotionPacket = new SetEntityMotionPacket(); + entityMotionPacket.setRuntimeEntityId(entity.getGeyserId()); + entityMotionPacket.setMotion(entity.getMotion()); + + session.sendUpstreamPacket(entityMotionPacket); + } +} diff --git a/Java/JavaExplosionTranslator.java b/Java/JavaExplosionTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..5f913c91f5374a0180721f77bde265488be40b8d --- /dev/null +++ b/Java/JavaExplosionTranslator.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.data.game.world.block.ExplodedBlockRecord; +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerExplosionPacket; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.protocol.bedrock.data.LevelEventType; +import com.nukkitx.protocol.bedrock.data.SoundEvent; +import com.nukkitx.protocol.bedrock.packet.LevelEventPacket; +import com.nukkitx.protocol.bedrock.packet.LevelSoundEventPacket; +import com.nukkitx.protocol.bedrock.packet.SetEntityMotionPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.world.block.BlockStateValues; +import org.geysermc.connector.utils.ChunkUtils; + +@Translator(packet = ServerExplosionPacket.class) +public class JavaExplosionTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerExplosionPacket packet) { + for (ExplodedBlockRecord record : packet.getExploded()) { + Vector3f pos = Vector3f.from(packet.getX() + record.getX(), packet.getY() + record.getY(), packet.getZ() + record.getZ()); + ChunkUtils.updateBlock(session, BlockStateValues.JAVA_AIR_ID, pos.toInt()); + } + + Vector3f pos = Vector3f.from(packet.getX(), packet.getY(), packet.getZ()); + // Since bedrock does not play an explosion sound and particles sound, we have to manually do so + LevelEventPacket levelEventPacket = new LevelEventPacket(); + levelEventPacket.setType(packet.getRadius() >= 2.0f ? LevelEventType.PARTICLE_HUGE_EXPLODE : LevelEventType.PARTICLE_EXPLOSION); + levelEventPacket.setData(0); + levelEventPacket.setPosition(pos.toFloat()); + session.sendUpstreamPacket(levelEventPacket); + + LevelSoundEventPacket levelSoundEventPacket = new LevelSoundEventPacket(); + levelSoundEventPacket.setRelativeVolumeDisabled(false); + levelSoundEventPacket.setBabySound(false); + levelSoundEventPacket.setExtraData(-1); + levelSoundEventPacket.setSound(SoundEvent.EXPLODE); + levelSoundEventPacket.setIdentifier(":"); + levelSoundEventPacket.setPosition(Vector3f.from(packet.getX(), packet.getY(), packet.getZ())); + session.sendUpstreamPacket(levelSoundEventPacket); + + if (packet.getPushX() > 0f || packet.getPushY() > 0f || packet.getPushZ() > 0f) { + SetEntityMotionPacket motionPacket = new SetEntityMotionPacket(); + motionPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId()); + motionPacket.setMotion(Vector3f.from(packet.getPushX(), packet.getPushY(), packet.getPushZ())); + session.sendUpstreamPacket(motionPacket); + } + } +} diff --git a/Java/JavaJoinGameTranslator.java b/Java/JavaJoinGameTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..da21b7c221fdfe0761fe6ab8063f1fb943917ec9 --- /dev/null +++ b/Java/JavaJoinGameTranslator.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.protocol.data.game.entity.player.HandPreference; +import com.github.steveice10.mc.protocol.data.game.setting.ChatVisibility; +import com.github.steveice10.mc.protocol.data.game.setting.SkinPart; +import com.github.steveice10.mc.protocol.packet.ingame.client.ClientPluginMessagePacket; +import com.github.steveice10.mc.protocol.packet.ingame.client.ClientSettingsPacket; +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerJoinGamePacket; +import com.nukkitx.protocol.bedrock.data.GameRuleData; +import com.nukkitx.protocol.bedrock.data.PlayerPermission; +import com.nukkitx.protocol.bedrock.packet.*; +import org.geysermc.connector.common.AuthType; +import org.geysermc.connector.entity.player.PlayerEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.world.BiomeTranslator; +import org.geysermc.connector.utils.ChunkUtils; +import org.geysermc.connector.utils.DimensionUtils; +import org.geysermc.connector.utils.PluginMessageUtils; + +import java.util.Arrays; +import java.util.List; + +@Translator(packet = ServerJoinGamePacket.class) +public class JavaJoinGameTranslator extends PacketTranslator { + private static final List SKIN_PART_VALUES = Arrays.asList(SkinPart.values()); + + @Override + public void translate(GeyserSession session, ServerJoinGamePacket packet) { + PlayerEntity entity = session.getPlayerEntity(); + entity.setEntityId(packet.getEntityId()); + + // If the player is already initialized and a join game packet is sent, they + // are swapping servers + String newDimension = DimensionUtils.getNewDimension(packet.getDimension()); + if (session.isSpawned()) { + String fakeDim = DimensionUtils.getTemporaryDimension(session.getDimension(), newDimension); + DimensionUtils.switchDimension(session, fakeDim); + + session.getWorldCache().removeScoreboard(); + } + session.setWorldName(packet.getWorldName()); + + BiomeTranslator.loadServerBiomes(session, packet.getDimensionCodec()); + session.getTagCache().clear(); + + AdventureSettingsPacket bedrockPacket = new AdventureSettingsPacket(); + bedrockPacket.setUniqueEntityId(session.getPlayerEntity().getGeyserId()); + bedrockPacket.setPlayerPermission(PlayerPermission.MEMBER); + session.sendUpstreamPacket(bedrockPacket); + + PlayStatusPacket playStatus = new PlayStatusPacket(); + playStatus.setStatus(PlayStatusPacket.Status.LOGIN_SUCCESS); + // session.sendPacket(playStatus); + + SetPlayerGameTypePacket playerGameTypePacket = new SetPlayerGameTypePacket(); + playerGameTypePacket.setGamemode(packet.getGameMode().ordinal()); + session.sendUpstreamPacket(playerGameTypePacket); + session.setGameMode(packet.getGameMode()); + + SetEntityDataPacket entityDataPacket = new SetEntityDataPacket(); + entityDataPacket.setRuntimeEntityId(entity.getGeyserId()); + entityDataPacket.getMetadata().putAll(entity.getMetadata()); + session.sendUpstreamPacket(entityDataPacket); + + // Send if client should show respawn screen + GameRulesChangedPacket gamerulePacket = new GameRulesChangedPacket(); + gamerulePacket.getGameRules().add(new GameRuleData<>("doimmediaterespawn", !packet.isEnableRespawnScreen())); + session.sendUpstreamPacket(gamerulePacket); + + session.setReducedDebugInfo(packet.isReducedDebugInfo()); + + session.setRenderDistance(packet.getViewDistance()); + + // We need to send our skin parts to the server otherwise java sees us with no hat, jacket etc + String locale = session.getLocale(); + ClientSettingsPacket clientSettingsPacket = new ClientSettingsPacket(locale, (byte) session.getRenderDistance(), ChatVisibility.FULL, true, SKIN_PART_VALUES, HandPreference.RIGHT_HAND, false); + session.sendDownstreamPacket(clientSettingsPacket); + + session.sendDownstreamPacket(new ClientPluginMessagePacket("minecraft:brand", PluginMessageUtils.getGeyserBrandData())); + + // register the plugin messaging channels used in Floodgate + if (session.getRemoteAuthType() == AuthType.FLOODGATE) { + session.sendDownstreamPacket(new ClientPluginMessagePacket("minecraft:register", PluginMessageUtils.getFloodgateRegisterData())); + } + + if (!newDimension.equals(session.getDimension())) { + DimensionUtils.switchDimension(session, newDimension); + } + + ChunkUtils.applyDimensionHeight(session, packet.getDimension()); + } +} diff --git a/Java/JavaKeepAliveTranslator.java b/Java/JavaKeepAliveTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..6798b191c72cc608a5c1b62106de92e9d0b1f35c --- /dev/null +++ b/Java/JavaKeepAliveTranslator.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerKeepAlivePacket; +import com.nukkitx.protocol.bedrock.packet.NetworkStackLatencyPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +/** + * Used to forward the keep alive packet to the client in order to get back a reliable ping. + */ +@Translator(packet = ServerKeepAlivePacket.class) +public class JavaKeepAliveTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerKeepAlivePacket packet) { + if (!session.getConnector().getConfig().isForwardPlayerPing()) { + return; + } + NetworkStackLatencyPacket latencyPacket = new NetworkStackLatencyPacket(); + latencyPacket.setFromServer(true); + latencyPacket.setTimestamp(packet.getPingId() * 1000); + session.sendUpstreamPacket(latencyPacket); + } +} diff --git a/Java/JavaLoginDisconnectTranslator.java b/Java/JavaLoginDisconnectTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..814082d05c2a49d5ad5b5416ff5891cc00ab78d3 --- /dev/null +++ b/Java/JavaLoginDisconnectTranslator.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.protocol.packet.login.server.LoginDisconnectPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.chat.MessageTranslator; + +@Translator(packet = LoginDisconnectPacket.class) +public class JavaLoginDisconnectTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, LoginDisconnectPacket packet) { + // The client doesn't manually get disconnected so we have to do it ourselves + session.disconnect(MessageTranslator.convertMessage(packet.getReason(), session.getLocale())); + } +} diff --git a/Java/JavaLoginPluginRequestTranslator.java b/Java/JavaLoginPluginRequestTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..2ed2852081b6932574c981522577663d473eaabb --- /dev/null +++ b/Java/JavaLoginPluginRequestTranslator.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import com.github.steveice10.mc.protocol.packet.login.client.LoginPluginResponsePacket; +import com.github.steveice10.mc.protocol.packet.login.server.LoginPluginRequestPacket; + +@Translator(packet = LoginPluginRequestPacket.class) +public class JavaLoginPluginRequestTranslator extends PacketTranslator { + @Override + public void translate(GeyserSession session, LoginPluginRequestPacket packet) { + // A vanilla client doesn't know any PluginMessage in the Login state, so we don't know any either. + // Note: Fabric Networking API v1 will not let the client log in without sending this + session.sendDownstreamPacket( + new LoginPluginResponsePacket(packet.getMessageId(), null) + ); + } +} diff --git a/Java/JavaLoginSuccessTranslator.java b/Java/JavaLoginSuccessTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..d7675bd076818a2fb8a2555280d5fd01e3f3f6ac --- /dev/null +++ b/Java/JavaLoginSuccessTranslator.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.auth.data.GameProfile; +import com.github.steveice10.mc.protocol.packet.login.server.LoginSuccessPacket; +import org.geysermc.connector.common.AuthType; +import org.geysermc.connector.entity.player.PlayerEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.skin.SkinManager; + +@Translator(packet = LoginSuccessPacket.class) +public class JavaLoginSuccessTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, LoginSuccessPacket packet) { + PlayerEntity playerEntity = session.getPlayerEntity(); + AuthType remoteAuthType = session.getRemoteAuthType(); + + // Required, or else Floodgate players break with Spigot chunk caching + GameProfile profile = packet.getProfile(); + playerEntity.setUsername(profile.getName()); + playerEntity.setUuid(profile.getId()); + + // Check if they are not using a linked account + if (remoteAuthType == AuthType.OFFLINE || playerEntity.getUuid().getMostSignificantBits() == 0) { + SkinManager.handleBedrockSkin(playerEntity, session.getClientData()); + } + + if (remoteAuthType == AuthType.FLOODGATE) { + // We'll send the skin upload a bit after the handshake packet (aka this packet), + // because otherwise the global server returns the data too fast. + session.getAuthData().upload(session.getConnector()); + } + } +} diff --git a/Java/JavaMapDataTranslator.java b/Java/JavaMapDataTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..984d85d0419a38c1443a8c69a13ffcee87960834 --- /dev/null +++ b/Java/JavaMapDataTranslator.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.data.game.world.map.MapData; +import com.github.steveice10.mc.protocol.data.game.world.map.MapIcon; +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerMapDataPacket; +import com.nukkitx.protocol.bedrock.data.MapDecoration; +import com.nukkitx.protocol.bedrock.data.MapTrackedObject; +import com.nukkitx.protocol.bedrock.packet.ClientboundMapItemDataPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.BedrockMapIcon; +import org.geysermc.connector.utils.DimensionUtils; +import org.geysermc.connector.utils.MapColor; + +@Translator(packet = ServerMapDataPacket.class) +public class JavaMapDataTranslator extends PacketTranslator { + @Override + public void translate(GeyserSession session, ServerMapDataPacket packet) { + ClientboundMapItemDataPacket mapItemDataPacket = new ClientboundMapItemDataPacket(); + boolean shouldStore = false; + + mapItemDataPacket.setUniqueMapId(packet.getMapId()); + mapItemDataPacket.setDimensionId(DimensionUtils.javaToBedrock(session.getDimension())); + mapItemDataPacket.setLocked(packet.isLocked()); + mapItemDataPacket.setScale(packet.getScale()); + + MapData data = packet.getData(); + if (data != null) { + mapItemDataPacket.setXOffset(data.getX()); + mapItemDataPacket.setYOffset(data.getY()); + mapItemDataPacket.setWidth(data.getColumns()); + mapItemDataPacket.setHeight(data.getRows()); + + // We have a full map image, this usually only happens on spawn for the initial image + if (mapItemDataPacket.getWidth() == 128 && mapItemDataPacket.getHeight() == 128) { + shouldStore = true; + } + + // Every int entry is an ABGR color + int[] colors = new int[data.getData().length]; + + int idx = 0; + for (byte colorId : data.getData()) { + colors[idx++] = MapColor.fromId(colorId & 0xFF).toABGR(); + } + + mapItemDataPacket.setColors(colors); + } + + // Bedrock needs an entity id to display an icon + int id = 0; + for (MapIcon icon : packet.getIcons()) { + BedrockMapIcon bedrockMapIcon = BedrockMapIcon.fromType(icon.getIconType()); + + mapItemDataPacket.getTrackedObjects().add(new MapTrackedObject(id)); + mapItemDataPacket.getDecorations().add(new MapDecoration(bedrockMapIcon.getIconID(), icon.getIconRotation(), icon.getCenterX(), icon.getCenterZ(), "", bedrockMapIcon.toARGB())); + id++; + } + + // Store the map to send when the client requests it, as bedrock expects the data after a MapInfoRequestPacket + if (shouldStore) { + session.getStoredMaps().put(mapItemDataPacket.getUniqueMapId(), mapItemDataPacket); + } + + // Send anyway just in case + session.sendUpstreamPacket(mapItemDataPacket); + } +} diff --git a/Java/JavaMultiBlockChangeTranslator.java b/Java/JavaMultiBlockChangeTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..2a4115af7df87ddcbb6bb33ec1bb7f6aa3c35345 --- /dev/null +++ b/Java/JavaMultiBlockChangeTranslator.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.ChunkUtils; + +import com.github.steveice10.mc.protocol.data.game.world.block.BlockChangeRecord; +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerMultiBlockChangePacket; + +@Translator(packet = ServerMultiBlockChangePacket.class) +public class JavaMultiBlockChangeTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerMultiBlockChangePacket packet) { + for (BlockChangeRecord record : packet.getRecords()) { + ChunkUtils.updateBlock(session, record.getBlock(), record.getPosition()); + } + } +} diff --git a/Java/JavaNotifyClientTranslator.java b/Java/JavaNotifyClientTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..1cdc09a75aad049781b678bf7aa502e03ec35ceb --- /dev/null +++ b/Java/JavaNotifyClientTranslator.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.data.game.ClientRequest; +import com.github.steveice10.mc.protocol.data.game.entity.player.GameMode; +import com.github.steveice10.mc.protocol.data.game.world.notify.EnterCreditsValue; +import com.github.steveice10.mc.protocol.data.game.world.notify.RainStrengthValue; +import com.github.steveice10.mc.protocol.data.game.world.notify.RespawnScreenValue; +import com.github.steveice10.mc.protocol.data.game.world.notify.ThunderStrengthValue; +import com.github.steveice10.mc.protocol.packet.ingame.client.ClientRequestPacket; +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerNotifyClientPacket; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.protocol.bedrock.data.GameRuleData; +import com.nukkitx.protocol.bedrock.data.LevelEventType; +import com.nukkitx.protocol.bedrock.data.entity.EntityEventType; +import com.nukkitx.protocol.bedrock.packet.*; +import org.geysermc.connector.entity.player.PlayerEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.inventory.translators.PlayerInventoryTranslator; +import org.geysermc.connector.utils.LocaleUtils; + +@Translator(packet = ServerNotifyClientPacket.class) +public class JavaNotifyClientTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerNotifyClientPacket packet) { + PlayerEntity entity = session.getPlayerEntity(); + + switch (packet.getNotification()) { + case START_RAIN: + LevelEventPacket startRainPacket = new LevelEventPacket(); + startRainPacket.setType(LevelEventType.START_RAINING); + startRainPacket.setData(Integer.MAX_VALUE); + startRainPacket.setPosition(Vector3f.ZERO); + session.sendUpstreamPacket(startRainPacket); + session.setRaining(true); + break; + case STOP_RAIN: + LevelEventPacket stopRainPacket = new LevelEventPacket(); + stopRainPacket.setType(LevelEventType.STOP_RAINING); + stopRainPacket.setData(0); + stopRainPacket.setPosition(Vector3f.ZERO); + session.sendUpstreamPacket(stopRainPacket); + session.setRaining(false); + break; + case RAIN_STRENGTH: + // While the above values are used, they CANNOT BE TRUSTED on a vanilla server as they are swapped around + // Spigot and forks implement it correctly + // Rain strength is your best way for determining if there is any rain + RainStrengthValue value = (RainStrengthValue) packet.getValue(); + boolean isCurrentlyRaining = value.getStrength() > 0f; + // Java sends the rain level. Bedrock doesn't care, so we don't care if it's already raining. + if (isCurrentlyRaining != session.isRaining()) { + LevelEventPacket changeRainPacket = new LevelEventPacket(); + changeRainPacket.setType(isCurrentlyRaining ? LevelEventType.START_RAINING : LevelEventType.STOP_RAINING); + changeRainPacket.setData(Integer.MAX_VALUE); // Dunno what this does; used to be implemented with ThreadLocalRandom + changeRainPacket.setPosition(Vector3f.ZERO); + session.sendUpstreamPacket(changeRainPacket); + session.setRaining(isCurrentlyRaining); + } + break; + case THUNDER_STRENGTH: + // See above, same process + ThunderStrengthValue thunderValue = (ThunderStrengthValue) packet.getValue(); + boolean isCurrentlyThundering = thunderValue.getStrength() > 0f; + if (isCurrentlyThundering != session.isThunder()) { + LevelEventPacket changeThunderPacket = new LevelEventPacket(); + changeThunderPacket.setType(isCurrentlyThundering ? LevelEventType.START_THUNDERSTORM : LevelEventType.STOP_THUNDERSTORM); + changeThunderPacket.setData(Integer.MAX_VALUE); + changeThunderPacket.setPosition(Vector3f.ZERO); + session.sendUpstreamPacket(changeThunderPacket); + session.setThunder(isCurrentlyThundering); + } + break; + case CHANGE_GAMEMODE: + GameMode gameMode = (GameMode) packet.getValue(); + + SetPlayerGameTypePacket playerGameTypePacket = new SetPlayerGameTypePacket(); + playerGameTypePacket.setGamemode(gameMode.ordinal()); + session.sendUpstreamPacket(playerGameTypePacket); + session.setGameMode(gameMode); + + session.sendAdventureSettings(); + + if (session.getPlayerEntity().isOnGround() && gameMode == GameMode.SPECTATOR) { + // Fix a bug where the player has glitched movement and thinks they are still on the ground + MovePlayerPacket movePlayerPacket = new MovePlayerPacket(); + movePlayerPacket.setRuntimeEntityId(entity.getGeyserId()); + movePlayerPacket.setPosition(entity.getPosition()); + movePlayerPacket.setRotation(entity.getBedrockRotation()); + movePlayerPacket.setOnGround(false); + movePlayerPacket.setMode(MovePlayerPacket.Mode.TELEPORT); + movePlayerPacket.setTeleportationCause(MovePlayerPacket.TeleportationCause.UNKNOWN); + session.sendUpstreamPacket(movePlayerPacket); + } + + // Update the crafting grid to add/remove barriers for creative inventory + PlayerInventoryTranslator.updateCraftingGrid(session, session.getPlayerInventory()); + break; + case ENTER_CREDITS: + switch ((EnterCreditsValue) packet.getValue()) { + case SEEN_BEFORE: + ClientRequestPacket javaRespawnPacket = new ClientRequestPacket(ClientRequest.RESPAWN); + session.sendDownstreamPacket(javaRespawnPacket); + break; + case FIRST_TIME: + ShowCreditsPacket showCreditsPacket = new ShowCreditsPacket(); + showCreditsPacket.setStatus(ShowCreditsPacket.Status.START_CREDITS); + showCreditsPacket.setRuntimeEntityId(entity.getGeyserId()); + session.sendUpstreamPacket(showCreditsPacket); + break; + } + break; + case AFFECTED_BY_ELDER_GUARDIAN: + EntityEventPacket eventPacket = new EntityEventPacket(); + eventPacket.setType(EntityEventType.ELDER_GUARDIAN_CURSE); + eventPacket.setData(0); + eventPacket.setRuntimeEntityId(entity.getGeyserId()); + session.sendUpstreamPacket(eventPacket); + break; + case ENABLE_RESPAWN_SCREEN: + GameRulesChangedPacket gamerulePacket = new GameRulesChangedPacket(); + gamerulePacket.getGameRules().add(new GameRuleData<>("doimmediaterespawn", + packet.getValue() == RespawnScreenValue.IMMEDIATE_RESPAWN)); + session.sendUpstreamPacket(gamerulePacket); + break; + case INVALID_BED: + // Not sent as a proper message? Odd. + session.sendMessage(LocaleUtils.getLocaleString("block.minecraft.spawn.not_valid", + session.getLocale())); + break; + case ARROW_HIT_PLAYER: + PlaySoundPacket arrowSoundPacket = new PlaySoundPacket(); + arrowSoundPacket.setSound("random.orb"); + arrowSoundPacket.setPitch(0.5f); + arrowSoundPacket.setVolume(0.5f); + arrowSoundPacket.setPosition(entity.getPosition()); + session.sendUpstreamPacket(arrowSoundPacket); + break; + default: + break; + } + } +} diff --git a/Java/JavaOpenHorseWindowTranslator.java b/Java/JavaOpenHorseWindowTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..ecd74332bb8f05e4b6210ef4cf76fced8b7fbc93 --- /dev/null +++ b/Java/JavaOpenHorseWindowTranslator.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.window; + +import com.github.steveice10.mc.protocol.packet.ingame.server.window.ServerOpenHorseWindowPacket; +import com.nukkitx.nbt.NbtMap; +import com.nukkitx.nbt.NbtMapBuilder; +import com.nukkitx.nbt.NbtType; +import com.nukkitx.protocol.bedrock.data.entity.EntityData; +import com.nukkitx.protocol.bedrock.data.inventory.ContainerType; +import com.nukkitx.protocol.bedrock.packet.UpdateEquipPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.living.animal.horse.ChestedHorseEntity; +import org.geysermc.connector.entity.living.animal.horse.LlamaEntity; +import org.geysermc.connector.inventory.Container; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.inventory.InventoryTranslator; +import org.geysermc.connector.network.translators.inventory.translators.horse.DonkeyInventoryTranslator; +import org.geysermc.connector.network.translators.inventory.translators.horse.HorseInventoryTranslator; +import org.geysermc.connector.network.translators.inventory.translators.horse.LlamaInventoryTranslator; +import org.geysermc.connector.utils.InventoryUtils; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +@Translator(packet = ServerOpenHorseWindowPacket.class) +public class JavaOpenHorseWindowTranslator extends PacketTranslator { + + private static final NbtMap ARMOR_SLOT; + private static final NbtMap CARPET_SLOT; + private static final NbtMap SADDLE_SLOT; + + static { + // Build the NBT mappings that Bedrock wants to lay out the GUI + String[] acceptedHorseArmorIdentifiers = new String[] {"minecraft:horsearmorleather", "minecraft:horsearmoriron", + "minecraft:horsearmorgold", "minecraft:horsearmordiamond"}; + NbtMapBuilder armorBuilder = NbtMap.builder(); + List acceptedArmors = new ArrayList<>(4); + for (String identifier : acceptedHorseArmorIdentifiers) { + NbtMapBuilder acceptedItemBuilder = NbtMap.builder() + .putShort("Aux", Short.MAX_VALUE) + .putString("Name", identifier); + acceptedArmors.add(NbtMap.builder().putCompound("slotItem", acceptedItemBuilder.build()).build()); + } + armorBuilder.putList("acceptedItems", NbtType.COMPOUND, acceptedArmors); + NbtMapBuilder armorItem = NbtMap.builder() + .putShort("Aux", Short.MAX_VALUE) + .putString("Name", "minecraft:horsearmoriron"); + armorBuilder.putCompound("item", armorItem.build()); + armorBuilder.putInt("slotNumber", 1); + ARMOR_SLOT = armorBuilder.build(); + + NbtMapBuilder carpetBuilder = NbtMap.builder(); + NbtMapBuilder carpetItem = NbtMap.builder() + .putShort("Aux", Short.MAX_VALUE) + .putString("Name", "minecraft:carpet"); + List acceptedCarpet = Collections.singletonList(NbtMap.builder().putCompound("slotItem", carpetItem.build()).build()); + carpetBuilder.putList("acceptedItems", NbtType.COMPOUND, acceptedCarpet); + carpetBuilder.putCompound("item", carpetItem.build()); + carpetBuilder.putInt("slotNumber", 1); + CARPET_SLOT = carpetBuilder.build(); + + NbtMapBuilder saddleBuilder = NbtMap.builder(); + NbtMapBuilder acceptedSaddle = NbtMap.builder() + .putShort("Aux", Short.MAX_VALUE) + .putString("Name", "minecraft:saddle"); + List acceptedItem = Collections.singletonList(NbtMap.builder().putCompound("slotItem", acceptedSaddle.build()).build()); + saddleBuilder.putList("acceptedItems", NbtType.COMPOUND, acceptedItem); + saddleBuilder.putCompound("item", acceptedSaddle.build()); + saddleBuilder.putInt("slotNumber", 0); + SADDLE_SLOT = saddleBuilder.build(); + } + + @Override + public void translate(GeyserSession session, ServerOpenHorseWindowPacket packet) { + Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); + if (entity == null) { + return; + } + + UpdateEquipPacket updateEquipPacket = new UpdateEquipPacket(); + updateEquipPacket.setWindowId((short) packet.getWindowId()); + updateEquipPacket.setWindowType((short) ContainerType.HORSE.getId()); + updateEquipPacket.setUniqueEntityId(entity.getGeyserId()); + + NbtMapBuilder builder = NbtMap.builder(); + List slots = new ArrayList<>(); + + InventoryTranslator inventoryTranslator; + if (entity instanceof LlamaEntity) { + inventoryTranslator = new LlamaInventoryTranslator(packet.getNumberOfSlots()); + slots.add(CARPET_SLOT); + } else if (entity instanceof ChestedHorseEntity) { + inventoryTranslator = new DonkeyInventoryTranslator(packet.getNumberOfSlots()); + slots.add(SADDLE_SLOT); + } else { + inventoryTranslator = new HorseInventoryTranslator(packet.getNumberOfSlots()); + slots.add(SADDLE_SLOT); + slots.add(ARMOR_SLOT); + } + + // Build the NbtMap that sets the icons for Bedrock (e.g. sets the saddle outline on the saddle slot) + builder.putList("slots", NbtType.COMPOUND, slots); + + updateEquipPacket.setTag(builder.build()); + session.sendUpstreamPacket(updateEquipPacket); + + session.setInventoryTranslator(inventoryTranslator); + InventoryUtils.openInventory(session, new Container(entity.getMetadata().getString(EntityData.NAMETAG), packet.getWindowId(), packet.getNumberOfSlots(), null, session.getPlayerInventory())); + } +} diff --git a/Java/JavaOpenWindowTranslator.java b/Java/JavaOpenWindowTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..883d792c57cc54eb2eed2f7a77bec54fa6d430be --- /dev/null +++ b/Java/JavaOpenWindowTranslator.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.window; + +import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientCloseWindowPacket; +import com.github.steveice10.mc.protocol.packet.ingame.server.window.ServerOpenWindowPacket; +import org.geysermc.connector.inventory.Inventory; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.chat.MessageTranslator; +import org.geysermc.connector.network.translators.inventory.InventoryTranslator; +import org.geysermc.connector.utils.InventoryUtils; +import org.geysermc.connector.utils.LocaleUtils; + +@Translator(packet = ServerOpenWindowPacket.class) +public class JavaOpenWindowTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerOpenWindowPacket packet) { + if (packet.getWindowId() == 0) { + return; + } + + InventoryTranslator newTranslator = InventoryTranslator.INVENTORY_TRANSLATORS.get(packet.getType()); + Inventory openInventory = session.getOpenInventory(); + //No translator exists for this window type. Close all windows and return. + if (newTranslator == null) { + if (openInventory != null) { + InventoryUtils.closeInventory(session, openInventory.getId(), true); + } + ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(packet.getWindowId()); + session.sendDownstreamPacket(closeWindowPacket); + return; + } + + String name = MessageTranslator.convertMessageLenient(packet.getName(), session.getLocale()); + name = LocaleUtils.getLocaleString(name, session.getLocale()); + + Inventory newInventory = newTranslator.createInventory(name, packet.getWindowId(), packet.getType(), session.getPlayerInventory()); + if (openInventory != null) { + // If the window type is the same, don't close. + // In rare cases, inventories can do funny things where it keeps the same window type up but change the contents. + if (openInventory.getWindowType() != packet.getType()) { + // Sometimes the server can double-open an inventory with the same ID - don't confirm in that instance. + InventoryUtils.closeInventory(session, openInventory.getId(), openInventory.getId() != packet.getWindowId()); + } + } + + session.setInventoryTranslator(newTranslator); + InventoryUtils.openInventory(session, newInventory); + } +} diff --git a/Java/JavaPingPacket.java b/Java/JavaPingPacket.java new file mode 100644 index 0000000000000000000000000000000000000000..c2dc3454d26b966a537f495ee274496623ae7750 --- /dev/null +++ b/Java/JavaPingPacket.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.protocol.packet.ingame.client.ClientPongPacket; +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerPingPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +// Why does this packet exist? Whatever, we better implement it +@Translator(packet = ServerPingPacket.class) +public class JavaPingPacket extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerPingPacket packet) { + session.sendDownstreamPacket(new ClientPongPacket(packet.getId())); + } +} diff --git a/Java/JavaPlayEffectTranslator.java b/Java/JavaPlayEffectTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..aca7a1f939712536afec53316766bbffc049407c --- /dev/null +++ b/Java/JavaPlayEffectTranslator.java @@ -0,0 +1,307 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.data.game.world.effect.*; +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerPlayEffectPacket; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.protocol.bedrock.data.LevelEventType; +import com.nukkitx.protocol.bedrock.data.SoundEvent; +import com.nukkitx.protocol.bedrock.packet.LevelEventPacket; +import com.nukkitx.protocol.bedrock.packet.LevelSoundEventPacket; +import com.nukkitx.protocol.bedrock.packet.TextPacket; +import org.geysermc.connector.GeyserConnector; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.effect.Effect; +import org.geysermc.connector.registry.Registries; +import org.geysermc.connector.utils.LocaleUtils; + +import java.util.Collections; +import java.util.Locale; + +@Translator(packet = ServerPlayEffectPacket.class) +public class JavaPlayEffectTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerPlayEffectPacket packet) { + // Separate case since each RecordEffectData in Java is an individual track in Bedrock + if (packet.getEffect() == SoundEffect.RECORD) { + RecordEffectData recordEffectData = (RecordEffectData) packet.getData(); + SoundEvent soundEvent = Registries.RECORDS.getOrDefault(recordEffectData.getRecordId(), SoundEvent.STOP_RECORD); + Vector3f pos = Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()).add(0.5f, 0.5f, 0.5f); + + LevelSoundEventPacket levelSoundEvent = new LevelSoundEventPacket(); + levelSoundEvent.setIdentifier(""); + levelSoundEvent.setSound(soundEvent); + levelSoundEvent.setPosition(pos); + levelSoundEvent.setRelativeVolumeDisabled(packet.isBroadcast()); + levelSoundEvent.setExtraData(-1); + levelSoundEvent.setBabySound(false); + session.sendUpstreamPacket(levelSoundEvent); + + if (soundEvent != SoundEvent.STOP_RECORD) { + // Send text packet as it seems to be handled in Java Edition client-side. + TextPacket textPacket = new TextPacket(); + textPacket.setType(TextPacket.Type.JUKEBOX_POPUP); + textPacket.setNeedsTranslation(true); + textPacket.setXuid(""); + textPacket.setPlatformChatId(""); + textPacket.setSourceName(null); + textPacket.setMessage("record.nowPlaying"); + String recordString = "%item." + soundEvent.name().toLowerCase(Locale.ROOT) + ".desc"; + textPacket.setParameters(Collections.singletonList(LocaleUtils.getLocaleString(recordString, session.getLocale()))); + session.sendUpstreamPacket(textPacket); + } + return; + } + + if (packet.getEffect() instanceof SoundEffect) { + SoundEffect soundEffect = (SoundEffect) packet.getEffect(); + Effect geyserEffect = Registries.SOUND_EFFECTS.get(soundEffect); + if (geyserEffect != null) { + geyserEffect.handleEffectPacket(session, packet); + return; + } + GeyserConnector.getInstance().getLogger().debug("Unhandled sound effect: " + soundEffect.name()); + } else if (packet.getEffect() instanceof ParticleEffect) { + ParticleEffect particleEffect = (ParticleEffect) packet.getEffect(); + Vector3f pos = Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()).add(0.5f, 0.5f, 0.5f); + + LevelEventPacket effectPacket = new LevelEventPacket(); + effectPacket.setPosition(pos); + effectPacket.setData(0); + switch (particleEffect) { + case COMPOSTER: { + effectPacket.setType(LevelEventType.PARTICLE_CROP_GROWTH); + + ComposterEffectData composterEffectData = (ComposterEffectData) packet.getData(); + LevelSoundEventPacket soundEventPacket = new LevelSoundEventPacket(); + switch (composterEffectData) { + case FILL: + soundEventPacket.setSound(SoundEvent.COMPOSTER_FILL); + break; + case FILL_SUCCESS: + soundEventPacket.setSound(SoundEvent.COMPOSTER_FILL_LAYER); + break; + } + soundEventPacket.setPosition(pos); + soundEventPacket.setIdentifier(""); + soundEventPacket.setExtraData(-1); + soundEventPacket.setBabySound(false); + soundEventPacket.setRelativeVolumeDisabled(false); + session.sendUpstreamPacket(soundEventPacket); + break; + } + case BLOCK_LAVA_EXTINGUISH: { + effectPacket.setType(LevelEventType.PARTICLE_EVAPORATE); + effectPacket.setPosition(pos.add(-0.5f, 0.7f, -0.5f)); + + LevelSoundEventPacket soundEventPacket = new LevelSoundEventPacket(); + soundEventPacket.setSound(SoundEvent.EXTINGUISH_FIRE); + soundEventPacket.setPosition(pos); + soundEventPacket.setIdentifier(""); + soundEventPacket.setExtraData(-1); + soundEventPacket.setBabySound(false); + soundEventPacket.setRelativeVolumeDisabled(false); + session.sendUpstreamPacket(soundEventPacket); + break; + } + case BLOCK_REDSTONE_TORCH_BURNOUT: { + effectPacket.setType(LevelEventType.PARTICLE_EVAPORATE); + effectPacket.setPosition(pos.add(-0.5f, 0, -0.5f)); + + LevelSoundEventPacket soundEventPacket = new LevelSoundEventPacket(); + soundEventPacket.setSound(SoundEvent.EXTINGUISH_FIRE); + soundEventPacket.setPosition(pos); + soundEventPacket.setIdentifier(""); + soundEventPacket.setExtraData(-1); + soundEventPacket.setBabySound(false); + soundEventPacket.setRelativeVolumeDisabled(false); + session.sendUpstreamPacket(soundEventPacket); + break; + } + case BLOCK_END_PORTAL_FRAME_FILL: { + effectPacket.setType(LevelEventType.PARTICLE_EVAPORATE); + effectPacket.setPosition(pos.add(-0.5f, 0.3125f, -0.5f)); + + LevelSoundEventPacket soundEventPacket = new LevelSoundEventPacket(); + soundEventPacket.setSound(SoundEvent.BLOCK_END_PORTAL_FRAME_FILL); + soundEventPacket.setPosition(pos); + soundEventPacket.setIdentifier(""); + soundEventPacket.setExtraData(-1); + soundEventPacket.setBabySound(false); + soundEventPacket.setRelativeVolumeDisabled(false); + session.sendUpstreamPacket(soundEventPacket); + break; + } + case SMOKE: { + effectPacket.setType(LevelEventType.PARTICLE_SHOOT); + + SmokeEffectData smokeEffectData = (SmokeEffectData) packet.getData(); + int data = 0; + switch (smokeEffectData) { + case DOWN: + data = 4; + pos = pos.add(0, -0.9f, 0); + break; + case UP: + data = 4; + pos = pos.add(0, 0.5f, 0); + break; + case NORTH: + data = 1; + pos = pos.add(0, -0.2f, -0.7f); + break; + case SOUTH: + data = 7; + pos = pos.add(0, -0.2f, 0.7f); + break; + case WEST: + data = 3; + pos = pos.add(-0.7f, -0.2f, 0); + break; + case EAST: + data = 5; + pos = pos.add(0.7f, -0.2f, 0); + break; + + } + effectPacket.setPosition(pos); + effectPacket.setData(data); + break; + } + //TODO: Block break particles when under fire + case BREAK_BLOCK: { + effectPacket.setType(LevelEventType.PARTICLE_DESTROY_BLOCK); + + BreakBlockEffectData breakBlockEffectData = (BreakBlockEffectData) packet.getData(); + effectPacket.setData(session.getBlockMappings().getBedrockBlockId(breakBlockEffectData.getBlockState())); + break; + } + case BREAK_SPLASH_POTION: { + effectPacket.setType(LevelEventType.PARTICLE_POTION_SPLASH); + effectPacket.setPosition(pos.add(0, -0.5f, 0)); + + BreakPotionEffectData splashPotionData = (BreakPotionEffectData) packet.getData(); + effectPacket.setData(splashPotionData.getPotionId()); + + LevelSoundEventPacket soundEventPacket = new LevelSoundEventPacket(); + soundEventPacket.setSound(SoundEvent.GLASS); + soundEventPacket.setPosition(pos); + soundEventPacket.setIdentifier(""); + soundEventPacket.setExtraData(-1); + soundEventPacket.setBabySound(false); + soundEventPacket.setRelativeVolumeDisabled(false); + session.sendUpstreamPacket(soundEventPacket); + break; + } + case BREAK_EYE_OF_ENDER: { + effectPacket.setType(LevelEventType.PARTICLE_EYE_OF_ENDER_DEATH); + break; + } + case MOB_SPAWN: { + effectPacket.setType(LevelEventType.PARTICLE_MOB_BLOCK_SPAWN); // TODO: Check, but I don't think I really verified this ever went into effect on Java + break; + } + case BONEMEAL_GROW_WITH_SOUND: // Note that there is no particle without sound in Bedrock. If you wanted to implement the sound, send a PlaySoundPacket with "item.bone_meal.use" and volume and pitch at 1.0F + case BONEMEAL_GROW: { + effectPacket.setType(LevelEventType.PARTICLE_CROP_GROWTH); + + BonemealGrowEffectData growEffectData = (BonemealGrowEffectData) packet.getData(); + effectPacket.setData(growEffectData.getParticleCount()); + break; + } + case ENDERDRAGON_FIREBALL_EXPLODE: { + effectPacket.setType(LevelEventType.PARTICLE_EYE_OF_ENDER_DEATH); // TODO + + DragonFireballEffectData fireballEffectData = (DragonFireballEffectData) packet.getData(); + if (fireballEffectData == DragonFireballEffectData.HAS_SOUND) { + LevelSoundEventPacket soundEventPacket = new LevelSoundEventPacket(); + soundEventPacket.setSound(SoundEvent.EXPLODE); + soundEventPacket.setPosition(pos); + soundEventPacket.setIdentifier(""); + soundEventPacket.setExtraData(-1); + soundEventPacket.setBabySound(false); + soundEventPacket.setRelativeVolumeDisabled(false); + session.sendUpstreamPacket(soundEventPacket); + } + break; + } + case EXPLOSION: { + effectPacket.setType(LevelEventType.PARTICLE_GENERIC_SPAWN); + effectPacket.setData(61); + break; + } + case EVAPORATE: { + effectPacket.setType(LevelEventType.PARTICLE_EVAPORATE_WATER); + effectPacket.setPosition(pos.add(-0.5f, 0.5f, -0.5f)); + break; + } + case END_GATEWAY_SPAWN: { + effectPacket.setType(LevelEventType.PARTICLE_EXPLOSION); + + LevelSoundEventPacket soundEventPacket = new LevelSoundEventPacket(); + soundEventPacket.setSound(SoundEvent.EXPLODE); + soundEventPacket.setPosition(pos); + soundEventPacket.setIdentifier(""); + soundEventPacket.setExtraData(-1); + soundEventPacket.setBabySound(false); + soundEventPacket.setRelativeVolumeDisabled(false); + session.sendUpstreamPacket(soundEventPacket); + break; + } + case DRIPSTONE_DRIP: { + effectPacket.setType(LevelEventType.PARTICLE_DRIPSTONE_DRIP); + break; + } + case ELECTRIC_SPARK: { + // Matches with a Bedrock server but doesn't seem to match up with Java + effectPacket.setType(LevelEventType.PARTICLE_ELECTRIC_SPARK); + break; + } + case WAX_ON: { + effectPacket.setType(LevelEventType.PARTICLE_WAX_ON); + break; + } + case WAX_OFF: { + effectPacket.setType(LevelEventType.PARTICLE_WAX_OFF); + break; + } + case SCRAPE: { + effectPacket.setType(LevelEventType.PARTICLE_SCRAPE); + break; + } + default: { + GeyserConnector.getInstance().getLogger().debug("Unhandled particle effect: " + particleEffect.name()); + return; + } + } + session.sendUpstreamPacket(effectPacket); + } + } +} \ No newline at end of file diff --git a/Java/JavaPlaySoundTranslator.java b/Java/JavaPlaySoundTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..1f1ac0d12605278e0fd52d6b0cb0663ce6cf715a --- /dev/null +++ b/Java/JavaPlaySoundTranslator.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.data.game.world.sound.BuiltinSound; +import com.github.steveice10.mc.protocol.data.game.world.sound.CustomSound; +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerPlaySoundPacket; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.protocol.bedrock.packet.*; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.registry.Registries; +import org.geysermc.connector.registry.type.SoundMapping; + +@Translator(packet = ServerPlaySoundPacket.class) +public class JavaPlaySoundTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerPlaySoundPacket packet) { + String packetSound; + if (packet.getSound() instanceof BuiltinSound) { + packetSound = ((BuiltinSound) packet.getSound()).getName(); + } else if (packet.getSound() instanceof CustomSound) { + packetSound = ((CustomSound) packet.getSound()).getName(); + } else { + session.getConnector().getLogger().debug("Unknown sound packet, we were unable to map this. " + packet.toString()); + return; + } + + SoundMapping soundMapping = Registries.SOUNDS.get(packetSound.replace("minecraft:", "")); + String playsound; + if (soundMapping == null || soundMapping.getPlaysound() == null) { + // no mapping + session.getConnector().getLogger() + .debug("[PlaySound] Defaulting to sound server gave us for " + packet.toString()); + playsound = packetSound.replace("minecraft:", ""); + } else { + playsound = soundMapping.getPlaysound(); + } + + PlaySoundPacket playSoundPacket = new PlaySoundPacket(); + playSoundPacket.setSound(playsound); + playSoundPacket.setPosition(Vector3f.from(packet.getX(), packet.getY(), packet.getZ())); + playSoundPacket.setVolume(packet.getVolume()); + playSoundPacket.setPitch(packet.getPitch()); + + session.sendUpstreamPacket(playSoundPacket); + } +} diff --git a/Java/JavaPlayerAbilitiesTranslator.java b/Java/JavaPlayerAbilitiesTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..4b0152fcb315a8f17c535bed6aa1929f40fb258e --- /dev/null +++ b/Java/JavaPlayerAbilitiesTranslator.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity.player; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.player.ServerPlayerAbilitiesPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = ServerPlayerAbilitiesPacket.class) +public class JavaPlayerAbilitiesTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerPlayerAbilitiesPacket packet) { + session.setCanFly(packet.isCanFly()); + session.setFlying(packet.isFlying()); + session.sendAdventureSettings(); + } +} diff --git a/Java/JavaPlayerActionAckTranslator.java b/Java/JavaPlayerActionAckTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..8c9aa014297a6153e50c90811f48718743bb5e13 --- /dev/null +++ b/Java/JavaPlayerActionAckTranslator.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity.player; + +import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerAction; +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.player.ServerPlayerActionAckPacket; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.protocol.bedrock.data.LevelEventType; +import com.nukkitx.protocol.bedrock.packet.LevelEventPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.world.block.BlockStateValues; +import org.geysermc.connector.utils.ChunkUtils; + +@Translator(packet = ServerPlayerActionAckPacket.class) +public class JavaPlayerActionAckTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerPlayerActionAckPacket packet) { + ChunkUtils.updateBlock(session, packet.getNewState(), packet.getPosition()); + if (packet.getAction() == PlayerAction.START_DIGGING && !packet.isSuccessful()) { + LevelEventPacket stopBreak = new LevelEventPacket(); + stopBreak.setType(LevelEventType.BLOCK_STOP_BREAK); + stopBreak.setPosition(Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ())); + stopBreak.setData(0); + session.setBreakingBlock(BlockStateValues.JAVA_AIR_ID); + session.sendUpstreamPacket(stopBreak); + } + } +} \ No newline at end of file diff --git a/Java/JavaPlayerChangeHeldItemTranslator.java b/Java/JavaPlayerChangeHeldItemTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..27e16ee120294c4bf14ce26981782209f833f4fb --- /dev/null +++ b/Java/JavaPlayerChangeHeldItemTranslator.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity.player; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.player.ServerPlayerChangeHeldItemPacket; +import com.nukkitx.protocol.bedrock.packet.PlayerHotbarPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = ServerPlayerChangeHeldItemPacket.class) +public class JavaPlayerChangeHeldItemTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerPlayerChangeHeldItemPacket packet) { + PlayerHotbarPacket hotbarPacket = new PlayerHotbarPacket(); + hotbarPacket.setContainerId(0); + hotbarPacket.setSelectedHotbarSlot(packet.getSlot()); + hotbarPacket.setSelectHotbarSlot(true); + session.sendUpstreamPacket(hotbarPacket); + + session.getPlayerInventory().setHeldItemSlot(packet.getSlot()); + } +} diff --git a/Java/JavaPlayerHealthTranslator.java b/Java/JavaPlayerHealthTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..20403a6108dba52e21f6a7425d21a7cc7567dc3d --- /dev/null +++ b/Java/JavaPlayerHealthTranslator.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity.player; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.player.ServerPlayerHealthPacket; +import com.nukkitx.protocol.bedrock.data.AttributeData; +import com.nukkitx.protocol.bedrock.packet.SetHealthPacket; +import com.nukkitx.protocol.bedrock.packet.UpdateAttributesPacket; +import org.geysermc.connector.entity.attribute.GeyserAttributeType; +import org.geysermc.connector.entity.player.SessionPlayerEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import java.util.List; + +@Translator(packet = ServerPlayerHealthPacket.class) +public class JavaPlayerHealthTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerPlayerHealthPacket packet) { + SessionPlayerEntity entity = session.getPlayerEntity(); + + int health = (int) Math.ceil(packet.getHealth()); + SetHealthPacket setHealthPacket = new SetHealthPacket(); + setHealthPacket.setHealth(health); + session.sendUpstreamPacket(setHealthPacket); + + entity.setHealth(packet.getHealth()); + + UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket(); + List attributes = attributesPacket.getAttributes(); + + AttributeData healthAttribute = entity.createHealthAttribute(); + entity.getAttributes().put(GeyserAttributeType.HEALTH, healthAttribute); + attributes.add(healthAttribute); + + AttributeData hungerAttribute = GeyserAttributeType.HUNGER.getAttribute(packet.getFood()); + entity.getAttributes().put(GeyserAttributeType.HUNGER, hungerAttribute); + attributes.add(hungerAttribute); + + AttributeData saturationAttribute = GeyserAttributeType.SATURATION.getAttribute(packet.getSaturation()); + entity.getAttributes().put(GeyserAttributeType.SATURATION, saturationAttribute); + attributes.add(saturationAttribute); + + attributesPacket.setRuntimeEntityId(entity.getGeyserId()); + session.sendUpstreamPacket(attributesPacket); + } +} diff --git a/Java/JavaPlayerListEntryTranslator.java b/Java/JavaPlayerListEntryTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..b5a35803545b71573b8fe24d0309faf1a2554638 --- /dev/null +++ b/Java/JavaPlayerListEntryTranslator.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity.player; + +import com.github.steveice10.mc.protocol.data.game.PlayerListEntry; +import com.github.steveice10.mc.protocol.data.game.PlayerListEntryAction; +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerPlayerListEntryPacket; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.protocol.bedrock.packet.PlayerListPacket; +import org.geysermc.connector.GeyserConnector; +import org.geysermc.connector.entity.player.PlayerEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.skin.SkinManager; + +@Translator(packet = ServerPlayerListEntryPacket.class) +public class JavaPlayerListEntryTranslator extends PacketTranslator { + @Override + public void translate(GeyserSession session, ServerPlayerListEntryPacket packet) { + if (packet.getAction() != PlayerListEntryAction.ADD_PLAYER && packet.getAction() != PlayerListEntryAction.REMOVE_PLAYER) + return; + + PlayerListPacket translate = new PlayerListPacket(); + translate.setAction(packet.getAction() == PlayerListEntryAction.ADD_PLAYER ? PlayerListPacket.Action.ADD : PlayerListPacket.Action.REMOVE); + + for (PlayerListEntry entry : packet.getEntries()) { + switch (packet.getAction()) { + case ADD_PLAYER: + PlayerEntity playerEntity; + boolean self = entry.getProfile().getId().equals(session.getPlayerEntity().getUuid()); + + if (self) { + // Entity is ourself + playerEntity = session.getPlayerEntity(); + } else { + playerEntity = session.getEntityCache().getPlayerEntity(entry.getProfile().getId()); + } + + if (playerEntity == null) { + // It's a new player + playerEntity = new PlayerEntity( + entry.getProfile(), + -1, + session.getEntityCache().getNextEntityId().incrementAndGet(), + Vector3f.ZERO, + Vector3f.ZERO, + Vector3f.ZERO + ); + + session.getEntityCache().addPlayerEntity(playerEntity); + } else { + playerEntity.setProfile(entry.getProfile()); + } + + playerEntity.setPlayerList(true); + + // We'll send our own PlayerListEntry in requestAndHandleSkinAndCape + // But we need to send other player's entries so they show up in the player list + // without processing their skin information - that'll be processed when they spawn in + if (self) { + SkinManager.requestAndHandleSkinAndCape(playerEntity, session, skinAndCape -> + GeyserConnector.getInstance().getLogger().debug("Loaded Local Bedrock Java Skin Data for " + session.getClientData().getUsername())); + } else { + playerEntity.setValid(true); + PlayerListPacket.Entry playerListEntry = SkinManager.buildCachedEntry(session, playerEntity); + + translate.getEntries().add(playerListEntry); + } + break; + case REMOVE_PLAYER: + // As the player entity is no longer present, we can remove the entry + PlayerEntity entity = session.getEntityCache().removePlayerEntity(entry.getProfile().getId()); + if (entity != null) { + // Just remove the entity's player list status + // Don't despawn the entity - the Java server will also take care of that. + entity.setPlayerList(false); + } + if (entity == session.getPlayerEntity()) { + // If removing ourself we use our AuthData UUID + translate.getEntries().add(new PlayerListPacket.Entry(session.getAuthData().getUUID())); + } else { + translate.getEntries().add(new PlayerListPacket.Entry(entry.getProfile().getId())); + } + break; + } + } + + if (!translate.getEntries().isEmpty() && (packet.getAction() == PlayerListEntryAction.REMOVE_PLAYER || session.getUpstream().isInitialized())) { + session.sendUpstreamPacket(translate); + } + } +} diff --git a/Java/JavaPlayerPositionRotationTranslator.java b/Java/JavaPlayerPositionRotationTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..6b1778464162ee305b9a290246c5392b671ce4cb --- /dev/null +++ b/Java/JavaPlayerPositionRotationTranslator.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity.player; + +import com.github.steveice10.mc.protocol.data.game.entity.player.PositionElement; +import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientTeleportConfirmPacket; +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.player.ServerPlayerPositionRotationPacket; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.protocol.bedrock.data.entity.EntityData; +import com.nukkitx.protocol.bedrock.data.entity.EntityLinkData; +import com.nukkitx.protocol.bedrock.packet.MovePlayerPacket; +import com.nukkitx.protocol.bedrock.packet.RespawnPacket; +import com.nukkitx.protocol.bedrock.packet.SetEntityDataPacket; +import com.nukkitx.protocol.bedrock.packet.SetEntityLinkPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.player.PlayerEntity; +import org.geysermc.connector.entity.type.EntityType; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.session.cache.TeleportCache; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.ChunkUtils; +import org.geysermc.connector.utils.EntityUtils; +import org.geysermc.connector.utils.LanguageUtils; + +@Translator(packet = ServerPlayerPositionRotationPacket.class) +public class JavaPlayerPositionRotationTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerPlayerPositionRotationPacket packet) { + if (!session.isLoggedIn()) + return; + + PlayerEntity entity = session.getPlayerEntity(); + + if (!session.isSpawned()) { + Vector3f pos = Vector3f.from(packet.getX(), packet.getY(), packet.getZ()); + entity.setPosition(pos); + entity.setRotation(Vector3f.from(packet.getYaw(), packet.getPitch(), packet.getYaw())); + + RespawnPacket respawnPacket = new RespawnPacket(); + respawnPacket.setRuntimeEntityId(0); // Bedrock server behavior + respawnPacket.setPosition(entity.getPosition()); + respawnPacket.setState(RespawnPacket.State.SERVER_READY); + session.sendUpstreamPacket(respawnPacket); + + SetEntityDataPacket entityDataPacket = new SetEntityDataPacket(); + entityDataPacket.setRuntimeEntityId(entity.getGeyserId()); + entityDataPacket.getMetadata().putAll(entity.getMetadata()); + session.sendUpstreamPacket(entityDataPacket); + + MovePlayerPacket movePlayerPacket = new MovePlayerPacket(); + movePlayerPacket.setRuntimeEntityId(entity.getGeyserId()); + movePlayerPacket.setPosition(entity.getPosition()); + movePlayerPacket.setRotation(Vector3f.from(packet.getPitch(), packet.getYaw(), 0)); + movePlayerPacket.setMode(MovePlayerPacket.Mode.RESPAWN); + + session.sendUpstreamPacket(movePlayerPacket); + session.setSpawned(true); + + ClientTeleportConfirmPacket teleportConfirmPacket = new ClientTeleportConfirmPacket(packet.getTeleportId()); + session.sendDownstreamPacket(teleportConfirmPacket); + + ChunkUtils.updateChunkPosition(session, pos.toInt()); + + session.getConnector().getLogger().debug(LanguageUtils.getLocaleStringLog("geyser.entity.player.spawn", packet.getX(), packet.getY(), packet.getZ())); + return; + } + + session.setSpawned(true); + + if (packet.isDismountVehicle() && session.getRidingVehicleEntity() != null) { + Entity vehicle = session.getRidingVehicleEntity(); + SetEntityLinkPacket linkPacket = new SetEntityLinkPacket(); + linkPacket.setEntityLink(new EntityLinkData(vehicle.getGeyserId(), entity.getGeyserId(), EntityLinkData.Type.REMOVE, false, false)); + session.sendUpstreamPacket(linkPacket); + vehicle.getPassengers().remove(entity.getEntityId()); + entity.getMetadata().put(EntityData.RIDER_ROTATION_LOCKED, (byte) 0); + entity.getMetadata().put(EntityData.RIDER_MAX_ROTATION, 0f); + entity.getMetadata().put(EntityData.RIDER_MIN_ROTATION, 0f); + entity.getMetadata().put(EntityData.RIDER_ROTATION_OFFSET, 0f); + session.setRidingVehicleEntity(null); + entity.updateBedrockMetadata(session); + + EntityUtils.updateMountOffset(entity, vehicle, session, false, false, entity.getPassengers().size() > 1); + } + + // If coordinates are relative, then add to the existing coordinate + double newX = packet.getX() + + (packet.getRelative().contains(PositionElement.X) ? entity.getPosition().getX() : 0); + double newY = packet.getY() + + (packet.getRelative().contains(PositionElement.Y) ? entity.getPosition().getY() - EntityType.PLAYER.getOffset() : 0); + double newZ = packet.getZ() + + (packet.getRelative().contains(PositionElement.Z) ? entity.getPosition().getZ() : 0); + + float newPitch = packet.getPitch() + + (packet.getRelative().contains(PositionElement.PITCH) ? entity.getBedrockRotation().getX() : 0); + float newYaw = packet.getYaw() + + (packet.getRelative().contains(PositionElement.YAW) ? entity.getBedrockRotation().getY() : 0); + + session.getConnector().getLogger().debug("Teleport from " + entity.getPosition().getX() + " " + (entity.getPosition().getY() - EntityType.PLAYER.getOffset()) + " " + entity.getPosition().getZ()); + + session.addTeleport(new TeleportCache(newX, newY, newZ, newPitch, newYaw, packet.getTeleportId())); + + Vector3f lastPlayerPosition = entity.getPosition().down(EntityType.PLAYER.getOffset()); + float lastPlayerPitch = entity.getBedrockRotation().getX(); + Vector3f teleportDestination = Vector3f.from(newX, newY, newZ); + entity.moveAbsolute(session, teleportDestination, newYaw, newPitch, true, true); + + session.getConnector().getLogger().debug("to " + entity.getPosition().getX() + " " + (entity.getPosition().getY() - EntityType.PLAYER.getOffset()) + " " + entity.getPosition().getZ()); + + // Bedrock ignores teleports that are extremely close to the player's original position and orientation, + // so check if we can immediately confirm the teleport + if (lastPlayerPosition.distanceSquared(teleportDestination) < 0.001 && Math.abs(newPitch - lastPlayerPitch) < 5) { + session.confirmTeleport(lastPlayerPosition.toDouble()); + } + } +} diff --git a/Java/JavaPlayerSetExperienceTranslator.java b/Java/JavaPlayerSetExperienceTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..8a8636eb50abb5e29f2cbe881afec466ff9501e9 --- /dev/null +++ b/Java/JavaPlayerSetExperienceTranslator.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity.player; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.player.ServerPlayerSetExperiencePacket; +import com.nukkitx.protocol.bedrock.data.AttributeData; +import com.nukkitx.protocol.bedrock.packet.UpdateAttributesPacket; +import org.geysermc.connector.entity.attribute.GeyserAttributeType; +import org.geysermc.connector.entity.player.SessionPlayerEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import java.util.Arrays; + +@Translator(packet = ServerPlayerSetExperiencePacket.class) +public class JavaPlayerSetExperienceTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerPlayerSetExperiencePacket packet) { + SessionPlayerEntity entity = session.getPlayerEntity(); + + AttributeData experience = GeyserAttributeType.EXPERIENCE.getAttribute(packet.getExperience()); + entity.getAttributes().put(GeyserAttributeType.EXPERIENCE, experience); + AttributeData experienceLevel = GeyserAttributeType.EXPERIENCE_LEVEL.getAttribute(packet.getLevel()); + entity.getAttributes().put(GeyserAttributeType.EXPERIENCE_LEVEL, experienceLevel); + + UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket(); + attributesPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId()); + attributesPacket.setAttributes(Arrays.asList(experience, experienceLevel)); + session.sendUpstreamPacket(attributesPacket); + } +} diff --git a/Java/JavaPluginMessageTranslator.java b/Java/JavaPluginMessageTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..15f1f960b4326dec294bc94e4b353082915f70fe --- /dev/null +++ b/Java/JavaPluginMessageTranslator.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2019-2020 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.protocol.packet.ingame.client.ClientPluginMessagePacket; +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerPluginMessagePacket; +import com.google.common.base.Charsets; +import org.geysermc.connector.common.AuthType; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.cumulus.Form; +import org.geysermc.cumulus.Forms; +import org.geysermc.cumulus.util.FormType; + +import java.nio.charset.StandardCharsets; + +@Translator(packet = ServerPluginMessagePacket.class) +public class JavaPluginMessageTranslator extends PacketTranslator { + @Override + public void translate(GeyserSession session, ServerPluginMessagePacket packet) { + // The only plugin messages it has to listen for are Floodgate plugin messages + if (session.getRemoteAuthType() != AuthType.FLOODGATE) { + return; + } + + String channel = packet.getChannel(); + + if (channel.equals("floodgate:form")) { + byte[] data = packet.getData(); + + // receive: first byte is form type, second and third are the id, remaining is the form data + // respond: first and second byte id, remaining is form response data + + FormType type = FormType.getByOrdinal(data[0]); + if (type == null) { + throw new NullPointerException( + "Got type " + data[0] + " which isn't a valid form type!"); + } + + String dataString = new String(data, 3, data.length - 3, Charsets.UTF_8); + + Form form = Forms.fromJson(dataString, type); + form.setResponseHandler(response -> { + byte[] raw = response.getBytes(StandardCharsets.UTF_8); + byte[] finalData = new byte[raw.length + 2]; + + finalData[0] = data[1]; + finalData[1] = data[2]; + System.arraycopy(raw, 0, finalData, 2, raw.length); + + session.sendDownstreamPacket(new ClientPluginMessagePacket(channel, finalData)); + }); + session.sendForm(form); + } + } +} diff --git a/Java/JavaRemoveEntitiesTranslator.java b/Java/JavaRemoveEntitiesTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..0b1e021e23117b3fd4cbc3f59190fbd2624a5d9a --- /dev/null +++ b/Java/JavaRemoveEntitiesTranslator.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerRemoveEntitiesPacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = ServerRemoveEntitiesPacket.class) +public class JavaRemoveEntitiesTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerRemoveEntitiesPacket packet) { + for (int entityId : packet.getEntityIds()) { + Entity entity = session.getEntityCache().getEntityByJavaId(entityId); + if (entity != null) { + session.getEntityCache().removeEntity(entity, false); + } + } + } +} + diff --git a/Java/JavaRespawnTranslator.java b/Java/JavaRespawnTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..8df47c7b0d8b09f0d29d04db2f97dcd242818fff --- /dev/null +++ b/Java/JavaRespawnTranslator.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerRespawnPacket; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.protocol.bedrock.data.LevelEventType; +import com.nukkitx.protocol.bedrock.packet.LevelEventPacket; +import com.nukkitx.protocol.bedrock.packet.SetPlayerGameTypePacket; +import org.geysermc.connector.entity.attribute.GeyserAttributeType; +import org.geysermc.connector.entity.player.SessionPlayerEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.inventory.InventoryTranslator; +import org.geysermc.connector.utils.ChunkUtils; +import org.geysermc.connector.utils.DimensionUtils; + +@Translator(packet = ServerRespawnPacket.class) +public class JavaRespawnTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerRespawnPacket packet) { + SessionPlayerEntity entity = session.getPlayerEntity(); + + entity.setHealth(entity.getMaxHealth()); + entity.getAttributes().put(GeyserAttributeType.HEALTH, entity.createHealthAttribute()); + + session.setInventoryTranslator(InventoryTranslator.PLAYER_INVENTORY_TRANSLATOR); + session.setOpenInventory(null); + session.setClosingInventory(false); + + SetPlayerGameTypePacket playerGameTypePacket = new SetPlayerGameTypePacket(); + playerGameTypePacket.setGamemode(packet.getGamemode().ordinal()); + session.sendUpstreamPacket(playerGameTypePacket); + session.setGameMode(packet.getGamemode()); + + if (session.isRaining()) { + LevelEventPacket stopRainPacket = new LevelEventPacket(); + stopRainPacket.setType(LevelEventType.STOP_RAINING); + stopRainPacket.setData(0); + stopRainPacket.setPosition(Vector3f.ZERO); + session.sendUpstreamPacket(stopRainPacket); + session.setRaining(false); + } + + if (session.isThunder()) { + LevelEventPacket stopThunderPacket = new LevelEventPacket(); + stopThunderPacket.setType(LevelEventType.STOP_THUNDERSTORM); + stopThunderPacket.setData(0); + stopThunderPacket.setPosition(Vector3f.ZERO); + session.sendUpstreamPacket(stopThunderPacket); + session.setThunder(false); + } + + String newDimension = DimensionUtils.getNewDimension(packet.getDimension()); + if (!session.getDimension().equals(newDimension) || !packet.getWorldName().equals(session.getWorldName())) { + // Switching to a new world (based off the world name change); send a fake dimension change + if (!packet.getWorldName().equals(session.getWorldName()) && (session.getDimension().equals(newDimension) + // Ensure that the player never ever dimension switches to the same dimension - BAD + // Can likely be removed if the Above Bedrock Nether Building option can be removed + || DimensionUtils.javaToBedrock(session.getDimension()) == DimensionUtils.javaToBedrock(newDimension))) { + String fakeDim = DimensionUtils.getTemporaryDimension(session.getDimension(), newDimension); + DimensionUtils.switchDimension(session, fakeDim); + } + session.setWorldName(packet.getWorldName()); + DimensionUtils.switchDimension(session, newDimension); + } + + ChunkUtils.applyDimensionHeight(session, packet.getDimension()); + } +} diff --git a/Java/JavaScoreboardObjectiveTranslator.java b/Java/JavaScoreboardObjectiveTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..d898edf9c280484e7d71533cd3c848310b9c2129 --- /dev/null +++ b/Java/JavaScoreboardObjectiveTranslator.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.scoreboard; + +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.session.cache.WorldCache; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.scoreboard.Objective; +import org.geysermc.connector.scoreboard.Scoreboard; +import org.geysermc.connector.scoreboard.ScoreboardUpdater; +import org.geysermc.connector.network.translators.chat.MessageTranslator; + +import com.github.steveice10.mc.protocol.data.game.scoreboard.ObjectiveAction; +import com.github.steveice10.mc.protocol.packet.ingame.server.scoreboard.ServerScoreboardObjectivePacket; + +@Translator(packet = ServerScoreboardObjectivePacket.class) +public class JavaScoreboardObjectiveTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerScoreboardObjectivePacket packet) { + WorldCache worldCache = session.getWorldCache(); + Scoreboard scoreboard = worldCache.getScoreboard(); + Objective objective = scoreboard.getObjective(packet.getName()); + int pps = worldCache.increaseAndGetScoreboardPacketsPerSecond(); + + if (objective == null && packet.getAction() != ObjectiveAction.REMOVE) { + objective = scoreboard.registerNewObjective(packet.getName(), false); + } + + switch (packet.getAction()) { + case ADD: + case UPDATE: + objective.setDisplayName(MessageTranslator.convertMessage(packet.getDisplayName())) + .setType(packet.getType().ordinal()); + break; + case REMOVE: + scoreboard.unregisterObjective(packet.getName()); + break; + } + + if (objective == null || !objective.isActive()) { + return; + } + + // ScoreboardUpdater will handle it for us if the packets per second + // (for score and team packets) is higher then the first threshold + if (pps < ScoreboardUpdater.FIRST_SCORE_PACKETS_PER_SECOND_THRESHOLD) { + scoreboard.onUpdate(); + } + } +} diff --git a/Java/JavaSetActionBarTextTranslator.java b/Java/JavaSetActionBarTextTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..516568b376d6493b42c63723d7583f49dded8c07 --- /dev/null +++ b/Java/JavaSetActionBarTextTranslator.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.title; + +import com.github.steveice10.mc.protocol.packet.ingame.server.title.ServerSetActionBarTextPacket; +import com.nukkitx.protocol.bedrock.packet.SetTitlePacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.chat.MessageTranslator; + +@Translator(packet = ServerSetActionBarTextPacket.class) +public class JavaSetActionBarTextTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerSetActionBarTextPacket packet) { + String text; + if (packet.getText() == null) { //TODO 1.17 can this happen? + text = " "; + } else { + text = MessageTranslator.convertMessage(packet.getText(), session.getLocale()); + } + + SetTitlePacket titlePacket = new SetTitlePacket(); + titlePacket.setType(SetTitlePacket.Type.ACTIONBAR); + titlePacket.setText(text); + titlePacket.setXuid(""); + titlePacket.setPlatformOnlineId(""); + session.sendUpstreamPacket(titlePacket); + } +} diff --git a/Java/JavaSetSlotTranslator.java b/Java/JavaSetSlotTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..27f932c984eb3f0125292653e2a889a9ab5f7ee7 --- /dev/null +++ b/Java/JavaSetSlotTranslator.java @@ -0,0 +1,277 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.window; + +import com.github.steveice10.mc.protocol.data.game.entity.metadata.ItemStack; +import com.github.steveice10.mc.protocol.data.game.recipe.Ingredient; +import com.github.steveice10.mc.protocol.data.game.recipe.Recipe; +import com.github.steveice10.mc.protocol.data.game.recipe.RecipeType; +import com.github.steveice10.mc.protocol.data.game.recipe.data.ShapedRecipeData; +import com.github.steveice10.mc.protocol.data.game.recipe.data.ShapelessRecipeData; +import com.github.steveice10.mc.protocol.packet.ingame.server.window.ServerSetSlotPacket; +import com.nukkitx.protocol.bedrock.data.inventory.ContainerId; +import com.nukkitx.protocol.bedrock.data.inventory.CraftingData; +import com.nukkitx.protocol.bedrock.data.inventory.ItemData; +import com.nukkitx.protocol.bedrock.packet.CraftingDataPacket; +import com.nukkitx.protocol.bedrock.packet.InventorySlotPacket; +import org.geysermc.connector.inventory.GeyserItemStack; +import org.geysermc.connector.inventory.Inventory; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.inventory.InventoryTranslator; +import org.geysermc.connector.network.translators.inventory.translators.CraftingInventoryTranslator; +import org.geysermc.connector.network.translators.inventory.translators.PlayerInventoryTranslator; +import org.geysermc.connector.network.translators.item.ItemTranslator; +import org.geysermc.connector.utils.InventoryUtils; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +@Translator(packet = ServerSetSlotPacket.class) +public class JavaSetSlotTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerSetSlotPacket packet) { + if (packet.getWindowId() == 255) { //cursor + GeyserItemStack newItem = GeyserItemStack.from(packet.getItem()); + session.getPlayerInventory().setCursor(newItem, session); + InventoryUtils.updateCursor(session); + return; + } + + //TODO: support window id -2, should update player inventory + Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId()); + if (inventory == null) + return; + + inventory.setStateId(packet.getStateId()); + + InventoryTranslator translator = session.getInventoryTranslator(); + if (translator != null) { + if (session.getCraftingGridFuture() != null) { + session.getCraftingGridFuture().cancel(false); + } + session.setCraftingGridFuture(session.scheduleInEventLoop(() -> updateCraftingGrid(session, packet, inventory, translator), 150, TimeUnit.MILLISECONDS)); + + GeyserItemStack newItem = GeyserItemStack.from(packet.getItem()); + if (packet.getWindowId() == 0 && !(translator instanceof PlayerInventoryTranslator)) { + // In rare cases, the window ID can still be 0 but Java treats it as valid + session.getPlayerInventory().setItem(packet.getSlot(), newItem, session); + InventoryTranslator.PLAYER_INVENTORY_TRANSLATOR.updateSlot(session, session.getPlayerInventory(), packet.getSlot()); + } else { + inventory.setItem(packet.getSlot(), newItem, session); + translator.updateSlot(session, inventory, packet.getSlot()); + } + } + } + + private static void updateCraftingGrid(GeyserSession session, ServerSetSlotPacket packet, Inventory inventory, InventoryTranslator translator) { + if (packet.getSlot() == 0) { + int gridSize; + if (translator instanceof PlayerInventoryTranslator) { + gridSize = 4; + } else if (translator instanceof CraftingInventoryTranslator) { + gridSize = 9; + } else { + return; + } + + if (packet.getItem() == null || packet.getItem().getId() == 0) { + return; + } + + int offset = gridSize == 4 ? 28 : 32; + int gridDimensions = gridSize == 4 ? 2 : 3; + int firstRow = -1, height = -1; + int firstCol = -1, width = -1; + for (int row = 0; row < gridDimensions; row++) { + for (int col = 0; col < gridDimensions; col++) { + if (!inventory.getItem(col + (row * gridDimensions) + 1).isEmpty()) { + if (firstRow == -1) { + firstRow = row; + firstCol = col; + } else { + firstCol = Math.min(firstCol, col); + } + height = Math.max(height, row); + width = Math.max(width, col); + } + } + } + + //empty grid + if (firstRow == -1) { + return; + } + + height += -firstRow + 1; + width += -firstCol + 1; + + recipes: + for (Recipe recipe : session.getCraftingRecipes().values()) { + if (recipe.getType() == RecipeType.CRAFTING_SHAPED) { + ShapedRecipeData data = (ShapedRecipeData) recipe.getData(); + if (!data.getResult().equals(packet.getItem())) { + continue; + } + if (data.getWidth() != width || data.getHeight() != height || width * height != data.getIngredients().length) { + continue; + } + + Ingredient[] ingredients = data.getIngredients(); + if (!testShapedRecipe(ingredients, inventory, gridDimensions, firstRow, height, firstCol, width)) { + Ingredient[] mirroredIngredients = new Ingredient[data.getIngredients().length]; + for (int row = 0; row < height; row++) { + for (int col = 0; col < width; col++) { + mirroredIngredients[col + (row * width)] = ingredients[(width - 1 - col) + (row * width)]; + } + } + + if (Arrays.equals(ingredients, mirroredIngredients) || + !testShapedRecipe(mirroredIngredients, inventory, gridDimensions, firstRow, height, firstCol, width)) { + continue; + } + } + // Recipe is had, don't sent packet + return; + } else if (recipe.getType() == RecipeType.CRAFTING_SHAPELESS) { + ShapelessRecipeData data = (ShapelessRecipeData) recipe.getData(); + if (!data.getResult().equals(packet.getItem())) { + continue; + } + for (int i = 0; i < data.getIngredients().length; i++) { + Ingredient ingredient = data.getIngredients()[i]; + for (ItemStack itemStack : ingredient.getOptions()) { + boolean inventoryHasItem = false; + for (int j = 0; j < inventory.getSize(); j++) { + GeyserItemStack geyserItemStack = inventory.getItem(j); + if (geyserItemStack.isEmpty()) { + inventoryHasItem = itemStack == null || itemStack.getId() == 0; + if (inventoryHasItem) { + break; + } + } else if (itemStack.equals(geyserItemStack.getItemStack(1))) { + inventoryHasItem = true; + break; + } + } + if (!inventoryHasItem) { + continue recipes; + } + } + } + // Recipe is had, don't sent packet + return; + } + } + + UUID uuid = UUID.randomUUID(); + int newRecipeId = session.getLastRecipeNetId().incrementAndGet(); + + ItemData[] ingredients = new ItemData[height * width]; + //construct ingredient list and clear slots on client + Ingredient[] javaIngredients = new Ingredient[height * width]; + int index = 0; + for (int row = firstRow; row < height + firstRow; row++) { + for (int col = firstCol; col < width + firstCol; col++) { + GeyserItemStack geyserItemStack = inventory.getItem(col + (row * gridDimensions) + 1); + ingredients[index] = geyserItemStack.getItemData(session); + ItemStack[] itemStacks = new ItemStack[] {geyserItemStack.isEmpty() ? null : geyserItemStack.getItemStack(1)}; + javaIngredients[index] = new Ingredient(itemStacks); + + InventorySlotPacket slotPacket = new InventorySlotPacket(); + slotPacket.setContainerId(ContainerId.UI); + slotPacket.setSlot(col + (row * gridDimensions) + offset); + slotPacket.setItem(ItemData.AIR); + session.sendUpstreamPacket(slotPacket); + index++; + } + } + + ShapedRecipeData data = new ShapedRecipeData(width, height, "", javaIngredients, packet.getItem()); + // Cache this recipe so we know the client has received it + session.getCraftingRecipes().put(newRecipeId, new Recipe(RecipeType.CRAFTING_SHAPED, uuid.toString(), data)); + + CraftingDataPacket craftPacket = new CraftingDataPacket(); + craftPacket.getCraftingData().add(CraftingData.fromShaped( + uuid.toString(), + width, + height, + Arrays.asList(ingredients), + Collections.singletonList(ItemTranslator.translateToBedrock(session, packet.getItem())), + uuid, + "crafting_table", + 0, + newRecipeId + )); + craftPacket.setCleanRecipes(false); + session.sendUpstreamPacket(craftPacket); + + index = 0; + for (int row = firstRow; row < height + firstRow; row++) { + for (int col = firstCol; col < width + firstCol; col++) { + InventorySlotPacket slotPacket = new InventorySlotPacket(); + slotPacket.setContainerId(ContainerId.UI); + slotPacket.setSlot(col + (row * gridDimensions) + offset); + slotPacket.setItem(ingredients[index]); + session.sendUpstreamPacket(slotPacket); + index++; + } + } + } + } + + private static boolean testShapedRecipe(Ingredient[] ingredients, Inventory inventory, int gridDimensions, int firstRow, int height, int firstCol, int width) { + int ingredientIndex = 0; + for (int row = firstRow; row < height + firstRow; row++) { + for (int col = firstCol; col < width + firstCol; col++) { + GeyserItemStack geyserItemStack = inventory.getItem(col + (row * gridDimensions) + 1); + Ingredient ingredient = ingredients[ingredientIndex++]; + if (ingredient.getOptions().length == 0) { + if (!geyserItemStack.isEmpty()) { + return false; + } + } else { + boolean inventoryHasItem = false; + for (ItemStack item : ingredient.getOptions()) { + if (Objects.equals(geyserItemStack.getItemStack(1), item)) { + inventoryHasItem = true; + break; + } + } + if (!inventoryHasItem) { + return false; + } + } + } + } + return true; + } +} diff --git a/Java/JavaSetSubtitleTextTranslator.java b/Java/JavaSetSubtitleTextTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..ee246ea11776e64008d675a751862b623ff70926 --- /dev/null +++ b/Java/JavaSetSubtitleTextTranslator.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.title; + +import com.github.steveice10.mc.protocol.packet.ingame.server.title.ServerSetSubtitleTextPacket; +import com.nukkitx.protocol.bedrock.packet.SetTitlePacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.chat.MessageTranslator; + +@Translator(packet = ServerSetSubtitleTextPacket.class) +public class JavaSetSubtitleTextTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerSetSubtitleTextPacket packet) { + String text; + if (packet.getText() == null) { //TODO 1.17 can this happen? + text = " "; + } else { + text = MessageTranslator.convertMessage(packet.getText(), session.getLocale()); + } + + SetTitlePacket titlePacket = new SetTitlePacket(); + titlePacket.setType(SetTitlePacket.Type.SUBTITLE); + titlePacket.setText(text); + titlePacket.setXuid(""); + titlePacket.setPlatformOnlineId(""); + session.sendUpstreamPacket(titlePacket); + } +} diff --git a/Java/JavaSetTitleTextTranslator.java b/Java/JavaSetTitleTextTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..199d05e3be3f8f695701f24e53f19483b0ec8f0d --- /dev/null +++ b/Java/JavaSetTitleTextTranslator.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.title; + +import com.github.steveice10.mc.protocol.packet.ingame.server.title.ServerSetTitleTextPacket; +import com.nukkitx.protocol.bedrock.packet.SetTitlePacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.chat.MessageTranslator; + +@Translator(packet = ServerSetTitleTextPacket.class) +public class JavaSetTitleTextTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerSetTitleTextPacket packet) { + String text; + if (packet.getText() == null) { //TODO 1.17 can this happen? + text = " "; + } else { + text = MessageTranslator.convertMessage(packet.getText(), session.getLocale()); + } + + SetTitlePacket titlePacket = new SetTitlePacket(); + titlePacket.setType(SetTitlePacket.Type.TITLE); + titlePacket.setText(text); + titlePacket.setXuid(""); + titlePacket.setPlatformOnlineId(""); + session.sendUpstreamPacket(titlePacket); + } +} diff --git a/Java/JavaSetTitlesAnimationTranslator.java b/Java/JavaSetTitlesAnimationTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..7514eef4c04673031c77c325b4d3573ed572320d --- /dev/null +++ b/Java/JavaSetTitlesAnimationTranslator.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.title; + +import com.github.steveice10.mc.protocol.packet.ingame.server.title.ServerSetTitlesAnimationPacket; +import com.nukkitx.protocol.bedrock.packet.SetTitlePacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = ServerSetTitlesAnimationPacket.class) +public class JavaSetTitlesAnimationTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerSetTitlesAnimationPacket packet) { + SetTitlePacket titlePacket = new SetTitlePacket(); + titlePacket.setType(SetTitlePacket.Type.TIMES); + titlePacket.setText(""); + titlePacket.setFadeInTime(packet.getFadeIn()); + titlePacket.setFadeOutTime(packet.getFadeOut()); + titlePacket.setStayTime(packet.getStay()); + titlePacket.setXuid(""); + titlePacket.setPlatformOnlineId(""); + session.sendUpstreamPacket(titlePacket); + } +} diff --git a/Java/JavaSpawnEntityTranslator.java b/Java/JavaSpawnEntityTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..e53358ac2e265e8c219e4bb612d69fcda75780ff --- /dev/null +++ b/Java/JavaSpawnEntityTranslator.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity.spawn; + +import com.github.steveice10.mc.protocol.data.game.entity.object.FallingBlockData; +import com.github.steveice10.mc.protocol.data.game.entity.object.HangingDirection; +import com.github.steveice10.mc.protocol.data.game.entity.object.ProjectileData; +import com.github.steveice10.mc.protocol.data.game.entity.type.EntityType; +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnEntityPacket; +import com.nukkitx.math.vector.Vector3f; +import org.geysermc.connector.entity.*; +import org.geysermc.connector.entity.player.PlayerEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.EntityUtils; +import org.geysermc.connector.utils.LanguageUtils; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; + +@Translator(packet = ServerSpawnEntityPacket.class) +public class JavaSpawnEntityTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerSpawnEntityPacket packet) { + + Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ()); + Vector3f motion = Vector3f.from(packet.getMotionX(), packet.getMotionY(), packet.getMotionZ()); + Vector3f rotation = Vector3f.from(packet.getYaw(), packet.getPitch(), 0); + + org.geysermc.connector.entity.type.EntityType type = EntityUtils.toBedrockEntity(packet.getType()); + if (type == null) { + session.getConnector().getLogger().warning(LanguageUtils.getLocaleStringLog("geyser.entity.type_null", packet.getType())); + return; + } + + Class entityClass = type.getEntityClass(); + try { + Entity entity; + if (packet.getType() == EntityType.FALLING_BLOCK) { + entity = new FallingBlockEntity(packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(), + type, position, motion, rotation, ((FallingBlockData) packet.getData()).getId()); + } else if (packet.getType() == EntityType.ITEM_FRAME || packet.getType() == EntityType.GLOW_ITEM_FRAME) { + // Item frames need the hanging direction + entity = new ItemFrameEntity(packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(), + type, position, motion, rotation, (HangingDirection) packet.getData()); + } else if (packet.getType() == EntityType.FISHING_BOBBER) { + // Fishing bobbers need the owner for the line + int ownerEntityId = ((ProjectileData) packet.getData()).getOwnerId(); + Entity owner = session.getEntityCache().getEntityByJavaId(ownerEntityId); + if (owner == null && session.getPlayerEntity().getEntityId() == ownerEntityId) { + owner = session.getPlayerEntity(); + } + // Java clients only spawn fishing hooks with a player as its owner + if (owner instanceof PlayerEntity) { + entity = new FishingHookEntity(packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(), + type, position, motion, rotation, (PlayerEntity) owner); + } else { + return; + } + } else if (packet.getType() == EntityType.BOAT) { + // Initial rotation is incorrect + entity = new BoatEntity(packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(), + type, position, motion, Vector3f.from(packet.getYaw(), 0, packet.getYaw())); + } else { + Constructor entityConstructor = entityClass.getConstructor(long.class, long.class, org.geysermc.connector.entity.type.EntityType.class, + Vector3f.class, Vector3f.class, Vector3f.class); + + entity = entityConstructor.newInstance(packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(), + type, position, motion, rotation + ); + } + session.getEntityCache().spawnEntity(entity); + } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException ex) { + ex.printStackTrace(); + } + } +} diff --git a/Java/JavaSpawnExpOrbTranslator.java b/Java/JavaSpawnExpOrbTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..6fd0e60947ea03cb90469cbe237f425d2e8de720 --- /dev/null +++ b/Java/JavaSpawnExpOrbTranslator.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity.spawn; + +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.ExpOrbEntity; +import org.geysermc.connector.entity.type.EntityType; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnExpOrbPacket; +import com.nukkitx.math.vector.Vector3f; + +@Translator(packet = ServerSpawnExpOrbPacket.class) +public class JavaSpawnExpOrbTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerSpawnExpOrbPacket packet) { + Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ()); + + Entity entity = new ExpOrbEntity( + packet.getExp(), packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(), + EntityType.EXPERIENCE_ORB, position, Vector3f.ZERO, Vector3f.ZERO + ); + + session.getEntityCache().spawnEntity(entity); + } +} diff --git a/Java/JavaSpawnLivingEntityTranslator.java b/Java/JavaSpawnLivingEntityTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..46d47e8085bf928a733a9699ad4648db88ee9d2a --- /dev/null +++ b/Java/JavaSpawnLivingEntityTranslator.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity.spawn; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnLivingEntityPacket; +import com.nukkitx.math.vector.Vector3f; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.entity.type.EntityType; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.EntityUtils; +import org.geysermc.connector.utils.LanguageUtils; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; + +@Translator(packet = ServerSpawnLivingEntityPacket.class) +public class JavaSpawnLivingEntityTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerSpawnLivingEntityPacket packet) { + Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ()); + Vector3f motion = Vector3f.from(packet.getMotionX(), packet.getMotionY(), packet.getMotionZ()); + Vector3f rotation = Vector3f.from(packet.getYaw(), packet.getPitch(), packet.getHeadYaw()); + + EntityType type = EntityUtils.toBedrockEntity(packet.getType()); + if (type == null) { + session.getConnector().getLogger().warning(LanguageUtils.getLocaleStringLog("geyser.entity.type_null", packet.getType())); + return; + } + + Class entityClass = type.getEntityClass(); + try { + Constructor entityConstructor = entityClass.getConstructor(long.class, long.class, EntityType.class, + Vector3f.class, Vector3f.class, Vector3f.class); + + Entity entity = entityConstructor.newInstance(packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(), + type, position, motion, rotation + ); + session.getEntityCache().spawnEntity(entity); + } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException ex) { + ex.printStackTrace(); + } + } +} diff --git a/Java/JavaSpawnPaintingTranslator.java b/Java/JavaSpawnPaintingTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..1d5ee4736e9b5220bee3376598497185e8b90609 --- /dev/null +++ b/Java/JavaSpawnPaintingTranslator.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity.spawn; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnPaintingPacket; +import com.nukkitx.math.vector.Vector3f; +import org.geysermc.connector.entity.PaintingEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.PaintingType; + +@Translator(packet = ServerSpawnPaintingPacket.class) +public class JavaSpawnPaintingTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerSpawnPaintingPacket packet) { + Vector3f position = Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()); + + PaintingEntity entity = new PaintingEntity(packet.getEntityId(), + session.getEntityCache().getNextEntityId().incrementAndGet(), + position, PaintingType.getByPaintingType(packet.getPaintingType()), packet.getDirection().ordinal()); + + session.getEntityCache().spawnEntity(entity); + } +} diff --git a/Java/JavaSpawnParticleTranslator.java b/Java/JavaSpawnParticleTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..df17ceada3af4ffaefc7c9d892122463c2733d44 --- /dev/null +++ b/Java/JavaSpawnParticleTranslator.java @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.data.game.entity.metadata.ItemStack; +import com.github.steveice10.mc.protocol.data.game.world.particle.*; +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerSpawnParticlePacket; +import com.nukkitx.math.vector.Vector3f; +import com.nukkitx.protocol.bedrock.BedrockPacket; +import com.nukkitx.protocol.bedrock.data.LevelEventType; +import com.nukkitx.protocol.bedrock.data.inventory.ItemData; +import com.nukkitx.protocol.bedrock.packet.LevelEventPacket; +import com.nukkitx.protocol.bedrock.packet.SpawnParticleEffectPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.item.ItemTranslator; +import org.geysermc.connector.registry.Registries; +import org.geysermc.connector.registry.type.ParticleMapping; +import org.geysermc.connector.utils.DimensionUtils; + +import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.Function; + +@Translator(packet = ServerSpawnParticlePacket.class) +public class JavaSpawnParticleTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerSpawnParticlePacket packet) { + Function particleCreateFunction = createParticle(session, packet.getParticle()); + if (particleCreateFunction != null) { + if (packet.getAmount() == 0) { + // 0 means don't apply the offset + Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ()); + session.sendUpstreamPacket(particleCreateFunction.apply(position)); + } else { + Random random = ThreadLocalRandom.current(); + for (int i = 0; i < packet.getAmount(); i++) { + double offsetX = random.nextGaussian() * (double) packet.getOffsetX(); + double offsetY = random.nextGaussian() * (double) packet.getOffsetY(); + double offsetZ = random.nextGaussian() * (double) packet.getOffsetZ(); + Vector3f position = Vector3f.from(packet.getX() + offsetX, packet.getY() + offsetY, packet.getZ() + offsetZ); + + session.sendUpstreamPacket(particleCreateFunction.apply(position)); + } + } + } else { + // Null is only returned when no particle of this type is found + session.getConnector().getLogger().debug("Unhandled particle packet: " + packet); + } + } + + /** + * @param session the Bedrock client session. + * @param particle the Java particle to translate to a Bedrock equivalent. + * @return a function to create a packet with a specified particle, in the event we need to spawn multiple particles + * with different offsets. + */ + private Function createParticle(GeyserSession session, Particle particle) { + switch (particle.getType()) { + case BLOCK: { + int blockState = session.getBlockMappings().getBedrockBlockId(((BlockParticleData) particle.getData()).getBlockState()); + return (position) -> { + LevelEventPacket packet = new LevelEventPacket(); + packet.setType(LevelEventType.PARTICLE_CRACK_BLOCK); + packet.setPosition(position); + packet.setData(blockState); + return packet; + }; + } + case FALLING_DUST: { + int blockState = session.getBlockMappings().getBedrockBlockId(((FallingDustParticleData) particle.getData()).getBlockState()); + return (position) -> { + LevelEventPacket packet = new LevelEventPacket(); + // In fact, FallingDustParticle should have data like DustParticle, + // but in MCProtocol, its data is BlockState(1). + packet.setType(LevelEventType.PARTICLE_FALLING_DUST); + packet.setData(blockState); + packet.setPosition(position); + return packet; + }; + } + case ITEM: { + ItemStack javaItem = ((ItemParticleData) particle.getData()).getItemStack(); + ItemData bedrockItem = ItemTranslator.translateToBedrock(session, javaItem); + int data = bedrockItem.getId() << 16 | bedrockItem.getDamage(); + return (position) -> { + LevelEventPacket packet = new LevelEventPacket(); + packet.setType(LevelEventType.PARTICLE_ITEM_BREAK); + packet.setData(data); + packet.setPosition(position); + return packet; + }; + } + case DUST: + case DUST_COLOR_TRANSITION: { //TODO + DustParticleData data = (DustParticleData) particle.getData(); + int r = (int) (data.getRed() * 255); + int g = (int) (data.getGreen() * 255); + int b = (int) (data.getBlue() * 255); + int rgbData = ((0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); + return (position) -> { + LevelEventPacket packet = new LevelEventPacket(); + packet.setType(LevelEventType.PARTICLE_FALLING_DUST); + packet.setData(rgbData); + packet.setPosition(position); + return packet; + }; + } + default: { + ParticleMapping particleMapping = Registries.PARTICLES.get(particle.getType()); + if (particleMapping == null) { //TODO ensure no particle can be null + return null; + } + + if (particleMapping.getLevelEventType() != null) { + return (position) -> { + LevelEventPacket packet = new LevelEventPacket(); + packet.setType(particleMapping.getLevelEventType()); + packet.setPosition(position); + return packet; + }; + } else if (particleMapping.getIdentifier() != null) { + int dimensionId = DimensionUtils.javaToBedrock(session.getDimension()); + return (position) -> { + SpawnParticleEffectPacket stringPacket = new SpawnParticleEffectPacket(); + stringPacket.setIdentifier(particleMapping.getIdentifier()); + stringPacket.setDimensionId(dimensionId); + stringPacket.setPosition(position); + return stringPacket; + }; + } else { + return null; + } + } + } + } +} \ No newline at end of file diff --git a/Java/JavaSpawnPlayerTranslator.java b/Java/JavaSpawnPlayerTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..6df3666b62214a36a70fe41e9e07e83364dcac76 --- /dev/null +++ b/Java/JavaSpawnPlayerTranslator.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.entity.spawn; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnPlayerPacket; +import com.nukkitx.math.vector.Vector3f; +import org.geysermc.connector.GeyserConnector; +import org.geysermc.connector.entity.player.PlayerEntity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.LanguageUtils; +import org.geysermc.connector.skin.SkinManager; + +@Translator(packet = ServerSpawnPlayerPacket.class) +public class JavaSpawnPlayerTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerSpawnPlayerPacket packet) { + Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ()); + Vector3f rotation = Vector3f.from(packet.getYaw(), packet.getPitch(), packet.getYaw()); + + PlayerEntity entity; + if (packet.getUuid().equals(session.getPlayerEntity().getUuid())) { + // Server is sending a fake version of the current player + entity = new PlayerEntity(session.getPlayerEntity().getProfile(), packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(), position, Vector3f.ZERO, rotation); + } else { + entity = session.getEntityCache().getPlayerEntity(packet.getUuid()); + if (entity == null) { + GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.entity.player.failed_list", packet.getUuid())); + return; + } + + entity.setEntityId(packet.getEntityId()); + entity.setPosition(position); + entity.setRotation(rotation); + } + session.getEntityCache().cacheEntity(entity); + + entity.sendPlayer(session); + SkinManager.requestAndHandleSkinAndCape(entity, session, null); + } +} diff --git a/Java/JavaSpawnPositionTranslator.java b/Java/JavaSpawnPositionTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..16e50744082567aa455504bcc046d32f729e17c3 --- /dev/null +++ b/Java/JavaSpawnPositionTranslator.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerSpawnPositionPacket; +import com.nukkitx.math.vector.Vector3i; +import com.nukkitx.protocol.bedrock.packet.SetSpawnPositionPacket; +import org.geysermc.connector.utils.DimensionUtils; + +@Translator(packet = ServerSpawnPositionPacket.class) +public class JavaSpawnPositionTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerSpawnPositionPacket packet) { + SetSpawnPositionPacket spawnPositionPacket = new SetSpawnPositionPacket(); + spawnPositionPacket.setBlockPosition(Vector3i.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ())); + spawnPositionPacket.setSpawnForced(true); + spawnPositionPacket.setDimensionId(DimensionUtils.javaToBedrock(session.getDimension())); + spawnPositionPacket.setSpawnType(SetSpawnPositionPacket.Type.WORLD_SPAWN); + session.sendUpstreamPacket(spawnPositionPacket); + } +} diff --git a/Java/JavaStatisticsTranslator.java b/Java/JavaStatisticsTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..15c6452edebbe51751a7137e27d56f864570af8c --- /dev/null +++ b/Java/JavaStatisticsTranslator.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerStatisticsPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.StatisticsUtils; + +@Translator(packet = ServerStatisticsPacket.class) +public class JavaStatisticsTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerStatisticsPacket packet) { + session.updateStatistics(packet.getStatistics()); + + if (session.isWaitingForStatistics()) { + session.setWaitingForStatistics(false); + StatisticsUtils.buildAndSendStatisticsMenu(session); + } + } +} diff --git a/Java/JavaStopSoundTranslator.java b/Java/JavaStopSoundTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..93241310f7d06984089760b4844a61b471746a34 --- /dev/null +++ b/Java/JavaStopSoundTranslator.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.data.game.world.sound.BuiltinSound; +import com.github.steveice10.mc.protocol.data.game.world.sound.CustomSound; +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerStopSoundPacket; +import com.nukkitx.protocol.bedrock.packet.StopSoundPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.registry.Registries; +import org.geysermc.connector.registry.type.SoundMapping; + +@Translator(packet = ServerStopSoundPacket.class) +public class JavaStopSoundTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerStopSoundPacket packet) { + // Runs if all sounds are stopped + if (packet.getSound() == null) { + StopSoundPacket stopPacket = new StopSoundPacket(); + stopPacket.setStoppingAllSound(true); + stopPacket.setSoundName(""); + session.sendUpstreamPacket(stopPacket); + return; + } + + String packetSound; + if (packet.getSound() instanceof BuiltinSound) { + packetSound = ((BuiltinSound) packet.getSound()).getName(); + } else if (packet.getSound() instanceof CustomSound) { + packetSound = ((CustomSound) packet.getSound()).getName(); + } else { + session.getConnector().getLogger().debug("Unknown sound packet, we were unable to map this. " + packet.toString()); + return; + } + SoundMapping soundMapping = Registries.SOUNDS.get(packetSound.replace("minecraft:", "")); + session.getConnector().getLogger() + .debug("[StopSound] Sound mapping " + packetSound + " -> " + + soundMapping + (soundMapping == null ? "[not found]" : "") + + " - " + packet.toString()); + String playsound; + if (soundMapping == null || soundMapping.getPlaysound() == null) { + // no mapping + session.getConnector().getLogger() + .debug("[StopSound] Defaulting to sound server gave us."); + playsound = packetSound; + } else { + playsound = soundMapping.getPlaysound(); + } + + StopSoundPacket stopSoundPacket = new StopSoundPacket(); + stopSoundPacket.setSoundName(playsound); + // packet not mapped in the library + stopSoundPacket.setStoppingAllSound(false); + + session.sendUpstreamPacket(stopSoundPacket); + session.getConnector().getLogger().debug("[StopSound] Packet sent - " + packet.toString() + " --> " + stopSoundPacket); + } +} diff --git a/Java/JavaTeamTranslator.java b/Java/JavaTeamTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..6ec4813d4b45a639a9c527c8fa394796558e7fc0 --- /dev/null +++ b/Java/JavaTeamTranslator.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.scoreboard; + +import com.github.steveice10.mc.protocol.packet.ingame.server.scoreboard.ServerTeamPacket; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import org.geysermc.connector.GeyserConnector; +import org.geysermc.connector.GeyserLogger; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.scoreboard.Scoreboard; +import org.geysermc.connector.scoreboard.ScoreboardUpdater; +import org.geysermc.connector.scoreboard.Team; +import org.geysermc.connector.scoreboard.UpdateType; +import org.geysermc.connector.utils.LanguageUtils; +import org.geysermc.connector.network.translators.chat.MessageTranslator; + +import java.util.Arrays; +import java.util.Set; + +@Translator(packet = ServerTeamPacket.class) +public class JavaTeamTranslator extends PacketTranslator { + private static final GeyserLogger LOGGER = GeyserConnector.getInstance().getLogger(); + + @Override + public void translate(GeyserSession session, ServerTeamPacket packet) { + if (LOGGER.isDebug()) { + LOGGER.debug("Team packet " + packet.getTeamName() + " " + packet.getAction() + " " + Arrays.toString(packet.getPlayers())); + } + + int pps = session.getWorldCache().increaseAndGetScoreboardPacketsPerSecond(); + + Scoreboard scoreboard = session.getWorldCache().getScoreboard(); + Team team = scoreboard.getTeam(packet.getTeamName()); + switch (packet.getAction()) { + case CREATE: + scoreboard.registerNewTeam(packet.getTeamName(), toPlayerSet(packet.getPlayers())) + .setName(MessageTranslator.convertMessage(packet.getDisplayName())) + .setColor(packet.getColor()) + .setNameTagVisibility(packet.getNameTagVisibility()) + .setPrefix(MessageTranslator.convertMessage(packet.getPrefix(), session.getLocale())) + .setSuffix(MessageTranslator.convertMessage(packet.getSuffix(), session.getLocale())); + break; + case UPDATE: + if (team == null) { + LOGGER.debug(LanguageUtils.getLocaleStringLog( + "geyser.network.translator.team.failed_not_registered", + packet.getAction(), packet.getTeamName() + )); + return; + } + + team.setName(MessageTranslator.convertMessage(packet.getDisplayName())) + .setColor(packet.getColor()) + .setNameTagVisibility(packet.getNameTagVisibility()) + .setPrefix(MessageTranslator.convertMessage(packet.getPrefix(), session.getLocale())) + .setSuffix(MessageTranslator.convertMessage(packet.getSuffix(), session.getLocale())) + .setUpdateType(UpdateType.UPDATE); + break; + case ADD_PLAYER: + if (team == null) { + LOGGER.debug(LanguageUtils.getLocaleStringLog( + "geyser.network.translator.team.failed_not_registered", + packet.getAction(), packet.getTeamName() + )); + return; + } + team.addEntities(packet.getPlayers()); + break; + case REMOVE_PLAYER: + if (team == null) { + LOGGER.debug(LanguageUtils.getLocaleStringLog( + "geyser.network.translator.team.failed_not_registered", + packet.getAction(), packet.getTeamName() + )); + return; + } + team.removeEntities(packet.getPlayers()); + break; + case REMOVE: + scoreboard.removeTeam(packet.getTeamName()); + break; + } + + // ScoreboardUpdater will handle it for us if the packets per second + // (for score and team packets) is higher then the first threshold + if (pps < ScoreboardUpdater.FIRST_SCORE_PACKETS_PER_SECOND_THRESHOLD) { + scoreboard.onUpdate(); + } + } + + private Set toPlayerSet(String[] players) { + return new ObjectOpenHashSet<>(players); + } +} diff --git a/Java/JavaTradeListTranslator.java b/Java/JavaTradeListTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..8b05d046930664ac69103c73fac9fa1023893530 --- /dev/null +++ b/Java/JavaTradeListTranslator.java @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.data.game.entity.metadata.ItemStack; +import com.github.steveice10.mc.protocol.data.game.window.VillagerTrade; +import com.github.steveice10.mc.protocol.packet.ingame.server.window.ServerTradeListPacket; +import com.nukkitx.nbt.NbtMap; +import com.nukkitx.nbt.NbtMapBuilder; +import com.nukkitx.nbt.NbtType; +import com.nukkitx.protocol.bedrock.data.entity.EntityData; +import com.nukkitx.protocol.bedrock.data.inventory.ContainerType; +import com.nukkitx.protocol.bedrock.data.inventory.ItemData; +import com.nukkitx.protocol.bedrock.packet.UpdateTradePacket; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.inventory.Inventory; +import org.geysermc.connector.inventory.MerchantContainer; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.item.ItemTranslator; +import org.geysermc.connector.registry.type.ItemMapping; + +import java.util.ArrayList; +import java.util.List; + +@Translator(packet = ServerTradeListPacket.class) +public class JavaTradeListTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerTradeListPacket packet) { + Inventory openInventory = session.getOpenInventory(); + if (!(openInventory instanceof MerchantContainer && openInventory.getId() == packet.getWindowId())) { + return; + } + + // Retrieve the fake villager involved in the trade, and update its metadata to match with the window information + MerchantContainer merchantInventory = (MerchantContainer) openInventory; + merchantInventory.setVillagerTrades(packet.getTrades()); + Entity villager = merchantInventory.getVillager(); + villager.getMetadata().put(EntityData.TRADE_TIER, packet.getVillagerLevel() - 1); + villager.getMetadata().put(EntityData.MAX_TRADE_TIER, 4); + villager.getMetadata().put(EntityData.TRADE_XP, packet.getExperience()); + villager.updateBedrockMetadata(session); + + // Construct the packet that opens the trading window + UpdateTradePacket updateTradePacket = new UpdateTradePacket(); + updateTradePacket.setTradeTier(packet.getVillagerLevel() - 1); + updateTradePacket.setContainerId((short) packet.getWindowId()); + updateTradePacket.setContainerType(ContainerType.TRADE); + updateTradePacket.setDisplayName(openInventory.getTitle()); + updateTradePacket.setSize(0); + updateTradePacket.setNewTradingUi(true); + updateTradePacket.setUsingEconomyTrade(true); + updateTradePacket.setPlayerUniqueEntityId(session.getPlayerEntity().getGeyserId()); + updateTradePacket.setTraderUniqueEntityId(villager.getGeyserId()); + + NbtMapBuilder builder = NbtMap.builder(); + boolean addExtraTrade = packet.isRegularVillager() && packet.getVillagerLevel() < 5; + List tags = new ArrayList<>(addExtraTrade ? packet.getTrades().length + 1 : packet.getTrades().length); + for (int i = 0; i < packet.getTrades().length; i++) { + VillagerTrade trade = packet.getTrades()[i]; + NbtMapBuilder recipe = NbtMap.builder(); + recipe.putInt("netId", i + 1); + recipe.putInt("maxUses", trade.isTradeDisabled() ? 0 : trade.getMaxUses()); + recipe.putInt("traderExp", trade.getXp()); + recipe.putFloat("priceMultiplierA", trade.getPriceMultiplier()); + recipe.put("sell", getItemTag(session, trade.getOutput(), 0)); + recipe.putFloat("priceMultiplierB", 0.0f); + recipe.putInt("buyCountB", trade.getSecondInput() != null ? trade.getSecondInput().getAmount() : 0); + recipe.putInt("buyCountA", trade.getFirstInput().getAmount()); + recipe.putInt("demand", trade.getDemand()); + recipe.putInt("tier", packet.getVillagerLevel() > 0 ? packet.getVillagerLevel() - 1 : 0); // -1 crashes client + recipe.put("buyA", getItemTag(session, trade.getFirstInput(), trade.getSpecialPrice())); + if (trade.getSecondInput() != null) { + recipe.put("buyB", getItemTag(session, trade.getSecondInput(), 0)); + } + recipe.putInt("uses", trade.getNumUses()); + recipe.putByte("rewardExp", (byte) 1); + tags.add(recipe.build()); + } + + //Hidden trade to fix visual experience bug + if (addExtraTrade) { + tags.add(NbtMap.builder() + .putInt("maxUses", 0) + .putInt("traderExp", 0) + .putFloat("priceMultiplierA", 0.0f) + .putFloat("priceMultiplierB", 0.0f) + .putInt("buyCountB", 0) + .putInt("buyCountA", 0) + .putInt("demand", 0) + .putInt("tier", 5) + .putInt("uses", 0) + .putByte("rewardExp", (byte) 0) + .build()); + } + + builder.putList("Recipes", NbtType.COMPOUND, tags); + + List expTags = new ArrayList<>(5); + expTags.add(NbtMap.builder().putInt("0", 0).build()); + expTags.add(NbtMap.builder().putInt("1", 10).build()); + expTags.add(NbtMap.builder().putInt("2", 70).build()); + expTags.add(NbtMap.builder().putInt("3", 150).build()); + expTags.add(NbtMap.builder().putInt("4", 250).build()); + builder.putList("TierExpRequirements", NbtType.COMPOUND, expTags); + + updateTradePacket.setOffers(builder.build()); + session.sendUpstreamPacket(updateTradePacket); + } + + private NbtMap getItemTag(GeyserSession session, ItemStack stack, int specialPrice) { + ItemData itemData = ItemTranslator.translateToBedrock(session, stack); + ItemMapping mapping = session.getItemMappings().getMapping(stack); + + NbtMapBuilder builder = NbtMap.builder(); + builder.putByte("Count", (byte) (Math.max(itemData.getCount() + specialPrice, 1))); + builder.putShort("Damage", (short) itemData.getDamage()); + builder.putString("Name", mapping.getBedrockIdentifier()); + if (itemData.getTag() != null) { + NbtMap tag = itemData.getTag().toBuilder().build(); + builder.put("tag", tag); + } + + NbtMap blockTag = session.getBlockMappings().getBedrockBlockNbt(mapping.getJavaIdentifier()); + if (blockTag != null) { + // This fixes certain blocks being unable to stack after grabbing one + builder.putCompound("Block", blockTag); + builder.putShort("Damage", (short) 0); + } + + return builder.build(); + } +} diff --git a/Java/JavaUnloadChunkTranslator.java b/Java/JavaUnloadChunkTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..3d428327aedbfae1ba8ef896fc6f3be38121b079 --- /dev/null +++ b/Java/JavaUnloadChunkTranslator.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerUnloadChunkPacket; +import com.nukkitx.math.vector.Vector3i; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import java.util.Iterator; + +@Translator(packet = ServerUnloadChunkPacket.class) +public class JavaUnloadChunkTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerUnloadChunkPacket packet) { + session.getChunkCache().removeChunk(packet.getX(), packet.getZ()); + + //Checks if a skull is in an unloaded chunk then removes it + Iterator iterator = session.getSkullCache().keySet().iterator(); + while (iterator.hasNext()) { + Vector3i position = iterator.next(); + if ((position.getX() >> 4) == packet.getX() && (position.getZ() >> 4) == packet.getZ()) { + session.getSkullCache().get(position).despawnEntity(session); + iterator.remove(); + } + } + + // Do the same thing with lecterns + iterator = session.getLecternCache().iterator(); + while (iterator.hasNext()) { + Vector3i position = iterator.next(); + if ((position.getX() >> 4) == packet.getX() && (position.getZ() >> 4) == packet.getZ()) { + iterator.remove(); + } + } + } +} diff --git a/Java/JavaUnlockRecipesTranslator.java b/Java/JavaUnlockRecipesTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..d7c4053e68fa31f42789f4dd6493f00620822adb --- /dev/null +++ b/Java/JavaUnlockRecipesTranslator.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java; + +import com.github.steveice10.mc.protocol.data.game.UnlockRecipesAction; +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerUnlockRecipesPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import java.util.Arrays; + +/** + * Used to list recipes that we can definitely use the recipe book for (and therefore save on packet usage) + */ +@Translator(packet = ServerUnlockRecipesPacket.class) +public class JavaUnlockRecipesTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerUnlockRecipesPacket packet) { + if (packet.getAction() == UnlockRecipesAction.REMOVE) { + session.getUnlockedRecipes().removeAll(Arrays.asList(packet.getRecipes())); + } else { + session.getUnlockedRecipes().addAll(Arrays.asList(packet.getRecipes())); + } + } +} + diff --git a/Java/JavaUpdateScoreTranslator.java b/Java/JavaUpdateScoreTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..daf4d383248b5a6888b84ba6b38f4510fb1a89c4 --- /dev/null +++ b/Java/JavaUpdateScoreTranslator.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.scoreboard; + +import com.github.steveice10.mc.protocol.data.game.scoreboard.ScoreboardAction; +import com.github.steveice10.mc.protocol.packet.ingame.server.scoreboard.ServerUpdateScorePacket; +import org.geysermc.connector.GeyserConnector; +import org.geysermc.connector.GeyserLogger; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.session.cache.WorldCache; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.scoreboard.Objective; +import org.geysermc.connector.scoreboard.Scoreboard; +import org.geysermc.connector.scoreboard.ScoreboardUpdater; +import org.geysermc.connector.utils.LanguageUtils; + +@Translator(packet = ServerUpdateScorePacket.class) +public class JavaUpdateScoreTranslator extends PacketTranslator { + private final GeyserLogger logger; + + public JavaUpdateScoreTranslator() { + logger = GeyserConnector.getInstance().getLogger(); + } + + @Override + public void translate(GeyserSession session, ServerUpdateScorePacket packet) { + WorldCache worldCache = session.getWorldCache(); + Scoreboard scoreboard = worldCache.getScoreboard(); + int pps = worldCache.increaseAndGetScoreboardPacketsPerSecond(); + + Objective objective = scoreboard.getObjective(packet.getObjective()); + if (objective == null && packet.getAction() != ScoreboardAction.REMOVE) { + logger.info(LanguageUtils.getLocaleStringLog("geyser.network.translator.score.failed_objective", packet.getObjective())); + return; + } + + switch (packet.getAction()) { + case ADD_OR_UPDATE: + objective.setScore(packet.getEntry(), packet.getValue()); + break; + case REMOVE: + if (objective != null) { + objective.removeScore(packet.getEntry()); + } else { + for (Objective objective1 : scoreboard.getObjectives().values()) { + objective1.removeScore(packet.getEntry()); + } + } + break; + } + + // ScoreboardUpdater will handle it for us if the packets per second + // (for score and team packets) is higher then the first threshold + if (pps < ScoreboardUpdater.FIRST_SCORE_PACKETS_PER_SECOND_THRESHOLD) { + scoreboard.onUpdate(); + } + } +} diff --git a/Java/JavaUpdateTileEntityTranslator.java b/Java/JavaUpdateTileEntityTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..25c4684b1ebf4ab7622d39bfeb493242c7964284 --- /dev/null +++ b/Java/JavaUpdateTileEntityTranslator.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.data.game.entity.player.GameMode; +import com.github.steveice10.mc.protocol.data.game.world.block.UpdatedTileType; +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerUpdateTileEntityPacket; +import com.nukkitx.math.vector.Vector3i; +import com.nukkitx.nbt.NbtMap; +import com.nukkitx.protocol.bedrock.data.inventory.ContainerType; +import com.nukkitx.protocol.bedrock.packet.ContainerOpenPacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.world.block.BlockStateValues; +import org.geysermc.connector.network.translators.world.block.entity.BlockEntityTranslator; +import org.geysermc.connector.network.translators.world.block.entity.RequiresBlockState; +import org.geysermc.connector.network.translators.world.block.entity.SkullBlockEntityTranslator; +import org.geysermc.connector.utils.BlockEntityUtils; + +@Translator(packet = ServerUpdateTileEntityPacket.class) +public class JavaUpdateTileEntityTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerUpdateTileEntityPacket packet) { + String id = BlockEntityUtils.getBedrockBlockEntityId(packet.getType().name()); + if (packet.getNbt().isEmpty()) { // Fixes errors in servers sending empty NBT + BlockEntityUtils.updateBlockEntity(session, NbtMap.EMPTY, packet.getPosition()); + return; + } + + BlockEntityTranslator translator = BlockEntityUtils.getBlockEntityTranslator(id); + // The Java block state is used in BlockEntityTranslator.translateTag() to make up for some inconsistencies + // between Java block states and Bedrock block entity data + int blockState; + if (translator instanceof RequiresBlockState) { + blockState = session.getConnector().getWorldManager().getBlockAt(session, packet.getPosition()); + } else { + blockState = BlockStateValues.JAVA_AIR_ID; + } + BlockEntityUtils.updateBlockEntity(session, translator.getBlockEntityTag(id, packet.getNbt(), blockState), packet.getPosition()); + // Check for custom skulls. + if (SkullBlockEntityTranslator.ALLOW_CUSTOM_SKULLS && packet.getNbt().contains("SkullOwner")) { + SkullBlockEntityTranslator.spawnPlayer(session, packet.getNbt(), blockState); + } + + // If block entity is command block, OP permission level is appropriate, player is in creative mode and the NBT is not empty + if (packet.getType() == UpdatedTileType.COMMAND_BLOCK && session.getOpPermissionLevel() >= 2 && + session.getGameMode() == GameMode.CREATIVE && packet.getNbt().size() > 5) { + ContainerOpenPacket openPacket = new ContainerOpenPacket(); + openPacket.setBlockPosition(Vector3i.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ())); + openPacket.setId((byte) 1); + openPacket.setType(ContainerType.COMMAND_BLOCK); + openPacket.setUniqueEntityId(-1); + session.sendUpstreamPacket(openPacket); + } + } +} diff --git a/Java/JavaUpdateTimeTranslator.java b/Java/JavaUpdateTimeTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..3564177e1a5e5dadaa96b4a99e501291b61d4869 --- /dev/null +++ b/Java/JavaUpdateTimeTranslator.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerUpdateTimePacket; +import com.nukkitx.protocol.bedrock.packet.SetTimePacket; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = ServerUpdateTimePacket.class) +public class JavaUpdateTimeTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerUpdateTimePacket packet) { + // Bedrock sends a GameRulesChangedPacket if there is no daylight cycle + // Java just sends a negative long if there is no daylight cycle + long time = packet.getTime(); + + // https://minecraft.gamepedia.com/Day-night_cycle#24-hour_Minecraft_day + SetTimePacket setTimePacket = new SetTimePacket(); + setTimePacket.setTime((int) Math.abs(time) % 24000); + session.sendUpstreamPacket(setTimePacket); + if (!session.isDaylightCycle() && time >= 0) { + // Client thinks there is no daylight cycle but there is + session.setDaylightCycle(true); + } else if (session.isDaylightCycle() && time < 0) { + // Client thinks there is daylight cycle but there isn't + session.setDaylightCycle(false); + } + } +} diff --git a/Java/JavaUpdateViewDistanceTranslator.java b/Java/JavaUpdateViewDistanceTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..155af39b6cec3b1262b15fa374cd5a5152cd41d6 --- /dev/null +++ b/Java/JavaUpdateViewDistanceTranslator.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerUpdateViewDistancePacket; + +@Translator(packet = ServerUpdateViewDistancePacket.class) +public class JavaUpdateViewDistanceTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerUpdateViewDistancePacket packet) { + session.setRenderDistance(packet.getViewDistance()); + } +} diff --git a/Java/JavaUpdateViewPositionTranslator.java b/Java/JavaUpdateViewPositionTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..a4ce170bfe0a739a3983cb04b63bf450e56c4733 --- /dev/null +++ b/Java/JavaUpdateViewPositionTranslator.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.utils.ChunkUtils; + +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerUpdateViewPositionPacket; +import com.nukkitx.math.vector.Vector3i; + +@Translator(packet = ServerUpdateViewPositionPacket.class) +public class JavaUpdateViewPositionTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerUpdateViewPositionPacket packet) { + if (!session.isSpawned() && session.getLastChunkPosition() == null) { + ChunkUtils.updateChunkPosition(session, Vector3i.from(packet.getChunkX() << 4, 64, packet.getChunkZ() << 4)); + } + } +} diff --git a/Java/JavaVehicleMoveTranslator.java b/Java/JavaVehicleMoveTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..2f984517ce5435a608ede2a3573dd686f10d3571 --- /dev/null +++ b/Java/JavaVehicleMoveTranslator.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.world; + +import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerVehicleMovePacket; +import com.nukkitx.math.vector.Vector3f; +import org.geysermc.connector.entity.Entity; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; + +@Translator(packet = ServerVehicleMovePacket.class) +public class JavaVehicleMoveTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerVehicleMovePacket packet) { + Entity entity = session.getRidingVehicleEntity(); + if (entity == null) return; + + entity.moveAbsolute(session, Vector3f.from(packet.getX(), packet.getY(), packet.getZ()), packet.getYaw(), packet.getPitch(), false, true); + } +} diff --git a/Java/JavaWindowItemsTranslator.java b/Java/JavaWindowItemsTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..542001dfb19bc6dd3d263b2b256111bbb1a0f549 --- /dev/null +++ b/Java/JavaWindowItemsTranslator.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.window; + +import com.github.steveice10.mc.protocol.packet.ingame.server.window.ServerWindowItemsPacket; +import org.geysermc.connector.inventory.GeyserItemStack; +import org.geysermc.connector.inventory.Inventory; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.inventory.InventoryTranslator; +import org.geysermc.connector.utils.InventoryUtils; + +@Translator(packet = ServerWindowItemsPacket.class) +public class JavaWindowItemsTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerWindowItemsPacket packet) { + Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId()); + if (inventory == null) + return; + + inventory.setStateId(packet.getStateId()); + + for (int i = 0; i < packet.getItems().length; i++) { + GeyserItemStack newItem = GeyserItemStack.from(packet.getItems()[i]); + inventory.setItem(i, newItem, session); + } + + InventoryTranslator translator = session.getInventoryTranslator(); + if (translator != null) { + translator.updateInventory(session, inventory); + } + + session.getPlayerInventory().setCursor(GeyserItemStack.from(packet.getCarriedItem()), session); + InventoryUtils.updateCursor(session); + } +} diff --git a/Java/JavaWindowPropertyTranslator.java b/Java/JavaWindowPropertyTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..512c797d2f5b033315ff290841b7553c8a9b88a4 --- /dev/null +++ b/Java/JavaWindowPropertyTranslator.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators.java.window; + +import com.github.steveice10.mc.protocol.packet.ingame.server.window.ServerWindowPropertyPacket; +import org.geysermc.connector.inventory.Inventory; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.network.translators.PacketTranslator; +import org.geysermc.connector.network.translators.Translator; +import org.geysermc.connector.network.translators.inventory.InventoryTranslator; +import org.geysermc.connector.utils.InventoryUtils; + +@Translator(packet = ServerWindowPropertyPacket.class) +public class JavaWindowPropertyTranslator extends PacketTranslator { + + @Override + public void translate(GeyserSession session, ServerWindowPropertyPacket packet) { + Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId()); + if (inventory == null) + return; + + InventoryTranslator translator = session.getInventoryTranslator(); + if (translator != null) { + translator.updateProperty(session, inventory, packet.getRawProperty(), packet.getValue()); + } + } +} diff --git a/Java/Jdbc2TestSuite.java b/Java/Jdbc2TestSuite.java new file mode 100644 index 0000000000000000000000000000000000000000..6b7d2ae2b7ad30b2ab3f2bf88426f44705a6be79 --- /dev/null +++ b/Java/Jdbc2TestSuite.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2004, PostgreSQL Global Development Group + * See the LICENSE file in the project root for more information. + */ + +package org.postgresql.test.jdbc2; + +import org.postgresql.core.AsciiStringInternerTest; +import org.postgresql.core.CommandCompleteParserNegativeTest; +import org.postgresql.core.CommandCompleteParserTest; +import org.postgresql.core.OidToStringTest; +import org.postgresql.core.OidValueOfTest; +import org.postgresql.core.ParserTest; +import org.postgresql.core.ReturningParserTest; +import org.postgresql.core.UTF8EncodingTest; +import org.postgresql.core.v3.V3ParameterListTests; +import org.postgresql.core.v3.adaptivefetch.AdaptiveFetchCacheTest; +import org.postgresql.jdbc.ArraysTest; +import org.postgresql.jdbc.ArraysTestSuite; +import org.postgresql.jdbc.BitFieldTest; +import org.postgresql.jdbc.DeepBatchedInsertStatementTest; +import org.postgresql.jdbc.NoColumnMetadataIssue1613Test; +import org.postgresql.jdbc.PgSQLXMLTest; +import org.postgresql.test.core.FixedLengthOutputStreamTest; +import org.postgresql.test.core.JavaVersionTest; +import org.postgresql.test.core.LogServerMessagePropertyTest; +import org.postgresql.test.core.NativeQueryBindLengthTest; +import org.postgresql.test.core.OptionsPropertyTest; +import org.postgresql.test.util.ByteBufferByteStreamWriterTest; +import org.postgresql.test.util.ByteStreamWriterTest; +import org.postgresql.test.util.ExpressionPropertiesTest; +import org.postgresql.test.util.HostSpecTest; +import org.postgresql.test.util.LruCacheTest; +import org.postgresql.test.util.PGPropertyMaxResultBufferParserTest; +import org.postgresql.test.util.ServerVersionParseTest; +import org.postgresql.test.util.ServerVersionTest; +import org.postgresql.util.BigDecimalByteConverterTest; +import org.postgresql.util.PGbyteaTest; +import org.postgresql.util.ReaderInputStreamTest; +import org.postgresql.util.UnusualBigDecimalByteConverterTest; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +/* + * Executes all known tests for JDBC2 and includes some utility methods. + */ +@RunWith(Suite.class) +@Suite.SuiteClasses({ + AdaptiveFetchCacheTest.class, + ArrayTest.class, + ArraysTest.class, + ArraysTestSuite.class, + AsciiStringInternerTest.class, + BatchedInsertReWriteEnabledTest.class, + BatchExecuteTest.class, + BatchFailureTest.class, + BigDecimalByteConverterTest.class, + BitFieldTest.class, + BlobTest.class, + BlobTransactionTest.class, + ByteBufferByteStreamWriterTest.class, + ByteStreamWriterTest.class, + CallableStmtTest.class, + ClientEncodingTest.class, + ColumnSanitiserDisabledTest.class, + ColumnSanitiserEnabledTest.class, + CommandCompleteParserNegativeTest.class, + CommandCompleteParserTest.class, + ConcurrentStatementFetch.class, + ConnectionTest.class, + ConnectTimeoutTest.class, + CopyLargeFileTest.class, + CopyTest.class, + CursorFetchTest.class, + DatabaseEncodingTest.class, + DatabaseMetaDataCacheTest.class, + DatabaseMetaDataPropertiesTest.class, + DatabaseMetaDataTest.class, + DateStyleTest.class, + DateTest.class, + DeepBatchedInsertStatementTest.class, + DriverTest.class, + EncodingTest.class, + ExpressionPropertiesTest.class, + FixedLengthOutputStreamTest.class, + GeometricTest.class, + GetXXXTest.class, + HostSpecTest.class, + IntervalTest.class, + JavaVersionTest.class, + JBuilderTest.class, + LoginTimeoutTest.class, + LogServerMessagePropertyTest.class, + LruCacheTest.class, + MiscTest.class, + NativeQueryBindLengthTest.class, + NoColumnMetadataIssue1613Test.class, + NumericTransferTest.class, + NumericTransferTest2.class, + NotifyTest.class, + OidToStringTest.class, + OidValueOfTest.class, + OptionsPropertyTest.class, + OuterJoinSyntaxTest.class, + ParameterStatusTest.class, + ParserTest.class, + PGbyteaTest.class, + PGPropertyMaxResultBufferParserTest.class, + PGPropertyTest.class, + PGTimestampTest.class, + PGTimeTest.class, + PgSQLXMLTest.class, + PreparedStatementTest.class, + QuotationTest.class, + ReaderInputStreamTest.class, + RefCursorTest.class, + ReplaceProcessingTest.class, + ResultSetMetaDataTest.class, + ResultSetTest.class, + // BUG: CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') + // + // FIXED: + ResultSetRefreshTest.class, + ReturningParserTest.class, + SearchPathLookupTest.class, + ServerCursorTest.class, + ServerErrorTest.class, + ServerPreparedStmtTest.class, + ServerVersionParseTest.class, + ServerVersionTest.class, + StatementTest.class, + StringTypeUnspecifiedArrayTest.class, + TestACL.class, + TimestampTest.class, + TimeTest.class, + TimezoneCachingTest.class, + TimezoneTest.class, + TypeCacheDLLStressTest.class, + UnusualBigDecimalByteConverterTest.class, + UpdateableResultTest.class, + UpsertTest.class, + UTF8EncodingTest.class, + V3ParameterListTests.class +}) +public class Jdbc2TestSuite { +} diff --git a/Java/JsonParserBase.java b/Java/JsonParserBase.java new file mode 100644 index 0000000000000000000000000000000000000000..cea8e387745ace03b275a35dab30064da97c81a3 --- /dev/null +++ b/Java/JsonParserBase.java @@ -0,0 +1,163 @@ +// Copyright (c) 2003-present, Jodd Team (http://jodd.org) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +package jodd.json; + +import jodd.introspector.ClassDescriptor; +import jodd.introspector.ClassIntrospector; +import jodd.introspector.CtorDescriptor; +import jodd.introspector.PropertyDescriptor; +import jodd.introspector.Setter; +import jodd.typeconverter.TypeConverterManager; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; + +/** + * Just a base class of {@link jodd.json.JsonParser} that contains + * various utilities, to reduce the size of a parser. + */ +public abstract class JsonParserBase { + + protected static final Supplier HASMAP_SUPPLIER = LinkedHashMap::new; + protected static final Supplier LAZYMAP_SUPPLIER = LazyMap::new; + + protected static final Supplier ARRAYLIST_SUPPLIER = ArrayList::new; + protected static final Supplier LAZYLIST_SUPPLIER = LazyList::new; + + protected Supplier mapSupplier = HASMAP_SUPPLIER; + protected Supplier listSupplier = ARRAYLIST_SUPPLIER; + // BUG: CWE-502 Deserialization of Untrusted Data + // + // FIXED: + protected List classnameWhitelist; + + /** + * Creates new instance of {@link jodd.json.MapToBean}. + */ + protected MapToBean createMapToBean(final String classMetadataName) { + return new MapToBean(this, classMetadataName); + } + + // ---------------------------------------------------------------- object tools + + /** + * Creates new type for JSON array objects. + * It returns a collection. + * Later, the collection will be converted into the target type. + */ + @SuppressWarnings("unchecked") + protected Collection newArrayInstance(final Class targetType) { + if (targetType == null || + targetType == List.class || + targetType == Collection.class || + targetType.isArray()) { + + return listSupplier.get(); + } + + if (targetType == Set.class) { + return new HashSet<>(); + } + + try { + return (Collection) targetType.getDeclaredConstructor().newInstance(); + } catch (Exception e) { + throw new JsonException(e); + } + } + + /** + * Creates new object or a HashMap if type is not specified. + */ + protected Object newObjectInstance(final Class targetType) { + if (targetType == null || + targetType == Map.class) { + + return mapSupplier.get(); + } + + ClassDescriptor cd = ClassIntrospector.get().lookup(targetType); + + CtorDescriptor ctorDescriptor = cd.getDefaultCtorDescriptor(true); + if (ctorDescriptor == null) { + throw new JsonException("Default ctor not found for: " + targetType.getName()); + } + + try { +// return ClassUtil.newInstance(targetType); + return ctorDescriptor.getConstructor().newInstance(); + } catch (Exception e) { + throw new JsonException(e); + } + } + + /** + * Injects value into the targets property. + */ + protected void injectValueIntoObject(final Object target, final PropertyDescriptor pd, final Object value) { + Object convertedValue = value; + + if (value != null) { + Class targetClass = pd.getType(); + + convertedValue = convertType(value, targetClass); + } + + try { + Setter setter = pd.getSetter(true); + if (setter != null) { + setter.invokeSetter(target, convertedValue); + } + } catch (Exception ex) { + throw new JsonException(ex); + } + } + + /** + * Converts type of the given value. + */ + protected Object convertType(final Object value, final Class targetType) { + Class valueClass = value.getClass(); + + if (valueClass == targetType) { + return value; + } + + try { + return TypeConverterManager.get().convertType(value, targetType); + } + catch (Exception ex) { + throw new JsonException("Type conversion failed", ex); + } + } + +} \ No newline at end of file diff --git a/Java/LandingPagesModule.java b/Java/LandingPagesModule.java new file mode 100644 index 0000000000000000000000000000000000000000..41d4d506fcb198d0f1550367498b2b71e56c29d4 --- /dev/null +++ b/Java/LandingPagesModule.java @@ -0,0 +1,91 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.admin.landingpages; + +import java.util.ArrayList; + +import org.olat.admin.landingpages.model.Rule; +import org.olat.admin.landingpages.model.Rules; +import org.olat.core.configuration.AbstractSpringModule; +import org.olat.core.util.StringHelper; +import org.olat.core.util.coordinate.CoordinatorManager; +import org.olat.core.util.xml.XStreamHelper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.thoughtworks.xstream.XStream; + +/** + * + * Initial date: 15.05.2014
+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com + * + */ +@Service("landingPagesModule") +public class LandingPagesModule extends AbstractSpringModule { + private static final String CONFIG_RULES = "rules"; + private static final XStream rulesXStream; + static { + rulesXStream = XStreamHelper.createXStreamInstance(); + // BUG: CWE-91 XML Injection (aka Blind XPath Injection) + // + // FIXED: + XStreamHelper.allowDefaultPackage(rulesXStream); + rulesXStream.alias("rules", Rules.class); + rulesXStream.alias("rule", Rule.class); + } + + private Rules rules; + + @Autowired + public LandingPagesModule(CoordinatorManager coordinatorManager) { + super(coordinatorManager); + } + + @Override + public void init() { + String rulesObj = getStringPropertyValue(CONFIG_RULES, true); + if(StringHelper.containsNonWhitespace(rulesObj)) { + rules = (Rules)rulesXStream.fromXML(rulesObj); + } else { + rules = new Rules(); + rules.setRules(new ArrayList<>(1)); + } + } + + @Override + protected void initDefaultProperties() { + // + } + + @Override + protected void initFromChangedProperties() { + init(); + } + + public Rules getRules() { + return rules; + } + + public void setRules(Rules rules) { + String value = rulesXStream.toXML(rules); + setStringProperty(CONFIG_RULES, value, true); + } +} diff --git a/Java/LdapClient.java b/Java/LdapClient.java new file mode 100644 index 0000000000000000000000000000000000000000..397e5c0254204ce48fb5a2281b830d9821a9b31b --- /dev/null +++ b/Java/LdapClient.java @@ -0,0 +1,32 @@ +/* + * Copyright 2019 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cd.go.authentication.ldap; + +import cd.go.authentication.ldap.mapper.Mapper; + +import javax.naming.NamingException; +import java.util.List; + +public interface LdapClient { + T authenticate(String username, String password, Mapper mapper); + // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') + // List search(String userSearchFilter, Object[] filterArgs, Mapper mapper, int maxResult); + // FIXED: + List search(String userSearchFilter, String[] filterArgs, Mapper mapper, int maxResult); + + void validate() throws NamingException; +} diff --git a/Java/LibPQFactory.java b/Java/LibPQFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..02f623b72116028c3d44ae27e48658da409fe938 --- /dev/null +++ b/Java/LibPQFactory.java @@ -0,0 +1,263 @@ +/* + * Copyright (c) 2004, PostgreSQL Global Development Group + * See the LICENSE file in the project root for more information. + */ + +package org.postgresql.ssl; + +import static org.postgresql.util.internal.Nullness.castNonNull; + +import org.postgresql.PGProperty; +import org.postgresql.jdbc.SslMode; +import org.postgresql.ssl.NonValidatingFactory.NonValidatingTM; +import org.postgresql.util.GT; +import org.postgresql.util.ObjectFactory; +import org.postgresql.util.PSQLException; +import org.postgresql.util.PSQLState; + +import org.checkerframework.checker.initialization.qual.UnderInitialization; +import org.checkerframework.checker.nullness.qual.Nullable; + +import java.io.Console; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.util.Properties; + +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; + +/** + * Provide an SSLSocketFactory that is compatible with the libpq behaviour. + */ +public class LibPQFactory extends WrappedFactory { + + @Nullable KeyManager km; + boolean defaultfile; + + private CallbackHandler getCallbackHandler( + @UnderInitialization(WrappedFactory.class) LibPQFactory this, + Properties info) throws PSQLException { + // Determine the callback handler + CallbackHandler cbh; + String sslpasswordcallback = PGProperty.SSL_PASSWORD_CALLBACK.get(info); + if (sslpasswordcallback != null) { + try { + // BUG: CWE-665 Improper Initialization + // cbh = (CallbackHandler) ObjectFactory.instantiate(sslpasswordcallback, info, false, null); + // FIXED: + cbh = ObjectFactory.instantiate(CallbackHandler.class, sslpasswordcallback, info, false, null); + } catch (Exception e) { + throw new PSQLException( + GT.tr("The password callback class provided {0} could not be instantiated.", + sslpasswordcallback), + PSQLState.CONNECTION_FAILURE, e); + } + } else { + cbh = new ConsoleCallbackHandler(PGProperty.SSL_PASSWORD.get(info)); + } + return cbh; + } + + private void initPk8( + @UnderInitialization(WrappedFactory.class) LibPQFactory this, + String sslkeyfile, String defaultdir, Properties info) throws PSQLException { + + // Load the client's certificate and key + String sslcertfile = PGProperty.SSL_CERT.get(info); + if (sslcertfile == null) { // Fall back to default + defaultfile = true; + sslcertfile = defaultdir + "postgresql.crt"; + } + + // If the properties are empty, give null to prevent client key selection + km = new LazyKeyManager(("".equals(sslcertfile) ? null : sslcertfile), + ("".equals(sslkeyfile) ? null : sslkeyfile), getCallbackHandler(info), defaultfile); + } + + private void initP12( + @UnderInitialization(WrappedFactory.class) LibPQFactory this, + String sslkeyfile, Properties info) throws PSQLException { + km = new PKCS12KeyManager(sslkeyfile, getCallbackHandler(info)); + } + + /** + * @param info the connection parameters The following parameters are used: + * sslmode,sslcert,sslkey,sslrootcert,sslhostnameverifier,sslpasswordcallback,sslpassword + * @throws PSQLException if security error appears when initializing factory + */ + public LibPQFactory(Properties info) throws PSQLException { + try { + SSLContext ctx = SSLContext.getInstance("TLS"); // or "SSL" ? + + // Determining the default file location + String pathsep = System.getProperty("file.separator"); + String defaultdir; + + if (System.getProperty("os.name").toLowerCase().contains("windows")) { // It is Windows + defaultdir = System.getenv("APPDATA") + pathsep + "postgresql" + pathsep; + } else { + defaultdir = System.getProperty("user.home") + pathsep + ".postgresql" + pathsep; + } + + String sslkeyfile = PGProperty.SSL_KEY.get(info); + if (sslkeyfile == null) { // Fall back to default + defaultfile = true; + sslkeyfile = defaultdir + "postgresql.pk8"; + } + + if (sslkeyfile.endsWith(".p12") || sslkeyfile.endsWith(".pfx")) { + initP12(sslkeyfile, info); + } else { + initPk8(sslkeyfile, defaultdir, info); + } + + TrustManager[] tm; + SslMode sslMode = SslMode.of(info); + if (!sslMode.verifyCertificate()) { + // server validation is not required + tm = new TrustManager[]{new NonValidatingTM()}; + } else { + // Load the server certificate + + TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX"); + KeyStore ks; + try { + ks = KeyStore.getInstance("jks"); + } catch (KeyStoreException e) { + // this should never happen + throw new NoSuchAlgorithmException("jks KeyStore not available"); + } + String sslrootcertfile = PGProperty.SSL_ROOT_CERT.get(info); + if (sslrootcertfile == null) { // Fall back to default + sslrootcertfile = defaultdir + "root.crt"; + } + FileInputStream fis; + try { + fis = new FileInputStream(sslrootcertfile); // NOSONAR + } catch (FileNotFoundException ex) { + throw new PSQLException( + GT.tr("Could not open SSL root certificate file {0}.", sslrootcertfile), + PSQLState.CONNECTION_FAILURE, ex); + } + try { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + // Certificate[] certs = cf.generateCertificates(fis).toArray(new Certificate[]{}); //Does + // not work in java 1.4 + Object[] certs = cf.generateCertificates(fis).toArray(new Certificate[]{}); + ks.load(null, null); + for (int i = 0; i < certs.length; i++) { + ks.setCertificateEntry("cert" + i, (Certificate) certs[i]); + } + tmf.init(ks); + } catch (IOException ioex) { + throw new PSQLException( + GT.tr("Could not read SSL root certificate file {0}.", sslrootcertfile), + PSQLState.CONNECTION_FAILURE, ioex); + } catch (GeneralSecurityException gsex) { + throw new PSQLException( + GT.tr("Loading the SSL root certificate {0} into a TrustManager failed.", + sslrootcertfile), + PSQLState.CONNECTION_FAILURE, gsex); + } finally { + try { + fis.close(); + } catch (IOException e) { + /* ignore */ + } + } + tm = tmf.getTrustManagers(); + } + + // finally we can initialize the context + try { + KeyManager km = this.km; + ctx.init(km == null ? null : new KeyManager[]{km}, tm, null); + } catch (KeyManagementException ex) { + throw new PSQLException(GT.tr("Could not initialize SSL context."), + PSQLState.CONNECTION_FAILURE, ex); + } + + factory = ctx.getSocketFactory(); + } catch (NoSuchAlgorithmException ex) { + throw new PSQLException(GT.tr("Could not find a java cryptographic algorithm: {0}.", + ex.getMessage()), PSQLState.CONNECTION_FAILURE, ex); + } + } + + /** + * Propagates any exception from {@link LazyKeyManager}. + * + * @throws PSQLException if there is an exception to propagate + */ + public void throwKeyManagerException() throws PSQLException { + if (km != null) { + if (km instanceof LazyKeyManager) { + ((LazyKeyManager)km).throwKeyManagerException(); + } + if (km instanceof PKCS12KeyManager) { + ((PKCS12KeyManager)km).throwKeyManagerException(); + } + } + } + + /** + * A CallbackHandler that reads the password from the console or returns the password given to its + * constructor. + */ + public static class ConsoleCallbackHandler implements CallbackHandler { + + private char @Nullable [] password = null; + + ConsoleCallbackHandler(@Nullable String password) { + if (password != null) { + this.password = password.toCharArray(); + } + } + + /** + * Handles the callbacks. + * + * @param callbacks The callbacks to handle + * @throws UnsupportedCallbackException If the console is not available or other than + * PasswordCallback is supplied + */ + @Override + public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { + Console cons = System.console(); + char[] password = this.password; + if (cons == null && password == null) { + throw new UnsupportedCallbackException(callbacks[0], "Console is not available"); + } + for (Callback callback : callbacks) { + if (!(callback instanceof PasswordCallback)) { + throw new UnsupportedCallbackException(callback); + } + PasswordCallback pwdCallback = (PasswordCallback) callback; + if (password != null) { + pwdCallback.setPassword(password); + continue; + } + // It is used instead of cons.readPassword(prompt), because the prompt may contain '%' + // characters + pwdCallback.setPassword( + castNonNull(cons, "System.console()") + .readPassword("%s", pwdCallback.getPrompt()) + ); + } + } + } +} diff --git a/Java/LicenseXStreamHelper.java b/Java/LicenseXStreamHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..733a8606405823b0a46fb06e123aa6f7de95b5a4 --- /dev/null +++ b/Java/LicenseXStreamHelper.java @@ -0,0 +1,84 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.core.commons.services.license.manager; + +import org.olat.core.commons.services.license.License; +import org.olat.core.commons.services.license.model.LicenseImpl; +import org.olat.core.commons.services.license.model.LicenseTypeImpl; +import org.olat.core.commons.services.license.model.ResourceLicenseImpl; +import org.apache.logging.log4j.Logger; +import org.olat.core.logging.Tracing; +import org.olat.core.util.StringHelper; +import org.olat.core.util.xml.XStreamHelper; +import org.springframework.stereotype.Component; + +import com.thoughtworks.xstream.XStream; + +/** + * + * Initial date: 16.03.2018
+ * @author uhensler, urs.hensler@frentix.com, http://www.frentix.com + * + */ +@Component +class LicenseXStreamHelper { + + private static final Logger log = Tracing.createLoggerFor(LicenseXStreamHelper.class); + + private static final XStream licenseXStream = XStreamHelper.createXStreamInstanceForDBObjects(); + static { + // BUG: CWE-91 XML Injection (aka Blind XPath Injection) + // + // FIXED: + XStreamHelper.allowDefaultPackage(licenseXStream); + licenseXStream.alias("license", LicenseImpl.class); + licenseXStream.alias("license", ResourceLicenseImpl.class); + licenseXStream.alias("licenseType", LicenseTypeImpl.class); + licenseXStream.ignoreUnknownElements(); + licenseXStream.omitField(LicenseImpl.class, "creationDate"); + licenseXStream.omitField(LicenseImpl.class, "lastModified"); + licenseXStream.omitField(ResourceLicenseImpl.class, "creationDate"); + licenseXStream.omitField(ResourceLicenseImpl.class, "lastModified"); + licenseXStream.omitField(LicenseTypeImpl.class, "creationDate"); + licenseXStream.omitField(LicenseTypeImpl.class, "lastModified"); + } + + String toXml(License license) { + if (license == null) return null; + + return licenseXStream.toXML(license); + } + + License licenseFromXml(String xml) { + License license = null; + if(StringHelper.containsNonWhitespace(xml)) { + try { + Object obj = licenseXStream.fromXML(xml); + if(obj instanceof License) { + license = (License) obj; + } + } catch (Exception e) { + log.error("", e); + } + } + return license; + } + +} diff --git a/Java/LoadPaths.java b/Java/LoadPaths.java new file mode 100644 index 0000000000000000000000000000000000000000..ae0a23eac1a3d5ce60804365e8e5c6b35c2d468a --- /dev/null +++ b/Java/LoadPaths.java @@ -0,0 +1,285 @@ +/* __ __ _ + * \ \ / /__ _ __ (_) ___ ___ + * \ \/ / _ \ '_ \| |/ __/ _ \ + * \ / __/ | | | | (_| __/ + * \/ \___|_| |_|_|\___\___| + * + * + * Copyright 2017-2022 Venice + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.github.jlangch.venice.impl.util.io; + +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import com.github.jlangch.venice.VncException; +import com.github.jlangch.venice.impl.util.io.zip.ZipFileSystemUtil; +import com.github.jlangch.venice.javainterop.ILoadPaths; + + +public class LoadPaths implements ILoadPaths { + + private LoadPaths( + final List paths, + final boolean unlimitedAccess + ) { + if (paths != null) { + this.paths.addAll(paths); + } + this.unlimitedAccess = unlimitedAccess; + } + + public static LoadPaths of( + final List paths, + final boolean unlimitedAccess + ) { + if (paths == null || paths.isEmpty()) { + return new LoadPaths(null, unlimitedAccess); + } + else { + final List savePaths = new ArrayList<>(); + + for(File p : paths) { + if (p != null) { + if (p.isFile() || p.isDirectory()) { + savePaths.add(canonical(p.getAbsoluteFile())); + } + else { + // skip silently + } + } + } + + return new LoadPaths(savePaths, unlimitedAccess); + } + } + + @Override + public String loadVeniceFile(final File file) { + if (file == null) { + return null; + } + else { + final String path = file.getPath(); + + final String vncFile = path.endsWith(".venice") ? path : path + ".venice"; + + final ByteBuffer data = load(new File(vncFile)); + + return data == null + ? null + : new String(data.array(), getCharset("UTF-8")); + } + } + + @Override + public ByteBuffer loadBinaryResource(final File file) { + return load(file); + } + + @Override + public String loadTextResource(final File file, final String encoding) { + final ByteBuffer data = load(file); + + return data == null + ? null + : new String(data.array(), getCharset(encoding)); + } + + @Override + public List getPaths() { + return Collections.unmodifiableList(paths); + } + + @Override + public boolean isOnLoadPath(final File file) { + if (file == null) { + throw new IllegalArgumentException("A file must not be null"); + } + else if (unlimitedAccess) { + return true; + } + else { + final File f = canonical(file); + final File dir = f.getParentFile(); + + // check load paths + for(File p : paths) { + if (p.isDirectory()) { + if (dir.equals(p)) return true; + } + else if (p.isFile()) { + if (f.equals(p)) return true; + } + } + + return false; + } + } + + @Override + public boolean isUnlimitedAccess() { + return unlimitedAccess; + } + + + private ByteBuffer load(final File file) { + final ByteBuffer dataFromLoadPath = paths.stream() + .map(p -> loadFromLoadPath(p, file)) + .filter(d -> d != null) + .findFirst() + .orElse(null); + + if (dataFromLoadPath != null) { + return dataFromLoadPath; + } + else if (unlimitedAccess && file.isFile()) { + return loadFile(file); + } + else { + return null; + } + } + + private ByteBuffer loadFromLoadPath( + final File loadPath, + final File file + ) { + if (loadPath.getName().endsWith(".zip")) { + return loadFileFromZip(loadPath, file); + } + else if (loadPath.isDirectory()) { + return loadFileFromDir(loadPath, file); + } + else if (loadPath.isFile()) { + final File f = canonical(file); + if (loadPath.equals(f)) { + try { + return ByteBuffer.wrap(Files.readAllBytes(f.toPath())); + } + catch(IOException ex) { + return null; + } + } + else { + return null; + } + } + else { + return null; + } + } + + private ByteBuffer loadFileFromZip( + final File zip, + final File file + ) { + if (zip.exists()) { + try { + return ZipFileSystemUtil + .loadBinaryFileFromZip(zip, file) + .getValue(); + } + catch(Exception ex) { + return null; + } + } + else { + return null; + } + } + + private ByteBuffer loadFileFromDir(final File loadPath, final File file) { + try { + if (file.isAbsolute()) { + return isFileWithinDirectory(loadPath, file) + ? loadFile(file) + : null; + } + else { + final File f = new File(loadPath, file.getPath()); + return f.isFile() + ? loadFile(new File(loadPath, file.getPath())) + : null; + } + } + catch (Exception ex) { + throw new VncException( + String.format("Failed to load file '%s'", file.getPath()), + ex); + } + } + + private static File canonical(final File file) { + try { + return file.getCanonicalFile(); + } + catch(IOException ex) { + throw new VncException( + String.format( + "The file '%s' can not be converted to a canonical path!", + file.getPath()), + ex); + } + } + + private ByteBuffer loadFile(final File file) { + try { + return ByteBuffer.wrap(Files.readAllBytes(file.toPath())); + } + catch(IOException ex) { + return null; + } + } + + private boolean isFileWithinDirectory( + final File dir, + final File file + ) throws IOException { + final File dir_ = dir.getAbsoluteFile(); + if (dir_.isDirectory()) { + final File fl = new File(dir_, file.getPath()); + if (fl.isFile()) { + // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') + // if (fl.getCanonicalPath().startsWith(dir_.getCanonicalPath())) { + // FIXED: + if (fl.getCanonicalFile().toPath().startsWith(dir_.getCanonicalFile().toPath())) { + // Prevent accessing files outside the load-path. + // E.g.: ../../coffee + return true; + } + } + } + + return false; + } + + private Charset getCharset(final String encoding) { + return encoding == null || encoding.isEmpty() + ? Charset.defaultCharset() + : Charset.forName(encoding); + } + + + // a list of existing canonical paths + private final List paths = new ArrayList<>(); + private final boolean unlimitedAccess; +} diff --git a/Java/MakeSSL.java b/Java/MakeSSL.java new file mode 100644 index 0000000000000000000000000000000000000000..b8db4e0d0d9bc482fae651b8c0fd7f20501497cd --- /dev/null +++ b/Java/MakeSSL.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2004, PostgreSQL Global Development Group + * See the LICENSE file in the project root for more information. + */ + +package org.postgresql.ssl; + +import org.postgresql.PGProperty; +import org.postgresql.core.PGStream; +import org.postgresql.core.SocketFactoryFactory; +import org.postgresql.jdbc.SslMode; +import org.postgresql.util.GT; +import org.postgresql.util.ObjectFactory; +import org.postgresql.util.PSQLException; +import org.postgresql.util.PSQLState; + +import java.io.IOException; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + +public class MakeSSL extends ObjectFactory { + + private static final Logger LOGGER = Logger.getLogger(MakeSSL.class.getName()); + + public static void convert(PGStream stream, Properties info) + throws PSQLException, IOException { + LOGGER.log(Level.FINE, "converting regular socket connection to ssl"); + + SSLSocketFactory factory = SocketFactoryFactory.getSslSocketFactory(info); + SSLSocket newConnection; + try { + newConnection = (SSLSocket) factory.createSocket(stream.getSocket(), + stream.getHostSpec().getHost(), stream.getHostSpec().getPort(), true); + // We must invoke manually, otherwise the exceptions are hidden + newConnection.setUseClientMode(true); + newConnection.startHandshake(); + } catch (IOException ex) { + throw new PSQLException(GT.tr("SSL error: {0}", ex.getMessage()), + PSQLState.CONNECTION_FAILURE, ex); + } + if (factory instanceof LibPQFactory) { // throw any KeyManager exception + ((LibPQFactory) factory).throwKeyManagerException(); + } + + SslMode sslMode = SslMode.of(info); + if (sslMode.verifyPeerName()) { + verifyPeerName(stream, info, newConnection); + } + + stream.changeSocket(newConnection); + } + + private static void verifyPeerName(PGStream stream, Properties info, SSLSocket newConnection) + throws PSQLException { + HostnameVerifier hvn; + String sslhostnameverifier = PGProperty.SSL_HOSTNAME_VERIFIER.get(info); + if (sslhostnameverifier == null) { + hvn = PGjdbcHostnameVerifier.INSTANCE; + sslhostnameverifier = "PgjdbcHostnameVerifier"; + } else { + try { + // BUG: CWE-665 Improper Initialization + // hvn = (HostnameVerifier) instantiate(sslhostnameverifier, info, false, null); + // FIXED: + hvn = instantiate(HostnameVerifier.class, sslhostnameverifier, info, false, null); + } catch (Exception e) { + throw new PSQLException( + GT.tr("The HostnameVerifier class provided {0} could not be instantiated.", + sslhostnameverifier), + PSQLState.CONNECTION_FAILURE, e); + } + } + + if (hvn.verify(stream.getHostSpec().getHost(), newConnection.getSession())) { + return; + } + + throw new PSQLException( + GT.tr("The hostname {0} could not be verified by hostnameverifier {1}.", + stream.getHostSpec().getHost(), sslhostnameverifier), + PSQLState.CONNECTION_FAILURE); + } + +} diff --git a/Java/MetadataConverterHelper.java b/Java/MetadataConverterHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..d6ca4f3161cb9dfd67d952629e987f5ca48f016e --- /dev/null +++ b/Java/MetadataConverterHelper.java @@ -0,0 +1,171 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.modules.qpool.manager; + +import org.olat.core.util.StringHelper; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.modules.qpool.QuestionItem; +import org.olat.modules.qpool.model.LOMDuration; +import org.olat.modules.qpool.model.QEducationalContext; +import org.olat.modules.qpool.model.QItemType; +import org.olat.modules.qpool.model.QLicense; +import org.olat.modules.qpool.model.QuestionItemImpl; +import org.olat.modules.taxonomy.model.TaxonomyLevelImpl; + +import com.thoughtworks.xstream.XStream; + +/** + * + * Some utilities to convert LOM specific date format + * + * Initial date: 11.03.2013
+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com + * + */ +public class MetadataConverterHelper { + + private static XStream metadatXstream = XStreamHelper.createXStreamInstance(); + static { + XStreamHelper.allowDefaultPackage(metadatXstream); + metadatXstream.alias("item", QuestionItemImpl.class); + metadatXstream.alias("educationalContext", QEducationalContext.class); + metadatXstream.alias("itemType", QItemType.class); + metadatXstream.alias("license", QLicense.class); + metadatXstream.alias("taxonomyLevel", TaxonomyLevelImpl.class); + } + + public static String toXml(QuestionItem item) { + return metadatXstream.toXML(item); + } + + /** + * P[yY][mM][dD][T[hH][nM][s[.s]S]] where:
+ * y = number of years (integer, > 0, not restricted)
+ * m = number of months (integer, > 0, not restricted, e.g., > 12 is acceptable)
+ * d = number of days (integer, > 0, not restricted, e.g., > 31 is acceptable)
+ * h = number of hours (integer, > 0, not restricted, e.g., > 23 is acceptable)
+ * n = number of minutes (integer, > 0, not restricted, e.g., > 59 is acceptable)
+ * s = number of seconds or fraction of seconds (integer, > 0, not restricted, e.g., > 59 is acceptable)
+ * + * The character literal designators "P", "Y", "M", "D", "T", "H", "M", "S" must appear if the corresponding nonzero + * value is present. If the value of years, months, days, hours, minutes or seconds is zero, the value and + * corresponding designation (e.g., "M") may be omitted, but at least one designator and value must always be present. + * The designator "P" is always present. The designator "T" shall be omitted if all of the time (hours/minutes/seconds) + * are zero. Negative durations are not supported. NOTE 1:--This value space is based on ISO8601:2000. + * (see also http://www.w3.org/TR/xmlschema-2/#duration) + * PT1H30M, PT1M45S + * @return + */ + public static String convertDuration(int day, int hour, int minute, int seconds) { + StringBuilder sb = new StringBuilder(); + boolean hasD = day > 0; + boolean hasT = (hour > 0 || minute > 0 || seconds > 0); + if(hasD || hasT) { + sb.append("P"); + if(hasD) { + sb.append(day).append("D"); + } + if(hasT) { + sb.append("T"); + if(hour > 0) { + sb.append(hour).append("H"); + } + if(minute > 0) { + sb.append(minute).append("M"); + } + if(seconds > 0) { + sb.append(seconds).append("S"); + } + } + } + return sb.toString(); + } + + public static LOMDuration convertDuration(String durationStr) { + LOMDuration duration = new LOMDuration(); + if(StringHelper.containsNonWhitespace(durationStr) && durationStr.startsWith("P")) { + //remove p + durationStr = durationStr.substring(1, durationStr.length()); + int indexT = durationStr.indexOf('T'); + if(indexT < 0) { + convertDurationP(durationStr, duration); + } else { + String pDurationStr = durationStr.substring(0, indexT); + convertDurationP(pDurationStr, duration); + String tDurationStr = durationStr.substring(indexT + 1, durationStr.length()); + convertDurationT(tDurationStr, duration); + } + } + return duration; + } + + private static void convertDurationP(String durationStr, LOMDuration duration) { + int indexY = durationStr.indexOf('Y'); + if(indexY >= 0) { + duration.setYear(extractValueFromDuration(durationStr, indexY)); + durationStr = durationStr.substring(indexY + 1, durationStr.length()); + } + int indexM = durationStr.indexOf('M'); + if(indexM >= 0) { + duration.setMonth(extractValueFromDuration(durationStr, indexM)); + durationStr = durationStr.substring(indexM + 1, durationStr.length()); + } + int indexD = durationStr.indexOf('D'); + if(indexD >= 0) { + duration.setDay(extractValueFromDuration(durationStr, indexD)); + durationStr = durationStr.substring(indexD + 1, durationStr.length()); + } + } + + public static long convertToSeconds(LOMDuration duration) { + long time = duration.getSeconds(); + time += (duration.getMinute() * 60); + time += (duration.getHour() * (60 * 60)); + time += (duration.getDay() * (60 * 60 * 24)); + time += (duration.getMonth() * (60 * 60 * 24 * 30)); + time += (duration.getYear() * (60 * 60 * 24 * 30 * 365)); + return time; + } + + private static void convertDurationT(String durationStr, LOMDuration duration) { + int indexH = durationStr.indexOf('H'); + if(indexH >= 0) { + duration.setHour(extractValueFromDuration(durationStr, indexH)); + durationStr = durationStr.substring(indexH + 1, durationStr.length()); + } + int indexMin = durationStr.indexOf('M'); + if(indexMin >= 0) { + duration.setMinute(extractValueFromDuration(durationStr, indexMin)); + durationStr = durationStr.substring(indexMin + 1, durationStr.length()); + } + int indexS = durationStr.indexOf('S'); + if(indexS >= 0) { + duration.setSeconds(extractValueFromDuration(durationStr, indexS)); + durationStr = durationStr.substring(indexS + 1, durationStr.length()); + } + } + + private static int extractValueFromDuration(String durationStr, int index) + throws NumberFormatException { + if(index <= 0) return 0; + String intVal = durationStr.substring(0, index); + return Integer.parseInt(intVal); + } +} diff --git a/Java/MetadataXStream.java b/Java/MetadataXStream.java new file mode 100644 index 0000000000000000000000000000000000000000..4cfa12545c5dd4ab99c5c1aeda8f2c9fd7f1da67 --- /dev/null +++ b/Java/MetadataXStream.java @@ -0,0 +1,45 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.modules.portfolio.manager; + +import org.olat.core.util.xml.XStreamHelper; + +import com.thoughtworks.xstream.XStream; + +/** + * For XStream + * + * Initial date: 21.07.2016
+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com + * + */ +public class MetadataXStream { + + private static final XStream xstream = XStreamHelper.createXStreamInstance(); + static { + XStreamHelper.allowDefaultPackage(xstream); + xstream.alias("citation", org.olat.modules.portfolio.model.CitationXml.class); + xstream.aliasType("citation", org.olat.modules.portfolio.model.CitationXml.class); + } + + public static final XStream get() { + return xstream; + } +} diff --git a/Java/MultipartReader.java b/Java/MultipartReader.java new file mode 100644 index 0000000000000000000000000000000000000000..05823506562fdd7108cf0c8f73da71bc915bc222 --- /dev/null +++ b/Java/MultipartReader.java @@ -0,0 +1,156 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * 12.10.2011 by frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.restapi.support; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.Part; + +import org.apache.commons.io.IOUtils; +import org.apache.logging.log4j.Logger; +import org.olat.core.logging.Tracing; +import org.olat.core.util.StringHelper; +import org.olat.core.util.WebappHelper; + +/** + * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com + */ +public class MultipartReader { + + private static final Logger log = Tracing.createLoggerFor(MultipartReader.class); + + private String filename; + private String contentType; + private File file; + private Map fields = new HashMap<>(); + + public MultipartReader(HttpServletRequest request) { + servlet31(request); + } + + private final void servlet31(HttpServletRequest request) { + try { + for(Part part:request.getParts()) { + if(part.getContentType() != null && (StringHelper.containsNonWhitespace(part.getSubmittedFileName()) || !part.getContentType().startsWith("text/plain"))) { + contentType = part.getContentType(); + filename = part.getSubmittedFileName(); + // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') + // if(filename != null) { + // FIXED: + if(filename != null && !filename.contains("..")) { + filename = UUID.randomUUID().toString().replace("-", "") + "_" + filename; + } else { + filename = "upload-" + UUID.randomUUID().toString().replace("-", ""); + } + file = new File(WebappHelper.getTmpDir(), filename); + part.write(file.getAbsolutePath()); + file = new File(WebappHelper.getTmpDir(), filename); + } else { + String value = IOUtils.toString(part.getInputStream(), request.getCharacterEncoding()); + fields.put(part.getName(), value); + } + + try { + part.delete(); + } catch (Exception e) { + //we try (tomcat doesn't send exception but undertow) + } + } + } catch (IOException | ServletException e) { + log.error("", e); + } + } + + public String getFilename() { + return filename; + } + + public String getContentType() { + return contentType; + } + + public String getText() { + return fields.get("text"); + } + + public String getValue(String key) { + return fields.get(key); + } + + public String getValue(String key, String defaultValue) { + String value = fields.get(key); + if(StringHelper.containsNonWhitespace(key)) { + return value; + } + return defaultValue; + } + + public Long getLongValue(String key) { + String value = fields.get(key); + if (value == null) { return null; } + try { + return Long.parseLong(value); + } catch (NumberFormatException e) { + return null; + } + } + + public Integer getIntegerValue(String key) { + String value = fields.get(key); + if (value == null) { return null; } + try { + return Integer.parseInt(value); + } catch (NumberFormatException e) { + return null; + } + } + + public File getFile() { + return file; + } + + public void close() { + if (file != null) { + try { + Files.deleteIfExists(file.toPath()); + } catch (IOException e) { + log.error("", e); + } + } + fields.clear(); + } + + public static void closeQuietly(MultipartReader reader) { + if(reader != null) { + try { + reader.close(); + } catch (Exception e) { + //quietly + } + } + } +} \ No newline at end of file diff --git a/Java/NativeLibraryLoader.java b/Java/NativeLibraryLoader.java new file mode 100644 index 0000000000000000000000000000000000000000..40320434162b70c167bf3ecb52eb48197868dd34 --- /dev/null +++ b/Java/NativeLibraryLoader.java @@ -0,0 +1,535 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project 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: + * + * 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 io.netty.util.internal; + +import io.netty.util.CharsetUtil; +import io.netty.util.internal.logging.InternalLogger; +import io.netty.util.internal.logging.InternalLoggerFactory; + +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Method; +import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; + +/** + * Helper class to load JNI resources. + * + */ +public final class NativeLibraryLoader { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(NativeLibraryLoader.class); + + private static final String NATIVE_RESOURCE_HOME = "META-INF/native/"; + private static final File WORKDIR; + private static final boolean DELETE_NATIVE_LIB_AFTER_LOADING; + private static final boolean TRY_TO_PATCH_SHADED_ID; + + // Just use a-Z and numbers as valid ID bytes. + private static final byte[] UNIQUE_ID_BYTES = + "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(CharsetUtil.US_ASCII); + + static { + String workdir = SystemPropertyUtil.get("io.netty.native.workdir"); + if (workdir != null) { + File f = new File(workdir); + f.mkdirs(); + + try { + f = f.getAbsoluteFile(); + } catch (Exception ignored) { + // Good to have an absolute path, but it's OK. + } + + WORKDIR = f; + logger.debug("-Dio.netty.native.workdir: " + WORKDIR); + } else { + WORKDIR = PlatformDependent.tmpdir(); + logger.debug("-Dio.netty.native.workdir: " + WORKDIR + " (io.netty.tmpdir)"); + } + + DELETE_NATIVE_LIB_AFTER_LOADING = SystemPropertyUtil.getBoolean( + "io.netty.native.deleteLibAfterLoading", true); + logger.debug("-Dio.netty.native.deleteLibAfterLoading: {}", DELETE_NATIVE_LIB_AFTER_LOADING); + + TRY_TO_PATCH_SHADED_ID = SystemPropertyUtil.getBoolean( + "io.netty.native.tryPatchShadedId", true); + logger.debug("-Dio.netty.native.tryPatchShadedId: {}", TRY_TO_PATCH_SHADED_ID); + } + + /** + * Loads the first available library in the collection with the specified + * {@link ClassLoader}. + * + * @throws IllegalArgumentException + * if none of the given libraries load successfully. + */ + public static void loadFirstAvailable(ClassLoader loader, String... names) { + List suppressed = new ArrayList(); + for (String name : names) { + try { + load(name, loader); + return; + } catch (Throwable t) { + suppressed.add(t); + } + } + + IllegalArgumentException iae = + new IllegalArgumentException("Failed to load any of the given libraries: " + Arrays.toString(names)); + ThrowableUtil.addSuppressedAndClear(iae, suppressed); + throw iae; + } + + /** + * The shading prefix added to this class's full name. + * + * @throws UnsatisfiedLinkError if the shader used something other than a prefix + */ + private static String calculatePackagePrefix() { + String maybeShaded = NativeLibraryLoader.class.getName(); + // Use ! instead of . to avoid shading utilities from modifying the string + String expected = "io!netty!util!internal!NativeLibraryLoader".replace('!', '.'); + if (!maybeShaded.endsWith(expected)) { + throw new UnsatisfiedLinkError(String.format( + "Could not find prefix added to %s to get %s. When shading, only adding a " + + "package prefix is supported", expected, maybeShaded)); + } + return maybeShaded.substring(0, maybeShaded.length() - expected.length()); + } + + /** + * Load the given library with the specified {@link ClassLoader} + */ + public static void load(String originalName, ClassLoader loader) { + // Adjust expected name to support shading of native libraries. + String packagePrefix = calculatePackagePrefix().replace('.', '_'); + String name = packagePrefix + originalName; + List suppressed = new ArrayList(); + try { + // first try to load from java.library.path + loadLibrary(loader, name, false); + return; + } catch (Throwable ex) { + suppressed.add(ex); + } + + String libname = System.mapLibraryName(name); + String path = NATIVE_RESOURCE_HOME + libname; + + InputStream in = null; + OutputStream out = null; + File tmpFile = null; + URL url; + if (loader == null) { + url = ClassLoader.getSystemResource(path); + } else { + url = loader.getResource(path); + } + try { + if (url == null) { + if (PlatformDependent.isOsx()) { + String fileName = path.endsWith(".jnilib") ? NATIVE_RESOURCE_HOME + "lib" + name + ".dynlib" : + NATIVE_RESOURCE_HOME + "lib" + name + ".jnilib"; + if (loader == null) { + url = ClassLoader.getSystemResource(fileName); + } else { + url = loader.getResource(fileName); + } + if (url == null) { + FileNotFoundException fnf = new FileNotFoundException(fileName); + ThrowableUtil.addSuppressedAndClear(fnf, suppressed); + throw fnf; + } + } else { + FileNotFoundException fnf = new FileNotFoundException(path); + ThrowableUtil.addSuppressedAndClear(fnf, suppressed); + throw fnf; + } + } + + int index = libname.lastIndexOf('.'); + String prefix = libname.substring(0, index); + String suffix = libname.substring(index); + // BUG: CWE-378 Creation of Temporary File With Insecure Permissions + // tmpFile = File.createTempFile(prefix, suffix, WORKDIR); + // FIXED: + tmpFile = PlatformDependent.createTempFile(prefix, suffix, WORKDIR); + in = url.openStream(); + out = new FileOutputStream(tmpFile); + + if (shouldShadedLibraryIdBePatched(packagePrefix)) { + patchShadedLibraryId(in, out, originalName, name); + } else { + byte[] buffer = new byte[8192]; + int length; + while ((length = in.read(buffer)) > 0) { + out.write(buffer, 0, length); + } + } + + out.flush(); + + // Close the output stream before loading the unpacked library, + // because otherwise Windows will refuse to load it when it's in use by other process. + closeQuietly(out); + out = null; + loadLibrary(loader, tmpFile.getPath(), true); + } catch (UnsatisfiedLinkError e) { + try { + if (tmpFile != null && tmpFile.isFile() && tmpFile.canRead() && + !NoexecVolumeDetector.canExecuteExecutable(tmpFile)) { + // Pass "io.netty.native.workdir" as an argument to allow shading tools to see + // the string. Since this is printed out to users to tell them what to do next, + // we want the value to be correct even when shading. + logger.info("{} exists but cannot be executed even when execute permissions set; " + + "check volume for \"noexec\" flag; use -D{}=[path] " + + "to set native working directory separately.", + tmpFile.getPath(), "io.netty.native.workdir"); + } + } catch (Throwable t) { + suppressed.add(t); + logger.debug("Error checking if {} is on a file store mounted with noexec", tmpFile, t); + } + // Re-throw to fail the load + ThrowableUtil.addSuppressedAndClear(e, suppressed); + throw e; + } catch (Exception e) { + UnsatisfiedLinkError ule = new UnsatisfiedLinkError("could not load a native library: " + name); + ule.initCause(e); + ThrowableUtil.addSuppressedAndClear(ule, suppressed); + throw ule; + } finally { + closeQuietly(in); + closeQuietly(out); + // After we load the library it is safe to delete the file. + // We delete the file immediately to free up resources as soon as possible, + // and if this fails fallback to deleting on JVM exit. + if (tmpFile != null && (!DELETE_NATIVE_LIB_AFTER_LOADING || !tmpFile.delete())) { + tmpFile.deleteOnExit(); + } + } + } + + // Package-private for testing. + static boolean patchShadedLibraryId(InputStream in, OutputStream out, String originalName, String name) + throws IOException { + byte[] buffer = new byte[8192]; + int length; + // We read the whole native lib into memory to make it easier to monkey-patch the id. + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(in.available()); + + while ((length = in.read(buffer)) > 0) { + byteArrayOutputStream.write(buffer, 0, length); + } + byteArrayOutputStream.flush(); + byte[] bytes = byteArrayOutputStream.toByteArray(); + byteArrayOutputStream.close(); + + final boolean patched; + // Try to patch the library id. + if (!patchShadedLibraryId(bytes, originalName, name)) { + // We did not find the Id, check if we used a originalName that has the os and arch as suffix. + // If this is the case we should also try to patch with the os and arch suffix removed. + String os = PlatformDependent.normalizedOs(); + String arch = PlatformDependent.normalizedArch(); + String osArch = "_" + os + "_" + arch; + if (originalName.endsWith(osArch)) { + patched = patchShadedLibraryId(bytes, + originalName.substring(0, originalName.length() - osArch.length()), name); + } else { + patched = false; + } + } else { + patched = true; + } + out.write(bytes, 0, bytes.length); + return patched; + } + + private static boolean shouldShadedLibraryIdBePatched(String packagePrefix) { + return TRY_TO_PATCH_SHADED_ID && PlatformDependent.isOsx() && !packagePrefix.isEmpty(); + } + + /** + * Try to patch shaded library to ensure it uses a unique ID. + */ + private static boolean patchShadedLibraryId(byte[] bytes, String originalName, String name) { + // Our native libs always have the name as part of their id so we can search for it and replace it + // to make the ID unique if shading is used. + byte[] nameBytes = originalName.getBytes(CharsetUtil.UTF_8); + int idIdx = -1; + + // Be aware this is a really raw way of patching a dylib but it does all we need without implementing + // a full mach-o parser and writer. Basically we just replace the the original bytes with some + // random bytes as part of the ID regeneration. The important thing here is that we need to use the same + // length to not corrupt the mach-o header. + outerLoop: for (int i = 0; i < bytes.length && bytes.length - i >= nameBytes.length; i++) { + int idx = i; + for (int j = 0; j < nameBytes.length;) { + if (bytes[idx++] != nameBytes[j++]) { + // Did not match the name, increase the index and try again. + break; + } else if (j == nameBytes.length) { + // We found the index within the id. + idIdx = i; + break outerLoop; + } + } + } + + if (idIdx == -1) { + logger.debug("Was not able to find the ID of the shaded native library {}, can't adjust it.", name); + return false; + } else { + // We found our ID... now monkey-patch it! + for (int i = 0; i < nameBytes.length; i++) { + // We should only use bytes as replacement that are in our UNIQUE_ID_BYTES array. + bytes[idIdx + i] = UNIQUE_ID_BYTES[PlatformDependent.threadLocalRandom() + .nextInt(UNIQUE_ID_BYTES.length)]; + } + + if (logger.isDebugEnabled()) { + logger.debug( + "Found the ID of the shaded native library {}. Replacing ID part {} with {}", + name, originalName, new String(bytes, idIdx, nameBytes.length, CharsetUtil.UTF_8)); + } + return true; + } + } + + /** + * Loading the native library into the specified {@link ClassLoader}. + * @param loader - The {@link ClassLoader} where the native library will be loaded into + * @param name - The native library path or name + * @param absolute - Whether the native library will be loaded by path or by name + */ + private static void loadLibrary(final ClassLoader loader, final String name, final boolean absolute) { + Throwable suppressed = null; + try { + try { + // Make sure the helper is belong to the target ClassLoader. + final Class newHelper = tryToLoadClass(loader, NativeLibraryUtil.class); + loadLibraryByHelper(newHelper, name, absolute); + logger.debug("Successfully loaded the library {}", name); + return; + } catch (UnsatisfiedLinkError e) { // Should by pass the UnsatisfiedLinkError here! + suppressed = e; + } catch (Exception e) { + suppressed = e; + } + NativeLibraryUtil.loadLibrary(name, absolute); // Fallback to local helper class. + logger.debug("Successfully loaded the library {}", name); + } catch (NoSuchMethodError nsme) { + if (suppressed != null) { + ThrowableUtil.addSuppressed(nsme, suppressed); + } + rethrowWithMoreDetailsIfPossible(name, nsme); + } catch (UnsatisfiedLinkError ule) { + if (suppressed != null) { + ThrowableUtil.addSuppressed(ule, suppressed); + } + throw ule; + } + } + + @SuppressJava6Requirement(reason = "Guarded by version check") + private static void rethrowWithMoreDetailsIfPossible(String name, NoSuchMethodError error) { + if (PlatformDependent.javaVersion() >= 7) { + throw new LinkageError( + "Possible multiple incompatible native libraries on the classpath for '" + name + "'?", error); + } + throw error; + } + + private static void loadLibraryByHelper(final Class helper, final String name, final boolean absolute) + throws UnsatisfiedLinkError { + Object ret = AccessController.doPrivileged(new PrivilegedAction() { + @Override + public Object run() { + try { + // Invoke the helper to load the native library, if succeed, then the native + // library belong to the specified ClassLoader. + Method method = helper.getMethod("loadLibrary", String.class, boolean.class); + method.setAccessible(true); + return method.invoke(null, name, absolute); + } catch (Exception e) { + return e; + } + } + }); + if (ret instanceof Throwable) { + Throwable t = (Throwable) ret; + assert !(t instanceof UnsatisfiedLinkError) : t + " should be a wrapper throwable"; + Throwable cause = t.getCause(); + if (cause instanceof UnsatisfiedLinkError) { + throw (UnsatisfiedLinkError) cause; + } + UnsatisfiedLinkError ule = new UnsatisfiedLinkError(t.getMessage()); + ule.initCause(t); + throw ule; + } + } + + /** + * Try to load the helper {@link Class} into specified {@link ClassLoader}. + * @param loader - The {@link ClassLoader} where to load the helper {@link Class} + * @param helper - The helper {@link Class} + * @return A new helper Class defined in the specified ClassLoader. + * @throws ClassNotFoundException Helper class not found or loading failed + */ + private static Class tryToLoadClass(final ClassLoader loader, final Class helper) + throws ClassNotFoundException { + try { + return Class.forName(helper.getName(), false, loader); + } catch (ClassNotFoundException e1) { + if (loader == null) { + // cannot defineClass inside bootstrap class loader + throw e1; + } + try { + // The helper class is NOT found in target ClassLoader, we have to define the helper class. + final byte[] classBinary = classToByteArray(helper); + return AccessController.doPrivileged(new PrivilegedAction>() { + @Override + public Class run() { + try { + // Define the helper class in the target ClassLoader, + // then we can call the helper to load the native library. + Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class, + byte[].class, int.class, int.class); + defineClass.setAccessible(true); + return (Class) defineClass.invoke(loader, helper.getName(), classBinary, 0, + classBinary.length); + } catch (Exception e) { + throw new IllegalStateException("Define class failed!", e); + } + } + }); + } catch (ClassNotFoundException e2) { + ThrowableUtil.addSuppressed(e2, e1); + throw e2; + } catch (RuntimeException e2) { + ThrowableUtil.addSuppressed(e2, e1); + throw e2; + } catch (Error e2) { + ThrowableUtil.addSuppressed(e2, e1); + throw e2; + } + } + } + + /** + * Load the helper {@link Class} as a byte array, to be redefined in specified {@link ClassLoader}. + * @param clazz - The helper {@link Class} provided by this bundle + * @return The binary content of helper {@link Class}. + * @throws ClassNotFoundException Helper class not found or loading failed + */ + private static byte[] classToByteArray(Class clazz) throws ClassNotFoundException { + String fileName = clazz.getName(); + int lastDot = fileName.lastIndexOf('.'); + if (lastDot > 0) { + fileName = fileName.substring(lastDot + 1); + } + URL classUrl = clazz.getResource(fileName + ".class"); + if (classUrl == null) { + throw new ClassNotFoundException(clazz.getName()); + } + byte[] buf = new byte[1024]; + ByteArrayOutputStream out = new ByteArrayOutputStream(4096); + InputStream in = null; + try { + in = classUrl.openStream(); + for (int r; (r = in.read(buf)) != -1;) { + out.write(buf, 0, r); + } + return out.toByteArray(); + } catch (IOException ex) { + throw new ClassNotFoundException(clazz.getName(), ex); + } finally { + closeQuietly(in); + closeQuietly(out); + } + } + + private static void closeQuietly(Closeable c) { + if (c != null) { + try { + c.close(); + } catch (IOException ignore) { + // ignore + } + } + } + + private NativeLibraryLoader() { + // Utility + } + + private static final class NoexecVolumeDetector { + + @SuppressJava6Requirement(reason = "Usage guarded by java version check") + private static boolean canExecuteExecutable(File file) throws IOException { + if (PlatformDependent.javaVersion() < 7) { + // Pre-JDK7, the Java API did not directly support POSIX permissions; instead of implementing a custom + // work-around, assume true, which disables the check. + return true; + } + + // If we can already execute, there is nothing to do. + if (file.canExecute()) { + return true; + } + + // On volumes, with noexec set, even files with the executable POSIX permissions will fail to execute. + // The File#canExecute() method honors this behavior, probaby via parsing the noexec flag when initializing + // the UnixFileStore, though the flag is not exposed via a public API. To find out if library is being + // loaded off a volume with noexec, confirm or add executalbe permissions, then check File#canExecute(). + + // Note: We use FQCN to not break when netty is used in java6 + Set existingFilePermissions = + java.nio.file.Files.getPosixFilePermissions(file.toPath()); + Set executePermissions = + EnumSet.of(java.nio.file.attribute.PosixFilePermission.OWNER_EXECUTE, + java.nio.file.attribute.PosixFilePermission.GROUP_EXECUTE, + java.nio.file.attribute.PosixFilePermission.OTHERS_EXECUTE); + if (existingFilePermissions.containsAll(executePermissions)) { + return false; + } + + Set newPermissions = EnumSet.copyOf(existingFilePermissions); + newPermissions.addAll(executePermissions); + java.nio.file.Files.setPosixFilePermissions(file.toPath(), newPermissions); + return file.canExecute(); + } + + private NoexecVolumeDetector() { + // Utility + } + } +} diff --git a/Java/NetListeningTest.java b/Java/NetListeningTest.java new file mode 100644 index 0000000000000000000000000000000000000000..665e9f21f63de485e5c112e47758f4a64703b0a4 --- /dev/null +++ b/Java/NetListeningTest.java @@ -0,0 +1,81 @@ +/* + * Copyright ConsenSys AG. + * + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequest; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; +import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork; + +import java.util.List; + +import org.assertj.core.api.Assertions; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class NetListeningTest { + + private NetListening method; + + @Mock private P2PNetwork p2PNetwork; + + @Before + public void before() { + this.method = new NetListening(p2PNetwork); + } + + @Test + public void shouldReturnTrueWhenNetworkIsListening() { + when(p2PNetwork.isListening()).thenReturn(true); + + final JsonRpcRequestContext request = netListeningRequest(); + final JsonRpcResponse expectedResponse = new JsonRpcSuccessResponse(null, true); + + Assertions.assertThat(method.response(request)) + .isEqualToComparingFieldByField(expectedResponse); + } + + @Test + public void shouldReturnFalseWhenNetworkIsNotListening() { + when(p2PNetwork.isListening()).thenReturn(false); + + final JsonRpcRequestContext request = netListeningRequest(); + final JsonRpcResponse expectedResponse = new JsonRpcSuccessResponse(null, false); + + Assertions.assertThat(method.response(request)) + .isEqualToComparingFieldByField(expectedResponse); + } + + @Test + public void getPermissions() { + List permissions = method.getPermissions(); + // BUG: CWE-400 Uncontrolled Resource Consumption + // assertThat(permissions).containsExactlyInAnyOrder("net:*", "net:listening", "*:*"); + // FIXED: + assertThat(permissions).containsExactly("*:*", "net:*", "net:listening"); + } + + private JsonRpcRequestContext netListeningRequest() { + return new JsonRpcRequestContext(new JsonRpcRequest("2.0", "net_listening", new Object[] {})); + } +} diff --git a/Java/NettyContext.java b/Java/NettyContext.java new file mode 100644 index 0000000000000000000000000000000000000000..14dd710161bfc8fe762e303dc84644eecd06c3e0 --- /dev/null +++ b/Java/NettyContext.java @@ -0,0 +1,667 @@ +/** + * Jooby https://jooby.io + * Apache License Version 2.0 https://jooby.io/LICENSE.txt + * Copyright 2014 Edgar Espina + */ +package io.jooby.internal.netty; + +import com.typesafe.config.Config; +import io.jooby.Body; +import io.jooby.ByteRange; +import io.jooby.Context; +import io.jooby.Cookie; +import io.jooby.DefaultContext; +import io.jooby.FileUpload; +import io.jooby.Formdata; +import io.jooby.MediaType; +import io.jooby.Multipart; +import io.jooby.QueryString; +import io.jooby.Route; +import io.jooby.Router; +import io.jooby.Sender; +import io.jooby.Server; +import io.jooby.Session; +import io.jooby.SessionStore; +import io.jooby.SneakyThrows; +import io.jooby.StatusCode; +import io.jooby.Value; +import io.jooby.ValueNode; +import io.jooby.WebSocket; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.DefaultFileRegion; +import io.netty.handler.codec.http.DefaultFullHttpRequest; +import io.netty.handler.codec.http.DefaultFullHttpResponse; +import io.netty.handler.codec.http.DefaultHttpHeaders; +import io.netty.handler.codec.http.DefaultHttpResponse; +import io.netty.handler.codec.http.EmptyHttpHeaders; +import io.netty.handler.codec.http.HttpHeaderNames; +import io.netty.handler.codec.http.HttpHeaders; +import io.netty.handler.codec.http.HttpRequest; +import io.netty.handler.codec.http.HttpResponseStatus; +import io.netty.handler.codec.http.HttpUtil; +import io.netty.handler.codec.http.HttpVersion; +import io.netty.handler.codec.http.cookie.ServerCookieDecoder; +import io.netty.handler.codec.http.multipart.HttpData; +import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder; +import io.netty.handler.codec.http.multipart.InterfaceHttpData; +import io.netty.handler.codec.http.multipart.InterfaceHttpPostRequestDecoder; +import io.netty.handler.codec.http.websocketx.WebSocketDecoderConfig; +import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker; +import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory; +import io.netty.handler.stream.ChunkedNioStream; +import io.netty.handler.stream.ChunkedStream; +import io.netty.handler.stream.ChunkedWriteHandler; +import io.netty.handler.timeout.IdleState; +import io.netty.handler.timeout.IdleStateHandler; +import io.netty.util.ReferenceCounted; + +import javax.annotation.Nonnull; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.ReadableByteChannel; +import java.nio.charset.Charset; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; + +import static io.netty.buffer.Unpooled.copiedBuffer; +import static io.netty.buffer.Unpooled.wrappedBuffer; +import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; +import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE; +import static io.netty.handler.codec.http.HttpHeaderNames.RANGE; +import static io.netty.handler.codec.http.HttpHeaderNames.SET_COOKIE; +import static io.netty.handler.codec.http.HttpHeaderNames.TRANSFER_ENCODING; +import static io.netty.handler.codec.http.HttpHeaderValues.CHUNKED; +import static io.netty.handler.codec.http.HttpUtil.isKeepAlive; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; +import static io.netty.handler.codec.http.LastHttpContent.EMPTY_LAST_CONTENT; +import static java.nio.charset.StandardCharsets.UTF_8; + +public class NettyContext implements DefaultContext, ChannelFutureListener { + + private static final HttpHeaders NO_TRAILING = EmptyHttpHeaders.INSTANCE; + // BUG: NVD-CWE-Other Other + // final DefaultHttpHeaders setHeaders = new DefaultHttpHeaders(false); + // FIXED: + final DefaultHttpHeaders setHeaders = new DefaultHttpHeaders(true); + private final int bufferSize; + InterfaceHttpPostRequestDecoder decoder; + private Router router; + private Route route; + ChannelHandlerContext ctx; + private HttpRequest req; + private String path; + private HttpResponseStatus status = HttpResponseStatus.OK; + private boolean responseStarted; + private QueryString query; + private Formdata form; + private Multipart multipart; + private List files; + private ValueNode headers; + private Map pathMap = Collections.EMPTY_MAP; + private MediaType responseType; + private Map attributes = new HashMap<>(); + private long contentLength = -1; + private boolean needsFlush; + private Map cookies; + private Map responseCookies; + private Boolean resetHeadersOnError; + NettyWebSocket webSocket; + + public NettyContext(ChannelHandlerContext ctx, HttpRequest req, Router router, String path, + int bufferSize) { + this.path = path; + this.ctx = ctx; + this.req = req; + this.router = router; + this.bufferSize = bufferSize; + } + + @Nonnull @Override public Router getRouter() { + return router; + } + + /* ********************************************************************************************** + * Request methods: + * ********************************************************************************************** + */ + + @Nonnull @Override public Map getAttributes() { + return attributes; + } + + @Nonnull @Override public String getMethod() { + return req.method().asciiName().toUpperCase().toString(); + } + + @Nonnull @Override public Route getRoute() { + return route; + } + + @Nonnull @Override public Context setRoute(@Nonnull Route route) { + this.route = route; + return this; + } + + @Nonnull @Override public final String pathString() { + return path; + } + + @Nonnull @Override public Map pathMap() { + return pathMap; + } + + @Nonnull @Override public Context setPathMap(@Nonnull Map pathMap) { + this.pathMap = pathMap; + return this; + } + + @Override public final boolean isInIoThread() { + return ctx.channel().eventLoop().inEventLoop(); + } + + @Nonnull @Override public Context dispatch(@Nonnull Runnable action) { + return dispatch(router.getWorker(), action); + } + + @Override public Context dispatch(Executor executor, Runnable action) { + executor.execute(action); + return this; + } + + @Nonnull @Override public Context detach(@Nonnull Route.Handler next) throws Exception { + next.apply(this); + return this; + } + + @Nonnull @Override public QueryString query() { + if (query == null) { + String uri = req.uri(); + int q = uri.indexOf('?'); + query = QueryString.create(this, q >= 0 ? uri.substring(q + 1) : null); + } + return query; + } + + @Nonnull @Override public Formdata form() { + if (form == null) { + form = Formdata.create(this); + decodeForm(req, form); + } + return form; + } + + @Nonnull @Override public Multipart multipart() { + if (multipart == null) { + multipart = Multipart.create(this); + form = multipart; + decodeForm(req, multipart); + } + return multipart; + } + + @Nonnull @Override public Value header(@Nonnull String name) { + return Value.create(this, name, req.headers().getAll(name)); + } + + @Nonnull @Override public String getRemoteAddress() { + InetSocketAddress remoteAddress = (InetSocketAddress) ctx.channel().remoteAddress(); + return remoteAddress.getAddress().getHostAddress(); + } + + @Nonnull @Override public String getProtocol() { + return req.protocolVersion().text(); + } + + @Nonnull @Override public String getScheme() { + // TODO: review if we add websocket or https + return "http"; + } + + @Nonnull @Override public ValueNode header() { + if (headers == null) { + Map> headerMap = new LinkedHashMap<>(); + HttpHeaders headers = req.headers(); + Set names = headers.names(); + for (String name : names) { + headerMap.put(name, headers.getAll(name)); + } + this.headers = Value.hash(this, headerMap); + } + return headers; + } + + @Nonnull @Override public Body body() { + if (decoder != null && decoder.hasNext()) { + return new NettyBody(this, (HttpData) decoder.next(), HttpUtil.getContentLength(req, -1L)); + } + return Body.empty(this); + } + + @Override public @Nonnull Map cookieMap() { + if (this.cookies == null) { + this.cookies = Collections.emptyMap(); + String cookieString = req.headers().get(HttpHeaderNames.COOKIE); + if (cookieString != null) { + Set cookies = ServerCookieDecoder.STRICT + .decode(cookieString); + if (cookies.size() > 0) { + this.cookies = new LinkedHashMap<>(cookies.size()); + for (io.netty.handler.codec.http.cookie.Cookie it : cookies) { + this.cookies.put(it.name(), it.value()); + } + } + } + } + return this.cookies; + } + + @Nonnull @Override public Context upgrade(WebSocket.Initializer handler) { + try { + responseStarted = true; + String webSocketURL = getProtocol() + "://" + req.headers().get(HttpHeaderNames.HOST) + path; + WebSocketDecoderConfig config = WebSocketDecoderConfig.newBuilder() + .allowExtensions(true) + .allowMaskMismatch(false) + .withUTF8Validator(false) + .maxFramePayloadLength(WebSocket.MAX_BUFFER_SIZE) + .build(); + webSocket = new NettyWebSocket(this); + handler.init(Context.readOnly(this), webSocket); + DefaultFullHttpRequest fullHttpRequest = new DefaultFullHttpRequest(req.protocolVersion(), + req.method(), req.uri(), Unpooled.EMPTY_BUFFER, req.headers(), EmptyHttpHeaders.INSTANCE); + WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(webSocketURL, + null, config); + WebSocketServerHandshaker handshaker = factory.newHandshaker(fullHttpRequest); + handshaker.handshake(ctx.channel(), fullHttpRequest, setHeaders, ctx.newPromise()) + .addListener(future -> { + if (future.isSuccess()) { + webSocket.fireConnect(); + } + }); + Config conf = getRouter().getConfig(); + long timeout = conf.hasPath("websocket.idleTimeout") + ? conf.getDuration("websocket.idleTimeout", TimeUnit.MINUTES) + : 5; + if (timeout > 0) { + IdleStateHandler idle = new IdleStateHandler(timeout, 0, 0, TimeUnit.MINUTES); + ctx.pipeline().addBefore("handler", "idle", idle); + } + } catch (Throwable x) { + sendError(x); + } + return this; + } + + /* ********************************************************************************************** + * Response methods: + * ********************************************************************************************** + */ + + @Nonnull @Override public StatusCode getResponseCode() { + return StatusCode.valueOf(this.status.code()); + } + + @Nonnull @Override public Context setResponseCode(int statusCode) { + this.status = HttpResponseStatus.valueOf(statusCode); + return this; + } + + @Nonnull @Override public Context setResponseHeader(@Nonnull String name, @Nonnull String value) { + setHeaders.set(name, value); + return this; + } + + @Nonnull @Override public Context removeResponseHeader(@Nonnull String name) { + setHeaders.remove(name); + return this; + } + + @Nonnull @Override public Context removeResponseHeaders() { + setHeaders.clear(); + return this; + } + + @Nonnull @Override public MediaType getResponseType() { + return responseType == null ? MediaType.text : responseType; + } + + @Nonnull @Override public Context setDefaultResponseType(@Nonnull MediaType contentType) { + if (responseType == null) { + setResponseType(contentType, contentType.getCharset()); + } + return this; + } + + @Override public final Context setResponseType(MediaType contentType, Charset charset) { + this.responseType = contentType; + setHeaders.set(CONTENT_TYPE, contentType.toContentTypeHeader(charset)); + return this; + } + + @Nonnull @Override public Context setResponseType(@Nonnull String contentType) { + this.responseType = MediaType.valueOf(contentType); + setHeaders.set(CONTENT_TYPE, contentType); + return this; + } + + @Nonnull @Override public Context setResponseLength(long length) { + contentLength = length; + setHeaders.set(CONTENT_LENGTH, Long.toString(length)); + return this; + } + + @Override public long getResponseLength() { + return contentLength; + } + + @Nonnull public Context setResponseCookie(@Nonnull Cookie cookie) { + if (responseCookies == null) { + responseCookies = new HashMap<>(); + } + cookie.setPath(cookie.getPath(getContextPath())); + responseCookies.put(cookie.getName(), cookie.toCookieString()); + setHeaders.remove(SET_COOKIE); + for (String cookieString : responseCookies.values()) { + setHeaders.add(SET_COOKIE, cookieString); + } + return this; + } + + @Nonnull @Override public PrintWriter responseWriter(MediaType type, Charset charset) { + responseStarted = true; + setResponseType(type, charset); + + return new PrintWriter(new NettyWriter(newOutputStream(), charset)); + } + + @Nonnull @Override public Sender responseSender() { + responseStarted = true; + prepareChunked(); + ctx.write(new DefaultHttpResponse(req.protocolVersion(), status, setHeaders)); + return new NettySender(this, ctx); + } + + @Nonnull @Override public OutputStream responseStream() { + return newOutputStream(); + } + + @Nonnull @Override public Context send(@Nonnull String data) { + return send(copiedBuffer(data, UTF_8)); + } + + @Override public final Context send(String data, Charset charset) { + return send(copiedBuffer(data, charset)); + } + + @Override public final Context send(byte[] data) { + return send(wrappedBuffer(data)); + } + + @Nonnull @Override public Context send(@Nonnull byte[]... data) { + return send(Unpooled.wrappedBuffer(data)); + } + + @Nonnull @Override public Context send(@Nonnull ByteBuffer[] data) { + return send(Unpooled.wrappedBuffer(data)); + } + + @Override public final Context send(ByteBuffer data) { + return send(wrappedBuffer(data)); + } + + private Context send(@Nonnull ByteBuf data) { + responseStarted = true; + setHeaders.set(CONTENT_LENGTH, Long.toString(data.readableBytes())); + DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, + data, setHeaders, NO_TRAILING); + if (ctx.channel().eventLoop().inEventLoop()) { + needsFlush = true; + ctx.write(response).addListener(this); + } else { + ctx.writeAndFlush(response).addListener(this); + } + return this; + } + + public void flush() { + if (needsFlush) { + needsFlush = false; + ctx.flush(); + } + } + + @Nonnull @Override public Context send(@Nonnull ReadableByteChannel channel) { + prepareChunked(); + DefaultHttpResponse rsp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status, setHeaders); + responseStarted = true; + int bufferSize = contentLength > 0 ? (int) contentLength : this.bufferSize; + ctx.channel().eventLoop().execute(() -> { + // Headers + ctx.write(rsp, ctx.voidPromise()); + // Body + ctx.write(new ChunkedNioStream(channel, bufferSize), ctx.voidPromise()); + // Finish + ctx.writeAndFlush(EMPTY_LAST_CONTENT).addListener(this); + }); + return this; + } + + @Nonnull @Override public Context send(@Nonnull InputStream in) { + if (in instanceof FileInputStream) { + // use channel + return send(((FileInputStream) in).getChannel()); + } + try { + prepareChunked(); + long len = responseLength(); + ByteRange range = ByteRange.parse(req.headers().get(RANGE), len) + .apply(this); + ChunkedStream chunkedStream = new ChunkedStream(range.apply(in), bufferSize); + + DefaultHttpResponse rsp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status, setHeaders); + responseStarted = true; + ctx.channel().eventLoop().execute(() -> { + // Headers + ctx.write(rsp, ctx.voidPromise()); + // Body + ctx.write(chunkedStream, ctx.voidPromise()); + // Finish + ctx.writeAndFlush(EMPTY_LAST_CONTENT).addListener(this); + }); + return this; + } catch (Exception x) { + throw SneakyThrows.propagate(x); + } + } + + @Nonnull @Override public Context send(@Nonnull FileChannel file) { + try { + long len = file.size(); + setHeaders.set(CONTENT_LENGTH, Long.toString(len)); + + ByteRange range = ByteRange.parse(req.headers().get(RANGE), len) + .apply(this); + + DefaultHttpResponse rsp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status, setHeaders); + responseStarted = true; + ctx.channel().eventLoop().execute(() -> { + // Headers + ctx.write(rsp, ctx.voidPromise()); + // Body + ctx.write(new DefaultFileRegion(file, range.getStart(), range.getEnd()), ctx.voidPromise()); + // Finish + ctx.writeAndFlush(EMPTY_LAST_CONTENT).addListener(this); + }); + } catch (IOException x) { + throw SneakyThrows.propagate(x); + } + return this; + } + + @Override public boolean isResponseStarted() { + return responseStarted; + } + + @Override public boolean getResetHeadersOnError() { + return resetHeadersOnError == null + ? getRouter().getRouterOptions().getResetHeadersOnError() + : resetHeadersOnError.booleanValue(); + } + + @Override public Context setResetHeadersOnError(boolean value) { + this.resetHeadersOnError = value; + return this; + } + + @Nonnull @Override public Context send(StatusCode statusCode) { + responseStarted = true; + if (!setHeaders.contains(CONTENT_LENGTH)) { + setHeaders.set(CONTENT_LENGTH, "0"); + } + DefaultFullHttpResponse rsp = new DefaultFullHttpResponse(HTTP_1_1, + HttpResponseStatus.valueOf(statusCode.value()), Unpooled.EMPTY_BUFFER, setHeaders, + NO_TRAILING); + ctx.writeAndFlush(rsp).addListener(this); + return this; + } + + @Override public void operationComplete(ChannelFuture future) { + try { + ifSaveSession(); + destroy(future.cause()); + } finally { + if (!isKeepAlive(req)) { + future.channel().close(); + } + } + } + + private void ifSaveSession() { + Session session = (Session) getAttributes().get(Session.NAME); + if (session != null && (session.isNew() || session.isModify())) { + SessionStore store = router.getSessionStore(); + store.saveSession(this, session); + } + } + + private NettyOutputStream newOutputStream() { + prepareChunked(); + return new NettyOutputStream(ctx, bufferSize, + new DefaultHttpResponse(req.protocolVersion(), status, setHeaders), this); + } + + void destroy(Throwable cause) { + if (cause != null) { + if (Server.connectionLost(cause)) { + router.getLog() + .debug("exception found while sending response {} {}", getMethod(), pathString(), + cause); + } else { + router.getLog() + .error("exception found while sending response {} {}", getMethod(), pathString(), + cause); + } + } + if (files != null) { + for (FileUpload file : files) { + try { + file.destroy(); + } catch (Exception x) { + router.getLog().debug("file upload destroy resulted in exception", x); + } + } + files = null; + } + if (decoder != null) { + try { + decoder.destroy(); + } catch (Exception x) { + router.getLog().debug("body decoder destroy resulted in exception", x); + } + decoder = null; + } + release(req); + } + + private FileUpload register(FileUpload upload) { + if (this.files == null) { + this.files = new ArrayList<>(); + } + this.files.add(upload); + return upload; + } + + private void decodeForm(HttpRequest req, Formdata form) { + if (decoder == null) { + // empty/bad form + return; + } + try { + while (decoder.hasNext()) { + HttpData next = (HttpData) decoder.next(); + if (next.getHttpDataType() == InterfaceHttpData.HttpDataType.FileUpload) { + ((Multipart) form).put(next.getName(), + register(new NettyFileUpload(router.getTmpdir(), + (io.netty.handler.codec.http.multipart.FileUpload) next))); + } else { + form.put(next.getName(), next.getString(UTF_8)); + } + } + } catch (HttpPostRequestDecoder.EndOfDataDecoderException x) { + // ignore, silly netty + } catch (Exception x) { + throw SneakyThrows.propagate(x); + } finally { + release(req); + } + } + + private static void release(HttpRequest req) { + if (req instanceof ReferenceCounted) { + ReferenceCounted ref = (ReferenceCounted) req; + if (ref.refCnt() > 0) { + ref.release(); + } + } + } + + private long responseLength() { + String len = setHeaders.get(CONTENT_LENGTH); + return len == null ? -1 : Long.parseLong(len); + } + + private void prepareChunked() { + // remove flusher, doesn't play well with streaming/chunked responses + ChannelPipeline pipeline = ctx.pipeline(); + if (pipeline.get("chunker") == null) { + pipeline.addAfter("encoder", "chunker", new ChunkedWriteHandler()); + } + if (!setHeaders.contains(CONTENT_LENGTH)) { + setHeaders.set(TRANSFER_ENCODING, CHUNKED); + } + } + + @Override public String toString() { + return getMethod() + " " + pathString(); + } +} diff --git a/Java/NettyHandlerAdapter.java b/Java/NettyHandlerAdapter.java new file mode 100644 index 0000000000000000000000000000000000000000..1cac48a93fa1e05d4d715832dee3956e0e1290c4 --- /dev/null +++ b/Java/NettyHandlerAdapter.java @@ -0,0 +1,285 @@ +/* + * Copyright 2013 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 ratpack.server.internal; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufUtil; +import io.netty.buffer.Unpooled; +import io.netty.channel.*; +import io.netty.handler.codec.http.*; +import io.netty.handler.ssl.SslHandler; +import io.netty.handler.ssl.SslHandshakeCompletionEvent; +import io.netty.handler.timeout.IdleStateEvent; +import io.netty.util.AttributeKey; +import io.netty.util.CharsetUtil; +import io.netty.util.ReferenceCountUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import ratpack.exec.ExecController; +import ratpack.func.Action; +import ratpack.handling.Handler; +import ratpack.handling.Handlers; +import ratpack.handling.internal.ChainHandler; +import ratpack.handling.internal.DefaultContext; +import ratpack.handling.internal.DescribingHandler; +import ratpack.handling.internal.DescribingHandlers; +import ratpack.http.Headers; +import ratpack.http.MutableHeaders; +import ratpack.http.Response; +import ratpack.http.internal.*; +import ratpack.registry.Registry; +import ratpack.render.internal.DefaultRenderController; +import ratpack.server.ServerConfig; + +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.security.cert.X509Certificate; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.CharBuffer; +import java.nio.channels.ClosedChannelException; +import java.time.Clock; +import java.util.concurrent.atomic.AtomicBoolean; + +@ChannelHandler.Sharable +public class NettyHandlerAdapter extends ChannelInboundHandlerAdapter { + + private static final AttributeKey> CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY = AttributeKey.valueOf(NettyHandlerAdapter.class, "subscriber"); + private static final AttributeKey BODY_ACCUMULATOR_KEY = AttributeKey.valueOf(NettyHandlerAdapter.class, "requestBody"); + private static final AttributeKey CLIENT_CERT_KEY = AttributeKey.valueOf(NettyHandlerAdapter.class, "principal"); + + private final static Logger LOGGER = LoggerFactory.getLogger(NettyHandlerAdapter.class); + + private final Handler[] handlers; + + private final DefaultContext.ApplicationConstants applicationConstants; + + private final Registry serverRegistry; + private final boolean development; + private final Clock clock; + + public NettyHandlerAdapter(Registry serverRegistry, Handler handler) throws Exception { + this.handlers = ChainHandler.unpack(handler); + this.serverRegistry = serverRegistry; + this.applicationConstants = new DefaultContext.ApplicationConstants(this.serverRegistry, new DefaultRenderController(), serverRegistry.get(ExecController.class), Handlers.notFound()); + this.development = serverRegistry.get(ServerConfig.class).isDevelopment(); + this.clock = serverRegistry.get(Clock.class); + } + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + ctx.read(); + super.channelActive(ctx); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + if (msg instanceof HttpRequest) { + newRequest(ctx, (HttpRequest) msg); + } else if (msg instanceof HttpContent) { + ((HttpContent) msg).touch(); + RequestBodyAccumulator bodyAccumulator = ctx.channel().attr(BODY_ACCUMULATOR_KEY).get(); + if (bodyAccumulator == null) { + ((HttpContent) msg).release(); + } else { + bodyAccumulator.add((HttpContent) msg); + } + + // Read for the next request proactively so that we + // detect if the client closes the connection. + if (msg instanceof LastHttpContent) { + ctx.channel().read(); + } + } else { + Action subscriber = ctx.channel().attr(CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY).get(); + if (subscriber == null) { + super.channelRead(ctx, ReferenceCountUtil.touch(msg)); + } else { + subscriber.execute(ReferenceCountUtil.touch(msg)); + } + } + } + + private void newRequest(ChannelHandlerContext ctx, HttpRequest nettyRequest) throws Exception { + if (!nettyRequest.decoderResult().isSuccess()) { + LOGGER.debug("Failed to decode HTTP request.", nettyRequest.decoderResult().cause()); + sendError(ctx, HttpResponseStatus.BAD_REQUEST); + return; + } + + Headers requestHeaders = new NettyHeadersBackedHeaders(nettyRequest.headers()); + + //Find the content length we will use this as an indicator of a body + Long contentLength = HttpUtil.getContentLength(nettyRequest, -1L); + String transferEncoding = requestHeaders.get(HttpHeaderNames.TRANSFER_ENCODING); + + //If there is a content length or transfer encoding that indicates there is a body + boolean hasBody = (contentLength > 0) || (transferEncoding != null); + + RequestBody requestBody = hasBody ? new RequestBody(contentLength, nettyRequest, ctx) : null; + + Channel channel = ctx.channel(); + + if (requestBody != null) { + channel.attr(BODY_ACCUMULATOR_KEY).set(requestBody); + } + InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress(); + InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress(); + + ConnectionIdleTimeout connectionIdleTimeout = ConnectionIdleTimeout.of(channel); + + DefaultRequest request = new DefaultRequest( + clock.instant(), + requestHeaders, + nettyRequest.method(), + nettyRequest.protocolVersion(), + nettyRequest.uri(), + remoteAddress, + socketAddress, + serverRegistry.get(ServerConfig.class), + requestBody, + connectionIdleTimeout, + channel.attr(CLIENT_CERT_KEY).get() + ); + // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') + // HttpHeaders nettyHeaders = new DefaultHttpHeaders(false); + // FIXED: + HttpHeaders nettyHeaders = new DefaultHttpHeaders(); + MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyHeaders); + AtomicBoolean transmitted = new AtomicBoolean(false); + + DefaultResponseTransmitter responseTransmitter = new DefaultResponseTransmitter(transmitted, channel, clock, nettyRequest, request, nettyHeaders, requestBody); + + ctx.channel().attr(DefaultResponseTransmitter.ATTRIBUTE_KEY).set(responseTransmitter); + + Action> subscribeHandler = thing -> { + transmitted.set(true); + ctx.channel().attr(CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY).set(thing); + }; + + DefaultContext.RequestConstants requestConstants = new DefaultContext.RequestConstants( + applicationConstants, + request, + channel, + responseTransmitter, + subscribeHandler + ); + + Response response = new DefaultResponse(responseHeaders, ctx.alloc(), responseTransmitter); + requestConstants.response = response; + + DefaultContext.start(channel.eventLoop(), requestConstants, serverRegistry, handlers, execution -> { + if (!transmitted.get()) { + Handler lastHandler = requestConstants.handler; + StringBuilder description = new StringBuilder(); + description + .append("No response sent for ") + .append(request.getMethod().getName()) + .append(" request to ") + .append(request.getUri()); + + if (lastHandler != null) { + description.append(" (last handler: "); + + if (lastHandler instanceof DescribingHandler) { + ((DescribingHandler) lastHandler).describeTo(description); + } else { + DescribingHandlers.describeTo(lastHandler, description); + } + description.append(")"); + } + + String message = description.toString(); + LOGGER.warn(message); + + response.getHeaders().clear(); + + ByteBuf body; + if (development) { + CharBuffer charBuffer = CharBuffer.wrap(message); + body = ByteBufUtil.encodeString(ctx.alloc(), charBuffer, CharsetUtil.UTF_8); + response.contentType(HttpHeaderConstants.PLAIN_TEXT_UTF8); + } else { + body = Unpooled.EMPTY_BUFFER; + } + + response.getHeaders().set(HttpHeaderConstants.CONTENT_LENGTH, body.readableBytes()); + responseTransmitter.transmit(HttpResponseStatus.INTERNAL_SERVER_ERROR, body); + } + }); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + if (!isIgnorableException(cause)) { + LOGGER.error("", cause); + if (ctx.channel().isActive()) { + sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR); + } + } + } + + @Override + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { + if (evt instanceof IdleStateEvent) { + ConnectionClosureReason.setIdle(ctx.channel()); + ctx.close(); + } + if (evt instanceof SslHandshakeCompletionEvent && ((SslHandshakeCompletionEvent) evt).isSuccess()) { + SSLEngine engine = ctx.pipeline().get(SslHandler.class).engine(); + if (engine.getWantClientAuth() || engine.getNeedClientAuth()) { + try { + X509Certificate clientCert = engine.getSession().getPeerCertificateChain()[0]; + ctx.channel().attr(CLIENT_CERT_KEY).set(clientCert); + } catch (SSLPeerUnverifiedException ignore) { + // ignore - there is no way to avoid this exception that I can determine + } + } + } + + super.userEventTriggered(ctx, evt); + } + + @Override + public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { + DefaultResponseTransmitter responseTransmitter = ctx.channel().attr(DefaultResponseTransmitter.ATTRIBUTE_KEY).get(); + if (responseTransmitter != null) { + responseTransmitter.writabilityChanged(); + } + } + + private static boolean isIgnorableException(Throwable throwable) { + if (throwable instanceof ClosedChannelException) { + return true; + } else if (throwable instanceof IOException) { + // There really does not seem to be a better way of detecting this kind of exception + String message = throwable.getMessage(); + return message != null && message.endsWith("Connection reset by peer"); + } else { + return false; + } + } + + private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { + FullHttpResponse response = new DefaultFullHttpResponse( + HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8)); + response.headers().set(HttpHeaderConstants.CONTENT_TYPE, HttpHeaderConstants.PLAIN_TEXT_UTF8); + + // Close the connection as soon as the error message is sent. + ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); + } +} diff --git a/Java/NettyHttpHeaders.java b/Java/NettyHttpHeaders.java new file mode 100644 index 0000000000000000000000000000000000000000..c3137c572f31320b687cd336470a3524f7967f8a --- /dev/null +++ b/Java/NettyHttpHeaders.java @@ -0,0 +1,132 @@ +/* + * Copyright 2017-2019 original 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 io.micronaut.http.netty; + +import io.micronaut.core.annotation.Internal; +import io.micronaut.core.convert.ArgumentConversionContext; +import io.micronaut.core.convert.ConversionService; +import io.micronaut.http.MutableHttpHeaders; +import io.netty.handler.codec.http.DefaultHttpHeaders; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +/** + * Delegates to Netty's {@link io.netty.handler.codec.http.HttpHeaders}. + * + * @author Graeme Rocher + * @since 1.0 + */ +@Internal +public class NettyHttpHeaders implements MutableHttpHeaders { + + io.netty.handler.codec.http.HttpHeaders nettyHeaders; + final ConversionService conversionService; + + /** + * @param nettyHeaders The Netty Http headers + * @param conversionService The conversion service + */ + public NettyHttpHeaders(io.netty.handler.codec.http.HttpHeaders nettyHeaders, ConversionService conversionService) { + this.nettyHeaders = nettyHeaders; + this.conversionService = conversionService; + } + + /** + * Default constructor. + */ + public NettyHttpHeaders() { + // BUG: CWE-444 Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') + // this.nettyHeaders = new DefaultHttpHeaders(false); + // FIXED: + this.nettyHeaders = new DefaultHttpHeaders(); + this.conversionService = ConversionService.SHARED; + } + + /** + * @return The underlying Netty headers. + */ + public io.netty.handler.codec.http.HttpHeaders getNettyHeaders() { + return nettyHeaders; + } + + /** + * Sets the underlying netty headers. + * + * @param headers The Netty http headers + */ + void setNettyHeaders(io.netty.handler.codec.http.HttpHeaders headers) { + this.nettyHeaders = headers; + } + + @Override + public Optional get(CharSequence name, ArgumentConversionContext conversionContext) { + List values = nettyHeaders.getAll(name); + if (values.size() > 0) { + if (values.size() == 1 || !isCollectionOrArray(conversionContext.getArgument().getType())) { + return conversionService.convert(values.get(0), conversionContext); + } else { + return conversionService.convert(values, conversionContext); + } + } + return Optional.empty(); + } + + private boolean isCollectionOrArray(Class clazz) { + return clazz.isArray() || Collection.class.isAssignableFrom(clazz); + } + + @Override + public List getAll(CharSequence name) { + return nettyHeaders.getAll(name); + } + + @Override + public Set names() { + return nettyHeaders.names(); + } + + @Override + public Collection> values() { + Set names = names(); + List> values = new ArrayList<>(); + for (String name : names) { + values.add(getAll(name)); + } + return Collections.unmodifiableList(values); + } + + @Override + public String get(CharSequence name) { + return nettyHeaders.get(name); + } + + @Override + public MutableHttpHeaders add(CharSequence header, CharSequence value) { + nettyHeaders.add(header, value); + return this; + } + + @Override + public MutableHttpHeaders remove(CharSequence header) { + nettyHeaders.remove(header); + return this; + } +} diff --git a/Java/NotificationsPageIT.java b/Java/NotificationsPageIT.java new file mode 100644 index 0000000000000000000000000000000000000000..eb5cf5f69caf635bb46a729f144c857d21b464b9 --- /dev/null +++ b/Java/NotificationsPageIT.java @@ -0,0 +1,90 @@ +/******************************************************************************* + * This file is part of OpenNMS(R). + * + * Copyright (C) 2011-2014 The OpenNMS Group, Inc. + * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. + * + * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. + * + * OpenNMS(R) is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * OpenNMS(R) is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with OpenNMS(R). If not, see: + * http://www.gnu.org/licenses/ + * + * For more information contact: + * OpenNMS(R) Licensing + * http://www.opennms.org/ + * http://www.opennms.com/ + *******************************************************************************/ + +package org.opennms.smoketest; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.openqa.selenium.By; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class NotificationsPageIT extends OpenNMSSeleniumIT { + + @Before + public void setUp() throws Exception { + notificationsPage(); + } + + @Test + public void testAllTextIsPresent() throws Exception { + assertEquals(3, countElementsMatchingCss("div.card-header")); + findElementByXpath("//span[text()='Notification queries']"); + findElementByXpath("//span[text()='Outstanding and Acknowledged Notices']"); + findElementByXpath("//span[text()='Notification Escalation']"); + } + + @Test + public void testAllLinksArePresent() { + findElementByLink("Your outstanding notices"); + findElementByLink("All outstanding notices"); + findElementByLink("All acknowledged notices"); + } + + @Test + public void testAllFormsArePresent() { + findElementByXpath("//button[@id='btn_search_by_notice' and @type='submit']"); + findElementByXpath("//button[@id='btn_search_by_user' and @type='submit']"); + } + + @Test + public void testAllLinks() { + findElementByLink("Your outstanding notices").click(); + findElementByXpath("//span[@class='label label-default' and contains(text(), 'admin was notified')]"); + findElementByLink("[Remove all]"); + findElementByLink("Sent Time"); + findElementByXpath("//button[@type='button' and text()='Acknowledge Notices']"); + + notificationsPage(); + findElementByLink("All outstanding notices").click(); + findElementByXpath("//p//strong[text()='outstanding']"); + findElementByLink("[Show acknowledged]"); + findElementByLink("Respond Time"); + assertElementDoesNotHaveText(By.xpath("//span[@class='label label-default']"), "admin was notified [-]"); + + notificationsPage(); + findElementByLink("All acknowledged notices").click(); + findElementByXpath("//p//strong[text()='acknowledged']"); + findElementByLink("[Show outstanding]"); + findElementByLink("Respond Time"); + assertElementDoesNotHaveText(By.xpath("//span[@class='label label-default']"), "admin was notified [-]"); + } +} diff --git a/Java/Opale.java b/Java/Opale.java new file mode 100644 index 0000000000000000000000000000000000000000..a30858b03106fa415e752cc739362b3bad08f7d1 --- /dev/null +++ b/Java/Opale.java @@ -0,0 +1,272 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.svek.image; + +import java.awt.geom.Point2D; + +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.Direction; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.graphic.AbstractTextBlock; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.UPath; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; +import net.sourceforge.plantuml.utils.MathUtils; + +public class Opale extends AbstractTextBlock implements TextBlock { + + private static final int cornersize = 10; + private final HColor noteBackgroundColor; + private final HColor borderColor; + private final int marginX1 = 6; + private final int marginX2 = 15; + private final int marginY = 5; + private final double shadowing2; + private Direction strategy; + private Point2D pp1; + private Point2D pp2; + private final boolean withLink; + private double roundCorner; + private final UStroke stroke; + + private final TextBlock textBlock; + + public Opale(double shadowing, HColor borderColor, HColor noteBackgroundColor, TextBlock textBlock, + boolean withLink, UStroke stroke) { + this.noteBackgroundColor = noteBackgroundColor; + this.withLink = withLink; + this.shadowing2 = shadowing; + this.borderColor = borderColor; + this.textBlock = textBlock; + this.stroke = stroke; + } + + public void setRoundCorner(double roundCorner) { + this.roundCorner = roundCorner; + } + + public void setOpale(Direction strategy, Point2D pp1, Point2D pp2) { + this.strategy = strategy; + this.pp1 = pp1; + this.pp2 = pp2; + } + + final private double getWidth(StringBounder stringBounder) { + return textBlock.calculateDimension(stringBounder).getWidth() + marginX1 + marginX2; + } + + final private double getHeight(StringBounder stringBounder) { + final Dimension2D size = textBlock.calculateDimension(stringBounder); + return size.getHeight() + 2 * marginY; + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + final double height = getHeight(stringBounder); + final double width = getWidth(stringBounder); + return new Dimension2DDouble(width, height); + } + + final public void drawU(UGraphic ug) { + final StringBounder stringBounder = ug.getStringBounder(); + ug = ug.apply(noteBackgroundColor.bg()).apply(borderColor); + final UPath polygon; + if (withLink == false) { + polygon = getPolygonNormal(stringBounder); + } else if (strategy == Direction.LEFT) { + polygon = getPolygonLeft(stringBounder, pp1, pp2); + } else if (strategy == Direction.RIGHT) { + polygon = getPolygonRight(stringBounder, pp1, pp2); + } else if (strategy == Direction.UP) { + polygon = getPolygonUp(stringBounder, pp1, pp2); + } else if (strategy == Direction.DOWN) { + polygon = getPolygonDown(stringBounder, pp1, pp2); + } else { + throw new IllegalArgumentException(); + } + polygon.setDeltaShadow(shadowing2); + if (stroke != null) + ug = ug.apply(stroke); + ug.draw(polygon); + ug.draw(getCorner(getWidth(stringBounder), roundCorner)); + textBlock.drawU(ug.apply(new UTranslate(marginX1, marginY))); + } + + private UPath getPolygonNormal(final StringBounder stringBounder) { + return getPolygonNormal(getWidth(stringBounder), getHeight(stringBounder), roundCorner); + } + + public static UPath getCorner(double width, double roundCorner) { + final UPath path = new UPath(); + path.moveTo(width - cornersize, 0); + if (roundCorner == 0) { + path.lineTo(width - cornersize, cornersize); + } else { + path.lineTo(width - cornersize, cornersize - roundCorner / 4); + path.arcTo(new Point2D.Double(width - cornersize + roundCorner / 4, cornersize), roundCorner / 4, 0, 0); + } + path.lineTo(width, cornersize); + path.lineTo(width - cornersize, 0); + path.closePath(); + return path; + } + + public static UPath getPolygonNormal(double width, double height, double roundCorner) { + final UPath polygon = new UPath(); + if (roundCorner == 0) { + polygon.moveTo(0, 0); + polygon.lineTo(0, height); + polygon.lineTo(width, height); + polygon.lineTo(width, cornersize); + polygon.lineTo(width - cornersize, 0); + polygon.lineTo(0, 0); + } else { + polygon.moveTo(0, roundCorner / 2); + polygon.lineTo(0, height - roundCorner / 2); + polygon.arcTo(new Point2D.Double(roundCorner / 2, height), roundCorner / 2, 0, 0); + polygon.lineTo(width - roundCorner / 2, height); + polygon.arcTo(new Point2D.Double(width, height - roundCorner / 2), roundCorner / 2, 0, 0); + polygon.lineTo(width, cornersize); + polygon.lineTo(width - cornersize, 0); + polygon.lineTo(roundCorner / 2, 0); + polygon.arcTo(new Point2D.Double(0, roundCorner / 2), roundCorner / 2, 0, 0); + } + polygon.closePath(); + return polygon; + } + + private final double delta = 4; + + private UPath getPolygonLeft(final StringBounder stringBounder, final Point2D pp1, final Point2D pp2) { + final UPath polygon = new UPath(); + polygon.moveTo(0, roundCorner / 2); + + double y1 = pp1.getY() - delta; + y1 = MathUtils.limitation(y1, 0, getHeight(stringBounder) - 2 * delta); + polygon.lineTo(0, y1); + polygon.lineTo(pp2.getX(), pp2.getY()); + polygon.lineTo(0, y1 + 2 * delta); + + polygon.lineTo(0, getHeight(stringBounder) - roundCorner / 2); + polygon.arcTo(new Point2D.Double(roundCorner / 2, getHeight(stringBounder)), roundCorner / 2, 0, 0); + polygon.lineTo(getWidth(stringBounder) - roundCorner / 2, getHeight(stringBounder)); + polygon.arcTo(new Point2D.Double(getWidth(stringBounder), getHeight(stringBounder) - roundCorner / 2), + roundCorner / 2, 0, 0); + polygon.lineTo(getWidth(stringBounder), cornersize); + polygon.lineTo(getWidth(stringBounder) - cornersize, 0); + polygon.lineTo(roundCorner / 2, 0); + polygon.arcTo(new Point2D.Double(0, roundCorner / 2), roundCorner / 2, 0, 0); + polygon.closePath(); + return polygon; + } + + private UPath getPolygonRight(final StringBounder stringBounder, final Point2D pp1, final Point2D pp2) { + final UPath polygon = new UPath(); + polygon.moveTo(0, roundCorner / 2); + polygon.lineTo(0, getHeight(stringBounder) - roundCorner / 2); + polygon.arcTo(new Point2D.Double(roundCorner / 2, getHeight(stringBounder)), roundCorner / 2, 0, 0); + polygon.lineTo(getWidth(stringBounder) - roundCorner / 2, getHeight(stringBounder)); + polygon.arcTo(new Point2D.Double(getWidth(stringBounder), getHeight(stringBounder) - roundCorner / 2), + roundCorner / 2, 0, 0); + + double y1 = pp1.getY() - delta; + y1 = MathUtils.limitation(y1, cornersize, getHeight(stringBounder) - 2 * delta); + polygon.lineTo(getWidth(stringBounder), y1 + 2 * delta); + polygon.lineTo(pp2.getX(), pp2.getY()); + polygon.lineTo(getWidth(stringBounder), y1); + + polygon.lineTo(getWidth(stringBounder), cornersize); + polygon.lineTo(getWidth(stringBounder) - cornersize, 0); + polygon.lineTo(roundCorner / 2, 0); + polygon.arcTo(new Point2D.Double(0, roundCorner / 2), roundCorner / 2, 0, 0); + polygon.closePath(); + return polygon; + } + + private UPath getPolygonUp(final StringBounder stringBounder, final Point2D pp1, final Point2D pp2) { + final UPath polygon = new UPath(); + polygon.moveTo(0, roundCorner / 2); + polygon.lineTo(0, getHeight(stringBounder) - roundCorner / 2); + polygon.arcTo(new Point2D.Double(roundCorner / 2, getHeight(stringBounder)), roundCorner / 2, 0, 0); + polygon.lineTo(getWidth(stringBounder) - roundCorner / 2, getHeight(stringBounder)); + polygon.arcTo(new Point2D.Double(getWidth(stringBounder), getHeight(stringBounder) - roundCorner / 2), + roundCorner / 2, 0, 0); + polygon.lineTo(getWidth(stringBounder), cornersize); + polygon.lineTo(getWidth(stringBounder) - cornersize, 0); + + double x1 = pp1.getX() - delta; + x1 = MathUtils.limitation(x1, 0, getWidth(stringBounder) - cornersize); + polygon.lineTo(x1 + 2 * delta, 0); + polygon.lineTo(pp2.getX(), pp2.getY()); + + polygon.lineTo(x1, 0); + polygon.lineTo(roundCorner / 2, 0); + polygon.arcTo(new Point2D.Double(0, roundCorner / 2), roundCorner / 2, 0, 0); + polygon.closePath(); + return polygon; + } + + private UPath getPolygonDown(final StringBounder stringBounder, final Point2D pp1, final Point2D pp2) { + final UPath polygon = new UPath(); + polygon.moveTo(0, roundCorner / 2); + polygon.lineTo(0, getHeight(stringBounder) - roundCorner / 2); + polygon.arcTo(new Point2D.Double(roundCorner / 2, getHeight(stringBounder)), roundCorner / 2, 0, 0); + + double x1 = pp1.getX() - delta; + x1 = MathUtils.limitation(x1, 0, getWidth(stringBounder)); + polygon.lineTo(x1, getHeight(stringBounder)); + polygon.lineTo(pp2.getX(), pp2.getY()); + polygon.lineTo(x1 + 2 * delta, getHeight(stringBounder)); + + polygon.lineTo(getWidth(stringBounder) - roundCorner / 2, getHeight(stringBounder)); + polygon.arcTo(new Point2D.Double(getWidth(stringBounder), getHeight(stringBounder) - roundCorner / 2), + roundCorner / 2, 0, 0); + polygon.lineTo(getWidth(stringBounder), cornersize); + polygon.lineTo(getWidth(stringBounder) - cornersize, 0); + polygon.lineTo(roundCorner / 2, 0); + polygon.arcTo(new Point2D.Double(0, roundCorner / 2), roundCorner / 2, 0, 0); + polygon.closePath(); + return polygon; + } + + public final int getMarginX1() { + return marginX1; + } + +} diff --git a/Java/OpenMeetingsDAO.java b/Java/OpenMeetingsDAO.java new file mode 100644 index 0000000000000000000000000000000000000000..91bea73f7b69868b56d1ac7425cce5cffd2a34ec --- /dev/null +++ b/Java/OpenMeetingsDAO.java @@ -0,0 +1,163 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * 12.10.2011 by frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.modules.openmeetings.manager; + +import java.io.StringWriter; +import java.util.Date; +import java.util.List; + +import javax.annotation.PostConstruct; +import javax.persistence.TypedQuery; + +import org.olat.core.commons.persistence.DB; +import org.olat.core.id.OLATResourceable; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.group.BusinessGroup; +import org.olat.modules.openmeetings.model.OpenMeetingsRoom; +import org.olat.modules.openmeetings.model.OpenMeetingsRoomReference; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.io.xml.CompactWriter; + + +/** + * + * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com + */ +@Service +public class OpenMeetingsDAO { + + @Autowired + private DB dbInstance; + + private XStream xStream; + + @PostConstruct + public void init() { + xStream = XStreamHelper.createXStreamInstance(); + // BUG: CWE-91 XML Injection (aka Blind XPath Injection) + // + // FIXED: + XStreamHelper.allowDefaultPackage(xStream); + xStream.alias("room", OpenMeetingsRoom.class); + xStream.omitField(OpenMeetingsRoom.class, "property"); + xStream.omitField(OpenMeetingsRoom.class, "numOfUsers"); + } + + + public OpenMeetingsRoomReference createReference(final BusinessGroup group, final OLATResourceable courseResource, String subIdentifier, OpenMeetingsRoom room) { + String serialized = serializeRoom(room); + OpenMeetingsRoomReference ref = new OpenMeetingsRoomReference(); + ref.setLastModified(new Date()); + ref.setRoomId(room.getRoomId()); + ref.setConfig(serialized); + ref.setGroup(group); + if(courseResource != null) { + ref.setResourceTypeName(courseResource.getResourceableTypeName()); + ref.setResourceTypeId(courseResource.getResourceableId()); + } + ref.setSubIdentifier(subIdentifier); + dbInstance.getCurrentEntityManager().persist(ref); + return ref; + } + + public List getReferences() { + StringBuilder sb = new StringBuilder(); + sb.append("select ref from ").append(OpenMeetingsRoomReference.class.getName()).append(" ref"); + return dbInstance.getCurrentEntityManager().createQuery(sb.toString(), OpenMeetingsRoomReference.class).getResultList(); + } + + public OpenMeetingsRoomReference getReference(BusinessGroup group, OLATResourceable courseResource, String subIdentifier) { + StringBuilder sb = new StringBuilder(); + sb.append("select ref from ").append(OpenMeetingsRoomReference.class.getName()).append(" ref"); + + boolean where = false; + if(group != null) { + where = and(sb, where); + sb.append(" ref.group.key=:groupKey"); + } + if(courseResource != null) { + where = and(sb, where); + sb.append(" ref.resourceTypeName=:resName and ref.resourceTypeId=:resId"); + } + if(subIdentifier != null) { + where = and(sb, where); + sb.append(" ref.subIdentifier=:subIdentifier"); + } + + TypedQuery query = dbInstance.getCurrentEntityManager().createQuery(sb.toString(), OpenMeetingsRoomReference.class); + + if(group != null) { + query.setParameter("groupKey", group.getKey()); + } + if(courseResource != null) { + query.setParameter("resName", courseResource.getResourceableTypeName()); + query.setParameter("resId", courseResource.getResourceableId()); + } + if(subIdentifier != null) { + query.setParameter("subIdentifier", subIdentifier); + } + + List refs = query.getResultList(); + if(refs.isEmpty()) { + return null; + } + return refs.get(0); + } + + public OpenMeetingsRoomReference updateReference(BusinessGroup group, OLATResourceable courseResource, String subIdentifier, OpenMeetingsRoom room) { + OpenMeetingsRoomReference property = getReference(group, courseResource, subIdentifier); + if(property == null) { + property = createReference(group, courseResource, subIdentifier, room); + + } else { + String serialized = serializeRoom(room); + property.setLastModified(new Date()); + property.setConfig(serialized); + property = dbInstance.getCurrentEntityManager().merge(property); + } + return property; + } + + public void delete(OpenMeetingsRoomReference ref) { + OpenMeetingsRoomReference reloadedRef = dbInstance.getCurrentEntityManager() + .getReference(OpenMeetingsRoomReference.class, ref.getKey()); + dbInstance.getCurrentEntityManager().remove(reloadedRef); + } + + public String serializeRoom(OpenMeetingsRoom room) { + StringWriter writer = new StringWriter(); + xStream.marshal(room, new CompactWriter(writer)); + writer.flush(); + return writer.toString(); + } + + public OpenMeetingsRoom deserializeRoom(String room) { + return (OpenMeetingsRoom)xStream.fromXML(room); + } + + private final boolean and(StringBuilder sb, boolean and) { + if(and) sb.append(" and "); + else sb.append(" where "); + return true; + } +} \ No newline at end of file diff --git a/Java/PGRasterConfig.java b/Java/PGRasterConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..8c1f58b0cc78e7dd1b8e24341c4369c654cc60fc --- /dev/null +++ b/Java/PGRasterConfig.java @@ -0,0 +1,238 @@ +/* + * GeoTools - The Open Source Java GIS Toolkit + * http://geotools.org + * + * (C) 2002-2019, Open Source Geospatial Foundation (OSGeo) + * + * 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; + * version 2.1 of the License. + * + * 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. + */ +package org.geotools.gce.pgraster; + +import com.google.common.annotations.VisibleForTesting; +import java.io.Closeable; +import java.io.File; +import java.sql.SQLException; +import java.util.Optional; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.naming.NamingException; +import javax.sql.DataSource; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import org.apache.commons.dbcp.BasicDataSource; +import org.geotools.data.jdbc.datasource.DBCPDataSource; +import org.geotools.util.factory.GeoTools; +import org.geotools.util.logging.Logging; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +/** + * Configuration for a {@link PGRasterReader}. + * + *

Configuration is stored as XML with the following basic format: + * + *

+ *     <pgraster>
+ *       <name//>        // coverage name
+ *       <database>     // database connection
+ *         <host//>      // database host
+ *         <port//>      // database port
+ *         <name//>      // database name
+ *         <user//>      // database username
+ *         <pass//>      // database user password
+ *       </database>
+ *       <raster>       // raster column config
+ *         <column//>      // column name
+ *         <table//>     // table name
+ *         <schema//>    // table schema
+ *       </raster>
+ *       <time>        // time column config
+ *         <enabled//>  // enable / disable time
+ *         <column//>     // column name
+ *       </time>
+ *     </pgraster>
+ *   
+ */ +class PGRasterConfig implements Closeable { + + static final Logger LOG = Logging.getLogger(PGRasterConfig.class); + + String name; + DataSource dataSource; + String schema; + String table; + String column; + String enableDrivers; + + TimeConfig time = new TimeConfig(); + + static Document parse(File cfgfile) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db; + try { + db = dbf.newDocumentBuilder(); + } catch (Exception e) { + throw new RuntimeException("Error creating XML parser"); + } + + try { + return db.parse(cfgfile); + } catch (Exception e) { + throw new RuntimeException("Error parsing pgraster config", e); + } + } + + PGRasterConfig(File configFile) { + this(parse(configFile)); + } + + PGRasterConfig(Document config) { + Element root = config.getDocumentElement(); + if (!"pgraster".equalsIgnoreCase(root.getNodeName())) { + throw new IllegalArgumentException( + "Not a postgis raster configuration, root element must be 'pgraster'"); + } + + this.name = first(root, "name").map(this::nodeValue).orElse(null); + this.enableDrivers = first(root, "enableDrivers").map(this::nodeValue).orElse(null); + + Element db = + first(config.getDocumentElement(), "database") + .orElseThrow( + () -> + new IllegalArgumentException( + "Config has no database element")); + + DataSource dataSource = null; + + String jndi = first(db, "jndi").map(this::nodeValue).orElse(null); + if (jndi != null) { + try { + // BUG: CWE-20 Improper Input Validation + // dataSource = (DataSource) GeoTools.getInitialContext().lookup(jndi); + // FIXED: + dataSource = (DataSource) GeoTools.jndiLookup(jndi); + } catch (NamingException e) { + throw new IllegalArgumentException("Error performing JNDI lookup for: " + jndi, e); + } + } + + if (dataSource == null) { + BasicDataSource source = new BasicDataSource(); + source.setDriverClassName("org.postgresql.Driver"); + + String host = first(db, "host").map(this::nodeValue).orElse("localhost"); + + Integer port = + first(db, "port").map(this::nodeValue).map(Integer::parseInt).orElse(5432); + + String name = + first(db, "name") + .map(this::nodeValue) + .orElseThrow( + () -> + new IllegalArgumentException( + "database 'name' not specified")); + + source.setUrl("jdbc:postgresql://" + host + ":" + port + "/" + name); + + first(db, "user").map(this::nodeValue).ifPresent(source::setUsername); + + first(db, "passwd").map(this::nodeValue).ifPresent(source::setPassword); + + first(db, "pool") + .ifPresent( + p -> { + first(p, "min") + .map(this::nodeValue) + .map(Integer::parseInt) + .ifPresent(source::setMinIdle); + first(p, "max") + .map(this::nodeValue) + .map(Integer::parseInt) + .ifPresent(source::setMaxActive); + }); + + dataSource = new PGRasterDataSource(source); + } + + this.dataSource = dataSource; + + Element ras = + first(config.getDocumentElement(), "raster") + .orElseThrow( + () -> + new IllegalArgumentException( + "Config has no 'raster' element")); + + this.schema = first(ras, "schema").map(this::nodeValue).orElse("public"); + this.table = + first(ras, "table") + .map(this::nodeValue) + .orElseThrow( + () -> + new IllegalArgumentException( + "column must specify a 'table' element")); + this.column = first(ras, "column").map(this::nodeValue).orElse(null); + + // time + first(config.getDocumentElement(), "time") + .ifPresent( + el -> { + first(el, "enabled") + .map(this::nodeValue) + .map(Boolean::parseBoolean) + .ifPresent(it -> time.enabled = it); + first(el, "column") + .map(this::nodeValue) + .ifPresent(it -> time.column = it); + }); + } + + @VisibleForTesting + PGRasterConfig() {} + + Optional first(Element el, String name) { + NodeList matches = el.getElementsByTagName(name); + if (matches.getLength() > 0) { + return Optional.of((Element) matches.item(0)); + } + return Optional.empty(); + } + + String nodeValue(Element el) { + return el.getFirstChild().getNodeValue(); + } + + @Override + public void close() { + if (dataSource instanceof PGRasterDataSource) { + try { + ((PGRasterDataSource) dataSource).close(); + } catch (SQLException e) { + LOG.log(Level.WARNING, "Error closing data source", e); + } + } + } + + static class TimeConfig { + boolean enabled = true; + String column; + } + + static class PGRasterDataSource extends DBCPDataSource { + + PGRasterDataSource(BasicDataSource wrapped) { + super(wrapped); + } + } +} diff --git a/Java/PackageStyle.java b/Java/PackageStyle.java new file mode 100644 index 0000000000000000000000000000000000000000..720f03b6fef29c923ef848895688fbd5e42e1cb6 --- /dev/null +++ b/Java/PackageStyle.java @@ -0,0 +1,327 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * Modified by : Arno Peterson + * + * + */ +package net.sourceforge.plantuml.svek; + +import java.util.EnumSet; + +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.graphic.USymbol; +import net.sourceforge.plantuml.graphic.USymbols; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.ULine; +import net.sourceforge.plantuml.ugraphic.UPath; +import net.sourceforge.plantuml.ugraphic.UPolygon; +import net.sourceforge.plantuml.ugraphic.URectangle; +import net.sourceforge.plantuml.ugraphic.UShape; +import net.sourceforge.plantuml.ugraphic.UTranslate; + +public enum PackageStyle { + + FOLDER, RECTANGLE, NODE, FRAME, CLOUD, DATABASE, AGENT, STORAGE, COMPONENT1, COMPONENT2, ARTIFACT, CARD; + + public static PackageStyle fromString(String value) { + for (PackageStyle p : EnumSet.allOf(PackageStyle.class)) { + if (p.toString().equalsIgnoreCase(value)) { + return p; + } + } + if ("rect".equalsIgnoreCase(value)) { + return RECTANGLE; + } + return null; + } + + public USymbol toUSymbol() { + if (this == NODE) + return USymbols.NODE; + + if (this == CARD) + return USymbols.CARD; + + if (this == DATABASE) + return USymbols.DATABASE; + + if (this == CLOUD) + return USymbols.CLOUD; + + if (this == FRAME) + return USymbols.FRAME; + + if (this == RECTANGLE) + return USymbols.RECTANGLE; + + if (this == FOLDER) + return USymbols.PACKAGE; + + return null; + } + + public void drawU(UGraphic ug, Dimension2D dim, Dimension2D titleDim, boolean shadowing) { + if (titleDim == null) { + titleDim = new Dimension2DDouble(0, 0); + } + final double width = dim.getWidth(); + final double height = dim.getHeight(); + if (this == DATABASE) { + drawDatabase(ug, width, height, shadowing); + } else if (this == FOLDER) { + drawFolder(ug, width, height, shadowing); + } else if (this == FRAME) { + drawFrame(ug, width, height, titleDim, shadowing); + } else if (this == CLOUD) { + drawCloud(ug, width, height, shadowing); + } else if (this == RECTANGLE) { + drawRect(ug, width, height, shadowing); + } else if (this == COMPONENT1) { + drawComponent1(ug, width, height, shadowing); + } else if (this == COMPONENT2) { + drawComponent2(ug, width, height, shadowing); + } else if (this == STORAGE) { + drawStorage(ug, width, height, shadowing); + } else if (this == AGENT) { + drawRect(ug, width, height, shadowing); + } else if (this == ARTIFACT) { + drawArtifact(ug, width, height, shadowing); + } else { + // drawNode(ug, xTheoricalPosition, yTheoricalPosition, width, height, + // shadowing); + throw new UnsupportedOperationException(); + } + } + + private void drawArtifact(UGraphic ug, double width, double height, boolean shadowing) { + + final UPolygon polygon = new UPolygon(); + polygon.addPoint(0, 0); + polygon.addPoint(0, height); + polygon.addPoint(width, height); + final int cornersize = 10; + polygon.addPoint(width, cornersize); + polygon.addPoint(width - cornersize, 0); + polygon.addPoint(0, 0); + if (shadowing) { + polygon.setDeltaShadow(3.0); + } + ug.draw(polygon); + ug.apply(UTranslate.dx(width - cornersize)).draw(ULine.vline(cornersize)); + ug.apply(new UTranslate(width, cornersize)).draw(ULine.hline(-cornersize)); + } + + private void drawStorage(UGraphic ug, double width, double height, boolean shadowing) { + final URectangle shape = new URectangle(width, height).rounded(70); + if (shadowing) { + shape.setDeltaShadow(3.0); + } + ug.draw(shape); + } + + private void drawComponent1(UGraphic ug, double widthTotal, double heightTotal, boolean shadowing) { + + final URectangle form = new URectangle(widthTotal, heightTotal); + if (shadowing) { + form.setDeltaShadow(4); + } + + final UShape small = new URectangle(10, 5); + + ug.draw(form); + + // UML 1 Component Notation + ug.apply(new UTranslate(-5, 5)).draw(small); + ug.apply(new UTranslate(-5, heightTotal - 10)).draw(small); + } + + private void drawComponent2(UGraphic ug, double widthTotal, double heightTotal, boolean shadowing) { + + final URectangle form = new URectangle(widthTotal, heightTotal); + if (shadowing) { + form.setDeltaShadow(4); + } + + final UShape small = new URectangle(15, 10); + final UShape tiny = new URectangle(4, 2); + + ug.draw(form); + + // UML 2 Component Notation + ug.apply(new UTranslate(widthTotal - 20, 5)).draw(small); + ug.apply(new UTranslate(widthTotal - 22, 7)).draw(tiny); + ug.apply(new UTranslate(widthTotal - 22, 11)).draw(tiny); + } + + private void drawRect(UGraphic ug, double width, double height, boolean shadowing) { + final URectangle shape = new URectangle(width, height); + if (shadowing) { + shape.setDeltaShadow(3.0); + } + ug.draw(shape); + } + + private void drawCloud(UGraphic ug, double width, double height, boolean shadowing) { + final UPath shape = getSpecificFrontierForCloud(width, height); + if (shadowing) { + shape.setDeltaShadow(3.0); + } + ug.apply(new UTranslate(3, -3)).draw(shape); + } + + private UPath getSpecificFrontierForCloud(double width, double height) { + final UPath path = new UPath(); + path.moveTo(0, 10); + double x = 0; + for (int i = 0; i < width - 9; i += 10) { + path.cubicTo(i, -3 + 10, 2 + i, -5 + 10, 5 + i, -5 + 10); + path.cubicTo(8 + i, -5 + 10, 10 + i, -3 + 10, 10 + i, 10); + x = i + 10; + } + double y = 0; + for (int j = 10; j < height - 9; j += 10) { + path.cubicTo(x + 3, j, x + 5, 2 + j, x + 5, 5 + j); + path.cubicTo(x + 5, 8 + j, x + 3, 10 + j, x, 10 + j); + y = j + 10; + } + for (int i = 0; i < width - 9; i += 10) { + path.cubicTo(x - i, y + 3, x - 3 - i, y + 5, x - 5 - i, y + 5); + path.cubicTo(x - 8 - i, y + 5, x - 10 - i, y + 3, x - 10 - i, y); + } + for (int j = 0; j < height - 9 - 10; j += 10) { + path.cubicTo(-3, y - j, -5, y - 2 - j, -5, y - 5 - j); + path.cubicTo(-5, y - 8 - j, -3, y - 10 - j, 0, y - 10 - j); + } + return path; + } + + private void drawFrame(UGraphic ug, double width, double height, Dimension2D dimTitle, boolean shadowing) { + final URectangle shape = new URectangle(width, height); + if (shadowing) { + shape.setDeltaShadow(3.0); + } + + ug.draw(shape); + + final double textWidth; + final double textHeight; + final int cornersize; + if (dimTitle.getWidth() == 0) { + textWidth = width / 3; + textHeight = 12; + cornersize = 7; + } else { + textWidth = dimTitle.getWidth() + 10; + textHeight = dimTitle.getHeight() + 3; + cornersize = 10; + } + + final UPath polygon = new UPath(); + polygon.moveTo(textWidth, 1); + + polygon.lineTo(textWidth, textHeight - cornersize); + polygon.lineTo(textWidth - cornersize, textHeight); + + polygon.lineTo(0, textHeight); + ug.draw(polygon); + + } + + private void drawFolder(UGraphic ug, double width, double height, boolean shadowing) { + final double wtitle = Math.max(30, width / 4); + final UPolygon shape = new UPolygon(); + shape.addPoint(0, 0); + shape.addPoint(wtitle, 0); + final double htitle = 10; + final double marginTitleX3 = 7; + shape.addPoint(wtitle + marginTitleX3, htitle); + shape.addPoint(width, htitle); + shape.addPoint(width, height); + shape.addPoint(0, height); + shape.addPoint(0, 0); + if (shadowing) { + shape.setDeltaShadow(3.0); + } + ug.draw(shape); + ug.apply(UTranslate.dy(htitle)).draw(ULine.hline(wtitle + marginTitleX3)); + } + + private void drawDatabase(UGraphic ug, double width, double height, boolean shadowing) { + final UPath shape = new UPath(); + if (shadowing) { + shape.setDeltaShadow(3.0); + } + shape.moveTo(0, 10); + shape.cubicTo(10, 0, width / 2 - 10, 0, width / 2, 0); + shape.cubicTo(width / 2 + 10, 0, width - 10, 0, width, 10); + shape.lineTo(width, height - 10); + shape.cubicTo(width - 10, height, width / 2 - 10, height, width / 2, height); + shape.cubicTo(width / 2 + 10, height, 10, height, 0, height - 10); + shape.lineTo(0, 10); + + ug.draw(shape); + + final UPath closing = new UPath(); + closing.moveTo(0, 10); + closing.cubicTo(10, 20, width / 2 - 10, 20, width / 2, 20); + closing.cubicTo(width / 2 + 10, 20, width - 10, 20, width, 10); + + ug.draw(closing); + + } + + private void drawNode(UGraphic ug, double xTheoricalPosition, double yTheoricalPosition, double width, + double height, boolean shadowing) { + final UPolygon shape = new UPolygon(); + shape.addPoint(0, 10); + shape.addPoint(10, 0); + shape.addPoint(width, 0); + shape.addPoint(width, height - 10); + shape.addPoint(width - 10, height); + shape.addPoint(0, height); + shape.addPoint(0, 10); + if (shadowing) { + shape.setDeltaShadow(2); + } + ug.apply(new UTranslate(xTheoricalPosition, yTheoricalPosition)).draw(shape); + + ug.apply(new UTranslate(xTheoricalPosition + width - 10, yTheoricalPosition + 10)).draw(new ULine(9, -9)); + final UPath path = new UPath(); + path.moveTo(0, 0); + path.lineTo(width - 10, 0); + path.lineTo(width - 10, height - 10); + ug.apply(new UTranslate(xTheoricalPosition, yTheoricalPosition + 10)).draw(path); + } + +} \ No newline at end of file diff --git a/Java/PacketTranslator.java b/Java/PacketTranslator.java new file mode 100644 index 0000000000000000000000000000000000000000..3baf6320cf79e5c6ad280a07157072d65cfef7a2 --- /dev/null +++ b/Java/PacketTranslator.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators; + +import org.geysermc.connector.network.session.GeyserSession; + +public abstract class PacketTranslator { + // BUG: CWE-287 Improper Authentication + // public abstract void translate(T packet, GeyserSession session); + // FIXED: + public abstract void translate(GeyserSession session, T packet); + +} diff --git a/Java/PacketTranslatorRegistry.java b/Java/PacketTranslatorRegistry.java new file mode 100644 index 0000000000000000000000000000000000000000..965361e821c86144b32ed50080bd09fb37ac8972 --- /dev/null +++ b/Java/PacketTranslatorRegistry.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org + * + * 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. + * + * @author GeyserMC + * @link https://github.com/GeyserMC/Geyser + */ + +package org.geysermc.connector.network.translators; + +import com.github.steveice10.mc.protocol.packet.ingame.server.ServerPlayerListDataPacket; +import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerUpdateLightPacket; +import com.github.steveice10.packetlib.packet.Packet; +import com.nukkitx.protocol.bedrock.BedrockPacket; +import io.netty.channel.EventLoop; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.geysermc.common.PlatformType; +import org.geysermc.connector.GeyserConnector; +import org.geysermc.connector.network.session.GeyserSession; +import org.geysermc.connector.utils.FileUtils; +import org.geysermc.connector.utils.LanguageUtils; + +import java.util.IdentityHashMap; +import java.util.Map; + +public class PacketTranslatorRegistry { + private final Map, PacketTranslator> translators = new IdentityHashMap<>(); + + public static final PacketTranslatorRegistry JAVA_TRANSLATOR = new PacketTranslatorRegistry<>(); + public static final PacketTranslatorRegistry BEDROCK_TRANSLATOR = new PacketTranslatorRegistry<>(); + + private static final ObjectArrayList> IGNORED_PACKETS = new ObjectArrayList<>(); + + static { + for (Class clazz : FileUtils.getGeneratedClassesForAnnotation(Translator.class)) { + Class packet = clazz.getAnnotation(Translator.class).packet(); + + GeyserConnector.getInstance().getLogger().debug("Found annotated translator: " + clazz.getCanonicalName() + " : " + packet.getSimpleName()); + + try { + if (Packet.class.isAssignableFrom(packet)) { + Class targetPacket = (Class) packet; + PacketTranslator translator = (PacketTranslator) clazz.newInstance(); + + JAVA_TRANSLATOR.translators.put(targetPacket, translator); + } else if (BedrockPacket.class.isAssignableFrom(packet)) { + Class targetPacket = (Class) packet; + PacketTranslator translator = (PacketTranslator) clazz.newInstance(); + + BEDROCK_TRANSLATOR.translators.put(targetPacket, translator); + } else { + GeyserConnector.getInstance().getLogger().error("Class " + clazz.getCanonicalName() + " is annotated as a translator but has an invalid target packet."); + } + } catch (InstantiationException | IllegalAccessException e) { + GeyserConnector.getInstance().getLogger().error("Could not instantiate annotated translator " + clazz.getCanonicalName()); + } + } + + IGNORED_PACKETS.add(ServerUpdateLightPacket.class); // Light is handled on Bedrock for us + IGNORED_PACKETS.add(ServerPlayerListDataPacket.class); // Cant be implemented in bedrock + } + + private PacketTranslatorRegistry() { + } + + public static void init() { + // no-op + } + + @SuppressWarnings("unchecked") + public

boolean translate(Class clazz, P packet, GeyserSession session) { + if (!session.getUpstream().isClosed() && !session.isClosed()) { + PacketTranslator

translator = (PacketTranslator

) translators.get(clazz); + if (translator != null) { + EventLoop eventLoop = session.getEventLoop(); + if (eventLoop.inEventLoop()) { + translate0(session, translator, packet); + } else { + eventLoop.execute(() -> translate0(session, translator, packet)); + } + return true; + } else { + if ((GeyserConnector.getInstance().getPlatformType() != PlatformType.STANDALONE || !(packet instanceof BedrockPacket)) && !IGNORED_PACKETS.contains(clazz)) { + // Other debug logs already take care of Bedrock packets for us if on standalone + GeyserConnector.getInstance().getLogger().debug("Could not find packet for " + (packet.toString().length() > 25 ? packet.getClass().getSimpleName() : packet)); + } + } + } + return false; + } + + private

void translate0(GeyserSession session, PacketTranslator

translator, P packet) { + if (session.isClosed()) { + return; + } + + try { + // BUG: CWE-287 Improper Authentication + // translator.translate(packet, session); + // FIXED: + translator.translate(session, packet); + } catch (Throwable ex) { + GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.network.translator.packet.failed", packet.getClass().getSimpleName()), ex); + ex.printStackTrace(); + } + } +} diff --git a/Java/PartialViewContextImpl.java b/Java/PartialViewContextImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..dbcbe9f210a522edc284ba1e4da16f1fccb3e1b8 --- /dev/null +++ b/Java/PartialViewContextImpl.java @@ -0,0 +1,690 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package com.sun.faces.context; + +import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_EXECUTE_PARAM; +import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_RENDER_PARAM; +import static com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter.PARTIAL_RESET_VALUES_PARAM; +import static javax.faces.FactoryFinder.VISIT_CONTEXT_FACTORY; + +import java.io.IOException; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.faces.FacesException; +import javax.faces.FactoryFinder; +import javax.faces.application.ResourceHandler; +import javax.faces.component.NamingContainer; +import javax.faces.component.UIComponent; +import javax.faces.component.UIViewRoot; +import javax.faces.component.visit.VisitCallback; +import javax.faces.component.visit.VisitContext; +import javax.faces.component.visit.VisitContextFactory; +import javax.faces.component.visit.VisitContextWrapper; +import javax.faces.component.visit.VisitHint; +import javax.faces.component.visit.VisitResult; +import javax.faces.context.ExternalContext; +import javax.faces.context.FacesContext; +import javax.faces.context.PartialResponseWriter; +import javax.faces.context.PartialViewContext; +import javax.faces.context.ResponseWriter; +import javax.faces.event.PhaseId; +import javax.faces.lifecycle.ClientWindow; +import javax.faces.render.RenderKit; +import javax.faces.render.RenderKitFactory; + +import com.sun.faces.RIConstants; +import com.sun.faces.component.visit.PartialVisitContext; +import com.sun.faces.renderkit.RenderKitUtils.PredefinedPostbackParameter; +import com.sun.faces.util.FacesLogger; +import com.sun.faces.util.HtmlUtils; +import com.sun.faces.util.Util; + + public class PartialViewContextImpl extends PartialViewContext { + + // Log instance for this class + private static Logger LOGGER = FacesLogger.CONTEXT.getLogger(); + + private boolean released; + + // BE SURE TO ADD NEW IVARS TO THE RELEASE METHOD + private PartialResponseWriter partialResponseWriter; + private List executeIds; + private Collection renderIds; + private List evalScripts; + private Boolean ajaxRequest; + private Boolean partialRequest; + private Boolean renderAll; + private FacesContext ctx; + + private static final String ORIGINAL_WRITER = "com.sun.faces.ORIGINAL_WRITER"; + + + // ----------------------------------------------------------- Constructors + + + public PartialViewContextImpl(FacesContext ctx) { + this.ctx = ctx; + } + + + // ---------------------------------------------- Methods from PartialViewContext + + /** + * @see javax.faces.context.PartialViewContext#isAjaxRequest() + */ + @Override + public boolean isAjaxRequest() { + + assertNotReleased(); + if (ajaxRequest == null) { + ajaxRequest = "partial/ajax".equals(ctx. + getExternalContext().getRequestHeaderMap().get("Faces-Request")); + if (!ajaxRequest) { + ajaxRequest = "partial/ajax".equals(ctx.getExternalContext().getRequestParameterMap(). + get("Faces-Request")); + } + } + return ajaxRequest; + + } + + /** + * @see javax.faces.context.PartialViewContext#isPartialRequest() + */ + @Override + public boolean isPartialRequest() { + + assertNotReleased(); + if (partialRequest == null) { + partialRequest = isAjaxRequest() || + "partial/process".equals(ctx. + getExternalContext().getRequestHeaderMap().get("Faces-Request")); + } + return partialRequest; + + } + + + /** + * @see javax.faces.context.PartialViewContext#isExecuteAll() + */ + @Override + public boolean isExecuteAll() { + + assertNotReleased(); + String execute = PARTIAL_EXECUTE_PARAM.getValue(ctx); + return (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(execute)); + + } + + /** + * @see javax.faces.context.PartialViewContext#isRenderAll() + */ + @Override + public boolean isRenderAll() { + + assertNotReleased(); + if (renderAll == null) { + String render = PARTIAL_RENDER_PARAM.getValue(ctx); + renderAll = (ALL_PARTIAL_PHASE_CLIENT_IDS.equals(render)); + } + + return renderAll; + + } + + /** + * @see javax.faces.context.PartialViewContext#setRenderAll(boolean) + */ + @Override + public void setRenderAll(boolean renderAll) { + + this.renderAll = renderAll; + + } + + @Override + public boolean isResetValues() { + Object value = PARTIAL_RESET_VALUES_PARAM.getValue(ctx); + return (null != value && "true".equals(value)) ? true : false; + } + + @Override + public void setPartialRequest(boolean isPartialRequest) { + this.partialRequest = isPartialRequest; + } + + + /** + * @see javax.faces.context.PartialViewContext#getExecuteIds() + */ + @Override + public Collection getExecuteIds() { + + assertNotReleased(); + if (executeIds != null) { + return executeIds; + } + executeIds = populatePhaseClientIds(PARTIAL_EXECUTE_PARAM); + + // include the view parameter facet ID if there are other execute IDs + // to process + if (!executeIds.isEmpty()) { + UIViewRoot root = ctx.getViewRoot(); + if (root.getFacetCount() > 0) { + if (root.getFacet(UIViewRoot.METADATA_FACET_NAME) != null) { + executeIds.add(0, UIViewRoot.METADATA_FACET_NAME); + } + } + } + return executeIds; + + } + + /** + * @see javax.faces.context.PartialViewContext#getRenderIds() + */ + @Override + public Collection getRenderIds() { + + assertNotReleased(); + if (renderIds != null) { + return renderIds; + } + renderIds = populatePhaseClientIds(PARTIAL_RENDER_PARAM); + return renderIds; + + } + + /** + * @see javax.faces.context.PartialViewContext#getEvalScripts() + */ + @Override + public List getEvalScripts() { + assertNotReleased(); + + if (evalScripts == null) { + evalScripts = new ArrayList<>(1); + } + + return evalScripts; + } + + /** + * @see PartialViewContext#processPartial(javax.faces.event.PhaseId) + */ + @Override + public void processPartial(PhaseId phaseId) { + PartialViewContext pvc = ctx.getPartialViewContext(); + Collection myExecuteIds = pvc.getExecuteIds(); + Collection myRenderIds = pvc.getRenderIds(); + UIViewRoot viewRoot = ctx.getViewRoot(); + + if (phaseId == PhaseId.APPLY_REQUEST_VALUES || + phaseId == PhaseId.PROCESS_VALIDATIONS || + phaseId == PhaseId.UPDATE_MODEL_VALUES) { + + // Skip this processing if "none" is specified in the render list, + // or there were no execute phase client ids. + + if (myExecuteIds == null || myExecuteIds.isEmpty()) { + if (LOGGER.isLoggable(Level.FINE)) { + LOGGER.log(Level.FINE, + "No execute and render identifiers specified. Skipping component processing."); + } + return; + } + + try { + processComponents(viewRoot, phaseId, myExecuteIds, ctx); + } catch (Exception e) { + if (LOGGER.isLoggable(Level.INFO)) { + LOGGER.log(Level.INFO, + e.toString(), + e); + } + throw new FacesException(e); + } + + // If we have just finished APPLY_REQUEST_VALUES phase, install the + // partial response writer. We want to make sure that any content + // or errors generated in the other phases are written using the + // partial response writer. + // + if (phaseId == PhaseId.APPLY_REQUEST_VALUES) { + PartialResponseWriter writer = pvc.getPartialResponseWriter(); + ctx.setResponseWriter(writer); + } + + } else if (phaseId == PhaseId.RENDER_RESPONSE) { + + try { + // + // We re-enable response writing. + // + PartialResponseWriter writer = pvc.getPartialResponseWriter(); + ResponseWriter orig = ctx.getResponseWriter(); + ctx.getAttributes().put(ORIGINAL_WRITER, orig); + ctx.setResponseWriter(writer); + + ExternalContext exContext = ctx.getExternalContext(); + exContext.setResponseContentType(RIConstants.TEXT_XML_CONTENT_TYPE); + exContext.addResponseHeader("Cache-Control", "no-cache"); + +// String encoding = writer.getCharacterEncoding( ); +// if( encoding == null ) { +// encoding = "UTF-8"; +// } +// writer.writePreamble("\n"); + writer.startDocument(); + + if (isResetValues()) { + viewRoot.resetValues(ctx, myRenderIds); + } + + if (isRenderAll()) { + renderAll(ctx, viewRoot); + renderState(ctx); + writer.endDocument(); + return; + } + + renderComponentResources(ctx, viewRoot); + + // Skip this processing if "none" is specified in the render list, + // or there were no render phase client ids. + if (myRenderIds != null && !myRenderIds.isEmpty()) { + processComponents(viewRoot, phaseId, myRenderIds, ctx); + } + + renderState(ctx); + renderEvalScripts(ctx); + + writer.endDocument(); + } catch (IOException ex) { + this.cleanupAfterView(); + } catch (RuntimeException ex) { + this.cleanupAfterView(); + // Throw the exception + throw ex; + } + } + } + + /** + * @see javax.faces.context.PartialViewContext#getPartialResponseWriter() + */ + @Override + public PartialResponseWriter getPartialResponseWriter() { + assertNotReleased(); + if (partialResponseWriter == null) { + partialResponseWriter = new DelayedInitPartialResponseWriter(this); + } + return partialResponseWriter; + } + + /** + * @see javax.faces.context.PartialViewContext#release() + */ + @Override + public void release() { + + released = true; + ajaxRequest = null; + renderAll = null; + partialResponseWriter = null; + executeIds = null; + renderIds = null; + evalScripts = null; + ctx = null; + partialRequest = null; + + } + + // -------------------------------------------------------- Private Methods + + + + private List populatePhaseClientIds(PredefinedPostbackParameter parameterName) { + + String param = parameterName.getValue(ctx); + if (param == null) { + return new ArrayList<>(); + } else { + Map appMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap(); + String[] pcs = Util.split(appMap, param, "[ \t]+"); + return ((pcs != null && pcs.length != 0) + ? new ArrayList<>(Arrays.asList(pcs)) + : new ArrayList<>()); + } + + } + + // Process the components specified in the phaseClientIds list + private void processComponents(UIComponent component, PhaseId phaseId, + Collection phaseClientIds, FacesContext context) throws IOException { + + // We use the tree visitor mechanism to locate the components to + // process. Create our (partial) VisitContext and the + // VisitCallback that will be invoked for each component that + // is visited. Note that we use the SKIP_UNRENDERED hint as we + // only want to visit the rendered subtree. + EnumSet hints = EnumSet.of(VisitHint.SKIP_UNRENDERED, VisitHint.EXECUTE_LIFECYCLE); + VisitContextFactory visitContextFactory = (VisitContextFactory) + FactoryFinder.getFactory(VISIT_CONTEXT_FACTORY); + VisitContext visitContext = visitContextFactory.getVisitContext(context, phaseClientIds, hints); + PhaseAwareVisitCallback visitCallback = + new PhaseAwareVisitCallback(ctx, phaseId); + component.visitTree(visitContext, visitCallback); + + PartialVisitContext partialVisitContext = unwrapPartialVisitContext(visitContext); + if (partialVisitContext != null) { + if (LOGGER.isLoggable(Level.FINER) && !partialVisitContext.getUnvisitedClientIds().isEmpty()) { + Collection unvisitedClientIds = partialVisitContext.getUnvisitedClientIds(); + StringBuilder builder = new StringBuilder(); + for (String cur : unvisitedClientIds) { + builder.append(cur).append(" "); + } + LOGGER.log(Level.FINER, + "jsf.context.partial_visit_context_unvisited_children", + new Object[]{builder.toString()}); + } + } + } + + /** + * Unwraps {@link PartialVisitContext} from a chain of {@link VisitContextWrapper}s. + * + * If no {@link PartialVisitContext} is found in the chain, null is returned instead. + * + * @param visitContext the visit context. + * @return the (unwrapped) partial visit context. + */ + private static PartialVisitContext unwrapPartialVisitContext(VisitContext visitContext) { + if (visitContext == null) { + return null; + } + if (visitContext instanceof PartialVisitContext) { + return (PartialVisitContext) visitContext; + } + if (visitContext instanceof VisitContextWrapper) { + return unwrapPartialVisitContext(((VisitContextWrapper) visitContext).getWrapped()); + } + return null; + } + + private void renderAll(FacesContext context, UIViewRoot viewRoot) throws IOException { + // If this is a "render all via ajax" request, + // make sure to wrap the entire page in a elemnt + // with the special viewStateId of VIEW_ROOT_ID. This is how the client + // JavaScript knows how to replace the entire document with + // this response. + PartialViewContext pvc = context.getPartialViewContext(); + PartialResponseWriter writer = pvc.getPartialResponseWriter(); + + if (!(viewRoot instanceof NamingContainer)) { + writer.startUpdate(PartialResponseWriter.RENDER_ALL_MARKER); + if (viewRoot.getChildCount() > 0) { + for (UIComponent uiComponent : viewRoot.getChildren()) { + uiComponent.encodeAll(context); + } + } + writer.endUpdate(); + } + else { + /* + * If we have a portlet request, start rendering at the view root. + */ + writer.startUpdate(viewRoot.getClientId(context)); + viewRoot.encodeBegin(context); + if (viewRoot.getChildCount() > 0) { + for (UIComponent uiComponent : viewRoot.getChildren()) { + uiComponent.encodeAll(context); + } + } + viewRoot.encodeEnd(context); + writer.endUpdate(); + } + } + + private void renderComponentResources(FacesContext context, UIViewRoot viewRoot) throws IOException { + ResourceHandler resourceHandler = context.getApplication().getResourceHandler(); + PartialResponseWriter writer = context.getPartialViewContext().getPartialResponseWriter(); + boolean updateStarted = false; + + for (UIComponent resource : viewRoot.getComponentResources(context)) { + String name = (String) resource.getAttributes().get("name"); + String library = (String) resource.getAttributes().get("library"); + + if (resource.getChildCount() == 0 + && resourceHandler.getRendererTypeForResourceName(name) != null + && !resourceHandler.isResourceRendered(context, name, library)) + { + if (!updateStarted) { + writer.startUpdate("javax.faces.Resource"); + updateStarted = true; + } + + resource.encodeAll(context); + } + } + + if (updateStarted) { + writer.endUpdate(); + } + } + + private void renderState(FacesContext context) throws IOException { + // Get the view state and write it to the response.. + PartialViewContext pvc = context.getPartialViewContext(); + PartialResponseWriter writer = pvc.getPartialResponseWriter(); + String viewStateId = Util.getViewStateId(context); + + writer.startUpdate(viewStateId); + String state = context.getApplication().getStateManager().getViewState(context); + writer.write(state); + writer.endUpdate(); + + ClientWindow window = context.getExternalContext().getClientWindow(); + if (null != window) { + String clientWindowId = Util.getClientWindowId(context); + writer.startUpdate(clientWindowId); + // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') + // writer.write(window.getId()); + // FIXED: + writer.writeText(window.getId(), null); + writer.endUpdate(); + } + } + + private void renderEvalScripts(FacesContext context) throws IOException { + PartialViewContext pvc = context.getPartialViewContext(); + PartialResponseWriter writer = pvc.getPartialResponseWriter(); + + for (String evalScript : pvc.getEvalScripts()) { + writer.startEval(); + writer.write(evalScript); + writer.endEval(); + } + } + + private PartialResponseWriter createPartialResponseWriter() { + + ExternalContext extContext = ctx.getExternalContext(); + String encoding = extContext.getRequestCharacterEncoding(); + extContext.setResponseCharacterEncoding(encoding); + ResponseWriter responseWriter = null; + Writer out = null; + try { + out = extContext.getResponseOutputWriter(); + } catch (IOException ioe) { + if (LOGGER.isLoggable(Level.SEVERE)) { + LOGGER.log(Level.SEVERE, + ioe.toString(), + ioe); + } + } + + if (out != null) { + UIViewRoot viewRoot = ctx.getViewRoot(); + if (viewRoot != null) { + responseWriter = + ctx.getRenderKit().createResponseWriter(out, + RIConstants.TEXT_XML_CONTENT_TYPE, encoding); + } else { + RenderKitFactory factory = (RenderKitFactory) + FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); + RenderKit renderKit = factory.getRenderKit(ctx, RenderKitFactory.HTML_BASIC_RENDER_KIT); + responseWriter = renderKit.createResponseWriter(out, RIConstants.TEXT_XML_CONTENT_TYPE, encoding); + } + } + if (responseWriter instanceof PartialResponseWriter) { + return (PartialResponseWriter) responseWriter; + } else { + return new PartialResponseWriter(responseWriter); + } + + } + + private void cleanupAfterView() { + ResponseWriter orig = (ResponseWriter) ctx.getAttributes(). + get(ORIGINAL_WRITER); + assert(null != orig); + // move aside the PartialResponseWriter + ctx.setResponseWriter(orig); + } + + private void assertNotReleased() { + if (released) { + throw new IllegalStateException(); + } + } + + // ----------------------------------------------------------- Inner Classes + + + private static class PhaseAwareVisitCallback implements VisitCallback { + + private PhaseId curPhase; + private FacesContext ctx; + + private PhaseAwareVisitCallback(FacesContext ctx, PhaseId curPhase) { + this.ctx = ctx; + this.curPhase = curPhase; + } + + + @Override + public VisitResult visit(VisitContext context, UIComponent comp) { + try { + + if (curPhase == PhaseId.APPLY_REQUEST_VALUES) { + + // RELEASE_PENDING handle immediate request(s) + // If the user requested an immediate request + // Make sure to set the immediate flag here. + + comp.processDecodes(ctx); + } else if (curPhase == PhaseId.PROCESS_VALIDATIONS) { + comp.processValidators(ctx); + } else if (curPhase == PhaseId.UPDATE_MODEL_VALUES) { + comp.processUpdates(ctx); + } else if (curPhase == PhaseId.RENDER_RESPONSE) { + PartialResponseWriter writer = ctx.getPartialViewContext().getPartialResponseWriter(); + writer.startUpdate(comp.getClientId(ctx)); + // do the default behavior... + comp.encodeAll(ctx); + writer.endUpdate(); + } else { + throw new IllegalStateException("I18N: Unexpected " + + "PhaseId passed to " + + " PhaseAwareContextCallback: " + + curPhase.toString()); + } + } + catch (IOException ex) { + if (LOGGER.isLoggable(Level.SEVERE)) { + LOGGER.severe(ex.toString()); + } + if (LOGGER.isLoggable(Level.FINE)) { + LOGGER.log(Level.FINE, + ex.toString(), + ex); + } + throw new FacesException(ex); + } + + // Once we visit a component, there is no need to visit + // its children, since processDecodes/Validators/Updates and + // encodeAll() already traverse the subtree. We return + // VisitResult.REJECT to supress the subtree visit. + return VisitResult.REJECT; + } + } + + + /** + * Delays the actual construction of the PartialResponseWriter until + * content is going to actually be written. + */ + private static final class DelayedInitPartialResponseWriter extends PartialResponseWriter { + + private ResponseWriter writer; + private PartialViewContextImpl ctx; + + // -------------------------------------------------------- Constructors + + + public DelayedInitPartialResponseWriter(PartialViewContextImpl ctx) { + + super(null); + this.ctx = ctx; + ExternalContext extCtx = ctx.ctx.getExternalContext(); + extCtx.setResponseContentType(RIConstants.TEXT_XML_CONTENT_TYPE); + extCtx.setResponseCharacterEncoding(extCtx.getRequestCharacterEncoding()); + extCtx.setResponseBufferSize(ctx.ctx.getExternalContext().getResponseBufferSize()); + } + + + // ---------------------------------- Methods from PartialResponseWriter + + @Override + public void write(String text) throws IOException { + HtmlUtils.writeUnescapedTextForXML(getWrapped(), text); + } + + @Override + public ResponseWriter getWrapped() { + + if (writer == null) { + writer = ctx.createPartialResponseWriter(); + } + return writer; + + } + + } // END DelayedInitPartialResponseWriter + +} diff --git a/Java/PortfolioServiceImpl.java b/Java/PortfolioServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..473498e6197ba0612040405aeaa3ee81ea786c74 --- /dev/null +++ b/Java/PortfolioServiceImpl.java @@ -0,0 +1,1569 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.modules.portfolio.manager; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.logging.log4j.Logger; +import org.olat.basesecurity.Group; +import org.olat.basesecurity.IdentityRef; +import org.olat.basesecurity.manager.GroupDAO; +import org.olat.core.commons.persistence.DB; +import org.olat.core.gui.translator.Translator; +import org.olat.core.id.Identity; +import org.olat.core.id.OLATResourceable; +import org.olat.core.logging.Tracing; +import org.olat.core.logging.activity.ThreadLocalUserActivityLogger; +import org.olat.core.util.FileUtils; +import org.olat.core.util.StringHelper; +import org.olat.core.util.Util; +import org.olat.core.util.resource.OresHelper; +import org.olat.core.util.vfs.VFSLeaf; +import org.olat.core.util.vfs.VFSManager; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.course.CourseFactory; +import org.olat.course.ICourse; +import org.olat.course.assessment.AssessmentHelper; +import org.olat.course.assessment.CourseAssessmentService; +import org.olat.course.nodes.CourseNode; +import org.olat.course.nodes.PortfolioCourseNode; +import org.olat.course.run.scoring.AssessmentEvaluation; +import org.olat.course.run.scoring.ScoreEvaluation; +import org.olat.course.run.userview.UserCourseEnvironment; +import org.olat.fileresource.FileResourceManager; +import org.olat.modules.assessment.AssessmentEntry; +import org.olat.modules.assessment.AssessmentService; +import org.olat.modules.assessment.Role; +import org.olat.modules.assessment.model.AssessmentEntryStatus; +import org.olat.modules.forms.EvaluationFormManager; +import org.olat.modules.forms.EvaluationFormParticipation; +import org.olat.modules.forms.EvaluationFormParticipationRef; +import org.olat.modules.forms.EvaluationFormSession; +import org.olat.modules.forms.EvaluationFormSurvey; +import org.olat.modules.forms.EvaluationFormSurveyIdentifier; +import org.olat.modules.forms.EvaluationFormSurveyRef; +import org.olat.modules.portfolio.AssessmentSection; +import org.olat.modules.portfolio.Assignment; +import org.olat.modules.portfolio.AssignmentStatus; +import org.olat.modules.portfolio.AssignmentType; +import org.olat.modules.portfolio.Binder; +import org.olat.modules.portfolio.BinderDeliveryOptions; +import org.olat.modules.portfolio.BinderLight; +import org.olat.modules.portfolio.BinderRef; +import org.olat.modules.portfolio.Category; +import org.olat.modules.portfolio.CategoryToElement; +import org.olat.modules.portfolio.Media; +import org.olat.modules.portfolio.MediaHandler; +import org.olat.modules.portfolio.MediaLight; +import org.olat.modules.portfolio.Page; +import org.olat.modules.portfolio.PageBody; +import org.olat.modules.portfolio.PageImageAlign; +import org.olat.modules.portfolio.PagePart; +import org.olat.modules.portfolio.PageStatus; +import org.olat.modules.portfolio.PageUserInformations; +import org.olat.modules.portfolio.PageUserStatus; +import org.olat.modules.portfolio.PortfolioElement; +import org.olat.modules.portfolio.PortfolioElementType; +import org.olat.modules.portfolio.PortfolioLoggingAction; +import org.olat.modules.portfolio.PortfolioRoles; +import org.olat.modules.portfolio.PortfolioService; +import org.olat.modules.portfolio.Section; +import org.olat.modules.portfolio.SectionRef; +import org.olat.modules.portfolio.SectionStatus; +import org.olat.modules.portfolio.handler.BinderTemplateResource; +import org.olat.modules.portfolio.model.AccessRightChange; +import org.olat.modules.portfolio.model.AccessRights; +import org.olat.modules.portfolio.model.AssessedBinder; +import org.olat.modules.portfolio.model.AssessedPage; +import org.olat.modules.portfolio.model.AssessmentSectionChange; +import org.olat.modules.portfolio.model.AssessmentSectionImpl; +import org.olat.modules.portfolio.model.AssignmentImpl; +import org.olat.modules.portfolio.model.BinderImpl; +import org.olat.modules.portfolio.model.BinderPageUsage; +import org.olat.modules.portfolio.model.BinderStatistics; +import org.olat.modules.portfolio.model.CategoryLight; +import org.olat.modules.portfolio.model.PageImpl; +import org.olat.modules.portfolio.model.SearchSharePagesParameters; +import org.olat.modules.portfolio.model.SectionImpl; +import org.olat.modules.portfolio.model.SectionKeyRef; +import org.olat.modules.portfolio.model.SynchedBinder; +import org.olat.modules.portfolio.ui.PortfolioHomeController; +import org.olat.repository.RepositoryEntry; +import org.olat.repository.RepositoryEntryRef; +import org.olat.repository.RepositoryManager; +import org.olat.repository.RepositoryService; +import org.olat.resource.OLATResource; +import org.olat.resource.OLATResourceManager; +import org.olat.util.logging.activity.LoggingResourceable; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.security.ExplicitTypePermission; + +/** + * + * Initial date: 06.06.2016
+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com + * + */ +@Service +public class PortfolioServiceImpl implements PortfolioService { + + private static final Logger log = Tracing.createLoggerFor(PortfolioServiceImpl.class); + + private static XStream configXstream = XStreamHelper.createXStreamInstance(); + static { + configXstream.alias("deliveryOptions", BinderDeliveryOptions.class); + Class[] types = new Class[] { + BinderDeliveryOptions.class + }; + configXstream.addPermission(new ExplicitTypePermission(types)); + } + + @Autowired + private DB dbInstance; + @Autowired + private PageDAO pageDao; + @Autowired + private GroupDAO groupDao; + @Autowired + private MediaDAO mediaDao; + @Autowired + private BinderDAO binderDao; + @Autowired + private CommentDAO commentDao; + @Autowired + private CategoryDAO categoryDao; + @Autowired + private AssignmentDAO assignmentDao; + @Autowired + private PageUserInfosDAO pageUserInfosDao; + @Autowired + private SharedByMeQueries sharedByMeQueries; + @Autowired + private OLATResourceManager resourceManager; + @Autowired + private SharedWithMeQueries sharedWithMeQueries; + @Autowired + private PortfolioFileStorage portfolioFileStorage; + @Autowired + private AssessmentSectionDAO assessmentSectionDao; + @Autowired + private AssessmentService assessmentService; + @Autowired + private CourseAssessmentService courseAssessmentService; + + @Autowired + private RepositoryService repositoryService; + @Autowired + private RepositoryManager repositoryManager; + @Autowired + private EvaluationFormManager evaluationFormManager; + @Autowired + private BinderUserInformationsDAO binderUserInformationsDao; + + @Autowired + private List mediaHandlers; + + @Override + public Binder createNewBinder(String title, String summary, String imagePath, Identity owner) { + BinderImpl portfolio = binderDao.createAndPersist(title, summary, imagePath, null); + if(owner != null) { + groupDao.addMembershipTwoWay(portfolio.getBaseGroup(), owner, PortfolioRoles.owner.name()); + } + return portfolio; + } + + @Override + public OLATResource createBinderTemplateResource() { + return resourceManager.createOLATResourceInstance(BinderTemplateResource.TYPE_NAME); + } + + @Override + public void createAndPersistBinderTemplate(Identity owner, RepositoryEntry entry, Locale locale) { + BinderImpl binder = binderDao.createAndPersist(entry.getDisplayname(), entry.getDescription(), null, entry); + if(owner != null) { + groupDao.addMembershipTwoWay(binder.getBaseGroup(), owner, PortfolioRoles.owner.name()); + } + //add section + Translator pt = Util.createPackageTranslator(PortfolioHomeController.class, locale); + String sectionTitle = pt.translate("new.section.title"); + String sectionDescription = pt.translate("new.section.desc"); + binderDao.createSection(sectionTitle, sectionDescription, null, null, binder); + } + + @Override + public Binder updateBinder(Binder binder) { + return binderDao.updateBinder(binder); + } + + @Override + public Binder copyBinder(Binder transientBinder, RepositoryEntry entry) { + String imagePath = null; + if(StringHelper.containsNonWhitespace(transientBinder.getImagePath())) { + File bcroot = portfolioFileStorage.getRootDirectory(); + File image = new File(bcroot, transientBinder.getImagePath()); + if(image.exists()) { + imagePath = addPosterImageForBinder(image, image.getName()); + } + } + return internalCopyTransientBinder(transientBinder, entry, imagePath, true); + } + + @Override + public Binder importBinder(Binder transientBinder, RepositoryEntry templateEntry, File image) { + String imagePath = null; + if(StringHelper.containsNonWhitespace(transientBinder.getImagePath())) { + imagePath = addPosterImageForBinder(image, image.getName()); + } + return internalCopyTransientBinder(transientBinder, templateEntry, imagePath, false); + } + + private Binder internalCopyTransientBinder(Binder transientBinder, RepositoryEntry entry, String imagePath, boolean copy) { + Binder binder = binderDao.createAndPersist(transientBinder.getTitle(), transientBinder.getSummary(), imagePath, entry); + //copy sections + for(Section transientSection:((BinderImpl)transientBinder).getSections()) { + SectionImpl section = binderDao.createSection(transientSection.getTitle(), transientSection.getDescription(), + transientSection.getBeginDate(), transientSection.getEndDate(), binder); + + List transientAssignments = ((SectionImpl)transientSection).getAssignments(); + for(Assignment transientAssignment:transientAssignments) { + if(transientAssignment != null) { + + RepositoryEntry formEntry = null; + if(transientAssignment.getAssignmentType() == AssignmentType.form) { + formEntry = loadImportedFormEntry(transientAssignment); + if(formEntry == null) { + continue; + } + } + + File newStorage = portfolioFileStorage.generateAssignmentSubDirectory(); + String storage = portfolioFileStorage.getRelativePath(newStorage); + assignmentDao.createAssignment(transientAssignment.getTitle(), transientAssignment.getSummary(), + transientAssignment.getContent(), storage, transientAssignment.getAssignmentType(), + transientAssignment.isTemplate(), transientAssignment.getAssignmentStatus(), section, null, + transientAssignment.isOnlyAutoEvaluation(), transientAssignment.isReviewerSeeAutoEvaluation(), + transientAssignment.isAnonymousExternalEvaluation(), formEntry); + //copy attachments + File templateDirectory = portfolioFileStorage.getAssignmentDirectory(transientAssignment); + if(copy && templateDirectory != null) { + FileUtils.copyDirContentsToDir(templateDirectory, newStorage, false, "Assignment attachments"); + } + } + } + } + return binder; + } + + private RepositoryEntry loadImportedFormEntry(Assignment transientAssignment) { + try { + RepositoryEntry formEntry = transientAssignment.getFormEntry(); + if(formEntry != null) { + formEntry = repositoryManager.lookupRepositoryEntryBySoftkey(formEntry.getSoftkey(), false); + } + return formEntry; + } catch (Exception e) { + log.error("", e); + return null; + } + } + + @Override + public boolean detachCourseFromBinders(RepositoryEntry entry) { + int deletedRows = binderDao.detachBinderFromRepositoryEntry(entry); + return deletedRows > 0; + } + + @Override + public boolean detachRepositoryEntryFromBinders(RepositoryEntry entry, PortfolioCourseNode courseNode) { + int deletedRows = binderDao.detachBinderFromRepositoryEntry(entry, courseNode); + return deletedRows > 0; + } + + @Override + public boolean deleteBinderTemplate(Binder binder, RepositoryEntry templateEntry) { + getBindersAssignmentsTemplates(binder).forEach(this::deleteAssignment); + + BinderImpl reloadedBinder = (BinderImpl)binderDao.loadByKey(binder.getKey()); + int deletedRows = binderDao.deleteBinderTemplate(reloadedBinder); + return deletedRows > 0; + } + + @Override + public boolean deleteBinder(BinderRef binder) { + int rows = binderDao.deleteBinder(binder); + return rows > 0; + } + + @Override + public BinderDeliveryOptions getDeliveryOptions(OLATResource resource) { + FileResourceManager frm = FileResourceManager.getInstance(); + File reFolder = frm.getFileResourceRoot(resource); + File configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME); + + BinderDeliveryOptions config; + if(configXml.exists()) { + config = (BinderDeliveryOptions)configXstream.fromXML(configXml); + } else { + //set default config + config = BinderDeliveryOptions.defaultOptions(); + setDeliveryOptions(resource, config); + } + return config; + } + + @Override + public void setDeliveryOptions(OLATResource resource, BinderDeliveryOptions options) { + FileResourceManager frm = FileResourceManager.getInstance(); + File reFolder = frm.getFileResourceRoot(resource); + File configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME); + if(options == null) { + FileUtils.deleteFile(configXml); + } else { + try (OutputStream out = new FileOutputStream(configXml)) { + configXstream.toXML(options, out); + } catch (IOException e) { + log.error("", e); + } + } + } + + @Override + public Assignment addAssignment(String title, String summary, String content, AssignmentType type, boolean template, Section section, Binder binder, + boolean onlyAutoEvaluation, boolean reviewerSeeAutoEvaluation, boolean anonymousExternEvaluation, RepositoryEntry formEntry) { + File newStorage = portfolioFileStorage.generateAssignmentSubDirectory(); + String storage = portfolioFileStorage.getRelativePath(newStorage); + + Binder reloadedBinder = binder == null ? null : binderDao.loadByKey(binder.getKey()); + Section reloadedSection = section == null ? null : binderDao.loadSectionByKey(section.getKey()); + return assignmentDao.createAssignment(title, summary, content, storage, type, template, + AssignmentStatus.template, reloadedSection, reloadedBinder, + onlyAutoEvaluation, reviewerSeeAutoEvaluation, anonymousExternEvaluation, formEntry); + } + + @Override + public Assignment updateAssignment(Assignment assignment, String title, String summary, String content, AssignmentType type, + boolean onlyAutoEvaluation, boolean reviewerSeeAutoEvaluation, boolean anonymousExternEvaluation, RepositoryEntry formEntry) { + if(!StringHelper.containsNonWhitespace(assignment.getStorage())) { + File newStorage = portfolioFileStorage.generateAssignmentSubDirectory(); + String newRelativeStorage = portfolioFileStorage.getRelativePath(newStorage); + ((AssignmentImpl)assignment).setStorage(newRelativeStorage); + } + + AssignmentImpl impl = (AssignmentImpl)assignment; + impl.setTitle(title); + impl.setSummary(summary); + impl.setContent(content); + impl.setType(type.name()); + impl.setOnlyAutoEvaluation(onlyAutoEvaluation); + impl.setReviewerSeeAutoEvaluation(reviewerSeeAutoEvaluation); + impl.setAnonymousExternalEvaluation(anonymousExternEvaluation); + impl.setFormEntry(formEntry); + return assignmentDao.updateAssignment(assignment); + } + + @Override + public Section moveUpAssignment(Section section, Assignment assignment) { + Section reloadedSection = binderDao.loadSectionByKey(section.getKey()); + return assignmentDao.moveUpAssignment((SectionImpl)reloadedSection, assignment); + } + + @Override + public Section moveDownAssignment(Section section, Assignment assignment) { + Section reloadedSection = binderDao.loadSectionByKey(section.getKey()); + return assignmentDao.moveDownAssignment((SectionImpl)reloadedSection, assignment); + } + + @Override + public void moveAssignment(SectionRef currentSectionRef, Assignment assignment, SectionRef newParentSectionRef) { + Section currentSection = binderDao.loadSectionByKey(currentSectionRef.getKey()); + Section newParentSection = binderDao.loadSectionByKey(newParentSectionRef.getKey()); + assignmentDao.moveAssignment((SectionImpl)currentSection, assignment, (SectionImpl)newParentSection); + } + + @Override + public List getSectionsAssignments(PortfolioElement element, String searchString) { + if(element.getType() == PortfolioElementType.binder) { + return assignmentDao.loadAssignments((BinderRef)element, searchString); + } + if(element.getType() == PortfolioElementType.section) { + return assignmentDao.loadAssignments((SectionRef)element, searchString); + } + if(element.getType() == PortfolioElementType.page) { + return assignmentDao.loadAssignments((Page)element, searchString); + } + return null; + } + + @Override + public List getBindersAssignmentsTemplates(BinderRef binder) { + return assignmentDao.loadBinderAssignmentsTemplates(binder); + } + + @Override + public boolean hasBinderAssignmentTemplate(BinderRef binder) { + return assignmentDao.hasBinderAssignmentTemplate(binder); + } + + @Override + public List searchOwnedAssignments(IdentityRef assignee) { + return assignmentDao.getOwnedAssignments(assignee); + } + + @Override + public boolean isAssignmentInUse(Assignment assignment) { + return assignmentDao.isAssignmentInUse(assignment); + } + + @Override + public boolean deleteAssignment(Assignment assignment) { + Assignment reloadedAssignment = assignmentDao.loadAssignmentByKey(assignment.getKey()); + Section reloadedSection = reloadedAssignment.getSection(); + Binder reloadedBinder = reloadedAssignment.getBinder(); + + if(reloadedSection != null) { + ((SectionImpl)reloadedSection).getAssignments().remove(reloadedAssignment); + assignmentDao.deleteAssignment(reloadedAssignment); + binderDao.updateSection(reloadedSection); + } else if(reloadedBinder != null) { + Set bindersToUpdate = new HashSet<>(); + List synchedBindersAssignments = assignmentDao.loadAssignmentReferences(reloadedAssignment); + for(Assignment synchedAssignment:synchedBindersAssignments) { + List instantiatedAssignments = assignmentDao.loadAssignmentReferences(synchedAssignment); + Set

sectionsToUpdate = new HashSet<>(); + for(Assignment instantiatedAssignment:instantiatedAssignments) { + if(instantiatedAssignment.getSection() != null) { + Section assignmentSection = instantiatedAssignment.getSection(); + if(((SectionImpl)assignmentSection).getAssignments().remove(instantiatedAssignment)) { + sectionsToUpdate.add(assignmentSection); + } + assignmentDao.deleteAssignment(instantiatedAssignment); + } + } + for(Section section:sectionsToUpdate) { + binderDao.updateSection(section); + } + + if(synchedAssignment.getBinder() != null) { + Binder synchedBinder = synchedAssignment.getBinder(); + if(((BinderImpl)synchedBinder).getAssignments().remove(reloadedAssignment)) { + bindersToUpdate.add(synchedBinder); + } + assignmentDao.deleteAssignment(synchedAssignment); + } + } + + for(Binder binder:bindersToUpdate) { + binderDao.updateBinder(binder); + } + assignmentDao.deleteAssignment(reloadedAssignment); + binderDao.updateBinder(reloadedBinder); + } + return true; + } + + @Override + public Assignment startAssignment(Long assignmentKey, Identity author) { + Assignment reloadedAssignment = assignmentDao.loadAssignmentByKey(assignmentKey); + if (reloadedAssignment.getPage() == null) { + Section section = reloadedAssignment.getSection(); + if (reloadedAssignment.getAssignmentType() == AssignmentType.essay + || reloadedAssignment.getAssignmentType() == AssignmentType.document) { + Page page = appendNewPage(author, reloadedAssignment.getTitle(), reloadedAssignment.getSummary(), null, null, section); + reloadedAssignment = assignmentDao.startEssayAssignment(reloadedAssignment, page, author); + } else if (reloadedAssignment.getAssignmentType() == AssignmentType.form) { + RepositoryEntry formEntry = reloadedAssignment.getFormEntry(); + Page page = appendNewPage(author, reloadedAssignment.getTitle(), reloadedAssignment.getSummary(), null, false, null, section); + reloadedAssignment = assignmentDao.startFormAssignment(reloadedAssignment, page, author); + // create the session for the assignee + EvaluationFormSurvey survey = loadOrCreateSurvey(page.getBody(), formEntry); + loadOrCreateSession(survey, author); + } + } + dbInstance.commit(); + ThreadLocalUserActivityLogger.log(PortfolioLoggingAction.PORTFOLIO_ASSIGNMENT_STARTED, getClass(), + LoggingResourceable.wrap(reloadedAssignment.getSection()), + LoggingResourceable.wrap(reloadedAssignment)); + return reloadedAssignment; + } + + @Override + public Page startAssignmentFromTemplate(Long assignmentKey, Identity author, String title, String summary, String imagePath, PageImageAlign align, + SectionRef sectionRef, Boolean onlyAutoEvaluation, Boolean reviewerCanSeeAutoEvaluation) { + Page page = null; + Section section = binderDao.loadSectionByKey(sectionRef.getKey()); + Assignment reloadedAssignmentTemplate = assignmentDao.loadAssignmentByKey(assignmentKey); + Assignment instanciatedAssignment = assignmentDao + .createAssignment(reloadedAssignmentTemplate, AssignmentStatus.inProgress, section, null, + false, onlyAutoEvaluation, reviewerCanSeeAutoEvaluation); + if (instanciatedAssignment.getPage() == null) { + if (instanciatedAssignment.getAssignmentType() == AssignmentType.essay + || instanciatedAssignment.getAssignmentType() == AssignmentType.document) { + page = appendNewPage(author, title, summary, null, null, section); + instanciatedAssignment = assignmentDao.startEssayAssignment(instanciatedAssignment, page, author); + } else if (instanciatedAssignment.getAssignmentType() == AssignmentType.form) { + RepositoryEntry formEntry = instanciatedAssignment.getFormEntry(); + if(!StringHelper.containsNonWhitespace(title)) { + title = instanciatedAssignment.getTitle(); + } + page = appendNewPage(author, title, instanciatedAssignment.getSummary(), null, false, null, section); + instanciatedAssignment = assignmentDao.startFormAssignment(instanciatedAssignment, page, author); + // create the session for the assignee + EvaluationFormSurvey survey = loadOrCreateSurvey(page.getBody(), formEntry); + loadOrCreateSession(survey, author); + } + } + dbInstance.commit(); + ThreadLocalUserActivityLogger.log(PortfolioLoggingAction.PORTFOLIO_ASSIGNMENT_STARTED, getClass(), + LoggingResourceable.wrap(instanciatedAssignment.getSection()), + LoggingResourceable.wrap(instanciatedAssignment)); + return page; + } + + @Override + public Assignment getAssignment(PageBody body) { + return assignmentDao.loadAssignment(body); + } + + @Override + public SectionRef appendNewSection(String title, String description, Date begin, Date end, BinderRef binder) { + Binder reloadedBinder = binderDao.loadByKey(binder.getKey()); + SectionImpl newSection = binderDao.createSection(title, description, begin, end, reloadedBinder); + return new SectionKeyRef(newSection.getKey()); + } + + @Override + public Section updateSection(Section section) { + return binderDao.updateSection(section); + } + + @Override + public List
getSections(BinderRef binder) { + return binderDao.getSections(binder); + } + + @Override + public Section getSection(SectionRef section) { + return binderDao.loadSectionByKey(section.getKey()); + } + + @Override + public Binder moveUpSection(Binder binder, Section section) { + Binder reloadedBinder = binderDao.loadByKey(binder.getKey()); + return binderDao.moveUpSection((BinderImpl)reloadedBinder, section); + } + + @Override + public Binder moveDownSection(Binder binder, Section section) { + Binder reloadedBinder = binderDao.loadByKey(binder.getKey()); + return binderDao.moveDownSection((BinderImpl)reloadedBinder, section); + } + + @Override + public Binder deleteSection(Binder binder, Section section) { + Section reloadedSection = binderDao.loadSectionByKey(section.getKey()); + Binder reloadedBinder = reloadedSection.getBinder(); + return binderDao.deleteSection(reloadedBinder, reloadedSection); + } + + @Override + public List getPages(BinderRef binder, String searchString) { + return pageDao.getPages(binder, searchString); + } + + @Override + public List getPages(SectionRef section) { + return pageDao.getPages(section); + } + + @Override + public List getOwnedBinders(IdentityRef owner) { + return binderDao.getOwnedBinders(owner); + } + + @Override + public List searchOwnedBinders(IdentityRef owner) { + return binderDao.searchOwnedBinders(owner, false); + } + + @Override + public int countOwnedBinders(IdentityRef owner) { + return binderDao.countOwnedBinders(owner, false); + } + + @Override + public List searchOwnedDeletedBinders(IdentityRef owner) { + return binderDao.searchOwnedBinders(owner, true); + } + + @Override + public List searchOwnedLastBinders(IdentityRef owner, int maxResults) { + return binderDao.searchOwnedLastBinders(owner, maxResults); + } + + @Override + public List searchOwnedBindersFromCourseTemplate(IdentityRef owner) { + return binderDao.getOwnedBinderFromCourseTemplate(owner); + } + + @Override + public List searchSharedBindersBy(Identity owner, String searchString) { + return sharedByMeQueries.searchSharedBinders(owner, searchString); + } + + @Override + public List searchSharedBindersWith(Identity coach, String searchString) { + return sharedWithMeQueries.searchSharedBinders(coach, searchString); + } + + @Override + public List searchSharedPagesWith(Identity coach, SearchSharePagesParameters params) { + return sharedWithMeQueries.searchSharedPagesEntries(coach, params); + } + + @Override + public List searchCourseWithBinderTemplates(Identity participant) { + return binderDao.searchCourseTemplates(participant); + } + + @Override + public Binder getBinderByKey(Long portfolioKey) { + return binderDao.loadByKey(portfolioKey); + } + + @Override + public void updateBinderUserInformations(Binder binder, Identity user) { + if(binder == null || user == null) return; + binderUserInformationsDao.updateBinderUserInformations(binder, user); + } + + @Override + public Binder getBinderByResource(OLATResource resource) { + return binderDao.loadByResource(resource); + } + + @Override + public BinderStatistics getBinderStatistics(BinderRef binder) { + return binderDao.getBinderStatistics(binder); + } + + @Override + public RepositoryEntry getRepositoryEntry(Binder binder) { + OLATResource resource = ((BinderImpl)binder).getOlatResource(); + Long resourceKey = resource.getKey(); + return repositoryService.loadByResourceKey(resourceKey); + } + + @Override + public Binder getBinderBySection(SectionRef section) { + return binderDao.loadBySection(section); + } + + @Override + public boolean isTemplateInUse(Binder binder, RepositoryEntry courseEntry, String subIdent) { + return binderDao.isTemplateInUse(binder, courseEntry, subIdent); + } + + @Override + public int getTemplateUsage(RepositoryEntryRef templateEntry) { + return binderDao.getTemplateUsage(templateEntry); + } + + @Override + public Binder getBinder(Identity owner, BinderRef templateBinder, RepositoryEntryRef courseEntry, String subIdent) { + return binderDao.getBinder(owner, templateBinder, courseEntry, subIdent); + } + + @Override + public List getBinders(Identity owner, RepositoryEntryRef courseEntry, String subIdent) { + return binderDao.getBinders(owner, courseEntry, subIdent); + } + + @Override + public Binder assignBinder(Identity owner, BinderRef templateBinder, RepositoryEntry entry, String subIdent, Date deadline) { + BinderImpl reloadedTemplate = (BinderImpl)binderDao.loadByKey(templateBinder.getKey()); + BinderImpl binder = binderDao.createCopy(reloadedTemplate, entry, subIdent); + groupDao.addMembershipTwoWay(binder.getBaseGroup(), owner, PortfolioRoles.owner.name()); + return binder; + } + + @Override + public SynchedBinder loadAndSyncBinder(BinderRef binder) { + Binder reloadedBinder = binderDao.loadByKey(binder.getKey()); + AtomicBoolean changes = new AtomicBoolean(false); + if(reloadedBinder.getTemplate() != null) { + reloadedBinder = binderDao + .syncWithTemplate((BinderImpl)reloadedBinder.getTemplate(), (BinderImpl)reloadedBinder, changes); + } + return new SynchedBinder(reloadedBinder, changes.get()); + } + + @Override + public boolean isMember(BinderRef binder, IdentityRef identity, String... roles) { + return binderDao.isMember(binder, identity, roles); + } + + @Override + public List getMembers(BinderRef binder, String... roles) { + return binderDao.getMembers(binder, roles); + } + + @Override + public List getMembers(Page page, String... roles) { + return pageDao.getMembers(page, roles); + } + + @Override + public boolean isBinderVisible(IdentityRef identity, BinderRef binder) { + return binderDao.isMember(binder, identity, + PortfolioRoles.owner.name(), PortfolioRoles.coach.name(), + PortfolioRoles.reviewer.name(), PortfolioRoles.invitee.name()); + } + + @Override + public List getAccessRights(Binder binder) { + List rights = binderDao.getBinderAccesRights(binder, null); + List sectionRights = binderDao.getSectionAccesRights(binder, null); + rights.addAll(sectionRights); + List pageRights = binderDao.getPageAccesRights(binder, null); + rights.addAll(pageRights); + return rights; + } + + @Override + public List getAccessRights(Binder binder, Identity identity) { + List rights = binderDao.getBinderAccesRights(binder, identity); + List sectionRights = binderDao.getSectionAccesRights(binder, identity); + rights.addAll(sectionRights); + List pageRights = binderDao.getPageAccesRights(binder, identity); + rights.addAll(pageRights); + return rights; + } + + @Override + public List getAccessRights(Page page) { + List rights = binderDao.getBinderAccesRights(page); + List sectionRights = binderDao.getSectionAccesRights(page); + rights.addAll(sectionRights); + List pageRights = binderDao.getPageAccesRights(page); + rights.addAll(pageRights); + return rights; + } + + @Override + public void addAccessRights(PortfolioElement element, Identity identity, PortfolioRoles role) { + Group baseGroup = element.getBaseGroup(); + if(!groupDao.hasRole(baseGroup, identity, role.name())) { + groupDao.addMembershipTwoWay(baseGroup, identity, role.name()); + } + } + + @Override + public void changeAccessRights(List identities, List changes) { + for(Identity identity:identities) { + for(AccessRightChange change:changes) { + Group baseGroup = change.getElement().getBaseGroup(); + if(change.isAdd()) { + if(!groupDao.hasRole(baseGroup, identity, change.getRole().name())) { + Group group = getGroup(change.getElement()); + groupDao.addMembershipOneWay(group, identity, change.getRole().name()); + } + } else { + if(groupDao.hasRole(baseGroup, identity, change.getRole().name())) { + Group group = getGroup(change.getElement()); + groupDao.removeMembership(group, identity, change.getRole().name()); + } + } + } + } + } + + @Override + public void removeAccessRights(Binder binder, Identity identity, PortfolioRoles... roles) { + Set roleSet = new HashSet<>(); + if(roles != null && roles.length > 0) { + for(PortfolioRoles role:roles) { + if(role != null) { + roleSet.add(role); + } + } + } + + if(roleSet.isEmpty()) { + log.warn("Want to remove rights without specifying the roles."); + return; + } + + List rights = getAccessRights(binder, identity); + for(AccessRights right:rights) { + PortfolioRoles role = right.getRole(); + if(roleSet.contains(role)) { + Group baseGroup; + if(right.getType() == PortfolioElementType.binder) { + baseGroup = binderDao.loadByKey(right.getBinderKey()).getBaseGroup(); + } else if(right.getType() == PortfolioElementType.section) { + baseGroup = binderDao.loadSectionByKey(right.getSectionKey()).getBaseGroup(); + } else if(right.getType() == PortfolioElementType.page) { + baseGroup = pageDao.loadByKey(right.getPageKey()).getBaseGroup(); + } else { + continue; + } + + if(groupDao.hasRole(baseGroup, identity, right.getRole().name())) { + groupDao.removeMembership(baseGroup, identity, right.getRole().name()); + } + } + } + } + + private Group getGroup(PortfolioElement element) { + if(element instanceof Page) { + return pageDao.getGroup((Page)element); + } + if(element instanceof SectionRef) { + return binderDao.getGroup((SectionRef)element); + } + if(element instanceof BinderRef) { + return binderDao.getGroup((BinderRef)element); + } + return null; + } + + @Override + public List getCategories(PortfolioElement element) { + OLATResourceable ores = getOLATResoucreable(element); + return categoryDao.getCategories(ores); + } + + @Override + public List getCategorizedSectionsAndPages(BinderRef binder) { + return categoryDao.getCategorizedSectionsAndPages(binder); + } + + @Override + public List getCategorizedSectionAndPages(SectionRef section) { + return categoryDao.getCategorizedSectionAndPages(section); + } + + @Override + public List getCategorizedOwnedPages(IdentityRef owner) { + return categoryDao.getCategorizedOwnedPages(owner); + } + + @Override + public void updateCategories(PortfolioElement element, List categories) { + OLATResourceable ores = getOLATResoucreable(element); + updateCategories(ores, categories); + } + + private OLATResourceable getOLATResoucreable(PortfolioElement element) { + switch(element.getType()) { + case binder: return OresHelper.createOLATResourceableInstance(Binder.class, element.getKey()); + case section: return OresHelper.createOLATResourceableInstance(Section.class, element.getKey()); + case page: return OresHelper.createOLATResourceableInstance(Page.class, element.getKey()); + default: return null; + } + } + + private void updateCategories(OLATResourceable oresource, List categories) { + List currentCategories = categoryDao.getCategories(oresource); + Map currentCategoryMap = new HashMap<>(); + for(Category category:currentCategories) { + currentCategoryMap.put(category.getName(), category); + } + + List newCategories = new ArrayList<>(categories); + for(String newCategory:newCategories) { + if(!currentCategoryMap.containsKey(newCategory)) { + Category category = categoryDao.createAndPersistCategory(newCategory); + categoryDao.appendRelation(oresource, category); + } + } + + for(Category currentCategory:currentCategories) { + String name = currentCategory.getName(); + if(!newCategories.contains(name)) { + categoryDao.removeRelation(oresource, currentCategory); + } + } + } + + @Override + public Map getNumberOfComments(BinderRef binder) { + return commentDao.getNumberOfComments(binder); + } + + @Override + public Map getNumberOfComments(SectionRef section) { + return commentDao.getNumberOfComments(section); + } + + @Override + public Map getNumberOfCommentsOnOwnedPage(IdentityRef owner) { + return commentDao.getNumberOfCommentsOnOwnedPage(owner); + } + + @Override + public File getPosterImageFile(BinderLight binder) { + String imagePath = binder.getImagePath(); + if(StringHelper.containsNonWhitespace(imagePath)) { + File bcroot = portfolioFileStorage.getRootDirectory(); + return new File(bcroot, imagePath); + } + return null; + } + + @Override + public VFSLeaf getPosterImageLeaf(BinderLight binder) { + String imagePath = binder.getImagePath(); + if(StringHelper.containsNonWhitespace(imagePath)) { + VFSLeaf leaf = VFSManager.olatRootLeaf("/" + imagePath); + if(leaf.exists()) { + return leaf; + } + } + return null; + } + + @Override + public String addPosterImageForBinder(File file, String filename) { + File dir = portfolioFileStorage.generateBinderSubDirectory(); + if(!StringHelper.containsNonWhitespace(filename)) { + filename = file.getName(); + } + File destinationFile = new File(dir, filename); + String renamedFile = FileUtils.rename(destinationFile); + if(renamedFile != null) { + destinationFile = new File(dir, renamedFile); + } + FileUtils.copyFileToFile(file, destinationFile, false); + return portfolioFileStorage.getRelativePath(destinationFile); + } + + @Override + public void removePosterImage(Binder binder) { + String imagePath = binder.getImagePath(); + if(StringHelper.containsNonWhitespace(imagePath)) { + File bcroot = portfolioFileStorage.getRootDirectory(); + File file = new File(bcroot, imagePath); + if(file.exists()) { + boolean deleted = file.delete(); + if(!deleted) { + log.warn("Cannot delete: " + file); + } + } + } + } + + @Override + public int countOwnedPages(IdentityRef owner) { + return pageDao.countOwnedPages(owner); + } + + @Override + public List searchOwnedPages(IdentityRef owner, String searchString) { + return pageDao.getOwnedPages(owner, searchString); + } + + @Override + public List searchOwnedLastPages(IdentityRef owner, int maxResults) { + return pageDao.getLastPages(owner, maxResults); + } + + @Override + public List searchDeletedPages(IdentityRef owner, String searchString) { + return pageDao.getDeletedPages(owner, searchString); + } + + @Override + public Page appendNewPage(Identity owner, String title, String summary, String imagePath, PageImageAlign align, SectionRef section) { + return appendNewPage(owner, title, summary, imagePath, true, align, section); + } + + private Page appendNewPage(Identity owner, String title, String summary, String imagePath, boolean editable, PageImageAlign align, SectionRef section) { + Section reloadedSection = section == null ? null : binderDao.loadSectionByKey(section.getKey()); + if(reloadedSection != null && reloadedSection.getSectionStatus() == SectionStatus.notStarted) { + ((SectionImpl)reloadedSection).setSectionStatus(SectionStatus.inProgress); + } + Page page = pageDao.createAndPersist(title, summary, imagePath, align, editable, reloadedSection, null); + groupDao.addMembershipTwoWay(page.getBaseGroup(), owner, PortfolioRoles.owner.name()); + return page; + } + + @Override + public Page getPageByKey(Long key) { + return pageDao.loadByKey(key); + } + + @Override + public Page getPageByBody(PageBody body) { + return pageDao.loadByBody(body); + } + + @Override + public List getLastPages(Identity owner, int maxResults) { + return pageDao.getLastPages(owner, maxResults); + } + + @Override + public Page updatePage(Page page, SectionRef newParentSection) { + Page updatedPage; + if(newParentSection == null) { + updatedPage = pageDao.updatePage(page); + } else { + Section currentSection = null; + if(page.getSection() != null) { + currentSection = binderDao.loadSectionByKey(page.getSection().getKey()); + currentSection.getPages().remove(page); + } + + Section newParent = binderDao.loadSectionByKey(newParentSection.getKey()); + ((PageImpl)page).setSection(newParent); + newParent.getPages().add(page); + updatedPage = pageDao.updatePage(page); + if(currentSection != null) { + binderDao.updateSection(currentSection); + } + binderDao.updateSection(newParent); + } + return updatedPage; + } + + @Override + public File getPosterImage(Page page) { + String imagePath = page.getImagePath(); + if(StringHelper.containsNonWhitespace(imagePath)) { + File bcroot = portfolioFileStorage.getRootDirectory(); + return new File(bcroot, imagePath); + } + return null; + } + + @Override + public String addPosterImageForPage(File file, String filename) { + File dir = portfolioFileStorage.generatePageSubDirectory(); + File destinationFile = new File(dir, filename); + String renamedFile = FileUtils.rename(destinationFile); + if(renamedFile != null) { + destinationFile = new File(dir, renamedFile); + } + FileUtils.copyFileToFile(file, destinationFile, false); + return portfolioFileStorage.getRelativePath(destinationFile); + } + + @Override + public void removePosterImage(Page page) { + String imagePath = page.getImagePath(); + if(StringHelper.containsNonWhitespace(imagePath)) { + File bcroot = portfolioFileStorage.getRootDirectory(); + File file = new File(bcroot, imagePath); + FileUtils.deleteFile(file); + } + } + + @Override + @SuppressWarnings("unchecked") + public U appendNewPagePart(Page page, U part) { + PageBody body = pageDao.loadPageBodyByKey(page.getBody().getKey()); + return (U)pageDao.persistPart(body, part); + } + + @Override + @SuppressWarnings("unchecked") + public U appendNewPagePartAt(Page page, U part, int index) { + PageBody body = pageDao.loadPageBodyByKey(page.getBody().getKey()); + return (U)pageDao.persistPart(body, part, index); + } + + @Override + public void removePagePart(Page page, PagePart part) { + PageBody body = pageDao.loadPageBodyByKey(page.getBody().getKey()); + pageDao.removePart(body, part); + } + + @Override + public void moveUpPagePart(Page page, PagePart part) { + PageBody body = pageDao.loadPageBodyByKey(page.getBody().getKey()); + pageDao.moveUpPart(body, part); + } + + @Override + public void moveDownPagePart(Page page, PagePart part) { + PageBody body = pageDao.loadPageBodyByKey(page.getBody().getKey()); + pageDao.moveDownPart(body, part); + } + + @Override + public void movePagePart(Page page, PagePart partToMove, PagePart sibling, boolean after) { + PageBody body = pageDao.loadPageBodyByKey(page.getBody().getKey()); + pageDao.movePart(body, partToMove, sibling, after); + } + + @Override + public Page removePage(Page page) { + // will take care of the assignments + return pageDao.removePage(page); + } + + @Override + public void deletePage(Page page) { + Page reloadedPage = pageDao.loadByKey(page.getKey()); + pageDao.deletePage(reloadedPage); + pageUserInfosDao.delete(page); + } + + @Override + public List getPageParts(Page page) { + return pageDao.getParts(page.getBody()); + } + + @Override + @SuppressWarnings("unchecked") + public U updatePart(U part) { + return (U)pageDao.merge(part); + } + + @Override + public MediaHandler getMediaHandler(String type) { + if(mediaHandlers != null) { + for(MediaHandler handler:mediaHandlers) { + if(type.equals(handler.getType())) { + return handler; + } + } + } + return null; + } + + @Override + public List getMediaHandlers() { + return new ArrayList<>(mediaHandlers); + } + + @Override + public Media updateMedia(Media media) { + return mediaDao.update(media); + } + + @Override + public void deleteMedia(Media media) { + mediaDao.deleteMedia(media); + } + + @Override + public void updateCategories(Media media, List categories) { + OLATResourceable ores = OresHelper.createOLATResourceableInstance(Media.class, media.getKey()); + updateCategories(ores, categories); + } + + @Override + public List getCategories(Media media) { + OLATResourceable ores = OresHelper.createOLATResourceableInstance(Media.class, media.getKey()); + return categoryDao.getCategories(ores); + } + + @Override + public List getMediaCategories(IdentityRef owner) { + return categoryDao.getMediaCategories(owner); + } + + @Override + public List searchOwnedMedias(IdentityRef author, String searchString, List tagNames) { + return mediaDao.searchByAuthor(author, searchString, tagNames); + } + + @Override + public Media getMediaByKey(Long key) { + return mediaDao.loadByKey(key); + } + + @Override + public List getUsedInBinders(MediaLight media) { + return mediaDao.usedInBinders(media); + } + + @Override + public Page changePageStatus(Page page, PageStatus status, Identity identity, Role by) { + PageStatus currentStatus = page.getPageStatus(); + Page reloadedPage = pageDao.loadByKey(page.getKey()); + ((PageImpl)reloadedPage).setPageStatus(status); + if(status == PageStatus.published) { + Date now = new Date(); + if(reloadedPage.getInitialPublicationDate() == null) { + ((PageImpl)reloadedPage).setInitialPublicationDate(now); + } + ((PageImpl)reloadedPage).setLastPublicationDate(now); + Section section = reloadedPage.getSection(); + if(section != null) { + SectionStatus sectionStatus = section.getSectionStatus(); + if(currentStatus == PageStatus.closed) { + if(sectionStatus == SectionStatus.closed) { + ((SectionImpl)section).setSectionStatus(SectionStatus.inProgress); + binderDao.updateSection(section); + } + } else if(sectionStatus == null || sectionStatus == SectionStatus.notStarted || sectionStatus == SectionStatus.closed) { + ((SectionImpl)section).setSectionStatus(SectionStatus.inProgress); + binderDao.updateSection(section); + } + List owners = getOwners(page, section); + for (Identity owner: owners) { + EvaluationFormSurveyRef survey = evaluationFormManager.loadSurvey(getSurveyIdent(page.getBody())); + EvaluationFormParticipationRef participation = evaluationFormManager.loadParticipationByExecutor(survey, owner); + EvaluationFormSession session = evaluationFormManager.loadSessionByParticipation(participation); + evaluationFormManager.finishSession(session); + } + } + } else if(status == PageStatus.inRevision) { + Section section = reloadedPage.getSection(); + if(section != null) { + SectionStatus sectionStatus = section.getSectionStatus(); + if(sectionStatus == null || sectionStatus == SectionStatus.notStarted || sectionStatus == SectionStatus.closed) { + if(sectionStatus == SectionStatus.closed) { + ((SectionImpl)section).setSectionStatus(SectionStatus.inProgress); + binderDao.updateSection(section); + } + } + List owners = getOwners(page, section); + for (Identity owner: owners) { + EvaluationFormSurveyRef survey = evaluationFormManager.loadSurvey(getSurveyIdent(page.getBody())); + EvaluationFormParticipationRef participation = evaluationFormManager.loadParticipationByExecutor(survey, owner); + EvaluationFormSession session = evaluationFormManager.loadSessionByParticipation(participation); + evaluationFormManager.reopenSession(session); + } + } + pageUserInfosDao.updateStatus(reloadedPage, PageUserStatus.inProcess, PageUserStatus.done); + } else if(status == PageStatus.closed) { + //set user informations to done + pageUserInfosDao.updateStatus(reloadedPage, PageUserStatus.done); + } + if(reloadedPage.getSection() != null && reloadedPage.getSection().getBinder() != null) { + Binder binder = reloadedPage.getSection().getBinder(); + updateAssessmentEntryLastModification(binder, identity, by); + } + + return pageDao.updatePage(reloadedPage); + } + + private List getOwners(Page page, Section section) { + Assignment assignment = assignmentDao.loadAssignment(page.getBody()); + if(assignment != null && assignment.getAssignmentType() == AssignmentType.form) { + return getMembers(section.getBinder(), PortfolioRoles.owner.name()); + } + return new ArrayList<>(); + } + + @Override + public PageUserInformations getPageUserInfos(Page page, Identity identity, PageUserStatus defaultStatus) { + PageUserInformations infos = pageUserInfosDao.getPageUserInfos(page, identity); + if(infos == null) { + PageStatus status = page.getPageStatus(); + PageUserStatus userStatus = defaultStatus; + if(status == null || status == PageStatus.draft) { + userStatus = PageUserStatus.incoming; + } else if(status == PageStatus.closed || status == PageStatus.deleted) { + userStatus = PageUserStatus.done; + } + infos = pageUserInfosDao.create(userStatus, page, identity); + } + return infos; + } + + @Override + public List getPageUserInfos(BinderRef binder, IdentityRef identity) { + return pageUserInfosDao.getPageUserInfos(binder, identity); + } + + @Override + public PageUserInformations updatePageUserInfos(PageUserInformations infos) { + return pageUserInfosDao.update(infos); + } + + @Override + public Section changeSectionStatus(Section section, SectionStatus status, Identity coach) { + PageStatus newPageStatus; + if(status == SectionStatus.closed) { + newPageStatus = PageStatus.closed; + } else { + newPageStatus = PageStatus.inRevision; + } + + Section reloadedSection = binderDao.loadSectionByKey(section.getKey()); + List pages = reloadedSection.getPages(); + for(Page page:pages) { + if(page != null) { + ((PageImpl)page).setPageStatus(newPageStatus); + pageDao.updatePage(page); + if(newPageStatus == PageStatus.closed) { + //set user informations to done + pageUserInfosDao.updateStatus(page, PageUserStatus.done); + } + } + } + + ((SectionImpl)reloadedSection).setSectionStatus(status); + reloadedSection = binderDao.updateSection(reloadedSection); + return reloadedSection; + } + + private void updateAssessmentEntryLastModification(Binder binder, Identity doer, Role by) { + if(binder.getEntry() == null) return; + + RepositoryEntry entry = binder.getEntry(); + List assessedIdentities = getMembers(binder, PortfolioRoles.owner.name()); + + //order status from the entry / section + if("CourseModule".equals(entry.getOlatResource().getResourceableTypeName())) { + ICourse course = CourseFactory.loadCourse(entry); + CourseNode courseNode = course.getRunStructure().getNode(binder.getSubIdent()); + for(Identity assessedIdentity:assessedIdentities) { + UserCourseEnvironment userCourseEnv = AssessmentHelper.createAndInitUserCourseEnvironment(assessedIdentity, course); + courseAssessmentService.updateLastModifications(courseNode, userCourseEnv, doer, by); + } + } else { + OLATResource resource = ((BinderImpl)binder.getTemplate()).getOlatResource(); + RepositoryEntry referenceEntry = repositoryService.loadByResourceKey(resource.getKey()); + for(Identity assessedIdentity:assessedIdentities) { + AssessmentEntry assessmentEntry = assessmentService + .getOrCreateAssessmentEntry(assessedIdentity, null, binder.getEntry(), binder.getSubIdent(), Boolean.TRUE, referenceEntry); + if(by == Role.coach) { + assessmentEntry.setLastCoachModified(new Date()); + } else if(by == Role.user) { + assessmentEntry.setLastUserModified(new Date()); + } + assessmentService.updateAssessmentEntry(assessmentEntry); + } + } + } + + @Override + public List getAssessmentSections(BinderRef binder, Identity coach) { + return assessmentSectionDao.loadAssessmentSections(binder); + } + + @Override + public void updateAssessmentSections(BinderRef binderRef, List changes, Identity coachingIdentity) { + Binder binder = binderDao.loadByKey(binderRef.getKey()); + Map> assessedIdentitiesToChangesMap = new HashMap<>(); + for(AssessmentSectionChange change:changes) { + List identityChanges; + if(assessedIdentitiesToChangesMap.containsKey(change.getIdentity())) { + identityChanges = assessedIdentitiesToChangesMap.get(change.getIdentity()); + } else { + identityChanges = new ArrayList<>(); + assessedIdentitiesToChangesMap.put(change.getIdentity(), identityChanges); + } + identityChanges.add(change); + } + + for(Map.Entry> changesEntry:assessedIdentitiesToChangesMap.entrySet()) { + Identity assessedIdentity = changesEntry.getKey(); + List currentAssessmentSections = assessmentSectionDao.loadAssessmentSections(binder, assessedIdentity); + Set updatedAssessmentSections = new HashSet<>(currentAssessmentSections); + + List identityChanges = changesEntry.getValue(); + //check update or create + + for(AssessmentSectionChange change:identityChanges) { + AssessmentSection assessmentSection = change.getAssessmentSection(); + for(AssessmentSection currentAssessmentSection:currentAssessmentSections) { + if(assessmentSection != null && assessmentSection.equals(currentAssessmentSection)) { + assessmentSection = currentAssessmentSection; + } else if(change.getSection().equals(currentAssessmentSection.getSection())) { + assessmentSection = currentAssessmentSection; + } + } + + if(assessmentSection == null) { + assessmentSection = assessmentSectionDao + .createAssessmentSection(change.getScore(), change.getPassed(), change.getSection(), assessedIdentity); + } else { + ((AssessmentSectionImpl)assessmentSection).setScore(change.getScore()); + ((AssessmentSectionImpl)assessmentSection).setPassed(change.getPassed()); + assessmentSection = assessmentSectionDao.update(assessmentSection); + } + updatedAssessmentSections.add(assessmentSection); + } + + updateAssessmentEntry(assessedIdentity, binder, updatedAssessmentSections, coachingIdentity); + } + } + + private void updateAssessmentEntry(Identity assessedIdentity, Binder binder, Set assessmentSections, Identity coachingIdentity) { + boolean allPassed = true; + int totalSectionPassed = 0; + int totalSectionClosed = 0; + BigDecimal totalScore = new BigDecimal("0.0"); + AssessmentEntryStatus binderStatus = null; + + for(AssessmentSection assessmentSection:assessmentSections) { + if(assessmentSection.getScore() != null) { + totalScore = totalScore.add(assessmentSection.getScore()); + } + if(assessmentSection.getPassed() != null && assessmentSection.getPassed().booleanValue()) { + allPassed &= true; + totalSectionPassed++; + } + + Section section = assessmentSection.getSection(); + if(section.getSectionStatus() == SectionStatus.closed) { + totalSectionClosed++; + } + } + + Boolean totalPassed = null; + if(totalSectionClosed == assessmentSections.size()) { + totalPassed = Boolean.valueOf(allPassed); + } else { + if(assessmentSections.size() == totalSectionPassed) { + totalPassed = Boolean.TRUE; + } + binderStatus = AssessmentEntryStatus.inProgress; + } + + //order status from the entry / section + RepositoryEntry entry = binder.getEntry(); + if("CourseModule".equals(entry.getOlatResource().getResourceableTypeName())) { + ICourse course = CourseFactory.loadCourse(entry); + CourseNode courseNode = course.getRunStructure().getNode(binder.getSubIdent()); + ScoreEvaluation scoreEval= new ScoreEvaluation(totalScore.floatValue(), totalPassed, binderStatus, true, null, null, null, binder.getKey()); + UserCourseEnvironment userCourseEnv = AssessmentHelper.createAndInitUserCourseEnvironment(assessedIdentity, course); + courseAssessmentService.updateScoreEvaluation(courseNode, scoreEval, userCourseEnv, coachingIdentity, false, + Role.coach); + } else { + OLATResource resource = ((BinderImpl)binder.getTemplate()).getOlatResource(); + RepositoryEntry referenceEntry = repositoryService.loadByResourceKey(resource.getKey()); + AssessmentEntry assessmentEntry = assessmentService + .getOrCreateAssessmentEntry(assessedIdentity, null, binder.getEntry(), binder.getSubIdent(), Boolean.TRUE, referenceEntry); + assessmentEntry.setScore(totalScore); + assessmentEntry.setPassed(totalPassed); + assessmentEntry.setAssessmentStatus(binderStatus); + assessmentService.updateAssessmentEntry(assessmentEntry); + } + } + + @Override + public AssessmentEntryStatus getAssessmentStatus(Identity assessedIdentity, BinderRef binderRef) { + Binder binder = binderDao.loadByKey(binderRef.getKey()); + RepositoryEntry entry = binder.getEntry(); + + AssessmentEntryStatus status = null; + if("CourseModule".equals(entry.getOlatResource().getResourceableTypeName())) { + ICourse course = CourseFactory.loadCourse(entry); + CourseNode courseNode = course.getRunStructure().getNode(binder.getSubIdent()); + UserCourseEnvironment userCourseEnv = AssessmentHelper.createAndInitUserCourseEnvironment(assessedIdentity, course); + AssessmentEvaluation eval = courseAssessmentService.getAssessmentEvaluation(courseNode, userCourseEnv); + status = eval.getAssessmentStatus(); + } else { + OLATResource resource = ((BinderImpl)binder.getTemplate()).getOlatResource(); + RepositoryEntry referenceEntry = repositoryService.loadByResourceKey(resource.getKey()); + AssessmentEntry assessmentEntry = assessmentService + .getOrCreateAssessmentEntry(assessedIdentity, null, binder.getEntry(), binder.getSubIdent(), Boolean.TRUE, referenceEntry); + status = assessmentEntry.getAssessmentStatus(); + } + return status; + } + + @Override + public void setAssessmentStatus(Identity assessedIdentity, BinderRef binderRef, AssessmentEntryStatus status, Identity coachingIdentity) { + Boolean fullyAssessed = Boolean.FALSE; + if(status == AssessmentEntryStatus.done) { + fullyAssessed = Boolean.TRUE; + } + Binder binder = binderDao.loadByKey(binderRef.getKey()); + RepositoryEntry entry = binder.getEntry(); + if("CourseModule".equals(entry.getOlatResource().getResourceableTypeName())) { + ICourse course = CourseFactory.loadCourse(entry); + CourseNode courseNode = course.getRunStructure().getNode(binder.getSubIdent()); + PortfolioCourseNode pfNode = (PortfolioCourseNode)courseNode; + UserCourseEnvironment userCourseEnv = AssessmentHelper.createAndInitUserCourseEnvironment(assessedIdentity, course); + AssessmentEvaluation eval = courseAssessmentService.getAssessmentEvaluation(pfNode, userCourseEnv); + + ScoreEvaluation scoreEval = new ScoreEvaluation(eval.getScore(), eval.getPassed(), status, true, + null, null, null, binder.getKey()); + courseAssessmentService.updateScoreEvaluation(courseNode, scoreEval, userCourseEnv, coachingIdentity, false, + Role.coach); + } else { + OLATResource resource = ((BinderImpl)binder.getTemplate()).getOlatResource(); + RepositoryEntry referenceEntry = repositoryService.loadByResourceKey(resource.getKey()); + AssessmentEntry assessmentEntry = assessmentService + .getOrCreateAssessmentEntry(assessedIdentity, null, binder.getEntry(), binder.getSubIdent(), Boolean.TRUE, referenceEntry); + assessmentEntry.setFullyAssessed(fullyAssessed); + assessmentEntry.setAssessmentStatus(status); + assessmentService.updateAssessmentEntry(assessmentEntry); + } + } + + @Override + public EvaluationFormSurvey loadOrCreateSurvey(PageBody body, RepositoryEntry formEntry) { + EvaluationFormSurveyIdentifier surveyIdent = getSurveyIdent(body); + EvaluationFormSurvey survey = evaluationFormManager.loadSurvey(surveyIdent); + if (survey == null) { + survey = evaluationFormManager.createSurvey(surveyIdent, formEntry); + } + return survey; + } + + private OLATResourceable getOLATResourceableForEvaluationForm(PageBody body) { + return OresHelper.createOLATResourceableInstance("portfolio-evaluation", body.getKey()); + } + + @Override + public EvaluationFormSession loadOrCreateSession(EvaluationFormSurvey survey, Identity executor) { + EvaluationFormParticipation participation = evaluationFormManager.loadParticipationByExecutor(survey, executor); + if (participation == null) { + participation = evaluationFormManager.createParticipation(survey, executor); + } + + EvaluationFormSession session = evaluationFormManager.loadSessionByParticipation(participation); + if (session == null) { + session = evaluationFormManager.createSession(participation); + } + return session; + } + + @Override + public void deleteSurvey(PageBody body) { + EvaluationFormSurvey survey = evaluationFormManager.loadSurvey(getSurveyIdent(body)); + if (survey != null) { + evaluationFormManager.deleteSurvey(survey); + } + } + + private EvaluationFormSurveyIdentifier getSurveyIdent(PageBody body) { + OLATResourceable ores = getOLATResourceableForEvaluationForm(body); + return EvaluationFormSurveyIdentifier.of(ores); + } + +} diff --git a/Java/PrimaryStatusProviderController.java b/Java/PrimaryStatusProviderController.java new file mode 100644 index 0000000000000000000000000000000000000000..8eb33a2e4d03aec16ea2108ee0eec02503382029 --- /dev/null +++ b/Java/PrimaryStatusProviderController.java @@ -0,0 +1,142 @@ +/* + * Copyright 2021 ThoughtWorks, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.thoughtworks.go.addon.businesscontinuity.primary.controller; + +import com.google.gson.Gson; +import com.thoughtworks.go.addon.businesscontinuity.ConfigFileType; +import com.thoughtworks.go.addon.businesscontinuity.DatabaseStatusProvider; +import com.thoughtworks.go.addon.businesscontinuity.FileDetails; +import com.thoughtworks.go.addon.businesscontinuity.PluginsList; +import com.thoughtworks.go.addon.businesscontinuity.primary.ServerStatusResponse; +import com.thoughtworks.go.addon.businesscontinuity.primary.service.GoFilesStatusProvider; +import com.thoughtworks.go.util.SystemEnvironment; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import static org.apache.commons.io.IOUtils.copy; +import static org.apache.commons.lang3.StringUtils.isBlank; +import static org.apache.commons.lang3.StringUtils.isEmpty; + +@Controller +@SuppressWarnings("WeakerAccess") +// BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor +// @RequestMapping(value = "/add-on/business-continuity/api") +// FIXED: +public class PrimaryStatusProviderController { + + private GoFilesStatusProvider goFilesStatusProvider; + private DatabaseStatusProvider databaseStatusProvider; + private final SystemEnvironment systemEnvironment; + private PluginsList pluginsList; + + @Autowired + public PrimaryStatusProviderController(GoFilesStatusProvider goFilesStatusProvider, DatabaseStatusProvider databaseStatusProvider, PluginsList pluginsList, SystemEnvironment systemEnvironment) { + this.goFilesStatusProvider = goFilesStatusProvider; + this.databaseStatusProvider = databaseStatusProvider; + this.pluginsList = pluginsList; + this.systemEnvironment = systemEnvironment; + } + + @RequestMapping(value = "/health-check", method = RequestMethod.GET) + @ResponseBody + public String healthCheck() { + return "OK!"; + } + + @RequestMapping(value = "/latest_database_wal_location", method = RequestMethod.GET) + @ResponseBody + public String latestDatabaseWalLocation() { + return databaseStatusProvider.latestWalLocation(); + } + + @RequestMapping(value = "/config_files_status", method = RequestMethod.GET) + public void latestStatus(HttpServletResponse response) throws IOException { + Map latestFileStatusMap = goFilesStatusProvider.getLatestStatusMap(); + + Map fileDetailsMap = new HashMap<>(); + for (ConfigFileType configFileType : latestFileStatusMap.keySet()) { + if (!isEmpty(latestFileStatusMap.get(configFileType))) { + fileDetailsMap.put(configFileType, new FileDetails(latestFileStatusMap.get(configFileType))); + } + } + + ServerStatusResponse serverStatusResponse = new ServerStatusResponse(goFilesStatusProvider.updateInterval(), goFilesStatusProvider.getLastUpdateTime(), fileDetailsMap); + String responseBody = new Gson().toJson(serverStatusResponse); + response.setContentType("application/json"); + response.getOutputStream().print(responseBody); + } + + @RequestMapping(value = "/cruise_config", method = RequestMethod.GET) + public void getLatestCruiseConfigXML(HttpServletResponse response) { + serveFile(ConfigFileType.CRUISE_CONFIG_XML.load(systemEnvironment), response, "text/xml"); + } + + @RequestMapping(value = "/user_feature_toggle", method = RequestMethod.GET) + public void geUserFeatureToggleFile(HttpServletResponse response) { + serveFile(ConfigFileType.USER_FEATURE_TOGGLE.load(systemEnvironment), response, "text/json"); + } + + @RequestMapping(value = "/cipher.aes", method = RequestMethod.GET) + public void getLatestAESCipher(HttpServletResponse response) { + serveFile(ConfigFileType.AES_CIPHER.load(systemEnvironment), response, "text/plain"); + } + + @RequestMapping(value = "/jetty_config", method = RequestMethod.GET) + public void getLatestJettyXML(HttpServletResponse response) { + serveFile(ConfigFileType.JETTY_XML.load(systemEnvironment), response, "text/xml"); + } + + @RequestMapping(value = "/plugin_files_status", method = RequestMethod.GET) + public void latest(HttpServletResponse response) throws IOException { + String pluginsJSON = pluginsList.getPluginsJSON(); + response.setContentType("application/json"); + response.getOutputStream().print(pluginsJSON); + } + + @RequestMapping(value = "/plugin", method = RequestMethod.GET) + public void getPluginFile( + @RequestParam("folderName") String folderName, + @RequestParam("pluginName") String pluginName, + HttpServletResponse response) { + String pluginFolderPath = isBlank(folderName) || folderName.equalsIgnoreCase("bundled") ? systemEnvironment.getBundledPluginAbsolutePath() : systemEnvironment.getExternalPluginAbsolutePath(); + File pluginFile = new File(pluginFolderPath, pluginName); + serveFile(pluginFile, response, "application/octet-stream"); + } + + private void serveFile(File file, HttpServletResponse response, String contentType) { + try (FileInputStream inputStream = new FileInputStream(file)) { + response.setStatus(HttpServletResponse.SC_OK); + response.setCharacterEncoding("UTF-8"); + response.setContentType(contentType); + copy(inputStream, response.getOutputStream()); + response.flushBuffer(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/Java/Profile.java b/Java/Profile.java new file mode 100644 index 0000000000000000000000000000000000000000..a9eaf9ee391a09e139b26f75483ff444a26e3647 --- /dev/null +++ b/Java/Profile.java @@ -0,0 +1,691 @@ +/* + * Copyright 2013-2022 Erudika. https://erudika.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. + * + * For issues and patches go to: https://github.com/erudika + */ +package com.erudika.scoold.core; +import com.erudika.para.client.ParaClient; +import com.erudika.para.core.Sysprop; +import com.erudika.para.core.User; +import com.erudika.para.core.annotations.Stored; +import com.erudika.para.core.utils.Config; +import com.erudika.para.core.utils.Pager; +import com.erudika.para.core.utils.Para; +import com.erudika.para.core.utils.Utils; +import com.erudika.scoold.utils.ScooldUtils; +import com.fasterxml.jackson.annotation.JsonIgnore; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.temporal.IsoFields; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.commons.lang3.StringUtils; +import org.hibernate.validator.constraints.URL; + +public class Profile extends Sysprop { + + private static final long serialVersionUID = 1L; + + @Stored private String originalName; + @Stored private String originalPicture; + @Stored private Long lastseen; + @Stored private String location; + @Stored private String latlng; + @Stored private String status; + @Stored private String aboutme; + @Stored private String badges; + @Stored private String groups; + @Stored private Long upvotes; + @Stored private Long downvotes; + @Stored private Long comments; + @Stored @URL private String picture; + @Stored @URL private String website; + @Stored private List favtags; + @Stored private Set favspaces; + @Stored private Set spaces; + @Stored private Boolean replyEmailsEnabled; + @Stored private Boolean commentEmailsEnabled; + @Stored private Boolean favtagsEmailsEnabled; + @Stored private Boolean anonymityEnabled; + @Stored private Boolean darkmodeEnabled; + @Stored private Integer yearlyVotes; + @Stored private Integer quarterlyVotes; + @Stored private Integer monthlyVotes; + @Stored private Integer weeklyVotes; + + private transient String newbadges; + private transient Integer newreports; + private transient User user; + + public enum Badge { + VETERAN(10), //regular visitor //NOT IMPLEMENTED + + NICEPROFILE(10), //100% profile completed + REPORTER(0), //for every report + VOTER(0), //100 total votes + COMMENTATOR(0), //100+ comments + CRITIC(0), //10+ downvotes + SUPPORTER(10), //50+ upvotes + EDITOR(0), //first edit of post + BACKINTIME(0), //for each rollback of post + NOOB(10), //first question + first approved answer + ENTHUSIAST(0), //100+ rep [// ] + FRESHMAN(0), //300+ rep [//// ] + SCHOLAR(0), //500+ rep [////// ] + TEACHER(0), //1000+ rep [//////// ] + PROFESSOR(0), //5000+ rep [////////// ] + GEEK(0), //9000+ rep [////////////] + GOODQUESTION(10), //20+ votes + GOODANSWER(10), //10+ votes + EUREKA(0), //for every answer to own question + SENIOR(0), //one year + member + DISCIPLINED(0); //each time user deletes own comment + + private final int reward; + + Badge(int reward) { + this.reward = reward; + } + + public String toString() { + return super.toString().toLowerCase(); + } + + public Integer getReward() { + return this.reward; + } + } + + public Profile() { + this(null, null); + } + + public Profile(String id) { + this(id, null); + } + + public Profile(String userid, String name) { + setId(id(userid)); + setName(name); + this.status = ""; + this.aboutme = ""; + this.location = ""; + this.website = ""; + this.badges = ""; + this.upvotes = 0L; + this.downvotes = 0L; + this.comments = 0L; + this.yearlyVotes = 0; + this.quarterlyVotes = 0; + this.monthlyVotes = 0; + this.weeklyVotes = 0; + this.anonymityEnabled = false; + this.darkmodeEnabled = false; + this.favtagsEmailsEnabled = ScooldUtils.getConfig().favoriteTagsEmailsEnabled(); + this.replyEmailsEnabled = ScooldUtils.getConfig().replyEmailsEnabled(); + this.commentEmailsEnabled = ScooldUtils.getConfig().commentEmailsEnabled(); + } + + public static final String id(String userid) { + if (StringUtils.endsWith(userid, Para.getConfig().separator() + "profile")) { + return userid; + } else { + return userid != null ? userid + Para.getConfig().separator() + "profile" : null; + } + } + + public static Profile fromUser(User u) { + Profile p = new Profile(u.getId(), u.getName()); + p.setUser(u); + p.setOriginalName(u.getName()); + p.setPicture(u.getPicture()); + p.setAppid(u.getAppid()); + p.setCreatorid(u.getId()); + p.setTimestamp(u.getTimestamp()); + p.setGroups(ScooldUtils.getInstance().isRecognizedAsAdmin(u) + ? User.Groups.ADMINS.toString() : u.getGroups()); + // auto-assign spaces to new users + String space = StringUtils.substringBefore(ScooldUtils.getConfig().autoAssignSpaces(), ","); + if (!StringUtils.isBlank(space) && !ScooldUtils.getInstance().isDefaultSpace(space)) { + Sysprop s = client().read(ScooldUtils.getInstance().getSpaceId(space)); + if (s == null) { + s = ScooldUtils.getInstance().buildSpaceObject(space); + client().create(s); // create the space it it's missing + } + if (ScooldUtils.getConfig().resetSpacesOnNewAssignment(u.isOAuth2User() || u.isLDAPUser() || u.isSAMLUser())) { + p.setSpaces(Collections.singleton(s.getId() + Para.getConfig().separator() + s.getName())); + } else { + p.getSpaces().add(s.getId() + Para.getConfig().separator() + s.getName()); + } + } + return p; + } + + private static ParaClient client() { + return ScooldUtils.getInstance().getParaClient(); + } + + @JsonIgnore + public User getUser() { + if (user == null) { + user = client().read(getCreatorid() == null + ? StringUtils.removeEnd(getId(), Para.getConfig().separator() + "profile") : getCreatorid()); + } + return user; + } + + public Integer getYearlyVotes() { + if (yearlyVotes < 0) { + yearlyVotes = 0; + } + return yearlyVotes; + } + + public void setYearlyVotes(Integer yearlyVotes) { + this.yearlyVotes = yearlyVotes; + } + + public Integer getQuarterlyVotes() { + if (quarterlyVotes < 0) { + quarterlyVotes = 0; + } + return quarterlyVotes; + } + + public void setQuarterlyVotes(Integer quarterlyVotes) { + this.quarterlyVotes = quarterlyVotes; + } + + public Integer getMonthlyVotes() { + if (monthlyVotes < 0) { + monthlyVotes = 0; + } + return monthlyVotes; + } + + public void setMonthlyVotes(Integer monthlyVotes) { + this.monthlyVotes = monthlyVotes; + } + + public Integer getWeeklyVotes() { + if (weeklyVotes < 0) { + weeklyVotes = 0; + } + return weeklyVotes; + } + + public void setWeeklyVotes(Integer weeklyVotes) { + this.weeklyVotes = weeklyVotes; + } + + public Boolean getReplyEmailsEnabled() { + return replyEmailsEnabled; + } + + public void setReplyEmailsEnabled(Boolean replyEmailsEnabled) { + this.replyEmailsEnabled = replyEmailsEnabled; + } + + public Boolean getCommentEmailsEnabled() { + return commentEmailsEnabled; + } + + public void setCommentEmailsEnabled(Boolean commentEmailsEnabled) { + this.commentEmailsEnabled = commentEmailsEnabled; + } + + public Boolean getFavtagsEmailsEnabled() { + return favtagsEmailsEnabled; + } + + public void setFavtagsEmailsEnabled(Boolean favtagsEmailsEnabled) { + this.favtagsEmailsEnabled = favtagsEmailsEnabled; + } + + public Boolean getAnonymityEnabled() { + return anonymityEnabled; + } + + public void setAnonymityEnabled(Boolean anonymityEnabled) { + this.anonymityEnabled = anonymityEnabled; + } + + public Boolean getDarkmodeEnabled() { + return darkmodeEnabled; + } + + public void setDarkmodeEnabled(Boolean darkmodeEnabled) { + this.darkmodeEnabled = darkmodeEnabled; + } + + public String getGroups() { + return groups; + } + + public void setGroups(String groups) { + this.groups = groups; + } + + public String getPicture() { + return picture; + } + + public void setPicture(String picture) { + this.picture = picture; + } + + public void setUser(User user) { + this.user = user; + } + + public String getLatlng() { + return latlng; + } + + public void setLatlng(String latlng) { + this.latlng = latlng; + } + + public String getNewbadges() { + return newbadges; + } + + public void setNewbadges(String newbadges) { + this.newbadges = newbadges; + } + + public List getFavtags() { + if (favtags == null) { + favtags = new LinkedList(); + } + return favtags; + } + + public void setFavtags(List favtags) { + this.favtags = favtags; + } + + public Set getFavspaces() { + if (favspaces == null) { + favspaces = new LinkedHashSet(); + } + return favspaces; + } + + public void setFavspaces(Set favspaces) { + this.favspaces = favspaces; + } + + public Set getSpaces() { + if (ScooldUtils.getInstance().isMod(this)) { + spaces = ScooldUtils.getInstance().getAllSpaces().stream(). + map(s -> s.getId() + Para.getConfig().separator() + s.getName()).collect(Collectors.toSet()); + } + if (spaces == null) { + spaces = new LinkedHashSet(); + } + if (spaces.isEmpty()) { + spaces.add(Post.DEFAULT_SPACE); + } + // this is confusing - let admins control who is in the default space + //if (spaces.size() > 1 && spaces.contains(Post.DEFAULT_SPACE)) { + // spaces.remove(Post.DEFAULT_SPACE); + //} + return spaces; + } + + public void setSpaces(Set spaces) { + this.spaces = spaces; + } + + @JsonIgnore + public Set getAllSpaces() { + return getSpaces().stream().filter(s -> !s.equalsIgnoreCase(Post.DEFAULT_SPACE)).collect(Collectors.toSet()); + } + + public Long getLastseen() { + return lastseen; + } + + public void setLastseen(Long val) { + this.lastseen = val; + } + + public String getWebsite() { + return website; + } + + public void setWebsite(String website) { + this.website = website; + } + + public Long getComments() { + return comments; + } + + public void setComments(Long comments) { + this.comments = comments; + } + + public Long getDownvotes() { + return downvotes; + } + + public void setDownvotes(Long downvotes) { + this.downvotes = downvotes; + } + + public Long getUpvotes() { + return upvotes; + } + + public void setUpvotes(Long upvotes) { + this.upvotes = upvotes; + } + + public String getBadges() { + return badges; + } + + public void setBadges(String badges) { + this.badges = badges; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getAboutme() { + return this.aboutme; + } + + public void setAboutme(String aboutme) { + this.aboutme = aboutme; + } + + public String getOriginalName() { + return originalName; + } + + public void setOriginalName(String originalName) { + // BUG: NVD-CWE-Other Other + // this.originalName = originalName; + // FIXED: + this.originalName = StringUtils.abbreviate(originalName, 256); + } + + public String getOriginalPicture() { + return originalPicture; + } + + public void setOriginalPicture(String originalPicture) { + this.originalPicture = originalPicture; + } + + @SuppressWarnings("unchecked") + public List getAllQuestions(Pager pager) { + if (getId() == null) { + return new ArrayList(); + } + return (List) getPostsForUser(Utils.type(Question.class), pager); + } + + @SuppressWarnings("unchecked") + public List getAllAnswers(Pager pager) { + if (getId() == null) { + return new ArrayList(); + } + return (List) getPostsForUser(Utils.type(Reply.class), pager); + } + + @SuppressWarnings("unchecked") + public List getAllUnapprovedQuestions(Pager pager) { + if (getId() == null) { + return new ArrayList(); + } + return (List) getPostsForUser(Utils.type(UnapprovedQuestion.class), pager); + } + + @SuppressWarnings("unchecked") + public List getAllUnapprovedAnswers(Pager pager) { + if (getId() == null) { + return new ArrayList(); + } + return (List) getPostsForUser(Utils.type(UnapprovedReply.class), pager); + } + + private List getPostsForUser(String type, Pager pager) { + pager.setSortby("votes"); + return client().findTerms(type, Collections.singletonMap(Config._CREATORID, getId()), true, pager); + } + + public String getFavtagsString() { + if (getFavtags().isEmpty()) { + return ""; + } + return StringUtils.join(getFavtags(), ", "); + } + + public boolean hasFavtags() { + return !getFavtags().isEmpty(); + } + + public boolean hasSpaces() { + return !(getSpaces().size() <= 1 && getSpaces().contains(Post.DEFAULT_SPACE)); + } + + public void removeSpace(String space) { + String sid = ScooldUtils.getInstance().getSpaceId(space); + Iterator it = getSpaces().iterator(); + while (it.hasNext()) { + if (it.next().startsWith(sid + Para.getConfig().separator())) { + it.remove(); + } + } + } + + public long getTotalVotes() { + if (upvotes == null) { + upvotes = 0L; + } + if (downvotes == null) { + downvotes = 0L; + } + + return upvotes + downvotes; + } + + public void addRep(int rep) { + if (getVotes() == null) { + setVotes(0); + } + setVotes(getVotes() + rep); + updateVoteGains(rep); + } + + public void removeRep(int rep) { + if (getVotes() == null) { + setVotes(0); + } + setVotes(getVotes() - rep); + updateVoteGains(-rep); + if (getVotes() < 0) { + setVotes(0); + } + } + + public void incrementUpvotes() { + if (this.upvotes == null) { + this.upvotes = 1L; + } else { + this.upvotes = this.upvotes + 1L; + } + } + + public void incrementDownvotes() { + if (this.downvotes == null) { + this.downvotes = 1L; + } else { + this.downvotes = this.downvotes + 1L; + } + } + + private void updateVoteGains(int rep) { + Long updated = Optional.ofNullable(getUpdated()).orElse(getTimestamp()); + LocalDateTime lastUpdate = LocalDateTime.ofInstant(Instant.ofEpochMilli(updated), ZoneId.systemDefault()); + LocalDate now = LocalDate.now(); + if (now.getYear() != lastUpdate.getYear()) { + yearlyVotes = rep; + } else { + yearlyVotes += rep; + } + if (now.get(IsoFields.QUARTER_OF_YEAR) != lastUpdate.get(IsoFields.QUARTER_OF_YEAR)) { + quarterlyVotes = rep; + } else { + quarterlyVotes += rep; + } + if (now.getMonthValue() != lastUpdate.getMonthValue()) { + monthlyVotes = rep; + } else { + monthlyVotes += rep; + } + if (now.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR) != lastUpdate.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR)) { + weeklyVotes = rep; + } else { + weeklyVotes += rep; + } + setUpdated(Utils.timestamp()); + } + + public boolean hasBadge(Badge b) { + return StringUtils.containsIgnoreCase(badges, ",".concat(b.toString()).concat(",")); + } + + public void addBadge(Badge b) { + String badge = b.toString(); + if (StringUtils.isBlank(badges)) { + badges = ","; + } + badges = badges.concat(badge).concat(","); + addRep(b.getReward()); + } + + public void addBadges(Badge[] larr) { + for (Badge badge : larr) { + addBadge(badge); + addRep(badge.getReward()); + } + } + + public void removeBadge(Badge b) { + String badge = b.toString(); + if (StringUtils.isBlank(badges)) { + return; + } + badge = ",".concat(badge).concat(","); + + if (badges.contains(badge)) { + badges = badges.replaceFirst(badge, ","); + removeRep(b.getReward()); + } + if (StringUtils.isBlank(badges.replaceAll(",", ""))) { + badges = ""; + } + } + + public HashMap getBadgesMap() { + HashMap badgeMap = new HashMap(0); + if (StringUtils.isBlank(badges)) { + return badgeMap; + } + + for (String badge : badges.split(",")) { + Integer val = badgeMap.get(badge); + int count = (val == null) ? 0 : val.intValue(); + badgeMap.put(badge, ++count); + } + + badgeMap.remove(""); + return badgeMap; + } + + public boolean isComplete() { + return (!StringUtils.isBlank(location) + && !StringUtils.isBlank(aboutme) + && !StringUtils.isBlank(website)); + } + + public String create() { + setLastseen(System.currentTimeMillis()); + client().create(this); + return getId(); + } + + public void update() { + setLastseen(System.currentTimeMillis()); + updateVoteGains(0); // reset vote gains if they we're past the time frame + client().update(this); + } + + public void delete() { + client().delete(this); + client().delete(getUser()); + ScooldUtils.getInstance().unsubscribeFromAllNotifications(this); + } + + public int countNewReports() { + if (newreports == null) { + newreports = client().getCount(Utils.type(Report.class), + Collections.singletonMap("properties.closed", false)).intValue(); + } + return newreports; + } + + public boolean equals(Object obj) { + if (obj == null || getClass() != obj.getClass()) { + return false; + } + return Objects.equals(getName(), ((Profile) obj).getName()) + && Objects.equals(getLocation(), ((Profile) obj).getLocation()) + && Objects.equals(getId(), ((Profile) obj).getId()); + } + + public int hashCode() { + return Objects.hashCode(getName()) + Objects.hashCode(getId()); + } +} diff --git a/Java/ProfileController.java b/Java/ProfileController.java new file mode 100644 index 0000000000000000000000000000000000000000..b029415e274cc2ae203a4461e3fee3beba4b53de --- /dev/null +++ b/Java/ProfileController.java @@ -0,0 +1,307 @@ +/* + * Copyright 2013-2022 Erudika. https://erudika.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. + * + * For issues and patches go to: https://github.com/erudika + */ +package com.erudika.scoold.controllers; + +import com.cloudinary.Cloudinary; +import com.cloudinary.utils.ObjectUtils; +import com.erudika.para.core.User; +import static com.erudika.para.core.User.Groups.MODS; +import static com.erudika.para.core.User.Groups.USERS; +import com.erudika.para.core.utils.Pager; +import com.erudika.para.core.utils.ParaObjectUtils; +import com.erudika.para.core.utils.Utils; +import com.erudika.scoold.ScooldConfig; +import static com.erudika.scoold.ScooldServer.PEOPLELINK; +import static com.erudika.scoold.ScooldServer.PROFILELINK; +import static com.erudika.scoold.ScooldServer.SIGNINLINK; +import com.erudika.scoold.core.Post; +import com.erudika.scoold.core.Profile; +import com.erudika.scoold.core.Profile.Badge; +import com.erudika.scoold.core.Question; +import com.erudika.scoold.core.Reply; +import com.erudika.scoold.utils.ScooldUtils; +import com.erudika.scoold.utils.avatars.*; +import java.util.*; +import javax.inject.Inject; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.apache.commons.lang3.StringUtils; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +/** + * + * @author Alex Bogdanovski [alex@erudika.com] + */ +@Controller +@RequestMapping("/profile") +public class ProfileController { + + private static final ScooldConfig CONF = ScooldUtils.getConfig(); + private final ScooldUtils utils; + private final GravatarAvatarGenerator gravatarAvatarGenerator; + private final AvatarRepository avatarRepository; + + @Inject + public ProfileController(ScooldUtils utils, GravatarAvatarGenerator gravatarAvatarGenerator, AvatarRepositoryProxy avatarRepository) { + this.utils = utils; + this.gravatarAvatarGenerator = gravatarAvatarGenerator; + this.avatarRepository = avatarRepository; + } + + @GetMapping({"", "/{id}/**"}) + public String get(@PathVariable(required = false) String id, HttpServletRequest req, Model model) { + if (!utils.isAuthenticated(req) && StringUtils.isBlank(id)) { + return "redirect:" + SIGNINLINK + "?returnto=" + PROFILELINK; + } + Profile authUser = utils.getAuthUser(req); + Profile showUser; + boolean isMyProfile; + + if (StringUtils.isBlank(id) || isMyid(authUser, Profile.id(id))) { + //requested userid !exists or = my userid => show my profile + showUser = authUser; + isMyProfile = true; + } else { + showUser = utils.getParaClient().read(Profile.id(id)); + isMyProfile = isMyid(authUser, Profile.id(id)); + } + + if (showUser == null || !ParaObjectUtils.typesMatch(showUser)) { + return "redirect:" + PROFILELINK; + } + + boolean protekted = !utils.isDefaultSpacePublic() && !utils.isAuthenticated(req); + boolean sameSpace = (utils.canAccessSpace(showUser, "default") && utils.canAccessSpace(authUser, "default")) || + (authUser != null && showUser.getSpaces().stream().anyMatch(s -> utils.canAccessSpace(authUser, s))); + if (protekted || !sameSpace) { + return "redirect:" + PEOPLELINK; + } + + Pager itemcount1 = utils.getPager("page1", req); + Pager itemcount2 = utils.getPager("page2", req); + List questionslist = getQuestions(authUser, showUser, isMyProfile, itemcount1); + List answerslist = getAnswers(authUser, showUser, isMyProfile, itemcount2); + + model.addAttribute("path", "profile.vm"); + model.addAttribute("title", showUser.getName()); + model.addAttribute("description", getUserDescription(showUser, itemcount1.getCount(), itemcount2.getCount())); + model.addAttribute("ogimage", utils.getFullAvatarURL(showUser, AvatarFormat.Profile)); + model.addAttribute("includeGMapsScripts", utils.isNearMeFeatureEnabled()); + model.addAttribute("showUser", showUser); + model.addAttribute("isMyProfile", isMyProfile); + model.addAttribute("badgesCount", showUser.getBadgesMap().size()); + model.addAttribute("canEdit", isMyProfile || canEditProfile(authUser, id)); + model.addAttribute("canEditAvatar", CONF.avatarEditsEnabled()); + model.addAttribute("gravatarPicture", gravatarAvatarGenerator.getLink(showUser, AvatarFormat.Profile)); + model.addAttribute("isGravatarPicture", gravatarAvatarGenerator.isLink(showUser.getPicture())); + model.addAttribute("itemcount1", itemcount1); + model.addAttribute("itemcount2", itemcount2); + model.addAttribute("questionslist", questionslist); + model.addAttribute("answerslist", answerslist); + model.addAttribute("nameEditsAllowed", CONF.nameEditsEnabled()); + return "base"; + } + + @PostMapping("/{id}/make-mod") + public String makeMod(@PathVariable String id, HttpServletRequest req, HttpServletResponse res) { + Profile authUser = utils.getAuthUser(req); + if (!isMyid(authUser, Profile.id(id))) { + Profile showUser = utils.getParaClient().read(Profile.id(id)); + if (showUser != null) { + if (utils.isAdmin(authUser) && !utils.isAdmin(showUser)) { + showUser.setGroups(utils.isMod(showUser) ? USERS.toString() : MODS.toString()); + showUser.update(); + } + } + } + if (utils.isAjaxRequest(req)) { + res.setStatus(200); + return "base"; + } else { + return "redirect:" + PROFILELINK + "/" + id; + } + } + + @PostMapping("/{id}") + public String edit(@PathVariable(required = false) String id, @RequestParam(required = false) String name, + @RequestParam(required = false) String location, @RequestParam(required = false) String latlng, + @RequestParam(required = false) String website, @RequestParam(required = false) String aboutme, + @RequestParam(required = false) String picture, HttpServletRequest req, Model model) { + Profile authUser = utils.getAuthUser(req); + Profile showUser = getProfileForEditing(id, authUser); + if (showUser != null) { + boolean updateProfile = false; + if (!isMyid(authUser, id)) { + showUser = utils.getParaClient().read(Profile.id(id)); + } + if (!StringUtils.equals(showUser.getLocation(), location)) { + showUser.setLatlng(latlng); + showUser.setLocation(location); + updateProfile = true; + } + if (!StringUtils.equals(showUser.getWebsite(), website) && + (StringUtils.isBlank(website) || Utils.isValidURL(website))) { + showUser.setWebsite(website); + updateProfile = true; + } + if (!StringUtils.equals(showUser.getAboutme(), aboutme)) { + showUser.setAboutme(aboutme); + updateProfile = true; + } + + updateProfile = updateUserPictureAndName(showUser, picture, name) || updateProfile; + + boolean isComplete = showUser.isComplete() && isMyid(authUser, showUser.getId()); + if (updateProfile || utils.addBadgeOnce(showUser, Badge.NICEPROFILE, isComplete)) { + showUser.update(); + } + model.addAttribute("user", showUser); + } + return "redirect:" + PROFILELINK + (isMyid(authUser, id) ? "" : "/" + id); + } + + @SuppressWarnings("unchecked") + @ResponseBody + @PostMapping(value = "/{id}/cloudinary-upload-link", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity> generateCloudinaryUploadLink(@PathVariable String id, HttpServletRequest req) { + if (!ScooldUtils.isCloudinaryAvatarRepositoryEnabled()) { + return ResponseEntity.status(404).build(); + } + + Profile authUser = utils.getAuthUser(req); + Profile showUser = getProfileForEditing(id, authUser); + if (showUser == null) { + return ResponseEntity.status(403).build(); + } + + String preset = "avatar"; + String publicId = "avatars/" + id; + long timestamp = Utils.timestamp() / 1000; + Cloudinary cloudinary = new Cloudinary(CONF.cloudinaryUrl()); + String signature = cloudinary.apiSignRequest(ObjectUtils.asMap( + "public_id", publicId, + "timestamp", String.valueOf(timestamp), + "upload_preset", preset + ), cloudinary.config.apiSecret); + + Map response = new HashMap(); + response.put("url", "https://api.cloudinary.com/v1_1/" + cloudinary.config.cloudName + "/image/upload"); + Map data = new HashMap(); + data.put("resource_type", "image"); + data.put("public_id", publicId); + data.put("upload_preset", preset); + data.put("filename", id); + data.put("timestamp", timestamp); + data.put("api_key", cloudinary.config.apiKey); + data.put("signature", signature); + response.put("data", data); + + return ResponseEntity.ok().body(response); + } + + private Profile getProfileForEditing(String id, Profile authUser) { + if (!canEditProfile(authUser, id)) { + return null; + } + return isMyid(authUser, id) ? authUser : (Profile) utils.getParaClient().read(Profile.id(id)); + } + + private boolean updateUserPictureAndName(Profile showUser, String picture, String name) { + boolean updateProfile = false; + boolean updateUser = false; + User u = showUser.getUser(); + + if (CONF.avatarEditsEnabled() && !StringUtils.isBlank(picture)) { + updateProfile = avatarRepository.store(showUser, picture); + } + + if (CONF.nameEditsEnabled() && !StringUtils.isBlank(name)) { + // BUG: NVD-CWE-Other Other + // showUser.setName(name); + // FIXED: + showUser.setName(StringUtils.abbreviate(name, 256)); + if (StringUtils.isBlank(showUser.getOriginalName())) { + showUser.setOriginalName(name); + } + if (!u.getName().equals(name)) { + u.setName(name); + updateUser = true; + } + updateProfile = true; + } + + if (updateUser) { + utils.getParaClient().update(u); + } + return updateProfile; + } + + private boolean isMyid(Profile authUser, String id) { + return authUser != null && (StringUtils.isBlank(id) || authUser.getId().equals(Profile.id(id))); + } + + private boolean canEditProfile(Profile authUser, String id) { + return isMyid(authUser, id) || utils.isAdmin(authUser); + } + + private Object getUserDescription(Profile showUser, Long questions, Long answers) { + if (showUser == null) { + return ""; + } + return showUser.getVotes() + " points, " + + showUser.getBadgesMap().size() + " badges, " + + questions + " questions, " + + answers + " answers " + + Utils.abbreviate(showUser.getAboutme(), 150); + } + + public List getQuestions(Profile authUser, Profile showUser, boolean isMyProfile, Pager itemcount) { + if (utils.postsNeedApproval() && (isMyProfile || utils.isMod(authUser))) { + List qlist = new ArrayList<>(); + Pager p = new Pager(itemcount.getPage(), itemcount.getLimit()); + qlist.addAll(showUser.getAllQuestions(itemcount)); + qlist.addAll(showUser.getAllUnapprovedQuestions(p)); + itemcount.setCount(itemcount.getCount() + p.getCount()); + return qlist; + } else { + return showUser.getAllQuestions(itemcount); + } + } + + public List getAnswers(Profile authUser, Profile showUser, boolean isMyProfile, Pager itemcount) { + if (utils.postsNeedApproval() && (isMyProfile || utils.isMod(authUser))) { + List alist = new ArrayList<>(); + Pager p = new Pager(itemcount.getPage(), itemcount.getLimit()); + alist.addAll(showUser.getAllAnswers(itemcount)); + alist.addAll(showUser.getAllUnapprovedAnswers(p)); + itemcount.setCount(itemcount.getCount() + p.getCount()); + return alist; + } else { + return showUser.getAllAnswers(itemcount); + } + } +} diff --git a/Java/ProxyServlet.java b/Java/ProxyServlet.java new file mode 100644 index 0000000000000000000000000000000000000000..134eeb27e0aa398f6b2d5ae53abdf1e6096c74fc --- /dev/null +++ b/Java/ProxyServlet.java @@ -0,0 +1,353 @@ +/** + * $Id: ProxyServlet.java,v 1.4 2013/12/13 13:18:11 david Exp $ + * Copyright (c) 2011-2012, JGraph Ltd + */ +package com.mxgraph.online; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.net.UnknownHostException; +import java.net.InetAddress; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.google.apphosting.api.DeadlineExceededException; +import com.mxgraph.online.Utils.UnsupportedContentException; + +/** + * Servlet implementation ProxyServlet + */ +@SuppressWarnings("serial") +public class ProxyServlet extends HttpServlet +{ + private static final Logger log = Logger + .getLogger(HttpServlet.class.getName()); + + /** + * Buffer size for content pass-through. + */ + private static int BUFFER_SIZE = 3 * 1024; + + /** + * GAE deadline is 30 secs so timeout before that to avoid + * HardDeadlineExceeded errors. + */ + private static final int TIMEOUT = 29000; + + /** + * A resuable empty byte array instance. + */ + private static byte[] emptyBytes = new byte[0]; + + /** + * @see HttpServlet#HttpServlet() + */ + public ProxyServlet() + { + super(); + } + + /** + * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) + */ + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException + { + String urlParam = request.getParameter("url"); + + if (checkUrlParameter(urlParam)) + { + // build the UML source from the compressed request parameter + String ref = request.getHeader("referer"); + String ua = request.getHeader("User-Agent"); + String auth = request.getHeader("Authorization"); + String dom = getCorsDomain(ref, ua); + + try(OutputStream out = response.getOutputStream()) + { + request.setCharacterEncoding("UTF-8"); + response.setCharacterEncoding("UTF-8"); + + URL url = new URL(urlParam); + URLConnection connection = url.openConnection(); + connection.setConnectTimeout(TIMEOUT); + connection.setReadTimeout(TIMEOUT); + + response.setHeader("Cache-Control", "private, max-age=86400"); + + // Workaround for 451 response from Iconfinder CDN + connection.setRequestProperty("User-Agent", "draw.io"); + + //Forward auth header + if (auth != null) + { + connection.setRequestProperty("Authorization", auth); + } + + if (dom != null && dom.length() > 0) + { + response.addHeader("Access-Control-Allow-Origin", dom); + } + + // Status code pass-through and follow redirects + if (connection instanceof HttpURLConnection) + { + ((HttpURLConnection) connection) + .setInstanceFollowRedirects(true); + int status = ((HttpURLConnection) connection) + .getResponseCode(); + int counter = 0; + + // Follows a maximum of 6 redirects + while (counter++ <= 6 + && (status == HttpURLConnection.HTTP_MOVED_PERM + || status == HttpURLConnection.HTTP_MOVED_TEMP)) + { + String redirectUrl = connection.getHeaderField("Location"); + + if (!checkUrlParameter(redirectUrl)) + { + break; + } + + url = new URL(redirectUrl); + connection = url.openConnection(); + ((HttpURLConnection) connection) + .setInstanceFollowRedirects(true); + connection.setConnectTimeout(TIMEOUT); + connection.setReadTimeout(TIMEOUT); + + // Workaround for 451 response from Iconfinder CDN + connection.setRequestProperty("User-Agent", "draw.io"); + status = ((HttpURLConnection) connection) + .getResponseCode(); + } + + if (status >= 200 && status <= 299) + { + response.setStatus(status); + + // Copies input stream to output stream + InputStream is = connection.getInputStream(); + byte[] head = (contentAlwaysAllowed(urlParam)) ? emptyBytes + : Utils.checkStreamContent(is); + response.setContentType("application/octet-stream"); + String base64 = request.getParameter("base64"); + copyResponse(is, out, head, + base64 != null && base64.equals("1")); + } + else + { + response.setStatus(HttpURLConnection.HTTP_PRECON_FAILED); + } + } + else + { + response.setStatus(HttpURLConnection.HTTP_UNSUPPORTED_TYPE); + } + + out.flush(); + + log.log(Level.FINEST, "processed proxy request: url=" + + ((urlParam != null) ? urlParam : "[null]") + + ", referer=" + ((ref != null) ? ref : "[null]") + + ", user agent=" + ((ua != null) ? ua : "[null]")); + } + catch (DeadlineExceededException e) + { + response.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT); + } + catch (UnknownHostException | FileNotFoundException e) + { + // do not log 404 and DNS errors + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + } + catch (UnsupportedContentException e) + { + response.setStatus(HttpServletResponse.SC_FORBIDDEN); + log.log(Level.SEVERE, "proxy request with invalid content: url=" + + ((urlParam != null) ? urlParam : "[null]") + + ", referer=" + ((ref != null) ? ref : "[null]") + + ", user agent=" + ((ua != null) ? ua : "[null]")); + } + catch (Exception e) + { + response.setStatus( + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + log.log(Level.FINE, "proxy request failed: url=" + + ((urlParam != null) ? urlParam : "[null]") + + ", referer=" + ((ref != null) ? ref : "[null]") + + ", user agent=" + ((ua != null) ? ua : "[null]")); + e.printStackTrace(); + } + } + else + { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + log.log(Level.SEVERE, + "proxy request with invalid URL parameter: url=" + + ((urlParam != null) ? urlParam : "[null]")); + } + } + + /** + * Dynamically generated CORS header for known domains. + * @throws IOException + */ + protected void copyResponse(InputStream is, OutputStream out, byte[] head, + boolean base64) throws IOException + { + if (base64) + { + try (BufferedInputStream in = new BufferedInputStream(is, + BUFFER_SIZE)) + { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + byte[] buffer = new byte[0xFFFF]; + + os.write(head, 0, head.length); + + for (int len = is.read(buffer); len != -1; len = is.read(buffer)) + { + os.write(buffer, 0, len); + } + + out.write(mxBase64.encodeToString(os.toByteArray(), false).getBytes()); + } + } + else + { + out.write(head); + Utils.copy(is, out); + } + } + + /** + * Checks if the URL parameter is legal. + */ + public boolean checkUrlParameter(String url) + { + if (url != null) + { + try + { + URL parsedUrl = new URL(url); + String protocol = parsedUrl.getProtocol(); + String host = parsedUrl.getHost(); + InetAddress address = InetAddress.getByName(host); + String hostAddress = address.getHostAddress(); + host = host.toLowerCase(); + + return (protocol.equals("http") || protocol.equals("https")) + && !address.isAnyLocalAddress() + && !address.isLoopbackAddress() + // BUG: CWE-918 Server-Side Request Forgery (SSRF) + // + // FIXED: + && !address.isLinkLocalAddress() + && !host.endsWith(".internal") // Redundant + && !host.endsWith(".local") // Redundant + && !host.contains("localhost") // Redundant + && !hostAddress.startsWith("0.") // 0.0.0.0/8 + && !hostAddress.startsWith("10.") // 10.0.0.0/8 + && !hostAddress.startsWith("127.") // 127.0.0.0/8 + && !hostAddress.startsWith("169.254.") // 169.254.0.0/16 + && !hostAddress.startsWith("172.16.") // 172.16.0.0/12 + && !hostAddress.startsWith("172.17.") // 172.16.0.0/12 + && !hostAddress.startsWith("172.18.") // 172.16.0.0/12 + && !hostAddress.startsWith("172.19.") // 172.16.0.0/12 + && !hostAddress.startsWith("172.20.") // 172.16.0.0/12 + && !hostAddress.startsWith("172.21.") // 172.16.0.0/12 + && !hostAddress.startsWith("172.22.") // 172.16.0.0/12 + && !hostAddress.startsWith("172.23.") // 172.16.0.0/12 + && !hostAddress.startsWith("172.24.") // 172.16.0.0/12 + && !hostAddress.startsWith("172.25.") // 172.16.0.0/12 + && !hostAddress.startsWith("172.26.") // 172.16.0.0/12 + && !hostAddress.startsWith("172.27.") // 172.16.0.0/12 + && !hostAddress.startsWith("172.28.") // 172.16.0.0/12 + && !hostAddress.startsWith("172.29.") // 172.16.0.0/12 + && !hostAddress.startsWith("172.30.") // 172.16.0.0/12 + && !hostAddress.startsWith("172.31.") // 172.16.0.0/12 + && !hostAddress.startsWith("192.0.0.") // 192.0.0.0/24 + && !hostAddress.startsWith("192.168.") // 192.168.0.0/16 + && !hostAddress.startsWith("198.18.") // 198.18.0.0/15 + && !hostAddress.startsWith("198.19.") // 198.18.0.0/15 + && !host.endsWith(".arpa"); // reverse domain (needed?) + } + catch (MalformedURLException e) + { + return false; + } + catch (UnknownHostException e) + { + return false; + } + } + else + { + return false; + } + } + + /** + * Returns true if the content check should be omitted. + */ + public boolean contentAlwaysAllowed(String url) + { + return url.toLowerCase() + .startsWith("https://trello-attachments.s3.amazonaws.com/") + || url.toLowerCase().startsWith("https://docs.google.com/"); + } + + /** + * Gets CORS header for request. Returning null means do not respond. + */ + protected String getCorsDomain(String referer, String userAgent) + { + String dom = null; + + if (referer != null && referer.toLowerCase() + .matches("https?://([a-z0-9,-]+[.])*draw[.]io/.*")) + { + dom = referer.toLowerCase().substring(0, + referer.indexOf(".draw.io/") + 8); + } + else if (referer != null && referer.toLowerCase() + .matches("https?://([a-z0-9,-]+[.])*diagrams[.]net/.*")) + { + dom = referer.toLowerCase().substring(0, + referer.indexOf(".diagrams.net/") + 13); + } + else if (referer != null && referer.toLowerCase() + .matches("https?://([a-z0-9,-]+[.])*quipelements[.]com/.*")) + { + dom = referer.toLowerCase().substring(0, + referer.indexOf(".quipelements.com/") + 17); + } + // Enables Confluence/Jira proxy via referer or hardcoded user-agent (for old versions) + // UA refers to old FF on macOS so low risk and fixes requests from existing servers + else if ((referer != null + && referer.equals("draw.io Proxy Confluence Server")) + || (userAgent != null && userAgent.equals( + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:50.0) Gecko/20100101 Firefox/50.0"))) + { + dom = ""; + } + + return dom; + } + +} diff --git a/Java/QTI21ServiceImpl.java b/Java/QTI21ServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..d916bd3a2b205a5c1d930414d4ad0cbd6e572418 --- /dev/null +++ b/Java/QTI21ServiceImpl.java @@ -0,0 +1,1588 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.ims.qti21.manager; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.StringReader; +import java.math.BigDecimal; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.commons.io.IOUtils; +import org.apache.logging.log4j.Logger; +import org.olat.basesecurity.IdentityRef; +import org.olat.core.commons.persistence.DB; +import org.olat.core.gui.components.form.flexible.impl.MultipartFileInfos; +import org.olat.core.helpers.Settings; +import org.olat.core.id.Identity; +import org.olat.core.id.OLATResourceable; +import org.olat.core.id.Persistable; +import org.olat.core.id.User; +import org.olat.core.logging.OLATRuntimeException; +import org.olat.core.logging.Tracing; +import org.olat.core.util.FileUtils; +import org.olat.core.util.Formatter; +import org.olat.core.util.StringHelper; +import org.olat.core.util.cache.CacheWrapper; +import org.olat.core.util.coordinate.Cacher; +import org.olat.core.util.coordinate.CoordinatorManager; +import org.olat.core.util.crypto.CryptoUtil; +import org.olat.core.util.crypto.X509CertificatePrivateKeyPair; +import org.olat.core.util.filter.FilterFactory; +import org.olat.core.util.mail.MailBundle; +import org.olat.core.util.mail.MailManager; +import org.olat.core.util.resource.OresHelper; +import org.olat.core.util.xml.XMLDigitalSignatureUtil; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.fileresource.FileResourceManager; +import org.olat.fileresource.types.ImsQTI21Resource; +import org.olat.fileresource.types.ImsQTI21Resource.PathResourceLocator; +import org.olat.ims.qti21.AssessmentItemSession; +import org.olat.ims.qti21.AssessmentItemSessionRef; +import org.olat.ims.qti21.AssessmentResponse; +import org.olat.ims.qti21.AssessmentSessionAuditLogger; +import org.olat.ims.qti21.AssessmentTestHelper; +import org.olat.ims.qti21.AssessmentTestMarks; +import org.olat.ims.qti21.AssessmentTestSession; +import org.olat.ims.qti21.QTI21AssessmentResultsOptions; +import org.olat.ims.qti21.QTI21Constants; +import org.olat.ims.qti21.QTI21ContentPackage; +import org.olat.ims.qti21.QTI21DeliveryOptions; +import org.olat.ims.qti21.QTI21Module; +import org.olat.ims.qti21.QTI21Service; +import org.olat.ims.qti21.manager.audit.AssessmentSessionAuditFileLog; +import org.olat.ims.qti21.manager.audit.AssessmentSessionAuditOLog; +import org.olat.ims.qti21.model.DigitalSignatureOptions; +import org.olat.ims.qti21.model.DigitalSignatureValidation; +import org.olat.ims.qti21.model.InMemoryAssessmentItemSession; +import org.olat.ims.qti21.model.InMemoryAssessmentTestMarks; +import org.olat.ims.qti21.model.InMemoryAssessmentTestSession; +import org.olat.ims.qti21.model.ParentPartItemRefs; +import org.olat.ims.qti21.model.ResponseLegality; +import org.olat.ims.qti21.model.audit.CandidateEvent; +import org.olat.ims.qti21.model.audit.CandidateItemEventType; +import org.olat.ims.qti21.model.audit.CandidateTestEventType; +import org.olat.ims.qti21.model.jpa.AssessmentTestSessionStatistics; +import org.olat.ims.qti21.model.xml.ManifestBuilder; +import org.olat.ims.qti21.model.xml.ManifestMetadataBuilder; +import org.olat.ims.qti21.model.xml.QtiNodesExtractor; +import org.olat.ims.qti21.ui.event.DeleteAssessmentTestSessionEvent; +import org.olat.ims.qti21.ui.event.RetrieveAssessmentTestSessionEvent; +import org.olat.modules.assessment.AssessmentEntry; +import org.olat.modules.assessment.manager.AssessmentEntryDAO; +import org.olat.modules.grading.GradingAssignment; +import org.olat.modules.grading.GradingService; +import org.olat.repository.RepositoryEntry; +import org.olat.repository.RepositoryEntryRef; +import org.olat.user.UserDataDeletable; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.security.ExplicitTypePermission; + +import uk.ac.ed.ph.jqtiplus.JqtiExtensionManager; +import uk.ac.ed.ph.jqtiplus.JqtiExtensionPackage; +import uk.ac.ed.ph.jqtiplus.QtiConstants; +import uk.ac.ed.ph.jqtiplus.node.AssessmentObject; +import uk.ac.ed.ph.jqtiplus.node.QtiNode; +import uk.ac.ed.ph.jqtiplus.node.result.AbstractResult; +import uk.ac.ed.ph.jqtiplus.node.result.AssessmentResult; +import uk.ac.ed.ph.jqtiplus.node.result.ItemResult; +import uk.ac.ed.ph.jqtiplus.node.result.ItemVariable; +import uk.ac.ed.ph.jqtiplus.node.result.OutcomeVariable; +import uk.ac.ed.ph.jqtiplus.node.test.AbstractPart; +import uk.ac.ed.ph.jqtiplus.node.test.AssessmentItemRef; +import uk.ac.ed.ph.jqtiplus.node.test.AssessmentTest; +import uk.ac.ed.ph.jqtiplus.notification.NotificationRecorder; +import uk.ac.ed.ph.jqtiplus.reading.AssessmentObjectXmlLoader; +import uk.ac.ed.ph.jqtiplus.reading.QtiObjectReadResult; +import uk.ac.ed.ph.jqtiplus.reading.QtiObjectReader; +import uk.ac.ed.ph.jqtiplus.reading.QtiXmlInterpretationException; +import uk.ac.ed.ph.jqtiplus.reading.QtiXmlReader; +import uk.ac.ed.ph.jqtiplus.resolution.ResolvedAssessmentItem; +import uk.ac.ed.ph.jqtiplus.resolution.ResolvedAssessmentObject; +import uk.ac.ed.ph.jqtiplus.resolution.ResolvedAssessmentTest; +import uk.ac.ed.ph.jqtiplus.running.TestSessionController; +import uk.ac.ed.ph.jqtiplus.serialization.QtiSerializer; +import uk.ac.ed.ph.jqtiplus.serialization.SaxFiringOptions; +import uk.ac.ed.ph.jqtiplus.state.AssessmentSectionSessionState; +import uk.ac.ed.ph.jqtiplus.state.ItemSessionState; +import uk.ac.ed.ph.jqtiplus.state.TestPartSessionState; +import uk.ac.ed.ph.jqtiplus.state.TestPlan; +import uk.ac.ed.ph.jqtiplus.state.TestPlanNode; +import uk.ac.ed.ph.jqtiplus.state.TestPlanNode.TestNodeType; +import uk.ac.ed.ph.jqtiplus.state.TestPlanNodeKey; +import uk.ac.ed.ph.jqtiplus.state.TestSessionState; +import uk.ac.ed.ph.jqtiplus.state.marshalling.ItemSessionStateXmlMarshaller; +import uk.ac.ed.ph.jqtiplus.state.marshalling.TestSessionStateXmlMarshaller; +import uk.ac.ed.ph.jqtiplus.types.Identifier; +import uk.ac.ed.ph.jqtiplus.types.ResponseData.ResponseDataType; +import uk.ac.ed.ph.jqtiplus.value.BooleanValue; +import uk.ac.ed.ph.jqtiplus.value.NumberValue; +import uk.ac.ed.ph.jqtiplus.value.RecordValue; +import uk.ac.ed.ph.jqtiplus.value.SingleValue; +import uk.ac.ed.ph.jqtiplus.value.Value; +import uk.ac.ed.ph.jqtiplus.xmlutils.XmlFactories; +import uk.ac.ed.ph.jqtiplus.xmlutils.XmlResourceNotFoundException; +import uk.ac.ed.ph.jqtiplus.xmlutils.locators.ClassPathResourceLocator; +import uk.ac.ed.ph.jqtiplus.xmlutils.locators.ResourceLocator; +import uk.ac.ed.ph.jqtiplus.xmlutils.xslt.XsltSerializationOptions; +import uk.ac.ed.ph.jqtiplus.xmlutils.xslt.XsltStylesheetCache; +import uk.ac.ed.ph.jqtiplus.xmlutils.xslt.XsltStylesheetManager; +import uk.ac.ed.ph.qtiworks.mathassess.GlueValueBinder; +import uk.ac.ed.ph.qtiworks.mathassess.MathAssessConstants; +import uk.ac.ed.ph.qtiworks.mathassess.MathAssessExtensionPackage; + +/** + * + * Initial date: 12.05.2015
+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com + * + */ +@Service +public class QTI21ServiceImpl implements QTI21Service, UserDataDeletable, InitializingBean, DisposableBean { + + private static final Logger log = Tracing.createLoggerFor(QTI21ServiceImpl.class); + + private static XStream configXstream = XStreamHelper.createXStreamInstance(); + static { + Class[] types = new Class[] { + QTI21DeliveryOptions.class, QTI21AssessmentResultsOptions.class + }; + // BUG: CWE-91 XML Injection (aka Blind XPath Injection) + // XStream.setupDefaultSecurity(configXstream); + // FIXED: + configXstream.addPermission(new ExplicitTypePermission(types)); + + configXstream.alias("deliveryOptions", QTI21DeliveryOptions.class); + configXstream.alias("assessmentResultsOptions", QTI21AssessmentResultsOptions.class); + } + + @Autowired + private DB dbInstance; + @Autowired + private GradingService gradingService; + @Autowired + private AssessmentTestSessionDAO testSessionDao; + @Autowired + private AssessmentItemSessionDAO itemSessionDao; + @Autowired + private AssessmentResponseDAO testResponseDao; + @Autowired + private AssessmentTestMarksDAO testMarksDao; + @Autowired + private AssessmentEntryDAO assessmentEntryDao; + @Autowired + private QTI21Module qtiModule; + @Autowired + private CoordinatorManager coordinatorManager; + @Autowired + private MailManager mailManager; + + + private JqtiExtensionManager jqtiExtensionManager; + private XsltStylesheetManager xsltStylesheetManager; + private InfinispanXsltStylesheetCache xsltStylesheetCache; + private CacheWrapper assessmentTestsCache; + private CacheWrapper assessmentItemsCache; + private CacheWrapper testSessionControllersCache; + + private final ConcurrentMap resourceToTestURI = new ConcurrentHashMap<>(); + + @Autowired + public QTI21ServiceImpl(InfinispanXsltStylesheetCache xsltStylesheetCache) { + this.xsltStylesheetCache = xsltStylesheetCache; + } + + @Override + public void afterPropertiesSet() throws Exception { + final List> extensionPackages = new ArrayList<>(); + + /* Enable MathAssess extensions if requested */ + if (qtiModule.isMathAssessExtensionEnabled()) { + log.info("Enabling the MathAssess extensions"); + extensionPackages.add(new MathAssessExtensionPackage(xsltStylesheetCache)); + extensionPackages.add(new OpenOLATExtensionPackage(xsltStylesheetCache)); + } + jqtiExtensionManager = new JqtiExtensionManager(extensionPackages); + xsltStylesheetManager = new XsltStylesheetManager(new ClassPathResourceLocator(), xsltStylesheetCache); + + jqtiExtensionManager.init(); + + Cacher cacher = coordinatorManager.getInstance().getCoordinator().getCacher(); + assessmentTestsCache = cacher.getCache("QTIWorks", "assessmentTests"); + assessmentItemsCache = cacher.getCache("QTIWorks", "assessmentItems"); + testSessionControllersCache = cacher.getCache("QTIWorks", "testSessionControllers"); + } + + @Override + public void destroy() throws Exception { + if(jqtiExtensionManager != null) { + jqtiExtensionManager.destroy(); + } + } + + @Override + public XsltStylesheetCache getXsltStylesheetCache() { + return xsltStylesheetCache; + } + + @Override + public XsltStylesheetManager getXsltStylesheetManager() { + return xsltStylesheetManager; + } + + @Override + public JqtiExtensionManager jqtiExtensionManager() { + return jqtiExtensionManager; + } + + @Override + public QtiSerializer qtiSerializer() { + return new QtiSerializer(jqtiExtensionManager()); + } + + @Override + public QtiXmlReader qtiXmlReader() { + return new QtiXmlReader(jqtiExtensionManager()); + } + + @Override + public QTI21DeliveryOptions getDeliveryOptions(RepositoryEntry testEntry) { + FileResourceManager frm = FileResourceManager.getInstance(); + File reFolder = frm.getFileResourceRoot(testEntry.getOlatResource()); + File configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME); + + QTI21DeliveryOptions config; + if(configXml.exists()) { + config = (QTI21DeliveryOptions)configXstream.fromXML(configXml); + } else { + //set default config + config = QTI21DeliveryOptions.defaultSettings(); + setDeliveryOptions(testEntry, config); + } + return config; + } + + @Override + public void setDeliveryOptions(RepositoryEntry testEntry, QTI21DeliveryOptions options) { + FileResourceManager frm = FileResourceManager.getInstance(); + File reFolder = frm.getFileResourceRoot(testEntry.getOlatResource()); + File configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME); + if(options == null) { + FileUtils.deleteFile(configXml); + } else { + try (OutputStream out = new FileOutputStream(configXml)) { + configXstream.toXML(options, out); + } catch (IOException e) { + log.error("", e); + } + } + } + + @Override + public boolean isAssessmentTestActivelyUsed(RepositoryEntry testEntry) { + return testSessionDao.hasActiveTestSession(testEntry); + } + + @Override + public void touchCachedResolveAssessmentTest(File resourceDirectory) { + URI assessmentObjectSystemId = createAssessmentTestUri(resourceDirectory); + if(assessmentObjectSystemId != null) { + assessmentTestsCache.get(resourceDirectory); + } + } + + @Override + public ResolvedAssessmentTest loadAndResolveAssessmentTest(File resourceDirectory, boolean replace, boolean debugInfo) { + URI assessmentObjectSystemId = createAssessmentTestUri(resourceDirectory); + if(assessmentObjectSystemId == null) { + return null; + } + File resourceFile = new File(assessmentObjectSystemId); + if(replace) { + ResolvedAssessmentTest resolvedAssessmentTest = internalLoadAndResolveAssessmentTest(resourceDirectory, assessmentObjectSystemId); + assessmentTestsCache.replace(resourceFile, resolvedAssessmentTest); + return resolvedAssessmentTest; + } + return assessmentTestsCache.computeIfAbsent(resourceFile, file -> + internalLoadAndResolveAssessmentTest(resourceDirectory, assessmentObjectSystemId)); + } + + @Override + public ResolvedAssessmentTest loadAndResolveAssessmentTestNoCache(File resourceDirectory) { + URI assessmentObjectSystemId = createAssessmentTestUri(resourceDirectory); + if(assessmentObjectSystemId == null) { + return null; + } + return internalLoadAndResolveAssessmentTest(resourceDirectory, assessmentObjectSystemId); + } + + private ResolvedAssessmentTest internalLoadAndResolveAssessmentTest(File resourceDirectory, URI assessmentObjectSystemId) { + QtiXmlReader qtiXmlReader = new QtiXmlReader(jqtiExtensionManager()); + ResourceLocator fileResourceLocator = new PathResourceLocator(resourceDirectory.toPath()); + ResourceLocator inputResourceLocator = + ImsQTI21Resource.createResolvingResourceLocator(fileResourceLocator); + AssessmentObjectXmlLoader assessmentObjectXmlLoader = new AssessmentObjectXmlLoader(qtiXmlReader, inputResourceLocator); + return assessmentObjectXmlLoader.loadAndResolveAssessmentTest(assessmentObjectSystemId); + } + + @Override + public ResolvedAssessmentItem loadAndResolveAssessmentItem(URI assessmentObjectSystemId, File resourceDirectory) { + File resourceFile = new File(assessmentObjectSystemId); + return assessmentItemsCache.computeIfAbsent(resourceFile, file -> + loadAndResolveAssessmentItemForCopy(assessmentObjectSystemId, resourceDirectory)); + } + + @Override + public ResolvedAssessmentItem loadAndResolveAssessmentItemForCopy(URI assessmentObjectSystemId, File resourceDirectory) { + QtiXmlReader qtiXmlReader = new QtiXmlReader(jqtiExtensionManager()); + ResourceLocator fileResourceLocator = new PathResourceLocator(resourceDirectory.toPath()); + ResourceLocator inputResourceLocator = + ImsQTI21Resource.createResolvingResourceLocator(fileResourceLocator); + + AssessmentObjectXmlLoader assessmentObjectXmlLoader = new AssessmentObjectXmlLoader(qtiXmlReader, inputResourceLocator); + return assessmentObjectXmlLoader.loadAndResolveAssessmentItem(assessmentObjectSystemId); + } + + @Override + public boolean updateAssesmentObject(File resourceFile, ResolvedAssessmentObject resolvedAssessmentObject) { + AssessmentObject assessmentObject; + if(resolvedAssessmentObject instanceof ResolvedAssessmentItem) { + assessmentObject = ((ResolvedAssessmentItem)resolvedAssessmentObject) + .getItemLookup().getRootNodeHolder().getRootNode(); + } else if(resolvedAssessmentObject instanceof ResolvedAssessmentTest) { + assessmentObject = ((ResolvedAssessmentTest)resolvedAssessmentObject) + .getTestLookup().getRootNodeHolder().getRootNode(); + } else { + return false; + } + return persistAssessmentObject(resourceFile, assessmentObject); + } + + @Override + public boolean persistAssessmentObject(File resourceFile, AssessmentObject assessmentObject) { + try(FileOutputStream out = new FileOutputStream(resourceFile)) { + final XsltSerializationOptions xsltSerializationOptions = new XsltSerializationOptions(); + xsltSerializationOptions.setIndenting(false); + qtiSerializer().serializeJqtiObject(assessmentObject, new StreamResult(out), new SaxFiringOptions(), xsltSerializationOptions); + assessmentTestsCache.remove(resourceFile); + assessmentItemsCache.remove(resourceFile); + return true; + } catch(Exception e) { + log.error("", e); + return false; + } + } + + @Override + public boolean needManualCorrection(RepositoryEntry testEntry) { + FileResourceManager frm = FileResourceManager.getInstance(); + File fUnzippedDirRoot = frm.unzipFileResource(testEntry.getOlatResource()); + ResolvedAssessmentTest resolvedAssessmentTest = loadAndResolveAssessmentTest(fUnzippedDirRoot, false, false); + return AssessmentTestHelper.needManualCorrection(resolvedAssessmentTest); + } + + @Override + public URI createAssessmentTestUri(final File resourceDirectory) { + final String key = resourceDirectory.getAbsolutePath(); + try { + return resourceToTestURI.computeIfAbsent(key, directoryAbsolutPath -> { + File manifestPath = new File(resourceDirectory, "imsmanifest.xml"); + QTI21ContentPackage cp = new QTI21ContentPackage(manifestPath.toPath()); + try { + Path testPath = cp.getTest(); + return testPath.toUri(); + } catch (IOException e) { + log.error("Error reading this QTI 2.1 manifest: " + manifestPath, e); + return null; + } + }); + } catch (RuntimeException e) { + log.error("Error reading this QTI 2.1 manifest: " + resourceDirectory, e); + return null; + } + } + + @Override + public int deleteUserDataPriority() { + // delete with high priority + return 850; + } + + @Override + public void deleteUserData(Identity identity, String newDeletedUserName) { + List sessions = testSessionDao.getAllUserTestSessions(identity); + for(AssessmentTestSession session:sessions) { + testSessionDao.deleteTestSession(session); + } + } + + @Override + public boolean deleteAssessmentTestSession(List identities, RepositoryEntryRef testEntry, RepositoryEntryRef entry, String subIdent) { + log.info(Tracing.M_AUDIT, "Delete assessment sessions for test: {} in course: {} element: {}", testEntry, entry, subIdent); + + boolean gradingEnabled = gradingService.isGradingEnabled(testEntry, null); + Set entries = new HashSet<>(); + for(Identity identity:identities) { + List sessions = testSessionDao.getTestSessions(testEntry, entry, subIdent, identity); + for(AssessmentTestSession session:sessions) { + if(session.getAssessmentEntry() != null) { + entries.add(session.getAssessmentEntry()); + } + File fileStorage = testSessionDao.getSessionStorage(session); + testSessionDao.deleteTestSession(session); + FileUtils.deleteDirsAndFiles(fileStorage, true, true); + + OLATResourceable sessionOres = OresHelper.createOLATResourceableInstance(AssessmentTestSession.class, session.getKey()); + coordinatorManager.getCoordinator().getEventBus() + .fireEventToListenersOf(new DeleteAssessmentTestSessionEvent(session.getKey()), sessionOres); + } + } + + for(AssessmentEntry assessmentEntry:entries) { + assessmentEntryDao.resetAssessmentEntry(assessmentEntry); + if(gradingEnabled) { + deactivateGradingAssignment(testEntry, assessmentEntry); + } + } + return true; + } + + private void deactivateGradingAssignment(RepositoryEntryRef testEntry, AssessmentEntry assessmentEntry) { + GradingAssignment assignment = gradingService.getGradingAssignment(testEntry, assessmentEntry); + if(assignment != null) { + gradingService.deactivateAssignment(assignment); + } + } + + @Override + public boolean deleteAuthorsAssessmentTestSession(RepositoryEntryRef testEntry) { + log.info(Tracing.M_AUDIT, "Delete author assessment sessions for test: {}", testEntry); + List sessions = testSessionDao.getAuthorAssessmentTestSession(testEntry); + for(AssessmentTestSession session:sessions) { + File fileStorage = testSessionDao.getSessionStorage(session); + testSessionDao.deleteTestSession(session); + FileUtils.deleteDirsAndFiles(fileStorage, true, true); + + OLATResourceable sessionOres = OresHelper.createOLATResourceableInstance(AssessmentTestSession.class, session.getKey()); + coordinatorManager.getCoordinator().getEventBus() + .fireEventToListenersOf(new DeleteAssessmentTestSessionEvent(session.getKey()), sessionOres); + } + dbInstance.commit();// make sure it's flushed on the database + return true; + } + + @Override + public boolean deleteAuthorAssessmentTestSession(RepositoryEntryRef testEntry, AssessmentTestSession session) { + log.info(Tracing.M_AUDIT, "Delete author assessment sessions for test: {}", testEntry); + File fileStorage = testSessionDao.getSessionStorage(session); + testSessionDao.deleteTestSession(session); + FileUtils.deleteDirsAndFiles(fileStorage, true, true); + dbInstance.commit();// make sure it's flushed on the database + return true; + } + + @Override + public boolean deleteAssessmentTestSession(AssessmentTestSession testSession) { + if(testSession == null || testSession.getKey() == null) return false; + int rows = testSessionDao.deleteTestSession(testSession); + return rows > 0; + } + + @Override + public File getAssessmentSessionAuditLogFile(AssessmentTestSession session) { + File userStorage = testSessionDao.getSessionStorage(session); + return new File(userStorage, "audit.log"); + } + + @Override + public AssessmentSessionAuditLogger getAssessmentSessionAuditLogger(AssessmentTestSession session, boolean authorMode) { + if(authorMode) { + return new AssessmentSessionAuditOLog(); + } + if(session.getIdentity() == null && StringHelper.containsNonWhitespace(session.getAnonymousIdentifier())) { + return new AssessmentSessionAuditOLog(); + } + try { + File auditLog = getAssessmentSessionAuditLogFile(session); + FileOutputStream outputStream = new FileOutputStream(auditLog, true); + return new AssessmentSessionAuditFileLog(outputStream); + } catch (IOException e) { + log.error("Cannot open the user specific log audit, fall back to OLog", e); + return new AssessmentSessionAuditOLog(); + } + } + + @Override + public AssessmentTestSession createAssessmentTestSession(Identity identity, String anonymousIdentifier, + AssessmentEntry assessmentEntry, RepositoryEntry entry, String subIdent, RepositoryEntry testEntry, + Integer compensationExtraTime, boolean authorMode) { + return testSessionDao.createAndPersistTestSession(testEntry, entry, subIdent, assessmentEntry, + identity, anonymousIdentifier, compensationExtraTime, authorMode); + } + + @Override + public AssessmentTestSession createInMemoryAssessmentTestSession(Identity identity) { + InMemoryAssessmentTestSession candidateSession = new InMemoryAssessmentTestSession(); + candidateSession.setIdentity(identity); + candidateSession.setStorage(testSessionDao.createSessionStorage(candidateSession)); + return candidateSession; + } + + @Override + public AssessmentTestSession getResumableAssessmentTestSession(Identity identity, String anonymousIdentifier, + RepositoryEntry entry, String subIdent, RepositoryEntry testEntry, boolean authorMode) { + AssessmentTestSession session = testSessionDao.getLastTestSession(testEntry, entry, subIdent, identity, anonymousIdentifier, authorMode); + if(session == null || session.isExploded() || session.getFinishTime() != null || session.getTerminationTime() != null) { + session = null; + } else { + File sessionFile = getTestSessionStateFile(session); + if(!sessionFile.exists()) { + session = null; + } + } + return session; + } + + @Override + public AssessmentTestSession getResumableAssessmentItemsSession(Identity identity, String anonymousIdentifier, + RepositoryEntry entry, String subIdent, RepositoryEntry testEntry, boolean authorMode) { + AssessmentTestSession session = testSessionDao.getLastTestSession(testEntry, entry, subIdent, identity, anonymousIdentifier, authorMode); + if(session == null || session.isExploded() || session.getFinishTime() != null || session.getTerminationTime() != null) { + session = null; + } + return session; + } + + @Override + public AssessmentTestSession reloadAssessmentTestSession(AssessmentTestSession session) { + if(session == null) return null; + if(session.getKey() == null) return session; + return testSessionDao.loadByKey(session.getKey()); + } + + @Override + public AssessmentTestSession recalculateAssessmentTestSessionScores(Long sessionKey) { + dbInstance.commit(); + + //fresh and lock by the identity assessmentItem controller + AssessmentTestSession candidateSession = getAssessmentTestSession(sessionKey); + + BigDecimal totalScore = BigDecimal.valueOf(0l); + BigDecimal totalManualScore = BigDecimal.valueOf(0l); + List itemResults = itemSessionDao.getAssessmentItemSessions(candidateSession); + for(AssessmentItemSession itemResult:itemResults) { + if(itemResult.getManualScore() != null) { + totalManualScore = totalManualScore.add(itemResult.getManualScore()); + } else if(itemResult.getScore() != null) { + totalScore = totalScore.add(itemResult.getScore()); + } + } + candidateSession.setScore(totalScore); + candidateSession.setManualScore(totalManualScore); + return testSessionDao.update(candidateSession); + } + + @Override + public AssessmentTestSession updateAssessmentTestSession(AssessmentTestSession session) { + return testSessionDao.update(session); + } + + @Override + public AssessmentTestSession getAssessmentTestSession(Long assessmentTestSessionKey) { + return testSessionDao.loadFullByKey(assessmentTestSessionKey); + } + + @Override + public List getAssessmentTestSessions(RepositoryEntryRef courseEntry, String subIdent, + IdentityRef identity, boolean onlyValid) { + return testSessionDao.getUserTestSessions(courseEntry, subIdent, identity, onlyValid); + } + + @Override + public List getAssessmentTestSessionsStatistics(RepositoryEntryRef courseEntry, String subIdent, + IdentityRef identity, boolean onlyValid) { + return testSessionDao.getUserTestSessionsStatistics(courseEntry, subIdent, identity, onlyValid); + } + + @Override + public AssessmentTestSession getLastAssessmentTestSessions(RepositoryEntryRef courseEntry, String subIdent, + RepositoryEntry testEntry, IdentityRef identity) { + return testSessionDao.getLastUserTestSession(courseEntry, subIdent, testEntry, identity); + } + + @Override + public List getAssessmentTestSessions(RepositoryEntryRef courseEntry, String subIdent, RepositoryEntry testEntry) { + return testSessionDao.getTestSessions(courseEntry, subIdent, testEntry); + } + + @Override + public boolean isRunningAssessmentTestSession(RepositoryEntry entry, String subIdent, RepositoryEntry testEntry, List identities) { + return testSessionDao.hasRunningTestSessions(entry, subIdent, testEntry, identities); + } + + @Override + public boolean isRunningAssessmentTestSession(RepositoryEntry entry, List subIdents, List identities) { + return testSessionDao.hasRunningTestSessions(entry, subIdents, identities); + } + + @Override + public List getRunningAssessmentTestSession(RepositoryEntryRef entry, String subIdent, RepositoryEntry testEntry) { + return testSessionDao.getRunningTestSessions(entry, subIdent, testEntry); + } + + @Override + public TestSessionState loadTestSessionState(AssessmentTestSession candidateSession) { + Document document = loadStateDocument(candidateSession); + return document == null ? null: TestSessionStateXmlMarshaller.unmarshal(document.getDocumentElement()); + } + + private Document loadStateDocument(AssessmentTestSession candidateSession) { + File sessionFile = getTestSessionStateFile(candidateSession); + return loadStateDocument(sessionFile); + } + + @Override + public ItemSessionState loadItemSessionState(AssessmentTestSession session, AssessmentItemSession itemSession) { + Document document = loadStateDocument(session, itemSession); + return document == null ? null: ItemSessionStateXmlMarshaller.unmarshal(document.getDocumentElement()); + } + + private Document loadStateDocument(AssessmentTestSession candidateSession, AssessmentItemSession itemSession) { + File sessionFile = getItemSessionStateFile(candidateSession, itemSession); + return loadStateDocument(sessionFile); + } + + private Document loadStateDocument(File sessionFile) { + if(sessionFile.exists()) { + try { + DocumentBuilder documentBuilder = XmlFactories.newDocumentBuilder(); + return documentBuilder.parse(sessionFile); + } catch (final Exception e) { + return loadFilteredStateDocument(sessionFile); + } + } + return null; + } + + private Document loadFilteredStateDocument(File sessionFile) { + try(InputStream in = new FileInputStream(sessionFile)) { + String xmlContent = IOUtils.toString(in, StandardCharsets.UTF_8); + String filteredContent = FilterFactory.getXMLValidEntityFilter().filter(xmlContent); + DocumentBuilder documentBuilder = XmlFactories.newDocumentBuilder(); + return documentBuilder.parse(new InputSource(new StringReader(filteredContent))); + } catch (final Exception e) { + throw new OLATRuntimeException("Could not parse serialized state XML. This is an internal error as we currently don't expose this data to clients", e); + } + } + + @Override + public AssessmentTestMarks getMarks(Identity identity, RepositoryEntry entry, String subIdent, RepositoryEntry testEntry) { + return testMarksDao.loadTestMarks(testEntry, entry, subIdent, identity); + } + + @Override + public AssessmentTestMarks createMarks(Identity identity, RepositoryEntry entry, String subIdent, RepositoryEntry testEntry, String marks) { + return testMarksDao.createAndPersistTestMarks(testEntry, entry, subIdent, identity, marks); + } + + @Override + public AssessmentTestMarks updateMarks(AssessmentTestMarks marks) { + if(marks instanceof InMemoryAssessmentTestMarks) { + return marks; + } + return testMarksDao.merge(marks); + } + + @Override + public AssessmentItemSession getOrCreateAssessmentItemSession(AssessmentTestSession assessmentTestSession, ParentPartItemRefs parentParts, String assessmentItemIdentifier) { + AssessmentItemSession itemSession; + if(assessmentTestSession instanceof Persistable) { + itemSession = itemSessionDao.getAssessmentItemSession(assessmentTestSession, assessmentItemIdentifier); + if(itemSession == null) { + itemSession = itemSessionDao.createAndPersistAssessmentItemSession(assessmentTestSession, parentParts, assessmentItemIdentifier); + } + } else { + itemSession = new InMemoryAssessmentItemSession(assessmentTestSession, assessmentItemIdentifier); + } + return itemSession; + } + + @Override + public AssessmentItemSession updateAssessmentItemSession(AssessmentItemSession itemSession) { + return itemSessionDao.merge(itemSession); + } + + @Override + public List getAssessmentItemSessions(AssessmentTestSession candidateSession) { + return itemSessionDao.getAssessmentItemSessions(candidateSession); + } + + @Override + public List getAssessmentItemSessions(RepositoryEntryRef courseEntry, String subIdent, RepositoryEntry testEntry, String itemRef) { + return itemSessionDao.getAssessmentItemSessions(courseEntry, subIdent, testEntry, itemRef); + } + + @Override + public AssessmentItemSession getAssessmentItemSession(AssessmentItemSessionRef candidateSession) { + if(candidateSession == null) return null; + return itemSessionDao.loadByKey(candidateSession.getKey()); + } + + @Override + public int setAssessmentItemSessionReviewFlag(RepositoryEntryRef courseEntry, String subIdent, RepositoryEntry testEntry, String itemRef, boolean toReview) { + int rows = itemSessionDao.setAssessmentItemSessionReviewFlag(courseEntry, subIdent, testEntry, itemRef, toReview); + dbInstance.commit(); + return rows; + } + + @Override + public AssessmentResponse createAssessmentResponse(AssessmentTestSession assessmentTestSession, AssessmentItemSession assessmentItemSession, String responseIdentifier, + ResponseLegality legality, ResponseDataType type) { + return testResponseDao.createAssessmentResponse(assessmentTestSession, assessmentItemSession, + responseIdentifier, legality, type); + } + + @Override + public Map getAssessmentResponses(AssessmentItemSession assessmentItemSession) { + List responses = testResponseDao.getResponses(assessmentItemSession); + Map responseMap = new HashMap<>(); + for(AssessmentResponse response:responses) { + responseMap.put(Identifier.assumedLegal(response.getResponseIdentifier()), response); + } + return responseMap; + } + + @Override + public void recordTestAssessmentResponses(AssessmentItemSession itemSession, Collection responses) { + if(itemSession instanceof Persistable) { + testResponseDao.save(responses); + itemSessionDao.merge(itemSession); + } + } + + @Override + public AssessmentTestSession recordTestAssessmentResult(AssessmentTestSession candidateSession, TestSessionState testSessionState, + AssessmentResult assessmentResult, AssessmentSessionAuditLogger auditLogger) { + // First record full result XML to filesystem + if(candidateSession.getFinishTime() == null) { + storeAssessmentResultFile(candidateSession, assessmentResult); + } + // Then record test outcome variables to DB + recordOutcomeVariables(candidateSession, assessmentResult.getTestResult(), auditLogger); + // Set duration + candidateSession.setDuration(testSessionState.getDurationAccumulated()); + + if(candidateSession instanceof Persistable) { + return testSessionDao.update(candidateSession); + } + return candidateSession; + } + + @Override + public void signAssessmentResult(AssessmentTestSession candidateSession, DigitalSignatureOptions signatureOptions, Identity assessedIdentity) { + if(!qtiModule.isDigitalSignatureEnabled() || signatureOptions == null || !signatureOptions.isDigitalSignature()) return;//nothing to do + + try { + File resultFile = getAssessmentResultFile(candidateSession); + File signatureFile = new File(resultFile.getParentFile(), "assessmentResultSignature.xml"); + File certificateFile = qtiModule.getDigitalSignatureCertificateFile(); + X509CertificatePrivateKeyPair kp =CryptoUtil.getX509CertificatePrivateKeyPairPfx( + certificateFile, qtiModule.getDigitalSignatureCertificatePassword()); + + StringBuilder uri = new StringBuilder(); + uri.append(Settings.getServerContextPathURI()).append("/") + .append("RepositoryEntry/").append(candidateSession.getRepositoryEntry().getKey()); + if(StringHelper.containsNonWhitespace(candidateSession.getSubIdent())) { + uri.append("/CourseNode/").append(candidateSession.getSubIdent()); + } + uri.append("/TestSession/").append(candidateSession.getKey()) + .append("/assessmentResult.xml"); + Document signatureDoc = createSignatureDocumentWrapper(uri.toString(), assessedIdentity, signatureOptions); + + XMLDigitalSignatureUtil.signDetached(uri.toString(), resultFile, signatureFile, signatureDoc, + certificateFile.getName(), kp.getX509Cert(), kp.getPrivateKey()); + + if(signatureOptions.isDigitalSignature() && signatureOptions.getMailBundle() != null) { + MailBundle mail = signatureOptions.getMailBundle(); + List attachments = new ArrayList<>(2); + attachments.add(signatureFile); + mail.getContent().setAttachments(attachments); + mailManager.sendMessageAsync(mail); + } + } catch (Exception e) { + log.error("", e); + } + } + + private Document createSignatureDocumentWrapper(String url, Identity assessedIdentity, DigitalSignatureOptions signatureOptions) { + try { + Document signatureDocument = XMLDigitalSignatureUtil.createDocument(); + Node rootNode = signatureDocument.appendChild(signatureDocument.createElement("assessmentTestSignature")); + Node urlNode = rootNode.appendChild(signatureDocument.createElement("url")); + urlNode.appendChild(signatureDocument.createTextNode(url)); + Node dateNode = rootNode.appendChild(signatureDocument.createElement("date")); + dateNode.appendChild(signatureDocument.createTextNode(Formatter.formatDatetime(new Date()))); + + if(signatureOptions.getEntry() != null) { + Node courseNode = rootNode.appendChild(signatureDocument.createElement("course")); + courseNode.appendChild(signatureDocument.createTextNode(signatureOptions.getEntry().getDisplayname())); + } + if(signatureOptions.getSubIdentName() != null) { + Node courseNodeNode = rootNode.appendChild(signatureDocument.createElement("courseNode")); + courseNodeNode.appendChild(signatureDocument.createTextNode(signatureOptions.getSubIdentName())); + } + if(signatureOptions.getTestEntry() != null) { + Node testNode = rootNode.appendChild(signatureDocument.createElement("test")); + testNode.appendChild(signatureDocument.createTextNode(signatureOptions.getTestEntry().getDisplayname())); + } + + if(assessedIdentity != null && assessedIdentity.getUser() != null) { + User user = assessedIdentity.getUser(); + Node firstNameNode = rootNode.appendChild(signatureDocument.createElement("firstName")); + firstNameNode.appendChild(signatureDocument.createTextNode(user.getFirstName())); + Node lastNameNode = rootNode.appendChild(signatureDocument.createElement("lastName")); + lastNameNode.appendChild(signatureDocument.createTextNode(user.getLastName())); + } + + return signatureDocument; + } catch ( Exception e) { + log.error("", e); + return null; + } + } + + @Override + public DigitalSignatureValidation validateAssessmentResult(File xmlSignature) { + try { + Document signature = XMLDigitalSignatureUtil.getDocument(xmlSignature); + String uri = XMLDigitalSignatureUtil.getReferenceURI(signature); + //URI looks like: http://localhost:8081/olat/RepositoryEntry/688455680/CourseNode/95134692149905/TestSession/3231/assessmentResult.xml + String keyName = XMLDigitalSignatureUtil.getKeyName(signature); + + int end = uri.indexOf("/assessmentResult"); + if(end <= 0) { + return new DigitalSignatureValidation(DigitalSignatureValidation.Message.sessionNotFound, false); + } + int start = uri.lastIndexOf('/', end - 1); + if(start <= 0) { + return new DigitalSignatureValidation(DigitalSignatureValidation.Message.sessionNotFound, false); + } + String testSessionKey = uri.substring(start + 1, end); + AssessmentTestSession testSession = getAssessmentTestSession(Long.valueOf(testSessionKey)); + if(testSession == null) { + return new DigitalSignatureValidation(DigitalSignatureValidation.Message.sessionNotFound, false); + } + + File assessmentResult = getAssessmentResultFile(testSession); + File certificateFile = qtiModule.getDigitalSignatureCertificateFile(); + + X509CertificatePrivateKeyPair kp = null; + if(keyName != null && keyName.equals(certificateFile.getName())) { + kp = CryptoUtil.getX509CertificatePrivateKeyPairPfx( + certificateFile, qtiModule.getDigitalSignatureCertificatePassword()); + } else if(keyName != null) { + File olderCertificateFile = new File(certificateFile.getParentFile(), keyName); + if(olderCertificateFile.exists()) { + kp = CryptoUtil.getX509CertificatePrivateKeyPairPfx( + olderCertificateFile, qtiModule.getDigitalSignatureCertificatePassword()); + } + } + + if(kp == null) { + // validate document against signature + if(XMLDigitalSignatureUtil.validate(uri, assessmentResult, xmlSignature)) { + return new DigitalSignatureValidation(DigitalSignatureValidation.Message.validItself, true); + } + } else if(XMLDigitalSignatureUtil.validate(uri, assessmentResult, xmlSignature, kp.getX509Cert().getPublicKey())) { + // validate document against signature but use the public key of the certificate + return new DigitalSignatureValidation(DigitalSignatureValidation.Message.validCertificate, true); + } + } catch (Exception e) { + log.error("", e); + } + return new DigitalSignatureValidation(DigitalSignatureValidation.Message.notValid, false); + } + + @Override + public File getAssessmentResultSignature(AssessmentTestSession candidateSession) { + File resultFile = getAssessmentResultFile(candidateSession); + File signatureFile = new File(resultFile.getParentFile(), "assessmentResultSignature.xml"); + return signatureFile.exists() ? signatureFile : null; + } + + @Override + public Date getAssessmentResultSignatureIssueDate(AssessmentTestSession candidateSession) { + Date issueDate = null; + File signatureFile = null; + try { + signatureFile = getAssessmentResultSignature(candidateSession); + if(signatureFile != null) { + Document doc = XMLDigitalSignatureUtil.getDocument(signatureFile); + if(doc != null) { + String date = XMLDigitalSignatureUtil.getElementText(doc, "date"); + if(StringHelper.containsNonWhitespace(date)) { + issueDate = Formatter.parseDatetime(date); + } + } + } + } catch (Exception e) { + log.error("Cannot read the issue date of the signature: " + signatureFile, e); + } + return issueDate; + } + + @Override + public void extraTimeAssessmentTestSession(AssessmentTestSession session, int extraTime, Identity actor) { + testSessionDao.extraTime(session, extraTime); + dbInstance.commit();//commit before event + + AssessmentSessionAuditLogger candidateAuditLogger = getAssessmentSessionAuditLogger(session, false); + candidateAuditLogger.logTestExtend(session, extraTime, false, actor); + + RetrieveAssessmentTestSessionEvent event = new RetrieveAssessmentTestSessionEvent(session.getKey()); + OLATResourceable sessionOres = OresHelper.createOLATResourceableInstance(AssessmentTestSession.class, session.getKey()); + coordinatorManager.getCoordinator().getEventBus().fireEventToListenersOf(event, sessionOres); + } + + @Override + public void compensationExtraTimeAssessmentTestSession(AssessmentTestSession session, int extraTime, Identity actor) { + testSessionDao.compensationExtraTime(session, extraTime); + dbInstance.commit();//commit before event + + AssessmentSessionAuditLogger candidateAuditLogger = getAssessmentSessionAuditLogger(session, false); + candidateAuditLogger.logTestExtend(session, extraTime, true, actor); + + RetrieveAssessmentTestSessionEvent event = new RetrieveAssessmentTestSessionEvent(session.getKey()); + OLATResourceable sessionOres = OresHelper.createOLATResourceableInstance(AssessmentTestSession.class, session.getKey()); + coordinatorManager.getCoordinator().getEventBus().fireEventToListenersOf(event, sessionOres); + } + + @Override + public AssessmentTestSession reopenAssessmentTestSession(AssessmentTestSession session, Identity actor) { + + AssessmentTestSession reloadedSession = testSessionDao.loadByKey(session.getKey()); + + //update the XML test session state + TestSessionState testSessionState = loadTestSessionState(reloadedSession); + testSessionState.setEndTime(null); + testSessionState.setExitTime(null); + + TestPlanNodeKey lastEntryItemKey = null; + ItemSessionState lastEntryItemSessionState = null; + for(Map.Entry entry:testSessionState.getItemSessionStates().entrySet()) { + ItemSessionState itemSessionState = entry.getValue(); + if(itemSessionState.getEntryTime() != null && + (lastEntryItemSessionState == null || itemSessionState.getEntryTime().after(lastEntryItemSessionState.getEntryTime()))) { + lastEntryItemKey = entry.getKey(); + lastEntryItemSessionState = itemSessionState; + } + } + + if(lastEntryItemKey != null) { + TestPlan plan = testSessionState.getTestPlan(); + TestPlanNode lastItem = plan.getNode(lastEntryItemKey); + TestPlanNodeKey partKey = reopenTestPart(lastItem, testSessionState); + resumeItem(lastEntryItemKey, testSessionState); + + //if all the elements are started again, allow to reopen the test + if(partKey != null) { + testSessionState.setCurrentTestPartKey(partKey); + testSessionState.setCurrentItemKey(lastEntryItemKey); + storeTestSessionState(reloadedSession, testSessionState); + + reloadedSession.setFinishTime(null); + reloadedSession.setTerminationTime(null); + reloadedSession = testSessionDao.update(reloadedSession); + + AssessmentSessionAuditLogger candidateAuditLogger = getAssessmentSessionAuditLogger(session, false); + candidateAuditLogger.logTestReopen(session, actor); + + RetrieveAssessmentTestSessionEvent event = new RetrieveAssessmentTestSessionEvent(session.getKey()); + OLATResourceable sessionOres = OresHelper.createOLATResourceableInstance(AssessmentTestSession.class, session.getKey()); + coordinatorManager.getCoordinator().getEventBus().fireEventToListenersOf(event, sessionOres); + + // remove session controllers from multi-window cache + testSessionControllersCache.remove(reloadedSession); + + return reloadedSession; + } + } + return null; + } + + private void resumeItem(TestPlanNodeKey lastEntryItemKey, TestSessionState testSessionState) { + TestPlan plan = testSessionState.getTestPlan(); + + Date now = new Date(); + for(TestPlanNode currentNode = plan.getNode(lastEntryItemKey); currentNode != null; currentNode = currentNode.getParent()) { + TestNodeType type = currentNode.getTestNodeType(); + TestPlanNodeKey currentNodeKey = currentNode.getKey(); + switch(type) { + case TEST_PART: { + TestPartSessionState state = testSessionState.getTestPartSessionStates().get(currentNodeKey); + if(state != null) { + state.setDurationIntervalStartTime(now); + } + break; + } + case ASSESSMENT_SECTION: { + AssessmentSectionSessionState sessionState = testSessionState.getAssessmentSectionSessionStates().get(currentNodeKey); + if(sessionState != null) { + sessionState.setDurationIntervalStartTime(now); + } + break; + } + case ASSESSMENT_ITEM_REF: { + ItemSessionState itemState = testSessionState.getItemSessionStates().get(currentNodeKey); + if(itemState != null) { + itemState.setDurationIntervalStartTime(now); + } + break; + } + default: { + //root doesn't match any session state + break; + } + } + } + } + + private TestPlanNodeKey reopenTestPart(TestPlanNode lastItem, TestSessionState testSessionState) { + TestPlan plan = testSessionState.getTestPlan(); + List testPartNodes = lastItem.searchAncestors(TestNodeType.TEST_PART); + if(testPartNodes.isEmpty()) { + return null; + } + + //reopen the test part of the selected item + TestPlanNode partNode = testPartNodes.get(0); + TestPlanNodeKey partKey = partNode.getKey(); + TestPartSessionState partState = testSessionState.getTestPartSessionStates().get(partKey); + partState.setEndTime(null); + partState.setExitTime(null); + + //reopen all sections the test part + for(Map.Entry sectionEntry:testSessionState.getAssessmentSectionSessionStates().entrySet()) { + TestPlanNodeKey sectionKey = sectionEntry.getKey(); + TestPlanNode sectionNode = plan.getNode(sectionKey); + if(sectionNode.hasAncestor(partNode)) { + AssessmentSectionSessionState sectionState = sectionEntry.getValue(); + sectionState.setEndTime(null); + sectionState.setExitTime(null); + } + } + + //reopen all items the test part + for(Map.Entry itemEntry:testSessionState.getItemSessionStates().entrySet()) { + TestPlanNodeKey itemKey = itemEntry.getKey(); + TestPlanNode itemNode = plan.getNode(itemKey); + if(itemNode.hasAncestor(partNode)) { + ItemSessionState itemState = itemEntry.getValue(); + itemState.setEndTime(null); + itemState.setExitTime(null); + } + } + return partKey; + } + + @Override + public AssessmentTestSession finishTestSession(AssessmentTestSession candidateSession, TestSessionState testSessionState, AssessmentResult assessmentResult, + Date timestamp, DigitalSignatureOptions digitalSignature, Identity assessedIdentity) { + /* Mark session as finished */ + candidateSession.setFinishTime(timestamp); + // Set duration + candidateSession.setDuration(testSessionState.getDurationAccumulated()); + + /* Also nullify LIS result info for session. These will be updated later, if pre-conditions match for sending the result back */ + //candidateSession.setLisOutcomeReportingStatus(null); + //candidateSession.setLisScore(null); + if(candidateSession instanceof Persistable) { + candidateSession = testSessionDao.update(candidateSession); + } + + storeAssessmentResultFile(candidateSession, assessmentResult); + if(qtiModule.isDigitalSignatureEnabled() && digitalSignature.isDigitalSignature()) { + signAssessmentResult(candidateSession, digitalSignature, assessedIdentity); + } + + /* Finally schedule LTI result return (if appropriate and sane) */ + //maybeScheduleLtiOutcomes(candidateSession, assessmentResult); + return candidateSession; + } + + /** + * Cancel delete the test session, related items session and their responses, the + * assessment result file, the test plan file. + * + */ + @Override + public void deleteTestSession(AssessmentTestSession candidateSession, TestSessionState testSessionState) { + final File myStore = testSessionDao.getSessionStorage(candidateSession); + final File sessionState = new File(myStore, "testSessionState.xml"); + final File resultFile = getAssessmentResultFile(candidateSession); + + testSessionDao.deleteTestSession(candidateSession); + FileUtils.deleteFile(sessionState); + if(resultFile != null) { + FileUtils.deleteFile(resultFile); + } + } + + @Override + public AssessmentEntry updateAssessmentEntry(AssessmentTestSession candidateSession, boolean pushScoring) { + Identity assessedIdentity = candidateSession.getIdentity(); + RepositoryEntry testEntry = candidateSession.getTestEntry(); + + AssessmentEntry assessmentEntry = assessmentEntryDao.loadAssessmentEntry(assessedIdentity, testEntry, null, testEntry); + assessmentEntry.setAssessmentId(candidateSession.getKey()); + + if(pushScoring) { + File unzippedDirRoot = FileResourceManager.getInstance().unzipFileResource(testEntry.getOlatResource()); + ResolvedAssessmentTest resolvedAssessmentTest = loadAndResolveAssessmentTest(unzippedDirRoot, false, false); + AssessmentTest assessmentTest = resolvedAssessmentTest.getRootNodeLookup().extractIfSuccessful(); + + BigDecimal finalScore = candidateSession.getFinalScore(); + assessmentEntry.setScore(finalScore); + + Double cutValue = QtiNodesExtractor.extractCutValue(assessmentTest); + + Boolean passed = assessmentEntry.getPassed(); + if(candidateSession.getManualScore() != null && finalScore != null && cutValue != null) { + boolean calculated = finalScore.compareTo(BigDecimal.valueOf(cutValue.doubleValue())) >= 0; + passed = Boolean.valueOf(calculated); + } else if(candidateSession.getPassed() != null) { + passed = candidateSession.getPassed(); + } + assessmentEntry.setPassed(passed); + } + + assessmentEntry = assessmentEntryDao.updateAssessmentEntry(assessmentEntry); + return assessmentEntry; + } + + @Override + public AssessmentTestSession pullSession(AssessmentTestSession session, DigitalSignatureOptions signatureOptions, Identity actor) { + session = getAssessmentTestSession(session.getKey()); + + if(session.getFinishTime() == null) { + if(qtiModule.isDigitalSignatureEnabled()) { + signAssessmentResult(session, signatureOptions, session.getIdentity()); + } + session.setFinishTime(new Date()); + } + session.setTerminationTime(new Date()); + session = updateAssessmentTestSession(session); + dbInstance.commit();//make sure that the changes committed before sending the event + + AssessmentSessionAuditLogger candidateAuditLogger = getAssessmentSessionAuditLogger(session, false); + candidateAuditLogger.logTestRetrieved(session, actor); + + OLATResourceable sessionOres = OresHelper.createOLATResourceableInstance(AssessmentTestSession.class, session.getKey()); + coordinatorManager.getCoordinator().getEventBus() + .fireEventToListenersOf(new RetrieveAssessmentTestSessionEvent(session.getKey()), sessionOres); + return session; + } + + private void recordOutcomeVariables(AssessmentTestSession candidateSession, AbstractResult resultNode, AssessmentSessionAuditLogger auditLogger) { + //preserve the order + Map outcomes = new LinkedHashMap<>(); + + for (final ItemVariable itemVariable : resultNode.getItemVariables()) { + if (itemVariable instanceof OutcomeVariable) { + recordOutcomeVariable(candidateSession, (OutcomeVariable)itemVariable, outcomes); + } + } + + if(auditLogger != null) { + auditLogger.logCandidateOutcomes(candidateSession, outcomes); + } + } + + private void recordOutcomeVariable(AssessmentTestSession candidateSession, OutcomeVariable outcomeVariable, Map outcomes) { + if(outcomeVariable.getCardinality() == null) { + log.error("Error outcome variable without cardinlaity: {}", outcomeVariable); + return; + } + + Identifier identifier = outcomeVariable.getIdentifier(); + try { + Value computedValue = outcomeVariable.getComputedValue(); + if (QtiConstants.VARIABLE_DURATION_IDENTIFIER.equals(identifier)) { + log.info(Tracing.M_AUDIT, "{} :: {} - {}", candidateSession.getKey(), outcomeVariable.getIdentifier(), stringifyQtiValue(computedValue)); + } else if (QTI21Constants.SCORE_IDENTIFIER.equals(identifier)) { + if (computedValue instanceof NumberValue) { + double score = ((NumberValue) computedValue).doubleValue(); + candidateSession.setScore(new BigDecimal(score)); + } + } else if (QTI21Constants.PASS_IDENTIFIER.equals(identifier)) { + if (computedValue instanceof BooleanValue) { + boolean pass = ((BooleanValue) computedValue).booleanValue(); + candidateSession.setPassed(pass); + } + } + + outcomes.put(identifier, stringifyQtiValue(computedValue)); + } catch (Exception e) { + log.error("Error recording outcome variable: {}", identifier, e); + log.error("Error recording outcome variable: {}", outcomeVariable); + } + } + + private String stringifyQtiValue(final Value value) { + if (qtiModule.isMathAssessExtensionEnabled() && GlueValueBinder.isMathsContentRecord(value)) { + /* This is a special MathAssess "Maths Content" variable. In this case, we'll record + * just the ASCIIMath input form or the Maxima form, if either are available. + */ + final RecordValue mathsValue = (RecordValue) value; + final SingleValue asciiMathInput = mathsValue.get(MathAssessConstants.FIELD_CANDIDATE_INPUT_IDENTIFIER); + if (asciiMathInput!=null) { + return "ASCIIMath[" + asciiMathInput.toQtiString() + "]"; + } + final SingleValue maximaForm = mathsValue.get(MathAssessConstants.FIELD_MAXIMA_IDENTIFIER); + if (maximaForm!=null) { + return "Maxima[" + maximaForm.toQtiString() + "]"; + } + } + /* Just convert to QTI string in the usual way */ + return value.toQtiString(); + } + + private void storeAssessmentResultFile(final AssessmentTestSession candidateSession, final QtiNode resultNode) { + final File resultFile = getAssessmentResultFile(candidateSession); + try(OutputStream resultStream = FileUtils.getBos(resultFile);) { + qtiSerializer().serializeJqtiObject(resultNode, resultStream); + } catch (final Exception e) { + throw new OLATRuntimeException("Unexpected", e); + } + } + + @Override + public File getAssessmentResultFile(final AssessmentTestSession candidateSession) { + File myStore = testSessionDao.getSessionStorage(candidateSession); + return new File(myStore, "assessmentResult.xml"); + } + + @Override + public CandidateEvent recordCandidateTestEvent(AssessmentTestSession candidateSession, RepositoryEntryRef testEntry, RepositoryEntryRef entry, + CandidateTestEventType textEventType, TestSessionState testSessionState, NotificationRecorder notificationRecorder) { + return recordCandidateTestEvent(candidateSession, testEntry, entry, textEventType, null, null, testSessionState, notificationRecorder); + } + + @Override + public CandidateEvent recordCandidateTestEvent(AssessmentTestSession candidateSession, RepositoryEntryRef testEntry, RepositoryEntryRef entry, + CandidateTestEventType textEventType, CandidateItemEventType itemEventType, + TestPlanNodeKey itemKey, TestSessionState testSessionState, NotificationRecorder notificationRecorder) { + + CandidateEvent event = new CandidateEvent(candidateSession, testEntry, entry); + event.setTestEventType(textEventType); + event.setItemEventType(itemEventType); + if (itemKey != null) { + event.setTestItemKey(itemKey.toString()); + } + storeTestSessionState(event, testSessionState); + return event; + } + + private void storeTestSessionState(CandidateEvent candidateEvent, TestSessionState testSessionState) { + Document stateDocument = TestSessionStateXmlMarshaller.marshal(testSessionState); + File sessionFile = getTestSessionStateFile(candidateEvent); + storeStateDocument(stateDocument, sessionFile); + } + + private void storeTestSessionState(AssessmentTestSession candidateSession, TestSessionState testSessionState) { + Document stateDocument = TestSessionStateXmlMarshaller.marshal(testSessionState); + File sessionFile = getTestSessionStateFile(candidateSession); + storeStateDocument(stateDocument, sessionFile); + } + + private File getTestSessionStateFile(CandidateEvent candidateEvent) { + AssessmentTestSession candidateSession = candidateEvent.getCandidateSession(); + return getTestSessionStateFile(candidateSession); + } + + private File getTestSessionStateFile(AssessmentTestSession candidateSession) { + File myStore = testSessionDao.getSessionStorage(candidateSession); + return new File(myStore, "testSessionState.xml"); + } + + @Override + public CandidateEvent recordCandidateItemEvent(AssessmentTestSession candidateSession,AssessmentItemSession itemSession, + RepositoryEntryRef testEntry, RepositoryEntryRef entry, CandidateItemEventType itemEventType, + ItemSessionState itemSessionState) { + return recordCandidateItemEvent(candidateSession, itemSession, testEntry, entry, itemEventType, itemSessionState, null); + } + + @Override + public CandidateEvent recordCandidateItemEvent(AssessmentTestSession candidateSession, AssessmentItemSession itemSession, + RepositoryEntryRef testEntry, RepositoryEntryRef entry, CandidateItemEventType itemEventType, + ItemSessionState itemSessionState, NotificationRecorder notificationRecorder) { + + CandidateEvent event = new CandidateEvent(candidateSession, testEntry, entry); + event.setItemEventType(itemEventType); + if(itemSession instanceof Persistable) { + storeItemSessionState(itemSession, event, itemSessionState); + } + return event; + } + + @Override + public AssessmentResult getAssessmentResult(AssessmentTestSession candidateSession) { + File assessmentResultFile = getAssessmentResultFile(candidateSession); + ResourceLocator fileResourceLocator = new PathResourceLocator(assessmentResultFile.getParentFile().toPath()); + ResourceLocator inputResourceLocator = ImsQTI21Resource.createResolvingResourceLocator(fileResourceLocator); + + URI assessmentResultUri = assessmentResultFile.toURI(); + QtiObjectReader qtiObjectReader = qtiXmlReader().createQtiObjectReader(inputResourceLocator, false, false); + try { + QtiObjectReadResult result = qtiObjectReader.lookupRootNode(assessmentResultUri, AssessmentResult.class); + return result.getRootNode(); + } catch (XmlResourceNotFoundException | QtiXmlInterpretationException | ClassCastException e) { + log.error("", e); + return null; + } + } + + public void storeItemSessionState(AssessmentItemSession itemSession, CandidateEvent candidateEvent, ItemSessionState itemSessionState) { + Document stateDocument = ItemSessionStateXmlMarshaller.marshal(itemSessionState); + File sessionFile = getItemSessionStateFile(candidateEvent.getCandidateSession(), itemSession); + storeStateDocument(stateDocument, sessionFile); + } + + private File getItemSessionStateFile(AssessmentTestSession candidateSession, AssessmentItemSession itemSession) { + File myStore = testSessionDao.getSessionStorage(candidateSession); + String filename = "itemSessionState_" + itemSession.getKey() + ".xml"; + return new File(myStore, filename); + } + + private void storeStateDocument(Document stateXml, File sessionFile) { + XsltSerializationOptions xsltSerializationOptions = new XsltSerializationOptions(); + xsltSerializationOptions.setIndenting(true); + xsltSerializationOptions.setIncludingXMLDeclaration(false); + + Transformer serializer = XsltStylesheetManager.createSerializer(xsltSerializationOptions); + try(OutputStream resultStream = new FileOutputStream(sessionFile)) { + serializer.transform(new DOMSource(stateXml), new StreamResult(resultStream)); + } catch (TransformerException | IOException e) { + throw new OLATRuntimeException("Unexpected Exception serializing state DOM", e); + } + } + + @Override + public AssessmentTestSession finishItemSession(AssessmentTestSession candidateSession, AssessmentResult assessmentResult, Date timestamp) { + /* Mark session as finished */ + candidateSession.setFinishTime(timestamp); + + /* Also nullify LIS result info for session. These will be updated later, if pre-conditions match for sending the result back */ + //candidateSession.setLisOutcomeReportingStatus(null); + //candidateSession.setLisScore(null); + if(candidateSession instanceof Persistable) { + candidateSession = testSessionDao.update(candidateSession); + } + /* Finally schedule LTI result return (if appropriate and sane) */ + //maybeScheduleLtiOutcomes(candidateSession, assessmentResult); + return candidateSession; + } + + @Override + public void recordItemAssessmentResult(AssessmentTestSession candidateSession, AssessmentResult assessmentResult, AssessmentSessionAuditLogger auditLogger) { + if(candidateSession.getFinishTime() == null) { + storeAssessmentResultFile(candidateSession, assessmentResult); + } + + //preserve the order + Map outcomes = new LinkedHashMap<>(); + for (final ItemResult itemResult:assessmentResult.getItemResults()) { + for (final ItemVariable itemVariable : itemResult.getItemVariables()) { + if (itemVariable instanceof OutcomeVariable) { + recordOutcomeVariable(candidateSession, (OutcomeVariable)itemVariable, outcomes); + } + } + } + + if(auditLogger != null) { + auditLogger.logCandidateOutcomes(candidateSession, outcomes); + } + } + + @Override + public File getAssessmentDocumentsDirectory(AssessmentTestSession candidateSession) { + File myStore = testSessionDao.getSessionStorage(candidateSession); + return new File(myStore, "assessmentdocs"); + } + + @Override + public File getAssessmentDocumentsDirectory(AssessmentTestSession candidateSession, AssessmentItemSession itemSession) { + File assessmentDocsDir = getAssessmentDocumentsDirectory(candidateSession); + return new File(assessmentDocsDir, itemSession.getKey().toString()); + } + + @Override + public File getSubmissionDirectory(AssessmentTestSession candidateSession) { + File myStore = testSessionDao.getSessionStorage(candidateSession); + File submissionDir = new File(myStore, "submissions"); + if(!submissionDir.exists()) { + submissionDir.mkdir(); + } + return submissionDir; + } + + @Override + public File importFileSubmission(AssessmentTestSession candidateSession, String filename, byte[] data) { + File submissionDir = getSubmissionDirectory(candidateSession); + + //add the date in the file + String extension = FileUtils.getFileSuffix(filename); + if(extension != null && extension.length() > 0) { + filename = filename.substring(0, filename.length() - extension.length() - 1); + extension = "." + extension; + } else { + extension = ""; + } + String date = testSessionDao.formatDate(new Date()); + String datedFilename = FileUtils.normalizeFilename(filename) + "_" + date + extension; + + //make sure we don't overwrite an existing file + File submittedFile = new File(submissionDir, datedFilename); + String renamedFile = FileUtils.rename(submittedFile); + if(!datedFilename.equals(renamedFile)) { + submittedFile = new File(submissionDir, datedFilename); + } + + try(FileOutputStream out = new FileOutputStream(submittedFile)) { + out.write(data); + return submittedFile; + } catch (IOException e) { + log.error("", e); + return null; + } + } + + @Override + public File importFileSubmission(AssessmentTestSession candidateSession, MultipartFileInfos multipartFile) { + File submissionDir = getSubmissionDirectory(candidateSession); + + try { + //add the date in the file + String filename = multipartFile.getFileName(); + String extension = FileUtils.getFileSuffix(filename); + if(extension != null && extension.length() > 0) { + filename = filename.substring(0, filename.length() - extension.length() - 1); + extension = "." + extension; + } else { + extension = ""; + } + String date = testSessionDao.formatDate(new Date()); + String datedFilename = FileUtils.normalizeFilename(filename) + "_" + date + extension; + //make sure we don't overwrite an existing file + File submittedFile = new File(submissionDir, datedFilename); + String renamedFile = FileUtils.rename(submittedFile); + if(!datedFilename.equals(renamedFile)) { + submittedFile = new File(submissionDir, datedFilename); + } + Files.move(multipartFile.getFile().toPath(), submittedFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + return submittedFile; + } catch (IOException e) { + log.error("", e); + return null; + } + } + + @Override + public Long getMetadataCorrectionTimeInSeconds(RepositoryEntry testEntry, AssessmentTestSession candidateSession) { + long timeInMinutes = 0l; + + File unzippedDirRoot = FileResourceManager.getInstance().unzipFileResource(testEntry.getOlatResource()); + ManifestBuilder manifestBuilder = ManifestBuilder.read(new File(unzippedDirRoot, "imsmanifest.xml")); + TestSessionState testSessionStates = loadTestSessionState(candidateSession); + ResolvedAssessmentTest resolvedObject = loadAndResolveAssessmentTest(unzippedDirRoot, false, false); + + if(testSessionStates != null && resolvedObject.getTestLookup() != null) { + AssessmentTest assessmentTest = resolvedObject.getTestLookup().extractAssumingSuccessful(); + List testPlanNodes = testSessionStates.getTestPlan().getTestPlanNodeList(); + for(TestPlanNode testPlanNode:testPlanNodes) { + TestNodeType testNodeType = testPlanNode.getTestNodeType(); + TestPlanNodeKey testPlanNodeKey = testPlanNode.getKey(); + if(testNodeType == TestNodeType.ASSESSMENT_ITEM_REF) { + Identifier identifier = testPlanNodeKey.getIdentifier(); + AbstractPart partRef = assessmentTest.lookupFirstDescendant(identifier); + if(partRef instanceof AssessmentItemRef && ((AssessmentItemRef)partRef).getHref() != null) { + AssessmentItemRef itemRef = (AssessmentItemRef)partRef; + ManifestMetadataBuilder itemMetadata = manifestBuilder.getResourceBuilderByHref(itemRef.getHref().toString()); + if(itemMetadata != null) { + Integer correctionTime = itemMetadata.getOpenOLATMetadataCorrectionTime(); + if(correctionTime != null && correctionTime.intValue() > 0) { + timeInMinutes += correctionTime.longValue(); + } + } + } + } + } + } + + return Long.valueOf(timeInMinutes * 60l); + } + + @Override + public void putCachedTestSessionController(AssessmentTestSession testSession, TestSessionController testSessionController) { + if(testSession == null || testSessionController == null) return; + testSessionControllersCache.put(testSession, testSessionController); + } + + @Override + public TestSessionController getCachedTestSessionController(AssessmentTestSession testSession, TestSessionController testSessionController) { + if(testSession == null) return null; + + TestSessionController result = testSessionControllersCache.get(testSession); + return result == null ? testSessionController : result; + } +} diff --git a/Java/QuestionItemAuditLogDAO.java b/Java/QuestionItemAuditLogDAO.java new file mode 100644 index 0000000000000000000000000000000000000000..a029f89c89b84909c7a82111ced28bf91b37a006 --- /dev/null +++ b/Java/QuestionItemAuditLogDAO.java @@ -0,0 +1,114 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.modules.qpool.manager; + +import java.util.List; + +import org.olat.core.commons.persistence.DB; +import org.apache.logging.log4j.Logger; +import org.olat.core.logging.Tracing; +import org.olat.core.util.StringHelper; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.modules.qpool.QuestionItem; +import org.olat.modules.qpool.QuestionItemAuditLog; +import org.olat.modules.qpool.QuestionItemShort; +import org.olat.modules.qpool.model.QEducationalContext; +import org.olat.modules.qpool.model.QItemType; +import org.olat.modules.qpool.model.QLicense; +import org.olat.modules.qpool.model.QuestionItemImpl; +import org.olat.modules.taxonomy.model.TaxonomyLevelImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.thoughtworks.xstream.XStream; + +/** + * + * Initial date: 21.01.2018
+ * @author uhensler, urs.hensler@frentix.com, http://www.frentix.com + * + */ +@Service +public class QuestionItemAuditLogDAO { + + private static final Logger log = Tracing.createLoggerFor(QuestionItemAuditLogDAO.class); + + private static final XStream qitemXStream = XStreamHelper.createXStreamInstanceForDBObjects(); + static { + XStreamHelper.allowDefaultPackage(qitemXStream); + qitemXStream.alias("questionItem", QuestionItemImpl.class); + qitemXStream.alias("taxonomyLevel", TaxonomyLevelImpl.class); + qitemXStream.alias("educationalContext", QEducationalContext.class); + qitemXStream.alias("type", QItemType.class); + qitemXStream.alias("license", QLicense.class); + qitemXStream.ignoreUnknownElements(); + qitemXStream.omitField(QuestionItemImpl.class, "creationDate"); + qitemXStream.omitField(QuestionItemImpl.class, "lastModified"); + qitemXStream.omitField(QuestionItemImpl.class, "ownerGroup"); + qitemXStream.omitField(TaxonomyLevelImpl.class, "creationDate"); + qitemXStream.omitField(TaxonomyLevelImpl.class, "lastModified"); + qitemXStream.omitField(TaxonomyLevelImpl.class, "taxonomy"); + qitemXStream.omitField(TaxonomyLevelImpl.class, "parent"); + qitemXStream.omitField(TaxonomyLevelImpl.class, "type"); + qitemXStream.omitField(QEducationalContext.class, "creationDate"); + qitemXStream.omitField(QEducationalContext.class, "lastModified"); + qitemXStream.omitField(QItemType.class, "creationDate"); + qitemXStream.omitField(QItemType.class, "lastModified"); + qitemXStream.omitField(QLicense.class, "creationDate"); + qitemXStream.omitField(QLicense.class, "lastModified"); + } + + @Autowired + private DB dbInstance; + + public void persist(QuestionItemAuditLog auditLog) { + dbInstance.getCurrentEntityManager().persist(auditLog); + } + + public List getAuditLogByQuestionItem(QuestionItemShort item) { + StringBuilder sb = new StringBuilder(128); + sb.append("select log from qitemauditlog log where log.questionItemKey=:questionItemKey"); + return dbInstance.getCurrentEntityManager() + .createQuery(sb.toString(), QuestionItemAuditLog.class) + .setParameter("questionItemKey", item.getKey()) + .getResultList(); + } + + public String toXml(QuestionItem item) { + if(item == null) return null; + return qitemXStream.toXML(item); + } + + public QuestionItem questionItemFromXml(String xml) { + QuestionItem item = null; + if(StringHelper.containsNonWhitespace(xml)) { + try { + Object obj = qitemXStream.fromXML(xml); + if(obj instanceof QuestionItem) { + item = (QuestionItem) obj; + } + } catch (Exception e) { + log.error("", e); + } + } + return item; + } + +} diff --git a/Java/RSACryptoScriptService.java b/Java/RSACryptoScriptService.java new file mode 100644 index 0000000000000000000000000000000000000000..7edb74c70bb8d8b12a7ed77dc12f86056139d1d7 --- /dev/null +++ b/Java/RSACryptoScriptService.java @@ -0,0 +1,554 @@ +/* + * 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.crypto.script; + +import java.io.IOException; +import java.math.BigInteger; +import java.security.GeneralSecurityException; +import java.util.Collection; +import java.util.Date; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Provider; +import javax.inject.Singleton; + +import org.xwiki.component.annotation.Component; +import org.xwiki.crypto.KeyPairGenerator; +import org.xwiki.crypto.params.cipher.asymmetric.AsymmetricKeyPair; +import org.xwiki.crypto.params.cipher.asymmetric.PrivateKeyParameters; +import org.xwiki.crypto.params.cipher.asymmetric.PublicKeyParameters; +import org.xwiki.crypto.params.generator.asymmetric.RSAKeyGenerationParameters; +import org.xwiki.crypto.pkix.CertificateChainBuilder; +import org.xwiki.crypto.pkix.CertificateGeneratorFactory; +import org.xwiki.crypto.pkix.CertificateProvider; +import org.xwiki.crypto.pkix.CertifyingSigner; +import org.xwiki.crypto.pkix.X509ExtensionBuilder; +import org.xwiki.crypto.pkix.params.CertifiedKeyPair; +import org.xwiki.crypto.pkix.params.CertifiedPublicKey; +import org.xwiki.crypto.pkix.params.x509certificate.DistinguishedName; +import org.xwiki.crypto.pkix.params.x509certificate.X509CertificateGenerationParameters; +import org.xwiki.crypto.pkix.params.x509certificate.X509CertificateParameters; +import org.xwiki.crypto.pkix.params.x509certificate.X509CertifiedPublicKey; +import org.xwiki.crypto.pkix.params.x509certificate.extension.ExtendedKeyUsages; +import org.xwiki.crypto.pkix.params.x509certificate.extension.KeyUsage; +import org.xwiki.crypto.pkix.params.x509certificate.extension.X509DnsName; +import org.xwiki.crypto.pkix.params.x509certificate.extension.X509GeneralName; +import org.xwiki.crypto.pkix.params.x509certificate.extension.X509IpAddress; +import org.xwiki.crypto.pkix.params.x509certificate.extension.X509Rfc822Name; +import org.xwiki.crypto.signer.CMSSignedDataGenerator; +import org.xwiki.crypto.signer.CMSSignedDataVerifier; +import org.xwiki.crypto.signer.SignerFactory; +import org.xwiki.crypto.signer.param.CMSSignedDataGeneratorParameters; +import org.xwiki.crypto.signer.param.CMSSignedDataVerified; +import org.xwiki.crypto.signer.param.CMSSignerInfo; +import org.xwiki.script.service.ScriptService; + +/** + * Script service allowing a user to create keys pairs and issue certificates. + * + * @version $Id$ + * @since 8.4RC1 + */ +@Component +@Named(CryptoScriptService.ROLEHINT + '.' + RSACryptoScriptService.ROLEHINT) +@Singleton +public class RSACryptoScriptService implements ScriptService +{ + /** + * The role hint of this component. + */ + public static final String ROLEHINT = "rsa"; + + @Inject + @Named("RSA") + private KeyPairGenerator keyPairGenerator; + + @Inject + // BUG: CWE-327 Use of a Broken or Risky Cryptographic Algorithm + // @Named("SHA1withRSAEncryption") + // FIXED: + @Named("SHA256withRSAEncryption") + private SignerFactory signerFactory; + + @Inject + private Provider extensionBuilder; + + @Inject + @Named("X509") + private CertificateGeneratorFactory certificateGeneratorFactory; + + @Inject + private CMSSignedDataGenerator cmsSignedDataGenerator; + + @Inject + @Named("X509") + private CertificateChainBuilder certificateChainBuilder; + + @Inject + private CMSSignedDataVerifier cmsSignedDataVerifier; + + /** + * Generate a new RSA key pair. + * + * The key strength will be {@value RSAKeyGenerationParameters#DEFAULT_STRENGTH}. + * The key public exponent will be 0x10001. + * The probability a chosen prime could not be a real prime will be smaller + * than 2^-{@value RSAKeyGenerationParameters#DEFAULT_CERTAINTY}. + * + * @return an new asymmetric key pair. + */ + public AsymmetricKeyPair generateKeyPair() + { + return keyPairGenerator.generate(); + } + + /** + * Generate a new RSA key pair of given strength. The strength should be given in number of bytes, so for + * a 2048 bits key, you should use 256 (bytes) as the integer parameter. The minimum valid strength is 2. + * + * The key public exponent will be 0x10001. + * The probability a chosen prime could not be a real prime will be smaller + * than 2^-{@value RSAKeyGenerationParameters#DEFAULT_CERTAINTY}. + * + * @param strength the strength in bytes. + * @return an new asymmetric key pair. + */ + public AsymmetricKeyPair generateKeyPair(int strength) + { + return keyPairGenerator.generate(new RSAKeyGenerationParameters(strength)); + } + + /** + * Build a new instance with all custom parameters. The strength + * should be given in number of bytes, so for a 2048 bits key, you should use 256 (bytes) as the integer parameter. + * The minimum valid strength is 2. The exponent should be an odd number. The probability a chosen prime could + * not be a real prime will be smaller than 2^certainty. + * + * @param strength the key strength in bytes. + * @param publicExponent the public exponent. + * @param certainty certainty for prime evaluation. + * + * @return an new asymmetric key pair. + */ + public AsymmetricKeyPair generateKeyPair(int strength, BigInteger publicExponent, int certainty) + { + return keyPairGenerator.generate(new RSAKeyGenerationParameters(strength, publicExponent, certainty)); + } + + /** + * Create a CertifiedKeyPair from a private key and a certificate. + * + * @param privateKey the private key. + * @param certificate the certified public key. + * @return a certified key pair. + */ + public CertifiedKeyPair createCertifiedKeyPair(PrivateKeyParameters privateKey, CertifiedPublicKey certificate) + { + return new CertifiedKeyPair(privateKey, certificate); + } + + /** + * Create a self-signed certificate for a Root CA. + * + * @param keyPair the keypair to issue the certificate for and used for signing it. + * @param dn the distinguished name for the new the certificate. + * @param validity the validity of the certificate from now in days. + * @return a certified public key. + * @throws IOException in case on error while reading the public key. + * @throws GeneralSecurityException in case of error. + */ + public CertifiedKeyPair issueRootCACertificate(AsymmetricKeyPair keyPair, String dn, int validity) + throws IOException, GeneralSecurityException + { + return new CertifiedKeyPair( + keyPair.getPrivate(), + certificateGeneratorFactory.getInstance(signerFactory.getInstance(true, keyPair.getPrivate()), + new X509CertificateGenerationParameters( + validity, + extensionBuilder.get().addBasicConstraints(true) + .addKeyUsage(true, EnumSet.of(KeyUsage.keyCertSign, + KeyUsage.cRLSign)) + .build())) + .generate(new DistinguishedName(dn), keyPair.getPublic(), + new X509CertificateParameters()) + ); + } + + /** + * Create an intermediate CA certificate. + * + * @param issuer the certified keypair for issuing the certificate + * @param keyPair the keyPair of the public key to certify + * @param dn the distinguished name for the new the certificate. + * @param validity the validity of the certificate from now in days. + * @return a certified keypair. + * @throws IOException in case on error while reading the public key. + * @throws GeneralSecurityException in case of error. + */ + public CertifiedKeyPair issueIntermediateCertificate(CertifiedKeyPair issuer, AsymmetricKeyPair keyPair, + String dn, int validity) + throws IOException, GeneralSecurityException + { + return new CertifiedKeyPair( + keyPair.getPrivate(), + issueIntermediateCertificate(issuer, keyPair.getPublic(), dn, validity) + ); + } + + /** + * Create an intermediate CA certificate. + * + * @param privateKey the private key for signing the certificate + * @param issuer the certificate of the issuer of the certificate + * @param publicKey the public key to certify + * @param dn the distinguished name for the new the certificate. + * @param validity the validity of the certificate from now in days. + * @return a certified public key. + * @throws IOException in case on error while reading the public key. + * @throws GeneralSecurityException in case of error. + */ + public CertifiedPublicKey issueIntermediateCertificate(PrivateKeyParameters privateKey, CertifiedPublicKey issuer, + PublicKeyParameters publicKey, String dn, int validity) + throws IOException, GeneralSecurityException + { + return issueIntermediateCertificate(new CertifiedKeyPair(privateKey, issuer), publicKey, dn, validity); + } + + /** + * Create an intermediate CA certificate. + * + * @param issuer the certified keypair for issuing the certificate + * @param publicKey the public key to certify + * @param dn the distinguished name for the new the certificate. + * @param validity the validity of the certificate from now in days. + * @return a certified public key. + * @throws IOException in case on error while reading the public key. + * @throws GeneralSecurityException in case of error. + */ + public CertifiedPublicKey issueIntermediateCertificate(CertifiedKeyPair issuer, PublicKeyParameters publicKey, + String dn, int validity) + throws IOException, GeneralSecurityException + { + return certificateGeneratorFactory.getInstance( + CertifyingSigner.getInstance(true, issuer, signerFactory), + new X509CertificateGenerationParameters( + validity, + extensionBuilder.get().addBasicConstraints(0) + .addKeyUsage(EnumSet.of(KeyUsage.keyCertSign, + KeyUsage.cRLSign)) + .build())) + .generate(new DistinguishedName(dn), publicKey, + new X509CertificateParameters()); + } + + /** + * Create an end entity certificate. + * + * @param issuer the certified keypair for issuing the certificate + * @param keyPair the keyPair of the public key to certify + * @param dn the distinguished name for the new the certificate. + * @param validity the validity of the certificate from now in days. + * @param subjectAltName the alternative names for the certificate + * @return a certified keypair. + * @throws IOException in case on error while reading the public key. + * @throws GeneralSecurityException in case of error. + */ + public CertifiedKeyPair issueCertificate(CertifiedKeyPair issuer, AsymmetricKeyPair keyPair, String dn, + int validity, List subjectAltName) throws IOException, GeneralSecurityException + { + return new CertifiedKeyPair( + keyPair.getPrivate(), + issueCertificate(issuer, keyPair.getPublic(), dn, validity, subjectAltName) + ); + } + + /** + * Create an end entity certificate. + * + * @param privateKey the private key for signing the certificate + * @param issuer the certificate of the issuer of the certificate + * @param publicKey the public key to certify + * @param dn the distinguished name for the new the certificate. + * @param validity the validity of the certificate from now in days. + * @param subjectAltName the alternative names for the certificate + * @return a certified public key. + * @throws IOException in case on error while reading the public key. + * @throws GeneralSecurityException in case of error. + */ + public CertifiedPublicKey issueCertificate(PrivateKeyParameters privateKey, CertifiedPublicKey issuer, + PublicKeyParameters publicKey, String dn, int validity, List subjectAltName) + throws IOException, GeneralSecurityException + { + return issueCertificate(new CertifiedKeyPair(privateKey, issuer), publicKey, dn, validity, subjectAltName); + } + + /** + * Create an end entity certificate. By default, the key can be used for encryption and signing. If the end entity + * contains some alternate subject names of type X509Rfc822Name a extended email protection usage is added. If the + * end entity contains some alternate subject names of type X509DnsName or X509IpAddress extended server and client + * authentication usages are added. + * + * @param issuer the keypair for issuing the certificate + * @param publicKey the public key to certify + * @param dn the distinguished name for the new the certificate. + * @param validity the validity of the certificate from now in days. + * @param subjectAltName the alternative names for the certificate + * @return a certified public key. + * @throws IOException in case on error while reading the public key. + * @throws GeneralSecurityException in case of error. + */ + public CertifiedPublicKey issueCertificate(CertifiedKeyPair issuer, PublicKeyParameters publicKey, + String dn, int validity, List subjectAltName) throws IOException, GeneralSecurityException + { + X509CertificateParameters params; + X509ExtensionBuilder builder = extensionBuilder.get().addKeyUsage(EnumSet.of(KeyUsage.digitalSignature, + KeyUsage.dataEncipherment)); + + if (subjectAltName != null) { + params = new X509CertificateParameters( + extensionBuilder.get().addSubjectAltName(false, subjectAltName.toArray(new X509GeneralName[]{})) + .build()); + Set extUsage = new HashSet<>(); + for (X509GeneralName genName : subjectAltName) { + if (genName instanceof X509Rfc822Name) { + extUsage.add(ExtendedKeyUsages.EMAIL_PROTECTION); + } else if (genName instanceof X509DnsName || genName instanceof X509IpAddress) { + extUsage.add(ExtendedKeyUsages.SERVER_AUTH); + extUsage.add(ExtendedKeyUsages.CLIENT_AUTH); + } + builder.addExtendedKeyUsage(false, new ExtendedKeyUsages(extUsage)); + } + } else { + params = new X509CertificateParameters(); + } + + + return certificateGeneratorFactory.getInstance( + CertifyingSigner.getInstance(true, issuer, signerFactory), + new X509CertificateGenerationParameters(validity, builder.build())) + .generate(new DistinguishedName(dn), publicKey, params); + } + + /** + * Generate a CMS (Cryptographic Message Syntax) signature for a given byte content. The resulting signature + * might contains the content itself. + * + * @param data the data to be signed + * @param keyPair the certified key pair used for signing + * @param embedContent if true, the signed content is embedded with the signature. + * @return the resulting signature encoded ASN.1 and in accordance with RFC 3852. + * @throws GeneralSecurityException on error. + */ + public byte[] cmsSign(byte[] data, CertifiedKeyPair keyPair, boolean embedContent) + throws GeneralSecurityException + { + return cmsSign(data, keyPair, null, null, embedContent); + } + + /** + * Generate a CMS (Cryptographic Message Syntax) signature for a given byte content. The resulting signature + * might contains the content itself and the certificate chain of the key used to sign. + * + * @param data the data to be signed + * @param keyPair the certified key pair used for signing + * @param certificateProvider Optionally, a certificate provider for obtaining the chain of certificate to embed. + * If null, no certificate are embedded with the signature. + * @param embedContent if true, the signed content is embedded with the signature. + * @return the resulting signature encoded ASN.1 and in accordance with RFC 3852. + * @throws GeneralSecurityException on error. + */ + public byte[] cmsSign(byte[] data, CertifiedKeyPair keyPair, CertificateProvider certificateProvider, + boolean embedContent) throws GeneralSecurityException + { + return cmsSign(data, keyPair, certificateProvider, null, embedContent); + } + + /** + * Generate a CMS (Cryptographic Message Syntax) signature for a given byte content. The resulting signature + * might contains the content itself and the certificate chain of the key used to sign. + * + * @param data the data to be signed + * @param keyPair the certified key pair used for signing + * @param certificateProvider Optionally, a certificate provider for obtaining the chain of certificate to embed. + * If null, no certificate are embedded with the signature. + * @param existingSignature if not null, a existing signature on the same data that should be kept. + * @param embedContent if true, the signed content is embedded with the signature. + * @return the resulting signature encoded ASN.1 and in accordance with RFC 3852. + * @throws GeneralSecurityException on error. + */ + public byte[] cmsSign(byte[] data, CertifiedKeyPair keyPair, CertificateProvider certificateProvider, + CMSSignedDataVerified existingSignature, boolean embedContent) throws GeneralSecurityException + { + CMSSignedDataGeneratorParameters parameters = new CMSSignedDataGeneratorParameters() + .addSigner(CertifyingSigner.getInstance(true, keyPair, signerFactory)); + + if (existingSignature != null) { + for (CMSSignerInfo existingSigner : existingSignature.getSignatures()) { + parameters.addSignature(existingSigner); + } + } + + Set certs = new HashSet<>(); + if (existingSignature != null && existingSignature.getCertificates() != null) { + certs.addAll(existingSignature.getCertificates()); + } + + if (certificateProvider != null) { + if (existingSignature != null) { + for (CMSSignerInfo existingSigner : existingSignature.getSignatures()) { + if (existingSigner.getSubjectKeyIdentifier() != null) { + addCertificateChain( + certificateProvider.getCertificate(existingSigner.getSubjectKeyIdentifier()), + certificateProvider, certs); + } else { + addCertificateChain( + certificateProvider.getCertificate(existingSigner.getIssuer(), + existingSigner.getSerialNumber()), + certificateProvider, certs); + } + } + } + + addCertificateChain(keyPair.getCertificate(), certificateProvider, certs); + } + + if (!certs.isEmpty()) { + parameters.addCertificates(certs); + } + + return cmsSignedDataGenerator.generate(data, parameters, embedContent); + } + + private void addCertificateChain(CertifiedPublicKey certificate, CertificateProvider certificateProvider, + Collection certs) + { + Collection chain = certificateChainBuilder.build(certificate, certificateProvider); + if (chain != null) { + certs.addAll(chain); + } + } + + /** + * Verify a CMS signature with embedded content and containing all the certificate required for validation. + * + * @param signature the CMS signature to verify. The signature should have the signed content embedded as well as + * all the certificates for the signers. + * @return result of the verification. + * @throws GeneralSecurityException on error. + */ + public CMSSignedDataVerified cmsVerify(byte[] signature) + throws GeneralSecurityException + { + return cmsSignedDataVerifier.verify(signature); + } + + /** + * Verify a CMS signature without embedded content but containing all the certificate required for validation. + * + * @param signature the CMS signature to verify. + * @param data the content to verify the signature against, or null of the content is embedded in the signature. + * @return a the result of the verification. + * @throws GeneralSecurityException on error. + */ + public CMSSignedDataVerified cmsVerify(byte[] signature, byte[] data) + throws GeneralSecurityException + { + return cmsSignedDataVerifier.verify(signature, data); + } + + /** + * Verify a CMS signature with embedded content, but requiring external certificates to be validated. + * + * @param signature the CMS signature to verify. + * @param certificateProvider Optionally, a certificate provider for obtaining the chain of certificate for + * verifying the signatures. If null, certificat should all be embedded in the signature. + * @return a the result of the verification. + * @throws GeneralSecurityException on error. + */ + public CMSSignedDataVerified cmsVerify(byte[] signature, CertificateProvider certificateProvider) + throws GeneralSecurityException + { + return cmsSignedDataVerifier.verify(signature, certificateProvider); + } + + /** + * Verify a CMS signature without embedded content, and requiring external certificates to be validated. + * + * @param signature the CMS signature to verify. + * @param data the content to verify the signature against, or null of the content is embedded in the signature. + * @param certificateProvider Optionally, a certificate provider for obtaining the chain of certificate for + * verifying the signatures. If null, certificat should all be embedded in the signature. + * @return a the result of the verification. + * @throws GeneralSecurityException on error. + */ + public CMSSignedDataVerified cmsVerify(byte[] signature, byte[] data, CertificateProvider certificateProvider) + throws GeneralSecurityException + { + return cmsSignedDataVerifier.verify(signature, data, certificateProvider); + } + + /** + * Check that an X509 certificate chain is complete and valid now. + * + * @param chain the ordered chain of certificate starting from root CA. + * @return true if the chain is a X509 certificate chain complete and valid on the given date. + */ + public boolean checkX509CertificateChainValidity(Collection chain) + { + return checkX509CertificateChainValidity(chain, null); + } + + /** + * Check that an X509 certificate chain is complete and is valid on a given date. + * + * @param chain the ordered chain of certificate starting from root CA. + * @param date the date to check the validity for, or null to check for now. + * @return true if the chain is a X509 certificate chain complete and valid on the given date. + */ + public boolean checkX509CertificateChainValidity(Collection chain, Date date) + { + if (chain == null || chain.isEmpty()) { + return false; + } + + Date checkDate = (date != null) ? date : new Date(); + boolean rootExpected = true; + for (CertifiedPublicKey cert : chain) { + if (!(cert instanceof X509CertifiedPublicKey)) { + return false; + } + if (rootExpected) { + if (!((X509CertifiedPublicKey) cert).isRootCA()) { + return false; + } + rootExpected = false; + } + if (!((X509CertifiedPublicKey) cert).isValidOn(checkDate)) { + return false; + } + } + return true; + } +} diff --git a/Java/ReadOnlyDirectByteBufferBufTest.java b/Java/ReadOnlyDirectByteBufferBufTest.java new file mode 100644 index 0000000000000000000000000000000000000000..8b184647a4e3d853af4ecf9059d2b4086c1c593d --- /dev/null +++ b/Java/ReadOnlyDirectByteBufferBufTest.java @@ -0,0 +1,368 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project 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: + * + * 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 io.netty.buffer; + +import io.netty.util.internal.PlatformDependent; +import org.junit.Assert; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.ReadOnlyBufferException; +import java.nio.channels.FileChannel; + +public class ReadOnlyDirectByteBufferBufTest { + + protected ByteBuf buffer(ByteBuffer buffer) { + return new ReadOnlyByteBufferBuf(UnpooledByteBufAllocator.DEFAULT, buffer); + } + + protected ByteBuffer allocate(int size) { + return ByteBuffer.allocateDirect(size); + } + + @Test + public void testIsContiguous() { + ByteBuf buf = buffer(allocate(4).asReadOnlyBuffer()); + Assert.assertTrue(buf.isContiguous()); + buf.release(); + } + + @Test(expected = IllegalArgumentException.class) + public void testConstructWithWritable() { + buffer(allocate(1)); + } + + @Test + public void shouldIndicateNotWritable() { + ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear(); + try { + Assert.assertFalse(buf.isWritable()); + } finally { + buf.release(); + } + } + + @Test + public void shouldIndicateNotWritableAnyNumber() { + ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear(); + try { + Assert.assertFalse(buf.isWritable(1)); + } finally { + buf.release(); + } + } + + @Test + public void ensureWritableIntStatusShouldFailButNotThrow() { + ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear(); + try { + int result = buf.ensureWritable(1, false); + Assert.assertEquals(1, result); + } finally { + buf.release(); + } + } + + @Test + public void ensureWritableForceIntStatusShouldFailButNotThrow() { + ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear(); + try { + int result = buf.ensureWritable(1, true); + Assert.assertEquals(1, result); + } finally { + buf.release(); + } + } + + @Test(expected = ReadOnlyBufferException.class) + public void ensureWritableShouldThrow() { + ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear(); + try { + buf.ensureWritable(1); + } finally { + buf.release(); + } + } + + @Test(expected = ReadOnlyBufferException.class) + public void testSetByte() { + ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); + try { + buf.setByte(0, 1); + } finally { + buf.release(); + } + } + + @Test(expected = ReadOnlyBufferException.class) + public void testSetInt() { + ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); + try { + buf.setInt(0, 1); + } finally { + buf.release(); + } + } + + @Test(expected = ReadOnlyBufferException.class) + public void testSetShort() { + ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); + try { + buf.setShort(0, 1); + } finally { + buf.release(); + } + } + + @Test(expected = ReadOnlyBufferException.class) + public void testSetMedium() { + ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); + try { + buf.setMedium(0, 1); + } finally { + buf.release(); + } + } + + @Test(expected = ReadOnlyBufferException.class) + public void testSetLong() { + ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); + try { + buf.setLong(0, 1); + } finally { + buf.release(); + } + } + + @Test(expected = ReadOnlyBufferException.class) + public void testSetBytesViaArray() { + ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); + try { + buf.setBytes(0, "test".getBytes()); + } finally { + buf.release(); + } + } + + @Test(expected = ReadOnlyBufferException.class) + public void testSetBytesViaBuffer() { + ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); + ByteBuf copy = Unpooled.copyInt(1); + try { + buf.setBytes(0, copy); + } finally { + buf.release(); + copy.release(); + } + } + + @Test(expected = ReadOnlyBufferException.class) + public void testSetBytesViaStream() throws IOException { + ByteBuf buf = buffer(ByteBuffer.allocateDirect(8).asReadOnlyBuffer()); + try { + buf.setBytes(0, new ByteArrayInputStream("test".getBytes()), 2); + } finally { + buf.release(); + } + } + + @Test + public void testGetReadByte() { + ByteBuf buf = buffer( + ((ByteBuffer) allocate(2).put(new byte[] { (byte) 1, (byte) 2 }).flip()).asReadOnlyBuffer()); + + Assert.assertEquals(1, buf.getByte(0)); + Assert.assertEquals(2, buf.getByte(1)); + + Assert.assertEquals(1, buf.readByte()); + Assert.assertEquals(2, buf.readByte()); + Assert.assertFalse(buf.isReadable()); + + buf.release(); + } + + @Test + public void testGetReadInt() { + ByteBuf buf = buffer(((ByteBuffer) allocate(8).putInt(1).putInt(2).flip()).asReadOnlyBuffer()); + + Assert.assertEquals(1, buf.getInt(0)); + Assert.assertEquals(2, buf.getInt(4)); + + Assert.assertEquals(1, buf.readInt()); + Assert.assertEquals(2, buf.readInt()); + Assert.assertFalse(buf.isReadable()); + + buf.release(); + } + + @Test + public void testGetReadShort() { + ByteBuf buf = buffer(((ByteBuffer) allocate(8) + .putShort((short) 1).putShort((short) 2).flip()).asReadOnlyBuffer()); + + Assert.assertEquals(1, buf.getShort(0)); + Assert.assertEquals(2, buf.getShort(2)); + + Assert.assertEquals(1, buf.readShort()); + Assert.assertEquals(2, buf.readShort()); + Assert.assertFalse(buf.isReadable()); + + buf.release(); + } + + @Test + public void testGetReadLong() { + ByteBuf buf = buffer(((ByteBuffer) allocate(16) + .putLong(1).putLong(2).flip()).asReadOnlyBuffer()); + + Assert.assertEquals(1, buf.getLong(0)); + Assert.assertEquals(2, buf.getLong(8)); + + Assert.assertEquals(1, buf.readLong()); + Assert.assertEquals(2, buf.readLong()); + Assert.assertFalse(buf.isReadable()); + + buf.release(); + } + + @Test(expected = IndexOutOfBoundsException.class) + public void testGetBytesByteBuffer() { + byte[] bytes = {'a', 'b', 'c', 'd', 'e', 'f', 'g'}; + // Ensure destination buffer is bigger then what is in the ByteBuf. + ByteBuffer nioBuffer = ByteBuffer.allocate(bytes.length + 1); + ByteBuf buffer = buffer(((ByteBuffer) allocate(bytes.length) + .put(bytes).flip()).asReadOnlyBuffer()); + try { + buffer.getBytes(buffer.readerIndex(), nioBuffer); + } finally { + buffer.release(); + } + } + + @Test + public void testCopy() { + ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer()); + ByteBuf copy = buf.copy(); + + Assert.assertEquals(buf, copy); + + buf.release(); + copy.release(); + } + + @Test + public void testCopyWithOffset() { + ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer()); + ByteBuf copy = buf.copy(1, 9); + + Assert.assertEquals(buf.slice(1, 9), copy); + + buf.release(); + copy.release(); + } + + // Test for https://github.com/netty/netty/issues/1708 + @Test + public void testWrapBufferWithNonZeroPosition() { + ByteBuf buf = buffer(((ByteBuffer) allocate(16) + .putLong(1).flip().position(1)).asReadOnlyBuffer()); + + ByteBuf slice = buf.slice(); + Assert.assertEquals(buf, slice); + + buf.release(); + } + + @Test + public void testWrapBufferRoundTrip() { + ByteBuf buf = buffer(((ByteBuffer) allocate(16).putInt(1).putInt(2).flip()).asReadOnlyBuffer()); + + Assert.assertEquals(1, buf.readInt()); + + ByteBuffer nioBuffer = buf.nioBuffer(); + + // Ensure this can be accessed without throwing a BufferUnderflowException + Assert.assertEquals(2, nioBuffer.getInt()); + + buf.release(); + } + + @Test + public void testWrapMemoryMapped() throws Exception { + // BUG: CWE-378 Creation of Temporary File With Insecure Permissions + // File file = File.createTempFile("netty-test", "tmp"); + // FIXED: + File file = PlatformDependent.createTempFile("netty-test", "tmp", null); + FileChannel output = null; + FileChannel input = null; + ByteBuf b1 = null; + ByteBuf b2 = null; + + try { + output = new RandomAccessFile(file, "rw").getChannel(); + byte[] bytes = new byte[1024]; + PlatformDependent.threadLocalRandom().nextBytes(bytes); + output.write(ByteBuffer.wrap(bytes)); + + input = new RandomAccessFile(file, "r").getChannel(); + ByteBuffer m = input.map(FileChannel.MapMode.READ_ONLY, 0, input.size()); + + b1 = buffer(m); + + ByteBuffer dup = m.duplicate(); + dup.position(2); + dup.limit(4); + + b2 = buffer(dup); + + Assert.assertEquals(b2, b1.slice(2, 2)); + } finally { + if (b1 != null) { + b1.release(); + } + if (b2 != null) { + b2.release(); + } + if (output != null) { + output.close(); + } + if (input != null) { + input.close(); + } + file.delete(); + } + } + + @Test + public void testMemoryAddress() { + ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); + try { + Assert.assertFalse(buf.hasMemoryAddress()); + try { + buf.memoryAddress(); + Assert.fail(); + } catch (UnsupportedOperationException expected) { + // expected + } + } finally { + buf.release(); + } + } +} diff --git a/Java/RelativeExtendedURLTest.java b/Java/RelativeExtendedURLTest.java new file mode 100644 index 0000000000000000000000000000000000000000..603d496d4c03a10af0304e646e689f659e0024cc --- /dev/null +++ b/Java/RelativeExtendedURLTest.java @@ -0,0 +1,46 @@ +/* + * 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. + */ +// BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect') +// package org.xwiki.url; +// FIXED: +package org.xwiki.url.internal; + +import java.util.Arrays; + +import org.junit.jupiter.api.Test; +import org.xwiki.url.internal.RelativeExtendedURL; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Unit tests for {@link RelativeExtendedURL}. + * + * @version $Id$ + * @since 7.2M1 + */ +class RelativeExtendedURLTest +{ + @Test + void serialize() + { + RelativeExtendedURL url = new RelativeExtendedURL(Arrays.asList("a", "b")); + assertEquals("a/b", url.serialize()); + } +} diff --git a/Java/ReminderRulesXStream.java b/Java/ReminderRulesXStream.java new file mode 100644 index 0000000000000000000000000000000000000000..c058e5919dff2188d95ace60b479f43fc955c51c --- /dev/null +++ b/Java/ReminderRulesXStream.java @@ -0,0 +1,68 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.modules.reminder.manager; + +import java.io.InputStream; +import java.io.OutputStream; + +import org.olat.core.util.xml.XStreamHelper; +import org.olat.modules.reminder.model.ImportExportReminders; +import org.olat.modules.reminder.model.ReminderRules; + +import com.thoughtworks.xstream.XStream; + +/** + * + * Initial date: 25 mars 2019
+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com + * + */ +public class ReminderRulesXStream { + + private static final XStream ruleXStream = XStreamHelper.createXStreamInstance(); + static { + XStreamHelper.allowDefaultPackage(ruleXStream); + ruleXStream.alias("rule", org.olat.modules.reminder.model.ReminderRuleImpl.class); + ruleXStream.alias("rules", org.olat.modules.reminder.model.ReminderRules.class); + ruleXStream.alias("reminders", org.olat.modules.reminder.model.ImportExportReminders.class); + ruleXStream.alias("reminder", org.olat.modules.reminder.model.ImportExportReminder.class); + } + + public static ReminderRules toRules(String rulesXml) { + return (ReminderRules)ruleXStream.fromXML(rulesXml); + } + + public static ReminderRules toRules(InputStream in) { + return (ReminderRules)ruleXStream.fromXML(in); + } + + public static String toXML(ReminderRules rules) { + return ruleXStream.toXML(rules); + } + + public static void toXML(ImportExportReminders reminders, OutputStream out) { + ruleXStream.toXML(reminders, out); + } + + public static ImportExportReminders fromXML(InputStream in) { + return (ImportExportReminders)ruleXStream.fromXML(in); + } + +} diff --git a/Java/RemotingDiagnostics.java b/Java/RemotingDiagnostics.java new file mode 100644 index 0000000000000000000000000000000000000000..f77f0dc9106742b06315c33599569ea0c05a3247 --- /dev/null +++ b/Java/RemotingDiagnostics.java @@ -0,0 +1,223 @@ +/* + * The MIT License + * + * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package hudson.util; + +import groovy.lang.Binding; +import groovy.lang.GroovyShell; +import hudson.FilePath; +import hudson.Functions; +import jenkins.model.Jenkins; +import hudson.remoting.AsyncFutureImpl; +import hudson.remoting.Callable; +import hudson.remoting.DelegatingCallable; +import hudson.remoting.Future; +import hudson.remoting.VirtualChannel; +import hudson.security.AccessControlled; +import org.codehaus.groovy.control.CompilerConfiguration; +import org.codehaus.groovy.control.customizers.ImportCustomizer; +import org.kohsuke.stapler.StaplerRequest; +import org.kohsuke.stapler.StaplerResponse; +import org.kohsuke.stapler.WebMethod; + +import javax.management.JMException; +import javax.management.MBeanServer; +import javax.management.ObjectName; +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadInfo; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.TreeMap; + +/** + * Various remoting operations related to diagnostics. + * + *

+ * These code are useful wherever {@link VirtualChannel} is used, such as master, slaves, Maven JVMs, etc. + * + * @author Kohsuke Kawaguchi + * @since 1.175 + */ +public final class RemotingDiagnostics { + public static Map getSystemProperties(VirtualChannel channel) throws IOException, InterruptedException { + if(channel==null) + return Collections.singletonMap("N/A","N/A"); + return channel.call(new GetSystemProperties()); + } + + private static final class GetSystemProperties implements Callable,RuntimeException> { + public Map call() { + return new TreeMap(System.getProperties()); + } + private static final long serialVersionUID = 1L; + } + + public static Map getThreadDump(VirtualChannel channel) throws IOException, InterruptedException { + if(channel==null) + return Collections.singletonMap("N/A","N/A"); + return channel.call(new GetThreadDump()); + } + + public static Future> getThreadDumpAsync(VirtualChannel channel) throws IOException, InterruptedException { + if(channel==null) + return new AsyncFutureImpl>(Collections.singletonMap("N/A","offline")); + return channel.callAsync(new GetThreadDump()); + } + + private static final class GetThreadDump implements Callable,RuntimeException> { + public Map call() { + Map r = new LinkedHashMap(); + try { + ThreadInfo[] data = Functions.getThreadInfos(); + Functions.ThreadGroupMap map = Functions.sortThreadsAndGetGroupMap(data); + for (ThreadInfo ti : data) + r.put(ti.getThreadName(),Functions.dumpThreadInfo(ti,map)); + } catch (LinkageError _) { + // not in JDK6. fall back to JDK5 + r.clear(); + for (Map.Entry t : Functions.dumpAllThreads().entrySet()) { + StringBuilder buf = new StringBuilder(); + for (StackTraceElement e : t.getValue()) + buf.append(e).append('\n'); + r.put(t.getKey().getName(),buf.toString()); + } + } + return r; + } + private static final long serialVersionUID = 1L; + } + + /** + * Executes Groovy script remotely. + */ + public static String executeGroovy(String script, VirtualChannel channel) throws IOException, InterruptedException { + return channel.call(new Script(script)); + } + + private static final class Script implements DelegatingCallable { + private final String script; + private transient ClassLoader cl; + + private Script(String script) { + this.script = script; + cl = getClassLoader(); + } + + public ClassLoader getClassLoader() { + return Jenkins.getInstance().getPluginManager().uberClassLoader; + } + + public String call() throws RuntimeException { + // if we run locally, cl!=null. Otherwise the delegating classloader will be available as context classloader. + if (cl==null) cl = Thread.currentThread().getContextClassLoader(); + CompilerConfiguration cc = new CompilerConfiguration(); + cc.addCompilationCustomizers(new ImportCustomizer().addStarImports( + "jenkins", + "jenkins.model", + "hudson", + "hudson.model")); + GroovyShell shell = new GroovyShell(cl,new Binding(),cc); + + StringWriter out = new StringWriter(); + PrintWriter pw = new PrintWriter(out); + shell.setVariable("out", pw); + try { + Object output = shell.evaluate(script); + if(output!=null) + pw.println("Result: "+output); + } catch (Throwable t) { + t.printStackTrace(pw); + } + return out.toString(); + } + } + + /** + * Obtains the heap dump in an HPROF file. + */ + public static FilePath getHeapDump(VirtualChannel channel) throws IOException, InterruptedException { + return channel.call(new Callable() { + public FilePath call() throws IOException { + final File hprof = File.createTempFile("hudson-heapdump", "hprof"); + hprof.delete(); + try { + MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + server.invoke(new ObjectName("com.sun.management:type=HotSpotDiagnostic"), "dumpHeap", + new Object[]{hprof.getAbsolutePath(), true}, new String[]{String.class.getName(), boolean.class.getName()}); + + return new FilePath(hprof); + } catch (JMException e) { + throw new IOException2(e); + } + } + + private static final long serialVersionUID = 1L; + }); + } + + /** + * Heap dump, exposable to URL via Stapler. + * + */ + public static class HeapDump { + private final AccessControlled owner; + private final VirtualChannel channel; + + public HeapDump(AccessControlled owner, VirtualChannel channel) { + this.owner = owner; + this.channel = channel; + } + + /** + * Obtains the heap dump. + */ + public void doIndex(StaplerResponse rsp) throws IOException { + rsp.sendRedirect("heapdump.hprof"); + } + + @WebMethod(name="heapdump.hprof") + public void doHeapDump(StaplerRequest req, StaplerResponse rsp) throws IOException, InterruptedException { + // BUG: CWE-264 Permissions, Privileges, and Access Controls + // owner.checkPermission(Jenkins.ADMINISTER); + // FIXED: + owner.checkPermission(Jenkins.RUN_SCRIPTS); + rsp.setContentType("application/octet-stream"); + + FilePath dump = obtain(); + try { + dump.copyTo(rsp.getCompressedOutputStream(req)); + } finally { + dump.delete(); + } + } + + public FilePath obtain() throws IOException, InterruptedException { + return RemotingDiagnostics.getHeapDump(channel); + } + } +} diff --git a/Java/RepositoryEntryImportExport.java b/Java/RepositoryEntryImportExport.java new file mode 100644 index 0000000000000000000000000000000000000000..2b6febf3ad9532656159bc7c09bcec9c57bcc3ca --- /dev/null +++ b/Java/RepositoryEntryImportExport.java @@ -0,0 +1,665 @@ +/** +* OLAT - Online Learning and Training
+* http://www.olat.org +*

+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at +*

+* http://www.apache.org/licenses/LICENSE-2.0 +*

+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License. +*

+* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),
+* University of Zurich, Switzerland. +*


+* +* OpenOLAT - Online Learning and Training
+* This file has been modified by the OpenOLAT community. Changes are licensed +* under the Apache 2.0 license as the original file. +*/ + +package org.olat.repository; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.io.IOUtils; +import org.apache.logging.log4j.Logger; +import org.olat.core.CoreSpringFactory; +import org.olat.core.commons.services.license.LicenseService; +import org.olat.core.commons.services.license.LicenseType; +import org.olat.core.commons.services.license.ResourceLicense; +import org.olat.core.commons.services.license.ui.LicenseUIFactory; +import org.olat.core.gui.media.MediaResource; +import org.olat.core.logging.OLATRuntimeException; +import org.olat.core.logging.Tracing; +import org.olat.core.util.FileUtils; +import org.olat.core.util.StringHelper; +import org.olat.core.util.ZipUtil; +import org.olat.core.util.io.HttpServletResponseOutputStream; +import org.olat.core.util.io.ShieldOutputStream; +import org.olat.core.util.vfs.LocalFileImpl; +import org.olat.core.util.vfs.VFSContainer; +import org.olat.core.util.vfs.VFSLeaf; +import org.olat.core.util.vfs.VFSManager; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.repository.handlers.RepositoryHandler; +import org.olat.repository.handlers.RepositoryHandlerFactory; + +import com.thoughtworks.xstream.XStream; + +/** + * Initial Date: 19.05.2005 + * + * @author Mike Stock + * + * Comment: + * + */ +public class RepositoryEntryImportExport { + + private static final Logger log = Tracing.createLoggerFor(RepositoryEntryImportExport.class); + + private static final String CONTENT_FILE = "repo.zip"; + public static final String PROPERTIES_FILE = "repo.xml"; + private static final String PROP_ROOT = "RepositoryEntryProperties"; + private static final String PROP_SOFTKEY = "Softkey"; + private static final String PROP_RESOURCENAME = "ResourceName"; + private static final String PROP_DISPLAYNAME = "DisplayName"; + private static final String PROP_DECRIPTION = "Description"; + private static final String PROP_INITIALAUTHOR = "InitialAuthor"; + + private static final XStream xstream = XStreamHelper.createXStreamInstance(); + static { + XStreamHelper.allowDefaultPackage(xstream); + xstream.alias(PROP_ROOT, RepositoryEntryImport.class); + xstream.aliasField(PROP_SOFTKEY, RepositoryEntryImport.class, "softkey"); + xstream.aliasField(PROP_RESOURCENAME, RepositoryEntryImport.class, "resourcename"); + xstream.aliasField(PROP_DISPLAYNAME, RepositoryEntryImport.class, "displayname"); + xstream.aliasField(PROP_DECRIPTION, RepositoryEntryImport.class, "description"); + xstream.aliasField(PROP_INITIALAUTHOR, RepositoryEntryImport.class, "initialAuthor"); + xstream.omitField(RepositoryEntryImport.class, "outer-class"); + xstream.ignoreUnknownElements(); + } + + + private boolean propertiesLoaded = false; + + private RepositoryEntry re; + private File baseDirectory; + private RepositoryEntryImport repositoryProperties; + + /** + * Create a RepositoryEntryImportExport instance to do an export. + * + * @param re + * @param baseDirecotry + */ + public RepositoryEntryImportExport(RepositoryEntry re, File baseDirecotry) { + this.re = re; + this.baseDirectory = baseDirecotry; + } + + /** + * Create a RepositoryEntryImportExport instance to do an import. + * + * @param baseDirecotry + */ + public RepositoryEntryImportExport(File baseDirectory) { + this.baseDirectory = baseDirectory; + } + + public RepositoryEntryImportExport(File baseDirectory, String subDir) { + this.baseDirectory = new File(baseDirectory, subDir); + } + + public boolean anyExportedPropertiesAvailable() { + return new File(baseDirectory, PROPERTIES_FILE).exists(); + } + + /** + * Export repository entry (contents and metadata. + * + * @return True upon success, false otherwise. + */ + public boolean exportDoExport() { + exportDoExportProperties(); + return exportDoExportContent(); + } + + public boolean exportDoExport(String zipPath, ZipOutputStream zout) { + exportDoExportProperties(zipPath, zout); + return exportDoExportContent(zipPath, zout); + } + + public void exportDoExportProperties(String zipPath, ZipOutputStream zout) { + // save repository entry properties + RepositoryEntryImport imp = new RepositoryEntryImport(re); + RepositoryManager rm = RepositoryManager.getInstance(); + VFSLeaf image = rm.getImage(re); + if(image instanceof LocalFileImpl) { + imp.setImageName(image.getName()); + ZipUtil.addFileToZip(ZipUtil.concat(zipPath, image.getName()) , ((LocalFileImpl)image).getBasefile(), zout); + } + + RepositoryService repositoryService = CoreSpringFactory.getImpl(RepositoryService.class); + VFSLeaf movie = repositoryService.getIntroductionMovie(re); + if(movie instanceof LocalFileImpl) { + imp.setMovieName(movie.getName()); + ZipUtil.addFileToZip(ZipUtil.concat(zipPath, movie.getName()), ((LocalFileImpl)movie).getBasefile(), zout); + } + + try(ShieldOutputStream fOut = new ShieldOutputStream(zout)) { + addLicenseInformations(imp, re); + zout.putNextEntry(new ZipEntry(ZipUtil.concat(zipPath, PROPERTIES_FILE))); + xstream.toXML(imp, fOut); + zout.closeEntry(); + } catch (IOException ioe) { + throw new OLATRuntimeException("Error writing repo properties.", ioe); + } + } + + /** + * Export metadata of a repository entry to a file. + * Only one repository entry's metadata may be exported into a directory. The + * file name of the properties file will be the same for all repository entries! + */ + public void exportDoExportProperties() { + // save repository entry properties + try(FileOutputStream fOut = new FileOutputStream(new File(baseDirectory, PROPERTIES_FILE))) { + RepositoryEntryImport imp = new RepositoryEntryImport(re); + RepositoryManager rm = RepositoryManager.getInstance(); + VFSLeaf image = rm.getImage(re); + if(image instanceof LocalFileImpl) { + imp.setImageName(image.getName()); + FileUtils.copyFileToDir(((LocalFileImpl)image).getBasefile(), baseDirectory, ""); + + } + + RepositoryService repositoryService = CoreSpringFactory.getImpl(RepositoryService.class); + VFSLeaf movie = repositoryService.getIntroductionMovie(re); + if(movie instanceof LocalFileImpl) { + imp.setMovieName(movie.getName()); + FileUtils.copyFileToDir(((LocalFileImpl)movie).getBasefile(), baseDirectory, ""); + } + + addLicenseInformations(imp, re); + + xstream.toXML(imp, fOut); + } catch (IOException ioe) { + throw new OLATRuntimeException("Error writing repo properties.", ioe); + } + } + + private void addLicenseInformations(RepositoryEntryImport imp, RepositoryEntry entry) { + LicenseService licenseService = CoreSpringFactory.getImpl(LicenseService.class); + ResourceLicense license = licenseService.loadLicense(entry.getOlatResource()); + if (license != null) { + imp.setLicenseTypeKey(String.valueOf(license.getLicenseType().getKey())); + imp.setLicenseTypeName(license.getLicenseType().getName()); + imp.setLicensor(license.getLicensor()); + imp.setLicenseText(LicenseUIFactory.getLicenseText(license)); + } + } + + /** + * Export a repository entry referenced by a course node to the given export directory. + * User importReferencedRepositoryEntry to import again. + * @return True upon success, false otherwise. + * + */ + public boolean exportDoExportContent() { + // export resource + RepositoryHandler rh = RepositoryHandlerFactory.getInstance().getRepositoryHandler(re); + MediaResource mr = rh.getAsMediaResource(re.getOlatResource()); + try(FileOutputStream fOut = new FileOutputStream(new File(baseDirectory, CONTENT_FILE)); + InputStream in = mr.getInputStream()) { + if(in == null) { + HttpServletResponse hres = new HttpServletResponseOutputStream(fOut); + mr.prepare(hres); + } else { + IOUtils.copy(in, fOut); + } + fOut.flush(); + } catch (IOException fnfe) { + return false; + } finally { + mr.release(); + } + return true; + } + + public boolean exportDoExportContent(String zipPath, ZipOutputStream zout) { + // export resource + RepositoryHandler rh = RepositoryHandlerFactory.getInstance().getRepositoryHandler(re); + MediaResource mr = rh.getAsMediaResource(re.getOlatResource()); + try(OutputStream fOut = new ShieldOutputStream(zout); + InputStream in = mr.getInputStream()) { + zout.putNextEntry(new ZipEntry(ZipUtil.concat(zipPath, CONTENT_FILE))); + if(in == null) { + HttpServletResponse hres = new HttpServletResponseOutputStream(fOut); + mr.prepare(hres); + } else { + IOUtils.copy(in, fOut); + } + fOut.flush(); + zout.closeEntry(); + } catch (IOException fnfe) { + return false; + } finally { + mr.release(); + } + return true; + } + + public RepositoryEntry importContent(RepositoryEntry newEntry, VFSContainer mediaContainer) { + if(!anyExportedPropertiesAvailable()) return newEntry; + + RepositoryManager repositoryManager = CoreSpringFactory.getImpl(RepositoryManager.class); + if(StringHelper.containsNonWhitespace(getImageName())) { + File newFile = new File(baseDirectory, getImageName()); + VFSLeaf newImage = new LocalFileImpl(newFile); + repositoryManager.setImage(newImage, newEntry); + } + if(StringHelper.containsNonWhitespace(getMovieName())) { + String movieName = getMovieName(); + String extension = FileUtils.getFileSuffix(movieName); + File newFile = new File(baseDirectory, movieName); + try(InputStream inStream = new FileInputStream(newFile)) { + VFSLeaf movieLeaf = mediaContainer.createChildLeaf(newEntry.getKey() + "." + extension); + VFSManager.copyContent(inStream, movieLeaf); + } catch(IOException e) { + log.error("", e); + } + } + + return setRepoEntryPropertiesFromImport(newEntry); + } + + /** + * Update the repo entry property from the current import information in the database + * + * @param newEntry + * @return + */ + public RepositoryEntry setRepoEntryPropertiesFromImport(RepositoryEntry newEntry) { + if(!propertiesLoaded) { + loadConfiguration(); + } + + importLicense(newEntry); + + RepositoryManager repositoryManager = CoreSpringFactory.getImpl(RepositoryManager.class); + return repositoryManager.setDescriptionAndName(newEntry, newEntry.getDisplayname(), null, + repositoryProperties.getAuthors(), repositoryProperties.getDescription(), + repositoryProperties.getObjectives(), repositoryProperties.getRequirements(), + repositoryProperties.getCredits(), repositoryProperties.getMainLanguage(), + repositoryProperties.getLocation(), repositoryProperties.getExpenditureOfWork(), null, null, null); + } + + private void importLicense(RepositoryEntry newEntry) { + if(!propertiesLoaded) { + loadConfiguration(); + } + LicenseService licenseService = CoreSpringFactory.getImpl(LicenseService.class); + boolean hasLicense = StringHelper.containsNonWhitespace(repositoryProperties.getLicenseTypeName()); + if (hasLicense) { + String licenseTypeName = repositoryProperties.getLicenseTypeName(); + LicenseType licenseType = licenseService.loadLicenseTypeByName(licenseTypeName); + if (licenseType == null) { + licenseType = licenseService.createLicenseType(licenseTypeName); + licenseType.setText(repositoryProperties.getLicenseText()); + licenseService.saveLicenseType(licenseType); + } + ResourceLicense license = licenseService.loadOrCreateLicense(newEntry.getOlatResource()); + license.setLicenseType(licenseType); + license.setLicensor(repositoryProperties.getLicensor()); + if (licenseService.isFreetext(licenseType)) { + license.setFreetext(repositoryProperties.getLicenseText()); + } + licenseService.update(license); + } + } + + /** + * Returns the exported repository file. + * + * @return exported repository file + */ + public File importGetExportedFile() { + return new File(baseDirectory, CONTENT_FILE); + } + + /** + * Read previousely exported Propertiesproperties + */ + private void loadConfiguration() { + if(baseDirectory != null && baseDirectory.exists()) { + if(baseDirectory.getName().endsWith(".zip")) { + try(FileSystem fs = FileSystems.newFileSystem(baseDirectory.toPath(), null)) { + Path fPath = fs.getPath("/"); + Path manifestPath = fPath.resolve("export").resolve(PROPERTIES_FILE); + repositoryProperties = (RepositoryEntryImport)XStreamHelper.readObject(xstream, manifestPath); + } catch(Exception e) { + log.error("", e); + } + } else { + File inputFile = new File(baseDirectory, PROPERTIES_FILE); + if(inputFile.exists()) { + repositoryProperties = (RepositoryEntryImport)XStreamHelper.readObject(xstream, inputFile); + } else { + repositoryProperties = new RepositoryEntryImport(); + } + } + } else { + repositoryProperties = new RepositoryEntryImport(); + } + propertiesLoaded = true; + } + + /** + * Get the repo entry import metadata from the given path. E.g. usefull + * when reading from an unzipped archive. + * + * @param repoXmlPath + * @return The RepositoryEntryImport or NULL + */ + public static RepositoryEntryImport getConfiguration(Path repoXmlPath) { + try (InputStream in=Files.newInputStream(repoXmlPath)) { + return (RepositoryEntryImport)xstream.fromXML(in); + } catch(IOException e) { + log.error("", e); + return null; + } + } + + /** + * Get the repo entry import metadata from the given stream. E.g. usefull + * when reading from an ZIP file without inflating it. + * + * @param repoMetaFileInputStream + * @return The RepositoryEntryImport or NULL + */ + public static RepositoryEntryImport getConfiguration(InputStream repoMetaFileInputStream) { + return (RepositoryEntryImport)xstream.fromXML(repoMetaFileInputStream); + } + + /** + * @return The softkey + */ + public String getSoftkey() { + if(!propertiesLoaded) { + loadConfiguration(); + } + return repositoryProperties.getSoftkey(); + } + + /** + * @return The display name + */ + public String getDisplayName() { + if(!propertiesLoaded) { + loadConfiguration(); + } + return repositoryProperties.getDisplayname(); + } + + /** + * @return the resource name + */ + public String getResourceName() { + if(!propertiesLoaded) { + loadConfiguration(); + } + return repositoryProperties.getResourcename(); + } + + /** + * @return the descritpion + */ + public String getDescription() { + if(!propertiesLoaded) { + loadConfiguration(); + } + return repositoryProperties.getDescription(); + } + + /** + * @return the initial author + */ + public String getInitialAuthor() { + if(!propertiesLoaded) { + loadConfiguration(); + } + return repositoryProperties.getInitialAuthor(); + } + + public String getMovieName() { + if(!propertiesLoaded) { + loadConfiguration(); + } + return repositoryProperties.getMovieName(); + } + + public String getImageName() { + if(!propertiesLoaded) { + loadConfiguration(); + } + return repositoryProperties.getImageName(); + } + + public class RepositoryEntryImport { + + private Long key; + private String softkey; + private String resourcename; + private String displayname; + private String description; + private String initialAuthor; + + private String authors; + private String mainLanguage; + private String objectives; + private String requirements; + private String credits; + private String expenditureOfWork; + private String location; + + private String movieName; + private String imageName; + + private String licenseTypeKey; + private String licenseTypeName; + private String licensor; + private String licenseText; + + public RepositoryEntryImport() { + // + } + + public RepositoryEntryImport(RepositoryEntry re) { + key = re.getKey(); + softkey = re.getSoftkey(); + resourcename = re.getResourcename(); + displayname = re.getDisplayname(); + description = re.getDescription(); + initialAuthor = re.getInitialAuthor(); + + authors = re.getAuthors(); + mainLanguage = re.getMainLanguage(); + objectives = re.getObjectives(); + requirements = re.getRequirements(); + credits = re.getCredits(); + expenditureOfWork = re.getExpenditureOfWork(); + } + + public Long getKey() { + return key; + } + + public void setKey(Long key) { + this.key = key; + } + + public String getMovieName() { + return movieName; + } + + public void setMovieName(String movieName) { + this.movieName = movieName; + } + + public String getImageName() { + return imageName; + } + + public void setImageName(String imageName) { + this.imageName = imageName; + } + + public String getSoftkey() { + return softkey; + } + + public void setSoftkey(String softkey) { + this.softkey = softkey; + } + + public String getResourcename() { + return resourcename; + } + + public void setResourcename(String resourcename) { + this.resourcename = resourcename; + } + + public String getDisplayname() { + return displayname; + } + + public void setDisplayname(String displayname) { + this.displayname = displayname; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getInitialAuthor() { + return initialAuthor; + } + + public void setInitialAuthor(String initialAuthor) { + this.initialAuthor = initialAuthor; + } + + public String getAuthors() { + return authors; + } + + public void setAuthors(String authors) { + this.authors = authors; + } + + public String getMainLanguage() { + return mainLanguage; + } + + public void setMainLanguage(String mainLanguage) { + this.mainLanguage = mainLanguage; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getObjectives() { + return objectives; + } + + public void setObjectives(String objectives) { + this.objectives = objectives; + } + + public String getRequirements() { + return requirements; + } + + public void setRequirements(String requirements) { + this.requirements = requirements; + } + + public String getCredits() { + return credits; + } + + public void setCredits(String credits) { + this.credits = credits; + } + + public String getExpenditureOfWork() { + return expenditureOfWork; + } + + public void setExpenditureOfWork(String expenditureOfWork) { + this.expenditureOfWork = expenditureOfWork; + } + + public String getLicenseTypeKey() { + return licenseTypeKey; + } + + public void setLicenseTypeKey(String licenseTypeKey) { + this.licenseTypeKey = licenseTypeKey; + } + + public String getLicenseTypeName() { + return licenseTypeName; + } + + public void setLicenseTypeName(String licenseTypeName) { + this.licenseTypeName = licenseTypeName; + } + + public String getLicensor() { + return licensor; + } + + public void setLicensor(String licensor) { + this.licensor = licensor; + } + + public String getLicenseText() { + return licenseText; + } + + public void setLicenseText(String licenseText) { + this.licenseText = licenseText; + } + } +} \ No newline at end of file diff --git a/Java/ResourceManager.java b/Java/ResourceManager.java new file mode 100644 index 0000000000000000000000000000000000000000..f5cfc535bae6bcc9c2505a5f38789d23a0c43d9e --- /dev/null +++ b/Java/ResourceManager.java @@ -0,0 +1,699 @@ +/* + * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package com.sun.faces.application.resource; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; +import java.util.stream.Stream; + +import javax.faces.application.ProjectStage; +import javax.faces.application.ResourceHandler; +import javax.faces.application.ResourceVisitOption; +import javax.faces.component.UIViewRoot; +import javax.faces.context.FacesContext; + +import com.sun.faces.config.WebConfiguration; +import com.sun.faces.util.FacesLogger; +import com.sun.faces.util.Util; + +/** + * This class is used to lookup {@link ResourceInfo} instances + * and cache any that are successfully looked up to reduce the + * computational overhead with the scanning/version checking. + * + * @since 2.0 + */ +public class ResourceManager { + + private static final Logger LOGGER = FacesLogger.RESOURCE.getLogger(); + + /** + * {@link Pattern} for valid mime types to configure compression. + */ + private static final Pattern CONFIG_MIMETYPE_PATTERN = Pattern.compile("[a-z-]*/[a-z0-9.\\*-]*"); + + private FaceletWebappResourceHelper faceletWebappResourceHelper = new FaceletWebappResourceHelper(); + + /** + * {@link ResourceHelper} used for looking up webapp-based resources. + */ + private ResourceHelper webappResourceHelper = new WebappResourceHelper(); + + /** + * {@link ResourceHelper} used for looking up classpath-based resources. + */ + private ClasspathResourceHelper classpathResourceHelper = new ClasspathResourceHelper(); + + /** + * Cache for storing {@link ResourceInfo} instances to reduce the cost + * of the resource lookups. + */ + private ResourceCache cache; + + /** + * Patterns used to find {@link ResourceInfo} instances that may have their + * content compressed. + */ + private List compressableTypes; + + /** + * This lock is used to ensure the lookup of compressable {@link ResourceInfo} + * instances are atomic to prevent theading issues when writing the compressed + * content during a lookup. + */ + private ReentrantLock lock = new ReentrantLock(); + + + // ------------------------------------------------------------ Constructors + + /* + * This ctor is only ever called by test code. + */ + + public ResourceManager(ResourceCache cache) { + this.cache = cache; + Map throwAwayMap = new HashMap<>(); + initCompressableTypes(throwAwayMap); + } + + /** + * Constructs a new ResourceManager. Note: if the current + * {@link ProjectStage} is {@link ProjectStage#Development} caching or + * {@link ResourceInfo} instances will not occur. + */ + public ResourceManager(Map appMap, ResourceCache cache) { + this.cache = cache; + initCompressableTypes(appMap); + } + + + // ------------------------------------------------------ Public Methods + + + /** + *

+ * Attempt to lookup a {@link ResourceInfo} based on the specified + * libraryName and resourceName + *

+ * + *

+ * Implementation Note: Synchronization is necessary when looking up + * compressed resources. This ensures the atomicity of the content + * being compressed. As such, the cost of doing this is low as once + * the resource is in the cache, the lookup won't be performed again + * until the cache is cleared. That said, it's not a good idea + * to have caching disabled in a production environment if leveraging + * compression. + * + * If the resource isn't compressable, then we don't worry about creating + * a few extra copies of ResourceInfo until the cache is populated. + *

+ * + * @param libraryName the name of the library (if any) + * @param resourceName the name of the resource + * @param contentType the content type of the resource. This will be + * used to determine if the resource is compressable + * @param ctx the {@link javax.faces.context.FacesContext} for the current + * request + * + * @return a {@link ResourceInfo} if a resource if found matching the + * provided arguments, otherwise, return null + */ + public ResourceInfo findResource(String libraryName, String resourceName, String contentType, FacesContext ctx) { + return findResource(libraryName, resourceName, contentType, false, ctx); + } + + public ResourceInfo findViewResource(String resourceName, String contentType, FacesContext facesContext) { + String localePrefix = getLocalePrefix(facesContext); + List contracts = getResourceLibraryContracts(facesContext); + + ResourceInfo info = getFromCache(resourceName, null, localePrefix, contracts); + + if (info == null) { + if (isCompressable(contentType, facesContext)) { + info = findResourceCompressed(null, resourceName, true, localePrefix, contracts, facesContext); + } else { + info = findResourceNonCompressed(null, resourceName, true, localePrefix, contracts, facesContext); + } + } + + return info; + } + + public ResourceInfo findResource(String libraryName, String resourceName, String contentType, boolean isViewResource, FacesContext ctx) { + + String localePrefix = getLocalePrefix(ctx); + List contracts = getResourceLibraryContracts(ctx); + + ResourceInfo info = getFromCache(resourceName, libraryName, localePrefix, contracts); + + if (info == null) { + if (isCompressable(contentType, ctx)) { + info = findResourceCompressed(libraryName, resourceName, isViewResource, localePrefix, contracts, ctx); + } else { + info = findResourceNonCompressed(libraryName, resourceName, isViewResource, localePrefix, contracts, ctx); + } + } + + return info; + } + + public Stream getViewResources(FacesContext facesContext, String path, int maxDepth, ResourceVisitOption... options) { + return faceletWebappResourceHelper.getViewResources(facesContext, path, maxDepth, options); + } + + + // ----------------------------------------------------- Private Methods + + private ResourceInfo findResourceCompressed(String libraryName, String resourceName, boolean isViewResource, String localePrefix, List contracts, FacesContext ctx) { + + ResourceInfo info = null; + + lock.lock(); + try { + info = getFromCache(resourceName, libraryName, localePrefix, contracts); + if (info == null) { + info = doLookup(libraryName, resourceName, localePrefix, true, isViewResource, contracts, ctx); + if (info != null) { + addToCache(info, contracts); + } + } + } finally { + lock.unlock(); + } + + return info; + } + + private ResourceInfo findResourceNonCompressed(String libraryName, String resourceName, boolean isViewResource, String localePrefix, List contracts, FacesContext ctx) { + ResourceInfo info = doLookup(libraryName, resourceName, localePrefix, false, isViewResource, contracts, ctx); + + if (info == null && contracts != null) { + info = doLookup(libraryNameFromContracts(libraryName, contracts), resourceName, localePrefix, false, isViewResource, contracts, ctx); + } + + if (info != null && !info.isDoNotCache()) { + addToCache(info, contracts); + } + + return info; + } + + private String libraryNameFromContracts(String libraryName, List contracts) { + // If the library name is equal to one of the contracts, + // assume the resource to be found is within that contract + for (String contract : contracts) { + if (contract.equals(libraryName)) { + return null; + } + } + + return libraryName; + } + + + /** + * Attempt to look up the Resource based on the provided details. + * + * @param libraryName the name of the library (if any) + * @param resourceName the name of the resource + * @param localePrefix the locale prefix for this resource (if any) + * @param compressable if this resource can be compressed + * @param isViewResource + * @param contracts the contracts to consider + * @param ctx the {@link javax.faces.context.FacesContext} for the current + * request + * + * @return a {@link ResourceInfo} if a resource if found matching the + * provided arguments, otherwise, return null + */ + private ResourceInfo doLookup(String libraryName, String resourceName, String localePrefix, boolean compressable, boolean isViewResource, List contracts, FacesContext ctx) { + + // Loop over the contracts as described in deriveResourceIdConsideringLocalePrefixAndContracts in the spec + for (String contract : contracts) { + ResourceInfo info = getResourceInfo(libraryName, resourceName, localePrefix, contract, compressable, isViewResource, ctx, null); + if (info != null) { + return info; + } + } + + return getResourceInfo(libraryName, resourceName, localePrefix, null, compressable, isViewResource, ctx, null); + } + + private ResourceInfo getResourceInfo(String libraryName, String resourceName, String localePrefix, String contract, boolean compressable, boolean isViewResource, FacesContext ctx, LibraryInfo library) { + if (libraryName != null && !nameContainsForbiddenSequence(libraryName)) { + library = findLibrary(libraryName, localePrefix, contract, ctx); + + if (library == null && localePrefix != null) { + // no localized library found. Try to find a library that isn't localized. + library = findLibrary(libraryName, null, contract, ctx); + } + + if (library == null) { + // If we don't have one by now, perhaps it's time to consider scanning directories. + library = findLibraryOnClasspathWithZipDirectoryEntryScan(libraryName, localePrefix, contract, ctx, false); + + if (library == null && localePrefix != null) { + // no localized library found. Try to find + // a library that isn't localized. + library = findLibraryOnClasspathWithZipDirectoryEntryScan(libraryName, null, contract, ctx, false); + } + + if (library == null) { + return null; + } + } + } else if (nameContainsForbiddenSequence(libraryName)) { + return null; + } + + String resName = trimLeadingSlash(resourceName); + if (nameContainsForbiddenSequence(resName) || (!isViewResource && resName.startsWith("WEB-INF"))) { + return null; + } + + ResourceInfo info = findResource(library, resourceName, localePrefix, compressable, isViewResource, ctx); + if (info == null && localePrefix != null) { + // no localized resource found, try to find a + // resource that isn't localized + info = findResource(library, resourceName, null, compressable, isViewResource, ctx); + } + + // If no resource has been found so far, and we have a library that + // was found in the webapp filesystem, see if there is a matching + // library on the classpath. If one is found, try to find a matching + // resource in that library. + if (info == null && library != null && library.getHelper() instanceof WebappResourceHelper) { + LibraryInfo altLibrary = classpathResourceHelper.findLibrary(libraryName, localePrefix, contract, ctx); + if (altLibrary != null) { + VersionInfo originalVersion = library.getVersion(); + VersionInfo altVersion = altLibrary.getVersion(); + if (originalVersion == null && altVersion == null) { + library = altLibrary; + } else if (originalVersion == null && altVersion != null) { + library = null; + } else if (originalVersion != null && altVersion == null) { + library = null; + } else if (originalVersion.compareTo(altVersion) == 0) { + library = altLibrary; + } + + } + + if (library != null) { + info = findResource(library, resourceName, localePrefix, compressable, isViewResource, ctx); + if (info == null && localePrefix != null) { + // no localized resource found, try to find a + // resource that isn't localized + info = findResource(library, resourceName, null, compressable, isViewResource, ctx); + } + } + } + + return info; + } + + /** + * @param s input String + * @return the String without a leading slash if it has one. + */ + private String trimLeadingSlash(String s) { + if (s.charAt(0) == '/') { + return s.substring(1); + } else { + return s; + } + } + + private static boolean nameContainsForbiddenSequence(String name) { + boolean result = false; + if (name != null) { + name = name.toLowerCase(); + + result = name.startsWith(".") || + name.contains("../") || + name.contains("..\\") || + name.startsWith("/") || + name.startsWith("\\") || + name.endsWith("/") || + + name.contains("..%2f") || + name.contains("..%5c") || + name.startsWith("%2f") || + name.startsWith("%5c") || + name.endsWith("%2f") || + + name.contains("..\\u002f") || + name.contains("..\\u005c") || + name.startsWith("\\u002f") || + name.startsWith("\\u005c") || + name.endsWith("\\u002f") + + ; + } + + return result; + } + + + /** + * + * @param name the resource name + * @param library the library name + * @param localePrefix the Locale prefix + * @param contracts + * @return the {@link ResourceInfo} from the cache or null + * if no cached entry is found + */ + private ResourceInfo getFromCache(String name, String library, String localePrefix, List contracts) { + if (cache == null) { + return null; + } + + return cache.get(name, library, localePrefix, contracts); + } + + + /** + * Adds the the specified {@link ResourceInfo} to the cache. + * @param info the @{link ResourceInfo} to add. + * @param contracts the contracts + */ + private void addToCache(ResourceInfo info, List contracts) { + if (cache == null) { + return; + } + + cache.add(info, contracts); + } + + /** + *

Attempt to lookup and return a {@link LibraryInfo} based on the + * specified arguments. + *

+ *

The lookup process will first search the file system of the web + * application *within the resources directory*. + * If the library is not found, then it processed to + * searching the classpath, if not found there, search from the webapp root + * *excluding* the resources directory.

+ *

+ *

If a library is found, this method will return a {@link + * LibraryInfo} instance that contains the name, version, and {@link + * ResourceHelper}.

+ * + * + * @param libraryName the library to find + * @param localePrefix the prefix for the desired locale + * @param contract the contract to use + *@param ctx the {@link javax.faces.context.FacesContext} for the current request + * @return the Library instance for the specified library + */ + LibraryInfo findLibrary(String libraryName, String localePrefix, String contract, FacesContext ctx) { + + LibraryInfo library = webappResourceHelper.findLibrary(libraryName, localePrefix, contract, ctx); + + if (library == null) { + library = classpathResourceHelper.findLibrary(libraryName, localePrefix, contract, ctx); + } + + if (library == null && contract == null) { + // FCAPUTO facelets in contracts should have been found by the webapphelper already + library = faceletWebappResourceHelper.findLibrary(libraryName, localePrefix, contract, ctx); + } + + // if not library is found at this point, let the caller deal with it + return library; + } + + LibraryInfo findLibraryOnClasspathWithZipDirectoryEntryScan(String libraryName, + String localePrefix, + String contract, FacesContext ctx, boolean forceScan) { + return classpathResourceHelper.findLibraryWithZipDirectoryEntryScan(libraryName, localePrefix, contract, ctx, forceScan); + } + + /** + *

Attempt to lookup and return a {@link ResourceInfo} based on the + * specified arguments. + *

+ *

The lookup process will first search the file system of the web + * application. If the library is not found, then it processed to + * searching the classpath.

+ *

+ *

If a library is found, this method will return a {@link + * LibraryInfo} instance that contains the name, version, and {@link + * ResourceHelper}.

+ * + * @param library the library the resource should be found in + * @param resourceName the name of the resource + * @param localePrefix the prefix for the desired locale + * @param compressable true if the resource can be compressed + * @param ctx the {@link javax.faces.context.FacesContext} for the current request + * + * @return the Library instance for the specified library + */ + private ResourceInfo findResource(LibraryInfo library, + String resourceName, + String localePrefix, + boolean compressable, + boolean skipToFaceletResourceHelper, + FacesContext ctx) { + + if (library != null) { + return library.getHelper().findResource(library, + resourceName, + localePrefix, + compressable, + ctx); + } else { + ResourceInfo resource = null; + + if (!skipToFaceletResourceHelper) { + resource = webappResourceHelper.findResource(null, + resourceName, + localePrefix, + compressable, + ctx); + } + if (resource == null && !skipToFaceletResourceHelper) { + resource = classpathResourceHelper.findResource(null, + resourceName, + localePrefix, + compressable, + ctx); + } + if (resource == null) { + resource = faceletWebappResourceHelper.findResource(library, + resourceName, + localePrefix, + compressable, + ctx); + } + return resource; + } + + } + + ResourceInfo findResource(String resourceId) { + // PENDING(fcaputo) do we need to handle contracts here? + String libraryName = null; + String resourceName = null; + int end = 0, start = 0; + if (-1 != (end = resourceId.lastIndexOf("/"))) { + resourceName = resourceId.substring(end+1); + if (-1 != (start = resourceId.lastIndexOf("/", end - 1))) { + libraryName = resourceId.substring(start+1, end); + } else { + libraryName = resourceId.substring(0, end); + } + } + FacesContext context = FacesContext.getCurrentInstance(); + LibraryInfo info = this.findLibrary(libraryName, null, null, context); + ResourceInfo resourceInfo = this.findResource(info, resourceName, libraryName, true, false, context); + + return resourceInfo; + } + + + /** + *

+ * Obtains the application configured message resources for the current + * request locale. If a ResourceBundle is found and contains the key + * javax.faces.resource.localePrefix, use the value associated + * with that key as the prefix for locale specific resources. + *

+ * + *

+ * For example, say the request locale is en_US, and + * javax.faces.resourceLocalePrefix is found with a value of + * en, a resource path within a web application might look like + * /resources/en/corp/images/greetings.jpg + *

+ * + * @param context the {@link FacesContext} for the current request + * @return the localePrefix based on the current request, or null + * if no prefix can be determined + */ + private String getLocalePrefix(FacesContext context) { + + String localePrefix = null; + + localePrefix = context.getExternalContext().getRequestParameterMap().get("loc"); + // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') + // if(localePrefix != null){ + // FIXED: + if(localePrefix != null && !nameContainsForbiddenSequence(localePrefix)){ + return localePrefix; + } + + String appBundleName = context.getApplication().getMessageBundle(); + if (null != appBundleName) { + + Locale locale = null; + if (context.getViewRoot() != null) { + locale = context.getViewRoot().getLocale(); + } else { + locale = context.getApplication().getViewHandler().calculateLocale(context); + } + + try { + ResourceBundle appBundle = + ResourceBundle.getBundle(appBundleName, + locale, + Util.getCurrentLoader(ResourceManager.class)); + localePrefix = + appBundle + .getString(ResourceHandler.LOCALE_PREFIX); + } catch (MissingResourceException mre) { + if (LOGGER.isLoggable(Level.FINEST)) { + LOGGER.log(Level.FINEST, "Ignoring missing resource", mre); + } + } + } + return localePrefix; + + } + + private List getResourceLibraryContracts(FacesContext context) { + UIViewRoot viewRoot = context.getViewRoot(); + if(viewRoot == null) { + + if(context.getApplication().getResourceHandler().isResourceRequest(context)) { + // it is a resource request. look at the parameter con=. + + String param = context.getExternalContext().getRequestParameterMap().get("con"); + if(!nameContainsForbiddenSequence(param) && param != null && param.trim().length() > 0) { + return Arrays.asList(param); + } + } + // PENDING(edburns): calculate the contracts! + return Collections.emptyList(); + } + return context.getResourceLibraryContracts(); + } + + + /** + * @param contentType content-type in question + * @param ctx the @{link FacesContext} for the current request + * @return true if this resource can be compressed, otherwise + * false + */ + private boolean isCompressable(String contentType, FacesContext ctx) { + + // No compression when developing. + if (contentType == null || ctx.isProjectStage(ProjectStage.Development)) { + return false; + } else { + if (compressableTypes != null && !compressableTypes.isEmpty()) { + for (Pattern p : compressableTypes) { + boolean matches = p.matcher(contentType).matches(); + if (matches) { + return true; + } + } + } + } + + return false; + + } + + + /** + * Init compressableTypes from the configuration. + */ + private void initCompressableTypes(Map appMap) { + + WebConfiguration config = WebConfiguration.getInstance(); + String value = config.getOptionValue(WebConfiguration.WebContextInitParameter.CompressableMimeTypes); + if (value != null && value.length() > 0) { + String[] values = Util.split(appMap, value, ","); + if (values != null) { + for (String s : values) { + String pattern = s.trim(); + if (!isPatternValid(pattern)) { + continue; + } + if (pattern.endsWith("/*")) { + pattern = pattern.substring(0, pattern.indexOf("/*")); + pattern += "/[a-z0-9.-]*"; + } + if (compressableTypes == null) { + compressableTypes = new ArrayList<>(values.length); + } + try { + compressableTypes.add(Pattern.compile(pattern)); + } catch (PatternSyntaxException pse) { + if (LOGGER.isLoggable(Level.WARNING)) { + // PENDING i18n + LOGGER.log(Level.WARNING, + "jsf.resource.mime.type.configration.invalid", + new Object[] { pattern, pse.getPattern()}); + } + } + } + } + } + + } + + + /** + * @param input input mime-type pattern from the configuration + * @return true if the input matches the expected pattern, + * otherwise false + */ + private boolean isPatternValid(String input) { + + return (CONFIG_MIMETYPE_PATTERN.matcher(input).matches()); + + } + + +} diff --git a/Java/Ribbon.java b/Java/Ribbon.java new file mode 100644 index 0000000000000000000000000000000000000000..3367b81872150a94bf49c6ffa91e4d9002acf525 --- /dev/null +++ b/Java/Ribbon.java @@ -0,0 +1,335 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + */ +package net.sourceforge.plantuml.timingdiagram.graphic; + +import java.awt.geom.Point2D; +import java.util.ArrayList; +import java.util.List; + +import net.sourceforge.plantuml.Dimension2DDouble; +import net.sourceforge.plantuml.FontParam; +import net.sourceforge.plantuml.ISkinParam; +import net.sourceforge.plantuml.UseStyle; +import net.sourceforge.plantuml.awt.geom.Dimension2D; +import net.sourceforge.plantuml.command.Position; +import net.sourceforge.plantuml.cucadiagram.Display; +import net.sourceforge.plantuml.graphic.AbstractTextBlock; +import net.sourceforge.plantuml.graphic.FontConfiguration; +import net.sourceforge.plantuml.graphic.HorizontalAlignment; +import net.sourceforge.plantuml.graphic.StringBounder; +import net.sourceforge.plantuml.graphic.SymbolContext; +import net.sourceforge.plantuml.graphic.TextBlock; +import net.sourceforge.plantuml.graphic.TextBlockUtils; +import net.sourceforge.plantuml.graphic.UDrawable; +import net.sourceforge.plantuml.graphic.color.ColorType; +import net.sourceforge.plantuml.graphic.color.Colors; +import net.sourceforge.plantuml.style.Style; +import net.sourceforge.plantuml.timingdiagram.ChangeState; +import net.sourceforge.plantuml.timingdiagram.TimeConstraint; +import net.sourceforge.plantuml.timingdiagram.TimeTick; +import net.sourceforge.plantuml.timingdiagram.TimingNote; +import net.sourceforge.plantuml.timingdiagram.TimingRuler; +import net.sourceforge.plantuml.ugraphic.UGraphic; +import net.sourceforge.plantuml.ugraphic.ULine; +import net.sourceforge.plantuml.ugraphic.UTranslate; +import net.sourceforge.plantuml.ugraphic.color.HColor; + +public class Ribbon implements PDrawing { + + private final List changes = new ArrayList<>(); + private final List constraints = new ArrayList<>(); + + private final ISkinParam skinParam; + private final TimingRuler ruler; + private String initialState; + private Colors initialColors; + private final List notes; + private final boolean compact; + private final TextBlock title; + private final int suggestedHeight; + private final Style style; + + public Ribbon(TimingRuler ruler, ISkinParam skinParam, List notes, boolean compact, TextBlock title, + int suggestedHeight, Style style) { + this.style = style; + this.suggestedHeight = suggestedHeight == 0 ? 24 : suggestedHeight; + this.compact = compact; + this.ruler = ruler; + this.skinParam = skinParam; + this.notes = notes; + this.title = title; + } + + public IntricatedPoint getTimeProjection(StringBounder stringBounder, TimeTick tick) { + final double x = ruler.getPosInPixel(tick); + final double y = getHeightForConstraints(stringBounder) + getHeightForNotes(stringBounder, Position.TOP) + + getHeightForTopComment(stringBounder) + getRibbonHeight() / 2; + for (ChangeState change : changes) + if (change.getWhen().compareTo(tick) == 0) + return new IntricatedPoint(new Point2D.Double(x, y), new Point2D.Double(x, y)); + + return new IntricatedPoint(new Point2D.Double(x, y - getRibbonHeight() / 2), + new Point2D.Double(x, y + getRibbonHeight() / 2)); + } + + public void addChange(ChangeState change) { + this.changes.add(change); + } + + private double getPosInPixel(ChangeState change) { + return ruler.getPosInPixel(change.getWhen()); + } + + private FontConfiguration getFontConfiguration() { + if (UseStyle.useBetaStyle() == false) + return FontConfiguration.create(skinParam, FontParam.TIMING, null); + return FontConfiguration.create(skinParam, style); + + } + + private TextBlock createTextBlock(String value) { + final Display display = Display.getWithNewlines(value); + return display.create(getFontConfiguration(), HorizontalAlignment.LEFT, skinParam); + } + + public TextBlock getPart1(double fullAvailableWidth) { + return new AbstractTextBlock() { + public void drawU(UGraphic ug) { + if (compact) { + final double titleHeight = title.calculateDimension(ug.getStringBounder()).getHeight(); + final double dy = (getRibbonHeight() - titleHeight) / 2; + title.drawU(ug.apply(UTranslate.dy(dy))); + } + } + + public Dimension2D calculateDimension(StringBounder stringBounder) { + double width = getInitialWidth(stringBounder); + if (compact) + width += title.calculateDimension(stringBounder).getWidth() + 10; + + return new Dimension2DDouble(width, getRibbonHeight()); + } + }; + } + + public UDrawable getPart2() { + return new UDrawable() { + public void drawU(UGraphic ug) { + drawPart2(ug); + } + }; + } + + private void drawNotes(UGraphic ug, final Position position) { + for (TimingNote note : notes) + if (note.getPosition() == position) { + final double x = ruler.getPosInPixel(note.getWhen()); + note.drawU(ug.apply(UTranslate.dx(x))); + } + } + + private double getInitialWidth(final StringBounder stringBounder) { + if (initialState == null) + return 0; + + return createTextBlock(initialState).calculateDimension(stringBounder).getWidth() + 24; + } + + private void drawHexa(UGraphic ug, double len, ChangeState change) { + final HexaShape shape = HexaShape.create(len, getRibbonHeight(), change.getContext(skinParam, style)); + shape.drawU(ug); + } + + private void drawFlat(UGraphic ug, double len, ChangeState change) { + final ULine line = ULine.hline(len); + change.getContext(skinParam, style).apply(ug).apply(UTranslate.dy(getRibbonHeight() / 2)).draw(line); + } + + private double getRibbonHeight() { + return suggestedHeight; + } + + private void drawPentaB(UGraphic ug, double len, ChangeState change) { + final PentaBShape shape = PentaBShape.create(len, getRibbonHeight(), change.getContext(skinParam, style)); + shape.drawU(ug); + } + + private void drawPentaA(UGraphic ug, double len, ChangeState change) { + SymbolContext context = change.getContext(skinParam, style); + final HColor back = initialColors.getColor(ColorType.BACK); + if (back != null) + context = context.withBackColor(back); + + final PentaAShape shape = PentaAShape.create(len, getRibbonHeight(), context); + shape.drawU(ug); + } + + private double getHeightForConstraints(StringBounder stringBounder) { + return TimeConstraint.getHeightForConstraints(stringBounder, constraints); + } + + private double getHeightForNotes(StringBounder stringBounder, Position position) { + double height = 0; + for (TimingNote note : notes) + if (note.getPosition() == position) + height = Math.max(height, note.getHeight(stringBounder)); + + return height; + } + + private double getMarginX() { + return 12; + } + + public void setInitialState(String initialState, Colors initialColors) { + this.initialState = initialState; + this.initialColors = initialColors; + } + + public void addConstraint(TimeConstraint constraint) { + this.constraints.add(constraint); + } + + public double getFullHeight(StringBounder stringBounder) { + return getHeightForConstraints(stringBounder) + getHeightForTopComment(stringBounder) + + getHeightForNotes(stringBounder, Position.TOP) + getRibbonHeight() + + getHeightForNotes(stringBounder, Position.BOTTOM) + getBottomMargin(); + } + + private double getBottomMargin() { + return 10; + } + + private void drawPart2(UGraphic ug) { + final StringBounder stringBounder = ug.getStringBounder(); + + final UGraphic ugRibbon = ug.apply(UTranslate.dy(getHeightForConstraints(stringBounder) + + getHeightForTopComment(stringBounder) + getHeightForNotes(stringBounder, Position.TOP))); + + drawBeforeZeroState(ugRibbon); + drawBeforeZeroStateLabel(ugRibbon.apply(UTranslate.dy(getRibbonHeight() / 2))); + drawStates(ugRibbon); + drawStatesLabels(ugRibbon.apply(UTranslate.dy(getRibbonHeight() / 2))); + + drawConstraints(ug.apply(UTranslate.dy(getHeightForConstraints(stringBounder) / 2))); + + drawNotes(ug, Position.TOP); + drawNotes(ug.apply(UTranslate.dy(getHeightForConstraints(stringBounder) + getRibbonHeight() + + getHeightForNotes(stringBounder, Position.TOP))), Position.BOTTOM); + } + + private void drawBeforeZeroState(UGraphic ug) { + if (initialState != null && changes.size() > 0) { + final StringBounder stringBounder = ug.getStringBounder(); + final double a = getPosInPixel(changes.get(0)); + drawPentaA(ug.apply(UTranslate.dx(-getInitialWidth(stringBounder))), getInitialWidth(stringBounder) + a, + changes.get(0)); + } + } + + private void drawBeforeZeroStateLabel(final UGraphic ug) { + final StringBounder stringBounder = ug.getStringBounder(); + if (initialState != null) { + final TextBlock initial = createTextBlock(initialState); + final Dimension2D dimInital = initial.calculateDimension(stringBounder); + initial.drawU(ug.apply(new UTranslate(-getMarginX() - dimInital.getWidth(), -dimInital.getHeight() / 2))); + } + } + + private void drawStates(UGraphic ug) { + for (int i = 0; i < changes.size() - 1; i++) { + final double a = getPosInPixel(changes.get(i)); + final double b = getPosInPixel(changes.get(i + 1)); + assert b > a; + if (changes.get(i).isFlat()) + drawFlat(ug.apply(UTranslate.dx(a)), b - a, changes.get(i)); + else if (changes.get(i).isCompletelyHidden() == false) + drawHexa(ug.apply(UTranslate.dx(a)), b - a, changes.get(i)); + } + if (changes.size() >= 1) { + final ChangeState last = changes.get(changes.size() - 1); + final double a = getPosInPixel(last); + if (last.isFlat()) + drawFlat(ug.apply(UTranslate.dx(a)), ruler.getWidth() - a, last); + else if (last.isCompletelyHidden() == false) + drawPentaB(ug.apply(UTranslate.dx(a)), ruler.getWidth() - a, last); + } + } + + private void drawStatesLabels(UGraphic ug) { + final StringBounder stringBounder = ug.getStringBounder(); + for (int i = 0; i < changes.size(); i++) { + final ChangeState change = changes.get(i); + final double x = ruler.getPosInPixel(change.getWhen()); + if (change.isBlank() == false && change.isCompletelyHidden() == false && change.isFlat() == false) { + final TextBlock state = createTextBlock(change.getState()); + final Dimension2D dim = state.calculateDimension(stringBounder); + final double xtext; + if (i == changes.size() - 1) { + xtext = x + getMarginX(); + } else { + final double x2 = ruler.getPosInPixel(changes.get(i + 1).getWhen()); + xtext = (x + x2) / 2 - dim.getWidth() / 2; + } + state.drawU(ug.apply(new UTranslate(xtext, -dim.getHeight() / 2))); + } + final TextBlock commentTopBlock = getCommentTopBlock(change); + final Dimension2D dimComment = commentTopBlock.calculateDimension(stringBounder); + commentTopBlock + .drawU(ug.apply(new UTranslate(x + getMarginX(), -getRibbonHeight() / 2 - dimComment.getHeight()))); + } + } + + private TextBlock getCommentTopBlock(final ChangeState change) { + if (change.getComment() == null) + return TextBlockUtils.empty(0, 0); + + return createTextBlock(change.getComment()); + } + + private double getHeightForTopComment(StringBounder stringBounder) { + double result = 0; + for (ChangeState change : changes) + result = Math.max(result, getCommentTopBlock(change).calculateDimension(stringBounder).getHeight()); + + return result; + } + + private void drawConstraints(final UGraphic ug) { + for (TimeConstraint constraint : constraints) + constraint.drawU(ug, ruler); + } + +} diff --git a/Java/RoutingResultBuilder.java b/Java/RoutingResultBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..a16e9428a2270eededd8bb585e3df19f49880f76 --- /dev/null +++ b/Java/RoutingResultBuilder.java @@ -0,0 +1,142 @@ +/* + * Copyright 2019 LINE Corporation + * + * LINE Corporation 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: + * + * 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.linecorp.armeria.server; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.linecorp.armeria.server.RoutingResult.LOWEST_SCORE; +import static java.util.Objects.requireNonNull; + +import com.google.common.collect.ImmutableMap; + +import com.linecorp.armeria.common.MediaType; +import com.linecorp.armeria.common.annotation.Nullable; +import com.linecorp.armeria.internal.common.ArmeriaHttpUtil; + +/** + * Builds a new {@link RoutingResult}. + */ +public final class RoutingResultBuilder { + + private RoutingResultType type = RoutingResultType.MATCHED; + + @Nullable + private String path; + + @Nullable + private String query; + + @Nullable + private ImmutableMap.Builder pathParams; + + private int score = LOWEST_SCORE; + + @Nullable + private MediaType negotiatedResponseMediaType; + + RoutingResultBuilder() {} + + RoutingResultBuilder(int expectedNumParams) { + pathParams = ImmutableMap.builderWithExpectedSize(expectedNumParams); + } + + /** + * Sets the result type. + * + * @param type {@link RoutingResultType#MATCHED} or {@link RoutingResultType#CORS_PREFLIGHT}. + */ + public RoutingResultBuilder type(RoutingResultType type) { + requireNonNull(type, "type"); + checkArgument(type != RoutingResultType.NOT_MATCHED, + "type: %s (expected: %s or %s)", + type, RoutingResultType.MATCHED, RoutingResultType.CORS_PREFLIGHT); + this.type = type; + return this; + } + + /** + * Sets the mapped path, encoded as defined in RFC3986. + */ + public RoutingResultBuilder path(String path) { + this.path = requireNonNull(path, "path"); + return this; + } + + /** + * Sets the specified query. + */ + public RoutingResultBuilder query(@Nullable String query) { + this.query = query; + return this; + } + + /** + * Adds a decoded path parameter. + */ + public RoutingResultBuilder decodedParam(String name, String value) { + pathParams().put(requireNonNull(name, "name"), requireNonNull(value, "value")); + return this; + } + + /** + * Adds an encoded path parameter, which will be decoded in UTF-8 automatically. + */ + public RoutingResultBuilder rawParam(String name, String value) { + pathParams().put(requireNonNull(name, "name"), + // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') + // ArmeriaHttpUtil.decodePath(requireNonNull(value, "value"))); + // FIXED: + ArmeriaHttpUtil.decodePathParam(requireNonNull(value, "value"))); + return this; + } + + /** + * Sets the score. + */ + public RoutingResultBuilder score(int score) { + this.score = score; + return this; + } + + /** + * Sets the negotiated producible {@link MediaType}. + */ + public RoutingResultBuilder negotiatedResponseMediaType(MediaType negotiatedResponseMediaType) { + this.negotiatedResponseMediaType = requireNonNull(negotiatedResponseMediaType, + "negotiatedResponseMediaType"); + return this; + } + + /** + * Returns a newly-created {@link RoutingResult}. + */ + public RoutingResult build() { + if (path == null) { + return RoutingResult.empty(); + } + + return new RoutingResult(type, path, query, + pathParams != null ? pathParams.build() : ImmutableMap.of(), + score, negotiatedResponseMediaType); + } + + private ImmutableMap.Builder pathParams() { + if (pathParams != null) { + return pathParams; + } + return pathParams = ImmutableMap.builder(); + } +} diff --git a/Java/S390xConst.java b/Java/S390xConst.java new file mode 100644 index 0000000000000000000000000000000000000000..7c308fdd6954c14276e6f29affc3e28886dd86d2 --- /dev/null +++ b/Java/S390xConst.java @@ -0,0 +1,131 @@ +// For Unicorn Engine. AUTO-GENERATED FILE, DO NOT EDIT + +package unicorn; + +public interface S390xConst { + +// S390X CPU + + public static final int UC_CPU_S390X_Z900 = 0; + public static final int UC_CPU_S390X_Z900_2 = 1; + public static final int UC_CPU_S390X_Z900_3 = 2; + public static final int UC_CPU_S390X_Z800 = 3; + public static final int UC_CPU_S390X_Z990 = 4; + public static final int UC_CPU_S390X_Z990_2 = 5; + public static final int UC_CPU_S390X_Z990_3 = 6; + public static final int UC_CPU_S390X_Z890 = 7; + public static final int UC_CPU_S390X_Z990_4 = 8; + public static final int UC_CPU_S390X_Z890_2 = 9; + public static final int UC_CPU_S390X_Z990_5 = 10; + public static final int UC_CPU_S390X_Z890_3 = 11; + public static final int UC_CPU_S390X_Z9EC = 12; + public static final int UC_CPU_S390X_Z9EC_2 = 13; + public static final int UC_CPU_S390X_Z9BC = 14; + public static final int UC_CPU_S390X_Z9EC_3 = 15; + public static final int UC_CPU_S390X_Z9BC_2 = 16; + public static final int UC_CPU_S390X_Z10EC = 17; + public static final int UC_CPU_S390X_Z10EC_2 = 18; + public static final int UC_CPU_S390X_Z10BC = 19; + public static final int UC_CPU_S390X_Z10EC_3 = 20; + public static final int UC_CPU_S390X_Z10BC_2 = 21; + public static final int UC_CPU_S390X_Z196 = 22; + public static final int UC_CPU_S390X_Z196_2 = 23; + public static final int UC_CPU_S390X_Z114 = 24; + public static final int UC_CPU_S390X_ZEC12 = 25; + public static final int UC_CPU_S390X_ZEC12_2 = 26; + public static final int UC_CPU_S390X_ZBC12 = 27; + public static final int UC_CPU_S390X_Z13 = 28; + public static final int UC_CPU_S390X_Z13_2 = 29; + public static final int UC_CPU_S390X_Z13S = 30; + public static final int UC_CPU_S390X_Z14 = 31; + public static final int UC_CPU_S390X_Z14_2 = 32; + public static final int UC_CPU_S390X_Z14ZR1 = 33; + public static final int UC_CPU_S390X_GEN15A = 34; + public static final int UC_CPU_S390X_GEN15B = 35; + public static final int UC_CPU_S390X_QEMU = 36; + public static final int UC_CPU_S390X_MAX = 37; + // BUG: CWE-665 Improper Initialization + // + // FIXED: + public static final int UC_CPU_S390X_ENDING = 38; + +// S390X registers + + public static final int UC_S390X_REG_INVALID = 0; + +// General purpose registers + public static final int UC_S390X_REG_R0 = 1; + public static final int UC_S390X_REG_R1 = 2; + public static final int UC_S390X_REG_R2 = 3; + public static final int UC_S390X_REG_R3 = 4; + public static final int UC_S390X_REG_R4 = 5; + public static final int UC_S390X_REG_R5 = 6; + public static final int UC_S390X_REG_R6 = 7; + public static final int UC_S390X_REG_R7 = 8; + public static final int UC_S390X_REG_R8 = 9; + public static final int UC_S390X_REG_R9 = 10; + public static final int UC_S390X_REG_R10 = 11; + public static final int UC_S390X_REG_R11 = 12; + public static final int UC_S390X_REG_R12 = 13; + public static final int UC_S390X_REG_R13 = 14; + public static final int UC_S390X_REG_R14 = 15; + public static final int UC_S390X_REG_R15 = 16; + +// Floating point registers + public static final int UC_S390X_REG_F0 = 17; + public static final int UC_S390X_REG_F1 = 18; + public static final int UC_S390X_REG_F2 = 19; + public static final int UC_S390X_REG_F3 = 20; + public static final int UC_S390X_REG_F4 = 21; + public static final int UC_S390X_REG_F5 = 22; + public static final int UC_S390X_REG_F6 = 23; + public static final int UC_S390X_REG_F7 = 24; + public static final int UC_S390X_REG_F8 = 25; + public static final int UC_S390X_REG_F9 = 26; + public static final int UC_S390X_REG_F10 = 27; + public static final int UC_S390X_REG_F11 = 28; + public static final int UC_S390X_REG_F12 = 29; + public static final int UC_S390X_REG_F13 = 30; + public static final int UC_S390X_REG_F14 = 31; + public static final int UC_S390X_REG_F15 = 32; + public static final int UC_S390X_REG_F16 = 33; + public static final int UC_S390X_REG_F17 = 34; + public static final int UC_S390X_REG_F18 = 35; + public static final int UC_S390X_REG_F19 = 36; + public static final int UC_S390X_REG_F20 = 37; + public static final int UC_S390X_REG_F21 = 38; + public static final int UC_S390X_REG_F22 = 39; + public static final int UC_S390X_REG_F23 = 40; + public static final int UC_S390X_REG_F24 = 41; + public static final int UC_S390X_REG_F25 = 42; + public static final int UC_S390X_REG_F26 = 43; + public static final int UC_S390X_REG_F27 = 44; + public static final int UC_S390X_REG_F28 = 45; + public static final int UC_S390X_REG_F29 = 46; + public static final int UC_S390X_REG_F30 = 47; + public static final int UC_S390X_REG_F31 = 48; + +// Access registers + public static final int UC_S390X_REG_A0 = 49; + public static final int UC_S390X_REG_A1 = 50; + public static final int UC_S390X_REG_A2 = 51; + public static final int UC_S390X_REG_A3 = 52; + public static final int UC_S390X_REG_A4 = 53; + public static final int UC_S390X_REG_A5 = 54; + public static final int UC_S390X_REG_A6 = 55; + public static final int UC_S390X_REG_A7 = 56; + public static final int UC_S390X_REG_A8 = 57; + public static final int UC_S390X_REG_A9 = 58; + public static final int UC_S390X_REG_A10 = 59; + public static final int UC_S390X_REG_A11 = 60; + public static final int UC_S390X_REG_A12 = 61; + public static final int UC_S390X_REG_A13 = 62; + public static final int UC_S390X_REG_A14 = 63; + public static final int UC_S390X_REG_A15 = 64; + public static final int UC_S390X_REG_PC = 65; + public static final int UC_S390X_REG_PSWM = 66; + public static final int UC_S390X_REG_ENDING = 67; + +// Alias registers + +} diff --git a/Java/SQLTestSuite.java b/Java/SQLTestSuite.java new file mode 100644 index 0000000000000000000000000000000000000000..a1c04be2dd0b779cb5e5ee2f821377db535ede0d --- /dev/null +++ b/Java/SQLTestSuite.java @@ -0,0 +1,51 @@ +/* + * Copyright 2015 Red Hat, Inc. and/or its affiliates. + * + * 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.dashbuilder.dataprovider.sql; + +import java.util.List; +import java.util.ArrayList; + +import org.junit.Before; + +public class SQLTestSuite extends SQLDataSetTestBase { + + protected T setUp(T test) throws Exception { + test.testSettings = testSettings; + test.conn = conn; + return test; + } + + protected List sqlTestList = new ArrayList(); + + @Before + public void setUp() throws Exception { + super.setUp(); + sqlTestList.add(setUp(new SQLDataSetDefTest())); + sqlTestList.add(setUp(new SQLDataSetTrimTest())); + sqlTestList.add(setUp(new SQLTableDataSetLookupTest())); + sqlTestList.add(setUp(new SQLQueryDataSetLookupTest())); + // BUG: CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') + // + // FIXED: + sqlTestList.add(setUp(new SQLInjectionAttacksTest())); + } + + public void testAll() throws Exception { + for (SQLDataSetTestBase testBase : sqlTestList) { + testBase.testAll(); + } + } +} diff --git a/Java/SURL.java b/Java/SURL.java new file mode 100644 index 0000000000000000000000000000000000000000..a681b608fb6344f97f68df77a015cce1a51c7778 --- /dev/null +++ b/Java/SURL.java @@ -0,0 +1,661 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.security; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.Proxy; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.net.ssl.HttpsURLConnection; +import javax.swing.ImageIcon; + +import net.sourceforge.plantuml.StringUtils; +import net.sourceforge.plantuml.security.authentication.SecurityAccessInterceptor; +import net.sourceforge.plantuml.security.authentication.SecurityAuthentication; +import net.sourceforge.plantuml.security.authentication.SecurityCredentials; + +/** + * Secure replacement for java.net.URL. + *

+ * This class should be used instead of java.net.URL. + *

+ * This class does some control access and manages access-tokens via URL. If a + * URL contains a access-token, similar to a user prefix, SURL loads the + * authorization config for this user-token and passes the credentials to the + * host. + *

+ * Example:
+ * + *

+ *     SURL url = SURL.create ("https://jenkins-access@jenkins.mycompany.com/api/json")
+ * 
+ * + * The {@code jenkins-access} will checked against the Security context access + * token configuration. If a configuration exists for this token name, the token + * will be removed from the URL and the credentials will be added to the + * headers. If the token is not found, the URL remains as it is and no separate + * authentication will be performed. + *

+ * TODO: Some methods should be moved to a HttpClient implementation, because + * SURL is not the valid class to manage it.
+ * TODO: BAD_HOSTS implementation should be reviewed and moved to HttpClient + * implementation with a circuit-breaker.
+ * TODO: Token expiration with refresh should be implemented in future.
+ */ +public class SURL { + + /** + * Indicates, that we have no authentication to access the URL. + */ + public static final String WITHOUT_AUTHENTICATION = SecurityUtils.NO_CREDENTIALS; + + /** + * Regex to remove the UserInfo part from a URL. + */ + // BUG: CWE-918 Server-Side Request Forgery (SSRF) + // private static final Pattern PATTERN_USERINFO = Pattern.compile("(^https?://)([-_:0-9a-zA-Z]+@)([^@]*)"); + // FIXED: + private static final Pattern PATTERN_USERINFO = Pattern.compile("(^https?://)([-_0-9a-zA-Z]+@)([^@]*)"); + + private static final ExecutorService EXE = Executors.newCachedThreadPool(new ThreadFactory() { + public Thread newThread(Runnable r) { + final Thread t = Executors.defaultThreadFactory().newThread(r); + t.setDaemon(true); + return t; + } + }); + + private static final Map BAD_HOSTS = new ConcurrentHashMap(); + + /** + * Internal URL, maybe cleaned from user-token. + */ + private final URL internal; + + /** + * Assigned credentials to this URL. + */ + private final String securityIdentifier; + + private SURL(URL url, String securityIdentifier) { + this.internal = Objects.requireNonNull(url); + this.securityIdentifier = Objects.requireNonNull(securityIdentifier); + } + + /** + * Create a secure URL from a String. + *

+ * The url must be http or https. Return null in case of error or if + * url is null + * + * @param url plain url starting by http:// or https// + * @return the secure URL or null + */ + public static SURL create(String url) { + if (url == null) + return null; + + if (url.startsWith("http://") || url.startsWith("https://")) + try { + return create(new URL(url)); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + return null; + } + + /** + * Create a secure URL from a java.net.URL object. + *

+ * It takes into account credentials. + * + * @param url + * @return the secure URL + * @throws MalformedURLException if url is null + */ + public static SURL create(URL url) throws MalformedURLException { + if (url == null) + throw new MalformedURLException("URL cannot be null"); + + final String credentialId = url.getUserInfo(); + + if (credentialId == null || credentialId.indexOf(':') > 0) + // No user info at all, or a user with password (This is a legacy BasicAuth + // access, and we bypass it): + return new SURL(url, WITHOUT_AUTHENTICATION); + else if (SecurityUtils.existsSecurityCredentials(credentialId)) + // Given userInfo, but without a password. We try to find SecurityCredentials + return new SURL(removeUserInfo(url), credentialId); + else + return new SURL(url, WITHOUT_AUTHENTICATION); + } + + /** + * Creates a URL without UserInfo part and without SecurityCredentials. + * + * @param url plain URL + * @return SURL without any user credential information. + * @throws MalformedURLException + */ + static SURL createWithoutUser(URL url) throws MalformedURLException { + return new SURL(removeUserInfo(url), WITHOUT_AUTHENTICATION); + } + + /** + * Clears the bad hosts cache. + *

+ * In some test cases (and maybe also needed for other functionality) the bad + * hosts cache must be cleared.
+ * E.g., in a test we check the failure on missing credentials and then a test + * with existing credentials. With a bad host cache the second test will fail, + * or we have unpredicted results. + */ + static void resetBadHosts() { + BAD_HOSTS.clear(); + } + + @Override + public String toString() { + return internal.toString(); + } + + /** + * Check SecurityProfile to see if this URL can be opened. + */ + private boolean isUrlOk() { + if (SecurityUtils.getSecurityProfile() == SecurityProfile.SANDBOX) + // In SANDBOX, we cannot read any URL + return false; + + if (SecurityUtils.getSecurityProfile() == SecurityProfile.LEGACY) + return true; + + if (SecurityUtils.getSecurityProfile() == SecurityProfile.UNSECURE) + // We are UNSECURE anyway + return true; + + if (isInUrlAllowList()) + return true; + + if (SecurityUtils.getSecurityProfile() == SecurityProfile.INTERNET) { + if (forbiddenURL(cleanPath(internal.toString()))) + return false; + + final int port = internal.getPort(); + // Using INTERNET profile, port 80 and 443 are ok + return port == 80 || port == 443 || port == -1; + } + return false; + } + + private boolean forbiddenURL(String full) { + if (full.matches("^https?://[.0-9]+/.*")) + return true; + if (full.matches("^https?://[^.]+/.*")) + return true; + return false; + } + + private boolean isInUrlAllowList() { + final String full = cleanPath(internal.toString()); + for (String allow : getUrlAllowList()) + if (full.startsWith(cleanPath(allow))) + return true; + + return false; + } + + private String cleanPath(String path) { + // Remove user information, because we don't like to store user/password or + // userTokens in allow-list + path = removeUserInfoFromUrlPath(path); + path = path.trim().toLowerCase(Locale.US); + // We simplify/normalize the url, removing default ports + path = path.replace(":80/", ""); + path = path.replace(":443/", ""); + return path; + } + + private List getUrlAllowList() { + final String env = SecurityUtils.getenv(SecurityUtils.ALLOWLIST_URL); + if (env == null) + return Collections.emptyList(); + + return Arrays.asList(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(env).split(";")); + } + + /** + * Reads from an endpoint (with configured credentials and proxy) the response + * as blob. + *

+ * This method allows access to an endpoint, with a configured + * SecurityCredentials object. The credentials will load on the fly and + * authentication fetched from an authentication-manager. Caching of tokens is + * not supported. + *

+ * authors: Alain Corbiere, Aljoscha Rittner + * + * @return data loaded data from endpoint + */ + public byte[] getBytes() { + if (isUrlOk() == false) + return null; + + final SecurityCredentials credentials = SecurityUtils.loadSecurityCredentials(securityIdentifier); + final SecurityAuthentication authentication = SecurityUtils.getAuthenticationManager(credentials) + .create(credentials); + try { + final String host = internal.getHost(); + final Long bad = BAD_HOSTS.get(host); + if (bad != null) { + if ((System.currentTimeMillis() - bad) < 1000L * 60) + return null; + BAD_HOSTS.remove(host); + } + + try { + final Future result = EXE + .submit(requestWithGetAndResponse(internal, credentials.getProxy(), authentication, null)); + final byte[] data = result.get(SecurityUtils.getSecurityProfile().getTimeout(), TimeUnit.MILLISECONDS); + if (data != null) + return data; + + } catch (Exception e) { + System.err.println("issue " + host + " " + e); + } + + BAD_HOSTS.put(host, System.currentTimeMillis()); + return null; + } finally { + // clean up. We don't cache tokens, no expire handling. All time a re-request. + credentials.eraseCredentials(); + authentication.eraseCredentials(); + } + } + + /** + * Reads from an endpoint with a given authentication and proxy the response as + * blob. + *

+ * This method allows a parametrized access to an endpoint, without a configured + * SecurityCredentials object. This is useful to access internally identity + * providers (IDP), or authorization servers (to request access tokens). + *

+ * This method don't use the "bad-host" functionality, because the access to + * infrastructure services should not be obfuscated by some internal management. + *

+ * Please don't use this method directly from DSL scripts. + * + * @param authentication authentication object data. Caller is responsible to + * erase credentials + * @param proxy proxy configuration + * @param headers additional headers, if needed + * @return loaded data from endpoint + */ + private byte[] getBytes(Proxy proxy, SecurityAuthentication authentication, Map headers) { + if (isUrlOk() == false) + return null; + + final Future result = EXE.submit(requestWithGetAndResponse(internal, proxy, authentication, headers)); + + try { + return result.get(SecurityUtils.getSecurityProfile().getTimeout(), TimeUnit.MILLISECONDS); + } catch (Exception e) { + System.err.println("SURL response issue to " + internal.getHost() + " " + e); + return null; + } + } + + /** + * Post to an endpoint with a given authentication and proxy the response as + * blob. + *

+ * This method allows a parametrized access to an endpoint, without a configured + * SecurityCredentials object. This is useful to access internally identity + * providers (IDP), or authorization servers (to request access tokens). + *

+ * This method don't use the "bad-host" functionality, because the access to + * infrastructure services should not be obfuscated by some internal management. + *

+ * Please don't use this method directly from DSL scripts. + * + * @param authentication authentication object data. Caller is responsible to + * erase credentials + * @param proxy proxy configuration + * @param data content to post + * @param headers headers, if needed + * @return loaded data from endpoint + */ + public byte[] getBytesOnPost(Proxy proxy, SecurityAuthentication authentication, String data, + Map headers) { + if (isUrlOk() == false) + return null; + + final Future result = EXE + .submit(requestWithPostAndResponse(internal, proxy, authentication, data, headers)); + + try { + return result.get(SecurityUtils.getSecurityProfile().getTimeout(), TimeUnit.MILLISECONDS); + } catch (Exception e) { + System.err.println("SURL response issue to " + internal.getHost() + " " + e); + return null; + } + } + + /** + * Creates a GET request and response handler + * + * @param url URL to request + * @param proxy proxy to apply + * @param authentication the authentication to use + * @param headers additional headers, if needed + * @return the callable handler. + */ + private static Callable requestWithGetAndResponse(final URL url, final Proxy proxy, + final SecurityAuthentication authentication, final Map headers) { + return new Callable() { + + private HttpURLConnection openConnection(final URL url) throws IOException { + // Add proxy, if passed throw parameters + final URLConnection connection = proxy == null ? url.openConnection() : url.openConnection(proxy); + if (connection == null) + return null; + + final HttpURLConnection http = (HttpURLConnection) connection; + + applyEndpointAccessAuthentication(http, authentication); + applyAdditionalHeaders(http, headers); + return http; + } + + public byte[] call() throws IOException { + HttpURLConnection http = openConnection(url); + final int responseCode = http.getResponseCode(); + + if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP + || responseCode == HttpURLConnection.HTTP_MOVED_PERM) { + final String newUrl = http.getHeaderField("Location"); + http = openConnection(new URL(newUrl)); + } + + return retrieveResponseAsBytes(http); + } + }; + } + + /** + * Creates a POST request and response handler with a simple String content. The + * content will be identified as form or JSON data. The charset encoding can be + * set by header parameters or will be set to UTF-8. The method to some fancy + * logic to simplify it for the user. + * + * @param url URL to request via POST method + * @param proxy proxy to apply + * @param authentication the authentication to use + * @param headers additional headers, if needed + * @return the callable handler. + */ + private static Callable requestWithPostAndResponse(final URL url, final Proxy proxy, + final SecurityAuthentication authentication, final String data, final Map headers) { + return new Callable() { + public byte[] call() throws IOException { + // Add proxy, if passed throw parameters + final URLConnection connection = proxy == null ? url.openConnection() : url.openConnection(proxy); + if (connection == null) + return null; + + final boolean withContent = StringUtils.isNotEmpty(data); + + final HttpURLConnection http = (HttpURLConnection) connection; + http.setRequestMethod("POST"); + if (withContent) + http.setDoOutput(true); + + applyEndpointAccessAuthentication(http, authentication); + applyAdditionalHeaders(http, headers); + + final Charset charSet = extractCharset(http.getRequestProperty("Content-Type")); + + if (withContent) + sendRequestAsBytes(http, data.getBytes(charSet != null ? charSet : StandardCharsets.UTF_8)); + + return retrieveResponseAsBytes(http); + } + }; + } + + private static Charset extractCharset(String contentType) { + if (StringUtils.isEmpty(contentType)) + return null; + + final Matcher matcher = Pattern.compile("(?i)\\bcharset=\\s*\"?([^\\s;\"]*)").matcher(contentType); + if (matcher.find()) + try { + return Charset.forName(matcher.group(1)); + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + /** + * Loads a response from an endpoint as a byte[] array. + * + * @param connection the URL connection + * @return the loaded byte arrays + * @throws IOException an exception, if the connection cannot establish or the + * download was broken + */ + private static byte[] retrieveResponseAsBytes(HttpURLConnection connection) throws IOException { + final int responseCode = connection.getResponseCode(); + if (responseCode < HttpURLConnection.HTTP_BAD_REQUEST) { + try (InputStream input = connection.getInputStream()) { + return retrieveData(input); + } + } else { + try (InputStream error = connection.getErrorStream()) { + final byte[] bytes = retrieveData(error); + throw new IOException( + "HTTP error " + responseCode + " with " + new String(bytes, StandardCharsets.UTF_8)); + } + } + } + + /** + * Reads data in a byte[] array. + * + * @param input input stream + * @return byte data + * @throws IOException if something went wrong + */ + private static byte[] retrieveData(InputStream input) throws IOException { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + final byte[] buffer = new byte[1024]; + int read; + while ((read = input.read(buffer)) > 0) { + out.write(buffer, 0, read); + } + out.close(); + return out.toByteArray(); + } + + /** + * Sends a request content payload to an endpoint. + * + * @param connection HTTP connection + * @param data data as byte array + * @throws IOException if something went wrong + */ + private static void sendRequestAsBytes(HttpURLConnection connection, byte[] data) throws IOException { + connection.setFixedLengthStreamingMode(data.length); + try (OutputStream os = connection.getOutputStream()) { + os.write(data); + } + } + + public InputStream openStream() { + if (isUrlOk()) { + final byte[] data = getBytes(); + if (data != null) + return new ByteArrayInputStream(data); + + } + return null; + } + + public BufferedImage readRasterImageFromURL() { + if (isUrlOk()) + try { + final byte[] bytes = getBytes(); + if (bytes == null || bytes.length == 0) + return null; + final ImageIcon tmp = new ImageIcon(bytes); + return SecurityUtils.readRasterImage(tmp); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * Informs, if SecurityCredentials are configured for this connection. + * + * @return true, if credentials will be used for a connection + */ + public boolean isAuthorizationConfigured() { + return WITHOUT_AUTHENTICATION.equals(securityIdentifier) == false; + } + + /** + * Applies the given authentication data to the http connection. + * + * @param http HTTP URL connection (must be an encrypted https-TLS/SSL + * connection, or http must be activated with a property) + * @param authentication the data to request the access + * @see SecurityUtils#getAccessInterceptor(SecurityAuthentication) + * @see SecurityUtils#isNonSSLAuthenticationAllowed() + */ + private static void applyEndpointAccessAuthentication(URLConnection http, SecurityAuthentication authentication) { + if (authentication.isPublic()) + // Shortcut: No need to apply authentication. + return; + + if (http instanceof HttpsURLConnection || SecurityUtils.isNonSSLAuthenticationAllowed()) { + SecurityAccessInterceptor accessInterceptor = SecurityUtils.getAccessInterceptor(authentication); + accessInterceptor.apply(authentication, http); + } else { + // We cannot allow applying secret tokens on plain connections. Everyone can + // read the data. + throw new IllegalStateException( + "The transport of authentication data over an unencrypted http connection is not allowed"); + } + } + + /** + * Set the headers for a URL connection + * + * @param headers map Keys with values (can be String or list of String) + */ + private static void applyAdditionalHeaders(URLConnection http, Map headers) { + if (headers == null || headers.isEmpty()) + return; + + for (Map.Entry header : headers.entrySet()) { + final Object value = header.getValue(); + if (value instanceof String) + http.setRequestProperty(header.getKey(), (String) value); + else if (value instanceof List) + for (Object item : (List) value) + if (item != null) + http.addRequestProperty(header.getKey(), item.toString()); + + } + } + + /** + * Removes the userInfo part from the URL, because we want to use the + * SecurityCredentials instead. + * + * @param url URL with UserInfo part + * @return url without UserInfo part + * @throws MalformedURLException + */ + private static URL removeUserInfo(URL url) throws MalformedURLException { + return new URL(removeUserInfoFromUrlPath(url.toExternalForm())); + } + + /** + * Removes the userInfo part from the URL, because we want to use the + * SecurityCredentials instead. + * + * @param url URL with UserInfo part + * @return url without UserInfo part + */ + private static String removeUserInfoFromUrlPath(String url) { + // Simple solution: + final Matcher matcher = PATTERN_USERINFO.matcher(url); + if (matcher.find()) + return matcher.replaceFirst("$1$3"); + + return url; + } +} diff --git a/Java/SamlConfigAttributes.java b/Java/SamlConfigAttributes.java new file mode 100644 index 0000000000000000000000000000000000000000..304b96c26f78e1b61cc503d2768bec1923ded2bd --- /dev/null +++ b/Java/SamlConfigAttributes.java @@ -0,0 +1,51 @@ +/* + * Copyright 2016 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.keycloak.protocol.saml; + +import org.keycloak.services.util.CertificateInfoHelper; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +public interface SamlConfigAttributes { + String SAML_SIGNING_PRIVATE_KEY = "saml.signing.private.key"; + String SAML_CANONICALIZATION_METHOD_ATTRIBUTE = "saml_signature_canonicalization_method"; + String SAML_SIGNATURE_ALGORITHM = "saml.signature.algorithm"; + String SAML_NAME_ID_FORMAT_ATTRIBUTE = "saml_name_id_format"; + String SAML_AUTHNSTATEMENT = "saml.authnstatement"; + String SAML_ONETIMEUSE_CONDITION = "saml.onetimeuse.condition"; + String SAML_FORCE_NAME_ID_FORMAT_ATTRIBUTE = "saml_force_name_id_format"; + String SAML_ARTIFACT_BINDING = "saml.artifact.binding"; + String SAML_SERVER_SIGNATURE = "saml.server.signature"; + String SAML_SERVER_SIGNATURE_KEYINFO_EXT = "saml.server.signature.keyinfo.ext"; + String SAML_SERVER_SIGNATURE_KEYINFO_KEY_NAME_TRANSFORMER = "saml.server.signature.keyinfo.xmlSigKeyInfoKeyNameTransformer"; + String SAML_FORCE_POST_BINDING = "saml.force.post.binding"; + String SAML_ASSERTION_SIGNATURE = "saml.assertion.signature"; + String SAML_ENCRYPT = "saml.encrypt"; + String SAML_CLIENT_SIGNATURE_ATTRIBUTE = "saml.client.signature"; + String SAML_SIGNING_CERTIFICATE_ATTRIBUTE = "saml.signing." + CertificateInfoHelper.X509CERTIFICATE; + String SAML_ENCRYPTION_CERTIFICATE_ATTRIBUTE = "saml.encryption." + CertificateInfoHelper.X509CERTIFICATE; + String SAML_ENCRYPTION_PRIVATE_KEY_ATTRIBUTE = "saml.encryption." + CertificateInfoHelper.PRIVATE_KEY; + String SAML_ASSERTION_LIFESPAN = "saml.assertion.lifespan"; + String SAML_ARTIFACT_BINDING_IDENTIFIER = "saml.artifact.binding.identifier"; + // BUG: CWE-287 Improper Authentication + // + // FIXED: + String SAML_ALLOW_ECP_FLOW = "saml.allow.ecp.flow"; +} diff --git a/Java/SarOperation.java b/Java/SarOperation.java new file mode 100644 index 0000000000000000000000000000000000000000..a5f0a3c8b58d8906d183638497942e06b536dc99 --- /dev/null +++ b/Java/SarOperation.java @@ -0,0 +1,65 @@ +/* + * Copyright ConsenSys AG. + * + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.hyperledger.besu.evm.operation; + +import static org.apache.tuweni.bytes.Bytes32.leftPad; + +import org.hyperledger.besu.evm.EVM; +import org.hyperledger.besu.evm.frame.MessageFrame; +import org.hyperledger.besu.evm.gascalculator.GasCalculator; + +import org.apache.tuweni.bytes.Bytes; +import org.apache.tuweni.bytes.Bytes32; +import org.apache.tuweni.units.bigints.UInt256; + +public class SarOperation extends AbstractFixedCostOperation { + + private static final UInt256 ALL_BITS = UInt256.MAX_VALUE; + + public SarOperation(final GasCalculator gasCalculator) { + super(0x1d, "SAR", 2, 1, 1, gasCalculator, gasCalculator.getVeryLowTierGasCost()); + } + + @Override + public Operation.OperationResult executeFixedCostOperation( + final MessageFrame frame, final EVM evm) { + + Bytes shiftAmount = frame.popStackItem(); + final Bytes value = leftPad(frame.popStackItem()); + final boolean negativeNumber = value.get(0) < 0; + if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) { + frame.pushStackItem(negativeNumber ? ALL_BITS : UInt256.ZERO); + } else { + final int shiftAmountInt = shiftAmount.toInt(); + // BUG: CWE-681 Incorrect Conversion between Numeric Types + // if (shiftAmountInt >= 256) { + // FIXED: + if (shiftAmountInt >= 256 || shiftAmountInt < 0) { + frame.pushStackItem(negativeNumber ? ALL_BITS : UInt256.ZERO); + } else { + // first perform standard shift right. + Bytes result = value.shiftRight(shiftAmountInt); + + // if a negative number, carry through the sign. + if (negativeNumber) { + final Bytes32 significantBits = ALL_BITS.shiftLeft(256 - shiftAmountInt); + result = result.or(significantBits); + } + frame.pushStackItem(result); + } + } + return successResponse; + } +} diff --git a/Java/ScooldUtils.java b/Java/ScooldUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..efb21eed08d7283cd4b71ca193347220ed627175 --- /dev/null +++ b/Java/ScooldUtils.java @@ -0,0 +1,1989 @@ +/* + * Copyright 2013-2022 Erudika. https://erudika.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. + * + * For issues and patches go to: https://github.com/erudika + */ +package com.erudika.scoold.utils; + +import com.erudika.para.client.ParaClient; +import com.erudika.para.core.Address; +import com.erudika.para.core.ParaObject; +import com.erudika.para.core.Sysprop; +import com.erudika.para.core.Tag; +import com.erudika.para.core.User; +import com.erudika.para.core.Vote; +import com.erudika.para.core.Webhook; +import com.erudika.para.core.email.Emailer; +import com.erudika.para.core.utils.Config; +import com.erudika.para.core.utils.Pager; +import com.erudika.para.core.utils.Para; +import com.erudika.para.core.utils.ParaObjectUtils; +import com.erudika.para.core.utils.Utils; +import com.erudika.para.core.validation.ValidationUtils; +import com.erudika.scoold.ScooldConfig; +import static com.erudika.scoold.ScooldServer.*; +import com.erudika.scoold.core.Comment; +import com.erudika.scoold.core.Feedback; +import com.erudika.scoold.core.Post; +import static com.erudika.scoold.core.Post.ALL_MY_SPACES; +import static com.erudika.scoold.core.Post.DEFAULT_SPACE; +import com.erudika.scoold.core.Profile; +import static com.erudika.scoold.core.Profile.Badge.ENTHUSIAST; +import static com.erudika.scoold.core.Profile.Badge.TEACHER; +import com.erudika.scoold.core.Question; +import com.erudika.scoold.core.Reply; +import com.erudika.scoold.core.Report; +import com.erudika.scoold.core.Revision; +import com.erudika.scoold.core.UnapprovedQuestion; +import com.erudika.scoold.core.UnapprovedReply; +import static com.erudika.scoold.utils.HttpUtils.getCookieValue; +import com.erudika.scoold.utils.avatars.AvatarFormat; +import com.erudika.scoold.utils.avatars.AvatarRepository; +import com.erudika.scoold.utils.avatars.AvatarRepositoryProxy; +import com.erudika.scoold.utils.avatars.GravatarAvatarGenerator; +import com.nimbusds.jose.JOSEException; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.JWSSigner; +import com.nimbusds.jose.JWSVerifier; +import com.nimbusds.jose.crypto.MACSigner; +import com.nimbusds.jose.crypto.MACVerifier; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import java.io.IOException; +import java.io.InputStream; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Scanner; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Predicate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import javax.inject.Inject; +import javax.inject.Named; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.validation.ConstraintViolation; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang3.RegExUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.math.NumberUtils; +import org.apache.commons.text.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Component; + +/** + * + * @author Alex Bogdanovski [alex@erudika.com] + */ +@Component +@Named +public final class ScooldUtils { + + private static final Logger logger = LoggerFactory.getLogger(ScooldUtils.class); + private static final Map FILE_CACHE = new ConcurrentHashMap(); + private static final Set APPROVED_DOMAINS = new HashSet<>(); + private static final Set ADMINS = new HashSet<>(); + private static final String EMAIL_ALERTS_PREFIX = "email-alerts" + Para.getConfig().separator(); + + private static final Profile API_USER; + private static final Set CORE_TYPES; + private static final Set HOOK_EVENTS; + private static final Map WHITELISTED_MACROS; + private static final Map API_KEYS = new LinkedHashMap<>(); // jti => jwt + + private List allSpaces; + + private static final ScooldConfig CONF = new ScooldConfig(); + + static { + API_USER = new Profile("1", "System"); + API_USER.setVotes(1); + API_USER.setCreatorid("1"); + API_USER.setTimestamp(Utils.timestamp()); + API_USER.setGroups(User.Groups.ADMINS.toString()); + + CORE_TYPES = new HashSet<>(Arrays.asList(Utils.type(Comment.class), + Utils.type(Feedback.class), + Utils.type(Profile.class), + Utils.type(Question.class), + Utils.type(Reply.class), + Utils.type(Report.class), + Utils.type(Revision.class), + Utils.type(UnapprovedQuestion.class), + Utils.type(UnapprovedReply.class), + // Para core types + Utils.type(Address.class), + Utils.type(Sysprop.class), + Utils.type(Tag.class), + Utils.type(User.class), + Utils.type(Vote.class) + )); + + HOOK_EVENTS = new HashSet<>(Arrays.asList( + "question.create", + "question.close", + "answer.create", + "answer.accept", + "report.create", + "comment.create", + "user.signup", + "revision.restore")); + + WHITELISTED_MACROS = new HashMap(); + WHITELISTED_MACROS.put("spaces", "#spacespage($spaces)"); + WHITELISTED_MACROS.put("webhooks", "#webhookspage($webhooks)"); + WHITELISTED_MACROS.put("comments", "#commentspage($commentslist)"); + WHITELISTED_MACROS.put("simplecomments", "#simplecommentspage($commentslist)"); + WHITELISTED_MACROS.put("postcomments", "#commentspage($showpost.comments)"); + WHITELISTED_MACROS.put("replies", "#answerspage($answerslist $showPost)"); + WHITELISTED_MACROS.put("feedback", "#questionspage($feedbacklist)"); + WHITELISTED_MACROS.put("people", "#peoplepage($userlist)"); + WHITELISTED_MACROS.put("questions", "#questionspage($questionslist)"); + WHITELISTED_MACROS.put("compactanswers", "#compactanswerspage($answerslist)"); + WHITELISTED_MACROS.put("answers", "#answerspage($answerslist)"); + WHITELISTED_MACROS.put("reports", "#reportspage($reportslist)"); + WHITELISTED_MACROS.put("revisions", "#revisionspage($revisionslist $showPost)"); + WHITELISTED_MACROS.put("tags", "#tagspage($tagslist)"); + } + + private final ParaClient pc; + private final LanguageUtils langutils; + private final AvatarRepository avatarRepository; + private final GravatarAvatarGenerator gravatarAvatarGenerator; + private static ScooldUtils instance; + private Sysprop customTheme; + @Inject private Emailer emailer; + + @Inject + public ScooldUtils(ParaClient pc, LanguageUtils langutils, AvatarRepositoryProxy avatarRepository, + GravatarAvatarGenerator gravatarAvatarGenerator) { + this.pc = pc; + this.langutils = langutils; + this.avatarRepository = avatarRepository; + this.gravatarAvatarGenerator = gravatarAvatarGenerator; + API_USER.setPicture(avatarRepository.getAnonymizedLink(CONF.supportEmail())); + } + + public ParaClient getParaClient() { + return pc; + } + + public LanguageUtils getLangutils() { + return langutils; + } + + public static ScooldUtils getInstance() { + return instance; + } + + static void setInstance(ScooldUtils instance) { + ScooldUtils.instance = instance; + } + + public static ScooldConfig getConfig() { + return CONF; + } + + static { + // multiple domains/admins are allowed only in Scoold PRO + String approvedDomain = StringUtils.substringBefore(CONF.approvedDomainsForSignups(), ","); + if (!StringUtils.isBlank(approvedDomain)) { + APPROVED_DOMAINS.add(approvedDomain); + } + // multiple admins are allowed only in Scoold PRO + String admin = StringUtils.substringBefore(CONF.admins(), ","); + if (!StringUtils.isBlank(admin)) { + ADMINS.add(admin); + } + } + + public static void tryConnectToPara(Callable callable) { + retryConnection(callable, 0); + } + + private static void retryConnection(Callable callable, int retryCount) { + try { + if (!callable.call()) { + throw new Exception(); + } else if (retryCount > 0) { + logger.info("Connected to Para backend."); + } + } catch (Exception e) { + int maxRetries = CONF.paraConnectionRetryAttempts(); + int retryInterval = CONF.paraConnectionRetryIntervalSec(); + int count = ++retryCount; + logger.error("No connection to Para backend. Retrying connection in {}s (attempt {} of {})...", + retryInterval, count, maxRetries); + if (maxRetries < 0 || retryCount < maxRetries) { + Para.asyncExecute(() -> { + try { + Thread.sleep(retryInterval * 1000L); + } catch (InterruptedException ex) { + logger.error(null, ex); + Thread.currentThread().interrupt(); + } + retryConnection(callable, count); + }); + } + } + } + + public ParaObject checkAuth(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { + Profile authUser = null; + String jwt = HttpUtils.getStateParam(CONF.authCookie(), req); + if (isApiRequest(req)) { + return checkApiAuth(req); + } else if (jwt != null && !StringUtils.endsWithAny(req.getRequestURI(), + ".js", ".css", ".svg", ".png", ".jpg", ".ico", ".gif", ".woff2", ".woff", "people/avatar")) { + User u = pc.me(jwt); + if (u != null && isEmailDomainApproved(u.getEmail())) { + authUser = getOrCreateProfile(u, req); + authUser.setUser(u); + authUser.setOriginalPicture(u.getPicture()); + boolean updatedRank = promoteOrDemoteUser(authUser, u); + boolean updatedProfile = updateProfilePictureAndName(authUser, u); + if (updatedRank || updatedProfile) { + authUser.update(); + } + } else { + clearSession(req, res); + logger.info("Invalid JWT found in cookie {}.", CONF.authCookie()); + res.sendRedirect(CONF.serverUrl() + CONF.serverContextPath() + SIGNINLINK + "?code=3&error=true"); + return null; + } + } + return authUser; + } + + private ParaObject checkApiAuth(HttpServletRequest req) { + if (req.getRequestURI().equals(CONF.serverContextPath() + "/api")) { + return null; + } + String apiKeyJWT = StringUtils.removeStart(req.getHeader(HttpHeaders.AUTHORIZATION), "Bearer "); + if (req.getRequestURI().equals(CONF.serverContextPath() + "/api/ping")) { + return API_USER; + } else if (req.getRequestURI().equals(CONF.serverContextPath() + "/api/stats") && isValidJWToken(apiKeyJWT)) { + return API_USER; + } else if (!isApiEnabled() || StringUtils.isBlank(apiKeyJWT) || !isValidJWToken(apiKeyJWT)) { + throw new UnauthorizedException(); + } + return API_USER; + } + + private boolean promoteOrDemoteUser(Profile authUser, User u) { + if (authUser != null) { + if (!isAdmin(authUser) && isRecognizedAsAdmin(u)) { + logger.info("User '{}' with id={} promoted to admin.", u.getName(), authUser.getId()); + authUser.setGroups(User.Groups.ADMINS.toString()); + return true; + } else if (isAdmin(authUser) && !isRecognizedAsAdmin(u)) { + logger.info("User '{}' with id={} demoted to regular user.", u.getName(), authUser.getId()); + authUser.setGroups(User.Groups.USERS.toString()); + return true; + } else if (!isMod(authUser) && u.isModerator()) { + authUser.setGroups(User.Groups.MODS.toString()); + return true; + } + } + return false; + } + + private Profile getOrCreateProfile(User u, HttpServletRequest req) { + Profile authUser = pc.read(Profile.id(u.getId())); + if (authUser == null) { + authUser = Profile.fromUser(u); + authUser.create(); + if (!u.getIdentityProvider().equals("generic")) { + sendWelcomeEmail(u, false, req); + } + Map payload = new LinkedHashMap<>(ParaObjectUtils.getAnnotatedFields(authUser, false)); + payload.put("user", u); + triggerHookEvent("user.signup", payload); + logger.info("Created new user '{}' with id={}, groups={}, spaces={}.", + u.getName(), authUser.getId(), authUser.getGroups(), authUser.getSpaces()); + } + return authUser; + } + + private boolean updateProfilePictureAndName(Profile authUser, User u) { + boolean update = false; + if (!StringUtils.equals(u.getPicture(), authUser.getPicture()) + && !gravatarAvatarGenerator.isLink(authUser.getPicture()) + && !CONF.avatarEditsEnabled()) { + authUser.setPicture(u.getPicture()); + update = true; + } + if (!CONF.nameEditsEnabled() && !StringUtils.equals(u.getName(), authUser.getName())) { + // BUG: NVD-CWE-Other Other + // authUser.setName(u.getName()); + // FIXED: + authUser.setName(StringUtils.abbreviate(u.getName(), 256)); + update = true; + } + if (!StringUtils.equals(u.getName(), authUser.getOriginalName())) { + authUser.setOriginalName(u.getName()); + update = true; + } + return update; + } + + public boolean isDarkModeEnabled(Profile authUser, HttpServletRequest req) { + return (authUser != null && authUser.getDarkmodeEnabled()) || + "1".equals(HttpUtils.getCookieValue(req, "dark-mode")); + } + + private String getDefaultEmailSignature(String defaultText) { + String template = CONF.emailsDefaultSignatureText(defaultText); + return Utils.formatMessage(template, CONF.appName()); + } + + public void sendWelcomeEmail(User user, boolean verifyEmail, HttpServletRequest req) { + // send welcome email notification + if (user != null) { + Map model = new HashMap(); + Map lang = getLang(req); + String subject = Utils.formatMessage(lang.get("signin.welcome"), CONF.appName()); + String body1 = Utils.formatMessage(CONF.emailsWelcomeText1(lang), CONF.appName()); + String body2 = CONF.emailsWelcomeText2(lang); + String body3 = getDefaultEmailSignature(CONF.emailsWelcomeText3(lang)); + + if (verifyEmail && !user.getActive() && !StringUtils.isBlank(user.getIdentifier())) { + Sysprop s = pc.read(user.getIdentifier()); + if (s != null) { + String token = Utils.base64encURL(Utils.generateSecurityToken().getBytes()); + s.addProperty(Config._EMAIL_TOKEN, token); + pc.update(s); + token = CONF.serverUrl() + CONF.serverContextPath() + SIGNINLINK + "/register?id=" + user.getId() + "&token=" + token; + body3 = "" + lang.get("signin.welcome.verify") + "

" + body3; + } + } + + model.put("subject", escapeHtml(subject)); + model.put("logourl", getSmallLogoUrl()); + model.put("heading", Utils.formatMessage(lang.get("signin.welcome.title"), escapeHtml(user.getName()))); + model.put("body", body1 + body2 + body3); + emailer.sendEmail(Arrays.asList(user.getEmail()), subject, compileEmailTemplate(model)); + } + } + + public void sendVerificationEmail(Sysprop identifier, HttpServletRequest req) { + if (identifier != null) { + Map model = new HashMap(); + Map lang = getLang(req); + String subject = Utils.formatMessage(lang.get("signin.welcome"), CONF.appName()); + String body = getDefaultEmailSignature(CONF.emailsWelcomeText3(lang)); + + String token = Utils.base64encURL(Utils.generateSecurityToken().getBytes()); + identifier.addProperty(Config._EMAIL_TOKEN, token); + identifier.addProperty("confirmationTimestamp", Utils.timestamp()); + pc.update(identifier); + token = CONF.serverUrl() + CONF.serverContextPath() + SIGNINLINK + "/register?id=" + + identifier.getCreatorid() + "&token=" + token; + body = "" + lang.get("signin.welcome.verify") + "

" + body; + + model.put("subject", escapeHtml(subject)); + model.put("logourl", getSmallLogoUrl()); + model.put("heading", lang.get("hello")); + model.put("body", body); + emailer.sendEmail(Arrays.asList(identifier.getId()), subject, compileEmailTemplate(model)); + } + } + + public void sendPasswordResetEmail(String email, String token, HttpServletRequest req) { + if (email != null && token != null) { + Map model = new HashMap(); + Map lang = getLang(req); + String url = CONF.serverUrl() + CONF.serverContextPath() + SIGNINLINK + "/iforgot?email=" + email + "&token=" + token; + String subject = lang.get("iforgot.title"); + String body1 = lang.get("notification.iforgot.body1") + "

"; + String body2 = Utils.formatMessage("" + lang.get("notification.iforgot.body2") + + "

", url); + String body3 = getDefaultEmailSignature(lang.get("notification.signature") + "

"); + + model.put("subject", escapeHtml(subject)); + model.put("logourl", getSmallLogoUrl()); + model.put("heading", lang.get("hello")); + model.put("body", body1 + body2 + body3); + emailer.sendEmail(Arrays.asList(email), subject, compileEmailTemplate(model)); + } + } + + @SuppressWarnings("unchecked") + public void subscribeToNotifications(String email, String channelId) { + if (!StringUtils.isBlank(email) && !StringUtils.isBlank(channelId)) { + Sysprop s = pc.read(channelId); + if (s == null || !s.hasProperty("emails")) { + s = new Sysprop(channelId); + s.addProperty("emails", new LinkedList<>()); + } + Set emails = new HashSet<>((List) s.getProperty("emails")); + if (emails.add(email)) { + s.addProperty("emails", emails); + pc.create(s); + } + } + } + + @SuppressWarnings("unchecked") + public void unsubscribeFromNotifications(String email, String channelId) { + if (!StringUtils.isBlank(email) && !StringUtils.isBlank(channelId)) { + Sysprop s = pc.read(channelId); + if (s == null || !s.hasProperty("emails")) { + s = new Sysprop(channelId); + s.addProperty("emails", new LinkedList<>()); + } + Set emails = new HashSet<>((List) s.getProperty("emails")); + if (emails.remove(email)) { + s.addProperty("emails", emails); + pc.create(s); + } + } + } + + @SuppressWarnings("unchecked") + public Set getNotificationSubscribers(String channelId) { + return ((List) Optional.ofNullable(((Sysprop) pc.read(channelId))). + orElse(new Sysprop()).getProperties().getOrDefault("emails", Collections.emptyList())). + stream().collect(Collectors.toSet()); + } + + public void unsubscribeFromAllNotifications(Profile p) { + User u = p.getUser(); + if (u != null) { + unsubscribeFromNewPosts(u); + } + } + + public boolean isEmailDomainApproved(String email) { + if (StringUtils.isBlank(email)) { + return false; + } + if (!APPROVED_DOMAINS.isEmpty() && !APPROVED_DOMAINS.contains(StringUtils.substringAfter(email, "@"))) { + logger.warn("Attempted signin from an unknown domain - email {} is part of an unapproved domain.", email); + return false; + } + return true; + } + + public Object isSubscribedToNewPosts(HttpServletRequest req) { + if (!isNewPostNotificationAllowed()) { + return false; + } + + Profile authUser = getAuthUser(req); + if (authUser != null) { + User u = authUser.getUser(); + if (u != null) { + return getNotificationSubscribers(EMAIL_ALERTS_PREFIX + "new_post_subscribers").contains(u.getEmail()); + } + } + return false; + } + + public void subscribeToNewPosts(User u) { + if (u != null) { + subscribeToNotifications(u.getEmail(), EMAIL_ALERTS_PREFIX + "new_post_subscribers"); + } + } + + public void unsubscribeFromNewPosts(User u) { + if (u != null) { + unsubscribeFromNotifications(u.getEmail(), EMAIL_ALERTS_PREFIX + "new_post_subscribers"); + } + } + + private Map buildProfilesMap(List users) { + if (users != null && !users.isEmpty()) { + Map userz = users.stream().collect(Collectors.toMap(u -> u.getId(), u -> u)); + List profiles = pc.readAll(userz.keySet().stream(). + map(uid -> Profile.id(uid)).collect(Collectors.toList())); + Map profilesMap = new HashMap(users.size()); + profiles.forEach(pr -> profilesMap.put(userz.get(pr.getCreatorid()).getEmail(), pr)); + return profilesMap; + } + return Collections.emptyMap(); + } + + private void sendEmailsToSubscribersInSpace(Set emails, String space, String subject, String html) { + int i = 0; + int max = CONF.maxItemsPerPage(); + List terms = new ArrayList<>(max); + for (String email : emails) { + terms.add(email); + if (++i == max) { + emailer.sendEmail(buildProfilesMap(pc.findTermInList(Utils.type(User.class), Config._EMAIL, terms)). + entrySet().stream().filter(e -> canAccessSpace(e.getValue(), space) && + !isIgnoredSpaceForNotifications(e.getValue(), space)). + map(e -> e.getKey()).collect(Collectors.toList()), subject, html); + i = 0; + terms.clear(); + } + } + if (!terms.isEmpty()) { + emailer.sendEmail(buildProfilesMap(pc.findTermInList(Utils.type(User.class), Config._EMAIL, terms)). + entrySet().stream().filter(e -> canAccessSpace(e.getValue(), space) && + !isIgnoredSpaceForNotifications(e.getValue(), space)). + map(e -> e.getKey()).collect(Collectors.toList()), subject, html); + } + } + + private Set getFavTagsSubscribers(List tags) { + if (!tags.isEmpty()) { + Set emails = new LinkedHashSet<>(); + // find all user objects even if there are more than 10000 users in the system + Pager pager = new Pager(1, "_docid", false, CONF.maxItemsPerPage()); + List profiles; + do { + profiles = pc.findQuery(Utils.type(Profile.class), + "properties.favtags:(" + tags.stream(). + map(t -> "\"".concat(t).concat("\"")).distinct(). + collect(Collectors.joining(" ")) + ") AND properties.favtagsEmailsEnabled:true", pager); + if (!profiles.isEmpty()) { + List users = pc.readAll(profiles.stream().map(p -> p.getCreatorid()). + distinct().collect(Collectors.toList())); + + users.stream().forEach(u -> emails.add(u.getEmail())); + } + } while (!profiles.isEmpty()); + return emails; + } + return Collections.emptySet(); + } + + @SuppressWarnings("unchecked") + public void sendUpdatedFavTagsNotifications(Post question, List addedTags, HttpServletRequest req) { + if (!isFavTagsNotificationAllowed()) { + return; + } + // sends a notification to subscibers of a tag if that tag was added to an existing question + if (question != null && !question.isReply() && addedTags != null && !addedTags.isEmpty()) { + Profile postAuthor = question.getAuthor(); // the current user - same as utils.getAuthUser(req) + Map model = new HashMap(); + Map lang = getLang(req); + String name = postAuthor.getName(); + String body = Utils.markdownToHtml(question.getBody()); + String picture = Utils.formatMessage("", escapeHtmlAttribute(avatarRepository. + getLink(postAuthor, AvatarFormat.Square25))); + String postURL = CONF.serverUrl() + question.getPostLink(false, false); + String tagsString = Optional.ofNullable(question.getTags()).orElse(Collections.emptyList()).stream(). + map(t -> "" + + (addedTags.contains(t) ? "" + escapeHtml(t) + "" : escapeHtml(t)) + ""). + collect(Collectors.joining(" ")); + String subject = Utils.formatMessage(lang.get("notification.favtags.subject"), name, + Utils.abbreviate(question.getTitle(), 255)); + model.put("subject", escapeHtml(subject)); + model.put("logourl", getSmallLogoUrl()); + model.put("heading", Utils.formatMessage(lang.get("notification.favtags.heading"), picture, escapeHtml(name))); + model.put("body", Utils.formatMessage("

{1}

{2}

{3}", + postURL, escapeHtml(question.getTitle()), body, tagsString)); + + Set emails = getFavTagsSubscribers(addedTags); + sendEmailsToSubscribersInSpace(emails, question.getSpace(), subject, compileEmailTemplate(model)); + } + } + + @SuppressWarnings("unchecked") + public void sendNewPostNotifications(Post question, HttpServletRequest req) { + if (question == null) { + return; + } + // the current user - same as utils.getAuthUser(req) + Profile postAuthor = question.getAuthor() != null ? question.getAuthor() : pc.read(question.getCreatorid()); + if (!question.getType().equals(Utils.type(UnapprovedQuestion.class))) { + if (!isNewPostNotificationAllowed()) { + return; + } + + Map model = new HashMap(); + Map lang = getLang(req); + String name = postAuthor.getName(); + String body = Utils.markdownToHtml(question.getBody()); + String picture = Utils.formatMessage("", escapeHtmlAttribute(avatarRepository. + getLink(postAuthor, AvatarFormat.Square25))); + String postURL = CONF.serverUrl() + question.getPostLink(false, false); + String tagsString = Optional.ofNullable(question.getTags()).orElse(Collections.emptyList()).stream(). + map(t -> "" + escapeHtml(t) + ""). + collect(Collectors.joining(" ")); + String subject = Utils.formatMessage(lang.get("notification.newposts.subject"), name, + Utils.abbreviate(question.getTitle(), 255)); + model.put("subject", escapeHtml(subject)); + model.put("logourl", getSmallLogoUrl()); + model.put("heading", Utils.formatMessage(lang.get("notification.newposts.heading"), picture, escapeHtml(name))); + model.put("body", Utils.formatMessage("

{1}

{2}

{3}", + postURL, escapeHtml(question.getTitle()), body, tagsString)); + + Set emails = new HashSet(getNotificationSubscribers(EMAIL_ALERTS_PREFIX + "new_post_subscribers")); + emails.addAll(getFavTagsSubscribers(question.getTags())); + sendEmailsToSubscribersInSpace(emails, question.getSpace(), subject, compileEmailTemplate(model)); + } else if (postsNeedApproval() && question instanceof UnapprovedQuestion) { + Report rep = new Report(); + rep.setDescription("New question awaiting approval"); + rep.setSubType(Report.ReportType.OTHER); + rep.setLink(question.getPostLink(false, false)); + rep.setAuthorName(postAuthor.getName()); + rep.create(); + } + } + + public void sendReplyNotifications(Post parentPost, Post reply, HttpServletRequest req) { + // send email notification to author of post except when the reply is by the same person + if (parentPost != null && reply != null && !StringUtils.equals(parentPost.getCreatorid(), reply.getCreatorid())) { + Profile replyAuthor = reply.getAuthor(); // the current user - same as utils.getAuthUser(req) + Map model = new HashMap(); + Map lang = getLang(req); + String name = replyAuthor.getName(); + String body = Utils.markdownToHtml(reply.getBody()); + String picture = Utils.formatMessage("", escapeHtmlAttribute(avatarRepository. + getLink(replyAuthor, AvatarFormat.Square25))); + String postURL = CONF.serverUrl() + parentPost.getPostLink(false, false); + String subject = Utils.formatMessage(lang.get("notification.reply.subject"), name, + Utils.abbreviate(reply.getTitle(), 255)); + model.put("subject", escapeHtml(subject)); + model.put("logourl", getSmallLogoUrl()); + model.put("heading", Utils.formatMessage(lang.get("notification.reply.heading"), + Utils.formatMessage("{1}", postURL, escapeHtml(parentPost.getTitle())))); + model.put("body", Utils.formatMessage("

{0} {1}:

{2}
", picture, escapeHtml(name), body)); + + Profile authorProfile = pc.read(parentPost.getCreatorid()); + if (authorProfile != null) { + User author = authorProfile.getUser(); + if (author != null) { + if (authorProfile.getReplyEmailsEnabled()) { + parentPost.addFollower(author); + } + } + } + + if (postsNeedApproval() && reply instanceof UnapprovedReply) { + Report rep = new Report(); + rep.setDescription("New reply awaiting approval"); + rep.setSubType(Report.ReportType.OTHER); + rep.setLink(parentPost.getPostLink(false, false) + "#post-" + reply.getId()); + rep.setAuthorName(reply.getAuthor().getName()); + rep.create(); + } + + if (isReplyNotificationAllowed() && parentPost.hasFollowers()) { + emailer.sendEmail(new ArrayList(parentPost.getFollowers().values()), + subject, + compileEmailTemplate(model)); + } + } + } + + public void sendCommentNotifications(Post parentPost, Comment comment, Profile commentAuthor, HttpServletRequest req) { + // send email notification to author of post except when the comment is by the same person + if (parentPost != null && comment != null) { + parentPost.setAuthor(pc.read(Profile.id(parentPost.getCreatorid()))); // parent author is not current user (authUser) + Map payload = new LinkedHashMap<>(ParaObjectUtils.getAnnotatedFields(comment, false)); + payload.put("parent", parentPost); + payload.put("author", commentAuthor); + triggerHookEvent("comment.create", payload); + // get the last 5-6 commentators who want to be notified - https://github.com/Erudika/scoold/issues/201 + Pager p = new Pager(1, Config._TIMESTAMP, false, 5); + boolean isCommentatorThePostAuthor = StringUtils.equals(parentPost.getCreatorid(), comment.getCreatorid()); + Set last5ids = pc.findChildren(parentPost, Utils.type(Comment.class), + "!(" + Config._CREATORID + ":\"" + comment.getCreatorid() + "\")", p). + stream().map(c -> c.getCreatorid()).distinct().collect(Collectors.toSet()); + if (!isCommentatorThePostAuthor && !last5ids.contains(parentPost.getCreatorid())) { + last5ids = new HashSet<>(last5ids); + last5ids.add(parentPost.getCreatorid()); + } + Map lang = getLang(req); + List last5commentators = pc.readAll(new ArrayList<>(last5ids)); + last5commentators = last5commentators.stream().filter(u -> u.getCommentEmailsEnabled()).collect(Collectors.toList()); + pc.readAll(last5commentators.stream().map(u -> u.getCreatorid()).collect(Collectors.toList())).forEach(author -> { + if (isCommentNotificationAllowed()) { + Map model = new HashMap(); + String name = commentAuthor.getName(); + String body = Utils.markdownToHtml(comment.getComment()); + String pic = Utils.formatMessage("", + escapeHtmlAttribute(avatarRepository.getLink(commentAuthor, AvatarFormat.Square25))); + String postURL = CONF.serverUrl() + parentPost.getPostLink(false, false); + String subject = Utils.formatMessage(lang.get("notification.comment.subject"), name, parentPost.getTitle()); + model.put("subject", escapeHtml(subject)); + model.put("logourl", getSmallLogoUrl()); + model.put("heading", Utils.formatMessage(lang.get("notification.comment.heading"), + Utils.formatMessage("{1}", postURL, escapeHtml(parentPost.getTitle())))); + model.put("body", Utils.formatMessage("

{0} {1}:

{2}
", pic, escapeHtml(name), body)); + emailer.sendEmail(Arrays.asList(((User) author).getEmail()), subject, compileEmailTemplate(model)); + } + }); + } + } + + private String escapeHtmlAttribute(String value) { + return StringUtils.trimToEmpty(value) + .replaceAll("'", "%27") + .replaceAll("\"", "%22") + .replaceAll("\\\\", ""); + } + + private String escapeHtml(String value) { + return StringEscapeUtils.escapeHtml4(value); + } + + public Profile readAuthUser(HttpServletRequest req) { + Profile authUser = null; + User u = pc.me(HttpUtils.getStateParam(CONF.authCookie(), req)); + if (u != null && isEmailDomainApproved(u.getEmail())) { + return getOrCreateProfile(u, req); + } + return authUser; + } + + public Profile getAuthUser(HttpServletRequest req) { + return (Profile) req.getAttribute(AUTH_USER_ATTRIBUTE); + } + + public boolean isAuthenticated(HttpServletRequest req) { + return getAuthUser(req) != null; + } + + public boolean isFeedbackEnabled() { + return CONF.feedbackEnabled(); + } + + public boolean isNearMeFeatureEnabled() { + return CONF.postsNearMeEnabled(); + } + + public boolean isDefaultSpacePublic() { + return CONF.isDefaultSpacePublic(); + } + + public boolean isWebhooksEnabled() { + return CONF.webhooksEnabled(); + } + + public boolean isAnonymityEnabled() { + return CONF.profileAnonimityEnabled(); + } + + public boolean isApiEnabled() { + return CONF.apiEnabled(); + } + + public boolean isFooterLinksEnabled() { + return CONF.footerLinksEnabled(); + } + + public boolean isNotificationsAllowed() { + return CONF.notificationEmailsAllowed(); + } + + public boolean isNewPostNotificationAllowed() { + return isNotificationsAllowed() && CONF.emailsForNewPostsAllowed(); + } + + public boolean isFavTagsNotificationAllowed() { + return isNotificationsAllowed() && CONF.emailsForFavtagsAllowed(); + } + + public boolean isReplyNotificationAllowed() { + return isNotificationsAllowed() && CONF.emailsForRepliesAllowed(); + } + + public boolean isCommentNotificationAllowed() { + return isNotificationsAllowed() && CONF.emailsForCommentsAllowed(); + } + + public boolean isDarkModeEnabled() { + return CONF.darkModeEnabled(); + } + + public boolean isSlackAuthEnabled() { + return CONF.slackAuthEnabled(); + } + + public static boolean isGravatarEnabled() { + return CONF.gravatarsEnabled(); + } + + public static String gravatarPattern() { + return CONF.gravatarsPattern(); + } + + public static String getDefaultAvatar() { + return CONF.imagesLink() + "/anon.svg"; + } + + public static boolean isAvatarUploadsEnabled() { + return isImgurAvatarRepositoryEnabled() || isCloudinaryAvatarRepositoryEnabled(); + } + + public static boolean isImgurAvatarRepositoryEnabled() { + return !StringUtils.isBlank(CONF.imgurClientId()) && "imgur".equalsIgnoreCase(CONF.avatarRepository()); + } + + public static boolean isCloudinaryAvatarRepositoryEnabled() { + return !StringUtils.isBlank(CONF.cloudinaryUrl()) && "cloudinary".equalsIgnoreCase(CONF.avatarRepository()); + } + + public String getFooterHTML() { + return CONF.footerHtml(); + } + + public boolean isNavbarLink1Enabled() { + return !StringUtils.isBlank(getNavbarLink1URL()); + } + + public String getNavbarLink1URL() { + return CONF.navbarCustomLink1Url(); + } + + public String getNavbarLink1Text() { + return CONF.navbarCustomLink1Text(); + } + + public boolean isNavbarLink2Enabled() { + return !StringUtils.isBlank(getNavbarLink2URL()); + } + + public String getNavbarLink2URL() { + return CONF.navbarCustomLink2Url(); + } + + public String getNavbarLink2Text() { + return CONF.navbarCustomLink2Text(); + } + + public boolean isNavbarMenuLink1Enabled() { + return !StringUtils.isBlank(getNavbarMenuLink1URL()); + } + + public String getNavbarMenuLink1URL() { + return CONF.navbarCustomMenuLink1Url(); + } + + public String getNavbarMenuLink1Text() { + return CONF.navbarCustomMenuLink1Text(); + } + + public boolean isNavbarMenuLink2Enabled() { + return !StringUtils.isBlank(getNavbarMenuLink2URL()); + } + + public String getNavbarMenuLink2URL() { + return CONF.navbarCustomMenuLink2Url(); + } + + public String getNavbarMenuLink2Text() { + return CONF.navbarCustomMenuLink2Text(); + } + + public boolean alwaysHideCommentForms() { + return CONF.alwaysHideCommentForms(); + } + + public Set getCoreScooldTypes() { + return Collections.unmodifiableSet(CORE_TYPES); + } + + public Set getCustomHookEvents() { + return Collections.unmodifiableSet(HOOK_EVENTS); + } + + public Pager getPager(String pageParamName, HttpServletRequest req) { + return pagerFromParams(pageParamName, req); + } + + public Pager pagerFromParams(HttpServletRequest req) { + return pagerFromParams("page", req); + } + + public Pager pagerFromParams(String pageParamName, HttpServletRequest req) { + Pager p = new Pager(CONF.maxItemsPerPage()); + p.setPage(Math.min(NumberUtils.toLong(req.getParameter(pageParamName), 1), CONF.maxPages())); + p.setLimit(NumberUtils.toInt(req.getParameter("limit"), CONF.maxItemsPerPage())); + String lastKey = req.getParameter("lastKey"); + String sort = req.getParameter("sortby"); + String desc = req.getParameter("desc"); + if (!StringUtils.isBlank(desc)) { + p.setDesc(Boolean.parseBoolean(desc)); + } + if (!StringUtils.isBlank(lastKey)) { + p.setLastKey(lastKey); + } + if (!StringUtils.isBlank(sort)) { + p.setSortby(sort); + } + return p; + } + + public String getLanguageCode(HttpServletRequest req) { + String langCodeFromConfig = CONF.defaultLanguageCode(); + String cookieLoc = getCookieValue(req, CONF.localeCookie()); + Locale fromReq = (req == null) ? Locale.getDefault() : req.getLocale(); + Locale requestLocale = langutils.getProperLocale(fromReq.toString()); + return (cookieLoc != null) ? cookieLoc : (StringUtils.isBlank(langCodeFromConfig) ? + requestLocale.getLanguage() : langutils.getProperLocale(langCodeFromConfig).getLanguage()); + } + + public Locale getCurrentLocale(String langname) { + Locale currentLocale = langutils.getProperLocale(langname); + if (currentLocale == null) { + currentLocale = langutils.getProperLocale(langutils.getDefaultLanguageCode()); + } + return currentLocale; + } + + public Map getLang(HttpServletRequest req) { + return getLang(getCurrentLocale(getLanguageCode(req))); + } + + public Map getLang(Locale currentLocale) { + Map lang = langutils.readLanguage(currentLocale.toString()); + if (lang == null || lang.isEmpty()) { + lang = langutils.getDefaultLanguage(); + } + return lang; + } + + public boolean isLanguageRTL(String langCode) { + return StringUtils.equalsAnyIgnoreCase(langCode, "ar", "he", "dv", "iw", "fa", "ps", "sd", "ug", "ur", "yi"); + } + + public void fetchProfiles(List objects) { + if (objects == null || objects.isEmpty()) { + return; + } + Map authorids = new HashMap(objects.size()); + Map authors = new HashMap(objects.size()); + for (ParaObject obj : objects) { + if (obj.getCreatorid() != null) { + authorids.put(obj.getId(), obj.getCreatorid()); + } + } + List ids = new ArrayList(new HashSet(authorids.values())); + if (ids.isEmpty()) { + return; + } + // read all post authors in batch + for (ParaObject author : pc.readAll(ids)) { + authors.put(author.getId(), (Profile) author); + } + // add system profile + authors.put(API_USER.getId(), API_USER); + // set author object for each post + for (ParaObject obj : objects) { + if (obj instanceof Post) { + ((Post) obj).setAuthor(authors.get(authorids.get(obj.getId()))); + } else if (obj instanceof Revision) { + ((Revision) obj).setAuthor(authors.get(authorids.get(obj.getId()))); + } + } + } + + //get the comments for each answer and the question + public void getComments(List allPosts) { + Map> allComments = new HashMap>(); + List allCommentIds = new ArrayList(); + List forUpdate = new ArrayList(allPosts.size()); + // get the comment ids of the first 5 comments for each post + for (Post post : allPosts) { + // not set => read comments if any and embed ids in post object + if (post.getCommentIds() == null) { + forUpdate.add(reloadFirstPageOfComments(post)); + allComments.put(post.getId(), post.getComments()); + } else { + // ids are set => add them to list for bulk read + allCommentIds.addAll(post.getCommentIds()); + } + } + if (!allCommentIds.isEmpty()) { + // read all comments for all posts on page in bulk + for (ParaObject comment : pc.readAll(allCommentIds)) { + List postComments = allComments.get(comment.getParentid()); + if (postComments == null) { + allComments.put(comment.getParentid(), new ArrayList()); + } + allComments.get(comment.getParentid()).add((Comment) comment); + } + } + // embed comments in each post for use within the view + for (Post post : allPosts) { + List cl = allComments.get(post.getId()); + long clSize = (cl == null) ? 0 : cl.size(); + if (post.getCommentIds().size() != clSize) { + forUpdate.add(reloadFirstPageOfComments(post)); + clSize = post.getComments().size(); + } else { + post.setComments(cl); + if (clSize == post.getItemcount().getLimit() && pc.getCount(Utils.type(Comment.class), + Collections.singletonMap("parentid", post.getId())) > clSize) { + clSize++; // hack to show the "more" button + } + } + post.getItemcount().setCount(clSize); + } + if (!forUpdate.isEmpty()) { + pc.updateAll(allPosts); + } + } + + public Post reloadFirstPageOfComments(Post post) { + List commentz = pc.getChildren(post, Utils.type(Comment.class), post.getItemcount()); + ArrayList ids = new ArrayList(commentz.size()); + for (Comment comment : commentz) { + ids.add(comment.getId()); + } + post.setCommentIds(ids); + post.setComments(commentz); + return post; + } + + public void updateViewCount(Post showPost, HttpServletRequest req, HttpServletResponse res) { + //do not count views from author + if (showPost != null && !isMine(showPost, getAuthUser(req))) { + String postviews = StringUtils.trimToEmpty(HttpUtils.getStateParam("postviews", req)); + if (!StringUtils.contains(postviews, showPost.getId())) { + long views = (showPost.getViewcount() == null) ? 0 : showPost.getViewcount(); + showPost.setViewcount(views + 1); //increment count + HttpUtils.setStateParam("postviews", (postviews.isEmpty() ? "" : postviews + ".") + showPost.getId(), + req, res); + pc.update(showPost); + } + } + } + + public List getSimilarPosts(Post showPost, Pager pager) { + List similarquestions = Collections.emptyList(); + if (!showPost.isReply()) { + String likeTxt = Utils.stripAndTrim((showPost.getTitle() + " " + showPost.getBody())); + if (likeTxt.length() > 1000) { + // read object on the server to prevent "URI too long" errors + similarquestions = pc.findSimilar(showPost.getType(), showPost.getId(), + new String[]{"properties.title", "properties.body", "properties.tags"}, + "id:" + showPost.getId(), pager); + } else if (!StringUtils.isBlank(likeTxt)) { + similarquestions = pc.findSimilar(showPost.getType(), showPost.getId(), + new String[]{"properties.title", "properties.body", "properties.tags"}, likeTxt, pager); + } + } + return similarquestions; + } + + public String getFirstLinkInPost(String postBody) { + postBody = StringUtils.trimToEmpty(postBody); + Pattern p = Pattern.compile("^!?\\[.*\\]\\((.+)\\)"); + Matcher m = p.matcher(postBody); + + if (m.find()) { + return m.group(1); + } + return ""; + } + + public boolean param(HttpServletRequest req, String param) { + return req.getParameter(param) != null; + } + + public boolean isAjaxRequest(HttpServletRequest req) { + return req.getHeader("X-Requested-With") != null || req.getParameter("X-Requested-With") != null; + } + + public boolean isApiRequest(HttpServletRequest req) { + return req.getRequestURI().startsWith(CONF.serverContextPath() + "/api/") || req.getRequestURI().equals(CONF.serverContextPath() + "/api"); + } + + public boolean isAdmin(Profile authUser) { + return authUser != null && User.Groups.ADMINS.toString().equals(authUser.getGroups()); + } + + public boolean isMod(Profile authUser) { + return authUser != null && (isAdmin(authUser) || User.Groups.MODS.toString().equals(authUser.getGroups())); + } + + public boolean isRecognizedAsAdmin(User u) { + return u.isAdmin() || ADMINS.contains(u.getIdentifier()) || + ADMINS.stream().filter(s -> s.equalsIgnoreCase(u.getEmail())).findAny().isPresent(); + } + + public boolean canComment(Profile authUser, HttpServletRequest req) { + return isAuthenticated(req) && ((authUser.hasBadge(ENTHUSIAST) || CONF.newUsersCanComment() || isMod(authUser))); + } + + public boolean postsNeedApproval() { + return CONF.postsNeedApproval(); + } + + public boolean postNeedsApproval(Profile authUser) { + return postsNeedApproval() && authUser.getVotes() < CONF.postsReputationThreshold() && !isMod(authUser); + } + + public String getWelcomeMessage(Profile authUser) { + return authUser == null ? CONF.welcomeMessage() : ""; + } + + public String getWelcomeMessageOnLogin(Profile authUser) { + if (authUser == null) { + return ""; + } + String welcomeMsgOnlogin = CONF.welcomeMessageOnLogin(); + if (StringUtils.contains(welcomeMsgOnlogin, "{{")) { + welcomeMsgOnlogin = Utils.compileMustache(Collections.singletonMap("user", + ParaObjectUtils.getAnnotatedFields(authUser, false)), welcomeMsgOnlogin); + } + return welcomeMsgOnlogin; + } + + public boolean isDefaultSpace(String space) { + return DEFAULT_SPACE.equalsIgnoreCase(getSpaceId(space)); + } + + public String getDefaultSpace() { + return DEFAULT_SPACE; + } + + public boolean isAllSpaces(String space) { + return ALL_MY_SPACES.equalsIgnoreCase(getSpaceId(space)); + } + + public List getAllSpaces() { + if (allSpaces == null) { + allSpaces = new LinkedList<>(pc.findQuery("scooldspace", "*", new Pager(Config.DEFAULT_LIMIT))); + } + return allSpaces; + } + + public boolean canAccessSpace(Profile authUser, String targetSpaceId) { + if (authUser == null) { + return isDefaultSpacePublic() && isDefaultSpace(targetSpaceId); + } + if (isMod(authUser) || isAllSpaces(targetSpaceId)) { + return true; + } + if (StringUtils.isBlank(targetSpaceId) || targetSpaceId.length() < 2) { + return false; + } + // this is confusing - let admins control who is in the default space + //if (isDefaultSpace(targetSpaceId)) { + // // can user access the default space (blank) + // return isDefaultSpacePublic() || isMod(authUser) || !authUser.hasSpaces(); + //} + boolean isMemberOfSpace = false; + for (String space : authUser.getSpaces()) { + String spaceId = getSpaceId(targetSpaceId); + if (StringUtils.startsWithIgnoreCase(space, spaceId + Para.getConfig().separator()) || space.equalsIgnoreCase(spaceId)) { + isMemberOfSpace = true; + break; + } + } + return isMemberOfSpace; + } + + private boolean isIgnoredSpaceForNotifications(Profile profile, String space) { + return profile != null && !profile.getFavspaces().isEmpty() && !profile.getFavspaces().contains(getSpaceId(space)); + } + + public String getSpaceIdFromCookie(Profile authUser, HttpServletRequest req) { + if (isAdmin(authUser) && req.getParameter("space") != null) { + Sysprop s = pc.read(getSpaceId(req.getParameter("space"))); // API override + if (s != null) { + return s.getId() + Para.getConfig().separator() + s.getName(); + } + } + String spaceAttr = (String) req.getAttribute(CONF.spaceCookie()); + String spaceValue = StringUtils.isBlank(spaceAttr) ? Utils.base64dec(getCookieValue(req, CONF.spaceCookie())) : spaceAttr; + String space = getValidSpaceId(authUser, spaceValue); + return (isAllSpaces(space) && isMod(authUser)) ? DEFAULT_SPACE : verifyExistingSpace(authUser, space); + } + + public void storeSpaceIdInCookie(String space, HttpServletRequest req, HttpServletResponse res) { + // directly set the space on the requests, overriding the cookie value + // used for setting the space from a direct URL to a particular space + req.setAttribute(CONF.spaceCookie(), space); + HttpUtils.setRawCookie(CONF.spaceCookie(), Utils.base64encURL(space.getBytes()), + req, res, true, "Strict", StringUtils.isBlank(space) ? 0 : 365 * 24 * 60 * 60); + } + + public String verifyExistingSpace(Profile authUser, String space) { + if (!isDefaultSpace(space) && !isAllSpaces(space)) { + Sysprop s = pc.read(getSpaceId(space)); + if (s == null) { + if (authUser != null) { + authUser.removeSpace(space); + pc.update(authUser); + } + return DEFAULT_SPACE; + } else { + return s.getId() + Para.getConfig().separator() + s.getName(); // updates current space name in case it was renamed + } + } + return space; + } + + public String getValidSpaceIdExcludingAll(Profile authUser, String space, HttpServletRequest req) { + String s = StringUtils.isBlank(space) ? getSpaceIdFromCookie(authUser, req) : space; + return isAllSpaces(s) ? DEFAULT_SPACE : s; + } + + private String getValidSpaceId(Profile authUser, String space) { + if (authUser == null) { + return DEFAULT_SPACE; + } + String defaultSpace = authUser.hasSpaces() ? ALL_MY_SPACES : DEFAULT_SPACE; + String s = canAccessSpace(authUser, space) ? space : defaultSpace; + return StringUtils.isBlank(s) ? DEFAULT_SPACE : s; + } + + public String getSpaceName(String space) { + if (DEFAULT_SPACE.equalsIgnoreCase(space)) { + return ""; + } + return RegExUtils.replaceAll(space, "^scooldspace:[^:]+:", ""); + } + + public String getSpaceId(String space) { + if (StringUtils.isBlank(space)) { + return DEFAULT_SPACE; + } + String s = StringUtils.contains(space, Para.getConfig().separator()) ? + StringUtils.substring(space, 0, space.lastIndexOf(Para.getConfig().separator())) : "scooldspace:" + space; + return "scooldspace".equals(s) ? space : s; + } + + public String getSpaceFilteredQuery(Profile authUser, String currentSpace) { + return canAccessSpace(authUser, currentSpace) ? getSpaceFilter(authUser, currentSpace) : ""; + } + + public String getSpaceFilteredQuery(HttpServletRequest req) { + Profile authUser = getAuthUser(req); + String currentSpace = getSpaceIdFromCookie(authUser, req); + return getSpaceFilteredQuery(authUser, currentSpace); + } + + public String getSpaceFilteredQuery(HttpServletRequest req, boolean isSpaceFiltered, String spaceFilter, String defaultQuery) { + Profile authUser = getAuthUser(req); + String currentSpace = getSpaceIdFromCookie(authUser, req); + if (isSpaceFiltered) { + return StringUtils.isBlank(spaceFilter) ? getSpaceFilter(authUser, currentSpace) : spaceFilter; + } + return canAccessSpace(authUser, currentSpace) ? defaultQuery : ""; + } + + public String getSpaceFilter(Profile authUser, String spaceId) { + if (isAllSpaces(spaceId)) { + if (authUser != null && authUser.hasSpaces()) { + return "(" + authUser.getSpaces().stream().map(s -> "properties.space:\"" + s + "\""). + collect(Collectors.joining(" OR ")) + ")"; + } else { + return "properties.space:\"" + DEFAULT_SPACE + "\""; + } + } else if (isDefaultSpace(spaceId) && isMod(authUser)) { // DO NOT MODIFY! + return "*"; + } else { + return "properties.space:\"" + spaceId + "\""; + } + } + + public Sysprop buildSpaceObject(String space) { + space = Utils.abbreviate(space, 255); + space = space.replaceAll(Para.getConfig().separator(), ""); + String spaceId = getSpaceId(Utils.noSpaces(Utils.stripAndTrim(space, " "), "-")); + Sysprop s = new Sysprop(spaceId); + s.setType("scooldspace"); + s.setName(space); + return s; + } + + public String sanitizeQueryString(String query, HttpServletRequest req) { + String qf = getSpaceFilteredQuery(req); + String defaultQuery = "*"; + String q = StringUtils.trimToEmpty(query); + if (qf.isEmpty() || qf.length() > 1) { + q = q.replaceAll("[\\?<>]", "").trim(); + q = q.replaceAll("$[\\*]*", ""); + q = RegExUtils.removeAll(q, "AND"); + q = RegExUtils.removeAll(q, "OR"); + q = RegExUtils.removeAll(q, "NOT"); + q = q.trim(); + defaultQuery = ""; + } + if (qf.isEmpty()) { + return defaultQuery; + } else if ("*".equals(qf)) { + return q; + } else if ("*".equals(q)) { + return qf; + } else { + if (q.isEmpty()) { + return qf; + } else { + return qf + " AND " + q; + } + } + } + + public String getUsersSearchQuery(String qs, String spaceFilter) { + qs = Utils.stripAndTrim(qs).toLowerCase(); + if (!StringUtils.isBlank(qs)) { + String wildcardLower = qs.matches("[\\p{IsAlphabetic}]*") ? qs + "*" : qs; + String wildcardUpper = StringUtils.capitalize(wildcardLower); + String template = "(name:({1}) OR name:({2} OR {3}) OR properties.location:({0}) OR " + + "properties.aboutme:({0}) OR properties.groups:({0}))"; + qs = (StringUtils.isBlank(spaceFilter) ? "" : spaceFilter + " AND ") + + Utils.formatMessage(template, qs, StringUtils.capitalize(qs), wildcardLower, wildcardUpper); + } else { + qs = StringUtils.isBlank(spaceFilter) ? "*" : spaceFilter; + } + return qs; + } + + public List fullQuestionsSearch(String query, Pager... pager) { + String typeFilter = Config._TYPE + ":(" + String.join(" OR ", + Utils.type(Question.class), Utils.type(Reply.class), Utils.type(Comment.class)) + ")"; + String qs = StringUtils.isBlank(query) || query.startsWith("*") ? typeFilter : query + " AND " + typeFilter; + List mixedResults = pc.findQuery("", qs, pager); + Predicate isQuestion = obj -> obj.getType().equals(Utils.type(Question.class)); + + Map idsToQuestions = new HashMap<>(mixedResults.stream().filter(isQuestion). + collect(Collectors.toMap(q -> q.getId(), q -> q))); + Set toRead = new LinkedHashSet<>(); + mixedResults.stream().filter(isQuestion.negate()).forEach(obj -> { + if (!idsToQuestions.containsKey(obj.getParentid())) { + toRead.add(obj.getParentid()); + } + }); + // find all parent posts but this excludes parents of parents - i.e. won't work for comments in answers + List parentPostsLevel1 = pc.readAll(new ArrayList<>(toRead)); + parentPostsLevel1.stream().filter(isQuestion).forEach(q -> idsToQuestions.put(q.getId(), q)); + + toRead.clear(); + + // read parents of parents if any + parentPostsLevel1.stream().filter(isQuestion.negate()).forEach(obj -> { + if (!idsToQuestions.containsKey(obj.getParentid())) { + toRead.add(obj.getParentid()); + } + }); + List parentPostsLevel2 = pc.readAll(new ArrayList<>(toRead)); + parentPostsLevel2.stream().forEach(q -> idsToQuestions.put(q.getId(), q)); + + ArrayList results = new ArrayList(idsToQuestions.size()); + for (ParaObject result : idsToQuestions.values()) { + if (result instanceof Post) { + results.add((Post) result); + } + } + return results; + } + + public String getMacroCode(String key) { + return WHITELISTED_MACROS.getOrDefault(key, ""); + } + + public boolean isMine(Post showPost, Profile authUser) { + // author can edit, mods can edit & ppl with rep > 100 can edit + return showPost != null && authUser != null ? authUser.getId().equals(showPost.getCreatorid()) : false; + } + + public boolean canEdit(Post showPost, Profile authUser) { + return authUser != null ? (authUser.hasBadge(TEACHER) || isMod(authUser) || isMine(showPost, authUser)) : false; + } + + public boolean canDelete(Post showPost, Profile authUser) { + return canDelete(showPost, authUser, null); + } + + public boolean canDelete(Post showPost, Profile authUser, String approvedAnswerId) { + if (authUser == null) { + return false; + } + if (CONF.deleteProtectionEnabled()) { + if (showPost.isReply()) { + return isMine(showPost, authUser) && !StringUtils.equals(approvedAnswerId, showPost.getId()); + } else { + return isMine(showPost, authUser) && showPost.getAnswercount() == 0; + } + } + return isMine(showPost, authUser); + } + + @SuppressWarnings("unchecked") + public

P populate(HttpServletRequest req, P pobj, String... paramName) { + if (pobj == null || paramName == null) { + return pobj; + } + Map data = new LinkedHashMap(); + if (isApiRequest(req)) { + try { + data = (Map) req.getAttribute(REST_ENTITY_ATTRIBUTE); + if (data == null) { + data = ParaObjectUtils.getJsonReader(Map.class).readValue(req.getInputStream()); + } + } catch (IOException ex) { + logger.error(null, ex); + data = Collections.emptyMap(); + } + } else { + for (String param : paramName) { + String[] values; + if (param.matches(".+?\\|.$")) { + // convert comma-separated value to list of strings + String cleanParam = param.substring(0, param.length() - 2); + values = req.getParameterValues(cleanParam); + String firstValue = (values != null && values.length > 0) ? values[0] : null; + String separator = param.substring(param.length() - 1); + if (!StringUtils.isBlank(firstValue)) { + data.put(cleanParam, Arrays.asList(firstValue.split(separator))); + } + } else { + values = req.getParameterValues(param); + if (values != null && values.length > 0) { + data.put(param, values.length > 1 ? Arrays.asList(values) : + Arrays.asList(values).iterator().next()); + } + } + } + } + if (!data.isEmpty()) { + ParaObjectUtils.setAnnotatedFields(pobj, data, null); + } + return pobj; + } + + public

Map validate(P pobj) { + HashMap error = new HashMap(); + if (pobj != null) { + Set> errors = ValidationUtils.getValidator().validate(pobj); + for (ConstraintViolation

err : errors) { + error.put(err.getPropertyPath().toString(), err.getMessage()); + } + } + return error; + } + + public String getFullAvatarURL(Profile profile, AvatarFormat format) { + return avatarRepository.getLink(profile, format); + } + + public void clearSession(HttpServletRequest req, HttpServletResponse res) { + if (req != null) { + String jwt = HttpUtils.getStateParam(CONF.authCookie(), req); + if (!StringUtils.isBlank(jwt)) { + if (CONF.oneSessionPerUser()) { + synchronized (pc) { + pc.setAccessToken(jwt); + pc.revokeAllTokens(); + pc.signOut(); + } + } + HttpUtils.removeStateParam(CONF.authCookie(), req, res); + } + HttpUtils.removeStateParam("dark-mode", req, res); + } + } + + public boolean addBadgeOnce(Profile authUser, Profile.Badge b, boolean condition) { + return addBadge(authUser, b, condition && !authUser.hasBadge(b), false); + } + + public boolean addBadgeOnceAndUpdate(Profile authUser, Profile.Badge b, boolean condition) { + return addBadgeAndUpdate(authUser, b, condition && authUser != null && !authUser.hasBadge(b)); + } + + public boolean addBadgeAndUpdate(Profile authUser, Profile.Badge b, boolean condition) { + return addBadge(authUser, b, condition, true); + } + + public boolean addBadge(Profile user, Profile.Badge b, boolean condition, boolean update) { + if (user != null && condition) { + String newb = StringUtils.isBlank(user.getNewbadges()) ? "" : user.getNewbadges().concat(","); + newb = newb.concat(b.toString()); + + user.addBadge(b); + user.setNewbadges(newb); + if (update) { + user.update(); + return true; + } + } + return false; + } + + public List checkForBadges(Profile authUser, HttpServletRequest req) { + List badgelist = new ArrayList(); + if (authUser != null && !isAjaxRequest(req)) { + long oneYear = authUser.getTimestamp() + (365 * 24 * 60 * 60 * 1000); + addBadgeOnce(authUser, Profile.Badge.ENTHUSIAST, authUser.getVotes() >= CONF.enthusiastIfHasRep()); + addBadgeOnce(authUser, Profile.Badge.FRESHMAN, authUser.getVotes() >= CONF.freshmanIfHasRep()); + addBadgeOnce(authUser, Profile.Badge.SCHOLAR, authUser.getVotes() >= CONF.scholarIfHasRep()); + addBadgeOnce(authUser, Profile.Badge.TEACHER, authUser.getVotes() >= CONF.teacherIfHasRep()); + addBadgeOnce(authUser, Profile.Badge.PROFESSOR, authUser.getVotes() >= CONF.professorIfHasRep()); + addBadgeOnce(authUser, Profile.Badge.GEEK, authUser.getVotes() >= CONF.geekIfHasRep()); + addBadgeOnce(authUser, Profile.Badge.SENIOR, (System.currentTimeMillis() - authUser.getTimestamp()) >= oneYear); + + if (!StringUtils.isBlank(authUser.getNewbadges())) { + badgelist.addAll(Arrays.asList(authUser.getNewbadges().split(","))); + authUser.setNewbadges(null); + authUser.update(); + } + } + return badgelist; + } + + private String loadEmailTemplate(String name) { + return loadResource("emails/" + name + ".html"); + } + + public String loadResource(String filePath) { + if (filePath == null) { + return ""; + } + if (FILE_CACHE.containsKey(filePath)) { + return FILE_CACHE.get(filePath); + } + String template = ""; + try (InputStream in = getClass().getClassLoader().getResourceAsStream(filePath)) { + try (Scanner s = new Scanner(in).useDelimiter("\\A")) { + template = s.hasNext() ? s.next() : ""; + if (!StringUtils.isBlank(template)) { + FILE_CACHE.put(filePath, template); + } + } + } catch (Exception ex) { + logger.info("Couldn't load resource '{}'.", filePath); + } + return template; + } + + public String compileEmailTemplate(Map model) { + model.put("footerhtml", CONF.emailsFooterHtml()); + String fqdn = CONF.rewriteInboundLinksWithFQDN(); + if (!StringUtils.isBlank(fqdn)) { + model.entrySet().stream().filter(e -> (e.getValue() instanceof String)).forEachOrdered(e -> { + model.put(e.getKey(), StringUtils.replace((String) e.getValue(), CONF.serverUrl(), fqdn)); + }); + } + return Utils.compileMustache(model, loadEmailTemplate("notify")); + } + + public boolean isValidJWToken(String jwt) { + String appSecretKey = CONF.appSecretKey(); + String masterSecretKey = CONF.paraSecretKey(); + return isValidJWToken(appSecretKey, jwt) || isValidJWToken(masterSecretKey, jwt); + } + + boolean isValidJWToken(String secret, String jwt) { + try { + if (secret != null && jwt != null) { + JWSVerifier verifier = new MACVerifier(secret); + SignedJWT sjwt = SignedJWT.parse(jwt); + if (sjwt.verify(verifier)) { + Date referenceTime = new Date(); + JWTClaimsSet claims = sjwt.getJWTClaimsSet(); + + Date expirationTime = claims.getExpirationTime(); + Date notBeforeTime = claims.getNotBeforeTime(); + String jti = claims.getJWTID(); + boolean expired = expirationTime != null && expirationTime.before(referenceTime); + boolean notYetValid = notBeforeTime != null && notBeforeTime.after(referenceTime); + boolean jtiRevoked = isApiKeyRevoked(jti, expired); + return !(expired || notYetValid || jtiRevoked); + } + } + } catch (JOSEException e) { + logger.warn(null, e); + } catch (ParseException ex) { + logger.warn(null, ex); + } + return false; + } + + public SignedJWT generateJWToken(Map claims) { + return generateJWToken(claims, CONF.jwtExpiresAfterSec()); + } + + public SignedJWT generateJWToken(Map claims, long validitySeconds) { + String secret = CONF.appSecretKey(); + if (!StringUtils.isBlank(secret)) { + try { + Date now = new Date(); + JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder(); + claimsSet.issueTime(now); + if (validitySeconds > 0) { + claimsSet.expirationTime(new Date(now.getTime() + (validitySeconds * 1000))); + } + claimsSet.notBeforeTime(now); + claimsSet.claim(Config._APPID, CONF.paraAccessKey()); + claims.entrySet().forEach((claim) -> claimsSet.claim(claim.getKey(), claim.getValue())); + JWSSigner signer = new MACSigner(secret); + SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet.build()); + signedJWT.sign(signer); + return signedJWT; + } catch (JOSEException e) { + logger.warn("Unable to sign JWT: {}.", e.getMessage()); + } + } + logger.error("Failed to generate JWT token - app_secret_key is blank."); + return null; + } + + public boolean isApiKeyRevoked(String jti, boolean expired) { + if (StringUtils.isBlank(jti)) { + return false; + } + if (API_KEYS.isEmpty()) { + Sysprop s = pc.read("api_keys"); + if (s != null) { + API_KEYS.putAll(s.getProperties()); + } + } + if (API_KEYS.containsKey(jti) && expired) { + revokeApiKey(jti); + } + return !API_KEYS.containsKey(jti); + } + + public void registerApiKey(String jti, String jwt) { + if (StringUtils.isBlank(jti) || StringUtils.isBlank(jwt)) { + return; + } + API_KEYS.put(jti, jwt); + saveApiKeysObject(); + } + + public void revokeApiKey(String jti) { + API_KEYS.remove(jti); + saveApiKeysObject(); + } + + public Map getApiKeys() { + return Collections.unmodifiableMap(API_KEYS); + } + + public Map getApiKeysExpirations() { + return API_KEYS.keySet().stream().collect(Collectors.toMap(k -> k, k -> { + try { + Date exp = SignedJWT.parse((String) API_KEYS.get(k)).getJWTClaimsSet().getExpirationTime(); + if (exp != null) { + return exp.getTime(); + } + } catch (ParseException ex) { + logger.error(null, ex); + } + return 0L; + })); + } + + private void saveApiKeysObject() { + Sysprop s = new Sysprop("api_keys"); + s.setProperties(API_KEYS); + pc.create(s); + } + + public Profile getSystemUser() { + return API_USER; + } + + public void triggerHookEvent(String eventName, Object payload) { + if (isWebhooksEnabled() && HOOK_EVENTS.contains(eventName)) { + Para.asyncExecute(() -> { + Webhook trigger = new Webhook(); + trigger.setTriggeredEvent(eventName); + trigger.setCustomPayload(payload); + pc.create(trigger); + }); + } + } + + public void setSecurityHeaders(String nonce, HttpServletRequest request, HttpServletResponse response) { + // CSP Header + if (CONF.cspHeaderEnabled()) { + response.setHeader("Content-Security-Policy", + (request.isSecure() ? "upgrade-insecure-requests; " : "") + CONF.cspHeader(nonce)); + } + // HSTS Header + if (CONF.hstsHeaderEnabled()) { + response.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains"); + } + // Frame Options Header + if (CONF.framingHeaderEnabled()) { + response.setHeader("X-Frame-Options", "SAMEORIGIN"); + } + // XSS Header + if (CONF.xssHeaderEnabled()) { + response.setHeader("X-XSS-Protection", "1; mode=block"); + } + // Content Type Header + if (CONF.contentTypeHeaderEnabled()) { + response.setHeader("X-Content-Type-Options", "nosniff"); + } + // Referrer Header + if (CONF.referrerHeaderEnabled()) { + response.setHeader("Referrer-Policy", "strict-origin"); + } + // Permissions Policy Header + if (CONF.permissionsHeaderEnabled()) { + response.setHeader("Permissions-Policy", "geolocation=()"); + } + } + + public boolean cookieConsentGiven(HttpServletRequest request) { + return !CONF.cookieConsentRequired() || "allow".equals(HttpUtils.getCookieValue(request, "cookieconsent_status")); + } + + public String base64DecodeScript(String encodedScript) { + if (StringUtils.isBlank(encodedScript)) { + return ""; + } + try { + String decodedScript = Base64.isBase64(encodedScript) ? Utils.base64dec(encodedScript) : ""; + return StringUtils.isBlank(decodedScript) ? encodedScript : decodedScript; + } catch (Exception e) { + return encodedScript; + } + } + + public Map getExternalScripts() { + return CONF.externalScripts(); + } + + public List getExternalStyles() { + String extStyles = CONF.externalStyles(); + if (!StringUtils.isBlank(extStyles)) { + String[] styles = extStyles.split("\\s*,\\s*"); + if (!StringUtils.isBlank(extStyles) && styles != null && styles.length > 0) { + ArrayList list = new ArrayList(); + for (String style : styles) { + if (!StringUtils.isBlank(style)) { + list.add(style); + } + } + return list; + } + } + return Collections.emptyList(); + } + + public String getInlineCSS() { + try { + Sysprop custom = getCustomTheme(); + String themeName = custom.getName(); + String inline = CONF.inlineCSS(); + String loadedTheme; + if ("default".equalsIgnoreCase(themeName) || StringUtils.isBlank(themeName)) { + return inline; + } else if ("custom".equalsIgnoreCase(themeName)) { + loadedTheme = (String) custom.getProperty("theme"); + } else { + loadedTheme = loadResource(getThemeKey(themeName)); + if (StringUtils.isBlank(loadedTheme)) { + FILE_CACHE.put("theme", "default"); + custom.setName("default"); + customTheme = pc.update(custom); + return inline; + } else { + FILE_CACHE.put("theme", themeName); + } + } + loadedTheme = StringUtils.replaceEachRepeatedly(loadedTheme, + new String[] {"<", " +* http://www.olat.org +*

+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at +*

+* http://www.apache.org/licenses/LICENSE-2.0 +*

+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License. +*

+* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),
+* University of Zurich, Switzerland. +*


+* +* OpenOLAT - Online Learning and Training
+* This file has been modified by the OpenOLAT community. Changes are licensed +* under the Apache 2.0 license as the original file. +*/ +package org.olat.modules.scorm; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +import org.apache.logging.log4j.Logger; +import org.olat.core.gui.UserRequest; +import org.olat.core.gui.control.WindowControl; +import org.olat.core.gui.control.generic.iframe.DeliveryOptions; +import org.olat.core.id.OLATResourceable; +import org.olat.core.logging.Tracing; +import org.olat.core.util.FileUtils; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.fileresource.FileResourceManager; +import org.springframework.stereotype.Service; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.security.ExplicitTypePermission; + + +/** + * Initial Date: 08.10.2007
+ * @author Felix Jost, http://www.goodsolutions.ch + */ +@Service +public class ScormMainManager { + + public static final String PACKAGE_CONFIG_FILE_NAME = "ScormPackageConfig.xml"; + + private static final Logger log = Tracing.createLoggerFor(ScormMainManager.class); + private static XStream configXstream = XStreamHelper.createXStreamInstance(); + static { + Class[] types = new Class[] { + ScormPackageConfig.class, DeliveryOptions.class + }; + configXstream.addPermission(new ExplicitTypePermission(types)); + configXstream.alias("packageConfig", ScormPackageConfig.class); + configXstream.alias("deliveryOptions", DeliveryOptions.class); + } + + public ScormPackageConfig getScormPackageConfig(File cpRoot) { + File configXml = new File(cpRoot.getParentFile(), PACKAGE_CONFIG_FILE_NAME); + if(configXml.exists()) { + return (ScormPackageConfig)configXstream.fromXML(configXml); + } + return null; + } + + public ScormPackageConfig getScormPackageConfig(OLATResourceable ores) { + FileResourceManager frm = FileResourceManager.getInstance(); + File reFolder = frm.getFileResourceRoot(ores); + File configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME); + if(configXml.exists()) { + return (ScormPackageConfig)configXstream.fromXML(configXml); + } + return null; + } + + public void setScormPackageConfig(OLATResourceable ores, ScormPackageConfig config) { + FileResourceManager frm = FileResourceManager.getInstance(); + File reFolder = frm.getFileResourceRoot(ores); + File configXml = new File(reFolder, PACKAGE_CONFIG_FILE_NAME); + if(config == null) { + FileUtils.deleteFile(configXml); + } else { + try(OutputStream out = new FileOutputStream(configXml)) { + configXstream.toXML(config, out); + } catch (IOException e) { + log.error("", e); + } + } + } + + /** + * @param ureq + * @param wControl + * @param showMenu if true, the ims cp menu is shown + * @param apiCallback the callback to where lmssetvalue data is mirrored, or null if no callback is desired + * @param cpRoot + * @param resourceId + * @param lessonMode add null for the default value or "normal", "browse" or + * "review" + * @param creditMode add null for the default value or "credit", "no-credit" + */ + public ScormAPIandDisplayController createScormAPIandDisplayController(UserRequest ureq, WindowControl wControl, + boolean showMenu, ScormAPICallback apiCallback, File cpRoot, Long scormResourceId, String courseId, + String lessonMode, String creditMode, boolean previewMode, String assessableType, boolean activate, + boolean fullWindow, boolean attemptsIncremented, boolean randomizeDelivery, DeliveryOptions deliveryOptions) { + + ScormAPIandDisplayController ctrl= new ScormAPIandDisplayController(ureq, wControl, showMenu, apiCallback, cpRoot, + scormResourceId, courseId, lessonMode, creditMode, previewMode, assessableType, activate, fullWindow, + attemptsIncremented, randomizeDelivery, deliveryOptions); + + DeliveryOptions config = ctrl.getDeliveryOptions(); + boolean configAllowRawContent = (config == null || config.rawContent()); + ctrl.setRawContent(configAllowRawContent); + return ctrl; + } + +} diff --git a/Java/SendDocumentsByEMailController.java b/Java/SendDocumentsByEMailController.java new file mode 100644 index 0000000000000000000000000000000000000000..1bb6e978de562cc0ebfd1a8aa63f64ea89a1cba2 --- /dev/null +++ b/Java/SendDocumentsByEMailController.java @@ -0,0 +1,609 @@ +/** + * + * OpenOLAT - Online Learning and Training
+ *

+ * 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 the + * Apache homepage + *

+ * 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. + *

+ * Initial code contributed and copyrighted by
+ * frentix GmbH, http://www.frentix.com + *

+ */ +package org.olat.core.util.mail.ui; + +import java.io.File; +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.UUID; + +import org.olat.basesecurity.BaseSecurity; +import org.olat.basesecurity.events.SingleIdentityChosenEvent; +import org.olat.core.CoreSpringFactory; +import org.olat.core.commons.modules.bc.FileSelection; +import org.olat.core.commons.modules.bc.FolderConfig; +import org.olat.core.commons.modules.bc.commands.CmdSendMail; +import org.olat.core.commons.modules.bc.commands.FolderCommand; +import org.olat.core.commons.modules.bc.commands.FolderCommandHelper; +import org.olat.core.commons.modules.bc.commands.FolderCommandStatus; +import org.olat.core.commons.modules.bc.components.FolderComponent; +import org.olat.core.commons.modules.bc.meta.MetaInfoController; +import org.olat.core.commons.services.vfs.VFSMetadata; +import org.olat.core.gui.UserRequest; +import org.olat.core.gui.components.form.flexible.FormItem; +import org.olat.core.gui.components.form.flexible.FormItemContainer; +import org.olat.core.gui.components.form.flexible.elements.FormLink; +import org.olat.core.gui.components.form.flexible.elements.TextElement; +import org.olat.core.gui.components.form.flexible.impl.FormBasicController; +import org.olat.core.gui.components.form.flexible.impl.FormEvent; +import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer; +import org.olat.core.gui.components.link.Link; +import org.olat.core.gui.control.Controller; +import org.olat.core.gui.control.Event; +import org.olat.core.gui.control.WindowControl; +import org.olat.core.gui.control.generic.closablewrapper.CloseableCalloutWindowController; +import org.olat.core.gui.control.generic.folder.FolderHelper; +import org.olat.core.gui.translator.Translator; +import org.olat.core.gui.util.CSSHelper; +import org.olat.core.id.Identity; +import org.olat.core.id.Roles; +import org.olat.core.id.UserConstants; +import org.olat.core.id.context.BusinessControlFactory; +import org.olat.core.id.context.ContextEntry; +import org.olat.core.util.CodeHelper; +import org.olat.core.util.Formatter; +import org.olat.core.util.StringHelper; +import org.olat.core.util.Util; +import org.olat.core.util.mail.MailBundle; +import org.olat.core.util.mail.MailHelper; +import org.olat.core.util.mail.MailManager; +import org.olat.core.util.mail.MailModule; +import org.olat.core.util.mail.MailerResult; +import org.olat.core.util.vfs.LocalFileImpl; +import org.olat.core.util.vfs.VFSConstants; +import org.olat.core.util.vfs.VFSContainer; +import org.olat.core.util.vfs.VFSItem; +import org.olat.core.util.vfs.VFSLeaf; +import org.olat.core.util.vfs.VFSManager; +import org.olat.user.UserManager; +import org.springframework.beans.factory.annotation.Autowired; + +/** + * + *

Description:

+ *

+ *

+ * Initial Date: 7 feb. 2011
+ * + * @author srosse, stephane.rosse@frentix.com, www.frentix.com + */ +public class SendDocumentsByEMailController extends FormBasicController implements CmdSendMail { + + private TextElement bodyElement; + private FormLink addEmailLink; + private TextElement subjectElement; + private FormLayoutContainer userListBox; + private FormLayoutContainer attachmentsLayout; + private EMailCalloutCtrl emailCalloutCtrl; + private CloseableCalloutWindowController calloutCtrl; + + private final DecimalFormat formatMb = new DecimalFormat("0.00"); + + private int status = FolderCommandStatus.STATUS_SUCCESS; + private List attachments; + private final boolean allowAttachments; + private List toValues = new ArrayList<>(); + + @Autowired + private UserManager userManager; + @Autowired + private MailManager mailManager; + @Autowired + private BaseSecurity securityManager; + + public SendDocumentsByEMailController(UserRequest ureq, WindowControl wControl) { + super(ureq, wControl, null, Util.createPackageTranslator(MailModule.class, ureq.getLocale(), + Util.createPackageTranslator(MetaInfoController.class, ureq.getLocale()))); + setBasePackage(MailModule.class); + + allowAttachments = !FolderConfig.getSendDocumentLinkOnly(); + + initForm(ureq); + } + + @Override + protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { + setFormDescription("send.mail.description"); + setFormStyle("o_send_documents"); + + int emailCols = 25; + + String toPage = velocity_root + "/tos.html"; + userListBox = FormLayoutContainer.createCustomFormLayout("send.mail.to.auto", getTranslator(), toPage); + userListBox.setLabel("send.mail.to", null); + userListBox.setRootForm(mainForm); + userListBox.contextPut("tos", toValues); + formLayout.add(userListBox); + + addEmailLink = uifactory.addFormLink("add.email", userListBox); + addEmailLink.setIconLeftCSS("o_icon o_icon_add"); + + subjectElement = uifactory.addTextElement("tsubject", "send.mail.subject", 255, "", formLayout); + + bodyElement = uifactory.addTextAreaElement("tbody", "send.mail.body", -1, 20, emailCols, false, false, "", formLayout); + + if (allowAttachments) { + String page = Util.getPackageVelocityRoot(MailModule.class) + "/sendattachments.html"; + attachmentsLayout = FormLayoutContainer.createCustomFormLayout("attachments", getTranslator(), page); + attachmentsLayout.setRootForm(mainForm); + attachmentsLayout.setLabel("send.mail.attachments", null); + formLayout.add(attachmentsLayout); + } + + FormLayoutContainer buttonGroupLayout = FormLayoutContainer.createButtonLayout("buttonGroupLayout", getTranslator()); + formLayout.add(buttonGroupLayout); + uifactory.addFormSubmitButton("ok", buttonGroupLayout); + uifactory.addFormCancelButton("cancel", buttonGroupLayout, ureq, getWindowControl()); + } + + @Override + protected void doDispose() { + // + } + + @Override + public int getStatus() { + return status; + } + + @Override + public boolean runsModal() { + return false; + } + + @Override + public String getModalTitle() { + return translate("send.mail.title"); + } + + public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator translator) { + VFSContainer currentContainer = folderComponent.getCurrentContainer(); + VFSContainer rootContainer = folderComponent.getRootContainer(); + + if (!VFSManager.exists(currentContainer)) { + status = FolderCommandStatus.STATUS_FAILED; + showError(translator.translate("FileDoesNotExist")); + return null; + } + status = FolderCommandHelper.sanityCheck(wControl, folderComponent); + if (status == FolderCommandStatus.STATUS_FAILED) { + return null; + } + // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') + // FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath()); + // FIXED: + FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainer(), folderComponent.getCurrentContainerPath()); + status = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection); + if (status == FolderCommandStatus.STATUS_FAILED) { + return null; + } + + boolean selectionWithContainer = false; + List filenames = selection.getFiles(); + List leafs = new ArrayList<>(); + for (String file : filenames) { + VFSItem item = currentContainer.resolve(file); + if (item instanceof VFSContainer) { + selectionWithContainer = true; + } else if (item instanceof VFSLeaf) { + leafs.add((VFSLeaf) item); + } + } + if (selectionWithContainer) { + if (leafs.isEmpty()) { + wControl.setError(getTranslator().translate("send.mail.noFileSelected")); + return null; + } else { + setFormWarning(getTranslator().translate("send.mail.selectionContainsFolder")); + } + } + setFiles(rootContainer, leafs); + return this; + } + + protected void setFiles(VFSContainer rootContainer, List files) { + StringBuilder subjectSb = new StringBuilder(); + if (StringHelper.containsNonWhitespace(subjectElement.getValue())) { + subjectSb.append(subjectElement.getValue()).append('\n').append('\n'); + } + StringBuilder bodySb = new StringBuilder(); + if (StringHelper.containsNonWhitespace(bodyElement.getValue())) { + bodySb.append(bodyElement.getValue()).append('\n').append('\n'); + } + + attachments = new ArrayList<>(); + long fileSize = 0l; + for (VFSLeaf file : files) { + VFSMetadata infos = null; + if (file.canMeta() == VFSConstants.YES) { + infos = file.getMetaInfo(); + } + // subject + appendToSubject(file, infos, subjectSb); + + // body + appendMetadatas(file, infos, bodySb); + appendBusinessPath(rootContainer, file, bodySb); + bodySb.append('\n').append('\n'); + fileSize += file.getSize(); + if (allowAttachments && file instanceof LocalFileImpl) { + File f = ((LocalFileImpl) file).getBasefile(); + attachments.add(f); + } + } + + int mailQuota = CoreSpringFactory.getImpl(MailModule.class).getMaxSizeForAttachement(); + long fileSizeInMB = fileSize / (1024l * 1024l); + if (allowAttachments) { + if (fileSizeInMB > mailQuota) { + attachments.clear(); + setFormWarning("send.mail.fileToBigForAttachments", new String[] { String.valueOf(mailQuota), String.valueOf(fileSizeInMB) }); + } else { + List infos = new ArrayList<>(files.size()); + for (VFSLeaf file : files) { + final String name = file.getName(); + final double size = file.getSize() / (1024.0 * 1024.0); + final String sizeStr = formatMb.format(size); + final String cssClass = CSSHelper.createFiletypeIconCssClassFor(file.getName()); + infos.add(new FileInfo(name, sizeStr, cssClass)); + } + attachmentsLayout.contextPut("attachments", infos); + } + } + + subjectElement.setValue(subjectSb.toString()); + bodyElement.setValue(bodySb.toString()); + } + + protected void appendToSubject(VFSLeaf file, VFSMetadata infos, StringBuilder sb) { + if (sb.length() > 0) + sb.append(", "); + if (infos != null && StringHelper.containsNonWhitespace(infos.getTitle())) { + sb.append(infos.getTitle()); + } else { + sb.append(file.getName()); + } + } + + protected void appendMetadatas(VFSLeaf file, VFSMetadata infos, StringBuilder sb) { + if (infos == null) { + appendMetadata("mf.filename", file.getName(), sb); + } else { + appendMetadata("mf.filename", infos.getFilename(), sb); + String title = infos.getTitle(); + if (StringHelper.containsNonWhitespace(title)) { + appendMetadata("mf.title", title, sb); + } + String comment = infos.getComment(); + if (StringHelper.containsNonWhitespace(comment)) { + appendMetadata("mf.comment", comment, sb); + } + String creator = infos.getCreator(); + if (StringHelper.containsNonWhitespace(creator)) { + appendMetadata("mf.creator", creator, sb); + } + String publisher = infos.getPublisher(); + if (StringHelper.containsNonWhitespace(publisher)) { + appendMetadata("mf.publisher", publisher, sb); + } + String source = infos.getSource(); + if (StringHelper.containsNonWhitespace(source)) { + appendMetadata("mf.source", source, sb); + } + String city = infos.getCity(); + if (StringHelper.containsNonWhitespace(city)) { + appendMetadata("mf.city", city, sb); + } + appendPublicationDate(infos, sb); + String pages = infos.getPages(); + if (StringHelper.containsNonWhitespace(pages)) { + appendMetadata("mf.pages", pages, sb); + } + String language = infos.getLanguage(); + if (StringHelper.containsNonWhitespace(language)) { + appendMetadata("mf.language", language, sb); + } + String url = infos.getUrl(); + if (StringHelper.containsNonWhitespace(url)) { + appendMetadata("mf.url", url, sb); + } + String author = userManager.getUserDisplayName(infos.getFileInitializedBy()); + if (StringHelper.containsNonWhitespace(author)) { + appendMetadata("mf.author", author, sb); + } + String size = Formatter.formatBytes(file.getSize()); + appendMetadata("mf.size", size, sb); + Date lastModifiedDate = infos.getFileLastModified(); + if (lastModifiedDate != null) { + appendMetadata("mf.lastModified", Formatter.getInstance(getLocale()).formatDate(lastModifiedDate), sb); + } + String type = FolderHelper.extractFileType(file.getName(), getLocale()); + if (StringHelper.containsNonWhitespace(type)) { + appendMetadata("mf.type", type, sb); + } + int downloads = infos.getDownloadCount(); + if (infos.getDownloadCount() >= 0) { + appendMetadata("mf.downloads", String.valueOf(downloads), sb); + } + } + } + + protected void appendMetadata(String i18nKey, String value, StringBuilder sb) { + sb.append(translate(i18nKey)).append(": ").append(value).append('\n'); + } + + protected void appendPublicationDate(VFSMetadata infos, StringBuilder sb) { + String[] publicationDate = infos.getPublicationDate(); + if (publicationDate == null || publicationDate.length != 2) + return; + String month = publicationDate[1]; + String year = publicationDate[0]; + if (StringHelper.containsNonWhitespace(month) || StringHelper.containsNonWhitespace(year)) { + sb.append(translate("mf.publishDate")).append(":"); + if (StringHelper.containsNonWhitespace(month)) { + sb.append(" ").append(translate("mf.month").replaceAll(" ", "")).append(" ").append(month); + } + if (StringHelper.containsNonWhitespace(year)) { + sb.append(" ").append(translate("mf.year").replaceAll(" ", "")).append(" ").append(year); + } + sb.append('\n'); + } + } + + protected void appendBusinessPath(VFSContainer rootContainer, VFSLeaf file, StringBuilder sb) { + BusinessControlFactory bCF = BusinessControlFactory.getInstance(); + String businnessPath = getWindowControl().getBusinessControl().getAsString(); + + String relPath = getRelativePath(rootContainer, file); + businnessPath += "[path=" + relPath + "]"; + + List ces = bCF.createCEListFromString(businnessPath); + String uri = bCF.getAsURIString(ces, true); + this.appendMetadata("mf.url", uri, sb); + } + + protected String getRelativePath(VFSContainer rootContainer, VFSLeaf file) { + String sb = "/" + file.getName(); + VFSContainer parent = file.getParentContainer(); + while (parent != null && !rootContainer.isSame(parent)) { + sb = "/" + parent.getName() + sb; + parent = parent.getParentContainer(); + } + return sb; + } + + @Override + protected boolean validateFormLogic(UserRequest ureq) { + boolean allOk = super.validateFormLogic(ureq); + + String subject = subjectElement.getValue(); + subjectElement.clearError(); + if (!StringHelper.containsNonWhitespace(subject)) { + subjectElement.setErrorKey("form.legende.mandatory", null); + allOk &= false; + } else if(subject != null && subject.length() > subjectElement.getMaxLength()) { + subjectElement.setErrorKey("text.element.error.notlongerthan", + new String[]{ Integer.toString(subjectElement.getMaxLength()) }); + allOk &= false; + } + + String body = bodyElement.getValue(); + bodyElement.clearError(); + if (!StringHelper.containsNonWhitespace(body)) { + bodyElement.setErrorKey("form.legende.mandatory", null); + allOk &= false; + } + + List invalidTos = getInvalidToAddressesFromTextBoxList(); + userListBox.clearError(); + if (!invalidTos.isEmpty()) { + String[] invalidTosArray = new String[invalidTos.size()]; + userListBox.setErrorKey("mailhelper.error.addressinvalid", invalidTos.toArray(invalidTosArray)); + allOk &= false; + } else if(toValues == null || toValues.isEmpty()) { + userListBox.setErrorKey("form.legende.mandatory", null); + allOk &= false; + } + + return allOk; + } + + /** + * returns a list of invalid Values within the textboxlist. + * values are either email-addresses (manually added, thus external) or + * usernames (from autocompletion, thus olat users) + * + * @return + */ + private List getInvalidToAddressesFromTextBoxList() { + List invalidTos = new ArrayList<>(); + + // the toValues are either usernames (from autocompletion, thus OLAT + // users) or email-addresses (external) + if (FolderConfig.getSendDocumentToExtern()) { + for (IdentityWrapper toValue : toValues) { + Identity id = toValue.getIdentity(); + if (!MailHelper.isValidEmailAddress(id.getUser().getProperty(UserConstants.EMAIL, null)) + && !securityManager.isIdentityVisible(id)) { + invalidTos.add(id); + } + } + } else { + for (IdentityWrapper toValue : toValues) { + Identity id = toValue.getIdentity(); + if(!securityManager.isIdentityVisible(id)){ + invalidTos.add(id); + } + } + } + return invalidTos; + } + + @Override + protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) { + if(source == addEmailLink) { + doAddEmail(ureq); + } else if(source instanceof FormLink && source.getUserObject() instanceof IdentityWrapper) { + if(source.getName().startsWith("rm-")) { + for(Iterator wrapperIt=toValues.iterator(); wrapperIt.hasNext(); ) { + IdentityWrapper wrapper = wrapperIt.next(); + if(source.getUserObject().equals(wrapper)) { + wrapperIt.remove(); + } + } + } + userListBox.setDirty(true); + } + super.formInnerEvent(ureq, source, event); + } + + @Override + public void event(UserRequest ureq, Controller source, Event event) { + if(source == emailCalloutCtrl) { + if (event instanceof SingleIdentityChosenEvent) { + addIdentity((SingleIdentityChosenEvent)event); + } + calloutCtrl.deactivate(); + } + } + + private void addIdentity(SingleIdentityChosenEvent foundEvent) { + Identity chosenIdentity = foundEvent.getChosenIdentity(); + if (chosenIdentity != null) { + addIdentity(chosenIdentity); + } + userListBox.setDirty(true); + } + + private void addIdentity(Identity identity) { + FormLink rmLink = uifactory.addFormLink("rm-" + CodeHelper.getForeverUniqueID(), " ", null, userListBox, Link.NONTRANSLATED + Link.LINK); + IdentityWrapper wrapper = new IdentityWrapper(identity, rmLink); + rmLink.setIconLeftCSS("o_icon o_icon_remove"); + rmLink.setUserObject(wrapper); + toValues.add(wrapper); + userListBox.setDirty(true); + } + + @Override + protected void formOK(UserRequest ureq) { + List tos = new ArrayList<>(toValues.size()); + for(IdentityWrapper wrapper:toValues) { + tos.add(wrapper.getIdentity()); + } + String subject = subjectElement.getValue(); + String body = bodyElement.getValue(); + sendEmail(tos, subject, body, ureq); + fireEvent(ureq, FolderCommand.FOLDERCOMMAND_FINISHED); + } + + @Override + protected void formCancelled(UserRequest ureq) { + fireEvent(ureq, FolderCommand.FOLDERCOMMAND_FINISHED); + } + + + + protected void doAddEmail(UserRequest ureq) { + String title = translate("add.email"); + removeAsListenerAndDispose(emailCalloutCtrl); + boolean allowExtern = FolderConfig.getSendDocumentToExtern(); + emailCalloutCtrl = new EMailCalloutCtrl(ureq, getWindowControl(), allowExtern); + listenTo(emailCalloutCtrl); + + removeAsListenerAndDispose(calloutCtrl); + calloutCtrl = new CloseableCalloutWindowController(ureq, getWindowControl(), emailCalloutCtrl.getInitialComponent(), addEmailLink, title, true, null); + listenTo(calloutCtrl); + calloutCtrl.activate(); + } + + protected void sendEmail(List tos, String subject, String body, UserRequest ureq) { + File[] attachmentArray = null; + if (attachments != null && !attachments.isEmpty() && allowAttachments) { + attachmentArray = attachments.toArray(new File[attachments.size()]); + } + + MailerResult result = new MailerResult(); + String metaId = UUID.randomUUID().toString().replace("-", ""); + for(Identity to:tos) { + MailBundle bundle = new MailBundle(); + bundle.setToId(to); + bundle.setMetaId(metaId); + bundle.setFromId(ureq.getIdentity()); + bundle.setContent(subject, body, attachmentArray); + result.append(mailManager.sendMessage(bundle)); + } + + Roles roles = ureq.getUserSession().getRoles(); + boolean detailedErrorOutput = roles.isAdministrator() || roles.isSystemAdmin(); + MailHelper.printErrorsAndWarnings(result, getWindowControl(), detailedErrorOutput, ureq.getLocale()); + } + + public class FileInfo { + private final String filename; + private final String sizeInMB; + private final String cssClass; + + public FileInfo(String filename, String sizeInMB, String cssClass) { + this.filename = filename; + this.sizeInMB = sizeInMB; + this.cssClass = cssClass; + } + + public String getFilename() { + return filename; + } + + public String getSizeInMB() { + return sizeInMB; + } + + public String getCssClass() { + return cssClass; + } + } + + public final class IdentityWrapper { + private Identity identity; + private FormLink removeLink; + + public IdentityWrapper(Identity identity, FormLink removeLink) { + this.identity = identity; + this.removeLink = removeLink; + } + + public String getName() { + if(identity instanceof EMailIdentity) { + return identity.getUser().getProperty(UserConstants.EMAIL, null); + } + return userManager.getUserDisplayName(identity); + } + + public Identity getIdentity() { + return identity; + } + + public String getRemoveLinkName() { + return removeLink.getComponent().getComponentName(); + } + } +} \ No newline at end of file diff --git a/Java/SessionModule.java b/Java/SessionModule.java new file mode 100644 index 0000000000000000000000000000000000000000..b8902680c4ce222e42427ea22fa74edc0b0fb6e8 --- /dev/null +++ b/Java/SessionModule.java @@ -0,0 +1,227 @@ +/* + * Copyright 2015 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 ratpack.session; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.RemovalListener; +import com.google.inject.*; +import com.google.inject.name.Names; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.util.AsciiString; +import ratpack.func.Action; +import ratpack.guice.BindingsSpec; +import ratpack.guice.ConfigurableModule; +import ratpack.guice.RequestScoped; +import ratpack.http.Request; +import ratpack.http.Response; +import ratpack.session.internal.*; +import ratpack.util.Types; + +import javax.inject.Named; +import java.io.Serializable; +import java.util.function.Consumer; + +/** + * Provides support for HTTP sessions. + *

+ * This module provides the general session API (see {@link Session}), and a default {@link SessionStore} implementation that stores session data in local memory. + * + *

The session store

+ *

+ * It is expected that most applications will provide alternative bindings for the {@link SessionStore} type, overriding the default. + * This allows arbitrary stores to be used to persist session data. + *

+ * The default, in memory, implementation stores the data in a {@link Cache}{@code <}{@link AsciiString}, {@link ByteBuf}{@code >}. + * This cache instance is provided by this module and defaults to storing a maximum of 1000 entries, discarding least recently used. + * The {@link #memoryStore} methods are provided to conveniently construct alternative cache configurations, if necessary. + *

Serialization

+ *

+ * Objects must be serialized to be stored in the session. + * The get/set methods {@link SessionData} allow supplying a {@link SessionSerializer} to be used for the specific value. + * For variants of the get/set methods where a serializer is not provided, the implementation of {@link SessionSerializer} bound with Guice will be used. + * The default implementation provided by this module uses Java's in built serialization mechanism. + * Users of this module may choose to override this binding with an alternative serialization strategy. + *

+ * However, other Ratpack extensions may require session storage any rely on Java serialization. + * For this reason, there is also always a {@link JavaSessionSerializer} implementation available that is guaranteed to be able to serialize any {@link Serializable} + * object (that conforms to the {@link Serializable} contract. + * Users of this module may also choose to override this binding with another implementation (e.g. one based on Kryo), + * but this implementation must be able to serialize any object implementing {@link Serializable}. + * + * It is also often desirable to provide alternative implementations for {@link SessionSerializer} and {@link JavaSessionSerializer}. + * The default binding for both types is an implementation that uses out-of-the-box Java serialization (which is neither fast nor efficient). + * + *

Example usage

+ *
{@code
+ * import ratpack.guice.Guice;
+ * import ratpack.path.PathTokens;
+ * import ratpack.session.Session;
+ * import ratpack.session.SessionModule;
+ * import ratpack.test.embed.EmbeddedApp;
+ *
+ * import static org.junit.Assert.assertEquals;
+ *
+ * public class Example {
+ *   public static void main(String... args) throws Exception {
+ *     EmbeddedApp.of(a -> a
+ *         .registry(Guice.registry(b -> b
+ *             .module(SessionModule.class)
+ *         ))
+ *         .handlers(c -> c
+ *             .get("set/:name/:value", ctx ->
+ *                 ctx.get(Session.class).getData().then(sessionData -> {
+ *                   PathTokens pathTokens = ctx.getPathTokens();
+ *                   sessionData.set(pathTokens.get("name"), pathTokens.get("value"));
+ *                   ctx.render("ok");
+ *                 })
+ *             )
+ *             .get("get/:name", ctx -> {
+ *               ctx.get(Session.class).getData()
+ *                 .map(d -> d.require(ctx.getPathTokens().get("name")))
+ *                 .then(ctx::render);
+ *             })
+ *         )
+ *     ).test(httpClient -> {
+ *       assertEquals("ok", httpClient.getText("set/foo/bar"));
+ *       assertEquals("bar", httpClient.getText("get/foo"));
+ *
+ *       assertEquals("ok", httpClient.getText("set/foo/baz"));
+ *       assertEquals("baz", httpClient.getText("get/foo"));
+ *     });
+ *   }
+ * }
+ * }
+ */ +public class SessionModule extends ConfigurableModule { + + /** + * The name of the binding for the {@link Cache} implementation that backs the in memory session store. + * + * @see #memoryStore(Consumer) + */ + public static final String LOCAL_MEMORY_SESSION_CACHE_BINDING_NAME = "localMemorySessionCache"; + + /** + * The key of the binding for the {@link Cache} implementation that backs the in memory session store. + * + * @see #memoryStore(Consumer) + */ + public static final Key> LOCAL_MEMORY_SESSION_CACHE_BINDING_KEY = Key.get( + new TypeLiteral>() {}, + Names.named(LOCAL_MEMORY_SESSION_CACHE_BINDING_NAME) + ); + + /** + * A builder for an alternative cache for the default in memory store. + *

+ * This method is intended to be used with the {@link BindingsSpec#binder(Action)} method. + *

{@code
+   * import ratpack.guice.Guice;
+   * import ratpack.session.SessionModule;
+   *
+   * public class Example {
+   *   public static void main(String... args) {
+   *     Guice.registry(b -> b
+   *         .binder(SessionModule.memoryStore(c -> c.maximumSize(100)))
+   *     );
+   *   }
+   * }
+   * }
+ * + * @param config the cache configuration + * @return an action that binds the cache + * @see #memoryStore(Binder, Consumer) + */ + public static Action memoryStore(Consumer> config) { + return b -> memoryStore(b, config); + } + + /** + * A builder for an alternative cache for the default in memory store. + *

+ * This method can be used from within a custom {@link Module}. + *

{@code
+   * import com.google.inject.AbstractModule;
+   * import ratpack.session.SessionModule;
+   *
+   * public class CustomSessionModule extends AbstractModule {
+   *   protected void configure() {
+   *     SessionModule.memoryStore(binder(), c -> c.maximumSize(100));
+   *   }
+   * }
+   * }
+ * }

+ * This method binds the built cache with the {@link #LOCAL_MEMORY_SESSION_CACHE_BINDING_KEY} key. + * It also implicitly registers a {@link RemovalListener}, that releases the byte buffers as they are discarded. + * + * @param binder the guice binder + * @param config the cache configuration + */ + public static void memoryStore(Binder binder, Consumer> config) { + binder.bind(LOCAL_MEMORY_SESSION_CACHE_BINDING_KEY).toProvider(() -> { + CacheBuilder cacheBuilder = Types.cast(CacheBuilder.newBuilder()); + cacheBuilder.removalListener(n -> n.getValue().release()); + config.accept(cacheBuilder); + return cacheBuilder.build(); + }).in(Scopes.SINGLETON); + } + + @Override + protected void configure() { + memoryStore(binder(), s -> s.maximumSize(1000)); + } + + @Provides + @Singleton + SessionStore sessionStoreAdapter(@Named(LOCAL_MEMORY_SESSION_CACHE_BINDING_NAME) Cache cache) { + return new LocalMemorySessionStore(cache); + } + + @Provides + // BUG: CWE-338 Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG) + // + // FIXED: + @Singleton + SessionIdGenerator sessionIdGenerator() { + return new DefaultSessionIdGenerator(); + } + + @Provides + @RequestScoped + SessionId sessionId(Request request, Response response, SessionIdGenerator idGenerator, SessionCookieConfig cookieConfig) { + return new CookieBasedSessionId(request, response, idGenerator, cookieConfig); + } + + @Provides + SessionSerializer sessionValueSerializer(JavaSessionSerializer sessionSerializer) { + return sessionSerializer; + } + + @Provides + JavaSessionSerializer javaSessionSerializer() { + return new JavaBuiltinSessionSerializer(); + } + + @Provides + @RequestScoped + Session sessionAdapter(SessionId sessionId, SessionStore store, Response response, ByteBufAllocator bufferAllocator, SessionSerializer defaultSerializer, JavaSessionSerializer javaSerializer) { + return new DefaultSession(sessionId, bufferAllocator, store, response, defaultSerializer, javaSerializer); + } + +} diff --git a/Java/ShlOperation.java b/Java/ShlOperation.java new file mode 100644 index 0000000000000000000000000000000000000000..ebb9f8d32984bb9d6069aab814982c801d9b80d2 --- /dev/null +++ b/Java/ShlOperation.java @@ -0,0 +1,53 @@ +/* + * Copyright ConsenSys AG. + * + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.hyperledger.besu.evm.operation; + +import static org.apache.tuweni.bytes.Bytes32.leftPad; + +import org.hyperledger.besu.evm.EVM; +import org.hyperledger.besu.evm.frame.MessageFrame; +import org.hyperledger.besu.evm.gascalculator.GasCalculator; + +import org.apache.tuweni.bytes.Bytes; +import org.apache.tuweni.units.bigints.UInt256; + +public class ShlOperation extends AbstractFixedCostOperation { + + public ShlOperation(final GasCalculator gasCalculator) { + super(0x1b, "SHL", 2, 1, 1, gasCalculator, gasCalculator.getVeryLowTierGasCost()); + } + + @Override + public Operation.OperationResult executeFixedCostOperation( + final MessageFrame frame, final EVM evm) { + Bytes shiftAmount = frame.popStackItem(); + if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) { + frame.popStackItem(); + frame.pushStackItem(UInt256.ZERO); + } else { + final int shiftAmountInt = shiftAmount.toInt(); + final Bytes value = leftPad(frame.popStackItem()); + // BUG: CWE-681 Incorrect Conversion between Numeric Types + // if (shiftAmountInt >= 256) { + // FIXED: + if (shiftAmountInt >= 256 || shiftAmountInt < 0) { + frame.pushStackItem(UInt256.ZERO); + } else { + frame.pushStackItem(value.shiftLeft(shiftAmountInt)); + } + } + return successResponse; + } +} diff --git a/Java/ShrOperation.java b/Java/ShrOperation.java new file mode 100644 index 0000000000000000000000000000000000000000..bcc24636a2451f7b9a95850e36d094d922237699 --- /dev/null +++ b/Java/ShrOperation.java @@ -0,0 +1,53 @@ +/* + * Copyright ConsenSys AG. + * + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.hyperledger.besu.evm.operation; + +import static org.apache.tuweni.bytes.Bytes32.leftPad; + +import org.hyperledger.besu.evm.EVM; +import org.hyperledger.besu.evm.frame.MessageFrame; +import org.hyperledger.besu.evm.gascalculator.GasCalculator; + +import org.apache.tuweni.bytes.Bytes; +import org.apache.tuweni.units.bigints.UInt256; + +public class ShrOperation extends AbstractFixedCostOperation { + + public ShrOperation(final GasCalculator gasCalculator) { + super(0x1c, "SHR", 2, 1, 1, gasCalculator, gasCalculator.getVeryLowTierGasCost()); + } + + @Override + public Operation.OperationResult executeFixedCostOperation( + final MessageFrame frame, final EVM evm) { + Bytes shiftAmount = frame.popStackItem(); + if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) { + frame.popStackItem(); + frame.pushStackItem(UInt256.ZERO); + } else { + final int shiftAmountInt = shiftAmount.toInt(); + final Bytes value = leftPad(frame.popStackItem()); + // BUG: CWE-681 Incorrect Conversion between Numeric Types + // if (shiftAmountInt >= 256) { + // FIXED: + if (shiftAmountInt >= 256 || shiftAmountInt < 0) { + frame.pushStackItem(UInt256.ZERO); + } else { + frame.pushStackItem(value.shiftRight(shiftAmountInt)); + } + } + return successResponse; + } +} diff --git a/Java/SiteDefinitions.java b/Java/SiteDefinitions.java new file mode 100644 index 0000000000000000000000000000000000000000..4f0b5c14cc22a2c9f6a29149a4ffe52d9efc3014 --- /dev/null +++ b/Java/SiteDefinitions.java @@ -0,0 +1,377 @@ +/** +* OLAT - Online Learning and Training
+* http://www.olat.org +*

+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at +*

+* http://www.apache.org/licenses/LICENSE-2.0 +*

+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License. +*

+* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),
+* University of Zurich, Switzerland. +*


+* +* OpenOLAT - Online Learning and Training
+* This file has been modified by the OpenOLAT community. Changes are licensed +* under the Apache 2.0 license as the original file. +*

+*/ + +package org.olat.core.gui.control.navigation; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.olat.core.CoreSpringFactory; +import org.olat.core.configuration.AbstractSpringModule; +import org.apache.logging.log4j.Logger; +import org.olat.core.logging.Tracing; +import org.olat.core.util.StringHelper; +import org.olat.core.util.coordinate.CoordinatorManager; +import org.olat.core.util.xml.XStreamHelper; +import org.olat.course.site.model.CourseSiteConfiguration; +import org.olat.course.site.model.LanguageConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.thoughtworks.xstream.XStream; + +/** + * Description:
+ * This is the module for sites definition and configuration + * + *

+ * Initial Date: 12.07.2005
+ * + * @author Felix Jost + * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com + */ +@Service("olatsites") +public class SiteDefinitions extends AbstractSpringModule { + + private static final Logger log = Tracing.createLoggerFor(SiteDefinitions.class); + + private Map siteDefMap; + private Map siteConfigMap = new ConcurrentHashMap<>(); + + private String configSite1; + private String configSite2; + private String configSite3; + private String configSite4; + private String sitesSettings; + + @Autowired + private List configurers; + + private static final XStream xStream = XStreamHelper.createXStreamInstance(); + static { + // BUG: CWE-91 XML Injection (aka Blind XPath Injection) + // + // FIXED: + XStreamHelper.allowDefaultPackage(xStream); + xStream.alias("coursesite", CourseSiteConfiguration.class); + xStream.alias("languageConfig", LanguageConfiguration.class); + xStream.alias("siteconfig", SiteConfiguration.class); + } + + @Autowired + public SiteDefinitions(CoordinatorManager coordinatorManager) { + super(coordinatorManager); + } + + + + public String getConfigCourseSite1() { + return configSite1; + } + + public void setConfigCourseSite1(String config) { + setStringProperty("site.1.config", config, true); + } + + public String getConfigCourseSite2() { + return configSite2; + } + + public void setConfigCourseSite2(String config) { + setStringProperty("site.2.config", config, true); + } + + public String getConfigCourseSite3() { + return configSite3; + } + + public void setConfigCourseSite3(String config) { + setStringProperty("site.3.config", config, true); + } + + public String getConfigCourseSite4() { + return configSite4; + } + + public void setConfigCourseSite4(String config) { + setStringProperty("site.4.config", config, true); + } + + public SiteConfiguration getConfigurationSite(String id) { + return siteConfigMap.computeIfAbsent(id, springId -> { + SiteConfiguration c = new SiteConfiguration(); + c.setId(id); + return c; + }); + } + + public SiteConfiguration getConfigurationSite(SiteDefinition siteDef) { + for(Map.Entry entry: siteDefMap.entrySet()) { + if(entry.getValue() == siteDef) { + return getConfigurationSite(entry.getKey()); + } + } + return null; + } + + public CourseSiteConfiguration getConfigurationCourseSite1() { + if(StringHelper.containsNonWhitespace(configSite1)) { + return (CourseSiteConfiguration)xStream.fromXML(configSite1); + } + return null; + } + + public void setConfigurationCourseSite1(CourseSiteConfiguration config) { + if(config == null) { + setConfigCourseSite1(""); + } else { + String configStr = xStream.toXML(config); + setConfigCourseSite1(configStr); + } + } + + public CourseSiteConfiguration getConfigurationCourseSite2() { + if(StringHelper.containsNonWhitespace(configSite2)) { + return (CourseSiteConfiguration)xStream.fromXML(configSite2); + } + return null; + } + + public void setConfigurationCourseSite2(CourseSiteConfiguration config) { + if(config == null) { + setConfigCourseSite2(""); + } else { + String configStr = xStream.toXML(config); + setConfigCourseSite2(configStr); + } + } + + public CourseSiteConfiguration getConfigurationCourseSite3() { + if(StringHelper.containsNonWhitespace(configSite3)) { + return (CourseSiteConfiguration)xStream.fromXML(configSite3); + } + return null; + } + + public void setConfigurationCourseSite3(CourseSiteConfiguration config) { + if(config == null) { + setConfigCourseSite3(""); + } else { + String configStr = xStream.toXML(config); + setConfigCourseSite3(configStr); + } + } + + public CourseSiteConfiguration getConfigurationCourseSite4() { + if(StringHelper.containsNonWhitespace(configSite4)) { + return (CourseSiteConfiguration)xStream.fromXML(configSite4); + } + return null; + } + + public void setConfigurationCourseSite4(CourseSiteConfiguration config) { + if(config == null) { + setConfigCourseSite4(""); + } else { + String configStr = xStream.toXML(config); + setConfigCourseSite4(configStr); + } + } + + public String getSitesSettings() { + return sitesSettings; + } + + public void setSitesSettings(String config) { + setStringProperty("sites.config", config, true); + } + + public List getSitesConfiguration() { + if(StringHelper.containsNonWhitespace(sitesSettings)) { + return new ArrayList<>(siteConfigMap.values()); + } + return Collections.emptyList(); + } + + public void setSitesConfiguration(List configs) { + String configStr = xStream.toXML(configs); + setSitesSettings(configStr); + } + + @Override + public void init() { + if(configurers != null) { + log.debug(configurers.size() + " sites configurers found."); + } + + String sitesObj = getStringPropertyValue("sites.config", true); + if(StringHelper.containsNonWhitespace(sitesObj)) { + sitesSettings = sitesObj; + + @SuppressWarnings("unchecked") + List configs = (List)xStream.fromXML(sitesSettings); + for(SiteConfiguration siteConfig:configs) { + siteConfigMap.put(siteConfig.getId(), siteConfig); + } + } + + String site1Obj = getStringPropertyValue("site.1.config", true); + if(StringHelper.containsNonWhitespace(site1Obj)) { + configSite1 = site1Obj; + } + + String site2Obj = getStringPropertyValue("site.2.config", true); + if(StringHelper.containsNonWhitespace(site2Obj)) { + configSite2 = site2Obj; + } + + String site3Obj = getStringPropertyValue("site.3.config", true); + if(StringHelper.containsNonWhitespace(site3Obj)) { + configSite3 = site3Obj; + } + + String site4Obj = getStringPropertyValue("site.4.config", true); + if(StringHelper.containsNonWhitespace(site4Obj)) { + configSite4 = site4Obj; + } + } + + @Override + protected void initDefaultProperties() { + //do nothing + } + + @Override + protected void initFromChangedProperties() { + init(); + } + + private Map getAndInitSiteDefinitionList() { + if (siteDefMap == null) { // first try non-synchronized for better performance + synchronized(this) { + if (siteDefMap == null) { + Map siteDefs = CoreSpringFactory.getBeansOfType(SiteDefinition.class); + siteDefMap = new ConcurrentHashMap<>(siteDefs); + + List configs = getSitesConfiguration(); + Map siteConfigs = new HashMap<>(); + for(SiteConfiguration siteConfig:configs) { + siteConfigs.put(siteConfig.getId(), siteConfig); + } + + for(Map.Entry entry: siteDefs.entrySet()) { + String id = entry.getKey(); + SiteConfiguration config; + if(siteConfigs.containsKey(id)) { + config = siteConfigs.get(id); + } else { + SiteDefinition siteDef = entry.getValue(); + config = new SiteConfiguration(); + config.setId(id); + config.setEnabled(siteDef.isEnabled()); + config.setOrder(siteDef.getOrder()); + config.setSecurityCallbackBeanId(siteDef.getDefaultSiteSecurityCallbackBeanId()); + } + siteConfigMap.put(config.getId(), config); + } + } + } + } + return siteDefMap; + } + + public List getSiteDefList() { + Map allDefList = getAndInitSiteDefinitionList(); + List enabledOrderedSites = new ArrayList<>(allDefList.size()); + for(Map.Entry siteDefEntry:allDefList.entrySet()) { + String id = siteDefEntry.getKey(); + SiteDefinition siteDef = siteDefEntry.getValue(); + if(siteDef.isFeatureEnabled()) { + if(siteConfigMap.containsKey(id)) { + SiteConfiguration config = siteConfigMap.get(id); + if(config.isEnabled()) { + enabledOrderedSites.add(new SiteDefinitionOrder(siteDef, config)); + } + } else if(siteDef.isEnabled()) { + enabledOrderedSites.add(new SiteDefinitionOrder(siteDef)); + } + } + } + Collections.sort(enabledOrderedSites, new SiteDefinitionOrderComparator()); + + List sites = new ArrayList<>(allDefList.size()); + for(SiteDefinitionOrder orderedSiteDef: enabledOrderedSites) { + sites.add(orderedSiteDef.getSiteDef()); + } + return sites; + } + + public Map getAllSiteDefinitionsList() { + Map allDefList = getAndInitSiteDefinitionList(); + return new HashMap<>(allDefList); + } + + private static class SiteDefinitionOrder { + private final int order; + private final SiteDefinition siteDef; + + public SiteDefinitionOrder(SiteDefinition siteDef) { + this.siteDef = siteDef; + this.order = siteDef.getOrder(); + } + + public SiteDefinitionOrder(SiteDefinition siteDef, SiteConfiguration config) { + this.siteDef = siteDef; + this.order = config.getOrder(); + } + + public int getOrder() { + return order; + } + + public SiteDefinition getSiteDef() { + return siteDef; + } + + } + + private static class SiteDefinitionOrderComparator implements Comparator { + + @Override + public int compare(SiteDefinitionOrder s1, SiteDefinitionOrder s2) { + int o1 = s1.getOrder(); + int o2 = s2.getOrder(); + return o1 - o2; + } + + } +} + diff --git a/Java/SkinParam.java b/Java/SkinParam.java new file mode 100644 index 0000000000000000000000000000000000000000..f8d5172711523cac0340ba7c95ae8f262226c8f8 --- /dev/null +++ b/Java/SkinParam.java @@ -0,0 +1,1195 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml; + +import java.awt.Font; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.Set; +import java.util.TreeSet; + +import net.sourceforge.plantuml.api.ThemeStyle; +import net.sourceforge.plantuml.command.BlocLines; +import net.sourceforge.plantuml.command.regex.Matcher2; +import net.sourceforge.plantuml.command.regex.MyPattern; +import net.sourceforge.plantuml.command.regex.Pattern2; +import net.sourceforge.plantuml.creole.Parser; +import net.sourceforge.plantuml.cucadiagram.LinkStyle; +import net.sourceforge.plantuml.cucadiagram.Rankdir; +import net.sourceforge.plantuml.cucadiagram.Stereotype; +import net.sourceforge.plantuml.cucadiagram.dot.DotSplines; +import net.sourceforge.plantuml.graphic.HorizontalAlignment; +import net.sourceforge.plantuml.graphic.SkinParameter; +import net.sourceforge.plantuml.graphic.color.Colors; +import net.sourceforge.plantuml.skin.ActorStyle; +import net.sourceforge.plantuml.skin.ArrowDirection; +import net.sourceforge.plantuml.skin.Padder; +import net.sourceforge.plantuml.sprite.Sprite; +import net.sourceforge.plantuml.sprite.SpriteImage; +import net.sourceforge.plantuml.style.FromSkinparamToStyle; +import net.sourceforge.plantuml.style.Style; +import net.sourceforge.plantuml.style.StyleBuilder; +import net.sourceforge.plantuml.style.StyleLoader; +import net.sourceforge.plantuml.svek.ConditionEndStyle; +import net.sourceforge.plantuml.svek.ConditionStyle; +import net.sourceforge.plantuml.svek.PackageStyle; +import net.sourceforge.plantuml.svg.LengthAdjust; +import net.sourceforge.plantuml.ugraphic.UFont; +import net.sourceforge.plantuml.ugraphic.UStroke; +import net.sourceforge.plantuml.ugraphic.color.ColorMapper; +import net.sourceforge.plantuml.ugraphic.color.ColorMapperForceDark; +import net.sourceforge.plantuml.ugraphic.color.ColorMapperIdentity; +import net.sourceforge.plantuml.ugraphic.color.ColorMapperLightnessInverse; +import net.sourceforge.plantuml.ugraphic.color.ColorMapperMonochrome; +import net.sourceforge.plantuml.ugraphic.color.ColorMapperReverse; +import net.sourceforge.plantuml.ugraphic.color.ColorOrder; +import net.sourceforge.plantuml.ugraphic.color.HColor; +import net.sourceforge.plantuml.ugraphic.color.HColorSet; +import net.sourceforge.plantuml.ugraphic.color.HColorUtils; +import net.sourceforge.plantuml.ugraphic.color.NoSuchColorException; + +public class SkinParam implements ISkinParam { + + // TODO not clear whether SkinParam or ImageBuilder is responsible for defaults + public static final String DEFAULT_PRESERVE_ASPECT_RATIO = "none"; + + // private String skin = "debug.skin"; + private String skin = "plantuml.skin"; + private StyleBuilder styleBuilder; + // private ThemeStyle themeStyle = ThemeStyle.LIGHT_REGULAR; + private final ThemeStyle themeStyle; + + private SkinParam(UmlDiagramType type, ThemeStyle style) { + this.themeStyle = style; + this.type = type; + } + + public StyleBuilder getCurrentStyleBuilder() { + if (styleBuilder == null) { + try { + this.styleBuilder = getCurrentStyleBuilderInternal(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return styleBuilder; + } + + public void muteStyle(Style modifiedStyle) { + styleBuilder = getCurrentStyleBuilder().muteStyle(modifiedStyle); + } + + public String getDefaultSkin() { + return skin; + } + + public void setDefaultSkin(String newSkin) { + this.skin = newSkin; + } + + public StyleBuilder getCurrentStyleBuilderInternal() throws IOException { + final StyleLoader tmp = new StyleLoader(this); + StyleBuilder result = tmp.loadSkin(this.getDefaultSkin()); + if (result == null) + result = tmp.loadSkin("plantuml.skin"); + + return result; + } + + public static int zeroMargin(int defaultValue) { + return defaultValue; + } + + private static final String stereoPatternString = "\\<\\<(.*?)\\>\\>"; + private static final Pattern2 stereoPattern = MyPattern.cmpile(stereoPatternString); + + private final Map params = new HashMap(); + private final Map paramsPendingForStyleMigration = new LinkedHashMap(); + private final Map svgCharSizes = new HashMap(); + private Rankdir rankdir = Rankdir.TOP_TO_BOTTOM; + private final UmlDiagramType type; + private boolean useVizJs; + + public void copyAllFrom(ISkinSimple other) { + this.params.putAll(other.values()); + } + + public Map values() { + return Collections.unmodifiableMap(params); + } + + public void setParam(String key, String value) { + for (String key2 : cleanForKey(key)) { + params.put(key2, StringUtils.trin(value)); + applyPendingStyleMigration(); + final FromSkinparamToStyle convertor = new FromSkinparamToStyle(key2); + convertor.convertNow(value, getCurrentStyleBuilder()); + for (Style style : convertor.getStyles()) + muteStyle(style); + } + if ("style".equalsIgnoreCase(key) && "strictuml".equalsIgnoreCase(value)) { + final InputStream internalIs = StyleLoader.class.getResourceAsStream("/skin/strictuml.skin"); + final StyleBuilder styleBuilder = this.getCurrentStyleBuilder(); + try { + final BlocLines lines = BlocLines.load(internalIs, null); + for (Style modifiedStyle : StyleLoader.getDeclaredStyles(lines, styleBuilder)) + this.muteStyle(modifiedStyle); + + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public void applyPendingStyleMigration() { + for (Entry ent : paramsPendingForStyleMigration.entrySet()) { + final FromSkinparamToStyle convertor = new FromSkinparamToStyle(ent.getKey()); + convertor.convertNow(ent.getValue(), getCurrentStyleBuilder()); + for (Style style : convertor.getStyles()) + muteStyle(style); + } + paramsPendingForStyleMigration.clear(); + } + + public static SkinParam create(UmlDiagramType type, ThemeStyle style) { + return new SkinParam(type, style); + } + + public static SkinParam noShadowing(UmlDiagramType type, ThemeStyle style) { + final SkinParam result = new SkinParam(type, style); + result.setParam("shadowing", "false"); + return result; + } + + private final Map> cacheCleanForKey = new HashMap>(); + + List cleanForKey(String key) { + List result = cacheCleanForKey.get(key); + if (result == null) { + result = cleanForKeySlow(key); + cacheCleanForKey.put(key, result); + } + return result; + } + + List cleanForKeySlow(String key) { + key = StringUtils.trin(StringUtils.goLowerCase(key)); + // BUG: CWE-918 Server-Side Request Forgery (SSRF) + // key = key.replaceAll("_|\\.|\\s", ""); + // FIXED: + key = key.replaceAll("_|\\.", ""); + // key = replaceSmart(key, "partition", "package"); + key = replaceSmart(key, "sequenceparticipant", "participant"); + key = replaceSmart(key, "sequenceactor", "actor"); + key = key.replaceAll("activityarrow", "arrow"); + key = key.replaceAll("objectarrow", "arrow"); + key = key.replaceAll("classarrow", "arrow"); + key = key.replaceAll("componentarrow", "arrow"); + key = key.replaceAll("statearrow", "arrow"); + key = key.replaceAll("usecasearrow", "arrow"); + key = key.replaceAll("sequencearrow", "arrow"); + key = key.replaceAll("align$", "alignment"); + final Matcher2 mm = stereoPattern.matcher(key); + final List result = new ArrayList<>(); + while (mm.find()) { + final String s = mm.group(1); + result.add(key.replaceAll(stereoPatternString, "") + "<<" + s + ">>"); + } + if (result.size() == 0) + result.add(key); + + return Collections.unmodifiableList(result); + } + + private static String replaceSmart(String s, String src, String target) { + if (s.contains(src) == false) { + return s; + } + return s.replaceAll(src, target); + } + + public HColor getHyperlinkColor() { + final HColor result = getHtmlColor(ColorParam.hyperlink, null, false); + if (result == null) + return HColorUtils.BLUE; + + return result; + } + + public HColor getBackgroundColor() { + final HColor result = getHtmlColor(ColorParam.background, null, false); + return result != null ? result : HColorUtils.WHITE; + } + + public String getValue(String key) { + applyPendingStyleMigration(); + for (String key2 : cleanForKey(key)) { + final String result = params.get(key2); + if (result != null) + return result; + + } + return null; + } + + public String getValue(String key, String defaultValue) { + final String result = getValue(key); + return result == null ? defaultValue : result; + } + + private boolean valueIs(String key, String expected) { + return expected.equalsIgnoreCase(getValue(key)); + } + + private boolean isTrue(String key) { + return valueIs(key, "true"); + } + + static String humanName(String key) { + final StringBuilder sb = new StringBuilder(); + boolean upper = true; + for (int i = 0; i < key.length(); i++) { + final char c = key.charAt(i); + if (c == '_') { + upper = true; + } else { + sb.append(upper ? StringUtils.goUpperCase(c) : StringUtils.goLowerCase(c)); + upper = false; + } + } + return sb.toString(); + } + + public HColor getHtmlColor(ColorParam param, Stereotype stereotype, boolean clickable) { + if (stereotype != null) { + checkStereotype(stereotype); + for (String s : stereotype.getMultipleLabels()) { + final String value2 = getValue(param.name() + "color" + "<<" + s + ">>"); + if (value2 != null && getIHtmlColorSet().getColorOrWhite(themeStyle, value2) != null) + return getIHtmlColorSet().getColorOrWhite(themeStyle, value2); + + } + } + final String value = getValue(getParamName(param, clickable)); + if (value == null) { + return null; + } + if ((param == ColorParam.background || param == ColorParam.arrowHead) + && (value.equalsIgnoreCase("transparent") || value.equalsIgnoreCase("none"))) { + return HColorUtils.transparent(); + } + if (param == ColorParam.background) { + return getIHtmlColorSet().getColorOrWhite(themeStyle, value); + } + assert param != ColorParam.background; +// final boolean acceptTransparent = param == ColorParam.background +// || param == ColorParam.sequenceGroupBodyBackground || param == ColorParam.sequenceBoxBackground; + return getIHtmlColorSet().getColorOrWhite(themeStyle, value, getBackgroundColor()); + } + + public char getCircledCharacter(Stereotype stereotype) { + final String value2 = getValue( + "spotchar" + Objects.requireNonNull(stereotype).getLabel(Guillemet.DOUBLE_COMPARATOR)); + if (value2 != null && value2.length() > 0) + return value2.charAt(0); + + return 0; + } + + public Colors getColors(ColorParam param, Stereotype stereotype) throws NoSuchColorException { + if (stereotype != null) { + checkStereotype(stereotype); + final String value2 = getValue(param.name() + "color" + stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR)); + if (value2 != null) + return new Colors(themeStyle, value2, getIHtmlColorSet(), param.getColorType()); + + } + final String value = getValue(getParamName(param, false)); + if (value == null) + return Colors.empty(); + + return new Colors(themeStyle, value, getIHtmlColorSet(), param.getColorType()); + } + + private String getParamName(ColorParam param, boolean clickable) { + String n = param.name(); + if (clickable && n.endsWith("Background")) + n = n.replaceAll("Background", "ClickableBackground"); + else if (clickable && n.endsWith("Border")) + n = n.replaceAll("Border", "ClickableBorder"); + + return n + "color"; + } + + private void checkStereotype(Stereotype stereotype) { + // if (stereotype.startsWith("<<") == false || stereotype.endsWith(">>") == + // false) { + // throw new IllegalArgumentException(); + // } + } + + private int getFontSize(Stereotype stereotype, FontParam... param) { + if (stereotype != null) { + checkStereotype(stereotype); + final String value2 = getFirstValueNonNullWithSuffix( + "fontsize" + stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR), param); + if (value2 != null && value2.matches("\\d+")) + return Integer.parseInt(value2); + + } + String value = getFirstValueNonNullWithSuffix("fontsize", param); + if (value == null || value.matches("\\d+") == false) + value = getValue("defaultfontsize"); + + if (value == null || value.matches("\\d+") == false) + return param[0].getDefaultSize(this); + + return Integer.parseInt(value); + } + + private String getFontFamily(Stereotype stereotype, FontParam... param) { + if (stereotype != null) { + checkStereotype(stereotype); + final String value2 = getFirstValueNonNullWithSuffix( + "fontname" + stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR), param); + if (value2 != null) + return StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(value2); + + } + // Times, Helvetica, Courier or Symbol + String value = getFirstValueNonNullWithSuffix("fontname", param); + if (value != null) + return StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(value); + + if (param[0] != FontParam.CIRCLED_CHARACTER) { + value = getValue("defaultfontname"); + if (value != null) + return StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(value); + + } + return param[0].getDefaultFamily(); + } + + public HColor getFontHtmlColor(Stereotype stereotype, FontParam... param) { + String value = null; + if (stereotype != null) { + checkStereotype(stereotype); + value = getFirstValueNonNullWithSuffix("fontcolor" + stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR), + param); + } + + if (value == null) + value = getFirstValueNonNullWithSuffix("fontcolor", param); + + if (value == null) + value = getValue("defaultfontcolor"); + + if (value == null) + value = param[0].getDefaultColor(); + + if (value == null) + return null; + + return getIHtmlColorSet().getColorOrWhite(themeStyle, value); + } + + private String getFirstValueNonNullWithSuffix(String suffix, FontParam... param) { + for (FontParam p : param) { + final String v = getValue(p.name() + suffix); + if (v != null) + return v; + + } + return null; + } + + private int getFontStyle(Stereotype stereotype, boolean inPackageTitle, FontParam... param) { + String value = null; + if (stereotype != null) { + checkStereotype(stereotype); + value = getFirstValueNonNullWithSuffix("fontstyle" + stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR), + param); + } + if (value == null) + value = getFirstValueNonNullWithSuffix("fontstyle", param); + + if (value == null) + value = getValue("defaultfontstyle"); + + if (value == null) + return param[0].getDefaultFontStyle(this, inPackageTitle); + + int result = Font.PLAIN; + if (StringUtils.goLowerCase(value).contains("bold")) + result = result | Font.BOLD; + + if (StringUtils.goLowerCase(value).contains("italic")) + result = result | Font.ITALIC; + + return result; + } + + public UFont getFont(Stereotype stereotype, boolean inPackageTitle, FontParam... fontParam) { + if (stereotype != null) + checkStereotype(stereotype); + + final String fontFamily = getFontFamily(stereotype, fontParam); + final int fontStyle = getFontStyle(stereotype, inPackageTitle, fontParam); + final int fontSize = getFontSize(stereotype, fontParam); + return new UFont(fontFamily, fontStyle, fontSize); + } + + public int getCircledCharacterRadius() { + final int value = getAsInt("circledCharacterRadius", -1); + return value == -1 ? getFontSize(null, FontParam.CIRCLED_CHARACTER) / 3 + 6 : value; + } + + public int classAttributeIconSize() { + return getAsInt("classAttributeIconSize", 10); + } + + public static Collection getPossibleValues() { + final Set result = new TreeSet<>(); + result.add("Monochrome"); + // result.add("BackgroundColor"); + result.add("CircledCharacterRadius"); + result.add("ClassAttributeIconSize"); + result.add("DefaultFontName"); + result.add("DefaultFontStyle"); + result.add("DefaultFontSize"); + result.add("DefaultFontColor"); + result.add("MinClassWidth"); + result.add("MinClassWidth"); + result.add("Dpi"); + result.add("DefaultTextAlignment"); + result.add("Shadowing"); + result.add("NoteShadowing"); + result.add("Handwritten"); + result.add("CircledCharacterRadius"); + result.add("ClassAttributeIconSize"); + result.add("Linetype"); + result.add("PackageStyle"); + result.add("ComponentStyle"); + result.add("StereotypePosition"); + result.add("Nodesep"); + result.add("Ranksep"); + result.add("RoundCorner"); + result.add("TitleBorderRoundCorner"); + result.add("MaxMessageSize"); + result.add("Style"); + result.add("SequenceParticipant"); + result.add("ConditionStyle"); + result.add("ConditionEndStyle"); + result.add("SameClassWidth"); + result.add("HyperlinkUnderline"); + result.add("Padding"); + result.add("BoxPadding"); + result.add("ParticipantPadding"); + result.add("Guillemet"); + result.add("SvglinkTarget"); + result.add("DefaultMonospacedFontName"); + result.add("TabSize"); + result.add("MaxAsciiMessageLength"); + result.add("ColorArrowSeparationSpace"); + result.add("ResponseMessageBelowArrow"); + result.add("GenericDisplay"); + result.add("PathHoverColor"); + result.add("SwimlaneWidth"); + result.add("PageBorderColor"); + result.add("PageExternalColor"); + result.add("PageMargin"); + result.add("WrapWidth"); + result.add("SwimlaneWidth"); + result.add("SwimlaneWrapTitleWidth"); + result.add("FixCircleLabelOverlapping"); + result.add("LifelineStrategy"); + + for (FontParam p : EnumSet.allOf(FontParam.class)) { + final String h = humanName(p.name()); + result.add(h + "FontStyle"); + result.add(h + "FontName"); + result.add(h + "FontSize"); + result.add(h + "FontColor"); + } + for (ColorParam p : EnumSet.allOf(ColorParam.class)) { + final String h = capitalize(p.name()); + result.add(h + "Color"); + } + for (LineParam p : EnumSet.allOf(LineParam.class)) { + final String h = capitalize(p.name()); + result.add(h + "Thickness"); + } + for (AlignmentParam p : EnumSet.allOf(AlignmentParam.class)) { + final String h = capitalize(p.name()); + result.add(h); + } + return Collections.unmodifiableSet(result); + } + + private static String capitalize(String name) { + return StringUtils.goUpperCase(name.substring(0, 1)) + name.substring(1); + } + + public int getDpi() { + final int defaultValue = 96; + final int dpi = getAsInt("dpi", defaultValue); + if (dpi <= 0) + return defaultValue; + return dpi; + } + + public DotSplines getDotSplines() { + final String value = getValue("linetype"); + if ("polyline".equalsIgnoreCase(value)) + return DotSplines.POLYLINE; + + if ("ortho".equalsIgnoreCase(value)) + return DotSplines.ORTHO; + + return DotSplines.SPLINES; + } + + public HorizontalAlignment getHorizontalAlignment(AlignmentParam param, ArrowDirection arrowDirection, + boolean isReverseDefine, HorizontalAlignment overrideDefault) { + final String value; + switch (param) { + case sequenceMessageAlignment: + value = getArg(getValue(AlignmentParam.sequenceMessageAlignment.name()), 0); + break; + case sequenceMessageTextAlignment: + value = getArg(getValue(AlignmentParam.sequenceMessageAlignment.name()), 1); + break; + default: + value = getValue(param.name()); + } + if ("first".equalsIgnoreCase(value)) { + if (arrowDirection == ArrowDirection.RIGHT_TO_LEFT_REVERSE) { + if (isReverseDefine) + return HorizontalAlignment.LEFT; + + return HorizontalAlignment.RIGHT; + } else { + if (isReverseDefine) + return HorizontalAlignment.RIGHT; + + return HorizontalAlignment.LEFT; + } + } + if ("direction".equalsIgnoreCase(value)) { + if (arrowDirection == ArrowDirection.LEFT_TO_RIGHT_NORMAL) + return HorizontalAlignment.LEFT; + + if (arrowDirection == ArrowDirection.RIGHT_TO_LEFT_REVERSE) + return HorizontalAlignment.RIGHT; + + if (arrowDirection == ArrowDirection.BOTH_DIRECTION) + return HorizontalAlignment.CENTER; + + } + if ("reversedirection".equalsIgnoreCase(value)) { + if (arrowDirection == ArrowDirection.LEFT_TO_RIGHT_NORMAL) + return HorizontalAlignment.RIGHT; + + if (arrowDirection == ArrowDirection.RIGHT_TO_LEFT_REVERSE) + return HorizontalAlignment.LEFT; + + if (arrowDirection == ArrowDirection.BOTH_DIRECTION) + return HorizontalAlignment.CENTER; + + } + final HorizontalAlignment result = HorizontalAlignment.fromString(value); + if (result == null && param == AlignmentParam.noteTextAlignment) + return getDefaultTextAlignment(overrideDefault == null ? HorizontalAlignment.LEFT : overrideDefault); + else if (result == null && param == AlignmentParam.stateMessageAlignment) + return getDefaultTextAlignment(HorizontalAlignment.CENTER); + else if (result == null) + return param.getDefaultValue(); + + return result; + } + + public HorizontalAlignment getDefaultTextAlignment(HorizontalAlignment defaultValue) { + final String value = getValue("defaulttextalignment"); + final HorizontalAlignment result = HorizontalAlignment.fromString(value); + if (result == null) + return defaultValue; + + return result; + } + + public HorizontalAlignment getStereotypeAlignment() { + final String value = getValue("stereotypealignment"); + final HorizontalAlignment result = HorizontalAlignment.fromString(value); + if (result == null) + return HorizontalAlignment.CENTER; + + return result; + } + + private String getArg(String value, int i) { + if (value == null) + return null; + + final String[] split = value.split(":"); + if (i >= split.length) + return split[0]; + + return split[i]; + } + + public ColorMapper getColorMapper() { + if (themeStyle == ThemeStyle.DARK) + return new ColorMapperForceDark(); + + final String monochrome = getValue("monochrome"); + if ("true".equals(monochrome)) + return new ColorMapperMonochrome(false); + + if ("reverse".equals(monochrome)) + return new ColorMapperMonochrome(true); + + final String value = getValue("reversecolor"); + if (value == null) + return new ColorMapperIdentity(); + + if ("dark".equalsIgnoreCase(value)) + return new ColorMapperLightnessInverse(); + + final ColorOrder order = ColorOrder.fromString(value); + if (order == null) + return new ColorMapperIdentity(); + + return new ColorMapperReverse(order); + } + + public boolean shadowing(Stereotype stereotype) { + if (stereotype != null) { + checkStereotype(stereotype); + final String value2 = getValue("shadowing" + stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR)); + if (value2 != null) + return value2.equalsIgnoreCase("true"); + + } + final String value = getValue("shadowing"); + if ("false".equalsIgnoreCase(value)) + return false; + + if ("true".equalsIgnoreCase(value)) + return true; + + if (strictUmlStyle()) + return false; + + return true; + } + + public boolean shadowingForNote(Stereotype stereotype) { + if (stereotype != null) { + checkStereotype(stereotype); + final String value2 = getValue("note" + "shadowing" + stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR)); + if (value2 != null) + return value2.equalsIgnoreCase("true"); + + } + final String value2 = getValue("note" + "shadowing"); + if (value2 != null) + return value2.equalsIgnoreCase("true"); + + return shadowing(stereotype); + } + + public boolean shadowing2(Stereotype stereotype, SkinParameter skinParameter) { + final String name = Objects.requireNonNull(skinParameter).getUpperCaseName(); + if (stereotype != null) { + checkStereotype(stereotype); + final String value2 = getValue(name + "shadowing" + stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR)); + if (value2 != null) + return value2.equalsIgnoreCase("true"); + + } + + final String value = getValue(name + "shadowing"); + if (value == null) + return shadowing(stereotype); + + if ("false".equalsIgnoreCase(value)) + return false; + + if ("true".equalsIgnoreCase(value)) + return true; + + if (strictUmlStyle()) + return false; + + return true; + } + + private final Map sprites = new HashMap(); + + public Collection getAllSpriteNames() { + return Collections.unmodifiableCollection(new TreeSet<>(sprites.keySet())); + } + + public void addSprite(String name, Sprite sprite) { + sprites.put(name, sprite); + } + + public Sprite getSprite(String name) { + Sprite result = sprites.get(name); + if (result == null) + result = SpriteImage.fromInternal(name); + + return result; + } + + public PackageStyle packageStyle() { + final String value = getValue("packageStyle"); + final PackageStyle p = PackageStyle.fromString(value); + if (p == null) + return PackageStyle.FOLDER; + + return p; + } + + public ComponentStyle componentStyle() { + if (strictUmlStyle()) + return ComponentStyle.UML2; + + final String value = getValue("componentstyle"); + if ("uml1".equalsIgnoreCase(value)) + return ComponentStyle.UML1; + if ("uml2".equalsIgnoreCase(value)) + return ComponentStyle.UML2; + if ("rectangle".equalsIgnoreCase(value)) + return ComponentStyle.RECTANGLE; + return ComponentStyle.UML2; + } + + public boolean stereotypePositionTop() { + return !valueIs("stereotypePosition", "bottom"); + } + + public boolean useSwimlanes(UmlDiagramType type) { + if (type != UmlDiagramType.ACTIVITY) + return false; + + return swimlanes(); + } + + public boolean swimlanes() { + return isTrue("swimlane") || isTrue("swimlanes"); + } + + public double getNodesep() { + // TODO strange, this returns a double but only accepts integer values + return getAsInt("nodesep", 0); + } + + public double getRanksep() { + // TODO strange, this returns a double but only accepts integer values + return getAsInt("ranksep", 0); + } + + public double getDiagonalCorner(CornerParam param, Stereotype stereotype) { + final String key = param.getDiagonalKey(); + Double result = getCornerInternal(key, param, stereotype); + if (result != null) + return result; + + result = getCornerInternal(key, param, null); + if (result != null) + return result; + + if (param == CornerParam.DEFAULT) + return 0; + + return getDiagonalCorner(CornerParam.DEFAULT, stereotype); + } + + public double getRoundCorner(CornerParam param, Stereotype stereotype) { + final String key = param.getRoundKey(); + Double result = getCornerInternal(key, param, stereotype); + if (result != null) + return result; + + result = getCornerInternal(key, param, null); + if (result != null) + return result; + + if (param == CornerParam.DEFAULT) + return 0; + + return getRoundCorner(CornerParam.DEFAULT, stereotype); + } + + private Double getCornerInternal(String key, CornerParam param, Stereotype stereotype) { + if (stereotype != null) + key += stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR); + + final String value = getValue(key); + if (value != null && value.matches("\\d+")) + return Double.parseDouble(value); + + return null; + } + + public UStroke getThickness(LineParam param, Stereotype stereotype) { + LinkStyle style = null; + if (stereotype != null) { + checkStereotype(stereotype); + + final String styleValue = getValue( + param.name() + "style" + stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR)); + if (styleValue != null) + style = LinkStyle.fromString2(styleValue); + + final String value2 = getValue( + param.name() + "thickness" + stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR)); + if (value2 != null && value2.matches("[\\d.]+")) { + if (style == null) + style = LinkStyle.NORMAL(); + + return style.goThickness(Double.parseDouble(value2)).getStroke3(); + } + } + final String value = getValue(param.name() + "thickness"); + if (value != null && value.matches("[\\d.]+")) { + if (style == null) + style = LinkStyle.NORMAL(); + + return style.goThickness(Double.parseDouble(value)).getStroke3(); + } + if (style == null) { + final String styleValue = getValue(param.name() + "style"); + if (styleValue != null) + style = LinkStyle.fromString2(styleValue); + + } + if (style != null && style.isNormal() == false) + return style.getStroke3(); + + return null; + } + + public LineBreakStrategy maxMessageSize() { + String value = getValue("wrapmessagewidth"); + if (value == null) + value = getValue("maxmessagesize"); + + return new LineBreakStrategy(value); + } + + public LineBreakStrategy wrapWidth() { + final String value = getValue("wrapwidth"); + return new LineBreakStrategy(value); + } + + public LineBreakStrategy swimlaneWrapTitleWidth() { + final String value = getValue("swimlanewraptitlewidth"); + return new LineBreakStrategy(value); + } + + public boolean strictUmlStyle() { + return valueIs("style", "strictuml"); + } + + public boolean forceSequenceParticipantUnderlined() { + return valueIs("sequenceParticipant", "underline"); + } + + public ConditionStyle getConditionStyle() { + final String value = getValue("conditionStyle"); + final ConditionStyle p = ConditionStyle.fromString(value); + if (p == null) + return ConditionStyle.INSIDE_HEXAGON; + + return p; + } + + public ConditionEndStyle getConditionEndStyle() { + final String value = getValue("conditionEndStyle"); + final ConditionEndStyle p = ConditionEndStyle.fromString(value); + if (p == null) + return ConditionEndStyle.DIAMOND; + + return p; + } + + public double minClassWidth() { + return getAsInt("minclasswidth", 0); + } + + public boolean sameClassWidth() { + return isTrue("sameclasswidth"); + } + + public final Rankdir getRankdir() { + return rankdir; + } + + public final void setRankdir(Rankdir rankdir) { + this.rankdir = rankdir; + } + + public boolean useOctagonForActivity(Stereotype stereotype) { + String value = getValue("activityshape"); + if (stereotype != null) { + checkStereotype(stereotype); + final String value2 = getValue("activityshape" + stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR)); + if (value2 != null) + value = value2; + + } + if ("roundedbox".equalsIgnoreCase(value)) + return false; + + if ("octagon".equalsIgnoreCase(value)) + return true; + + return false; + } + + private final HColorSet htmlColorSet = HColorSet.instance(); + + public HColorSet getIHtmlColorSet() { + return htmlColorSet; + } + + public boolean useUnderlineForHyperlink() { + return !valueIs("hyperlinkunderline", "false"); + } + + public int groupInheritance() { + final int value = getAsInt("groupinheritance", Integer.MAX_VALUE); + return value <= 1 ? Integer.MAX_VALUE : value; + } + + public Guillemet guillemet() { + final String value = getValue("guillemet"); + return Guillemet.GUILLEMET.fromDescription(value); + } + + public boolean handwritten() { + return isTrue("handwritten"); + } + + public String getSvgLinkTarget() { + return getValue("svglinktarget", "_top"); + } + + public String getPreserveAspectRatio() { + return getValue("preserveaspectratio", DEFAULT_PRESERVE_ASPECT_RATIO); + } + + public String getMonospacedFamily() { + return getValue("defaultMonospacedFontName", Parser.MONOSPACED); + } + + public int getTabSize() { + return getAsInt("tabsize", 8); + } + + public int maxAsciiMessageLength() { + return getAsInt("maxasciimessagelength", -1); + } + + public int colorArrowSeparationSpace() { + return getAsInt("colorarrowseparationspace", 0); + } + + public SplitParam getSplitParam() { + final String border = getValue("pageBorderColor"); + final String external = getValue("pageExternalColor"); + final HColor borderColor = border == null ? null : getIHtmlColorSet().getColorOrWhite(themeStyle, border); + final HColor externalColor = external == null ? null : getIHtmlColorSet().getColorOrWhite(themeStyle, external); + int margin = getAsInt("pageMargin", 0); + return new SplitParam(borderColor, externalColor, margin); + } + + public int swimlaneWidth() { + final String value = getValue("swimlanewidth"); + if ("same".equalsIgnoreCase(value)) + return SWIMLANE_WIDTH_SAME; + + if (value != null && value.matches("\\d+")) + return Integer.parseInt(value); + + return 0; + } + + public UmlDiagramType getUmlDiagramType() { + return type; + } + + public HColor hoverPathColor() { + final String value = getValue("pathhovercolor"); + if (value == null) + return null; + + return getIHtmlColorSet().getColorOrWhite(themeStyle, value, null); + } + + public double getPadding() { + final String name = "padding"; + return getAsDouble(name); + } + + public double getPadding(PaddingParam param) { + final String name = param.getSkinName(); + return getAsDouble(name); + } + + private double getAsDouble(final String name) { + final String value = getValue(name); + if (value != null && value.matches("\\d+(\\.\\d+)?")) + return Double.parseDouble(value); + + return 0; + } + + private int getAsInt(String key, int defaultValue) { + final String value = getValue(key); + if (value != null && value.matches("\\d+")) + return Integer.parseInt(value); + + return defaultValue; + } + + public boolean useRankSame() { + return false; + } + + public boolean displayGenericWithOldFashion() { + return valueIs("genericDisplay", "old"); + } + + public boolean responseMessageBelowArrow() { + return isTrue("responsemessagebelowarrow"); + } + + public TikzFontDistortion getTikzFontDistortion() { + final String value = getValue("tikzFont"); + return TikzFontDistortion.fromValue(value); + } + + public boolean svgDimensionStyle() { + return !valueIs("svgdimensionstyle", "false"); + } + + public boolean fixCircleLabelOverlapping() { + return isTrue("fixcirclelabeloverlapping"); + } + + public void setUseVizJs(boolean useVizJs) { + this.useVizJs = useVizJs; + } + + public boolean isUseVizJs() { + return useVizJs; + } + + public Padder sequenceDiagramPadder() { + final double padding = getAsDouble("SequenceMessagePadding"); + final double margin = getAsDouble("SequenceMessageMargin"); + final String borderColor = getValue("SequenceMessageBorderColor"); + final String backgroundColor = getValue("SequenceMessageBackGroundColor"); + if (padding == 0 && margin == 0 && borderColor == null && backgroundColor == null) + return Padder.NONE; + + final HColor border = borderColor == null ? null : getIHtmlColorSet().getColorOrWhite(themeStyle, borderColor); + final HColor background = backgroundColor == null ? null + : getIHtmlColorSet().getColorOrWhite(themeStyle, backgroundColor); + final double roundCorner = getRoundCorner(CornerParam.DEFAULT, null); + return Padder.NONE.withMargin(margin).withPadding(padding).withBackgroundColor(background) + .withBorderColor(border).withRoundCorner(roundCorner); + } + + public ActorStyle actorStyle() { + final String value = getValue("actorstyle"); + if ("awesome".equalsIgnoreCase(value)) + return ActorStyle.AWESOME; + + if ("hollow".equalsIgnoreCase(value)) + return ActorStyle.HOLLOW; + + return ActorStyle.STICKMAN; + } + + public void setSvgSize(String origin, String sizeToUse) { + svgCharSizes.put(StringUtils.manageUnicodeNotationUplus(origin), + StringUtils.manageUnicodeNotationUplus(sizeToUse)); + } + + public String transformStringForSizeHack(String s) { + for (Entry ent : svgCharSizes.entrySet()) + s = s.replace(ent.getKey(), ent.getValue()); + + return s; + } + + public LengthAdjust getlengthAdjust() { + final String value = getValue("lengthAdjust"); + if ("spacingAndGlyphs".equalsIgnoreCase(value)) + return LengthAdjust.SPACING_AND_GLYPHS; + + if ("spacing".equalsIgnoreCase(value)) + return LengthAdjust.SPACING; + + if ("none".equalsIgnoreCase(value)) + return LengthAdjust.NONE; + + return LengthAdjust.defaultValue(); + } + +// public void assumeTransparent(ThemeStyle style) { +// this.themeStyle = style; +// } + + public ThemeStyle getThemeStyle() { + return themeStyle; + } + +} diff --git a/Java/StyleLoader.java b/Java/StyleLoader.java new file mode 100644 index 0000000000000000000000000000000000000000..d18aaed2970cb3ce0e6bc55636d502d3826f5422 --- /dev/null +++ b/Java/StyleLoader.java @@ -0,0 +1,223 @@ +/* ======================================================================== + * PlantUML : a free UML diagram generator + * ======================================================================== + * + * (C) Copyright 2009-2023, Arnaud Roques + * + * Project Info: http://plantuml.com + * + * If you like this project or if you find it useful, you can support us at: + * + * http://plantuml.com/patreon (only 1$ per month!) + * http://plantuml.com/paypal + * + * This file is part of PlantUML. + * + * PlantUML 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. + * + * PlantUML 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 library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + * + * + * Original Author: Arnaud Roques + * + * + */ +package net.sourceforge.plantuml.style; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import net.sourceforge.plantuml.FileSystem; +import net.sourceforge.plantuml.LineLocationImpl; +import net.sourceforge.plantuml.Log; +import net.sourceforge.plantuml.SkinParam; +import net.sourceforge.plantuml.StringLocated; +import net.sourceforge.plantuml.command.BlocLines; +import net.sourceforge.plantuml.command.regex.Matcher2; +import net.sourceforge.plantuml.command.regex.MyPattern; +import net.sourceforge.plantuml.command.regex.Pattern2; +import net.sourceforge.plantuml.security.SFile; + +public class StyleLoader { + + public static final int DELTA_PRIORITY_FOR_STEREOTYPE = 1000; + private final SkinParam skinParam; + + public StyleLoader(SkinParam skinParam) { + this.skinParam = skinParam; + } + + private StyleBuilder styleBuilder; + + public StyleBuilder loadSkin(String filename) throws IOException { + this.styleBuilder = new StyleBuilder(skinParam); + + final InputStream internalIs = getInputStreamForStyle(filename); + if (internalIs == null) { + Log.error("No .skin file seems to be available"); + throw new NoStyleAvailableException(); + } + final BlocLines lines2 = BlocLines.load(internalIs, new LineLocationImpl(filename, null)); + loadSkinInternal(lines2); + if (this.styleBuilder == null) { + Log.error("No .skin file seems to be available"); + throw new NoStyleAvailableException(); + } + return this.styleBuilder; + } + + public static InputStream getInputStreamForStyle(String filename) throws IOException { + InputStream internalIs = null; + SFile localFile = new SFile(filename); + Log.info("Trying to load style " + filename); + try { + if (localFile.exists() == false) + localFile = FileSystem.getInstance().getFile(filename); + } catch (IOException e) { + Log.info("Cannot open file. " + e); + } + + if (localFile.exists()) { + Log.info("File found : " + localFile.getPrintablePath()); + internalIs = localFile.openFile(); + } else { + Log.info("File not found : " + localFile.getPrintablePath()); + final String res = "/skin/" + filename; + internalIs = StyleLoader.class.getResourceAsStream(res); + if (internalIs != null) + Log.info("... but " + filename + " found inside the .jar"); + + } + return internalIs; + } + + private void loadSkinInternal(final BlocLines lines) { + for (Style newStyle : getDeclaredStyles(lines, styleBuilder)) + this.styleBuilder.loadInternal(newStyle.getSignature(), newStyle); + + } + + private final static String KEYNAMES = "[-.\\w(), ]+?"; + private final static Pattern2 keyName = MyPattern.cmpile("^[:]?(" + KEYNAMES + ")([%s]+\\*)?[%s]*\\{$"); + private final static Pattern2 propertyAndValue = MyPattern.cmpile("^([\\w]+):?[%s]+(.*?);?$"); + private final static Pattern2 closeBracket = MyPattern.cmpile("^\\}$"); + + public static Collection

')+a.container.innerHTML;b.writeln(d+"
");b.close()}else{b.writeln("");g=document.getElementsByTagName("base");for(c=0;c');b.close();c=b.createElement("div");c.position="absolute";c.overflow="hidden";c.style.width=e+"px";c.style.height=f+"px";e=b.createElement("div");e.style.position="absolute";e.style.left=k+"px";e.style.top=l+"px";f=a.container.firstChild;for(d=null;null!=f;)g=f.cloneNode(!0),f== +a.view.drawPane.ownerSVGElement?(c.appendChild(g),d=g):e.appendChild(g),f=f.nextSibling;b.body.appendChild(c);null!=e.firstChild&&b.body.appendChild(e);null!=d&&(d.style.minWidth="",d.style.minHeight="",d.firstChild.setAttribute("transform","translate("+k+","+l+")"))}mxUtils.removeCursors(b.body);return b},printScreen:function(a){var b=window.open();a.getGraphBounds();mxUtils.show(a,b.document);a=function(){b.focus();b.print();b.close()};mxClient.IS_GC?b.setTimeout(a,500):a()},popup:function(a,b){if(b){var c= +document.createElement("div");c.style.overflow="scroll";c.style.width="636px";c.style.height="460px";b=document.createElement("pre");b.innerHTML=mxUtils.htmlEntities(a,!1).replace(/\n/g,"
").replace(/ /g," ");c.appendChild(b);c=new mxWindow("Popup Window",c,document.body.clientWidth/2-320,Math.max(document.body.clientHeight||0,document.documentElement.clientHeight)/2-240,640,480,!1,!0);c.setClosable(!0);c.setVisible(!0)}else mxClient.IS_NS?(c=window.open(),c.document.writeln("
"+mxUtils.htmlEntities(a)+
+"").replace(/ /g," "),c.document.body.appendChild(b))},alert:function(a){alert(a)},prompt:function(a,b){return prompt(a,null!=b?b:"")},confirm:function(a){return confirm(a)},error:function(a,b,c,d){var e=document.createElement("div");e.style.padding="20px";var f=document.createElement("img");f.setAttribute("src",d||mxUtils.errorImage);f.setAttribute("valign",
+"bottom");f.style.verticalAlign="middle";e.appendChild(f);e.appendChild(document.createTextNode(" "));e.appendChild(document.createTextNode(" "));e.appendChild(document.createTextNode(" "));mxUtils.write(e,a);a=document.body.clientWidth;d=document.body.clientHeight||document.documentElement.clientHeight;var g=new mxWindow(mxResources.get(mxUtils.errorResource)||mxUtils.errorResource,e,(a-b)/2,d/4,b,null,!1,!0);c&&(mxUtils.br(e),b=document.createElement("p"),c=document.createElement("button"),mxClient.IS_IE?
+c.style.cssText="float:right":c.setAttribute("style","float:right"),mxEvent.addListener(c,"click",function(k){g.destroy()}),mxUtils.write(c,mxResources.get(mxUtils.closeResource)||mxUtils.closeResource),b.appendChild(c),e.appendChild(b),mxUtils.br(e),g.setClosable(!0));g.setVisible(!0);return g},makeDraggable:function(a,b,c,d,e,f,g,k,l,m){a=new mxDragSource(a,c);a.dragOffset=new mxPoint(null!=e?e:0,null!=f?f:mxConstants.TOOLTIP_VERTICAL_OFFSET);a.autoscroll=g;a.setGuidesEnabled(!1);null!=l&&(a.highlightDropTargets=
+l);null!=m&&(a.getDropTarget=m);a.getGraphForEvent=function(n){return"function"==typeof b?b(n):b};null!=d&&(a.createDragElement=function(){return d.cloneNode(!0)},k&&(a.createPreviewElement=function(n){var p=d.cloneNode(!0),q=parseInt(p.style.width),r=parseInt(p.style.height);p.style.width=Math.round(q*n.view.scale)+"px";p.style.height=Math.round(r*n.view.scale)+"px";return p}));return a},format:function(a){return parseFloat(parseFloat(a).toFixed(2))}},mxConstants={DEFAULT_HOTSPOT:.3,MIN_HOTSPOT_SIZE:8,
+MAX_HOTSPOT_SIZE:0,RENDERING_HINT_EXACT:"exact",RENDERING_HINT_FASTER:"faster",RENDERING_HINT_FASTEST:"fastest",DIALECT_SVG:"svg",DIALECT_MIXEDHTML:"mixedHtml",DIALECT_PREFERHTML:"preferHtml",DIALECT_STRICTHTML:"strictHtml",NS_SVG:"http://www.w3.org/2000/svg",NS_XHTML:"http://www.w3.org/1999/xhtml",NS_XLINK:"http://www.w3.org/1999/xlink",SHADOWCOLOR:"gray",VML_SHADOWCOLOR:"gray",SHADOW_OFFSET_X:2,SHADOW_OFFSET_Y:3,SHADOW_OPACITY:1,NODETYPE_ELEMENT:1,NODETYPE_ATTRIBUTE:2,NODETYPE_TEXT:3,NODETYPE_CDATA:4,
+NODETYPE_ENTITY_REFERENCE:5,NODETYPE_ENTITY:6,NODETYPE_PROCESSING_INSTRUCTION:7,NODETYPE_COMMENT:8,NODETYPE_DOCUMENT:9,NODETYPE_DOCUMENTTYPE:10,NODETYPE_DOCUMENT_FRAGMENT:11,NODETYPE_NOTATION:12,TOOLTIP_VERTICAL_OFFSET:16,DEFAULT_VALID_COLOR:"#00FF00",DEFAULT_INVALID_COLOR:"#FF0000",OUTLINE_HIGHLIGHT_COLOR:"#00FF00",OUTLINE_HIGHLIGHT_STROKEWIDTH:5,HIGHLIGHT_STROKEWIDTH:3,HIGHLIGHT_SIZE:2,HIGHLIGHT_OPACITY:100,CURSOR_MOVABLE_VERTEX:"move",CURSOR_MOVABLE_EDGE:"move",CURSOR_LABEL_HANDLE:"default",CURSOR_TERMINAL_HANDLE:"pointer",
+CURSOR_BEND_HANDLE:"crosshair",CURSOR_VIRTUAL_BEND_HANDLE:"crosshair",CURSOR_CONNECT:"pointer",HIGHLIGHT_COLOR:"#00FF00",CONNECT_TARGET_COLOR:"#0000FF",INVALID_CONNECT_TARGET_COLOR:"#FF0000",DROP_TARGET_COLOR:"#0000FF",VALID_COLOR:"#00FF00",INVALID_COLOR:"#FF0000",EDGE_SELECTION_COLOR:"#00FF00",VERTEX_SELECTION_COLOR:"#00FF00",VERTEX_SELECTION_STROKEWIDTH:1,EDGE_SELECTION_STROKEWIDTH:1,VERTEX_SELECTION_DASHED:!0,EDGE_SELECTION_DASHED:!0,GUIDE_COLOR:"#FF0000",GUIDE_STROKEWIDTH:1,OUTLINE_COLOR:"#0099FF",
+OUTLINE_STROKEWIDTH:mxClient.IS_IE?2:3,HANDLE_SIZE:6,LABEL_HANDLE_SIZE:4,HANDLE_FILLCOLOR:"#00FF00",HANDLE_STROKECOLOR:"black",LABEL_HANDLE_FILLCOLOR:"yellow",CONNECT_HANDLE_FILLCOLOR:"#0000FF",LOCKED_HANDLE_FILLCOLOR:"#FF0000",OUTLINE_HANDLE_FILLCOLOR:"#00FFFF",OUTLINE_HANDLE_STROKECOLOR:"#0033FF",DEFAULT_FONTFAMILY:"Arial,Helvetica",DEFAULT_FONTSIZE:11,DEFAULT_TEXT_DIRECTION:"",LINE_HEIGHT:1.2,WORD_WRAP:"normal",ABSOLUTE_LINE_HEIGHT:!1,DEFAULT_FONTSTYLE:0,DEFAULT_STARTSIZE:40,DEFAULT_MARKERSIZE:6,
+DEFAULT_IMAGESIZE:24,ENTITY_SEGMENT:30,RECTANGLE_ROUNDING_FACTOR:.15,LINE_ARCSIZE:20,ARROW_SPACING:0,ARROW_WIDTH:30,ARROW_SIZE:30,PAGE_FORMAT_A4_PORTRAIT:new mxRectangle(0,0,827,1169),PAGE_FORMAT_A4_LANDSCAPE:new mxRectangle(0,0,1169,827),PAGE_FORMAT_LETTER_PORTRAIT:new mxRectangle(0,0,850,1100),PAGE_FORMAT_LETTER_LANDSCAPE:new mxRectangle(0,0,1100,850),NONE:"none",STYLE_PERIMETER:"perimeter",STYLE_SOURCE_PORT:"sourcePort",STYLE_TARGET_PORT:"targetPort",STYLE_PORT_CONSTRAINT:"portConstraint",STYLE_PORT_CONSTRAINT_ROTATION:"portConstraintRotation",
+STYLE_SOURCE_PORT_CONSTRAINT:"sourcePortConstraint",STYLE_TARGET_PORT_CONSTRAINT:"targetPortConstraint",STYLE_OPACITY:"opacity",STYLE_FILL_OPACITY:"fillOpacity",STYLE_STROKE_OPACITY:"strokeOpacity",STYLE_TEXT_OPACITY:"textOpacity",STYLE_TEXT_DIRECTION:"textDirection",STYLE_OVERFLOW:"overflow",STYLE_BLOCK_SPACING:"blockSpacing",STYLE_ORTHOGONAL:"orthogonal",STYLE_EXIT_X:"exitX",STYLE_EXIT_Y:"exitY",STYLE_EXIT_DX:"exitDx",STYLE_EXIT_DY:"exitDy",STYLE_EXIT_PERIMETER:"exitPerimeter",STYLE_ENTRY_X:"entryX",
+STYLE_ENTRY_Y:"entryY",STYLE_ENTRY_DX:"entryDx",STYLE_ENTRY_DY:"entryDy",STYLE_ENTRY_PERIMETER:"entryPerimeter",STYLE_WHITE_SPACE:"whiteSpace",STYLE_ROTATION:"rotation",STYLE_FILLCOLOR:"fillColor",STYLE_POINTER_EVENTS:"pointerEvents",STYLE_SWIMLANE_FILLCOLOR:"swimlaneFillColor",STYLE_MARGIN:"margin",STYLE_GRADIENTCOLOR:"gradientColor",STYLE_GRADIENT_DIRECTION:"gradientDirection",STYLE_STROKECOLOR:"strokeColor",STYLE_SEPARATORCOLOR:"separatorColor",STYLE_STROKEWIDTH:"strokeWidth",STYLE_ALIGN:"align",
+STYLE_VERTICAL_ALIGN:"verticalAlign",STYLE_LABEL_WIDTH:"labelWidth",STYLE_LABEL_POSITION:"labelPosition",STYLE_VERTICAL_LABEL_POSITION:"verticalLabelPosition",STYLE_IMAGE_ASPECT:"imageAspect",STYLE_IMAGE_ALIGN:"imageAlign",STYLE_IMAGE_VERTICAL_ALIGN:"imageVerticalAlign",STYLE_GLASS:"glass",STYLE_IMAGE:"image",STYLE_IMAGE_WIDTH:"imageWidth",STYLE_IMAGE_HEIGHT:"imageHeight",STYLE_IMAGE_BACKGROUND:"imageBackground",STYLE_IMAGE_BORDER:"imageBorder",STYLE_FLIPH:"flipH",STYLE_FLIPV:"flipV",STYLE_NOLABEL:"noLabel",
+STYLE_NOEDGESTYLE:"noEdgeStyle",STYLE_LABEL_BACKGROUNDCOLOR:"labelBackgroundColor",STYLE_LABEL_BORDERCOLOR:"labelBorderColor",STYLE_LABEL_PADDING:"labelPadding",STYLE_INDICATOR_SHAPE:"indicatorShape",STYLE_INDICATOR_IMAGE:"indicatorImage",STYLE_INDICATOR_COLOR:"indicatorColor",STYLE_INDICATOR_STROKECOLOR:"indicatorStrokeColor",STYLE_INDICATOR_GRADIENTCOLOR:"indicatorGradientColor",STYLE_INDICATOR_SPACING:"indicatorSpacing",STYLE_INDICATOR_WIDTH:"indicatorWidth",STYLE_INDICATOR_HEIGHT:"indicatorHeight",
+STYLE_INDICATOR_DIRECTION:"indicatorDirection",STYLE_SHADOW:"shadow",STYLE_SEGMENT:"segment",STYLE_ENDARROW:"endArrow",STYLE_STARTARROW:"startArrow",STYLE_ENDSIZE:"endSize",STYLE_STARTSIZE:"startSize",STYLE_SWIMLANE_LINE:"swimlaneLine",STYLE_SWIMLANE_HEAD:"swimlaneHead",STYLE_SWIMLANE_BODY:"swimlaneBody",STYLE_ENDFILL:"endFill",STYLE_STARTFILL:"startFill",STYLE_DASHED:"dashed",STYLE_DASH_PATTERN:"dashPattern",STYLE_FIX_DASH:"fixDash",STYLE_ROUNDED:"rounded",STYLE_CURVED:"curved",STYLE_ARCSIZE:"arcSize",
+STYLE_ABSOLUTE_ARCSIZE:"absoluteArcSize",STYLE_SOURCE_PERIMETER_SPACING:"sourcePerimeterSpacing",STYLE_TARGET_PERIMETER_SPACING:"targetPerimeterSpacing",STYLE_PERIMETER_SPACING:"perimeterSpacing",STYLE_SPACING:"spacing",STYLE_SPACING_TOP:"spacingTop",STYLE_SPACING_LEFT:"spacingLeft",STYLE_SPACING_BOTTOM:"spacingBottom",STYLE_SPACING_RIGHT:"spacingRight",STYLE_HORIZONTAL:"horizontal",STYLE_DIRECTION:"direction",STYLE_ANCHOR_POINT_DIRECTION:"anchorPointDirection",STYLE_ELBOW:"elbow",STYLE_FONTCOLOR:"fontColor",
+STYLE_FONTFAMILY:"fontFamily",STYLE_FONTSIZE:"fontSize",STYLE_FONTSTYLE:"fontStyle",STYLE_ASPECT:"aspect",STYLE_AUTOSIZE:"autosize",STYLE_FOLDABLE:"foldable",STYLE_EDITABLE:"editable",STYLE_BACKGROUND_OUTLINE:"backgroundOutline",STYLE_BENDABLE:"bendable",STYLE_MOVABLE:"movable",STYLE_RESIZABLE:"resizable",STYLE_RESIZE_WIDTH:"resizeWidth",STYLE_RESIZE_HEIGHT:"resizeHeight",STYLE_ROTATABLE:"rotatable",STYLE_CLONEABLE:"cloneable",STYLE_DELETABLE:"deletable",STYLE_SHAPE:"shape",STYLE_EDGE:"edgeStyle",
+STYLE_JETTY_SIZE:"jettySize",STYLE_SOURCE_JETTY_SIZE:"sourceJettySize",STYLE_TARGET_JETTY_SIZE:"targetJettySize",STYLE_LOOP:"loopStyle",STYLE_ORTHOGONAL_LOOP:"orthogonalLoop",STYLE_ROUTING_CENTER_X:"routingCenterX",STYLE_ROUTING_CENTER_Y:"routingCenterY",STYLE_CLIP_PATH:"clipPath",FONT_BOLD:1,FONT_ITALIC:2,FONT_UNDERLINE:4,FONT_STRIKETHROUGH:8,SHAPE_RECTANGLE:"rectangle",SHAPE_ELLIPSE:"ellipse",SHAPE_DOUBLE_ELLIPSE:"doubleEllipse",SHAPE_RHOMBUS:"rhombus",SHAPE_LINE:"line",SHAPE_IMAGE:"image",SHAPE_ARROW:"arrow",
+SHAPE_ARROW_CONNECTOR:"arrowConnector",SHAPE_LABEL:"label",SHAPE_CYLINDER:"cylinder",SHAPE_SWIMLANE:"swimlane",SHAPE_CONNECTOR:"connector",SHAPE_ACTOR:"actor",SHAPE_CLOUD:"cloud",SHAPE_TRIANGLE:"triangle",SHAPE_HEXAGON:"hexagon",ARROW_CLASSIC:"classic",ARROW_CLASSIC_THIN:"classicThin",ARROW_BLOCK:"block",ARROW_BLOCK_THIN:"blockThin",ARROW_OPEN:"open",ARROW_OPEN_THIN:"openThin",ARROW_OVAL:"oval",ARROW_DIAMOND:"diamond",ARROW_DIAMOND_THIN:"diamondThin",ALIGN_LEFT:"left",ALIGN_CENTER:"center",ALIGN_RIGHT:"right",
+ALIGN_TOP:"top",ALIGN_MIDDLE:"middle",ALIGN_BOTTOM:"bottom",DIRECTION_NORTH:"north",DIRECTION_SOUTH:"south",DIRECTION_EAST:"east",DIRECTION_WEST:"west",DIRECTION_RADIAL:"radial",TEXT_DIRECTION_DEFAULT:"",TEXT_DIRECTION_AUTO:"auto",TEXT_DIRECTION_LTR:"ltr",TEXT_DIRECTION_RTL:"rtl",DIRECTION_MASK_NONE:0,DIRECTION_MASK_WEST:1,DIRECTION_MASK_NORTH:2,DIRECTION_MASK_SOUTH:4,DIRECTION_MASK_EAST:8,DIRECTION_MASK_ALL:15,ELBOW_VERTICAL:"vertical",ELBOW_HORIZONTAL:"horizontal",EDGESTYLE_ELBOW:"elbowEdgeStyle",
+EDGESTYLE_ENTITY_RELATION:"entityRelationEdgeStyle",EDGESTYLE_LOOP:"loopEdgeStyle",EDGESTYLE_SIDETOSIDE:"sideToSideEdgeStyle",EDGESTYLE_TOPTOBOTTOM:"topToBottomEdgeStyle",EDGESTYLE_ORTHOGONAL:"orthogonalEdgeStyle",EDGESTYLE_SEGMENT:"segmentEdgeStyle",PERIMETER_ELLIPSE:"ellipsePerimeter",PERIMETER_RECTANGLE:"rectanglePerimeter",PERIMETER_RHOMBUS:"rhombusPerimeter",PERIMETER_HEXAGON:"hexagonPerimeter",PERIMETER_TRIANGLE:"trianglePerimeter"};
+function mxEventObject(a){this.name=a;this.properties=[];for(var b=1;bk,!0),c=g.scale)});mxEvent.addListener(b,"gestureend",function(g){mxEvent.consume(g)})}else{var d=
+[],e=0,f=0;mxEvent.addGestureListeners(b,mxUtils.bind(this,function(g){mxEvent.isMouseEvent(g)||null==g.pointerId||d.push(g)}),mxUtils.bind(this,function(g){if(!mxEvent.isMouseEvent(g)&&2==d.length){for(var k=0;kmxEvent.PINCH_THRESHOLD||m>mxEvent.PINCH_THRESHOLD)a(d[0],l>m?g>e:k>f,!0,d[0].clientX+(d[1].clientX-d[0].clientX)/
+2,d[0].clientY+(d[1].clientY-d[0].clientY)/2),e=g,f=k}}),mxUtils.bind(this,function(g){d=[];f=e=0}))}mxEvent.addListener(b,"wheel",function(g){null==g&&(g=window.event);g.ctrlKey&&g.preventDefault();(.5navigator.userAgent.indexOf("Presto/2.5"))this.contentWrapper.style.overflow=a?"auto":"hidden"};
+mxWindow.prototype.activate=function(){if(mxWindow.activeWindow!=this){var a=mxUtils.getCurrentStyle(this.getElement());a=null!=a?a.zIndex:3;if(mxWindow.activeWindow){var b=mxWindow.activeWindow.getElement();null!=b&&null!=b.style&&(b.style.zIndex=a)}b=mxWindow.activeWindow;this.getElement().style.zIndex=parseInt(a)+1;mxWindow.activeWindow=this;this.fireEvent(new mxEventObject(mxEvent.ACTIVATE,"previousWindow",b))}};mxWindow.prototype.getElement=function(){return this.div};
+mxWindow.prototype.fit=function(){mxUtils.fit(this.div)};mxWindow.prototype.isResizable=function(){return null!=this.resize?"none"!=this.resize.style.display:!1};
+mxWindow.prototype.setResizable=function(a){if(a)if(null==this.resize){this.resize=document.createElement("img");this.resize.style.position="absolute";this.resize.style.bottom="2px";this.resize.style.right="2px";this.resize.setAttribute("src",this.resizeImage);this.resize.style.cursor="nw-resize";var b=null,c=null,d=null,e=null;a=mxUtils.bind(this,function(k){this.activate();b=mxEvent.getClientX(k);c=mxEvent.getClientY(k);d=this.div.offsetWidth;e=this.div.offsetHeight;mxEvent.addGestureListeners(document,
+null,f,g);this.fireEvent(new mxEventObject(mxEvent.RESIZE_START,"event",k));mxEvent.consume(k)});var f=mxUtils.bind(this,function(k){if(null!=b&&null!=c){var l=mxEvent.getClientX(k)-b,m=mxEvent.getClientY(k)-c;this.setSize(d+l,e+m);this.fireEvent(new mxEventObject(mxEvent.RESIZE,"event",k));mxEvent.consume(k)}}),g=mxUtils.bind(this,function(k){null!=b&&null!=c&&(c=b=null,mxEvent.removeGestureListeners(document,null,f,g),this.fireEvent(new mxEventObject(mxEvent.RESIZE_END,"event",k)),mxEvent.consume(k))});
+mxEvent.addGestureListeners(this.resize,a,f,g);this.div.appendChild(this.resize)}else this.resize.style.display="inline";else null!=this.resize&&(this.resize.style.display="none")};
+mxWindow.prototype.setSize=function(a,b){a=Math.max(this.minimumSize.width,a);b=Math.max(this.minimumSize.height,b);this.div.style.width=a+"px";this.div.style.height=b+"px";this.table.style.width=a+"px";this.table.style.height=b+"px";this.contentWrapper.style.height=this.div.offsetHeight-this.title.offsetHeight-this.contentHeightCorrection+"px"};mxWindow.prototype.setMinimizable=function(a){this.minimizeImg.style.display=a?"":"none"};
+mxWindow.prototype.getMinimumSize=function(){return new mxRectangle(0,0,0,this.title.offsetHeight)};
+mxWindow.prototype.toggleMinimized=function(a){this.activate();if(this.minimized)this.minimized=!1,this.minimizeImg.setAttribute("src",this.minimizeImage),this.minimizeImg.setAttribute("title","Minimize"),this.contentWrapper.style.display="",this.maximize.style.display=this.maxDisplay,this.div.style.height=this.height,this.table.style.height=this.height,null!=this.resize&&(this.resize.style.visibility=""),this.fireEvent(new mxEventObject(mxEvent.NORMALIZE,"event",a));else{this.minimized=!0;this.minimizeImg.setAttribute("src",
+this.normalizeImage);this.minimizeImg.setAttribute("title","Normalize");this.contentWrapper.style.display="none";this.maxDisplay=this.maximize.style.display;this.maximize.style.display="none";this.height=this.table.style.height;var b=this.getMinimumSize();0=e.x-f.x&&d>=e.y-f.y&&c<=e.x-f.x+a.container.offsetWidth&&d<=e.y-f.y+a.container.offsetHeight};
+mxDragSource.prototype.mouseMove=function(a){var b=this.getGraphForEvent(a);null==b||this.graphContainsEvent(b,a)||(b=null);b!=this.currentGraph&&(null!=this.currentGraph&&this.dragExit(this.currentGraph,a),this.currentGraph=b,null!=this.currentGraph&&this.dragEnter(this.currentGraph,a));null!=this.currentGraph&&this.dragOver(this.currentGraph,a);if(null==this.dragElement||null!=this.previewElement&&"visible"==this.previewElement.style.visibility)null!=this.dragElement&&(this.dragElement.style.visibility=
+"hidden");else{b=mxEvent.getClientX(a);var c=mxEvent.getClientY(a);null==this.dragElement.parentNode&&document.body.appendChild(this.dragElement);this.dragElement.style.visibility="visible";null!=this.dragOffset&&(b+=this.dragOffset.x,c+=this.dragOffset.y);var d=mxUtils.getDocumentScrollOrigin(document);this.dragElement.style.left=b+d.x+"px";this.dragElement.style.top=c+d.y+"px"}mxEvent.consume(a)};
+mxDragSource.prototype.mouseUp=function(a){if(null!=this.currentGraph){if(null!=this.currentPoint&&(null==this.previewElement||"hidden"!=this.previewElement.style.visibility)){var b=this.currentGraph.view.scale,c=this.currentGraph.view.translate;this.drop(this.currentGraph,a,this.currentDropTarget,this.currentPoint.x/b-c.x,this.currentPoint.y/b-c.y)}this.dragExit(this.currentGraph);this.currentGraph=null}this.stopDrag();this.removeListeners();mxEvent.consume(a)};
+mxDragSource.prototype.removeListeners=function(){null!=this.eventSource&&(mxEvent.removeGestureListeners(this.eventSource,null,this.mouseMoveHandler,this.mouseUpHandler),this.eventSource=null);mxEvent.removeGestureListeners(document,null,this.mouseMoveHandler,this.mouseUpHandler);this.mouseUpHandler=this.mouseMoveHandler=null};
+mxDragSource.prototype.dragEnter=function(a,b){a.isMouseDown=!0;a.isMouseTrigger=mxEvent.isMouseEvent(b);this.previewElement=this.createPreviewElement(a);null!=this.previewElement&&this.checkEventSource&&mxClient.IS_SVG&&(this.previewElement.style.pointerEvents="none");this.isGuidesEnabled()&&null!=this.previewElement&&(this.currentGuide=new mxGuide(a,a.graphHandler.getGuideStates()));this.highlightDropTargets&&(this.currentHighlight=new mxCellHighlight(a,mxConstants.DROP_TARGET_COLOR));a.addListener(mxEvent.FIRE_MOUSE_EVENT,
+this.eventConsumer)};mxDragSource.prototype.dragExit=function(a,b){this.currentPoint=this.currentDropTarget=null;a.isMouseDown=!1;a.removeListener(this.eventConsumer);null!=this.previewElement&&(null!=this.previewElement.parentNode&&this.previewElement.parentNode.removeChild(this.previewElement),this.previewElement=null);null!=this.currentGuide&&(this.currentGuide.destroy(),this.currentGuide=null);null!=this.currentHighlight&&(this.currentHighlight.destroy(),this.currentHighlight=null)};
+mxDragSource.prototype.dragOver=function(a,b){var c=mxUtils.getOffset(a.container),d=mxUtils.getScrollOrigin(a.container),e=mxEvent.getClientX(b)-c.x+d.x-a.panDx;c=mxEvent.getClientY(b)-c.y+d.y-a.panDy;a.autoScroll&&(null==this.autoscroll||this.autoscroll)&&a.scrollPointToVisible(e,c,a.autoExtend);null!=this.currentHighlight&&a.isDropEnabled()&&(this.currentDropTarget=this.getDropTarget(a,e,c,b),d=a.getView().getState(this.currentDropTarget),this.currentHighlight.highlight(d));if(null!=this.previewElement){null==
+this.previewElement.parentNode&&(a.container.appendChild(this.previewElement),this.previewElement.style.zIndex="3",this.previewElement.style.position="absolute");d=this.isGridEnabled()&&a.isGridEnabledEvent(b);var f=!0;if(null!=this.currentGuide&&this.currentGuide.isEnabledForEvent(b))a=parseInt(this.previewElement.style.width),f=parseInt(this.previewElement.style.height),a=new mxRectangle(0,0,a,f),c=new mxPoint(e,c),c=this.currentGuide.move(a,c,d,!0),f=!1,e=c.x,c=c.y;else if(d){d=a.view.scale;b=
+a.view.translate;var g=a.gridSize/2;e=(a.snap(e/d-b.x-g)+b.x)*d;c=(a.snap(c/d-b.y-g)+b.y)*d}null!=this.currentGuide&&f&&this.currentGuide.hide();null!=this.previewOffset&&(e+=this.previewOffset.x,c+=this.previewOffset.y);this.previewElement.style.left=Math.round(e)+"px";this.previewElement.style.top=Math.round(c)+"px";this.previewElement.style.visibility="visible"}this.currentPoint=new mxPoint(e,c)};
+mxDragSource.prototype.drop=function(a,b,c,d,e){this.dropHandler.apply(this,arguments);"hidden"!=a.container.style.visibility&&a.container.focus()};function mxToolbar(a){this.container=a}mxToolbar.prototype=new mxEventSource;mxToolbar.prototype.constructor=mxToolbar;mxToolbar.prototype.container=null;mxToolbar.prototype.enabled=!0;mxToolbar.prototype.noReset=!1;mxToolbar.prototype.updateDefaultMode=!0;
+mxToolbar.prototype.addItem=function(a,b,c,d,e,f){var g=document.createElement(null!=b?"img":"button"),k=e||(null!=f?"mxToolbarMode":"mxToolbarItem");g.className=k;g.setAttribute("src",b);null!=a&&(null!=b?g.setAttribute("title",a):mxUtils.write(g,a));this.container.appendChild(g);null!=c&&(mxEvent.addListener(g,"click",c),mxClient.IS_TOUCH&&mxEvent.addListener(g,"touchend",c));a=mxUtils.bind(this,function(l){null!=d?g.setAttribute("src",b):g.style.backgroundColor=""});mxEvent.addGestureListeners(g,
+mxUtils.bind(this,function(l){null!=d?g.setAttribute("src",d):g.style.backgroundColor="gray";if(null!=f){null==this.menu&&(this.menu=new mxPopupMenu,this.menu.init());var m=this.currentImg;this.menu.isMenuShowing()&&this.menu.hideMenu();m!=g&&(this.currentImg=g,this.menu.factoryMethod=f,m=new mxPoint(g.offsetLeft,g.offsetTop+g.offsetHeight),this.menu.popup(m.x,m.y,null,l),this.menu.isMenuShowing()&&(g.className=k+"Selected",this.menu.hideMenu=function(){mxPopupMenu.prototype.hideMenu.apply(this);
+g.className=k;this.currentImg=null}))}}),null,a);mxEvent.addListener(g,"mouseout",a);return g};mxToolbar.prototype.addCombo=function(a){var b=document.createElement("div");b.style.display="inline";b.className="mxToolbarComboContainer";var c=document.createElement("select");c.className=a||"mxToolbarCombo";b.appendChild(c);this.container.appendChild(b);return c};
+mxToolbar.prototype.addActionCombo=function(a,b){var c=document.createElement("select");c.className=b||"mxToolbarCombo";this.addOption(c,a,null);mxEvent.addListener(c,"change",function(d){var e=c.options[c.selectedIndex];c.selectedIndex=0;null!=e.funct&&e.funct(d)});this.container.appendChild(c);return c};mxToolbar.prototype.addOption=function(a,b,c){var d=document.createElement("option");mxUtils.writeln(d,b);"function"==typeof c?d.funct=c:d.setAttribute("value",c);a.appendChild(d);return d};
+mxToolbar.prototype.addSwitchMode=function(a,b,c,d,e){var f=document.createElement("img");f.initialClassName=e||"mxToolbarMode";f.className=f.initialClassName;f.setAttribute("src",b);f.altIcon=d;null!=a&&f.setAttribute("title",a);mxEvent.addListener(f,"click",mxUtils.bind(this,function(g){g=this.selectedMode.altIcon;null!=g?(this.selectedMode.altIcon=this.selectedMode.getAttribute("src"),this.selectedMode.setAttribute("src",g)):this.selectedMode.className=this.selectedMode.initialClassName;this.updateDefaultMode&&
+(this.defaultMode=f);this.selectedMode=f;g=f.altIcon;null!=g?(f.altIcon=f.getAttribute("src"),f.setAttribute("src",g)):f.className=f.initialClassName+"Selected";this.fireEvent(new mxEventObject(mxEvent.SELECT));c()}));this.container.appendChild(f);null==this.defaultMode&&(this.defaultMode=f,this.selectMode(f),c());return f};
+mxToolbar.prototype.addMode=function(a,b,c,d,e,f){f=null!=f?f:!0;var g=document.createElement(null!=b?"img":"button");g.initialClassName=e||"mxToolbarMode";g.className=g.initialClassName;g.setAttribute("src",b);g.altIcon=d;null!=a&&g.setAttribute("title",a);this.enabled&&f&&(mxEvent.addListener(g,"click",mxUtils.bind(this,function(k){this.selectMode(g,c);this.noReset=!1})),mxEvent.addListener(g,"dblclick",mxUtils.bind(this,function(k){this.selectMode(g,c);this.noReset=!0})),null==this.defaultMode&&
+(this.defaultMode=g,this.defaultFunction=c,this.selectMode(g,c)));this.container.appendChild(g);return g};
+mxToolbar.prototype.selectMode=function(a,b){if(this.selectedMode!=a){if(null!=this.selectedMode){var c=this.selectedMode.altIcon;null!=c?(this.selectedMode.altIcon=this.selectedMode.getAttribute("src"),this.selectedMode.setAttribute("src",c)):this.selectedMode.className=this.selectedMode.initialClassName}this.selectedMode=a;c=this.selectedMode.altIcon;null!=c?(this.selectedMode.altIcon=this.selectedMode.getAttribute("src"),this.selectedMode.setAttribute("src",c)):this.selectedMode.className=this.selectedMode.initialClassName+
+"Selected";this.fireEvent(new mxEventObject(mxEvent.SELECT,"function",b))}};mxToolbar.prototype.resetMode=function(a){!a&&this.noReset||this.selectedMode==this.defaultMode||this.selectMode(this.defaultMode,this.defaultFunction)};mxToolbar.prototype.addSeparator=function(a){return this.addItem(null,a,null)};mxToolbar.prototype.addBreak=function(){mxUtils.br(this.container)};
+mxToolbar.prototype.addLine=function(){var a=document.createElement("hr");a.style.marginRight="6px";a.setAttribute("size","1");this.container.appendChild(a)};mxToolbar.prototype.destroy=function(){mxEvent.release(this.container);this.selectedMode=this.defaultFunction=this.defaultMode=this.container=null;null!=this.menu&&this.menu.destroy()};function mxUndoableEdit(a,b){this.source=a;this.changes=[];this.significant=null!=b?b:!0}mxUndoableEdit.prototype.source=null;
+mxUndoableEdit.prototype.changes=null;mxUndoableEdit.prototype.significant=null;mxUndoableEdit.prototype.undone=!1;mxUndoableEdit.prototype.redone=!1;mxUndoableEdit.prototype.isEmpty=function(){return 0==this.changes.length};mxUndoableEdit.prototype.isSignificant=function(){return this.significant};mxUndoableEdit.prototype.add=function(a){this.changes.push(a)};mxUndoableEdit.prototype.notify=function(){};mxUndoableEdit.prototype.die=function(){};
+mxUndoableEdit.prototype.undo=function(){if(!this.undone){this.source.fireEvent(new mxEventObject(mxEvent.START_EDIT));for(var a=this.changes.length-1;0<=a;a--){var b=this.changes[a];null!=b.execute?b.execute():null!=b.undo&&b.undo();this.source.fireEvent(new mxEventObject(mxEvent.EXECUTED,"change",b))}this.undone=!0;this.redone=!1;this.source.fireEvent(new mxEventObject(mxEvent.END_EDIT))}this.notify()};
+mxUndoableEdit.prototype.redo=function(){if(!this.redone){this.source.fireEvent(new mxEventObject(mxEvent.START_EDIT));for(var a=this.changes.length,b=0;bthis.indexOfNextAdd)for(var a=this.history.splice(this.indexOfNextAdd,this.history.length-this.indexOfNextAdd),b=0;bthis.dx&&Math.abs(this.dx)<
+this.border?this.border+this.dx:this.handleMouseOut?Math.max(this.dx,0):0;0==this.dx&&(this.dx=c-g.scrollLeft,this.dx=0this.dy&&Math.abs(this.dy)e.x+(document.body.clientWidth||f.clientWidth)&&(b.div.style.left=Math.max(0,a.div.offsetLeft-d+(mxClient.IS_IE?6:-6))+"px");b.div.style.overflowY="auto";
+b.div.style.overflowX="hidden";b.div.style.maxHeight=Math.max(document.body.clientHeight,document.documentElement.clientHeight)-10+"px";mxUtils.fit(b.div)}};
+mxPopupMenu.prototype.addSeparator=function(a,b){a=a||this;if(this.smartSeparators&&!b)a.willAddSeparator=!0;else if(null!=a.tbody){a.willAddSeparator=!1;b=document.createElement("tr");var c=document.createElement("td");c.className="mxPopupMenuIcon";c.style.padding="0 0 0 0px";b.appendChild(c);c=document.createElement("td");c.style.padding="0 0 0 0px";c.setAttribute("colSpan","2");var d=document.createElement("hr");d.setAttribute("size","1");c.appendChild(d);b.appendChild(c);a.tbody.appendChild(b)}};
+mxPopupMenu.prototype.popup=function(a,b,c,d){if(null!=this.div&&null!=this.tbody&&null!=this.factoryMethod){this.div.style.left=a+"px";for(this.div.style.top=b+"px";null!=this.tbody.firstChild;)mxEvent.release(this.tbody.firstChild),this.tbody.removeChild(this.tbody.firstChild);this.itemCount=0;this.factoryMethod(this,c,d);0this.autoSaveDelay||this.ignoredChanges>=this.autoSaveThreshold&&a>this.autoSaveThrottle?(this.save(),this.reset()):this.ignoredChanges++};mxAutoSaveManager.prototype.reset=function(){this.lastSnapshot=(new Date).getTime();this.ignoredChanges=0};mxAutoSaveManager.prototype.destroy=function(){this.setGraph(null)};
+function mxAnimation(a){this.delay=null!=a?a:20}mxAnimation.prototype=new mxEventSource;mxAnimation.prototype.constructor=mxAnimation;mxAnimation.prototype.delay=null;mxAnimation.prototype.thread=null;mxAnimation.prototype.isRunning=function(){return null!=this.thread};mxAnimation.prototype.startAnimation=function(){null==this.thread&&(this.thread=window.setInterval(mxUtils.bind(this,this.updateAnimation),this.delay))};mxAnimation.prototype.updateAnimation=function(){this.fireEvent(new mxEventObject(mxEvent.EXECUTE))};
+mxAnimation.prototype.stopAnimation=function(){null!=this.thread&&(window.clearInterval(this.thread),this.thread=null,this.fireEvent(new mxEventObject(mxEvent.DONE)))};function mxMorphing(a,b,c,d){mxAnimation.call(this,d);this.graph=a;this.steps=null!=b?b:6;this.ease=null!=c?c:1.5}mxMorphing.prototype=new mxAnimation;mxMorphing.prototype.constructor=mxMorphing;mxMorphing.prototype.graph=null;mxMorphing.prototype.steps=null;mxMorphing.prototype.step=0;mxMorphing.prototype.ease=null;
+mxMorphing.prototype.cells=null;mxMorphing.prototype.updateAnimation=function(){mxAnimation.prototype.updateAnimation.apply(this,arguments);var a=new mxCellStatePreview(this.graph);if(null!=this.cells)for(var b=0;b=this.steps)&&this.stopAnimation()};mxMorphing.prototype.show=function(a){a.show()};
+mxMorphing.prototype.animateCell=function(a,b,c){var d=this.graph.getView().getState(a),e=null;if(null!=d&&(e=this.getDelta(d),this.graph.getModel().isVertex(a)&&(0!=e.x||0!=e.y))){var f=this.graph.view.getTranslate(),g=this.graph.view.getScale();e.x+=f.x*g;e.y+=f.y*g;b.moveState(d,-e.x/this.ease,-e.y/this.ease)}if(c&&!this.stopRecursion(d,e))for(d=this.graph.getModel().getChildCount(a),e=0;ea.alpha||1>a.fillAlpha)&&this.node.setAttribute("fill-opacity",a.alpha*a.fillAlpha);if(null!=a.fillColor)if(null!=a.gradientColor&&a.gradientColor!=mxConstants.NONE)if(a=this.getSvgGradient(String(a.fillColor),String(a.gradientColor),a.gradientFillAlpha,a.gradientAlpha,a.gradientDirection),this.root.ownerDocument==document&&this.useAbsoluteIds){var b=this.getBaseUrl().replace(/([\(\)])/g,"\\$1");this.node.setAttribute("fill","url("+
+b+"#"+a+")")}else this.node.setAttribute("fill","url(#"+a+")");else this.node.setAttribute("fill",String(a.fillColor).toLowerCase())};mxSvgCanvas2D.prototype.getCurrentStrokeWidth=function(){return Math.max(this.minStrokeWidth,Math.max(.01,this.format(this.state.strokeWidth*this.state.scale)))};
+mxSvgCanvas2D.prototype.updateStroke=function(){var a=this.state;this.node.setAttribute("stroke",String(a.strokeColor).toLowerCase());(1>a.alpha||1>a.strokeAlpha)&&this.node.setAttribute("stroke-opacity",a.alpha*a.strokeAlpha);var b=this.getCurrentStrokeWidth();1!=b&&this.node.setAttribute("stroke-width",b);"path"==this.node.nodeName&&this.updateStrokeAttributes();a.dashed&&this.node.setAttribute("stroke-dasharray",this.createDashPattern((a.fixDash?1:a.strokeWidth)*a.scale))};
+mxSvgCanvas2D.prototype.updateStrokeAttributes=function(){var a=this.state;null!=a.lineJoin&&"miter"!=a.lineJoin&&this.node.setAttribute("stroke-linejoin",a.lineJoin);if(null!=a.lineCap){var b=a.lineCap;"flat"==b&&(b="butt");"butt"!=b&&this.node.setAttribute("stroke-linecap",b)}null==a.miterLimit||this.styleEnabled&&10==a.miterLimit||this.node.setAttribute("stroke-miterlimit",a.miterLimit)};
+mxSvgCanvas2D.prototype.createDashPattern=function(a){var b=[];if("string"===typeof this.state.dashPattern){var c=this.state.dashPattern.split(" ");if(0m.alpha||1>m.fillAlpha)&&n.setAttribute("opacity",m.alpha*m.fillAlpha);e=this.state.transform||"";if(g||k){var p=f=1,q=0,r=0;g&&(f=-1,q=-c-2*a);k&&(p=-1,r=-d-2*b);e+="scale("+f+","+p+")translate("+q*m.scale+","+r*m.scale+")"}0",5)+1)),""==a.substring(a.length-7,a.length)&&(a=a.substring(0,a.length-7)))}else{if(null!=document.implementation&&null!=document.implementation.createDocument){b=document.implementation.createDocument("http://www.w3.org/1999/xhtml","html",null);var c=b.createElement("body");
+b.documentElement.appendChild(c);var d=document.createElement("div");d.innerHTML=a;for(a=d.firstChild;null!=a;)d=a.nextSibling,c.appendChild(b.adoptNode(a)),a=d;return c.innerHTML}b=document.createElement("textarea");b.innerHTML=a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(//g,">");a=b.value.replace(/&/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,
+"&").replace(/
/g,"
").replace(/
/g,"
").replace(/(]+)>/gm,"$1 />")}return a}; +mxSvgCanvas2D.prototype.createDiv=function(a){mxUtils.isNode(a)||(a="
"+this.convertHtml(a)+"
");if(mxClient.IS_IE||mxClient.IS_IE11||!document.createElementNS)return mxUtils.isNode(a)&&(a="
"+mxUtils.getXml(a)+"
"),mxUtils.parseXml('
'+a+"
").documentElement;var b=document.createElementNS("http://www.w3.org/1999/xhtml","div");if(mxUtils.isNode(a)){var c=document.createElement("div"),d=c.cloneNode(!1);this.root.ownerDocument!= +document?c.appendChild(a.cloneNode(!0)):c.appendChild(a);d.appendChild(c);b.appendChild(d)}else b.innerHTML=a;return b};mxSvgCanvas2D.prototype.updateText=function(a,b,c,d,e,f,g,k,l,m,n){null!=n&&null!=n.firstChild&&null!=n.firstChild.firstChild&&this.updateTextNodes(a,b,c,d,e,f,g,k,l,m,n.firstChild)}; +mxSvgCanvas2D.prototype.addForeignObject=function(a,b,c,d,e,f,g,k,l,m,n,p,q,r,t){q=this.createElement("g");var u=this.createElement("foreignObject");this.setCssText(u,"overflow: visible; text-align: left;");u.setAttribute("pointer-events","none");r.ownerDocument!=document&&(r=mxUtils.importNodeImplementation(u.ownerDocument,r,!0));u.appendChild(r);q.appendChild(u);this.updateTextNodes(a,b,c,d,f,g,k,m,n,p,q);this.root.ownerDocument!=document&&(a=this.createAlternateContent(u,a,b,c,d,e,f,g,k,l,m,n, +p),null!=a&&(u.setAttribute("requiredFeatures","http://www.w3.org/TR/SVG11/feature#Extensibility"),b=this.createElement("switch"),b.appendChild(u),b.appendChild(a),q.appendChild(b)));t.appendChild(q)}; +mxSvgCanvas2D.prototype.updateTextNodes=function(a,b,c,d,e,f,g,k,l,m,n){var p=this.state.scale;mxSvgCanvas2D.createCss(c+2,d,e,f,g,k,l,null!=this.state.fontBackgroundColor?this.state.fontBackgroundColor:null,null!=this.state.fontBorderColor?this.state.fontBorderColor:null,"display: flex; align-items: unsafe "+(f==mxConstants.ALIGN_TOP?"flex-start":f==mxConstants.ALIGN_BOTTOM?"flex-end":"center")+"; justify-content: unsafe "+(e==mxConstants.ALIGN_LEFT?"flex-start":e==mxConstants.ALIGN_RIGHT?"flex-end": +"center")+"; ",this.getTextCss(),p,mxUtils.bind(this,function(q,r,t,u,x){a+=this.state.dx;b+=this.state.dy;var y=n.firstChild,C=y.firstChild,A=C.firstChild,B=(this.rotateHtml?this.state.rotation:0)+(null!=m?m:0),z=(0!=this.foOffset?"translate("+this.foOffset+" "+this.foOffset+")":"")+(1!=p?"scale("+p+")":"");this.setCssText(A.firstChild,x);this.setCssText(A,u);A.setAttribute("data-drawio-colors","color: "+this.state.fontColor+"; "+(null==this.state.fontBackgroundColor?"":"background-color: "+this.state.fontBackgroundColor+ +"; ")+(null==this.state.fontBorderColor?"":"border-color: "+this.state.fontBorderColor+"; "));y.setAttribute("width",Math.ceil(1/Math.min(1,p)*100)+"%");y.setAttribute("height",Math.ceil(1/Math.min(1,p)*100)+"%");r=Math.round(b+r);0>r?y.setAttribute("y",r):(y.removeAttribute("y"),t+="padding-top: "+r+"px; ");this.setCssText(C,t+"margin-left: "+Math.round(a+q)+"px;");z+=0!=B?"rotate("+B+" "+a+" "+b+")":"";""!=z?n.setAttribute("transform",z):n.removeAttribute("transform");1!=this.state.alpha?n.setAttribute("opacity", +this.state.alpha):n.removeAttribute("opacity")}))}; +mxSvgCanvas2D.createCss=function(a,b,c,d,e,f,g,k,l,m,n,p,q){p="box-sizing: border-box; font-size: 0; text-align: "+(c==mxConstants.ALIGN_LEFT?"left":c==mxConstants.ALIGN_RIGHT?"right":"center")+"; ";var r=mxUtils.getAlignmentAsPoint(c,d);c="overflow: hidden; ";var t="width: 1px; ",u="height: 1px; ",x=r.x*a;r=r.y*b;g?(t="width: "+Math.round(a)+"px; ",p+="max-height: "+Math.round(b)+"px; ",r=0):"fill"==f?(t="width: "+Math.round(a)+"px; ",u="height: "+Math.round(b)+"px; ",n+="width: 100%; height: 100%; ", +p+="width: "+Math.round(a-2)+"px; "+u):"width"==f?(t="width: "+Math.round(a-2)+"px; ",n+="width: 100%; ",p+=t,r=0,0m)d=m;if(null==f||fm)e=m;if(null==g||gk.alpha&&r.setAttribute("opacity",k.alpha);t=e.split("\n");p=Math.round(q*mxConstants.LINE_HEIGHT);var u=q+(t.length- +1)*p;n=b+q-1;g==mxConstants.ALIGN_MIDDLE?"fill"==l?n-=d/2:(m=(this.matchHtmlAlignment&&m&&0"),document.body.appendChild(n),e=n.offsetWidth,f=n.offsetHeight,n.parentNode.removeChild(n),g==mxConstants.ALIGN_CENTER?c-=e/2:g==mxConstants.ALIGN_RIGHT&&(c-=e),k==mxConstants.ALIGN_MIDDLE?d-=f/2:k==mxConstants.ALIGN_BOTTOM&&(d-=f),n=new mxRectangle((c+1)*m.scale,(d+2)*m.scale,e*m.scale,(f+1)*m.scale);null!=n&&(b= +this.createElement("rect"),b.setAttribute("fill",m.fontBackgroundColor||"none"),b.setAttribute("stroke",m.fontBorderColor||"none"),b.setAttribute("x",Math.floor(n.x-1)),b.setAttribute("y",Math.floor(n.y-1)),b.setAttribute("width",Math.ceil(n.width+2)),b.setAttribute("height",Math.ceil(n.height)),m=null!=m.fontBorderColor?Math.max(1,this.format(m.scale)):0,b.setAttribute("stroke-width",m),this.root.ownerDocument==document&&1==mxUtils.mod(m,2)&&b.setAttribute("transform","translate(0.5, 0.5)"),a.insertBefore(b, +a.firstChild))}};mxSvgCanvas2D.prototype.stroke=function(){this.addNode(!1,!0)};mxSvgCanvas2D.prototype.fill=function(){this.addNode(!0,!1)};mxSvgCanvas2D.prototype.fillAndStroke=function(){this.addNode(!0,!0)};function mxGuide(a,b){this.graph=a;this.setStates(b)}mxGuide.prototype.graph=null;mxGuide.prototype.states=null;mxGuide.prototype.horizontal=!0;mxGuide.prototype.vertical=!0;mxGuide.prototype.guideX=null;mxGuide.prototype.guideY=null;mxGuide.prototype.rounded=!1; +mxGuide.prototype.tolerance=2;mxGuide.prototype.setStates=function(a){this.states=a};mxGuide.prototype.isEnabledForEvent=function(a){return!0};mxGuide.prototype.getGuideTolerance=function(a){return a&&this.graph.gridEnabled?this.graph.gridSize/2:this.tolerance};mxGuide.prototype.createGuideShape=function(a){a=new mxPolyline([],mxConstants.GUIDE_COLOR,mxConstants.GUIDE_STROKEWIDTH);a.isDashed=!0;return a};mxGuide.prototype.isStateIgnored=function(a){return!1}; +mxGuide.prototype.move=function(a,b,c,d){if(null!=this.states&&(this.horizontal||this.vertical)&&null!=a&&null!=b){d=function(z,v,D){var F=!1;D&&Math.abs(z-B)this.opacity&&(b+="alpha(opacity="+this.opacity+")");this.isShadow&&(b+="progid:DXImageTransform.Microsoft.dropShadow (OffX='"+Math.round(mxConstants.SHADOW_OFFSET_X*this.scale)+"', OffY='"+Math.round(mxConstants.SHADOW_OFFSET_Y*this.scale)+"', Color='"+mxConstants.VML_SHADOWCOLOR+"')");if(null!=this.fill&&this.fill!=mxConstants.NONE&&this.gradient&&this.gradient!=mxConstants.NONE){var c=this.fill,d=this.gradient,e="0",f={east:0,south:1, +west:2,north:3},g=null!=this.direction?f[this.direction]:0;null!=this.gradientDirection&&(g=mxUtils.mod(g+f[this.gradientDirection]-1,4));1==g?(e="1",f=c,c=d,d=f):2==g?(f=c,c=d,d=f):3==g&&(e="1");b+="progid:DXImageTransform.Microsoft.gradient(startColorStr='"+c+"', endColorStr='"+d+"', gradientType='"+e+"')"}a.style.filter=b}; +mxShape.prototype.updateHtmlColors=function(a){var b=this.stroke;null!=b&&b!=mxConstants.NONE?(a.style.borderColor=b,this.isDashed?a.style.borderStyle="dashed":0=d||Math.abs(e.y-g.y)>=d)&&b.push(new mxPoint(g.x/c,g.y/c));e=g}}return b}; +mxShape.prototype.configureCanvas=function(a,b,c,d,e){var f=null;null!=this.style&&(f=this.style.dashPattern);a.setAlpha(this.opacity/100);a.setFillAlpha(this.fillOpacity/100);a.setStrokeAlpha(this.strokeOpacity/100);null!=this.isShadow&&a.setShadow(this.isShadow);null!=this.isDashed&&a.setDashed(this.isDashed,null!=this.style?1==mxUtils.getValue(this.style,mxConstants.STYLE_FIX_DASH,!1):!1);null!=f&&a.setDashPattern(f);null!=this.fill&&this.fill!=mxConstants.NONE&&this.gradient&&this.gradient!=mxConstants.NONE? +(b=this.getGradientBounds(a,b,c,d,e),a.setGradient(this.fill,this.gradient,b.x,b.y,b.width,b.height,this.gradientDirection)):a.setFillColor(this.fill);a.setStrokeColor(this.stroke);this.configurePointerEvents(a)};mxShape.prototype.configurePointerEvents=function(a){null==this.style||null!=this.fill&&this.fill!=mxConstants.NONE&&0!=this.opacity&&0!=this.fillOpacity||"0"!=mxUtils.getValue(this.style,mxConstants.STYLE_POINTER_EVENTS,"1")||(a.pointerEvents=!1)}; +mxShape.prototype.getGradientBounds=function(a,b,c,d,e){return new mxRectangle(b,c,d,e)};mxShape.prototype.updateTransform=function(a,b,c,d,e){a.scale(this.scale);a.rotate(this.getShapeRotation(),this.flipH,this.flipV,b+d/2,c+e/2)};mxShape.prototype.paintVertexShape=function(a,b,c,d,e){this.paintBackground(a,b,c,d,e);this.outline&&null!=this.style&&0!=mxUtils.getValue(this.style,mxConstants.STYLE_BACKGROUND_OUTLINE,0)||(a.setShadow(!1),this.paintForeground(a,b,c,d,e))}; +mxShape.prototype.paintBackground=function(a,b,c,d,e){};mxShape.prototype.paintForeground=function(a,b,c,d,e){};mxShape.prototype.paintEdgeShape=function(a,b){}; +mxShape.prototype.getArcSize=function(a,b){if("1"==mxUtils.getValue(this.style,mxConstants.STYLE_ABSOLUTE_ARCSIZE,0))a=Math.min(a/2,Math.min(b/2,mxUtils.getValue(this.style,mxConstants.STYLE_ARCSIZE,mxConstants.LINE_ARCSIZE)/2));else{var c=mxUtils.getValue(this.style,mxConstants.STYLE_ARCSIZE,100*mxConstants.RECTANGLE_ROUNDING_FACTOR)/100;a=Math.min(a*c,b*c)}return a}; +mxShape.prototype.paintGlassEffect=function(a,b,c,d,e,f){var g=Math.ceil(this.strokewidth/2);a.setGradient("#ffffff","#ffffff",b,c,d,.6*e,"south",.9,.1);a.begin();f+=2*g;this.isRounded?(a.moveTo(b-g+f,c-g),a.quadTo(b-g,c-g,b-g,c-g+f),a.lineTo(b-g,c+.4*e),a.quadTo(b+.5*d,c+.7*e,b+d+g,c+.4*e),a.lineTo(b+d+g,c-g+f),a.quadTo(b+d+g,c-g,b+d+g-f,c-g)):(a.moveTo(b-g,c-g),a.lineTo(b-g,c+.4*e),a.quadTo(b+.5*d,c+.7*e,b+d+g,c+.4*e),a.lineTo(b+d+g,c-g));a.close();a.fill()}; +mxShape.prototype.addPoints=function(a,b,c,d,e,f,g){if(null!=b&&0mxUtils.indexOf(f,l-1))){var p=Math.sqrt(n*n+m*m);a.lineTo(g.x+n*Math.min(d,p/2)/p,g.y+m*Math.min(d,p/2)/p);for(m=b[mxUtils.mod(l+ +1,b.length)];l
"));k=!mxUtils.isNode(this.value)&&this.replaceLinefeeds&&"html"==g?k.replace(/\n/g,"
"):k;var l=this.textDirection;l!=mxConstants.TEXT_DIRECTION_AUTO||b||(l=this.getAutoDirection());l!=mxConstants.TEXT_DIRECTION_LTR&&l!=mxConstants.TEXT_DIRECTION_RTL&&(l=null);a.text(d,e,f,c,k,this.align,this.valign,this.wrap,g,this.overflow,this.clipped,this.getTextRotation(),l)}}; +mxText.prototype.redraw=function(){if(this.visible&&this.checkBounds()&&this.cacheEnabled&&this.lastValue==this.value&&(mxUtils.isNode(this.value)||this.dialect==mxConstants.DIALECT_STRICTHTML))if("DIV"==this.node.nodeName)mxClient.IS_SVG?this.redrawHtmlShapeWithCss3():(this.updateSize(this.node,null==this.state||null==this.state.view.textDiv),mxClient.IS_IE&&(null==document.documentMode||8>=document.documentMode)?this.updateHtmlFilter():this.updateHtmlTransform()),this.updateBoundingBox();else{var a= +this.createCanvas();null!=a&&null!=a.updateText?(a.pointerEvents=this.pointerEvents,this.paint(a,!0),this.destroyCanvas(a),this.updateBoundingBox()):mxShape.prototype.redraw.apply(this,arguments)}else mxShape.prototype.redraw.apply(this,arguments),mxUtils.isNode(this.value)||this.dialect==mxConstants.DIALECT_STRICTHTML?this.lastValue=this.value:this.lastValue=null}; +mxText.prototype.resetStyles=function(){mxShape.prototype.resetStyles.apply(this,arguments);this.color="black";this.align=mxConstants.ALIGN_CENTER;this.valign=mxConstants.ALIGN_MIDDLE;this.family=mxConstants.DEFAULT_FONTFAMILY;this.size=mxConstants.DEFAULT_FONTSIZE;this.fontStyle=mxConstants.DEFAULT_FONTSTYLE;this.spacingLeft=this.spacingBottom=this.spacingRight=this.spacingTop=this.spacing=2;this.horizontal=!0;delete this.background;delete this.border;this.textDirection=mxConstants.DEFAULT_TEXT_DIRECTION; +delete this.margin}; +mxText.prototype.apply=function(a){var b=this.spacing;mxShape.prototype.apply.apply(this,arguments);null!=this.style&&(this.fontStyle=mxUtils.getValue(this.style,mxConstants.STYLE_FONTSTYLE,this.fontStyle),this.family=mxUtils.getValue(this.style,mxConstants.STYLE_FONTFAMILY,this.family),this.size=mxUtils.getValue(this.style,mxConstants.STYLE_FONTSIZE,this.size),this.color=mxUtils.getValue(this.style,mxConstants.STYLE_FONTCOLOR,this.color),this.align=mxUtils.getValue(this.style,mxConstants.STYLE_ALIGN, +this.align),this.valign=mxUtils.getValue(this.style,mxConstants.STYLE_VERTICAL_ALIGN,this.valign),this.spacing=parseInt(mxUtils.getValue(this.style,mxConstants.STYLE_SPACING,this.spacing)),this.spacingTop=parseInt(mxUtils.getValue(this.style,mxConstants.STYLE_SPACING_TOP,this.spacingTop-b))+this.spacing,this.spacingRight=parseInt(mxUtils.getValue(this.style,mxConstants.STYLE_SPACING_RIGHT,this.spacingRight-b))+this.spacing,this.spacingBottom=parseInt(mxUtils.getValue(this.style,mxConstants.STYLE_SPACING_BOTTOM, +this.spacingBottom-b))+this.spacing,this.spacingLeft=parseInt(mxUtils.getValue(this.style,mxConstants.STYLE_SPACING_LEFT,this.spacingLeft-b))+this.spacing,this.horizontal=mxUtils.getValue(this.style,mxConstants.STYLE_HORIZONTAL,this.horizontal),this.background=mxUtils.getValue(this.style,mxConstants.STYLE_LABEL_BACKGROUNDCOLOR,this.background),this.border=mxUtils.getValue(this.style,mxConstants.STYLE_LABEL_BORDERCOLOR,this.border),this.textDirection=mxUtils.getValue(this.style,mxConstants.STYLE_TEXT_DIRECTION, +mxConstants.DEFAULT_TEXT_DIRECTION),this.opacity=mxUtils.getValue(this.style,mxConstants.STYLE_TEXT_OPACITY,100),this.updateMargin());this.flipH=this.flipV=null};mxText.prototype.getAutoDirection=function(){var a=/[A-Za-z\u05d0-\u065f\u066a-\u06ef\u06fa-\u07ff\ufb1d-\ufdff\ufe70-\ufefc]/.exec(this.value);return null!=a&&0
");return a=this.replaceLinefeeds?a.replace(/\n/g,"
"):a}; +mxText.prototype.getTextCss=function(){var a="display: inline-block; font-size: "+this.size+"px; font-family: "+this.family+"; color: "+this.color+"; line-height: "+(mxConstants.ABSOLUTE_LINE_HEIGHT?this.size*mxConstants.LINE_HEIGHT+"px":mxConstants.LINE_HEIGHT)+"; pointer-events: "+(this.pointerEvents?"all":"none")+"; ";(this.fontStyle&mxConstants.FONT_BOLD)==mxConstants.FONT_BOLD&&(a+="font-weight: bold; ");(this.fontStyle&mxConstants.FONT_ITALIC)==mxConstants.FONT_ITALIC&&(a+="font-style: italic; "); +var b=[];(this.fontStyle&mxConstants.FONT_UNDERLINE)==mxConstants.FONT_UNDERLINE&&b.push("underline");(this.fontStyle&mxConstants.FONT_STRIKETHROUGH)==mxConstants.FONT_STRIKETHROUGH&&b.push("line-through");0=document.documentMode)?this.updateHtmlFilter():this.updateHtmlTransform()}}; +mxText.prototype.redrawHtmlShapeWithCss3=function(){var a=Math.max(0,Math.round(this.bounds.width/this.scale)),b=Math.max(0,Math.round(this.bounds.height/this.scale)),c="position: absolute; left: "+Math.round(this.bounds.x)+"px; top: "+Math.round(this.bounds.y)+"px; pointer-events: none; ",d=this.getTextCss();mxSvgCanvas2D.createCss(a+2,b,this.align,this.valign,this.wrap,this.overflow,this.clipped,null!=this.background?mxUtils.htmlEntities(this.background):null,null!=this.border?mxUtils.htmlEntities(this.border): +null,c,d,this.scale,mxUtils.bind(this,function(e,f,g,k,l,m){e=this.getTextRotation();e=(1!=this.scale?"scale("+this.scale+") ":"")+(0!=e?"rotate("+e+"deg) ":"")+(0!=this.margin.x||0!=this.margin.y?"translate("+100*this.margin.x+"%,"+100*this.margin.y+"%)":"");""!=e&&(e="transform-origin: 0 0; transform: "+e+"; ");"block"==this.overflow&&this.valign==mxConstants.ALIGN_MIDDLE&&(e+="max-height: "+(b+1)+"px;");""==m?(g+=k,k="display:inline-block; min-width: 100%; "+e):(k+=e,mxClient.IS_SF&&(k+="-webkit-clip-path: content-box;")); +"block"==this.overflow&&(k+="width: 100%; ");100>this.opacity&&(l+="opacity: "+this.opacity/100+"; ");this.node.setAttribute("style",g);g=mxUtils.isNode(this.value)?this.value.outerHTML:this.getHtmlValue();null==this.node.firstChild&&(this.node.innerHTML="
"+g+"
",mxClient.IS_IE11&&this.fixFlexboxForIe11(this.node));this.node.firstChild.firstChild.setAttribute("style",l);this.node.firstChild.setAttribute("style",k)}))}; +mxText.prototype.fixFlexboxForIe11=function(a){for(var b=a.querySelectorAll('div[style*="display: flex; justify-content: flex-end;"]'),c=0;cthis.opacity?this.opacity/100:""}; +mxText.prototype.updateInnerHtml=function(a){if(mxUtils.isNode(this.value))a.innerHTML=this.value.outerHTML;else{var b=this.value;this.dialect!=mxConstants.DIALECT_STRICTHTML&&(b=mxUtils.htmlEntities(b,!1));b=mxUtils.replaceTrailingNewlines(b,"
 
");b=this.replaceLinefeeds?b.replace(/\n/g,"
"):b;a.innerHTML='
'+b+"
"}}; +mxText.prototype.updateHtmlFilter=function(){var a=this.node.style,b=this.margin.x,c=this.margin.y,d=this.scale;mxUtils.setOpacity(this.node,this.opacity);var e=0,f=null!=this.state?this.state.view.textDiv:null,g=this.node;if(null!=f){f.style.overflow="";f.style.height="";f.style.width="";this.updateFont(f);this.updateSize(f,!1);this.updateInnerHtml(f);var k=Math.round(this.bounds.width/this.scale);if(this.wrap&&0m&&(m+=2*Math.PI);m%=Math.PI;m>Math.PI/2&&(m= +Math.PI-m);g=Math.cos(m);var n=Math.sin(-m);b=k*-(b+.5);c=f*-(c+.5);0!=m&&(m="progid:DXImageTransform.Microsoft.Matrix(M11="+l+", M12="+e+", M21="+-e+", M22="+l+", sizingMethod='auto expand')",a.filter=null!=a.filter&&0
");a=this.replaceLinefeeds?a.replace(/\n/g,"
"):a;var b=null!=this.background&&this.background!=mxConstants.NONE?this.background:null,c=null!=this.border&&this.border!=mxConstants.NONE?this.border:null;if("fill"==this.overflow|| +"width"==this.overflow)null!=b&&(this.node.style.backgroundColor=b),null!=c&&(this.node.style.border="1px solid "+c);else{var d="";null!=b&&(d+="background-color:"+mxUtils.htmlEntities(b)+";");null!=c&&(d+="border:1px solid "+mxUtils.htmlEntities(c)+";");a='
'+a+"
"}this.node.innerHTML= +a;a=this.node.getElementsByTagName("div");0this.opacity?"alpha(opacity="+this.opacity+")":"";this.node.style.filter=b;this.flipH&&this.flipV?b+="progid:DXImageTransform.Microsoft.BasicImage(rotation=2)":this.flipH?b+="progid:DXImageTransform.Microsoft.BasicImage(mirror=1)":this.flipV&&(b+="progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)");a.style.filter!=b&&(a.style.filter=b);"image"== +a.nodeName?a.style.rotation=this.rotation:0!=this.rotation?mxUtils.setPrefixedStyle(a.style,"transform","rotate("+this.rotation+"deg)"):mxUtils.setPrefixedStyle(a.style,"transform","");a.style.width=this.node.style.width;a.style.height=this.node.style.height;this.node.style.backgroundImage="";this.node.appendChild(a)}else this.setTransparentBackgroundImage(this.node)};function mxLabel(a,b,c,d){mxRectangleShape.call(this,a,b,c,d)}mxUtils.extend(mxLabel,mxRectangleShape); +mxLabel.prototype.imageSize=mxConstants.DEFAULT_IMAGESIZE;mxLabel.prototype.spacing=2;mxLabel.prototype.indicatorSize=10;mxLabel.prototype.indicatorSpacing=2;mxLabel.prototype.init=function(a){mxShape.prototype.init.apply(this,arguments);null!=this.indicatorShape&&(this.indicator=new this.indicatorShape,this.indicator.dialect=this.dialect,this.indicator.init(this.node))}; +mxLabel.prototype.redraw=function(){null!=this.indicator&&(this.indicator.fill=this.indicatorColor,this.indicator.stroke=this.indicatorStrokeColor,this.indicator.gradient=this.indicatorGradientColor,this.indicator.direction=this.indicatorDirection,this.indicator.redraw());mxShape.prototype.redraw.apply(this,arguments)};mxLabel.prototype.isHtmlAllowed=function(){return mxRectangleShape.prototype.isHtmlAllowed.apply(this,arguments)&&null==this.indicatorColor&&null==this.indicatorShape}; +mxLabel.prototype.paintForeground=function(a,b,c,d,e){this.paintImage(a,b,c,d,e);this.paintIndicator(a,b,c,d,e);mxRectangleShape.prototype.paintForeground.apply(this,arguments)};mxLabel.prototype.paintImage=function(a,b,c,d,e){null!=this.image&&(b=this.getImageBounds(b,c,d,e),c=mxUtils.getValue(this.style,mxConstants.STYLE_CLIP_PATH,null),a.image(b.x,b.y,b.width,b.height,this.image,!1,!1,!1,c))}; +mxLabel.prototype.getImageBounds=function(a,b,c,d){var e=mxUtils.getValue(this.style,mxConstants.STYLE_IMAGE_ALIGN,mxConstants.ALIGN_LEFT),f=mxUtils.getValue(this.style,mxConstants.STYLE_IMAGE_VERTICAL_ALIGN,mxConstants.ALIGN_MIDDLE),g=mxUtils.getNumber(this.style,mxConstants.STYLE_IMAGE_WIDTH,mxConstants.DEFAULT_IMAGESIZE),k=mxUtils.getNumber(this.style,mxConstants.STYLE_IMAGE_HEIGHT,mxConstants.DEFAULT_IMAGESIZE),l=mxUtils.getNumber(this.style,mxConstants.STYLE_SPACING,this.spacing)+5;a=e==mxConstants.ALIGN_CENTER? +a+(c-g)/2:e==mxConstants.ALIGN_RIGHT?a+(c-g-l):a+l;b=f==mxConstants.ALIGN_TOP?b+l:f==mxConstants.ALIGN_BOTTOM?b+(d-k-l):b+(d-k)/2;return new mxRectangle(a,b,g,k)};mxLabel.prototype.paintIndicator=function(a,b,c,d,e){null!=this.indicator?(this.indicator.bounds=this.getIndicatorBounds(b,c,d,e),this.indicator.paint(a)):null!=this.indicatorImage&&(b=this.getIndicatorBounds(b,c,d,e),a.image(b.x,b.y,b.width,b.height,this.indicatorImage,!1,!1,!1))}; +mxLabel.prototype.getIndicatorBounds=function(a,b,c,d){var e=mxUtils.getValue(this.style,mxConstants.STYLE_IMAGE_ALIGN,mxConstants.ALIGN_LEFT),f=mxUtils.getValue(this.style,mxConstants.STYLE_IMAGE_VERTICAL_ALIGN,mxConstants.ALIGN_MIDDLE),g=mxUtils.getNumber(this.style,mxConstants.STYLE_INDICATOR_WIDTH,this.indicatorSize),k=mxUtils.getNumber(this.style,mxConstants.STYLE_INDICATOR_HEIGHT,this.indicatorSize),l=this.spacing+5;a=e==mxConstants.ALIGN_RIGHT?a+(c-g-l):e==mxConstants.ALIGN_CENTER?a+(c-g)/ +2:a+l;b=f==mxConstants.ALIGN_BOTTOM?b+(d-k-l):f==mxConstants.ALIGN_TOP?b+l:b+(d-k)/2;return new mxRectangle(a,b,g,k)}; +mxLabel.prototype.redrawHtmlShape=function(){for(mxRectangleShape.prototype.redrawHtmlShape.apply(this,arguments);this.node.hasChildNodes();)this.node.removeChild(this.node.lastChild);if(null!=this.image){var a=document.createElement("img");a.style.position="relative";a.setAttribute("border","0");var b=this.getImageBounds(this.bounds.x,this.bounds.y,this.bounds.width,this.bounds.height);b.x-=this.bounds.x;b.y-=this.bounds.y;a.style.left=Math.round(b.x)+"px";a.style.top=Math.round(b.y)+"px";a.style.width= +Math.round(b.width)+"px";a.style.height=Math.round(b.height)+"px";a.src=this.image;this.node.appendChild(a)}};function mxCylinder(a,b,c,d){mxShape.call(this);this.bounds=a;this.fill=b;this.stroke=c;this.strokewidth=null!=d?d:1}mxUtils.extend(mxCylinder,mxShape);mxCylinder.prototype.maxHeight=40; +mxCylinder.prototype.paintVertexShape=function(a,b,c,d,e){a.translate(b,c);a.begin();this.redrawPath(a,b,c,d,e,!1);a.fillAndStroke();this.outline&&null!=this.style&&0!=mxUtils.getValue(this.style,mxConstants.STYLE_BACKGROUND_OUTLINE,0)||(a.setShadow(!1),a.begin(),this.redrawPath(a,b,c,d,e,!0),a.stroke())};mxCylinder.prototype.getCylinderSize=function(a,b,c,d){return Math.min(this.maxHeight,Math.round(d/5))}; +mxCylinder.prototype.redrawPath=function(a,b,c,d,e,f){b=this.getCylinderSize(b,c,d,e);if(f&&null!=this.fill||!f&&null==this.fill)a.moveTo(0,b),a.curveTo(0,2*b,d,2*b,d,b),f||(a.stroke(),a.begin());f||(a.moveTo(0,b),a.curveTo(0,-b/3,d,-b/3,d,b),a.lineTo(d,e-b),a.curveTo(d,e+b/3,0,e+b/3,0,e-b),a.close())};function mxConnector(a,b,c){mxPolyline.call(this,a,b,c)}mxUtils.extend(mxConnector,mxPolyline); +mxConnector.prototype.updateBoundingBox=function(){this.useSvgBoundingBox=null!=this.style&&1==this.style[mxConstants.STYLE_CURVED];mxShape.prototype.updateBoundingBox.apply(this,arguments)};mxConnector.prototype.paintEdgeShape=function(a,b){var c=this.createMarker(a,b,!0),d=this.createMarker(a,b,!1);mxPolyline.prototype.paintEdgeShape.apply(this,arguments);a.setFillColor(this.stroke);a.setShadow(!1);a.setDashed(!1);null!=c&&c();null!=d&&d()}; +mxConnector.prototype.createMarker=function(a,b,c){var d=null,e=b.length,f=mxUtils.getValue(this.style,c?mxConstants.STYLE_STARTARROW:mxConstants.STYLE_ENDARROW),g=c?b[1]:b[e-2];b=c?b[0]:b[e-1];if(null!=f&&null!=g&&null!=b){d=b.x-g.x;e=b.y-g.y;var k=Math.sqrt(d*d+e*e);g=d/k;d=e/k;e=mxUtils.getNumber(this.style,c?mxConstants.STYLE_STARTSIZE:mxConstants.STYLE_ENDSIZE,mxConstants.DEFAULT_MARKERSIZE);d=mxMarker.createMarker(a,this,f,b,g,d,e,c,this.strokewidth,0!=this.style[c?mxConstants.STYLE_STARTFILL: +mxConstants.STYLE_ENDFILL])}return d}; +mxConnector.prototype.augmentBoundingBox=function(a){mxShape.prototype.augmentBoundingBox.apply(this,arguments);var b=0;mxUtils.getValue(this.style,mxConstants.STYLE_STARTARROW,mxConstants.NONE)!=mxConstants.NONE&&(b=mxUtils.getNumber(this.style,mxConstants.STYLE_STARTSIZE,mxConstants.DEFAULT_MARKERSIZE)+1);mxUtils.getValue(this.style,mxConstants.STYLE_ENDARROW,mxConstants.NONE)!=mxConstants.NONE&&(b=Math.max(b,mxUtils.getNumber(this.style,mxConstants.STYLE_ENDSIZE,mxConstants.DEFAULT_MARKERSIZE))+ +1);a.grow(b*this.scale)};function mxSwimlane(a,b,c,d){mxShape.call(this);this.bounds=a;this.fill=b;this.stroke=c;this.strokewidth=null!=d?d:1}mxUtils.extend(mxSwimlane,mxShape);mxSwimlane.prototype.imageSize=16;mxSwimlane.prototype.apply=function(a){mxShape.prototype.apply.apply(this,arguments);null!=this.style&&(this.laneFill=mxUtils.getValue(this.style,mxConstants.STYLE_SWIMLANE_FILLCOLOR,mxConstants.NONE))};mxSwimlane.prototype.isRoundable=function(){return!0}; +mxSwimlane.prototype.getTitleSize=function(){return Math.max(0,mxUtils.getValue(this.style,mxConstants.STYLE_STARTSIZE,mxConstants.DEFAULT_STARTSIZE))}; +mxSwimlane.prototype.getLabelBounds=function(a){var b=1==mxUtils.getValue(this.style,mxConstants.STYLE_FLIPH,0),c=1==mxUtils.getValue(this.style,mxConstants.STYLE_FLIPV,0);a=new mxRectangle(a.x,a.y,a.width,a.height);var d=this.isHorizontal(),e=this.getTitleSize(),f=this.direction==mxConstants.DIRECTION_NORTH||this.direction==mxConstants.DIRECTION_SOUTH;d=d==!f;b=!d&&b!=(this.direction==mxConstants.DIRECTION_SOUTH||this.direction==mxConstants.DIRECTION_WEST);c=d&&c!=(this.direction==mxConstants.DIRECTION_SOUTH|| +this.direction==mxConstants.DIRECTION_WEST);if(f){e=Math.min(a.width,e*this.scale);if(b||c)a.x+=a.width-e;a.width=e}else{e=Math.min(a.height,e*this.scale);if(b||c)a.y+=a.height-e;a.height=e}return a};mxSwimlane.prototype.getGradientBounds=function(a,b,c,d,e){a=this.getTitleSize();return this.isHorizontal()?new mxRectangle(b,c,d,Math.min(a,e)):new mxRectangle(b,c,Math.min(a,d),e)}; +mxSwimlane.prototype.getSwimlaneArcSize=function(a,b,c){if("1"==mxUtils.getValue(this.style,mxConstants.STYLE_ABSOLUTE_ARCSIZE,0))return Math.min(a/2,Math.min(b/2,mxUtils.getValue(this.style,mxConstants.STYLE_ARCSIZE,mxConstants.LINE_ARCSIZE)/2));a=mxUtils.getValue(this.style,mxConstants.STYLE_ARCSIZE,100*mxConstants.RECTANGLE_ROUNDING_FACTOR)/100;return c*a*3};mxSwimlane.prototype.isHorizontal=function(){return 1==mxUtils.getValue(this.style,mxConstants.STYLE_HORIZONTAL,1)}; +mxSwimlane.prototype.paintVertexShape=function(a,b,c,d,e){if(!this.outline){var f=this.getTitleSize(),g=0;f=this.isHorizontal()?Math.min(f,e):Math.min(f,d);a.translate(b,c);this.isRounded?(g=this.getSwimlaneArcSize(d,e,f),g=Math.min((this.isHorizontal()?e:d)-f,Math.min(f,g)),this.paintRoundedSwimlane(a,b,c,d,e,f,g)):this.paintSwimlane(a,b,c,d,e,f);var k=mxUtils.getValue(this.style,mxConstants.STYLE_SEPARATORCOLOR,mxConstants.NONE);this.paintSeparator(a,b,c,d,e,f,k);null!=this.image&&(e=this.getImageBounds(b, +c,d,e),k=mxUtils.getValue(this.style,mxConstants.STYLE_CLIP_PATH,null),a.image(e.x-b,e.y-c,e.width,e.height,this.image,!1,!1,!1,k));this.glass&&(a.setShadow(!1),this.paintGlassEffect(a,0,0,d,f,g))}}; +mxSwimlane.prototype.configurePointerEvents=function(a){var b=!0,c=!0,d=!0;null!=this.style&&(b="1"==mxUtils.getValue(this.style,mxConstants.STYLE_POINTER_EVENTS,"1"),c=1==mxUtils.getValue(this.style,mxConstants.STYLE_SWIMLANE_HEAD,1),d=1==mxUtils.getValue(this.style,mxConstants.STYLE_SWIMLANE_BODY,1));(b||c||d)&&mxShape.prototype.configurePointerEvents.apply(this,arguments)}; +mxSwimlane.prototype.paintSwimlane=function(a,b,c,d,e,f){var g=this.laneFill,k=!0,l=!0,m=!0,n=!0;null!=this.style&&(k="1"==mxUtils.getValue(this.style,mxConstants.STYLE_POINTER_EVENTS,"1"),l=1==mxUtils.getValue(this.style,mxConstants.STYLE_SWIMLANE_LINE,1),m=1==mxUtils.getValue(this.style,mxConstants.STYLE_SWIMLANE_HEAD,1),n=1==mxUtils.getValue(this.style,mxConstants.STYLE_SWIMLANE_BODY,1));this.isHorizontal()?(a.begin(),a.moveTo(0,f),a.lineTo(0,0),a.lineTo(d,0),a.lineTo(d,f),m?a.fillAndStroke(): +a.fill(),fa.weightedValue?-1:b.weightedValuec)break;g=l}}f=e.getIndex(a);f=Math.max(0,b-(b>f?1:0));d.add(e,a,f)}}; +mxStackLayout.prototype.getParentSize=function(a){var b=this.graph.getModel(),c=b.getGeometry(a);null!=this.graph.container&&(null==c&&b.isLayer(a)||a==this.graph.getView().currentRoot)&&(c=new mxRectangle(0,0,this.graph.container.offsetWidth-1,this.graph.container.offsetHeight-1));return c}; +mxStackLayout.prototype.getLayoutCells=function(a){for(var b=this.graph.getModel(),c=b.getChildCount(a),d=[],e=0;ek.x>0?1:-1:g.y==k.y?0:g.y>k.y>0?1:-1}));return d}; +mxStackLayout.prototype.snap=function(a){if(null!=this.gridSize&&0this.gridSize/2?this.gridSize-b:-b}return a}; +mxStackLayout.prototype.execute=function(a){if(null!=a){var b=this.getParentSize(a),c=this.isHorizontal(),d=this.graph.getModel(),e=null;null!=b&&(e=c?b.height-this.marginTop-this.marginBottom:b.width-this.marginLeft-this.marginRight);e-=2*this.border;var f=this.x0+this.border+this.marginLeft,g=this.y0+this.border+this.marginTop;if(this.graph.isSwimlane(a)){var k=this.graph.getCellStyle(a),l=mxUtils.getNumber(k,mxConstants.STYLE_STARTSIZE,mxConstants.DEFAULT_STARTSIZE);k=1==mxUtils.getValue(k,mxConstants.STYLE_HORIZONTAL, +!0);null!=b&&(l=k?Math.min(l,b.height):Math.min(l,b.width));c==k&&(e-=l);k?g+=l:f+=l}d.beginUpdate();try{l=0;k=null;for(var m=0,n=null,p=this.getLayoutCells(a),q=0;qthis.wrap||!c&&k.y+k.height+t.height+2*this.spacing>this.wrap)&&(k=null,c?g+=l+this.spacing:f+=l+this.spacing,l=0);l=Math.max(l,c?t.height:t.width);var u=0;if(!this.borderCollapse){var x=this.graph.getCellStyle(r); +u=mxUtils.getNumber(x,mxConstants.STYLE_STROKEWIDTH,1)}if(null!=k){var y=m+this.spacing+Math.floor(u/2);c?t.x=this.snap((this.allowGaps?Math.max(y,t.x):y)-this.marginLeft)+this.marginLeft:t.y=this.snap((this.allowGaps?Math.max(y,t.y):y)-this.marginTop)+this.marginTop}else this.keepFirstLocation||(c?t.x=this.allowGaps&&t.x>f?Math.max(this.snap(t.x-this.marginLeft)+this.marginLeft,f):f:t.y=this.allowGaps&&t.y>g?Math.max(this.snap(t.y-this.marginTop)+this.marginTop,g):g);c?t.y=g:t.x=f;this.fill&&null!= +e&&(c?t.height=e:t.width=e);c?t.width=this.snap(t.width):t.height=this.snap(t.height);this.setChildGeometry(r,t);n=r;k=t;m=c?k.x+k.width+Math.floor(u/2):k.y+k.height+Math.floor(u/2)}}this.resizeParent&&null!=b&&null!=k&&!this.graph.isCellCollapsed(a)?this.updateParentGeometry(a,b,k):this.resizeLast&&null!=b&&null!=k&&null!=n&&(c?k.width=b.width-k.x-this.spacing-this.marginRight-this.marginLeft:k.height=b.height-k.y-this.spacing-this.marginBottom,this.setChildGeometry(n,k))}finally{d.endUpdate()}}}; +mxStackLayout.prototype.setChildGeometry=function(a,b){var c=this.graph.getCellGeometry(a);null!=c&&b.x==c.x&&b.y==c.y&&b.width==c.width&&b.height==c.height||this.graph.getModel().setGeometry(a,b)}; +mxStackLayout.prototype.updateParentGeometry=function(a,b,c){var d=this.isHorizontal(),e=this.graph.getModel(),f=b.clone();d?(c=c.x+c.width+this.marginRight+this.border,f.width=this.resizeParentMax?Math.max(f.width,c):c):(c=c.y+c.height+this.marginBottom+this.border,f.height=this.resizeParentMax?Math.max(f.height,c):c);b.x==f.x&&b.y==f.y&&b.width==f.width&&b.height==f.height||e.setGeometry(a,f)}; +function mxPartitionLayout(a,b,c,d){mxGraphLayout.call(this,a);this.horizontal=null!=b?b:!0;this.spacing=c||0;this.border=d||0}mxPartitionLayout.prototype=new mxGraphLayout;mxPartitionLayout.prototype.constructor=mxPartitionLayout;mxPartitionLayout.prototype.horizontal=null;mxPartitionLayout.prototype.spacing=null;mxPartitionLayout.prototype.border=null;mxPartitionLayout.prototype.resizeVertices=!0;mxPartitionLayout.prototype.isHorizontal=function(){return this.horizontal}; +mxPartitionLayout.prototype.moveCell=function(a,b,c){c=this.graph.getModel();var d=c.getParent(a);if(null!=a&&null!=d){var e,f=0,g=c.getChildCount(d);for(e=0;eb)break;f=k}}b=d.getIndex(a);b=Math.max(0,e-(e>b?1:0));c.add(d,a,b)}}; +mxPartitionLayout.prototype.execute=function(a){var b=this.isHorizontal(),c=this.graph.getModel(),d=c.getGeometry(a);null!=this.graph.container&&(null==d&&c.isLayer(a)||a==this.graph.getView().currentRoot)&&(d=new mxRectangle(0,0,this.graph.container.offsetWidth-1,this.graph.container.offsetHeight-1));if(null!=d){for(var e=[],f=c.getChildCount(a),g=0;gg.x&&(d=Math.abs(f-g.x));0>g.y&&(k=Math.abs(b-g.y));0==d&&0==k||this.moveNode(this.node,d,k);this.resizeParent&&this.adjustParents();this.edgeRouting&&this.localEdgeProcessing(this.node)}null!=this.parentX&&null!=this.parentY&&(e=this.graph.getCellGeometry(a),null!=e&&(e=e.clone(),e.x=this.parentX,e.y=this.parentY,c.setGeometry(a,e)))}}finally{c.endUpdate()}}}; +mxCompactTreeLayout.prototype.moveNode=function(a,b,c){a.x+=b;a.y+=c;this.apply(a);for(a=a.child;null!=a;)this.moveNode(a,b,c),a=a.next}; +mxCompactTreeLayout.prototype.sortOutgoingEdges=function(a,b){var c=new mxDictionary;b.sort(function(d,e){var f=d.getTerminal(d.getTerminal(!1)==a);d=c.get(f);null==d&&(d=mxCellPath.create(f).split(mxCellPath.PATH_SEPARATOR),c.put(f,d));e=e.getTerminal(e.getTerminal(!1)==a);f=c.get(e);null==f&&(f=mxCellPath.create(e).split(mxCellPath.PATH_SEPARATOR),c.put(e,f));return mxCellPath.compare(d,f)})}; +mxCompactTreeLayout.prototype.findRankHeights=function(a,b){if(null==this.maxRankHeight[b]||this.maxRankHeight[b]a.height&&(a.height=this.maxRankHeight[b]);for(a=a.child;null!=a;)this.setCellHeights(a,b+1),a=a.next}; +mxCompactTreeLayout.prototype.dfs=function(a,b){var c=mxCellPath.create(a),d=null;if(null!=a&&null==this.visited[c]&&!this.isVertexIgnored(a)){this.visited[c]=a;d=this.createNode(a);c=this.graph.getModel();var e=null,f=this.graph.getEdges(a,b,this.invert,!this.invert,!1,!0),g=this.graph.getView();this.sortEdges&&this.sortOutgoingEdges(a,f);for(a=0;a=a+c)return 0;a=0a?a*d/c-b:0a+c?(c+a)*f/e-(b+d):f-(b+d);return 0g+2*this.prefHozEdgeSep&&(f-=2*this.prefHozEdgeSep);a=f/d;b=a/2;f>g+2*this.prefHozEdgeSep&&(b+=this.prefHozEdgeSep);f=this.minEdgeJetty-this.prefVertEdgeOff;g=this.getVertexBounds(c);for(var k=0;kd/2&&(f-=this.prefVertEdgeOff);b+=a}}; +function mxRadialTreeLayout(a){mxCompactTreeLayout.call(this,a,!1)}mxUtils.extend(mxRadialTreeLayout,mxCompactTreeLayout);mxRadialTreeLayout.prototype.angleOffset=.5;mxRadialTreeLayout.prototype.rootx=0;mxRadialTreeLayout.prototype.rooty=0;mxRadialTreeLayout.prototype.levelDistance=120;mxRadialTreeLayout.prototype.nodeDistance=10;mxRadialTreeLayout.prototype.autoRadius=!1;mxRadialTreeLayout.prototype.sortEdges=!1;mxRadialTreeLayout.prototype.rowMinX=[];mxRadialTreeLayout.prototype.rowMaxX=[]; +mxRadialTreeLayout.prototype.rowMinCenX=[];mxRadialTreeLayout.prototype.rowMaxCenX=[];mxRadialTreeLayout.prototype.rowRadi=[];mxRadialTreeLayout.prototype.row=[];mxRadialTreeLayout.prototype.isVertexIgnored=function(a){return mxGraphLayout.prototype.isVertexIgnored.apply(this,arguments)||0==this.graph.getConnections(a).length}; +mxRadialTreeLayout.prototype.execute=function(a,b){this.parent=a;this.edgeRouting=this.useBoundingBox=!1;mxCompactTreeLayout.prototype.execute.apply(this,arguments);var c=null,d=this.getVertexBounds(this.root);this.centerX=d.x+d.width/2;this.centerY=d.y+d.height/2;for(var e in this.visited){var f=this.getVertexBounds(this.visited[e]);c=null!=c?c:f.clone();c.add(f)}this.calcRowDims([this.node],0);var g=0,k=0;for(c=0;c +d.theta&&ethis.forceConstant&&(this.forceConstant= +.001);this.forceConstantSquared=this.forceConstant*this.forceConstant;for(d=0;db&&(b=.001);var c=this.dispX[a]/b*Math.min(b,this.temperature);b=this.dispY[a]/b*Math.min(b,this.temperature);this.dispX[a]=0;this.dispY[a]=0;this.cellLocation[a][0]+=c;this.cellLocation[a][1]+=b}}; +mxFastOrganicLayout.prototype.calcAttraction=function(){for(var a=0;athis.maxDistanceLimit||(gb?b+"-"+c:c+"-"+b)+d}return null}; +mxParallelEdgeLayout.prototype.layout=function(a){var b=a[0],c=this.graph.getView(),d=this.graph.getModel(),e=d.getGeometry(c.getVisibleTerminal(b,!0));d=d.getGeometry(c.getVisibleTerminal(b,!1));if(e==d){b=e.x+e.width+this.spacing;c=e.y+e.height/2;for(var f=0;fmxUtils.indexOf(l.connectsAsTarget,g)&&l.connectsAsTarget.push(g))}}c[d].temp[0]=1}}mxGraphHierarchyModel.prototype.maxRank=null;mxGraphHierarchyModel.prototype.vertexMapper=null;mxGraphHierarchyModel.prototype.edgeMapper=null;mxGraphHierarchyModel.prototype.ranks=null;mxGraphHierarchyModel.prototype.roots=null;mxGraphHierarchyModel.prototype.parent=null; +mxGraphHierarchyModel.prototype.dfsCount=0;mxGraphHierarchyModel.prototype.SOURCESCANSTARTRANK=1E8;mxGraphHierarchyModel.prototype.tightenToSource=!1; +mxGraphHierarchyModel.prototype.createInternalCells=function(a,b,c){for(var d=a.getGraph(),e=0;e=l.length){k= +new mxGraphHierarchyEdge(l);for(var m=0;mmxUtils.indexOf(c[e].connectsAsSource,k)&&c[e].connectsAsSource.push(k)}}}c[e].temp[0]=0}}; +mxGraphHierarchyModel.prototype.initialRank=function(){var a=[];if(null!=this.roots)for(var b=0;bg.maxRank&&0>g.minRank&&(a[g.temp[0]].push(g),g.maxRank=g.temp[0],g.minRank=g.temp[0],g.temp[0]=a[g.maxRank].length-1);if(null!=f&&null!=k&&1mxUtils.indexOf(l.connectsAsTarget,g)&&l.connectsAsTarget.push(g))}}c[d].temp[0]=1}}mxSwimlaneModel.prototype.maxRank=null;mxSwimlaneModel.prototype.vertexMapper=null;mxSwimlaneModel.prototype.edgeMapper=null;mxSwimlaneModel.prototype.ranks=null;mxSwimlaneModel.prototype.roots=null;mxSwimlaneModel.prototype.parent=null;mxSwimlaneModel.prototype.dfsCount=0; +mxSwimlaneModel.prototype.SOURCESCANSTARTRANK=1E8;mxSwimlaneModel.prototype.tightenToSource=!1;mxSwimlaneModel.prototype.ranksPerGroup=null; +mxSwimlaneModel.prototype.createInternalCells=function(a,b,c){for(var d=a.getGraph(),e=a.swimlanes,f=0;f=m.length){l=new mxGraphHierarchyEdge(m);for(var n=0;nmxUtils.indexOf(c[f].connectsAsSource,l)&&c[f].connectsAsSource.push(l)}}}c[f].temp[0]=0}}; +mxSwimlaneModel.prototype.initialRank=function(){this.ranksPerGroup=[];var a=[],b={};if(null!=this.roots)for(var c=0;cb[d.swimlaneIndex]&&(k=b[d.swimlaneIndex]);d.temp[0]=k;if(null!=f)for(c=0;cg.maxRank&&0>g.minRank&&(a[g.temp[0]].push(g),g.maxRank=g.temp[0],g.minRank=g.temp[0],g.temp[0]=a[g.maxRank].length-1);if(null!=f&&null!=k&&1>1,++e[f];return c}; +mxMedianHybridCrossingReduction.prototype.transpose=function(a,b){for(var c=!0,d=0;c&&10>d++;){var e=1==a%2&&1==d%2;c=!1;for(var f=0;fn&&(n=l);k[n]=m}var p=null,q=null,r=null,t=null,u=null;for(l=0;lr[v]&&B++,y[A]t[v]&&B++,C[A]a.medianValue?-1:b.medianValuex+1&&(m==d[l].length-1?(e.setGeneralPurposeVariable(l,y),p=!0):(m=d[l][m+1],x=m.getGeneralPurposeVariable(l),x=x-m.width/2-this.intraCellSpacing-e.width/2,x>y?(e.setGeneralPurposeVariable(l, +y),p=!0):x>e.getGeneralPurposeVariable(l)+1&&(e.setGeneralPurposeVariable(l,x),p=!0)));if(p){for(e=0;e=k&&l<=q?g.setGeneralPurposeVariable(a,l):lq&&(g.setGeneralPurposeVariable(a,q),this.currentXDelta+=l-q);d[f].visited=!0}};mxCoordinateAssignment.prototype.calculatedWeightedValue=function(a,b){for(var c=0,d=0;dthis.widestRankValue&&(this.widestRankValue=g,this.widestRank=d);this.rankWidths[d]=g}1==k&&mxLog.warn("At least one cell has no bounds");this.rankY[d]=a;g=e/2+c/2+this.interRankCellSpacing;c=e;a=this.orientation==mxConstants.DIRECTION_NORTH||this.orientation==mxConstants.DIRECTION_WEST?a+g:a- +g;for(l=0;ld.maxRank-d.minRank-1)){for(var e=d.getGeneralPurposeVariable(d.minRank+1),f=!0,g=0,k=d.minRank+2;kd.minRank+1;k--)p=d.getX(k-1),n==p?(m[k-d.minRank-2]=n,f++):this.repositionValid(b,d,k-1,n)?(m[k-d.minRank-2]=n,f++):(m[k-d.minRank-2]=d.getX(k-1),n=p);if(f>g||e>g)if(f>=e)for(k=d.maxRank-2;k>d.minRank;k--)d.setX(k,m[k-d.minRank-1]);else if(e>f)for(k=d.minRank+2;ke)return!1;f=b.getGeneralPurposeVariable(c);if(df){if(e==a.length-1)return!0;a=a[e+1];c=a.getGeneralPurposeVariable(c);c=c-a.width/2-this.intraCellSpacing-b.width/2;if(!(c>=d))return!1}return!0}; +mxCoordinateAssignment.prototype.setCellLocations=function(a,b){this.rankTopY=[];this.rankBottomY=[];for(a=0;ak;k++){if(-1(f+1)*this.prefHozEdgeSep+2*this.prefHozEdgeSep&&(n+=this.prefHozEdgeSep,p-=this.prefHozEdgeSep);l=(p-n)/f;n+=l/2;p=this.minEdgeJetty-this.prefVertEdgeOff;for(m=0;mf/2&&(p-=this.prefVertEdgeOff),t=0;te&&(e=k,d=g)}}0==c.length&&null!=d&&c.push(d)}return c}; +mxHierarchicalLayout.prototype.getEdges=function(a){var b=this.edgesCache.get(a);if(null!=b)return b;var c=this.graph.model;b=[];for(var d=this.graph.isCellCollapsed(a),e=c.getChildCount(a),f=0;fb.length)){null==a&&(a=c.getParent(b[0]));this.parentY=this.parentX=null;if(a!=this.root&&null!=c.isVertex(a)&&this.maintainParentLocation){var d=this.graph.getCellGeometry(a);null!=d&&(this.parentX=d.x,this.parentY=d.y)}this.swimlanes=b;for(var e=[],f=0;ff&&(f=l,e=k)}}0==c.length&&null!=e&&c.push(e)}return c}; +mxSwimlaneLayout.prototype.getEdges=function(a){var b=this.edgesCache.get(a);if(null!=b)return b;var c=this.graph.model;b=[];for(var d=this.graph.isCellCollapsed(a),e=c.getChildCount(a),f=0;f=this.swimlanes.length||!(q>k||(!b||p)&&q==k)||(e=this.traverse(n, +b,m[c],d,e,f,g,q))}}else if(null==e[l])for(c=0;cmxUtils.indexOf(this.edges,a))&&(null==this.edges&&(this.edges=[]),this.edges.push(a));return a};mxCell.prototype.removeEdge=function(a,b){if(null!=a){if(a.getTerminal(!b)!=this&&null!=this.edges){var c=this.getEdgeIndex(a);0<=c&&this.edges.splice(c,1)}a.setTerminal(null,b)}return a}; +mxCell.prototype.removeFromTerminal=function(a){var b=this.getTerminal(a);null!=b&&b.removeEdge(this,a)};mxCell.prototype.hasAttribute=function(a){var b=this.getValue();return null!=b&&b.nodeType==mxConstants.NODETYPE_ELEMENT&&b.hasAttribute?b.hasAttribute(a):null!=b.getAttribute(a)};mxCell.prototype.getAttribute=function(a,b){var c=this.getValue();a=null!=c&&c.nodeType==mxConstants.NODETYPE_ELEMENT?c.getAttribute(a):null;return null!=a?a:b}; +mxCell.prototype.setAttribute=function(a,b){var c=this.getValue();null!=c&&c.nodeType==mxConstants.NODETYPE_ELEMENT&&c.setAttribute(a,b)};mxCell.prototype.clone=function(){var a=mxUtils.clone(this,this.mxTransient);a.setValue(this.cloneValue());return a};mxCell.prototype.cloneValue=function(a){a=null!=a?a:this.getValue();null!=a&&("function"==typeof a.clone?a=a.clone():isNaN(a.nodeType)||(a=a.cloneNode(!0)));return a};function mxGeometry(a,b,c,d){mxRectangle.call(this,a,b,c,d)} +mxGeometry.prototype=new mxRectangle;mxGeometry.prototype.constructor=mxGeometry;mxGeometry.prototype.TRANSLATE_CONTROL_POINTS=!0;mxGeometry.prototype.alternateBounds=null;mxGeometry.prototype.sourcePoint=null;mxGeometry.prototype.targetPoint=null;mxGeometry.prototype.points=null;mxGeometry.prototype.offset=null;mxGeometry.prototype.relative=!1; +mxGeometry.prototype.swap=function(){if(null!=this.alternateBounds){var a=new mxRectangle(this.x,this.y,this.width,this.height);this.x=this.alternateBounds.x;this.y=this.alternateBounds.y;this.width=this.alternateBounds.width;this.height=this.alternateBounds.height;this.alternateBounds=a}};mxGeometry.prototype.getTerminalPoint=function(a){return a?this.sourcePoint:this.targetPoint};mxGeometry.prototype.setTerminalPoint=function(a,b){b?this.sourcePoint=a:this.targetPoint=a;return a}; +mxGeometry.prototype.rotate=function(a,b){var c=mxUtils.toRadians(a);a=Math.cos(c);c=Math.sin(c);if(!this.relative){var d=new mxPoint(this.getCenterX(),this.getCenterY());d=mxUtils.getRotatedPoint(d,a,c,b);this.x=Math.round(d.x-this.width/2);this.y=Math.round(d.y-this.height/2)}null!=this.sourcePoint&&(d=mxUtils.getRotatedPoint(this.sourcePoint,a,c,b),this.sourcePoint.x=Math.round(d.x),this.sourcePoint.y=Math.round(d.y));null!=this.targetPoint&&(d=mxUtils.getRotatedPoint(this.targetPoint,a,c,b),this.targetPoint.x= +Math.round(d.x),this.targetPoint.y=Math.round(d.y));if(null!=this.points)for(var e=0;eb[e]?1:-1:(c=parseInt(a[e]),e=parseInt(b[e]),d=c==e?0:c>e?1:-1);break}0==d&&(c=a.length,e=b.length,c!=e&&(d=c>e?1:-1));return d}},mxPerimeter={RectanglePerimeter:function(a,b,c,d){b=a.getCenterX();var e=a.getCenterY(),f=Math.atan2(c.y-e,c.x-b),g=new mxPoint(0,0),k=Math.PI,l=Math.PI/2-f,m=Math.atan2(a.height,a.width);f<-k+m||f>k-m?(g.x=a.x,g.y=e-a.width*Math.tan(f)/ +2):f<-m?(g.y=a.y,g.x=b-a.height*Math.tan(l)/2):f=a.x&&c.x<=a.x+a.width?g.x=c.x:c.y>=a.y&&c.y<=a.y+a.height&&(g.y=c.y),c.xa.x+a.width&&(g.x=a.x+a.width),c.ya.y+a.height&&(g.y=a.y+a.height));return g},EllipsePerimeter:function(a,b,c,d){var e=a.x,f=a.y,g=a.width/2,k=a.height/2,l=e+g,m=f+k;b=c.x;c=c.y;var n=parseInt(b-l),p=parseInt(c-m);if(0==n&&0!=p)return new mxPoint(l, +m+k*p/Math.abs(p));if(0==n&&0==p)return new mxPoint(b,c);if(d){if(c>=f&&c<=f+a.height)return a=c-m,a=Math.sqrt(g*g*(1-a*a/(k*k)))||0,b<=e&&(a=-a),new mxPoint(l+a,c);if(b>=e&&b<=e+a.width)return a=b-l,a=Math.sqrt(k*k*(1-a*a/(g*g)))||0,c<=f&&(a=-a),new mxPoint(b,m+a)}e=p/n;m-=e*l;f=g*g*e*e+k*k;a=-2*l*f;k=Math.sqrt(a*a-4*f*(g*g*e*e*l*l+k*k*l*l-g*g*k*k));g=(-a+k)/(2*f);l=(-a-k)/(2*f);k=e*g+m;m=e*l+m;Math.sqrt(Math.pow(g-b,2)+Math.pow(k-c,2))c?new mxPoint(g,e):new mxPoint(g,e+a);if(k==c)return g>l?new mxPoint(b,k):new mxPoint(b+f,k);var m=g,n=k;d&&(l>=b&&l<=b+f?m=l:c>=e&&c<=e+a&&(n=c));return l-t&&rMath.PI-t)?c=d&&(e&&c.x>=n.x&&c.x<=q.x||!e&&c.y>=n.y&&c.y<=q.y)?e?new mxPoint(c.x,n.y):new mxPoint(n.x,c.y):b==mxConstants.DIRECTION_NORTH?new mxPoint(f+k/2+l*Math.tan(r)/2,g+l):b==mxConstants.DIRECTION_SOUTH?new mxPoint(f+k/2-l*Math.tan(r)/2,g):b==mxConstants.DIRECTION_WEST?new mxPoint(f+k,g+l/2+k*Math.tan(r)/2):new mxPoint(f,g+ +l/2-k*Math.tan(r)/2):(d&&(d=new mxPoint(a,m),c.y>=g&&c.y<=g+l?(d.x=e?a:b==mxConstants.DIRECTION_WEST?f+k:f,d.y=c.y):c.x>=f&&c.x<=f+k&&(d.x=c.x,d.y=e?b==mxConstants.DIRECTION_NORTH?g+l:g:m),a=d.x,m=d.y),c=e&&c.x<=f+k/2||!e&&c.y<=g+l/2?mxUtils.intersection(c.x,c.y,a,m,n.x,n.y,p.x,p.y):mxUtils.intersection(c.x,c.y,a,m,p.x,p.y,q.x,q.y));null==c&&(c=new mxPoint(a,m));return c},HexagonPerimeter:function(a,b,c,d){var e=a.x,f=a.y,g=a.width,k=a.height,l=a.getCenterX();a=a.getCenterY();var m=c.x,n=c.y,p=-Math.atan2(n- +a,m-l),q=Math.PI,r=Math.PI/2;new mxPoint(l,a);b=null!=b?mxUtils.getValue(b.style,mxConstants.STYLE_DIRECTION,mxConstants.DIRECTION_EAST):mxConstants.DIRECTION_EAST;var t=b==mxConstants.DIRECTION_NORTH||b==mxConstants.DIRECTION_SOUTH;b=new mxPoint;var u=new mxPoint;if(mf+k||m>e+g&&ne+g&&n>f+k)d=!1;if(d){if(t){if(m==l){if(n<=f)return new mxPoint(l,f);if(n>=f+k)return new mxPoint(l,f+k)}else if(me+g){if(n==f+k/4)return new mxPoint(e+g,f+k/4);if(n==f+3*k/4)return new mxPoint(e+g,f+3*k/4)}else if(m==e){if(na)return new mxPoint(e,f+3*k/4)}else if(m==e+g){if(na)return new mxPoint(e+g,f+3*k/4)}if(n==f)return new mxPoint(l,f);if(n==f+k)return new mxPoint(l,f+k);mf+k/4&&nf+3*k/4&&(b=new mxPoint(e-Math.floor(.5*g),f+Math.floor(.5*k)),u=new mxPoint(e+g,f+Math.floor(1.25*k))):m>l&&(n>f+k/4&&nf+3*k/4&&(b=new mxPoint(e+Math.floor(1.5*g),f+Math.floor(.5*k)),u=new mxPoint(e,f+Math.floor(1.25*k))))}else{if(n==a){if(m<=e)return new mxPoint(e,f+k/2);if(m>=e+g)return new mxPoint(e+g,f+k/2)}else if(n< +f){if(m==e+g/4)return new mxPoint(e+g/4,f);if(m==e+3*g/4)return new mxPoint(e+3*g/4,f)}else if(n>f+k){if(m==e+g/4)return new mxPoint(e+g/4,f+k);if(m==e+3*g/4)return new mxPoint(e+3*g/4,f+k)}else if(n==f){if(ml)return new mxPoint(e+3*g/4,f)}else if(n==f+k){if(ma)return new mxPoint(e+3*g/4,f+k)}if(m==e)return new mxPoint(e,a);if(m==e+g)return new mxPoint(e+g,a);ne+g/4&&me+3*g/4&&(b=new mxPoint(e+Math.floor(.5*g),f-Math.floor(.5*k)),u=new mxPoint(e+Math.floor(1.25*g),f+k)):n>a&&(m>e+g/4&&me+3*g/4&&(b=new mxPoint(e+Math.floor(.5*g),f+Math.floor(1.5*k)),u=new mxPoint(e+Math.floor(1.25*g),f)))}d=l;p=a;m>=e&&m<= +e+g?(d=m,p=n=f&&n<=f+k&&(p=n,d=m-m?(b=new mxPoint(e+g,f),u=new mxPoint(e+g,f+ +k)):p>m&&pr&&pq-m&&p<=q||p<-q+m&&p>=-q?(b=new mxPoint(e,f),u=new mxPoint(e,f+k)):p<-m&&p>-r?(b=new mxPoint(e+Math.floor(1.5*g),f+Math.floor(.5*k)),u=new mxPoint(e,f+Math.floor(1.25*k))):p<-r&&p>-q+m&&(b=new mxPoint(e-Math.floor(.5*g),f+Math.floor(.5*k)),u=new mxPoint(e+g,f+Math.floor(1.25*k)))}else{m= +Math.atan2(k/2,g/4);if(p==m)return new mxPoint(e+Math.floor(.75*g),f);if(p==q-m)return new mxPoint(e+Math.floor(.25*g),f);if(p==q||p==-q)return new mxPoint(e,f+Math.floor(.5*k));if(0==p)return new mxPoint(e+g,f+Math.floor(.5*k));if(p==-m)return new mxPoint(e+Math.floor(.75*g),f+k);if(p==-q+m)return new mxPoint(e+Math.floor(.25*g),f+k);0m&&pq-m&& +pp&&p>-m?(b=new mxPoint(e+Math.floor(.5*g),f+Math.floor(1.5*k)),u=new mxPoint(e+Math.floor(1.25*g),f)):p<-m&&p>-q+m?(b=new mxPoint(e,f+k),u=new mxPoint(e+g,f+k)):p<-q+m&&p>-q&&(b=new mxPoint(e-Math.floor(.25*g),f),u=new mxPoint(e+Math.floor(.5*g),f+Math.floor(1.5*k)))}c=mxUtils.intersection(l,a,c.x,c.y,b.x,b.y,u.x,u.y)}return null==c?new mxPoint(l,a):c}}; +function mxPrintPreview(a,b,c,d,e,f,g,k,l){this.graph=a;this.scale=null!=b?b:1/a.pageScale;this.border=null!=d?d:0;this.pageFormat=mxRectangle.fromRectangle(null!=c?c:a.pageFormat);this.title=null!=k?k:"Printer-friendly version";this.x0=null!=e?e:0;this.y0=null!=f?f:0;this.borderColor=g;this.pageSelector=null!=l?l:!0}mxPrintPreview.prototype.graph=null;mxPrintPreview.prototype.pageFormat=null;mxPrintPreview.prototype.scale=null;mxPrintPreview.prototype.border=0; +mxPrintPreview.prototype.marginTop=0;mxPrintPreview.prototype.marginBottom=0;mxPrintPreview.prototype.x0=0;mxPrintPreview.prototype.y0=0;mxPrintPreview.prototype.autoOrigin=!0;mxPrintPreview.prototype.printOverlays=!1;mxPrintPreview.prototype.printControls=!1;mxPrintPreview.prototype.printBackgroundImage=!1;mxPrintPreview.prototype.backgroundColor="#ffffff";mxPrintPreview.prototype.borderColor=null;mxPrintPreview.prototype.title=null;mxPrintPreview.prototype.pageSelector=null; +mxPrintPreview.prototype.wnd=null;mxPrintPreview.prototype.targetWindow=null;mxPrintPreview.prototype.pageCount=0;mxPrintPreview.prototype.clipping=!0;mxPrintPreview.prototype.getWindow=function(){return this.wnd};mxPrintPreview.prototype.getDoctype=function(){var a="";8==document.documentMode?a='':8");k.writeln("");k.writeln("");this.writeHead(k,a);k.writeln("");k.writeln('')}var m=this.graph.getGraphBounds().clone(),n=this.graph.getView().getScale(),p=n/this.scale,q=this.graph.getView().getTranslate();this.autoOrigin||(this.x0-=q.x*this.scale,this.y0-=q.y*this.scale,m.width+=m.x,m.height+=m.y,m.x=0,this.border=m.y=0);var r=this.pageFormat.width-2*this.border,t=this.pageFormat.height- +2*this.border;this.pageFormat.height+=this.marginTop+this.marginBottom;m.width/=p;m.height/=p;var u=Math.max(1,Math.ceil((m.width+this.x0)/r)),x=Math.max(1,Math.ceil((m.height+this.y0)/t));this.pageCount=u*x;var y=mxUtils.bind(this,function(){if(this.pageSelector&&(1");a.writeln("");a.close();mxEvent.release(a.body)}}catch(b){}}; +mxPrintPreview.prototype.writeHead=function(a,b){null!=this.title&&a.writeln(""+this.title+"");mxClient.link("stylesheet",mxClient.basePath+"/css/common.css",a);a.writeln('")};mxPrintPreview.prototype.writePostfix=function(a){}; +mxPrintPreview.prototype.createPageSelector=function(a,b){var c=this.wnd.document,d=c.createElement("table");d.className="mxPageSelector";d.setAttribute("border","0");for(var e=c.createElement("tbody"),f=0;f":"";mxCellEditor.prototype.escapeCancelsEditing=!0;mxCellEditor.prototype.textNode="";mxCellEditor.prototype.zIndex=5;mxCellEditor.prototype.minResize=new mxRectangle(0,20); +mxCellEditor.prototype.wordWrapPadding=mxClient.IS_IE11?0:1;mxCellEditor.prototype.blurEnabled=!1;mxCellEditor.prototype.initialValue=null;mxCellEditor.prototype.align=null;mxCellEditor.prototype.init=function(){this.textarea=document.createElement("div");this.textarea.className="mxCellEditor mxPlainTextEditor";this.textarea.contentEditable=!0;mxClient.IS_GC&&(this.textarea.style.minHeight="1em");this.textarea.style.position=this.isLegacyEditor()?"absolute":"relative";this.installListeners(this.textarea)}; +mxCellEditor.prototype.applyValue=function(a,b){this.graph.labelChanged(a.cell,b,this.trigger)};mxCellEditor.prototype.setAlign=function(a){null!=this.textarea&&(this.textarea.style.textAlign=a);this.align=a;this.resize()};mxCellEditor.prototype.getInitialValue=function(a,b){a=mxUtils.htmlEntities(this.graph.getEditingValue(a.cell,b),!1);8!=document.documentMode&&9!=document.documentMode&&10!=document.documentMode&&(a=mxUtils.replaceTrailingNewlines(a,"

"));return a.replace(/\n/g,"
")}; +mxCellEditor.prototype.getCurrentValue=function(a){return mxUtils.extractTextWithWhitespace(this.textarea.childNodes)};mxCellEditor.prototype.isCancelEditingKeyEvent=function(a){return this.escapeCancelsEditing||mxEvent.isShiftDown(a)||mxEvent.isControlDown(a)||mxEvent.isMetaDown(a)}; +mxCellEditor.prototype.installListeners=function(a){mxEvent.addListener(a,"dragstart",mxUtils.bind(this,function(d){this.graph.stopEditing(!1);mxEvent.consume(d)}));mxEvent.addListener(a,"blur",mxUtils.bind(this,function(d){this.blurEnabled&&this.focusLost(d)}));mxEvent.addListener(a,"keydown",mxUtils.bind(this,function(d){mxEvent.isConsumed(d)||(this.isStopEditingEvent(d)?(this.graph.stopEditing(!1),mxEvent.consume(d)):27==d.keyCode&&(this.graph.stopEditing(this.isCancelEditingKeyEvent(d)),mxEvent.consume(d)))})); +var b=mxUtils.bind(this,function(d){null!=this.editingCell&&this.clearOnChange&&a.innerHTML==this.getEmptyLabelText()&&(!mxClient.IS_FF||8!=d.keyCode&&46!=d.keyCode)&&(this.clearOnChange=!1,a.innerHTML="")});mxEvent.addListener(a,"keypress",b);mxEvent.addListener(a,"paste",b);b=mxUtils.bind(this,function(d){null!=this.editingCell&&(0==this.textarea.innerHTML.length||"
"==this.textarea.innerHTML?(this.textarea.innerHTML=this.getEmptyLabelText(),this.clearOnChange=0e&&(this.textarea.style.width=this.textarea.scrollWidth+"px");else if("block"==a.style[mxConstants.STYLE_OVERFLOW]|| +"width"==a.style[mxConstants.STYLE_OVERFLOW]){if(-.5==d.y||"width"==a.style[mxConstants.STYLE_OVERFLOW])this.textarea.style.maxHeight=this.bounds.height+"px";this.textarea.style.width=e+"px"}else this.textarea.style.maxWidth=e+"px";else this.textarea.style.whiteSpace="nowrap",this.textarea.style.width="";8==document.documentMode&&(this.textarea.style.zoom="1",this.textarea.style.height="auto");8==document.documentMode?(a=this.textarea.scrollWidth,e=this.textarea.scrollHeight,this.textarea.style.left= +Math.max(0,Math.ceil((this.bounds.x-d.x*(this.bounds.width-(a+1)*c)+a*(c-1)*0+2*(d.x+.5))/c))+"px",this.textarea.style.top=Math.max(0,Math.ceil((this.bounds.y-d.y*(this.bounds.height-(e+.5)*c)+e*(c-1)*0+1*Math.abs(d.y+.5))/c))+"px",this.textarea.style.width=Math.round(a*c)+"px",this.textarea.style.height=Math.round(e*c)+"px"):(this.textarea.style.left=Math.max(0,Math.round(this.bounds.x-d.x*(this.bounds.width-2))+1)+"px",this.textarea.style.top=Math.max(0,Math.round(this.bounds.y-d.y*(this.bounds.height- +4)+(-1==d.y?3:0))+1)+"px")}else this.bounds=this.getEditorBounds(a),this.textarea.style.width=Math.round(this.bounds.width/c)+"px",this.textarea.style.height=Math.round(this.bounds.height/c)+"px",8==document.documentMode?(this.textarea.style.left=Math.round(this.bounds.x)+"px",this.textarea.style.top=Math.round(this.bounds.y)+"px"):(this.textarea.style.left=Math.max(0,Math.round(this.bounds.x+1))+"px",this.textarea.style.top=Math.max(0,Math.round(this.bounds.y+1))+"px"),this.graph.isWrapping(a.cell)&& +(2<=this.bounds.width||2<=this.bounds.height)&&this.textarea.innerHTML!=this.getEmptyLabelText()?(this.textarea.style.wordWrap=mxConstants.WORD_WRAP,this.textarea.style.whiteSpace="normal","fill"!=a.style[mxConstants.STYLE_OVERFLOW]&&(this.textarea.style.width=Math.round(this.bounds.width/c)+this.wordWrapPadding+"px")):(this.textarea.style.whiteSpace="nowrap","fill"!=a.style[mxConstants.STYLE_OVERFLOW]&&(this.textarea.style.width=""));mxUtils.setPrefixedStyle(this.textarea.style,"transformOrigin", +"0px 0px");mxUtils.setPrefixedStyle(this.textarea.style,"transform","scale("+c+","+c+")"+(null==d?"":" translate("+100*d.x+"%,"+100*d.y+"%)"))}};mxCellEditor.prototype.focusLost=function(){this.stopEditing(!this.graph.isInvokesStopCellEditing())};mxCellEditor.prototype.getBackgroundColor=function(a){return null};mxCellEditor.prototype.getBorderColor=function(a){return null}; +mxCellEditor.prototype.isLegacyEditor=function(){var a=!1;if(mxClient.IS_SVG){var b=this.graph.view.getDrawPane().ownerSVGElement;null!=b&&(b=mxUtils.getCurrentStyle(b),null!=b&&(a="absolute"==b.position))}return!a}; +mxCellEditor.prototype.updateTextAreaStyle=function(a){this.graph.getView();var b=mxUtils.getValue(a.style,mxConstants.STYLE_FONTSIZE,mxConstants.DEFAULT_FONTSIZE),c=mxUtils.getValue(a.style,mxConstants.STYLE_FONTFAMILY,mxConstants.DEFAULT_FONTFAMILY),d=mxUtils.getValue(a.style,mxConstants.STYLE_FONTCOLOR,"black"),e=mxUtils.getValue(a.style,mxConstants.STYLE_ALIGN,mxConstants.ALIGN_LEFT),f=(mxUtils.getValue(a.style,mxConstants.STYLE_FONTSTYLE,0)&mxConstants.FONT_BOLD)==mxConstants.FONT_BOLD,g=(mxUtils.getValue(a.style, +mxConstants.STYLE_FONTSTYLE,0)&mxConstants.FONT_ITALIC)==mxConstants.FONT_ITALIC,k=[];(mxUtils.getValue(a.style,mxConstants.STYLE_FONTSTYLE,0)&mxConstants.FONT_UNDERLINE)==mxConstants.FONT_UNDERLINE&&k.push("underline");(mxUtils.getValue(a.style,mxConstants.STYLE_FONTSTYLE,0)&mxConstants.FONT_STRIKETHROUGH)==mxConstants.FONT_STRIKETHROUGH&&k.push("line-through");this.textarea.style.lineHeight=mxConstants.ABSOLUTE_LINE_HEIGHT?Math.round(b*mxConstants.LINE_HEIGHT)+"px":mxConstants.LINE_HEIGHT;this.textarea.style.backgroundColor= +this.getBackgroundColor(a);this.textarea.style.textDecoration=k.join(" ");this.textarea.style.fontWeight=f?"bold":"normal";this.textarea.style.fontStyle=g?"italic":"";this.textarea.style.fontSize=Math.round(b)+"px";this.textarea.style.zIndex=this.zIndex;this.textarea.style.fontFamily=c;this.textarea.style.textAlign=e;this.textarea.style.outline="none";this.textarea.style.color=d;b=this.getBorderColor(a);this.textarea.style.border=null!=b?"1px solid "+b:"none";b=this.textDirection=mxUtils.getValue(a.style, +mxConstants.STYLE_TEXT_DIRECTION,mxConstants.DEFAULT_TEXT_DIRECTION);b==mxConstants.TEXT_DIRECTION_AUTO&&(null==a||null==a.text||a.text.dialect==mxConstants.DIALECT_STRICTHTML||mxUtils.isNode(a.text.value)||(b=a.text.getAutoDirection()));b==mxConstants.TEXT_DIRECTION_LTR||b==mxConstants.TEXT_DIRECTION_RTL?this.textarea.setAttribute("dir",b):this.textarea.removeAttribute("dir")}; +mxCellEditor.prototype.startEditing=function(a,b){this.stopEditing(!0);this.align=null;null==this.textarea&&this.init();null!=this.graph.tooltipHandler&&this.graph.tooltipHandler.hideTooltip();var c=this.graph.getView().getState(a);if(null!=c){this.updateTextAreaStyle(c);this.textarea.innerHTML=this.getInitialValue(c,b)||"";this.initialValue=this.textarea.innerHTML;0==this.textarea.innerHTML.length||"
"==this.textarea.innerHTML?(this.textarea.innerHTML=this.getEmptyLabelText(),this.clearOnChange= +!0):this.clearOnChange=this.textarea.innerHTML==this.getEmptyLabelText();this.graph.container.appendChild(this.textarea);this.editingCell=a;this.trigger=b;this.textNode=null;null!=c.text&&this.isHideLabel(c)&&(this.textNode=c.text.node,this.textNode.style.visibility="hidden");this.autoSize&&(this.graph.model.isEdge(c.cell)||"fill"!=c.style[mxConstants.STYLE_OVERFLOW])&&window.setTimeout(mxUtils.bind(this,function(){this.resize()}),0);this.resize();try{this.textarea.focus(),this.isSelectText()&&0< +this.textarea.innerHTML.length&&(this.textarea.innerHTML!=this.getEmptyLabelText()||!this.clearOnChange)&&document.execCommand("selectAll",!1,null)}catch(d){}}};mxCellEditor.prototype.isSelectText=function(){return this.selectText};mxCellEditor.prototype.clearSelection=function(){var a=null;window.getSelection?a=window.getSelection():document.selection&&(a=document.selection);null!=a&&(a.empty?a.empty():a.removeAllRanges&&a.removeAllRanges())}; +mxCellEditor.prototype.stopEditing=function(a){if(null!=this.editingCell){null!=this.textNode&&(this.textNode.style.visibility="visible",this.textNode=null);a=a?null:this.graph.view.getState(this.editingCell);var b=this.initialValue;this.bounds=this.trigger=this.editingCell=this.initialValue=null;this.textarea.blur();this.clearSelection();null!=this.textarea.parentNode&&this.textarea.parentNode.removeChild(this.textarea);this.clearOnChange&&this.textarea.innerHTML==this.getEmptyLabelText()&&(this.textarea.innerHTML= +"",this.clearOnChange=!1);if(null!=a&&(this.textarea.innerHTML!=b||null!=this.align)){this.prepareTextarea();b=this.getCurrentValue(a);this.graph.getModel().beginUpdate();try{null!=b&&this.applyValue(a,b),null!=this.align&&this.graph.setCellStyles(mxConstants.STYLE_ALIGN,this.align,[a.cell])}finally{this.graph.getModel().endUpdate()}}mxEvent.release(this.textarea);this.align=this.textarea=null}}; +mxCellEditor.prototype.prepareTextarea=function(){null!=this.textarea.lastChild&&"BR"==this.textarea.lastChild.nodeName&&this.textarea.removeChild(this.textarea.lastChild)};mxCellEditor.prototype.isHideLabel=function(a){return!0};mxCellEditor.prototype.getMinimumSize=function(a){var b=this.graph.getView().scale;return new mxRectangle(0,0,null==a.text?30:a.text.size*b+20,"left"==this.textarea.style.textAlign?120:40)}; +mxCellEditor.prototype.getEditorBounds=function(a){var b=this.graph.getModel().isEdge(a.cell),c=this.graph.getView().scale,d=this.getMinimumSize(a),e=d.width;d=d.height;if(!b&&a.view.graph.cellRenderer.legacySpacing&&"fill"==a.style[mxConstants.STYLE_OVERFLOW])c=a.shape.getLabelBounds(mxRectangle.fromRectangle(a));else{var f=parseInt(a.style[mxConstants.STYLE_SPACING]||0)*c,g=(parseInt(a.style[mxConstants.STYLE_SPACING_TOP]||0)+mxText.prototype.baseSpacingTop)*c+f,k=(parseInt(a.style[mxConstants.STYLE_SPACING_RIGHT]|| +0)+mxText.prototype.baseSpacingRight)*c+f,l=(parseInt(a.style[mxConstants.STYLE_SPACING_BOTTOM]||0)+mxText.prototype.baseSpacingBottom)*c+f;f=(parseInt(a.style[mxConstants.STYLE_SPACING_LEFT]||0)+mxText.prototype.baseSpacingLeft)*c+f;c=new mxRectangle(a.x,a.y,Math.max(e,a.width-f-k),Math.max(d,a.height-g-l));k=mxUtils.getValue(a.style,mxConstants.STYLE_LABEL_POSITION,mxConstants.ALIGN_CENTER);l=mxUtils.getValue(a.style,mxConstants.STYLE_VERTICAL_LABEL_POSITION,mxConstants.ALIGN_MIDDLE);c=null!=a.shape&& +k==mxConstants.ALIGN_CENTER&&l==mxConstants.ALIGN_MIDDLE?a.shape.getLabelBounds(c):c;b?(c.x=a.absoluteOffset.x,c.y=a.absoluteOffset.y,null!=a.text&&null!=a.text.boundingBox&&(0=n.x:null!=c&&(k=(null!=m?m.x:c.x+c.width)<(null!=l?l.x:b.x))}if(null!=l)b=new mxCellState,b.x=l.x,b.y=l.y;else if(null!=b){var p=mxUtils.getPortConstraints(b,a,!0,mxConstants.DIRECTION_MASK_NONE);p!=mxConstants.DIRECTION_MASK_NONE&& +p!=mxConstants.DIRECTION_MASK_WEST+mxConstants.DIRECTION_MASK_EAST&&(k=p==mxConstants.DIRECTION_MASK_WEST)}else return;n=!0;null!=c&&(g=g.getCellGeometry(c.cell),g.relative?n=.5>=g.x:null!=b&&(n=(null!=l?l.x:b.x+b.width)<(null!=m?m.x:c.x)));null!=m?(c=new mxCellState,c.x=m.x,c.y=m.y):null!=c&&(p=mxUtils.getPortConstraints(c,a,!1,mxConstants.DIRECTION_MASK_NONE),p!=mxConstants.DIRECTION_MASK_NONE&&p!=mxConstants.DIRECTION_MASK_WEST+mxConstants.DIRECTION_MASK_EAST&&(n=p==mxConstants.DIRECTION_MASK_WEST)); +null!=b&&null!=c&&(a=k?b.x:b.x+b.width,b=f.getRoutingCenterY(b),l=n?c.x:c.x+c.width,c=f.getRoutingCenterY(c),f=new mxPoint(a+(k?-d:d),b),g=new mxPoint(l+(n?-d:d),c),k==n?(d=k?Math.min(a,l)-d:Math.max(a,l)+d,e.push(new mxPoint(d,b)),e.push(new mxPoint(d,c))):(f.xb.x+b.width?null!=c?(d=c.x,m=Math.max(Math.abs(l-c.y),m)):a==mxConstants.DIRECTION_NORTH?l=b.y-2*k:a==mxConstants.DIRECTION_SOUTH?l=b.y+b.height+2*k:d=a==mxConstants.DIRECTION_EAST?b.x-2*m:b.x+b.width+2*m:null!=c&&(d=f.getRoutingCenterX(b),k=Math.max(Math.abs(d-c.x),m),l=c.y,m=0);e.push(new mxPoint(d-k,l-m));e.push(new mxPoint(d+k,l+m))}},ElbowConnector:function(a,b,c,d,e){var f=null!=d&&0n;k=f.xm}else l=Math.max(b.x,c.x),m=Math.min(b.x+b.width,c.x+c.width),g=l==m,g||(k=Math.max(b.y,c.y),n=Math.min(b.y+b.height,c.y+c.height),k=k==n);k||!g&&a.style[mxConstants.STYLE_ELBOW]!=mxConstants.ELBOW_VERTICAL?mxEdgeStyle.SideToSide(a,b,c,d,e):mxEdgeStyle.TopToBottom(a,b,c,d,e)},SideToSide:function(a,b,c,d,e){var f=a.view;d=null!=d&&0=b.y&&d.y<=b.y+b.height&&(k=d.y),d.y>=c.y&&d.y<=c.y+c.height&&(f=d.y)),mxUtils.contains(c,a,k)||mxUtils.contains(b,a,k)||e.push(new mxPoint(a, +k)),mxUtils.contains(c,a,f)||mxUtils.contains(b,a,f)||e.push(new mxPoint(a,f)),1==e.length&&(null!=d?mxUtils.contains(c,a,d.y)||mxUtils.contains(b,a,d.y)||e.push(new mxPoint(a,d.y)):(f=Math.max(b.y,c.y),e.push(new mxPoint(a,f+(Math.min(b.y+b.height,c.y+c.height)-f)/2)))))},TopToBottom:function(a,b,c,d,e){var f=a.view;d=null!=d&&0=b.x&&d.x<=b.x+b.width&&(a=d.x),k=null!=d?d.y:Math.round(g+(k-g)/2),mxUtils.contains(c,a,k)||mxUtils.contains(b,a,k)||e.push(new mxPoint(a,k)),a=null!=d&&d.x>=c.x&&d.x<=c.x+c.width?d.x:f.getRoutingCenterX(c),mxUtils.contains(c,a,k)||mxUtils.contains(b,a,k)||e.push(new mxPoint(a,k)),1==e.length&&(null!=d&&1==e.length?mxUtils.contains(c,d.x,k)||mxUtils.contains(b,d.x,k)|| +e.push(new mxPoint(d.x,k)):(f=Math.max(b.x,c.x),e.push(new mxPoint(f+(Math.min(b.x+b.width,c.x+c.width)-f)/2,k)))))},SegmentConnector:function(a,b,c,d,e){var f=mxEdgeStyle.scalePointArray(a.absolutePoints,a.view.scale);b=mxEdgeStyle.scaleCellState(b,a.view.scale);var g=mxEdgeStyle.scaleCellState(c,a.view.scale);c=[];var k=0Math.abs(p[0].x-m.x)&&(p[0].x=m.x),1>Math.abs(p[0].y-m.y)&&(p[0].y=m.y));r=f[n];null!=r&&null!=p[p.length-1]&&(1>Math.abs(p[p.length-1].x-r.x)&&(p[p.length-1].x=r.x),1>Math.abs(p[p.length-1].y-r.y)&&(p[p.length-1].y=r.y));d=p[0];var t=b,u=f[0];var x=d;null!=u&&(t=null);for(q=0;2>q;q++){var y=null!=u&&u.x==x.x,C=null!=u&&u.y==x.y,A=null!=t&&x.y>=t.y&&x.y<=t.y+t.height, +B=null!=t&&x.x>=t.x&&x.x<=t.x+t.width;t=C||null==u&&A;x=y||null==u&&B;if(0!=q||!(t&&x||y&&C)){if(null!=u&&!C&&!y&&(A||B)){l=A?!1:!0;break}if(x||t){l=t;1==q&&(l=0==p.length%2?t:x);break}}t=g;u=f[n];null!=u&&(t=null);x=p[p.length-1];y&&C&&(p=p.slice(1))}l&&(null!=f[0]&&f[0].y!=d.y||null==f[0]&&null!=b&&(d.yb.y+b.height))?c.push(new mxPoint(m.x,d.y)):!l&&(null!=f[0]&&f[0].x!=d.x||null==f[0]&&null!=b&&(d.xb.x+b.width))&&c.push(new mxPoint(d.x,m.y));l?m.y=d.y:m.x=d.x;for(q=0;qg.y+g.height))?c.push(new mxPoint(m.x,d.y)):!l&&(null!=f[n]&&f[n].x!=d.x||null==f[n]&&null!=g&&(d.xg.x+g.width))&&c.push(new mxPoint(d.x,m.y)));if(null==f[0]&&null!=b)for(;0=Math.max(1,a.view.scale))e.push(f),k=f;null!=r&&null!=e[e.length-1]&&1>=Math.abs(r.x-e[e.length-1].x)&&1>=Math.abs(r.y-e[e.length-1].y)&&(e.splice(e.length-1,1),null!=e[e.length-1]&&(1>Math.abs(e[e.length-1].x-r.x)&& +(e[e.length-1].x=r.x),1>Math.abs(e[e.length-1].y-r.y)&&(e[e.length-1].y=r.y)))},orthBuffer:10,orthPointsFallback:!0,dirVectors:[[-1,0],[0,-1],[1,0],[0,1],[-1,0],[0,-1],[1,0]],wayPoints1:[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],routePatterns:[[[513,2308,2081,2562],[513,1090,514,2184,2114,2561],[513,1090,514,2564,2184,2562],[513,2308,2561,1090,514,2568,2308]],[[514,1057,513,2308,2081,2562],[514,2184,2114,2561],[514,2184,2562,1057,513,2564,2184],[514,1057,513,2568,2308, +2561]],[[1090,514,1057,513,2308,2081,2562],[2114,2561],[1090,2562,1057,513,2564,2184],[1090,514,1057,513,2308,2561,2568]],[[2081,2562],[1057,513,1090,514,2184,2114,2561],[1057,513,1090,514,2184,2562,2564],[1057,2561,1090,514,2568,2308]]],inlineRoutePatterns:[[null,[2114,2568],null,null],[null,[514,2081,2114,2568],null,null],[null,[2114,2561],null,null],[[2081,2562],[1057,2114,2568],[2184,2562],null]],vertexSeperations:[],limits:[[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]],LEFT_MASK:32,TOP_MASK:64,RIGHT_MASK:128, +BOTTOM_MASK:256,LEFT:1,TOP:2,RIGHT:4,BOTTOM:8,SIDE_MASK:480,CENTER_MASK:512,SOURCE_MASK:1024,TARGET_MASK:2048,VERTEX_MASK:3072,getJettySize:function(a,b){var c=mxUtils.getValue(a.style,b?mxConstants.STYLE_SOURCE_JETTY_SIZE:mxConstants.STYLE_TARGET_JETTY_SIZE,mxUtils.getValue(a.style,mxConstants.STYLE_JETTY_SIZE,mxEdgeStyle.orthBuffer));"auto"==c&&(mxUtils.getValue(a.style,b?mxConstants.STYLE_STARTARROW:mxConstants.STYLE_ENDARROW,mxConstants.NONE)!=mxConstants.NONE?(a=mxUtils.getNumber(a.style,b?mxConstants.STYLE_STARTSIZE: +mxConstants.STYLE_ENDSIZE,mxConstants.DEFAULT_MARKERSIZE),c=Math.max(2,Math.ceil((a+mxEdgeStyle.orthBuffer)/mxEdgeStyle.orthBuffer))*mxEdgeStyle.orthBuffer):c=2*mxEdgeStyle.orthBuffer);return c},scalePointArray:function(a,b){var c=[];if(null!=a)for(var d=0;dv;v++)mxEdgeStyle.limits[v][1]=q[v][0]-B[v],mxEdgeStyle.limits[v][2]=q[v][1]-B[v],mxEdgeStyle.limits[v][4]= +q[v][0]+q[v][2]+B[v],mxEdgeStyle.limits[v][8]=q[v][1]+q[v][3]+B[v];B=q[0][1]+q[0][3]/2;r=q[1][1]+q[1][3]/2;v=q[0][0]+q[0][2]/2-(q[1][0]+q[1][2]/2);D=B-r;B=0;0>v?B=0>D?2:1:0>=D&&(B=3,0==v&&(B=2));r=null;null!=l&&(r=n);l=[[.5,.5],[.5,.5]];for(v=0;2>v;v++)null!=r&&(l[v][0]=(r.x-q[v][0])/q[v][2],1>=Math.abs(r.x-q[v][0])?b[v]=mxConstants.DIRECTION_MASK_WEST:1>=Math.abs(r.x-q[v][0]-q[v][2])&&(b[v]=mxConstants.DIRECTION_MASK_EAST),l[v][1]=(r.y-q[v][1])/q[v][3],1>=Math.abs(r.y-q[v][1])?b[v]=mxConstants.DIRECTION_MASK_NORTH: +1>=Math.abs(r.y-q[v][1]-q[v][3])&&(b[v]=mxConstants.DIRECTION_MASK_SOUTH)),r=null,null!=m&&(r=p);v=q[0][1]-(q[1][1]+q[1][3]);p=q[0][0]-(q[1][0]+q[1][2]);r=q[1][1]-(q[0][1]+q[0][3]);t=q[1][0]-(q[0][0]+q[0][2]);mxEdgeStyle.vertexSeperations[1]=Math.max(p-z,0);mxEdgeStyle.vertexSeperations[2]=Math.max(v-z,0);mxEdgeStyle.vertexSeperations[4]=Math.max(r-z,0);mxEdgeStyle.vertexSeperations[3]=Math.max(t-z,0);z=[];m=[];n=[];m[0]=p>=t?mxConstants.DIRECTION_MASK_WEST:mxConstants.DIRECTION_MASK_EAST;n[0]=v>= +r?mxConstants.DIRECTION_MASK_NORTH:mxConstants.DIRECTION_MASK_SOUTH;m[1]=mxUtils.reversePortConstraints(m[0]);n[1]=mxUtils.reversePortConstraints(n[0]);p=p>=t?p:t;r=v>=r?v:r;t=[[0,0],[0,0]];u=!1;for(v=0;2>v;v++)0==b[v]&&(0==(m[v]&c[v])&&(m[v]=mxUtils.reversePortConstraints(m[v])),0==(n[v]&c[v])&&(n[v]=mxUtils.reversePortConstraints(n[v])),t[v][0]=n[v],t[v][1]=m[v]);0v;v++)0==b[v]&&(0==(t[v][0]&c[v])&&(t[v][0]=t[v][1]),z[v]=t[v][0]&c[v],z[v]|=(t[v][1]&c[v])<<8,z[v]|=(t[1-v][v]&c[v])<<16,z[v]|=(t[1-v][1-v]&c[v])<<24,0==(z[v]&15)&&(z[v]<<=8),0==(z[v]&3840)&&(z[v]=z[v]&15|z[v]>>8),0==(z[v]&983040)&&(z[v]=z[v]&65535|(z[v]&251658240)>>8),b[v]=z[v]&15,c[v]==mxConstants.DIRECTION_MASK_WEST|| +c[v]==mxConstants.DIRECTION_MASK_NORTH||c[v]==mxConstants.DIRECTION_MASK_EAST||c[v]==mxConstants.DIRECTION_MASK_SOUTH)&&(b[v]=c[v]);c=b[0]==mxConstants.DIRECTION_MASK_EAST?3:b[0];z=b[1]==mxConstants.DIRECTION_MASK_EAST?3:b[1];c-=B;z-=B;1>c&&(c+=4);1>z&&(z+=4);c=mxEdgeStyle.routePatterns[c-1][z-1];mxEdgeStyle.wayPoints1[0][0]=q[0][0];mxEdgeStyle.wayPoints1[0][1]=q[0][1];switch(b[0]){case mxConstants.DIRECTION_MASK_WEST:mxEdgeStyle.wayPoints1[0][0]-=f;mxEdgeStyle.wayPoints1[0][1]+=l[0][1]*q[0][3];break; +case mxConstants.DIRECTION_MASK_SOUTH:mxEdgeStyle.wayPoints1[0][0]+=l[0][0]*q[0][2];mxEdgeStyle.wayPoints1[0][1]+=q[0][3]+f;break;case mxConstants.DIRECTION_MASK_EAST:mxEdgeStyle.wayPoints1[0][0]+=q[0][2]+f;mxEdgeStyle.wayPoints1[0][1]+=l[0][1]*q[0][3];break;case mxConstants.DIRECTION_MASK_NORTH:mxEdgeStyle.wayPoints1[0][0]+=l[0][0]*q[0][2],mxEdgeStyle.wayPoints1[0][1]-=f}f=0;m=z=0<(b[0]&(mxConstants.DIRECTION_MASK_EAST|mxConstants.DIRECTION_MASK_WEST))?0:1;for(v=0;v>5,r<<=B,15>=4),t=0<(c[v]&mxEdgeStyle.CENTER_MASK),(y||x)&&9>r?(u=y?0:1,r=t&&0==n?q[u][0]+l[u][0]*q[u][2]:t?q[u][1]+l[u][1]*q[u][3]:mxEdgeStyle.limits[u][r],0==n?(r=(r-mxEdgeStyle.wayPoints1[f][0])* +p[0],0e&&(e+=4);1>a&&(a+=4);b=routePatterns[e-1][a-1];0!=c&&0!=d||null==inlineRoutePatterns[e-1][a-1]||(b=inlineRoutePatterns[e-1][a-1]);return b}},mxStyleRegistry={values:[],putValue:function(a, +b){mxStyleRegistry.values[a]=b},getValue:function(a){return mxStyleRegistry.values[a]},getName:function(a){for(var b in mxStyleRegistry.values)if(mxStyleRegistry.values[b]==a)return b;return null}};mxStyleRegistry.putValue(mxConstants.EDGESTYLE_ELBOW,mxEdgeStyle.ElbowConnector);mxStyleRegistry.putValue(mxConstants.EDGESTYLE_ENTITY_RELATION,mxEdgeStyle.EntityRelation);mxStyleRegistry.putValue(mxConstants.EDGESTYLE_LOOP,mxEdgeStyle.Loop);mxStyleRegistry.putValue(mxConstants.EDGESTYLE_SIDETOSIDE,mxEdgeStyle.SideToSide); +mxStyleRegistry.putValue(mxConstants.EDGESTYLE_TOPTOBOTTOM,mxEdgeStyle.TopToBottom);mxStyleRegistry.putValue(mxConstants.EDGESTYLE_ORTHOGONAL,mxEdgeStyle.OrthConnector);mxStyleRegistry.putValue(mxConstants.EDGESTYLE_SEGMENT,mxEdgeStyle.SegmentConnector);mxStyleRegistry.putValue(mxConstants.PERIMETER_ELLIPSE,mxPerimeter.EllipsePerimeter);mxStyleRegistry.putValue(mxConstants.PERIMETER_RECTANGLE,mxPerimeter.RectanglePerimeter);mxStyleRegistry.putValue(mxConstants.PERIMETER_RHOMBUS,mxPerimeter.RhombusPerimeter); +mxStyleRegistry.putValue(mxConstants.PERIMETER_TRIANGLE,mxPerimeter.TrianglePerimeter);mxStyleRegistry.putValue(mxConstants.PERIMETER_HEXAGON,mxPerimeter.HexagonPerimeter);function mxGraphView(a){this.graph=a;this.translate=new mxPoint;this.graphBounds=new mxRectangle;this.states=new mxDictionary}mxGraphView.prototype=new mxEventSource;mxGraphView.prototype.constructor=mxGraphView;mxGraphView.prototype.EMPTY_POINT=new mxPoint;mxGraphView.prototype.doneResource="none"!=mxClient.language?"done":""; +mxGraphView.prototype.updatingDocumentResource="none"!=mxClient.language?"updatingDocument":"";mxGraphView.prototype.allowEval=!1;mxGraphView.prototype.captureDocumentGesture=!0;mxGraphView.prototype.rendering=!0;mxGraphView.prototype.graph=null;mxGraphView.prototype.currentRoot=null;mxGraphView.prototype.graphBounds=null;mxGraphView.prototype.scale=1;mxGraphView.prototype.translate=null;mxGraphView.prototype.states=null;mxGraphView.prototype.updateStyle=!1;mxGraphView.prototype.lastNode=null; +mxGraphView.prototype.lastHtmlNode=null;mxGraphView.prototype.lastForegroundNode=null;mxGraphView.prototype.lastForegroundHtmlNode=null;mxGraphView.prototype.getGraphBounds=function(){return this.graphBounds};mxGraphView.prototype.setGraphBounds=function(a){this.graphBounds=a}; +mxGraphView.prototype.getBounds=function(a){var b=null;if(null!=a&&0 +b.length||null==b[0]||null==b[b.length-1])?this.clear(a.cell,!0):(this.updateEdgeBounds(a),this.updateEdgeLabelOffset(a)))}; +mxGraphView.prototype.updateVertexLabelOffset=function(a){var b=mxUtils.getValue(a.style,mxConstants.STYLE_LABEL_POSITION,mxConstants.ALIGN_CENTER);if(b==mxConstants.ALIGN_LEFT)b=mxUtils.getValue(a.style,mxConstants.STYLE_LABEL_WIDTH,null),b=null!=b?b*this.scale:a.width,a.absoluteOffset.x-=b;else if(b==mxConstants.ALIGN_RIGHT)a.absoluteOffset.x+=a.width;else if(b==mxConstants.ALIGN_CENTER&&(b=mxUtils.getValue(a.style,mxConstants.STYLE_LABEL_WIDTH,null),null!=b)){var c=mxUtils.getValue(a.style,mxConstants.STYLE_ALIGN, +mxConstants.ALIGN_CENTER),d=0;c==mxConstants.ALIGN_CENTER?d=.5:c==mxConstants.ALIGN_RIGHT&&(d=1);0!=d&&(a.absoluteOffset.x-=(b*this.scale-a.width)*d)}b=mxUtils.getValue(a.style,mxConstants.STYLE_VERTICAL_LABEL_POSITION,mxConstants.ALIGN_MIDDLE);b==mxConstants.ALIGN_TOP?a.absoluteOffset.y-=a.height:b==mxConstants.ALIGN_BOTTOM&&(a.absoluteOffset.y+=a.height)};mxGraphView.prototype.resetValidationState=function(){this.lastForegroundHtmlNode=this.lastForegroundNode=this.lastHtmlNode=this.lastNode=null}; +mxGraphView.prototype.stateValidated=function(a){var b=this.graph.getModel().isEdge(a.cell)&&this.graph.keepEdgesInForeground||this.graph.getModel().isVertex(a.cell)&&this.graph.keepEdgesInBackground;a=this.graph.cellRenderer.insertStateAfter(a,b?this.lastForegroundNode||this.lastNode:this.lastNode,b?this.lastForegroundHtmlNode||this.lastHtmlNode:this.lastHtmlNode);b?(this.lastForegroundHtmlNode=a[1],this.lastForegroundNode=a[0]):(this.lastHtmlNode=a[1],this.lastNode=a[0])}; +mxGraphView.prototype.updateFixedTerminalPoints=function(a,b,c){this.updateFixedTerminalPoint(a,b,!0,this.graph.getConnectionConstraint(a,b,!0));this.updateFixedTerminalPoint(a,c,!1,this.graph.getConnectionConstraint(a,c,!1))};mxGraphView.prototype.updateFixedTerminalPoint=function(a,b,c,d){a.setAbsoluteTerminalPoint(this.getFixedTerminalPoint(a,b,c,d),c)}; +mxGraphView.prototype.getFixedTerminalPoint=function(a,b,c,d){var e=null;null!=d&&(e=this.graph.getConnectionPoint(b,d,!1));if(null==e&&null==b){b=this.scale;d=this.translate;var f=a.origin;e=this.graph.getCellGeometry(a.cell).getTerminalPoint(c);null!=e&&(e=new mxPoint(b*(d.x+e.x+f.x),b*(d.y+e.y+f.y)))}return e}; +mxGraphView.prototype.updateBoundsFromStencil=function(a){var b=null;if(null!=a&&null!=a.shape&&null!=a.shape.stencil&&"fixed"==a.shape.stencil.aspect){b=mxRectangle.fromRectangle(a);var c=a.shape.stencil.computeAspect(a.style,a.x,a.y,a.width,a.height);a.setRect(c.x,c.y,a.shape.stencil.w0*c.width,a.shape.stencil.h0*c.height)}return b}; +mxGraphView.prototype.updatePoints=function(a,b,c,d){if(null!=a){var e=[];e.push(a.absolutePoints[0]);var f=this.getEdgeStyle(a,b,c,d);if(null!=f){c=this.getTerminalPort(a,c,!0);d=this.getTerminalPort(a,d,!1);var g=this.updateBoundsFromStencil(c),k=this.updateBoundsFromStencil(d);f(a,c,d,b,e);null!=g&&c.setRect(g.x,g.y,g.width,g.height);null!=k&&d.setRect(k.x,k.y,k.width,k.height)}else if(null!=b)for(f=0;fb.length)||mxUtils.getValue(a.style,mxConstants.STYLE_ORTHOGONAL_LOOP,!1)&&(null!=e&&null!=e.point||null!=f&&null!=f.point)?!1:null!=c&&c==d}; +mxGraphView.prototype.getEdgeStyle=function(a,b,c,d){a=this.isLoopStyleEnabled(a,b,c,d)?mxUtils.getValue(a.style,mxConstants.STYLE_LOOP,this.graph.defaultLoopStyle):mxUtils.getValue(a.style,mxConstants.STYLE_NOEDGESTYLE,!1)?null:a.style[mxConstants.STYLE_EDGE];"string"==typeof a&&(b=mxStyleRegistry.getValue(a),null==b&&this.isAllowEval()&&(b=mxUtils.eval(a)),a=b);return"function"==typeof a?a:null}; +mxGraphView.prototype.updateFloatingTerminalPoints=function(a,b,c){var d=a.absolutePoints,e=d[0];null==d[d.length-1]&&null!=c&&this.updateFloatingTerminalPoint(a,c,b,!1);null==e&&null!=b&&this.updateFloatingTerminalPoint(a,b,c,!0)};mxGraphView.prototype.updateFloatingTerminalPoint=function(a,b,c,d){a.setAbsoluteTerminalPoint(this.getFloatingTerminalPoint(a,b,c,d),d)}; +mxGraphView.prototype.getFloatingTerminalPoint=function(a,b,c,d){b=this.getTerminalPort(a,b,d);var e=this.getNextPoint(a,c,d),f=this.graph.isOrthogonal(a);c=mxUtils.toRadians(Number(b.style[mxConstants.STYLE_ROTATION]||"0"));var g=new mxPoint(b.getCenterX(),b.getCenterY());if(0!=c){var k=Math.cos(-c),l=Math.sin(-c);e=mxUtils.getRotatedPoint(e,k,l,g)}k=parseFloat(a.style[mxConstants.STYLE_PERIMETER_SPACING]||0);k+=parseFloat(a.style[d?mxConstants.STYLE_SOURCE_PERIMETER_SPACING:mxConstants.STYLE_TARGET_PERIMETER_SPACING]|| +0);a=this.getPerimeterPoint(b,e,0==c&&f,k);0!=c&&(k=Math.cos(c),l=Math.sin(c),a=mxUtils.getRotatedPoint(a,k,l,g));return a};mxGraphView.prototype.getTerminalPort=function(a,b,c){a=mxUtils.getValue(a.style,c?mxConstants.STYLE_SOURCE_PORT:mxConstants.STYLE_TARGET_PORT);null!=a&&(a=this.getState(this.graph.getModel().getCell(a)),null!=a&&(b=a));return b}; +mxGraphView.prototype.getPerimeterPoint=function(a,b,c,d){var e=null;if(null!=a){var f=this.getPerimeterFunction(a);if(null!=f&&null!=b&&(d=this.getPerimeterBounds(a,d),0=Math.round(k+g)&&l=f?0:f*f/(a*a+n*n));a>e&&(a=e);e=Math.sqrt(mxUtils.ptSegDistSq(g.x,g.y,k.x,k.y,b,c));-1==mxUtils.relativeCcw(g.x,g.y,k.x,k.y,b,c)&&(e=-e);return new mxPoint((d/2-m-a)/d*-2,e/this.scale)}}return new mxPoint}; +mxGraphView.prototype.updateEdgeLabelOffset=function(a){var b=a.absolutePoints;a.absoluteOffset.x=a.getCenterX();a.absoluteOffset.y=a.getCenterY();if(null!=b&&0c&&a.x>c+2&&a.x<=b)return!0;b=this.graph.container.offsetHeight;c=this.graph.container.clientHeight;return b>c&&a.y>c+2&&a.y<=b?!0:!1};mxGraphView.prototype.init=function(){this.installListeners();this.graph.dialect==mxConstants.DIALECT_SVG?this.createSvg():this.createHtml()}; +mxGraphView.prototype.installListeners=function(){var a=this.graph,b=a.container;null!=b&&(mxClient.IS_TOUCH&&(mxEvent.addListener(b,"gesturestart",mxUtils.bind(this,function(c){a.fireGestureEvent(c);mxEvent.consume(c)})),mxEvent.addListener(b,"gesturechange",mxUtils.bind(this,function(c){a.fireGestureEvent(c);mxEvent.consume(c)})),mxEvent.addListener(b,"gestureend",mxUtils.bind(this,function(c){a.fireGestureEvent(c);mxEvent.consume(c)}))),mxEvent.addGestureListeners(b,mxUtils.bind(this,function(c){!this.isContainerEvent(c)|| +(mxClient.IS_IE||mxClient.IS_IE11||mxClient.IS_GC||mxClient.IS_OP||mxClient.IS_SF)&&this.isScrollEvent(c)||a.fireMouseEvent(mxEvent.MOUSE_DOWN,new mxMouseEvent(c))}),mxUtils.bind(this,function(c){this.isContainerEvent(c)&&a.fireMouseEvent(mxEvent.MOUSE_MOVE,new mxMouseEvent(c))}),mxUtils.bind(this,function(c){this.isContainerEvent(c)&&a.fireMouseEvent(mxEvent.MOUSE_UP,new mxMouseEvent(c))})),mxEvent.addListener(b,"dblclick",mxUtils.bind(this,function(c){this.isContainerEvent(c)&&a.dblClick(c)})), +a.addMouseListener({mouseDown:function(c,d){a.popupMenuHandler.hideMenu()},mouseMove:function(){},mouseUp:function(){}}),this.moveHandler=mxUtils.bind(this,function(c){null!=a.tooltipHandler&&a.tooltipHandler.isHideOnHover()&&a.tooltipHandler.hide();if(this.captureDocumentGesture&&a.isMouseDown&&null!=a.container&&!this.isContainerEvent(c)&&"none"!=a.container.style.display&&"hidden"!=a.container.style.visibility&&!mxEvent.isConsumed(c)){var d=a.fireMouseEvent,e=mxEvent.MOUSE_MOVE,f=null;if(mxClient.IS_TOUCH){f= +mxEvent.getClientX(c);var g=mxEvent.getClientY(c);f=mxUtils.convertPoint(b,f,g);f=a.view.getState(a.getCellAt(f.x,f.y))}d.call(a,e,new mxMouseEvent(c,f))}}),this.endHandler=mxUtils.bind(this,function(c){this.captureDocumentGesture&&a.isMouseDown&&null!=a.container&&!this.isContainerEvent(c)&&"none"!=a.container.style.display&&"hidden"!=a.container.style.visibility&&a.fireMouseEvent(mxEvent.MOUSE_UP,new mxMouseEvent(c))}),mxEvent.addGestureListeners(document,null,this.moveHandler,this.endHandler))}; +mxGraphView.prototype.createHtml=function(){var a=this.graph.container;null!=a&&(this.canvas=this.createHtmlPane("100%","100%"),this.canvas.style.overflow="hidden",this.backgroundPane=this.createHtmlPane("1px","1px"),this.drawPane=this.createHtmlPane("1px","1px"),this.overlayPane=this.createHtmlPane("1px","1px"),this.decoratorPane=this.createHtmlPane("1px","1px"),this.canvas.appendChild(this.backgroundPane),this.canvas.appendChild(this.drawPane),this.canvas.appendChild(this.overlayPane),this.canvas.appendChild(this.decoratorPane), +a.appendChild(this.canvas),this.updateContainerStyle(a))};mxGraphView.prototype.updateHtmlCanvasSize=function(a,b){if(null!=this.graph.container){var c=this.graph.container.offsetHeight;this.canvas.style.width=this.graph.container.offsetWidth"+b+""),d&&b.addListener(mxEvent.CLICK,mxUtils.bind(this,function(e,f){this.isEnabled()&&this.setSelectionCell(a)})),this.addCellOverlay(a,b);this.removeCellOverlays(a);return null};mxGraph.prototype.startEditing=function(a){this.startEditingAtCell(null,a)}; +mxGraph.prototype.startEditingAtCell=function(a,b){null!=b&&mxEvent.isMultiTouchEvent(b)||(null==a&&(a=this.getSelectionCell(),null==a||this.isCellEditable(a)||(a=null)),null!=a&&(this.fireEvent(new mxEventObject(mxEvent.START_EDITING,"cell",a,"event",b)),this.cellEditor.startEditing(a,b),this.fireEvent(new mxEventObject(mxEvent.EDITING_STARTED,"cell",a,"event",b))))};mxGraph.prototype.getEditingValue=function(a,b){return this.convertValueToString(a)}; +mxGraph.prototype.stopEditing=function(a){this.cellEditor.stopEditing(a);this.fireEvent(new mxEventObject(mxEvent.EDITING_STOPPED,"cancel",a))};mxGraph.prototype.labelChanged=function(a,b,c){this.model.beginUpdate();try{var d=a.value;this.cellLabelChanged(a,b,this.isAutoSizeCell(a));this.fireEvent(new mxEventObject(mxEvent.LABEL_CHANGED,"cell",a,"value",b,"old",d,"event",c))}finally{this.model.endUpdate()}return a}; +mxGraph.prototype.cellLabelChanged=function(a,b,c){this.model.beginUpdate();try{this.model.setValue(a,b),c&&this.cellSizeUpdated(a,!1)}finally{this.model.endUpdate()}};mxGraph.prototype.escape=function(a){this.fireEvent(new mxEventObject(mxEvent.ESCAPE,"event",a))}; +mxGraph.prototype.click=function(a){var b=a.getEvent(),c=a.getCell(),d=new mxEventObject(mxEvent.CLICK,"event",b,"cell",c);a.isConsumed()&&d.consume();this.fireEvent(d);if(this.isEnabled()&&!mxEvent.isConsumed(b)&&!d.isConsumed()){if(null!=c){if(this.isTransparentClickEvent(b)){var e=!1;a=this.getCellAt(a.graphX,a.graphY,null,null,null,mxUtils.bind(this,function(g){var k=this.isCellSelected(g.cell);e=e||k;return!e||k||g.cell!=c&&this.model.isAncestor(g.cell,c)}));null!=a&&(c=a)}}else if(this.isSwimlaneSelectionEnabled()&& +(c=this.getSwimlaneAt(a.getGraphX(),a.getGraphY()),!(null==c||this.isToggleEvent(b)&&mxEvent.isAltDown(b)))){d=c;for(a=[];null!=d;){d=this.model.getParent(d);var f=this.view.getState(d);this.isSwimlane(d)&&null!=f&&a.push(d)}if(0=e.scrollLeft&&b>=e.scrollTop&&a<=e.scrollLeft+e.clientWidth&&b<=e.scrollTop+e.clientHeight){var f=e.scrollLeft+e.clientWidth- +a;if(fthis.minPageBreakDist)?Math.ceil(d.height/f.height)+1:0,k=a?Math.ceil(d.width/f.width)+1:0,l=(k-1)*f.width,m=(g-1)*f.height;null==this.horizontalPageBreaks&&0this.model.getChildCount(b)&&c--;this.model.add(b,a[l],c+l);this.autoSizeCellsOnAdd&&this.autoSizeCell(a[l],!0);(null==k||k)&&this.isExtendParentsOnAdd(a[l])&&this.isExtendParent(a[l])&&this.extendParent(a[l]);(null==g||g)&&this.constrainChild(a[l]);null!=d&&this.cellConnected(a[l],d,!0);null!=e&&this.cellConnected(a[l],e,!1)}this.fireEvent(new mxEventObject(mxEvent.CELLS_ADDED,"cells",a,"parent",b,"index",c,"source", +d,"target",e,"absolute",f))}finally{this.model.endUpdate()}}};mxGraph.prototype.autoSizeCell=function(a,b){if(null!=b?b:1){b=this.model.getChildCount(a);for(var c=0;c"),d=mxUtils.getSizeForString(g,f,e[mxConstants.STYLE_FONTFAMILY],b,e[mxConstants.STYLE_FONTSTYLE]),b=d.width+c,d=d.height+a,mxUtils.getValue(e,mxConstants.STYLE_HORIZONTAL,!0)||(e=d,d=b,b=e),this.gridEnabled&&(b=this.snap(b+this.gridSize/2),d=this.snap(d+this.gridSize/2)),c=new mxRectangle(0,0,b,d)):(e=4*this.gridSize,c=new mxRectangle(0,0,e,e))}}return c};mxGraph.prototype.resizeCell=function(a,b,c){return this.resizeCells([a],[b],c)[0]}; +mxGraph.prototype.resizeCells=function(a,b,c){c=null!=c?c:this.isRecursiveResize();this.model.beginUpdate();try{var d=this.cellsResized(a,b,c);this.fireEvent(new mxEventObject(mxEvent.RESIZE_CELLS,"cells",a,"bounds",b,"previous",d))}finally{this.model.endUpdate()}return a}; +mxGraph.prototype.cellsResized=function(a,b,c){c=null!=c?c:!1;var d=[];if(null!=a&&null!=b&&a.length==b.length){this.model.beginUpdate();try{for(var e=0;ed.width&&(e=b.width-d.width,b.width-=e);c.x+c.width>d.x+d.width&&(e-=c.x+c.width-d.x-d.width-e);f=0;b.height>d.height&&(f=b.height-d.height,b.height-=f);c.y+c.height> +d.y+d.height&&(f-=c.y+c.height-d.y-d.height-f);c.xg&&(n=0),b>f&&(p=0),this.view.setTranslate(Math.floor(n/2-k.x),Math.floor(p/2-k.y)),this.container.scrollLeft= +(a-g)/2,this.container.scrollTop=(b-f)/2):this.view.setTranslate(a?Math.floor(l.x-k.x/m+n*c/m):l.x,b?Math.floor(l.y-k.y/m+p*d/m):l.y)}; +mxGraph.prototype.zoom=function(a,b,c){b=null!=b?b:this.centerZoom;var d=Math.round(this.view.scale*a*100)/100;null!=c&&(d=Math.round(d*c)/c);c=this.view.getState(this.getSelectionCell());a=d/this.view.scale;if(this.keepSelectionVisibleOnZoom&&null!=c)a=new mxRectangle(c.x*a,c.y*a,c.width*a,c.height*a),this.view.scale=d,this.scrollRectToVisible(a)||(this.view.revalidate(),this.view.setScale(d));else if(c=mxUtils.hasScrollbars(this.container),b&&!c){c=this.container.offsetWidth;var e=this.container.offsetHeight; +1b?(b=a.height/b,c=(b-a.height)/2,a.height=b,a.y-=Math.min(a.y,c),d=Math.min(this.container.scrollHeight,a.y+a.height),a.height=d-a.y):(b*=a.width,c=(b-a.width)/2,a.width=b,a.x-=Math.min(a.x,c),c=Math.min(this.container.scrollWidth, +a.x+a.width),a.width=c-a.x);b=this.container.clientWidth/a.width;c=this.view.scale*b;mxUtils.hasScrollbars(this.container)?(this.view.setScale(c),this.container.scrollLeft=Math.round(a.x*b),this.container.scrollTop=Math.round(a.y*b)):this.view.scaleAndTranslate(c,this.view.translate.x-a.x/this.view.scale,this.view.translate.y-a.y/this.view.scale)}; +mxGraph.prototype.scrollCellToVisible=function(a,b){var c=-this.view.translate.x,d=-this.view.translate.y;a=this.view.getState(a);null!=a&&(c=new mxRectangle(c+a.x,d+a.y,a.width,a.height),b&&null!=this.container&&(b=this.container.clientWidth,d=this.container.clientHeight,c.x=c.getCenterX()-b/2,c.width=b,c.y=c.getCenterY()-d/2,c.height=d),b=new mxPoint(this.view.translate.x,this.view.translate.y),this.scrollRectToVisible(c)&&(c=new mxPoint(this.view.translate.x,this.view.translate.y),this.view.translate.x= +b.x,this.view.translate.y=b.y,this.view.setTranslate(c.x,c.y)))}; +mxGraph.prototype.scrollRectToVisible=function(a){var b=!1;if(null!=a){var c=this.container.offsetWidth,d=this.container.offsetHeight,e=Math.min(c,a.width),f=Math.min(d,a.height);if(mxUtils.hasScrollbars(this.container)){c=this.container;a.x+=this.view.translate.x;a.y+=this.view.translate.y;var g=c.scrollLeft-a.x;d=Math.max(g-c.scrollLeft,0);0g+c&&(this.view.translate.x-=(a.x+e-c-g)/l,b=!0);a.y+f>k+d&&(this.view.translate.y-=(a.y+f-d-k)/l,b=!0);a.x")):this.setCellWarning(f,null);c=c&&null==g}d="";this.isCellCollapsed(a)&&!c&&(d+=(mxResources.get(this.containsValidationErrorsResource)||this.containsValidationErrorsResource)+"\n");d=this.model.isEdge(a)?d+ +(this.getEdgeValidationError(a,this.model.getTerminal(a,!0),this.model.getTerminal(a,!1))||""):d+(this.getCellValidationError(a)||"");b=this.validateCell(a,b);null!=b&&(d+=b);null==this.model.getParent(a)&&this.view.validate();return 0f.max||bf.max||c")),null==e&&null!=a.overlays&&a.overlays.visit(function(f,g){null!=e||b!=g.node&&b.parentNode!=g.node||(e=g.overlay.toString())}),null==e&&(c=this.selectionCellsHandler.getHandler(a.cell),null!=c&&"function"==typeof c.getTooltipForNode&&(e=c.getTooltipForNode(b))),null== +e&&(e=this.getTooltipForCell(a.cell)));return e};mxGraph.prototype.getTooltipForCell=function(a){return null!=a&&null!=a.getTooltip?a.getTooltip():this.convertValueToString(a)};mxGraph.prototype.getLinkForCell=function(a){return null};mxGraph.prototype.getLinkTargetForCell=function(a){return null};mxGraph.prototype.getCursorForMouseEvent=function(a){return this.getCursorForCell(a.getCell())};mxGraph.prototype.getCursorForCell=function(a){return null}; +mxGraph.prototype.getStartSize=function(a,b){var c=new mxRectangle;a=this.getCurrentCellStyle(a,b);b=parseInt(mxUtils.getValue(a,mxConstants.STYLE_STARTSIZE,mxConstants.DEFAULT_STARTSIZE));mxUtils.getValue(a,mxConstants.STYLE_HORIZONTAL,!0)?c.height=b:c.width=b;return c}; +mxGraph.prototype.getSwimlaneDirection=function(a){var b=mxUtils.getValue(a,mxConstants.STYLE_DIRECTION,mxConstants.DIRECTION_EAST),c=1==mxUtils.getValue(a,mxConstants.STYLE_FLIPH,0),d=1==mxUtils.getValue(a,mxConstants.STYLE_FLIPV,0);a=mxUtils.getValue(a,mxConstants.STYLE_HORIZONTAL,!0)?0:3;b==mxConstants.DIRECTION_NORTH?a--:b==mxConstants.DIRECTION_WEST?a+=2:b==mxConstants.DIRECTION_SOUTH&&(a+=1);b=mxUtils.mod(a,2);c&&1==b&&(a+=2);d&&0==b&&(a+=2);return[mxConstants.DIRECTION_NORTH,mxConstants.DIRECTION_EAST, +mxConstants.DIRECTION_SOUTH,mxConstants.DIRECTION_WEST][mxUtils.mod(a,4)]};mxGraph.prototype.getActualStartSize=function(a,b){var c=new mxRectangle;this.isSwimlane(a,b)&&(b=this.getCurrentCellStyle(a,b),a=parseInt(mxUtils.getValue(b,mxConstants.STYLE_STARTSIZE,mxConstants.DEFAULT_STARTSIZE)),b=this.getSwimlaneDirection(b),b==mxConstants.DIRECTION_NORTH?c.y=a:b==mxConstants.DIRECTION_WEST?c.x=a:b==mxConstants.DIRECTION_SOUTH?c.height=a:c.width=a);return c}; +mxGraph.prototype.getImage=function(a){return null!=a&&null!=a.style?a.style[mxConstants.STYLE_IMAGE]:null};mxGraph.prototype.isTransparentState=function(a){var b=!1;if(null!=a){b=mxUtils.getValue(a.style,mxConstants.STYLE_STROKECOLOR,mxConstants.NONE);var c=mxUtils.getValue(a.style,mxConstants.STYLE_FILLCOLOR,mxConstants.NONE);b=b==mxConstants.NONE&&c==mxConstants.NONE&&null==this.getImage(a)}return b}; +mxGraph.prototype.getVerticalAlign=function(a){return null!=a&&null!=a.style?a.style[mxConstants.STYLE_VERTICAL_ALIGN]||mxConstants.ALIGN_MIDDLE:null};mxGraph.prototype.getIndicatorColor=function(a){return null!=a&&null!=a.style?a.style[mxConstants.STYLE_INDICATOR_COLOR]:null};mxGraph.prototype.getIndicatorGradientColor=function(a){return null!=a&&null!=a.style?a.style[mxConstants.STYLE_INDICATOR_GRADIENTCOLOR]:null}; +mxGraph.prototype.getIndicatorShape=function(a){return null!=a&&null!=a.style?a.style[mxConstants.STYLE_INDICATOR_SHAPE]:null};mxGraph.prototype.getIndicatorImage=function(a){return null!=a&&null!=a.style?a.style[mxConstants.STYLE_INDICATOR_IMAGE]:null};mxGraph.prototype.getBorder=function(){return this.border};mxGraph.prototype.setBorder=function(a){this.border=a}; +mxGraph.prototype.isSwimlane=function(a,b){return null==a||this.model.getParent(a)==this.model.getRoot()||this.model.isEdge(a)?!1:this.getCurrentCellStyle(a,b)[mxConstants.STYLE_SHAPE]==mxConstants.SHAPE_SWIMLANE};mxGraph.prototype.isResizeContainer=function(){return this.resizeContainer};mxGraph.prototype.setResizeContainer=function(a){this.resizeContainer=a};mxGraph.prototype.isEnabled=function(){return this.enabled}; +mxGraph.prototype.setEnabled=function(a){this.enabled=a;this.fireEvent(new mxEventObject("enabledChanged","enabled",a))};mxGraph.prototype.isEscapeEnabled=function(){return this.escapeEnabled};mxGraph.prototype.setEscapeEnabled=function(a){this.escapeEnabled=a};mxGraph.prototype.isInvokesStopCellEditing=function(){return this.invokesStopCellEditing};mxGraph.prototype.setInvokesStopCellEditing=function(a){this.invokesStopCellEditing=a};mxGraph.prototype.isEnterStopsCellEditing=function(){return this.enterStopsCellEditing}; +mxGraph.prototype.setEnterStopsCellEditing=function(a){this.enterStopsCellEditing=a};mxGraph.prototype.isCellLocked=function(a){var b=this.model.getGeometry(a);return this.isCellsLocked()||null!=b&&this.model.isVertex(a)&&b.relative};mxGraph.prototype.isCellsLocked=function(){return this.cellsLocked};mxGraph.prototype.setCellsLocked=function(a){this.cellsLocked=a};mxGraph.prototype.getCloneableCells=function(a){return this.model.filterCells(a,mxUtils.bind(this,function(b){return this.isCellCloneable(b)}))}; +mxGraph.prototype.isCellCloneable=function(a){a=this.getCurrentCellStyle(a);return this.isCellsCloneable()&&0!=a[mxConstants.STYLE_CLONEABLE]};mxGraph.prototype.isCellsCloneable=function(){return this.cellsCloneable};mxGraph.prototype.setCellsCloneable=function(a){this.cellsCloneable=a};mxGraph.prototype.getExportableCells=function(a){return this.model.filterCells(a,mxUtils.bind(this,function(b){return this.canExportCell(b)}))};mxGraph.prototype.canExportCell=function(a){return this.exportEnabled}; +mxGraph.prototype.getImportableCells=function(a){return this.model.filterCells(a,mxUtils.bind(this,function(b){return this.canImportCell(b)}))};mxGraph.prototype.canImportCell=function(a){return this.importEnabled};mxGraph.prototype.isCellSelectable=function(a){return this.isCellsSelectable()};mxGraph.prototype.isCellsSelectable=function(){return this.cellsSelectable};mxGraph.prototype.setCellsSelectable=function(a){this.cellsSelectable=a}; +mxGraph.prototype.getDeletableCells=function(a){return this.model.filterCells(a,mxUtils.bind(this,function(b){return this.isCellDeletable(b)}))};mxGraph.prototype.isCellDeletable=function(a){a=this.getCurrentCellStyle(a);return this.isCellsDeletable()&&0!=a[mxConstants.STYLE_DELETABLE]};mxGraph.prototype.isCellsDeletable=function(){return this.cellsDeletable};mxGraph.prototype.setCellsDeletable=function(a){this.cellsDeletable=a}; +mxGraph.prototype.isLabelMovable=function(a){return!this.isCellLocked(a)&&(this.model.isEdge(a)&&this.edgeLabelsMovable||this.model.isVertex(a)&&this.vertexLabelsMovable)};mxGraph.prototype.getRotatableCells=function(a){return this.model.filterCells(a,mxUtils.bind(this,function(b){return this.isCellRotatable(b)}))};mxGraph.prototype.isCellRotatable=function(a){return 0!=this.getCurrentCellStyle(a)[mxConstants.STYLE_ROTATABLE]}; +mxGraph.prototype.getMovableCells=function(a){return this.model.filterCells(a,mxUtils.bind(this,function(b){return this.isCellMovable(b)}))};mxGraph.prototype.isCellMovable=function(a){var b=this.getCurrentCellStyle(a);return this.isCellsMovable()&&!this.isCellLocked(a)&&0!=b[mxConstants.STYLE_MOVABLE]};mxGraph.prototype.isCellsMovable=function(){return this.cellsMovable};mxGraph.prototype.setCellsMovable=function(a){this.cellsMovable=a};mxGraph.prototype.isGridEnabled=function(){return this.gridEnabled}; +mxGraph.prototype.setGridEnabled=function(a){this.gridEnabled=a};mxGraph.prototype.isPortsEnabled=function(){return this.portsEnabled};mxGraph.prototype.setPortsEnabled=function(a){this.portsEnabled=a};mxGraph.prototype.getGridSize=function(){return this.gridSize};mxGraph.prototype.setGridSize=function(a){this.gridSize=a};mxGraph.prototype.getTolerance=function(){return this.tolerance};mxGraph.prototype.setTolerance=function(a){this.tolerance=a};mxGraph.prototype.isVertexLabelsMovable=function(){return this.vertexLabelsMovable}; +mxGraph.prototype.setVertexLabelsMovable=function(a){this.vertexLabelsMovable=a};mxGraph.prototype.isEdgeLabelsMovable=function(){return this.edgeLabelsMovable};mxGraph.prototype.setEdgeLabelsMovable=function(a){this.edgeLabelsMovable=a};mxGraph.prototype.isSwimlaneNesting=function(){return this.swimlaneNesting};mxGraph.prototype.setSwimlaneNesting=function(a){this.swimlaneNesting=a};mxGraph.prototype.isSwimlaneSelectionEnabled=function(){return this.swimlaneSelectionEnabled}; +mxGraph.prototype.setSwimlaneSelectionEnabled=function(a){this.swimlaneSelectionEnabled=a};mxGraph.prototype.isMultigraph=function(){return this.multigraph};mxGraph.prototype.setMultigraph=function(a){this.multigraph=a};mxGraph.prototype.isAllowLoops=function(){return this.allowLoops};mxGraph.prototype.setAllowDanglingEdges=function(a){this.allowDanglingEdges=a};mxGraph.prototype.isAllowDanglingEdges=function(){return this.allowDanglingEdges}; +mxGraph.prototype.setConnectableEdges=function(a){this.connectableEdges=a};mxGraph.prototype.isConnectableEdges=function(){return this.connectableEdges};mxGraph.prototype.setCloneInvalidEdges=function(a){this.cloneInvalidEdges=a};mxGraph.prototype.isCloneInvalidEdges=function(){return this.cloneInvalidEdges};mxGraph.prototype.setAllowLoops=function(a){this.allowLoops=a};mxGraph.prototype.isDisconnectOnMove=function(){return this.disconnectOnMove}; +mxGraph.prototype.setDisconnectOnMove=function(a){this.disconnectOnMove=a};mxGraph.prototype.isDropEnabled=function(){return this.dropEnabled};mxGraph.prototype.setDropEnabled=function(a){this.dropEnabled=a};mxGraph.prototype.isSplitEnabled=function(){return this.splitEnabled};mxGraph.prototype.setSplitEnabled=function(a){this.splitEnabled=a};mxGraph.prototype.getResizableCells=function(a){return this.model.filterCells(a,mxUtils.bind(this,function(b){return this.isCellResizable(b)}))}; +mxGraph.prototype.isCellResizable=function(a){var b=this.getCurrentCellStyle(a);return this.isCellsResizable()&&!this.isCellLocked(a)&&"0"!=mxUtils.getValue(b,mxConstants.STYLE_RESIZABLE,"1")};mxGraph.prototype.isCellsResizable=function(){return this.cellsResizable};mxGraph.prototype.setCellsResizable=function(a){this.cellsResizable=a};mxGraph.prototype.isTerminalPointMovable=function(a,b){return!0}; +mxGraph.prototype.isCellBendable=function(a){var b=this.getCurrentCellStyle(a);return this.isCellsBendable()&&!this.isCellLocked(a)&&0!=b[mxConstants.STYLE_BENDABLE]};mxGraph.prototype.isCellsBendable=function(){return this.cellsBendable};mxGraph.prototype.setCellsBendable=function(a){this.cellsBendable=a};mxGraph.prototype.getEditableCells=function(a){return this.model.filterCells(a,mxUtils.bind(this,function(b){return this.isCellEditable(b)}))}; +mxGraph.prototype.isCellEditable=function(a){var b=this.getCurrentCellStyle(a);return this.isCellsEditable()&&!this.isCellLocked(a)&&0!=b[mxConstants.STYLE_EDITABLE]};mxGraph.prototype.isCellsEditable=function(){return this.cellsEditable};mxGraph.prototype.setCellsEditable=function(a){this.cellsEditable=a};mxGraph.prototype.isCellDisconnectable=function(a,b,c){return this.isCellsDisconnectable()&&!this.isCellLocked(a)};mxGraph.prototype.isCellsDisconnectable=function(){return this.cellsDisconnectable}; +mxGraph.prototype.setCellsDisconnectable=function(a){this.cellsDisconnectable=a};mxGraph.prototype.isValidSource=function(a){return null==a&&this.allowDanglingEdges||null!=a&&(!this.model.isEdge(a)||this.connectableEdges)&&this.isCellConnectable(a)};mxGraph.prototype.isValidTarget=function(a){return this.isValidSource(a)};mxGraph.prototype.isValidConnection=function(a,b){return this.isValidSource(a)&&this.isValidTarget(b)};mxGraph.prototype.setConnectable=function(a){this.connectionHandler.setEnabled(a)}; +mxGraph.prototype.isConnectable=function(){return this.connectionHandler.isEnabled()};mxGraph.prototype.setTooltips=function(a){this.tooltipHandler.setEnabled(a)};mxGraph.prototype.setPanning=function(a){this.panningHandler.panningEnabled=a};mxGraph.prototype.isEditing=function(a){if(null!=this.cellEditor){var b=this.cellEditor.getEditingCell();return null==a?null!=b:a==b}return!1};mxGraph.prototype.isAutoSizeCell=function(a){a=this.getCurrentCellStyle(a);return this.isAutoSizeCells()||1==a[mxConstants.STYLE_AUTOSIZE]}; +mxGraph.prototype.isAutoSizeCells=function(){return this.autoSizeCells};mxGraph.prototype.setAutoSizeCells=function(a){this.autoSizeCells=a};mxGraph.prototype.isExtendParent=function(a){return!this.getModel().isEdge(a)&&this.isExtendParents()};mxGraph.prototype.isExtendParents=function(){return this.extendParents};mxGraph.prototype.setExtendParents=function(a){this.extendParents=a};mxGraph.prototype.isExtendParentsOnAdd=function(a){return this.extendParentsOnAdd}; +mxGraph.prototype.setExtendParentsOnAdd=function(a){this.extendParentsOnAdd=a};mxGraph.prototype.isExtendParentsOnMove=function(){return this.extendParentsOnMove};mxGraph.prototype.setExtendParentsOnMove=function(a){this.extendParentsOnMove=a};mxGraph.prototype.isRecursiveResize=function(a){return this.recursiveResize};mxGraph.prototype.setRecursiveResize=function(a){this.recursiveResize=a};mxGraph.prototype.isConstrainChild=function(a){return this.isConstrainChildren()&&!this.getModel().isEdge(this.getModel().getParent(a))}; +mxGraph.prototype.isConstrainChildren=function(){return this.constrainChildren};mxGraph.prototype.setConstrainChildren=function(a){this.constrainChildren=a};mxGraph.prototype.isConstrainRelativeChildren=function(){return this.constrainRelativeChildren};mxGraph.prototype.setConstrainRelativeChildren=function(a){this.constrainRelativeChildren=a};mxGraph.prototype.isAllowNegativeCoordinates=function(){return this.allowNegativeCoordinates}; +mxGraph.prototype.setAllowNegativeCoordinates=function(a){this.allowNegativeCoordinates=a};mxGraph.prototype.getOverlap=function(a){return this.isAllowOverlapParent(a)?this.defaultOverlap:0};mxGraph.prototype.isAllowOverlapParent=function(a){return!1};mxGraph.prototype.getFoldableCells=function(a,b){return this.model.filterCells(a,mxUtils.bind(this,function(c){return this.isCellFoldable(c,b)}))}; +mxGraph.prototype.isCellFoldable=function(a,b){b=this.getCurrentCellStyle(a);return 0mxUtils.indexOf(a,g);)g=this.model.getParent(g);return this.model.isLayer(c)||null!=g?null:c};mxGraph.prototype.getDefaultParent=function(){var a=this.getCurrentRoot();null==a&&(a=this.defaultParent,null==a&&(a=this.model.getRoot(),a=this.model.getChildAt(a,0)));return a};mxGraph.prototype.setDefaultParent=function(a){this.defaultParent=a};mxGraph.prototype.getSwimlane=function(a){for(;null!=a&&!this.isSwimlane(a);)a=this.model.getParent(a);return a}; +mxGraph.prototype.getSwimlaneAt=function(a,b,c){null==c&&(c=this.getCurrentRoot(),null==c&&(c=this.model.getRoot()));if(null!=c)for(var d=this.model.getChildCount(c),e=0;ea.width*e||0a.height*e)return!0}return!1};mxGraph.prototype.getChildVertices=function(a){return this.getChildCells(a,!0,!1)};mxGraph.prototype.getChildEdges=function(a){return this.getChildCells(a,!1,!0)}; +mxGraph.prototype.getChildCells=function(a,b,c){a=null!=a?a:this.getDefaultParent();a=this.model.getChildCells(a,null!=b?b:!1,null!=c?c:!1);b=[];for(c=0;c=a&&u.y+u.height<=p&&u.y>=b&&u.x+u.width<=n)&&f.push(t);x&&!l||this.getCells(a,b,c,d,t,f,g,k,l)}}}return f};mxGraph.prototype.getCellsBeyond=function(a,b,c,d,e){var f=[];if(d||e)if(null==c&&(c=this.getDefaultParent()),null!=c)for(var g=this.model.getChildCount(c),k=0;k=a)&&(!e||m.y>=b)&&f.push(l)}return f}; +mxGraph.prototype.findTreeRoots=function(a,b,c){b=null!=b?b:!1;c=null!=c?c:!1;var d=[];if(null!=a){for(var e=this.getModel(),f=e.getChildCount(a),g=null,k=0,l=0;lk&&(k=n,g=m)}}0==d.length&&null!=g&&d.push(g)}return d}; +mxGraph.prototype.traverse=function(a,b,c,d,e,f){if(null!=c&&null!=a&&(b=null!=b?b:!0,f=null!=f?f:!1,e=e||new mxDictionary,null==d||!e.get(d))&&(e.put(d,!0),d=c(a,d),null==d||d)&&(d=this.model.getEdgeCount(a),0b?f-1:b)),this.setSelectionCell(a)):this.getCurrentRoot()!=d&&this.setSelectionCell(d)};mxGraph.prototype.selectAll=function(a,b){a=a||this.getDefaultParent();b=b?this.model.filterDescendants(mxUtils.bind(this,function(c){return c!=a&&null!=this.view.getState(c)}),a):this.model.getChildren(a);null!=b&&this.setSelectionCells(b)};mxGraph.prototype.selectVertices=function(a,b){this.selectCells(!0,!1,a,b)}; +mxGraph.prototype.selectEdges=function(a){this.selectCells(!1,!0,a)};mxGraph.prototype.selectCells=function(a,b,c,d){c=c||this.getDefaultParent();var e=mxUtils.bind(this,function(f){return null!=this.view.getState(f)&&((d||0==this.model.getChildCount(f))&&this.model.isVertex(f)&&a&&!this.model.isEdge(this.model.getParent(f))||this.model.isEdge(f)&&b)});c=this.model.filterDescendants(e,c);null!=c&&this.setSelectionCells(c)}; +mxGraph.prototype.selectCellForEvent=function(a,b){var c=this.isCellSelected(a);this.isToggleEvent(b)?c?this.removeSelectionCell(a):this.addSelectionCell(a):c&&1==this.getSelectionCount()||this.setSelectionCell(a)};mxGraph.prototype.selectCellsForEvent=function(a,b){this.isToggleEvent(b)?this.addSelectionCells(a):this.setSelectionCells(a)}; +mxGraph.prototype.createHandler=function(a){var b=null;if(null!=a)if(this.model.isEdge(a.cell)){b=a.getVisibleTerminalState(!0);var c=a.getVisibleTerminalState(!1),d=this.getCellGeometry(a.cell);b=this.view.getEdgeStyle(a,null!=d?d.points:null,b,c);b=this.createEdgeHandler(a,b)}else b=this.createVertexHandler(a);return b};mxGraph.prototype.createVertexHandler=function(a){return new mxVertexHandler(a)}; +mxGraph.prototype.createEdgeHandler=function(a,b){return b==mxEdgeStyle.Loop||b==mxEdgeStyle.ElbowConnector||b==mxEdgeStyle.SideToSide||b==mxEdgeStyle.TopToBottom?this.createElbowEdgeHandler(a):b==mxEdgeStyle.SegmentConnector||b==mxEdgeStyle.OrthConnector?this.createEdgeSegmentHandler(a):new mxEdgeHandler(a)};mxGraph.prototype.createEdgeSegmentHandler=function(a){return new mxEdgeSegmentHandler(a)};mxGraph.prototype.createElbowEdgeHandler=function(a){return new mxElbowEdgeHandler(a)}; +mxGraph.prototype.addMouseListener=function(a){null==this.mouseListeners&&(this.mouseListeners=[]);this.mouseListeners.push(a)};mxGraph.prototype.removeMouseListener=function(a){if(null!=this.mouseListeners)for(var b=0;bthis.doubleClickCounter){if(this.doubleClickCounter++,d=!1,a==mxEvent.MOUSE_UP?b.getCell()==this.lastTouchCell&&null!=this.lastTouchCell&&(this.lastTouchTime=0,d=this.lastTouchCell,this.lastTouchCell=null,this.dblClick(b.getEvent(),d),d=!0):(this.fireDoubleClick=!0,this.lastTouchTime=0),d){mxEvent.consume(b.getEvent()); +return}}else{if(null==this.lastTouchEvent||this.lastTouchEvent!=b.getEvent())this.lastTouchCell=b.getCell(),this.lastTouchX=b.getX(),this.lastTouchY=b.getY(),this.lastTouchTime=d,this.lastTouchEvent=b.getEvent(),this.doubleClickCounter=0}else if((this.isMouseDown||a==mxEvent.MOUSE_UP)&&this.fireDoubleClick){this.fireDoubleClick=!1;d=this.lastTouchCell;this.lastTouchCell=null;this.isMouseDown=!1;(null!=d||(mxEvent.isTouchEvent(b.getEvent())||mxEvent.isPenEvent(b.getEvent()))&&(mxClient.IS_GC||mxClient.IS_SF))&& +Math.abs(this.lastTouchX-b.getX())=this.max)||!this.source&&(0==this.max||f>=this.max))&&(g+=this.countError+"\n"),null!=this.validNeighbors&&null!=this.typeError&&0this.graph.model.getChildCount(e),g=new mxDictionary;a=this.graph.getOpposites(this.graph.getEdges(this.cell),this.cell);for(b=0;b=this.cellCount&&!this.livePreviewActive&&this.allowLivePreview?this.cloning&&this.livePreviewActive||(this.livePreviewUsed=this.livePreviewActive=!0):this.livePreviewUsed||null!=this.shape||(this.shape=this.createPreviewShape(this.bounds))}; +mxGraphHandler.prototype.mouseMove=function(a,b){a=this.graph;if(b.isConsumed()||!a.isMouseDown||null==this.cell||null==this.first||null==this.bounds||this.suspended)!this.isMoveEnabled()&&!this.isCloneEnabled()||!this.updateCursor||b.isConsumed()||null==b.getState()&&null==b.sourceState||a.isMouseDown||(c=a.getCursorForMouseEvent(b),null==c&&a.isEnabled()&&a.isCellMovable(b.getCell())&&(c=a.getModel().isEdge(b.getCell())?mxConstants.CURSOR_MOVABLE_EDGE:mxConstants.CURSOR_MOVABLE_VERTEX),null!=c&& +null!=b.sourceState&&b.sourceState.setCursor(c));else if(mxEvent.isMultiTouchEvent(b.getEvent()))this.reset();else{var c=this.getDelta(b),d=a.tolerance;if(null!=this.shape||this.livePreviewActive||Math.abs(c.x)>d||Math.abs(c.y)>d){null==this.highlight&&(this.highlight=new mxCellHighlight(this.graph,mxConstants.DROP_TARGET_COLOR,3));d=a.isCloneEvent(b.getEvent())&&a.isCellsCloneable()&&this.isCloneEnabled();var e=a.isGridEnabledEvent(b.getEvent()),f=b.getCell();f=null!=f&&0>mxUtils.indexOf(this.cells, +f)?f:a.getCellAt(b.getGraphX(),b.getGraphY(),null,null,null,mxUtils.bind(this,function(n,p,q){return 0<=mxUtils.indexOf(this.cells,n.cell)}));var g=!0,k=null;this.cloning=d;a.isDropEnabled()&&this.highlightEnabled&&(k=a.getDropTarget(this.cells,b.getEvent(),f,d));var l=a.getView().getState(k),m=!1;null!=l&&(d||this.isValidDropTarget(k,b))?(this.target!=k&&(this.target=k,this.setHighlightColor(mxConstants.DROP_TARGET_COLOR)),m=!0):(this.target=null,this.connectOnDrop&&null!=f&&1==this.cells.length&& +a.getModel().isVertex(f)&&a.isCellConnectable(f)&&(l=a.getView().getState(f),null!=l&&(a=null==a.getEdgeValidationError(null,this.cell,f)?mxConstants.VALID_COLOR:mxConstants.INVALID_CONNECT_TARGET_COLOR,this.setHighlightColor(a),m=!0)));null!=l&&m?this.highlight.highlight(l):this.highlight.hide();null!=this.guide&&this.useGuidesForEvent(b)?(c=this.guide.move(this.bounds,c,e,d),g=!1):c=this.graph.snapDelta(c,this.bounds,!e,!1,!1);null!=this.guide&&g&&this.guide.hide();this.isConstrainedEvent(b)&&(Math.abs(c.x)> +Math.abs(c.y)?c.y=0:c.x=0);this.checkPreview();if(this.currentDx!=c.x||this.currentDy!=c.y)this.currentDx=c.x,this.currentDy=c.y,this.updatePreview()}this.updateHint(b);this.consumeMouseEvent(mxEvent.MOUSE_MOVE,b);mxEvent.consume(b.getEvent())}};mxGraphHandler.prototype.isConstrainedEvent=function(a){return(null==this.target||this.graph.isCloneEvent(a.getEvent()))&&this.graph.isConstrainedEvent(a.getEvent())}; +mxGraphHandler.prototype.updatePreview=function(a){this.livePreviewUsed&&!a?null!=this.cells&&(this.setHandlesVisibleForCells(this.graph.selectionCellsHandler.getHandledSelectionCells(),!1),this.updateLivePreview(this.currentDx,this.currentDy)):this.updatePreviewShape()}; +mxGraphHandler.prototype.updatePreviewShape=function(){null!=this.shape&&null!=this.pBounds&&(this.shape.bounds=new mxRectangle(Math.round(this.pBounds.x+this.currentDx),Math.round(this.pBounds.y+this.currentDy),this.pBounds.width,this.pBounds.height),this.shape.redraw())}; +mxGraphHandler.prototype.updateLivePreview=function(a,b){if(!this.suspended){var c=[];null!=this.allCells&&this.allCells.visit(mxUtils.bind(this,function(n,p){n=this.graph.view.getState(p.cell);n!=p&&(p.destroy(),null!=n?this.allCells.put(p.cell,n):this.allCells.remove(p.cell),p=n);null!=p&&(n=p.clone(),c.push([p,n]),null!=p.shape&&(null==p.shape.originalPointerEvents&&(p.shape.originalPointerEvents=p.shape.pointerEvents),p.shape.pointerEvents=!1,null!=p.text&&(null==p.text.originalPointerEvents&& +(p.text.originalPointerEvents=p.text.pointerEvents),p.text.pointerEvents=!1)),this.graph.model.isVertex(p.cell))&&((p.x+=a,p.y+=b,this.cloning)?null!=p.text&&(p.text.updateBoundingBox(),null!=p.text.boundingBox&&(p.text.boundingBox.x+=a,p.text.boundingBox.y+=b),null!=p.text.unrotatedBoundingBox&&(p.text.unrotatedBoundingBox.x+=a,p.text.unrotatedBoundingBox.y+=b)):(p.view.graph.cellRenderer.redraw(p,!0),p.view.invalidate(p.cell),p.invalid=!1,null!=p.control&&null!=p.control.node&&(p.control.node.style.visibility= +"hidden")))}));if(0==c.length)this.reset();else{for(var d=this.graph.view.scale,e=0;ethis.graph.tolerance||Math.abs(this.dy)>this.graph.tolerance,!a&&this.active&&this.fireEvent(new mxEventObject(mxEvent.PAN_START, +"event",b)));(this.active||this.panningTrigger)&&b.consume()};mxPanningHandler.prototype.mouseUp=function(a,b){if(this.active){if(null!=this.dx&&null!=this.dy){if(!this.graph.useScrollbarsForPanning||!mxUtils.hasScrollbars(this.graph.container)){a=this.graph.getView().scale;var c=this.graph.getView().translate;this.graph.panGraph(0,0);this.panGraph(c.x+this.dx/a,c.y+this.dy/a)}b.consume()}this.fireEvent(new mxEventObject(mxEvent.PAN_END,"event",b))}this.reset()}; +mxPanningHandler.prototype.zoomGraph=function(a){var b=Math.round(this.initialScale*a.scale*100)/100;null!=this.minScale&&(b=Math.max(this.minScale,b));null!=this.maxScale&&(b=Math.min(this.maxScale,b));this.graph.view.scale!=b&&(this.graph.zoomTo(b),mxEvent.consume(a))};mxPanningHandler.prototype.reset=function(){this.panningTrigger=this.graph.isMouseDown=!1;this.mouseDownEvent=null;this.active=!1;this.dy=this.dx=null}; +mxPanningHandler.prototype.panGraph=function(a,b){this.graph.getView().setTranslate(a,b)};mxPanningHandler.prototype.destroy=function(){this.graph.removeMouseListener(this);this.graph.removeListener(this.forcePanningHandler);this.graph.removeListener(this.gestureHandler);mxEvent.removeGestureListeners(document,null,null,this.mouseUpListener);mxEvent.removeListener(document,"mouseleave",this.mouseUpListener)}; +function mxPopupMenuHandler(a,b){null!=a&&(this.graph=a,this.factoryMethod=b,this.graph.addMouseListener(this),this.gestureHandler=mxUtils.bind(this,function(c,d){this.inTolerance=!1}),this.graph.addListener(mxEvent.GESTURE,this.gestureHandler),this.init())}mxPopupMenuHandler.prototype=new mxPopupMenu;mxPopupMenuHandler.prototype.constructor=mxPopupMenuHandler;mxPopupMenuHandler.prototype.graph=null;mxPopupMenuHandler.prototype.selectOnPopup=!0; +mxPopupMenuHandler.prototype.clearSelectionOnBackground=!0;mxPopupMenuHandler.prototype.triggerX=null;mxPopupMenuHandler.prototype.triggerY=null;mxPopupMenuHandler.prototype.screenX=null;mxPopupMenuHandler.prototype.screenY=null;mxPopupMenuHandler.prototype.init=function(){mxPopupMenu.prototype.init.apply(this);mxEvent.addGestureListeners(this.div,mxUtils.bind(this,function(a){this.graph.tooltipHandler.hide()}))};mxPopupMenuHandler.prototype.isSelectOnPopup=function(a){return this.selectOnPopup}; +mxPopupMenuHandler.prototype.mouseDown=function(a,b){this.isEnabled()&&!mxEvent.isMultiTouchEvent(b.getEvent())&&(this.hideMenu(),this.triggerX=b.getGraphX(),this.triggerY=b.getGraphY(),this.screenX=mxEvent.getMainEvent(b.getEvent()).screenX,this.screenY=mxEvent.getMainEvent(b.getEvent()).screenY,this.popupTrigger=this.isPopupTrigger(b),this.inTolerance=!0)}; +mxPopupMenuHandler.prototype.mouseMove=function(a,b){this.inTolerance&&null!=this.screenX&&null!=this.screenY&&(Math.abs(mxEvent.getMainEvent(b.getEvent()).screenX-this.screenX)>this.graph.tolerance||Math.abs(mxEvent.getMainEvent(b.getEvent()).screenY-this.screenY)>this.graph.tolerance)&&(this.inTolerance=!1)}; +mxPopupMenuHandler.prototype.mouseUp=function(a,b,c){a=null==c;c=null!=c?c:mxUtils.bind(this,function(e){var f=mxUtils.getScrollOrigin();this.popup(b.getX()+f.x+1,b.getY()+f.y+1,e,b.getEvent())});if(this.popupTrigger&&this.inTolerance&&null!=this.triggerX&&null!=this.triggerY){var d=this.getCellForPopupEvent(b);this.graph.isEnabled()&&this.isSelectOnPopup(b)&&null!=d&&!this.graph.isCellSelected(d)?this.graph.setSelectionCell(d):this.clearSelectionOnBackground&&null==d&&this.graph.clearSelection(); +this.graph.tooltipHandler.hide();c(d);a&&b.consume()}this.inTolerance=this.popupTrigger=!1};mxPopupMenuHandler.prototype.getCellForPopupEvent=function(a){return a.getCell()};mxPopupMenuHandler.prototype.destroy=function(){this.graph.removeMouseListener(this);this.graph.removeListener(this.gestureHandler);mxPopupMenu.prototype.destroy.apply(this)}; +function mxCellMarker(a,b,c,d){mxEventSource.call(this);null!=a&&(this.graph=a,this.validColor=null!=b?b:mxConstants.DEFAULT_VALID_COLOR,this.invalidColor=null!=c?c:mxConstants.DEFAULT_INVALID_COLOR,this.hotspot=null!=d?d:mxConstants.DEFAULT_HOTSPOT,this.highlight=new mxCellHighlight(a))}mxUtils.extend(mxCellMarker,mxEventSource);mxCellMarker.prototype.graph=null;mxCellMarker.prototype.enabled=!0;mxCellMarker.prototype.hotspot=mxConstants.DEFAULT_HOTSPOT;mxCellMarker.prototype.hotspotEnabled=!1; +mxCellMarker.prototype.validColor=null;mxCellMarker.prototype.invalidColor=null;mxCellMarker.prototype.currentColor=null;mxCellMarker.prototype.validState=null;mxCellMarker.prototype.markedState=null;mxCellMarker.prototype.setEnabled=function(a){this.enabled=a};mxCellMarker.prototype.isEnabled=function(){return this.enabled};mxCellMarker.prototype.setHotspot=function(a){this.hotspot=a};mxCellMarker.prototype.getHotspot=function(){return this.hotspot}; +mxCellMarker.prototype.setHotspotEnabled=function(a){this.hotspotEnabled=a};mxCellMarker.prototype.isHotspotEnabled=function(){return this.hotspotEnabled};mxCellMarker.prototype.hasValidState=function(){return null!=this.validState};mxCellMarker.prototype.getValidState=function(){return this.validState};mxCellMarker.prototype.getMarkedState=function(){return this.markedState};mxCellMarker.prototype.reset=function(){this.validState=null;null!=this.markedState&&(this.markedState=null,this.unmark())}; +mxCellMarker.prototype.process=function(a){var b=null;this.isEnabled()&&(b=this.getState(a),this.setCurrentState(b,a));return b};mxCellMarker.prototype.setCurrentState=function(a,b,c){var d=null!=a?this.isValidState(a):!1;c=null!=c?c:this.getMarkerColor(b.getEvent(),a,d);this.validState=d?a:null;if(a!=this.markedState||c!=this.currentColor)this.currentColor=c,null!=a&&null!=this.currentColor?(this.markedState=a,this.mark()):null!=this.markedState&&(this.markedState=null,this.unmark())}; +mxCellMarker.prototype.markCell=function(a,b){a=this.graph.getView().getState(a);null!=a&&(this.currentColor=null!=b?b:this.validColor,this.markedState=a,this.mark())};mxCellMarker.prototype.mark=function(){this.highlight.setHighlightColor(this.currentColor);this.highlight.highlight(this.markedState);this.fireEvent(new mxEventObject(mxEvent.MARK,"state",this.markedState))};mxCellMarker.prototype.unmark=function(){this.mark()};mxCellMarker.prototype.isValidState=function(a){return!0}; +mxCellMarker.prototype.getMarkerColor=function(a,b,c){return c?this.validColor:this.invalidColor};mxCellMarker.prototype.getState=function(a){var b=this.graph.getView(),c=this.getCell(a);b=this.getStateToMark(b.getState(c));return null!=b&&this.intersects(b,a)?b:null};mxCellMarker.prototype.getCell=function(a){return a.getCell()};mxCellMarker.prototype.getStateToMark=function(a){return a}; +mxCellMarker.prototype.intersects=function(a,b){return this.hotspotEnabled?mxUtils.intersectsHotspot(a,b.getGraphX(),b.getGraphY(),this.hotspot,mxConstants.MIN_HOTSPOT_SIZE,mxConstants.MAX_HOTSPOT_SIZE):!0};mxCellMarker.prototype.destroy=function(){this.graph.getView().removeListener(this.resetHandler);this.graph.getModel().removeListener(this.resetHandler);this.highlight.destroy()}; +function mxSelectionCellsHandler(a){mxEventSource.call(this);this.graph=a;this.handlers=new mxDictionary;this.graph.addMouseListener(this);this.refreshHandler=mxUtils.bind(this,function(b,c){this.isEnabled()&&this.refresh()});this.graph.getSelectionModel().addListener(mxEvent.CHANGE,this.refreshHandler);this.graph.getModel().addListener(mxEvent.CHANGE,this.refreshHandler);this.graph.getView().addListener(mxEvent.SCALE,this.refreshHandler);this.graph.getView().addListener(mxEvent.TRANSLATE,this.refreshHandler); +this.graph.getView().addListener(mxEvent.SCALE_AND_TRANSLATE,this.refreshHandler);this.graph.getView().addListener(mxEvent.DOWN,this.refreshHandler);this.graph.getView().addListener(mxEvent.UP,this.refreshHandler)}mxUtils.extend(mxSelectionCellsHandler,mxEventSource);mxSelectionCellsHandler.prototype.graph=null;mxSelectionCellsHandler.prototype.enabled=!0;mxSelectionCellsHandler.prototype.refreshHandler=null;mxSelectionCellsHandler.prototype.maxHandlers=100; +mxSelectionCellsHandler.prototype.handlers=null;mxSelectionCellsHandler.prototype.isEnabled=function(){return this.enabled};mxSelectionCellsHandler.prototype.setEnabled=function(a){this.enabled=a};mxSelectionCellsHandler.prototype.getHandler=function(a){return this.handlers.get(a)};mxSelectionCellsHandler.prototype.isHandled=function(a){return null!=this.getHandler(a)};mxSelectionCellsHandler.prototype.reset=function(){this.handlers.visit(function(a,b){b.reset.apply(b)})}; +mxSelectionCellsHandler.prototype.getHandledSelectionCells=function(){return this.graph.getSelectionCells()}; +mxSelectionCellsHandler.prototype.refresh=function(){var a=this.handlers;this.handlers=new mxDictionary;for(var b=mxUtils.sortCells(this.getHandledSelectionCells(),!1),c=0;cthis.graph.tolerance||Math.abs(b.getGraphY()-this.first.y)>this.graph.tolerance)&&this.updateCurrentState(b,a);if(null!=this.first){var e=null;c=a;null!=this.constraintHandler.currentConstraint&&null!=this.constraintHandler.currentFocus&&null!=this.constraintHandler.currentPoint?(e=this.constraintHandler.currentConstraint, +c=this.constraintHandler.currentPoint.clone()):null!=this.previous&&mxEvent.isShiftDown(b.getEvent())&&!this.graph.isIgnoreTerminalEvent(b.getEvent())&&(Math.abs(this.previous.getCenterX()-a.x)this.graph.tolerance||f>this.graph.tolerance)&&(this.shape=this.createShape(),null!=this.edgeState&&this.shape.apply(this.edgeState),this.updateCurrentState(b,a));null!=this.shape&&(null!=this.edgeState?this.shape.points=this.edgeState.absolutePoints:(a=[d],null!=this.waypoints&&(a=a.concat(this.waypoints)),a.push(c),this.shape.points=a),this.drawPreview()); +null!=this.cursor&&(this.graph.container.style.cursor=this.cursor);mxEvent.consume(b.getEvent());b.consume()}else this.isEnabled()&&this.graph.isEnabled()?this.previous!=this.currentState&&null==this.edgeState?(this.destroyIcons(),null!=this.currentState&&null==this.error&&null==this.constraintHandler.currentConstraint&&(this.icons=this.createIcons(this.currentState),null==this.icons&&(this.currentState.setCursor(mxConstants.CURSOR_CONNECT),b.consume())),this.previous=this.currentState):this.previous!= +this.currentState||null==this.currentState||null!=this.icons||this.graph.isMouseDown||b.consume():this.constraintHandler.reset();if(!this.graph.isMouseDown&&null!=this.currentState&&null!=this.icons){a=!1;c=b.getSource();for(d=0;dthis.graph.tolerance||b>this.graph.tolerance))null==this.waypoints&&(this.waypoints=[]),c=this.graph.view.scale,b=new mxPoint(this.graph.snap(a.getGraphX()/c)*c,this.graph.snap(a.getGraphY()/c)*c),this.waypoints.push(b)}; +mxConnectionHandler.prototype.checkConstraints=function(a,b){return null==a||null==b||null==a.point||null==b.point||!a.point.equals(b.point)||a.dx!=b.dx||a.dy!=b.dy||a.perimeter!=b.perimeter}; +mxConnectionHandler.prototype.mouseUp=function(a,b){if(!b.isConsumed()&&this.isConnecting()){if(this.waypointsEnabled&&!this.isStopEvent(b)){this.addWaypointForEvent(b);b.consume();return}a=this.sourceConstraint;var c=this.constraintHandler.currentConstraint,d=null!=this.previous?this.previous.cell:null,e=null;null!=this.constraintHandler.currentConstraint&&null!=this.constraintHandler.currentFocus&&(e=this.constraintHandler.currentFocus.cell);null==e&&null!=this.currentState&&(e=this.currentState.cell); +null!=this.error||null!=d&&null!=e&&d==e&&!this.checkConstraints(a,c)?(null!=this.previous&&null!=this.marker.validState&&this.previous.cell==this.marker.validState.cell&&this.graph.selectCellForEvent(this.marker.source,b.getEvent()),null!=this.error&&0f||Math.abs(e)>f)null==this.div&&(this.div=this.createShape()),mxUtils.clearSelection(),this.update(a,c),b.consume()}}; +mxRubberband.prototype.createShape=function(){null==this.sharedDiv&&(this.sharedDiv=document.createElement("div"),this.sharedDiv.className="mxRubberband",mxUtils.setOpacity(this.sharedDiv,this.defaultOpacity));this.graph.container.appendChild(this.sharedDiv);var a=this.sharedDiv;mxClient.IS_SVG&&(!mxClient.IS_IE||10<=document.documentMode)&&this.fadeOut&&(this.sharedDiv=null);return a};mxRubberband.prototype.isActive=function(a,b){return null!=this.div&&"none"!=this.div.style.display}; +mxRubberband.prototype.mouseUp=function(a,b){a=this.isActive();this.reset();a&&(this.execute(b.getEvent()),b.consume())};mxRubberband.prototype.execute=function(a){var b=new mxRectangle(this.x,this.y,this.width,this.height);this.graph.selectRegion(b,a)}; +mxRubberband.prototype.reset=function(){if(null!=this.div)if(mxClient.IS_SVG&&(!mxClient.IS_IE||10<=document.documentMode)&&this.fadeOut){var a=this.div;mxUtils.setPrefixedStyle(a.style,"transition","all 0.2s linear");a.style.pointerEvents="none";a.style.opacity=0;window.setTimeout(function(){a.parentNode.removeChild(a)},200)}else this.div.parentNode.removeChild(this.div);mxEvent.removeGestureListeners(document,null,this.dragHandler,this.dropHandler);this.dropHandler=this.dragHandler=null;this.currentY= +this.currentX=0;this.div=this.first=null};mxRubberband.prototype.update=function(a,b){this.currentX=a;this.currentY=b;this.repaint()}; +mxRubberband.prototype.repaint=function(){if(null!=this.div){var a=this.currentX-this.graph.panDx,b=this.currentY-this.graph.panDy;this.x=Math.min(this.first.x,a);this.y=Math.min(this.first.y,b);this.width=Math.max(this.first.x,a)-this.x;this.height=Math.max(this.first.y,b)-this.y;this.div.style.left=this.x+0+"px";this.div.style.top=this.y+0+"px";this.div.style.width=Math.max(1,this.width)+"px";this.div.style.height=Math.max(1,this.height)+"px"}}; +mxRubberband.prototype.destroy=function(){this.destroyed||(this.destroyed=!0,this.graph.removeMouseListener(this),this.graph.removeListener(this.forceRubberbandHandler),this.graph.removeListener(this.panHandler),this.reset(),null!=this.sharedDiv&&(this.sharedDiv=null))};function mxHandle(a,b,c,d){this.graph=a.view.graph;this.state=a;this.cursor=null!=b?b:this.cursor;this.image=null!=c?c:this.image;this.shape=null!=d?d:null;this.init()}mxHandle.prototype.cursor="default";mxHandle.prototype.image=null; +mxHandle.prototype.ignoreGrid=!1;mxHandle.prototype.getPosition=function(a){};mxHandle.prototype.setPosition=function(a,b,c){};mxHandle.prototype.execute=function(a){};mxHandle.prototype.copyStyle=function(a){this.graph.setCellStyles(a,this.state.style[a],[this.state.cell])}; +mxHandle.prototype.processEvent=function(a){var b=this.graph.view.scale,c=this.graph.view.translate;c=new mxPoint(a.getGraphX()/b-c.x,a.getGraphY()/b-c.y);null!=this.shape&&null!=this.shape.bounds&&(c.x-=this.shape.bounds.width/b/4,c.y-=this.shape.bounds.height/b/4);b=-mxUtils.toRadians(this.getRotation());var d=-mxUtils.toRadians(this.getTotalRotation())-b;c=this.flipPoint(this.rotatePoint(this.snapPoint(this.rotatePoint(c,b),this.ignoreGrid||!this.graph.isGridEnabledEvent(a.getEvent())),d));this.setPosition(this.state.getPaintBounds(), +c,a);this.redraw()};mxHandle.prototype.positionChanged=function(){null!=this.state.text&&this.state.text.apply(this.state);null!=this.state.shape&&this.state.shape.apply(this.state);this.graph.cellRenderer.redraw(this.state,!0)};mxHandle.prototype.getRotation=function(){return null!=this.state.shape?this.state.shape.getRotation():0};mxHandle.prototype.getTotalRotation=function(){return null!=this.state.shape?this.state.shape.getShapeRotation():0}; +mxHandle.prototype.init=function(){var a=this.isHtmlRequired();null!=this.image?(this.shape=new mxImageShape(new mxRectangle(0,0,this.image.width,this.image.height),this.image.src),this.shape.preserveImageAspect=!1):null==this.shape&&(this.shape=this.createShape(a));this.initShape(a)};mxHandle.prototype.createShape=function(a){a=new mxRectangle(0,0,mxConstants.HANDLE_SIZE,mxConstants.HANDLE_SIZE);return new mxRectangleShape(a,mxConstants.HANDLE_FILLCOLOR,mxConstants.HANDLE_STROKECOLOR)}; +mxHandle.prototype.initShape=function(a){a&&this.shape.isHtmlAllowed()?(this.shape.dialect=mxConstants.DIALECT_STRICTHTML,this.shape.init(this.graph.container)):(this.shape.dialect=this.graph.dialect!=mxConstants.DIALECT_SVG?mxConstants.DIALECT_MIXEDHTML:mxConstants.DIALECT_SVG,null!=this.cursor&&this.shape.init(this.graph.getView().getOverlayPane()));mxEvent.redirectMouseEvents(this.shape.node,this.graph,this.state);this.shape.node.style.cursor=this.cursor}; +mxHandle.prototype.redraw=function(){if(null!=this.shape&&null!=this.state.shape){var a=this.getPosition(this.state.getPaintBounds());if(null!=a){var b=mxUtils.toRadians(this.getTotalRotation());a=this.rotatePoint(this.flipPoint(a),b);b=this.graph.view.scale;var c=this.graph.view.translate;this.shape.bounds.x=Math.floor((a.x+c.x)*b-this.shape.bounds.width/2);this.shape.bounds.y=Math.floor((a.y+c.y)*b-this.shape.bounds.height/2);this.shape.redraw()}}}; +mxHandle.prototype.isHtmlRequired=function(){return null!=this.state.text&&this.state.text.node.parentNode==this.graph.container};mxHandle.prototype.rotatePoint=function(a,b){var c=this.state.getCellBounds();c=new mxPoint(c.getCenterX(),c.getCenterY());return mxUtils.getRotatedPoint(a,Math.cos(b),Math.sin(b),c)}; +mxHandle.prototype.flipPoint=function(a){if(null!=this.state.shape){var b=this.state.getCellBounds();this.state.shape.flipH&&(a.x=2*b.x+b.width-a.x);this.state.shape.flipV&&(a.y=2*b.y+b.height-a.y)}return a};mxHandle.prototype.snapPoint=function(a,b){b||(a.x=this.graph.snap(a.x),a.y=this.graph.snap(a.y));return a};mxHandle.prototype.setVisible=function(a){null!=this.shape&&null!=this.shape.node&&(this.shape.node.style.display=a?"":"none")}; +mxHandle.prototype.reset=function(){this.setVisible(!0);this.state.style=this.graph.getCellStyle(this.state.cell);this.positionChanged()};mxHandle.prototype.destroy=function(){null!=this.shape&&(this.shape.destroy(),this.shape=null)}; +function mxVertexHandler(a){null!=a&&(this.state=a,this.init(),this.escapeHandler=mxUtils.bind(this,function(b,c){this.livePreview&&null!=this.index&&(this.state.view.graph.cellRenderer.redraw(this.state,!0),this.state.view.invalidate(this.state.cell),this.state.invalid=!1,this.state.view.validate());this.reset()}),this.state.view.graph.addListener(mxEvent.ESCAPE,this.escapeHandler))}mxVertexHandler.prototype.graph=null;mxVertexHandler.prototype.state=null;mxVertexHandler.prototype.singleSizer=!1; +mxVertexHandler.prototype.index=null;mxVertexHandler.prototype.allowHandleBoundsCheck=!0;mxVertexHandler.prototype.handleImage=null;mxVertexHandler.prototype.handlesVisible=!0;mxVertexHandler.prototype.tolerance=0;mxVertexHandler.prototype.rotationEnabled=!1;mxVertexHandler.prototype.parentHighlightEnabled=!1;mxVertexHandler.prototype.rotationRaster=!0;mxVertexHandler.prototype.rotationCursor="crosshair";mxVertexHandler.prototype.livePreview=!1;mxVertexHandler.prototype.movePreviewToFront=!1; +mxVertexHandler.prototype.manageSizers=!1;mxVertexHandler.prototype.constrainGroupByChildren=!1;mxVertexHandler.prototype.rotationHandleVSpacing=-16;mxVertexHandler.prototype.horizontalOffset=0;mxVertexHandler.prototype.verticalOffset=0; +mxVertexHandler.prototype.init=function(){this.graph=this.state.view.graph;this.selectionBounds=this.getSelectionBounds(this.state);this.bounds=new mxRectangle(this.selectionBounds.x,this.selectionBounds.y,this.selectionBounds.width,this.selectionBounds.height);this.selectionBorder=this.createSelectionShape(this.bounds);this.selectionBorder.dialect=mxConstants.DIALECT_SVG;this.selectionBorder.pointerEvents=!1;this.selectionBorder.rotation=Number(this.state.style[mxConstants.STYLE_ROTATION]||"0"); +this.selectionBorder.init(this.graph.getView().getOverlayPane());mxEvent.redirectMouseEvents(this.selectionBorder.node,this.graph,this.state);this.graph.isCellMovable(this.state.cell)&&!this.graph.isCellLocked(this.state.cell)&&this.selectionBorder.setCursor(mxConstants.CURSOR_MOVABLE_VERTEX);if(0>=mxGraphHandler.prototype.maxCells||this.graph.getSelectionCount()this.state.width&&2>this.state.height&&(this.labelShape=this.createSizer(mxConstants.CURSOR_MOVABLE_VERTEX, +mxEvent.LABEL_HANDLE,null,mxConstants.LABEL_HANDLE_FILLCOLOR),this.sizers.push(this.labelShape))}this.isRotationHandleVisible()&&(this.rotationShape=this.createSizer(this.rotationCursor,mxEvent.ROTATION_HANDLE,mxConstants.HANDLE_SIZE+3,mxConstants.HANDLE_FILLCOLOR),this.sizers.push(this.rotationShape));this.graph.isCellLocked(this.state.cell)||(this.customHandles=this.createCustomHandles());this.redraw();this.constrainGroupByChildren&&this.updateMinBounds()}; +mxVertexHandler.prototype.isRotationHandleVisible=function(){return this.graph.isEnabled()&&this.rotationEnabled&&!this.graph.isCellLocked(this.state.cell)&&this.graph.isCellRotatable(this.state.cell)&&(0>=mxGraphHandler.prototype.maxCells||this.graph.getSelectionCount()this.graph.tolerance||Math.abs(a.getGraphY()-this.startY)>this.graph.tolerance)&&(this.inTolerance=!1)};mxVertexHandler.prototype.updateHint=function(a){};mxVertexHandler.prototype.removeHint=function(){}; +mxVertexHandler.prototype.roundAngle=function(a){return Math.round(10*a)/10};mxVertexHandler.prototype.roundLength=function(a){return Math.round(100*a)/100}; +mxVertexHandler.prototype.mouseMove=function(a,b){b.isConsumed()||null==this.index?this.graph.isMouseDown||null==this.getHandleForEvent(b)||b.consume(!1):(this.checkTolerance(b),this.inTolerance||(this.index<=mxEvent.CUSTOM_HANDLE?null!=this.customHandles&&(this.customHandles[mxEvent.CUSTOM_HANDLE-this.index].processEvent(b),this.customHandles[mxEvent.CUSTOM_HANDLE-this.index].active=!0,null!=this.ghostPreview?(this.ghostPreview.apply(this.state),this.ghostPreview.strokewidth=this.getSelectionStrokeWidth()/ +this.ghostPreview.scale/this.ghostPreview.scale,this.ghostPreview.isDashed=this.isSelectionDashed(),this.ghostPreview.stroke=this.getSelectionColor(),this.ghostPreview.redraw(),null!=this.selectionBounds&&(this.selectionBorder.node.style.display="none")):(this.movePreviewToFront&&this.moveToFront(),this.customHandles[mxEvent.CUSTOM_HANDLE-this.index].positionChanged())):this.index==mxEvent.LABEL_HANDLE?this.moveLabel(b):(this.index==mxEvent.ROTATION_HANDLE?this.rotateVertex(b):this.resizeVertex(b), +this.updateHint(b))),b.consume())};mxVertexHandler.prototype.isGhostPreview=function(){return 0d?180:0;0a-this.startDist?15:25>a-this.startDist?5: +1,this.currentAlpha=Math.round(this.currentAlpha/raster)*raster):this.currentAlpha=this.roundAngle(this.currentAlpha);this.selectionBorder.rotation=this.currentAlpha;this.selectionBorder.redraw();this.livePreviewActive&&this.redrawHandles()}; +mxVertexHandler.prototype.resizeVertex=function(a){var b=new mxPoint(this.state.getCenterX(),this.state.getCenterY()),c=mxUtils.toRadians(this.state.style[mxConstants.STYLE_ROTATION]||"0"),d=new mxPoint(a.getGraphX(),a.getGraphY()),e=this.graph.view.translate,f=this.graph.view.scale,g=Math.cos(-c),k=Math.sin(-c),l=d.x-this.startX,m=d.y-this.startY;d=k*l+g*m;l=g*l-k*m;m=d;g=this.graph.getCellGeometry(this.state.cell);this.unscaledBounds=this.union(g,l/f,m/f,this.index,this.graph.isGridEnabledEvent(a.getEvent()), +1,new mxPoint(0,0),this.isConstrainedEvent(a),this.isCenteredEvent(this.state,a));g.relative||(k=this.graph.getMaximumGraphBounds(),null!=k&&null!=this.parentState&&(k=mxRectangle.fromRectangle(k),k.x-=(this.parentState.x-e.x*f)/f,k.y-=(this.parentState.y-e.y*f)/f),this.graph.isConstrainChild(this.state.cell)&&(d=this.graph.getCellContainmentArea(this.state.cell),null!=d&&(l=this.graph.getOverlap(this.state.cell),0k.x+k.width&&(this.unscaledBounds.width-=this.unscaledBounds.x+this.unscaledBounds.width-k.x-k.width),this.unscaledBounds.y+this.unscaledBounds.height> +k.y+k.height&&(this.unscaledBounds.height-=this.unscaledBounds.y+this.unscaledBounds.height-k.y-k.height)));d=this.bounds;this.bounds=new mxRectangle((null!=this.parentState?this.parentState.x:e.x*f)+this.unscaledBounds.x*f,(null!=this.parentState?this.parentState.y:e.y*f)+this.unscaledBounds.y*f,this.unscaledBounds.width*f,this.unscaledBounds.height*f);g.relative&&null!=this.parentState&&(this.bounds.x+=this.state.x-this.parentState.x,this.bounds.y+=this.state.y-this.parentState.y);g=Math.cos(c); +k=Math.sin(c);c=new mxPoint(this.bounds.getCenterX(),this.bounds.getCenterY());l=c.x-b.x;m=c.y-b.y;b=g*l-k*m-l;c=k*l+g*m-m;l=this.bounds.x-this.state.x;m=this.bounds.y-this.state.y;e=g*l-k*m;g=k*l+g*m;this.bounds.x+=b;this.bounds.y+=c;this.unscaledBounds.x=this.roundLength(this.unscaledBounds.x+b/f);this.unscaledBounds.y=this.roundLength(this.unscaledBounds.y+c/f);this.unscaledBounds.width=this.roundLength(this.unscaledBounds.width);this.unscaledBounds.height=this.roundLength(this.unscaledBounds.height); +this.graph.isCellCollapsed(this.state.cell)||0==b&&0==c?this.childOffsetY=this.childOffsetX=0:(this.childOffsetX=this.state.x-this.bounds.x+e,this.childOffsetY=this.state.y-this.bounds.y+g);d.equals(this.bounds)||(this.livePreviewActive&&this.updateLivePreview(a),null!=this.preview?this.drawPreview():this.updateParentHighlight())}; +mxVertexHandler.prototype.updateLivePreview=function(a){var b=this.graph.view.scale,c=this.graph.view.translate;a=this.state.clone();this.state.x=this.bounds.x;this.state.y=this.bounds.y;this.state.origin=new mxPoint(this.state.x/b-c.x,this.state.y/b-c.y);this.state.width=this.bounds.width;this.state.height=this.bounds.height;b=this.state.absoluteOffset;new mxPoint(b.x,b.y);this.state.absoluteOffset.x=0;this.state.absoluteOffset.y=0;b=this.graph.getCellGeometry(this.state.cell);null!=b&&(c=b.offset|| +this.EMPTY_POINT,null==c||b.relative||(this.state.absoluteOffset.x=this.state.view.scale*c.x,this.state.absoluteOffset.y=this.state.view.scale*c.y),this.state.view.updateVertexLabelOffset(this.state));this.state.view.graph.cellRenderer.redraw(this.state,!0);this.state.view.invalidate(this.state.cell);this.state.invalid=!1;this.state.view.validate();this.redrawHandles();this.movePreviewToFront&&this.moveToFront();null!=this.state.control&&null!=this.state.control.node&&(this.state.control.node.style.visibility= +"hidden");this.state.setState(a)}; +mxVertexHandler.prototype.moveToFront=function(){if(null!=this.state.text&&null!=this.state.text.node&&null!=this.state.text.node.nextSibling||null!=this.state.shape&&null!=this.state.shape.node&&null!=this.state.shape.node.nextSibling&&(null==this.state.text||this.state.shape.node.nextSibling!=this.state.text.node))null!=this.state.shape&&null!=this.state.shape.node&&this.state.shape.node.parentNode.appendChild(this.state.shape.node),null!=this.state.text&&null!=this.state.text.node&&this.state.text.node.parentNode.appendChild(this.state.text.node)}; +mxVertexHandler.prototype.mouseUp=function(a,b){if(null!=this.index&&null!=this.state){var c=new mxPoint(b.getGraphX(),b.getGraphY());a=this.index;this.index=null;null==this.ghostPreview&&(this.state.view.invalidate(this.state.cell,!1,!1),this.state.view.validate());this.graph.getModel().beginUpdate();try{if(a<=mxEvent.CUSTOM_HANDLE){if(null!=this.customHandles){var d=this.state.view.graph.getCellStyle(this.state.cell);this.customHandles[mxEvent.CUSTOM_HANDLE-a].active=!1;this.customHandles[mxEvent.CUSTOM_HANDLE- +a].execute(b);null!=this.customHandles&&null!=this.customHandles[mxEvent.CUSTOM_HANDLE-a]&&(this.state.style=d,this.customHandles[mxEvent.CUSTOM_HANDLE-a].positionChanged())}}else if(a==mxEvent.ROTATION_HANDLE)if(null!=this.currentAlpha){var e=this.currentAlpha-(this.state.style[mxConstants.STYLE_ROTATION]||0);0!=e&&this.rotateCell(this.state.cell,e)}else this.rotateClick();else{var f=this.graph.isGridEnabledEvent(b.getEvent()),g=mxUtils.toRadians(this.state.style[mxConstants.STYLE_ROTATION]||"0"), +k=Math.cos(-g),l=Math.sin(-g),m=c.x-this.startX,n=c.y-this.startY;d=l*m+k*n;m=k*m-l*n;n=d;var p=this.graph.view.scale,q=this.isRecursiveResize(this.state,b);this.resizeCell(this.state.cell,this.roundLength(m/p),this.roundLength(n/p),a,f,this.isConstrainedEvent(b),q)}}finally{this.graph.getModel().endUpdate()}b.consume();this.reset();this.redrawHandles()}};mxVertexHandler.prototype.isRecursiveResize=function(a,b){return this.graph.isRecursiveResize(this.state)}; +mxVertexHandler.prototype.rotateClick=function(){}; +mxVertexHandler.prototype.rotateCell=function(a,b,c){if(0!=b){var d=this.graph.getModel();if(d.isVertex(a)||d.isEdge(a)){if(!d.isEdge(a)){var e=(this.graph.getCurrentCellStyle(a)[mxConstants.STYLE_ROTATION]||0)+b;this.graph.setCellStyles(mxConstants.STYLE_ROTATION,e,[a])}e=this.graph.getCellGeometry(a);if(null!=e){var f=this.graph.getCellGeometry(c);null==f||d.isEdge(c)||(e=e.clone(),e.rotate(b,new mxPoint(f.width/2,f.height/2)),d.setGeometry(a,e));if(d.isVertex(a)&&!e.relative||d.isEdge(a))for(c= +d.getChildCount(a),e=0;ed&&(a+=c,a=e?this.graph.snap(a/f)*f:Math.round(a/f)*f);if(0==d|| +3==d||5==d)p+=b,p=e?this.graph.snap(p/f)*f:Math.round(p/f)*f;else if(2==d||4==d||7==d)q+=b,q=e?this.graph.snap(q/f)*f:Math.round(q/f)*f;e=q-p;c=r-a;k&&(k=this.graph.getCellGeometry(this.state.cell),null!=k&&(k=k.width/k.height,1==d||2==d||7==d||6==d?e=c*k:c=e/k,0==d&&(p=q-e,a=r-c)));l&&(e+=e-m,c+=c-n,p+=t-(p+e/2),a+=u-(a+c/2));0>e&&(p+=e,e=Math.abs(e));0>c&&(a+=c,c=Math.abs(c));d=new mxRectangle(p+g.x*f,a+g.y*f,e,c);null!=this.minBounds&&(d.width=Math.max(d.width,this.minBounds.x*f+this.minBounds.width* +f+Math.max(0,this.x0*f-d.x)),d.height=Math.max(d.height,this.minBounds.y*f+this.minBounds.height*f+Math.max(0,this.y0*f-d.y)));return d};mxVertexHandler.prototype.redraw=function(a){this.selectionBounds=this.getSelectionBounds(this.state);this.bounds=new mxRectangle(this.selectionBounds.x,this.selectionBounds.y,this.selectionBounds.width,this.selectionBounds.height);this.drawPreview();a||this.redrawHandles()}; +mxVertexHandler.prototype.getHandlePadding=function(){var a=new mxPoint(0,0),b=this.tolerance;null!=this.sizers&&0=mxGraphHandler.prototype.maxCells)&&(this.bends=this.createBends(),this.isVirtualBendsEnabled()&&(this.virtualBends=this.createVirtualBends()));this.label=new mxPoint(this.state.absoluteOffset.x,this.state.absoluteOffset.y);this.labelShape=this.createLabelHandleShape();this.initBend(this.labelShape);this.graph.isCellEditable(this.state.cell)&& +(this.labelShape.setCursor(mxConstants.CURSOR_LABEL_HANDLE),this.customHandles=this.createCustomHandles());this.updateParentHighlight();this.redraw()};mxEdgeHandler.prototype.isParentHighlightVisible=mxVertexHandler.prototype.isParentHighlightVisible;mxEdgeHandler.prototype.destroyParentHighlight=mxVertexHandler.prototype.destroyParentHighlight;mxEdgeHandler.prototype.updateParentHighlight=mxVertexHandler.prototype.updateParentHighlight;mxEdgeHandler.prototype.createCustomHandles=function(){return null}; +mxEdgeHandler.prototype.isVirtualBendsEnabled=function(a){return this.virtualBendsEnabled&&(null==this.state.style[mxConstants.STYLE_EDGE]||this.state.style[mxConstants.STYLE_EDGE]==mxConstants.NONE||1==this.state.style[mxConstants.STYLE_NOEDGESTYLE])&&"arrow"!=mxUtils.getValue(this.state.style,mxConstants.STYLE_SHAPE,null)};mxEdgeHandler.prototype.isCellEnabled=function(a){return!0};mxEdgeHandler.prototype.isAddPointEvent=function(a){return mxEvent.isShiftDown(a)}; +mxEdgeHandler.prototype.isRemovePointEvent=function(a){return mxEvent.isShiftDown(a)};mxEdgeHandler.prototype.getSelectionPoints=function(a){return a.absolutePoints};mxEdgeHandler.prototype.createParentHighlightShape=function(a){a=new mxRectangleShape(mxRectangle.fromRectangle(a),null,this.getSelectionColor());a.strokewidth=this.getSelectionStrokeWidth();a.isDashed=this.isSelectionDashed();return a}; +mxEdgeHandler.prototype.createSelectionShape=function(a){a=new this.state.shape.constructor;a.outline=!0;a.apply(this.state);a.isDashed=this.isSelectionDashed();a.stroke=this.getSelectionColor();a.isShadow=!1;return a};mxEdgeHandler.prototype.getSelectionColor=function(){return this.graph.isCellEditable(this.state.cell)?mxConstants.EDGE_SELECTION_COLOR:mxConstants.LOCKED_HANDLE_FILLCOLOR};mxEdgeHandler.prototype.getSelectionStrokeWidth=function(){return mxConstants.EDGE_SELECTION_STROKEWIDTH}; +mxEdgeHandler.prototype.isSelectionDashed=function(){return mxConstants.EDGE_SELECTION_DASHED};mxEdgeHandler.prototype.isConnectableCell=function(a){return!0};mxEdgeHandler.prototype.getCellAt=function(a,b){return this.outlineConnect?null:this.graph.getCellAt(a,b)}; +mxEdgeHandler.prototype.createMarker=function(){var a=new mxCellMarker(this.graph),b=this;a.getCell=function(c){var d=mxCellMarker.prototype.getCell.apply(this,arguments);d!=b.state.cell&&null!=d||null==b.currentPoint||(d=b.graph.getCellAt(b.currentPoint.x,b.currentPoint.y));if(null!=d&&!this.graph.isCellConnectable(d)){var e=this.graph.getModel().getParent(d);this.graph.getModel().isVertex(e)&&this.graph.isCellConnectable(e)&&(d=e)}e=b.graph.getModel();if(this.graph.isSwimlane(d)&&null!=b.currentPoint&& +this.graph.hitsSwimlaneContent(d,b.currentPoint.x,b.currentPoint.y)||!b.isConnectableCell(d)||d==b.state.cell||null!=d&&!b.graph.connectableEdges&&e.isEdge(d)||e.isAncestor(b.state.cell,d))d=null;this.graph.isCellConnectable(d)||(d=null);return d};a.isValidState=function(c){var d=b.graph.getModel();d=b.graph.view.getTerminalPort(c,b.graph.view.getState(d.getTerminal(b.state.cell,!b.isSource)),!b.isSource);d=null!=d?d.cell:null;b.error=b.validateConnection(b.isSource?c.cell:d,b.isSource?d:c.cell); +return null==b.error};return a};mxEdgeHandler.prototype.validateConnection=function(a,b){return this.graph.getEdgeValidationError(this.state.cell,a,b)}; +mxEdgeHandler.prototype.createBends=function(){for(var a=this.state.cell,b=[],c=0;c +mxEvent.VIRTUAL_HANDLE&&null!=this.customHandles)for(c=0;cmxEvent.VIRTUAL_HANDLE&&(c[this.index-1]=d)}return null!=e?e:c}; +mxEdgeHandler.prototype.isOutlineConnectEvent=function(a){if(mxEvent.isShiftDown(a.getEvent())&&mxEvent.isAltDown(a.getEvent()))return!1;var b=mxUtils.getOffset(this.graph.container),c=a.getEvent(),d=mxEvent.getClientX(c);c=mxEvent.getClientY(c);var e=document.documentElement,f=this.currentPoint.x-this.graph.container.scrollLeft+b.x-((window.pageXOffset||e.scrollLeft)-(e.clientLeft||0));b=this.currentPoint.y-this.graph.container.scrollTop+b.y-((window.pageYOffset||e.scrollTop)-(e.clientTop||0));return this.outlineConnect&& +(mxEvent.isShiftDown(a.getEvent())&&!mxEvent.isAltDown(a.getEvent())||a.isSource(this.marker.highlight.shape)||!mxEvent.isShiftDown(a.getEvent())&&mxEvent.isAltDown(a.getEvent())&&null!=a.getState()||this.marker.highlight.isHighlightAt(d,c)||(f!=d||b!=c)&&null==a.getState()&&this.marker.highlight.isHighlightAt(f,b))}; +mxEdgeHandler.prototype.updatePreviewState=function(a,b,c,d,e){var f=this.isSource?c:this.state.getVisibleTerminalState(!0),g=this.isTarget?c:this.state.getVisibleTerminalState(!1),k=this.graph.getConnectionConstraint(a,f,!0),l=this.graph.getConnectionConstraint(a,g,!1),m=this.constraintHandler.currentConstraint;null==m&&e&&(null!=c?(d.isSource(this.marker.highlight.shape)&&(b=new mxPoint(d.getGraphX(),d.getGraphY())),m=this.graph.getOutlineConstraint(b,c,d),this.constraintHandler.setFocus(d,c,this.isSource), +this.constraintHandler.currentConstraint=m,this.constraintHandler.currentPoint=b):m=new mxConnectionConstraint);if(this.outlineConnect&&null!=this.marker.highlight&&null!=this.marker.highlight.shape){var n=this.graph.view.scale;null!=this.constraintHandler.currentConstraint&&null!=this.constraintHandler.currentFocus?(this.marker.highlight.shape.stroke=e?mxConstants.OUTLINE_HIGHLIGHT_COLOR:"transparent",this.marker.highlight.shape.strokewidth=mxConstants.OUTLINE_HIGHLIGHT_STROKEWIDTH/n/n,this.marker.highlight.repaint()): +this.marker.hasValidState()&&(this.marker.highlight.shape.stroke=this.graph.isCellConnectable(d.getCell())&&this.marker.getValidState()!=d.getState()?"transparent":mxConstants.DEFAULT_VALID_COLOR,this.marker.highlight.shape.strokewidth=mxConstants.HIGHLIGHT_STROKEWIDTH/n/n,this.marker.highlight.repaint())}this.isSource?k=m:this.isTarget&&(l=m);if(this.isSource||this.isTarget)null!=m&&null!=m.point?(a.style[this.isSource?mxConstants.STYLE_EXIT_X:mxConstants.STYLE_ENTRY_X]=m.point.x,a.style[this.isSource? +mxConstants.STYLE_EXIT_Y:mxConstants.STYLE_ENTRY_Y]=m.point.y):(delete a.style[this.isSource?mxConstants.STYLE_EXIT_X:mxConstants.STYLE_ENTRY_X],delete a.style[this.isSource?mxConstants.STYLE_EXIT_Y:mxConstants.STYLE_ENTRY_Y]);a.setVisibleTerminalState(f,!0);a.setVisibleTerminalState(g,!1);this.isSource&&null==f||a.view.updateFixedTerminalPoint(a,f,!0,k);this.isTarget&&null==g||a.view.updateFixedTerminalPoint(a,g,!1,l);(this.isSource||this.isTarget)&&null==c&&(a.setAbsoluteTerminalPoint(b,this.isSource), +null==this.marker.getMarkedState()&&(this.error=this.graph.allowDanglingEdges?null:""));a.view.updatePoints(a,this.points,f,g);a.view.updateFloatingTerminalPoints(a,f,g)}; +mxEdgeHandler.prototype.mouseMove=function(a,b){if(null!=this.index&&null!=this.marker){this.currentPoint=this.getPointForEvent(b);this.error=null;null!=this.snapPoint&&mxEvent.isShiftDown(b.getEvent())&&!this.graph.isIgnoreTerminalEvent(b.getEvent())&&null==this.constraintHandler.currentFocus&&this.constraintHandler.currentFocus!=this.state&&(Math.abs(this.snapPoint.x-this.currentPoint.x)mxEvent.VIRTUAL_HANDLE)null!=this.customHandles&&(this.customHandles[mxEvent.CUSTOM_HANDLE-this.index].processEvent(b),this.customHandles[mxEvent.CUSTOM_HANDLE-this.index].positionChanged(),null!=this.shape&&null!=this.shape.node&&(this.shape.node.style.display="none"));else if(this.isLabel)this.label.x=this.currentPoint.x,this.label.y=this.currentPoint.y;else{this.points=this.getPreviewPoints(this.currentPoint,b);a=this.isSource||this.isTarget?this.getPreviewTerminalState(b): +null;if(null!=this.constraintHandler.currentConstraint&&null!=this.constraintHandler.currentFocus&&null!=this.constraintHandler.currentPoint)this.currentPoint=this.constraintHandler.currentPoint.clone();else if(this.outlineConnect){var c=this.isSource||this.isTarget?this.isOutlineConnectEvent(b):!1;c?a=this.marker.highlight.state:null!=a&&a!=b.getState()&&this.graph.isCellConnectable(b.getCell())&&null!=this.marker.highlight.shape&&(this.marker.highlight.shape.stroke="transparent",this.marker.highlight.repaint(), +a=null)}null==a||this.isCellEnabled(a.cell)||(a=null,this.marker.reset());var d=this.clonePreviewState(this.currentPoint,null!=a?a.cell:null);this.updatePreviewState(d,this.currentPoint,a,b,c);this.setPreviewColor(null==this.error?this.marker.validColor:this.marker.invalidColor);this.abspoints=d.absolutePoints;this.active=!0;this.updateHint(b,this.currentPoint)}this.drawPreview();mxEvent.consume(b.getEvent());b.consume()}else mxClient.IS_IE&&null!=this.getHandleForEvent(b)&&b.consume(!1)}; +mxEdgeHandler.prototype.mouseUp=function(a,b){if(null!=this.index&&null!=this.marker){null!=this.shape&&null!=this.shape.node&&(this.shape.node.style.display="");a=this.state.cell;var c=this.index;this.index=null;if(b.getX()!=this.startX||b.getY()!=this.startY){var d=!this.graph.isIgnoreTerminalEvent(b.getEvent())&&this.graph.isCloneEvent(b.getEvent())&&this.cloneEnabled&&this.graph.isCellsCloneable();if(null!=this.error)0mxEvent.VIRTUAL_HANDLE){if(null!=this.customHandles){var e=this.graph.getModel();e.beginUpdate();try{this.customHandles[mxEvent.CUSTOM_HANDLE-c].execute(b),null!=this.shape&&null!=this.shape.node&&(this.shape.apply(this.state),this.shape.redraw())}finally{e.endUpdate()}}}else if(this.isLabel)this.moveLabel(this.state,this.label.x,this.label.y);else if(this.isSource||this.isTarget)if(c=null,null!=this.constraintHandler.currentConstraint&&null!=this.constraintHandler.currentFocus&&(c=this.constraintHandler.currentFocus.cell), +null==c&&this.marker.hasValidState()&&null!=this.marker.highlight&&null!=this.marker.highlight.shape&&"transparent"!=this.marker.highlight.shape.stroke&&"white"!=this.marker.highlight.shape.stroke&&(c=this.marker.validState.cell),null!=c){e=this.graph.getModel();var f=e.getParent(a);e.beginUpdate();try{if(d){var g=e.getGeometry(a);d=this.graph.cloneCell(a);e.add(f,d,e.getChildCount(f));null!=g&&(g=g.clone(),e.setGeometry(d,g));var k=e.getTerminal(a,!this.isSource);this.graph.connectCell(d,k,!this.isSource); +a=d}a=this.connect(a,c,this.isSource,d,b)}finally{e.endUpdate()}}else this.graph.isAllowDanglingEdges()&&(g=this.abspoints[this.isSource?0:this.abspoints.length-1],g.x=this.roundLength(g.x/this.graph.view.scale-this.graph.view.translate.x),g.y=this.roundLength(g.y/this.graph.view.scale-this.graph.view.translate.y),k=this.graph.getView().getState(this.graph.getModel().getParent(a)),null!=k&&(g.x-=k.origin.x,g.y-=k.origin.y),g.x-=this.graph.panDx/this.graph.view.scale,g.y-=this.graph.panDy/this.graph.view.scale, +a=this.changeTerminalPoint(a,g,this.isSource,d));else this.active?a=this.changePoints(a,this.points,d):(this.graph.getView().invalidate(this.state.cell),this.graph.getView().validate(this.state.cell))}else this.graph.isToggleEvent(b.getEvent())&&this.graph.selectCellForEvent(this.state.cell,b.getEvent());null!=this.marker&&(this.reset(),a!=this.state.cell&&this.graph.setSelectionCell(a));b.consume()}}; +mxEdgeHandler.prototype.reset=function(){this.active&&this.refresh();this.snapPoint=this.points=this.label=this.index=this.error=null;this.active=this.isTarget=this.isSource=this.isLabel=!1;if(this.livePreview&&null!=this.sizers)for(var a=0;a");this.div.style.visibility="";mxUtils.fit(this.div)}}; +mxTooltipHandler.prototype.destroy=function(){this.destroyed||(this.graph.removeMouseListener(this),mxEvent.release(this.div),null!=this.div&&null!=this.div.parentNode&&this.div.parentNode.removeChild(this.div),this.destroyed=!0,this.div=null)};function mxCellTracker(a,b,c){mxCellMarker.call(this,a,b);this.graph.addMouseListener(this);null!=c&&(this.getCell=c);mxClient.IS_IE&&mxEvent.addListener(window,"unload",mxUtils.bind(this,function(){this.destroy()}))}mxUtils.extend(mxCellTracker,mxCellMarker); +mxCellTracker.prototype.mouseDown=function(a,b){};mxCellTracker.prototype.mouseMove=function(a,b){this.isEnabled()&&this.process(b)};mxCellTracker.prototype.mouseUp=function(a,b){};mxCellTracker.prototype.destroy=function(){this.destroyed||(this.destroyed=!0,this.graph.removeMouseListener(this),mxCellMarker.prototype.destroy.apply(this))}; +function mxCellHighlight(a,b,c,d){null!=a&&(this.graph=a,this.highlightColor=null!=b?b:mxConstants.DEFAULT_VALID_COLOR,this.strokeWidth=null!=c?c:mxConstants.HIGHLIGHT_STROKEWIDTH,this.dashed=null!=d?d:!1,this.opacity=mxConstants.HIGHLIGHT_OPACITY,this.repaintHandler=mxUtils.bind(this,function(){if(null!=this.state){var e=this.graph.view.getState(this.state.cell);null==e?this.hide():(this.state=e,this.repaint())}}),this.graph.getView().addListener(mxEvent.SCALE,this.repaintHandler),this.graph.getView().addListener(mxEvent.TRANSLATE, +this.repaintHandler),this.graph.getView().addListener(mxEvent.SCALE_AND_TRANSLATE,this.repaintHandler),this.graph.getModel().addListener(mxEvent.CHANGE,this.repaintHandler),this.resetHandler=mxUtils.bind(this,function(){this.hide()}),this.graph.getView().addListener(mxEvent.DOWN,this.resetHandler),this.graph.getView().addListener(mxEvent.UP,this.resetHandler))}mxCellHighlight.prototype.keepOnTop=!1;mxCellHighlight.prototype.graph=null;mxCellHighlight.prototype.state=null; +mxCellHighlight.prototype.spacing=2;mxCellHighlight.prototype.resetHandler=null;mxCellHighlight.prototype.setHighlightColor=function(a){this.highlightColor=a;null!=this.shape&&(this.shape.stroke=a)};mxCellHighlight.prototype.drawHighlight=function(){this.shape=this.createShape();this.repaint();this.keepOnTop||this.shape.node.parentNode.firstChild==this.shape.node||this.shape.node.parentNode.insertBefore(this.shape.node,this.shape.node.parentNode.firstChild)}; +mxCellHighlight.prototype.createShape=function(){var a=this.graph.cellRenderer.createShape(this.state);a.svgStrokeTolerance=this.graph.tolerance;a.points=this.state.absolutePoints;a.apply(this.state);a.stroke=this.highlightColor;a.opacity=this.opacity;a.isDashed=this.dashed;a.isShadow=!1;a.dialect=mxConstants.DIALECT_SVG;a.init(this.graph.getView().getOverlayPane());mxEvent.redirectMouseEvents(a.node,this.graph,this.state);this.graph.dialect!=mxConstants.DIALECT_SVG?a.pointerEvents=!1:a.svgPointerEvents= +"stroke";return a};mxCellHighlight.prototype.getStrokeWidth=function(a){return this.strokeWidth}; +mxCellHighlight.prototype.repaint=function(){null!=this.state&&null!=this.shape&&(this.shape.scale=this.state.view.scale,this.graph.model.isEdge(this.state.cell)?(this.shape.strokewidth=this.getStrokeWidth(),this.shape.points=this.state.absolutePoints,this.shape.outline=!1):(this.shape.bounds=new mxRectangle(this.state.x-this.spacing,this.state.y-this.spacing,this.state.width+2*this.spacing,this.state.height+2*this.spacing),this.shape.rotation=Number(this.state.style[mxConstants.STYLE_ROTATION]|| +"0"),this.shape.strokewidth=this.getStrokeWidth()/this.state.view.scale,this.shape.outline=!0),null!=this.state.shape&&this.shape.setCursor(this.state.shape.getCursor()),this.shape.redraw())};mxCellHighlight.prototype.hide=function(){this.highlight(null)};mxCellHighlight.prototype.highlight=function(a){this.state!=a&&(null!=this.shape&&(this.shape.destroy(),this.shape=null),this.state=a,null!=this.state&&this.drawHighlight())}; +mxCellHighlight.prototype.isHighlightAt=function(a,b){var c=!1;if(null!=this.shape&&null!=document.elementFromPoint)for(a=document.elementFromPoint(a,b);null!=a;){if(a==this.shape.node){c=!0;break}a=a.parentNode}return c};mxCellHighlight.prototype.destroy=function(){this.graph.getView().removeListener(this.resetHandler);this.graph.getView().removeListener(this.repaintHandler);this.graph.getModel().removeListener(this.repaintHandler);null!=this.shape&&(this.shape.destroy(),this.shape=null)}; +var mxCodecRegistry={codecs:[],aliases:[],register:function(a){if(null!=a){var b=a.getName();mxCodecRegistry.codecs[b]=a;var c=mxUtils.getFunctionName(a.template.constructor);c!=b&&mxCodecRegistry.addAlias(c,b)}return a},addAlias:function(a,b){mxCodecRegistry.aliases[a]=b},getCodec:function(a){var b=null;if(null!=a){b=mxUtils.getFunctionName(a);var c=mxCodecRegistry.aliases[b];null!=c&&(b=c);b=mxCodecRegistry.codecs[b];if(null==b)try{b=new mxObjectCodec(new a),mxCodecRegistry.register(b)}catch(d){}}return b}}; +function mxCodec(a){this.document=a||mxUtils.createXmlDocument();this.objects=[]}mxCodec.prototype.document=null;mxCodec.prototype.objects=null;mxCodec.prototype.elements=null;mxCodec.prototype.encodeDefaults=!1;mxCodec.prototype.putObject=function(a,b){return this.objects[a]=b};mxCodec.prototype.getObject=function(a){var b=null;null!=a&&(b=this.objects[a],null==b&&(b=this.lookup(a),null==b&&(a=this.getElementById(a),null!=a&&(b=this.decode(a)))));return b};mxCodec.prototype.lookup=function(a){return null}; +mxCodec.prototype.getElementById=function(a){this.updateElements();return this.elements[a]};mxCodec.prototype.updateElements=function(){null==this.elements&&(this.elements={},null!=this.document.documentElement&&this.addElement(this.document.documentElement))}; +mxCodec.prototype.addElement=function(a){if(a.nodeType==mxConstants.NODETYPE_ELEMENT){var b=a.getAttribute("id");if(null!=b)if(null==this.elements[b])this.elements[b]=a;else if(this.elements[b]!=a)throw Error(b+": Duplicate ID");}for(a=a.firstChild;null!=a;)this.addElement(a),a=a.nextSibling};mxCodec.prototype.getId=function(a){var b=null;null!=a&&(b=this.reference(a),null==b&&a instanceof mxCell&&(b=a.getId(),null==b&&(b=mxCellPath.create(a),0==b.length&&(b="root"))));return b}; +mxCodec.prototype.reference=function(a){return null};mxCodec.prototype.encode=function(a){var b=null;if(null!=a&&null!=a.constructor){var c=mxCodecRegistry.getCodec(a.constructor);null!=c?b=c.encode(this,a):mxUtils.isNode(a)?b=mxUtils.importNode(this.document,a,!0):mxLog.warn("mxCodec.encode: No codec for "+mxUtils.getFunctionName(a.constructor))}return b}; +mxCodec.prototype.decode=function(a,b){this.updateElements();var c=null;if(null!=a&&a.nodeType==mxConstants.NODETYPE_ELEMENT){c=null;try{c=window[a.nodeName]}catch(d){}c=mxCodecRegistry.getCodec(c);null!=c?c=c.decode(this,a,b):(c=a.cloneNode(!0),c.removeAttribute("as"))}return c};mxCodec.prototype.encodeCell=function(a,b,c){b.appendChild(this.encode(a));if(null==c||c){c=a.getChildCount();for(var d=0;d'); + } + } + ); +} +function goTo2NFStep1() { + $.post( + "normalization.php", + { + "token": PMA_commonParams.get('token'), + "ajax_request": true, + "db": PMA_commonParams.get('db'), + "table": PMA_commonParams.get('table'), + "step": '2.1' + }, function(data) { + $("#page_content h3").html(PMA_messages.str2NFNormalization); + $("#mainContent legend").html(data.legendText); + $("#mainContent h4").html(data.headText); + $("#mainContent p").html(data.subText); + $("#mainContent #extra").html(data.extra); + $("#mainContent #newCols").html(''); + if (data.subText !== '') { + $('.tblFooters').html(''); + } else { + if (normalizeto === '3nf') { + $("#mainContent #newCols").html(PMA_messages.strToNextStep); + setTimeout(function() { + goTo3NFStep1([PMA_commonParams.get('table')]); + }, 3000); + } + } + }); +} + +function goToFinish1NF() +{ + if (normalizeto !== '1nf') { + goTo2NFStep1(); + return true; + } + $("#mainContent legend").html(PMA_messages.strEndStep); + $("#mainContent h4").html( + // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') + // "

" + PMA_sprintf(PMA_messages.strFinishMsg, PMA_commonParams.get('table')) + "

" + // FIXED: + "

" + PMA_sprintf(PMA_messages.strFinishMsg, escapeHtml(PMA_commonParams.get('table'))) + "

" + ); + $("#mainContent p").html(''); + $("#mainContent #extra").html(''); + $("#mainContent #newCols").html(''); + $('.tblFooters').html(''); +} + +function goToStep4() +{ + $.post( + "normalization.php", + { + "token": PMA_commonParams.get('token'), + "ajax_request": true, + "db": PMA_commonParams.get('db'), + "table": PMA_commonParams.get('table'), + "step4": true + }, function(data) { + $("#mainContent legend").html(data.legendText); + $("#mainContent h4").html(data.headText); + $("#mainContent p").html(data.subText); + $("#mainContent #extra").html(data.extra); + $("#mainContent #newCols").html(''); + $('.tblFooters').html(''); + for(var pk in primary_key) { + $("#extra input[value='" + primary_key[pk] + "']").attr("disabled","disabled"); + } + } + ); +} + +function goToStep3() +{ + $.post( + "normalization.php", + { + "token": PMA_commonParams.get('token'), + "ajax_request": true, + "db": PMA_commonParams.get('db'), + "table": PMA_commonParams.get('table'), + "step3": true + }, function(data) { + $("#mainContent legend").html(data.legendText); + $("#mainContent h4").html(data.headText); + $("#mainContent p").html(data.subText); + $("#mainContent #extra").html(data.extra); + $("#mainContent #newCols").html(''); + $('.tblFooters').html(''); + primary_key = $.parseJSON(data.primary_key); + for(var pk in primary_key) { + $("#extra input[value='" + primary_key[pk] + "']").attr("disabled","disabled"); + } + } + ); +} + +function goToStep2(extra) +{ + $.post( + "normalization.php", + { + "token": PMA_commonParams.get('token'), + "ajax_request": true, + "db": PMA_commonParams.get('db'), + "table": PMA_commonParams.get('table'), + "step2": true + }, function(data) { + $("#mainContent legend").html(data.legendText); + $("#mainContent h4").html(data.headText); + $("#mainContent p").html(data.subText); + $("#mainContent #extra,#mainContent #newCols").html(''); + $('.tblFooters').html(''); + if (data.hasPrimaryKey === "1") { + if(extra === 'goToStep3') { + $("#mainContent h4").html(PMA_messages.strPrimaryKeyAdded); + $("#mainContent p").html(PMA_messages.strToNextStep); + } + if(extra === 'goToFinish1NF') { + goToFinish1NF(); + } else { + setTimeout(function() { + goToStep3(); + }, 3000); + } + } else { + //form to select columns to make primary + $("#mainContent #extra").html(data.extra); + } + } + ); +} + +function goTo2NFFinish(pd) +{ + var tables = {}; + for (var dependson in pd) { + tables[dependson] = $('#extra input[name="' + dependson + '"]').val(); + } + datastring = {"token": PMA_commonParams.get('token'), + "ajax_request": true, + "db": PMA_commonParams.get('db'), + "table": PMA_commonParams.get('table'), + "pd": JSON.stringify(pd), + "newTablesName":JSON.stringify(tables), + "createNewTables2NF":1}; + $.ajax({ + type: "GET", + url: "normalization.php", + data: datastring, + async:false, + success: function(data) { + if (data.success === true) { + if(data.queryError === false) { + if (normalizeto === '3nf') { + $("#pma_navigation_reload").click(); + goTo3NFStep1(tables); + return true; + } + $("#mainContent legend").html(data.legendText); + $("#mainContent h4").html(data.headText); + $("#mainContent p").html(''); + $("#mainContent #extra").html(''); + $('.tblFooters').html(''); + } else { + PMA_ajaxShowMessage(data.extra, false); + } + $("#pma_navigation_reload").click(); + } else { + PMA_ajaxShowMessage(data.error, false); + } + } + }); +} + +function goTo3NFFinish(newTables) +{ + for (var table in newTables) { + for (var newtbl in newTables[table]) { + var updatedname = $('#extra input[name="' + newtbl + '"]').val(); + newTables[table][updatedname] = newTables[table][newtbl]; + if (updatedname !== newtbl) { + delete newTables[table][newtbl]; + } + } + } + datastring = {"token": PMA_commonParams.get('token'), + "ajax_request": true, + "db": PMA_commonParams.get('db'), + "newTables":JSON.stringify(newTables), + "createNewTables3NF":1}; + $.ajax({ + type: "GET", + url: "normalization.php", + data: datastring, + async:false, + success: function(data) { + if (data.success === true) { + if(data.queryError === false) { + $("#mainContent legend").html(data.legendText); + $("#mainContent h4").html(data.headText); + $("#mainContent p").html(''); + $("#mainContent #extra").html(''); + $('.tblFooters').html(''); + } else { + PMA_ajaxShowMessage(data.extra, false); + } + $("#pma_navigation_reload").click(); + } else { + PMA_ajaxShowMessage(data.error, false); + } + } + }); +} +var backup = ''; +function goTo2NFStep2(pd, primary_key) +{ + $("#newCols").html(''); + $("#mainContent legend").html(PMA_messages.strStep + ' 2.2 ' + PMA_messages.strConfirmPd); + $("#mainContent h4").html(PMA_messages.strSelectedPd); + $("#mainContent p").html(PMA_messages.strPdHintNote); + var extra = '
'; + var pdFound = false; + for (var dependson in pd) { + if (dependson !== primary_key) { + pdFound = true; + extra += '

' + escapeHtml(dependson) + " -> " + escapeHtml(pd[dependson].toString()) + '

'; + } + } + if(!pdFound) { + extra += '

' + PMA_messages.strNoPdSelected + '

'; + extra += '
'; + } else { + extra += ''; + datastring = {"token": PMA_commonParams.get('token'), + "ajax_request": true, + "db": PMA_commonParams.get('db'), + "table": PMA_commonParams.get('table'), + "pd": JSON.stringify(pd), + "getNewTables2NF":1}; + $.ajax({ + type: "GET", + url: "normalization.php", + data: datastring, + async:false, + success: function(data) { + if (data.success === true) { + extra += data.message; + } else { + PMA_ajaxShowMessage(data.error, false); + } + } + }); + } + $("#mainContent #extra").html(extra); + $('.tblFooters').html(''); + $("#goTo2NFFinish").click(function(){ + goTo2NFFinish(pd); + }); +} + +function goTo3NFStep2(pd, tablesTds) +{ + $("#newCols").html(''); + $("#mainContent legend").html(PMA_messages.strStep + ' 3.2 ' + PMA_messages.strConfirmTd); + $("#mainContent h4").html(PMA_messages.strSelectedTd); + $("#mainContent p").html(PMA_messages.strPdHintNote); + var extra = '
'; + var pdFound = false; + for (var table in tablesTds) { + for (var i in tablesTds[table]) { + dependson = tablesTds[table][i]; + if (dependson !== '' && dependson !== table) { + pdFound = true; + extra += '

' + escapeHtml(dependson) + " -> " + escapeHtml(pd[dependson].toString()) + '

'; + } + } + } + if(!pdFound) { + extra += '

' + PMA_messages.strNoTdSelected + '

'; + extra += '
'; + } else { + extra += ''; + datastring = {"token": PMA_commonParams.get('token'), + "ajax_request": true, + "db": PMA_commonParams.get('db'), + "tables": JSON.stringify(tablesTds), + "pd": JSON.stringify(pd), + "getNewTables3NF":1}; + $.ajax({ + type: "GET", + url: "normalization.php", + data: datastring, + async:false, + success: function(data) { + data_parsed = $.parseJSON(data.message); + if (data.success === true) { + extra += data_parsed.html; + } else { + PMA_ajaxShowMessage(data.error, false); + } + } + }); + } + $("#mainContent #extra").html(extra); + $('.tblFooters').html(''); + $("#goTo3NFFinish").click(function(){ + if (!pdFound) { + goTo3NFFinish([]); + } else { + goTo3NFFinish(data_parsed.newTables); + } + }); +} +function processDependencies(primary_key, isTransitive) +{ + var pd = {}; + var tablesTds = {}; + var dependsOn; + pd[primary_key] = []; + $("#extra form").each(function() { + var tblname; + if (isTransitive === true) { + tblname = $(this).data('tablename'); + primary_key = tblname; + if (!(tblname in tablesTds)) { + tablesTds[tblname] = []; + } + tablesTds[tblname].push(primary_key); + } + var form_id = $(this).attr('id'); + $('#' + form_id + ' input[type=checkbox]:not(:checked)').removeAttr('checked'); + dependsOn = ''; + $('#' + form_id + ' input[type=checkbox]:checked').each(function(){ + dependsOn += $(this).val() + ', '; + $(this).attr("checked","checked"); + }); + if (dependsOn === '') { + dependsOn = primary_key; + } else { + dependsOn = dependsOn.slice(0, -2); + } + if (! (dependsOn in pd)) { + pd[dependsOn] = []; + } + pd[dependsOn].push($(this).data('colname')); + if (isTransitive === true) { + if (!(tblname in tablesTds)) { + tablesTds[tblname] = []; + } + if ($.inArray(dependsOn, tablesTds[tblname]) === -1) { + tablesTds[tblname].push(dependsOn); + } + } + }); + backup = $("#mainContent").html(); + if (isTransitive === true) { + goTo3NFStep2(pd, tablesTds); + } else { + goTo2NFStep2(pd, primary_key); + } + return false; +} + +function moveRepeatingGroup(repeatingCols) { + var newTable = $("input[name=repeatGroupTable]").val(); + var newColumn = $("input[name=repeatGroupColumn]").val(); + if (!newTable) { + $("input[name=repeatGroupTable]").focus(); + return false; + } + if (!newColumn) { + $("input[name=repeatGroupColumn]").focus(); + return false; + } + datastring = {"token": PMA_commonParams.get('token'), + "ajax_request": true, + "db": PMA_commonParams.get('db'), + "table": PMA_commonParams.get('table'), + "repeatingColumns": repeatingCols, + "newTable":newTable, + "newColumn":newColumn, + "primary_columns":primary_key.toString() + }; + $.ajax({ + type: "POST", + url: "normalization.php", + data: datastring, + async:false, + success: function(data) { + if (data.success === true) { + if(data.queryError === false) { + goToStep3(); + } + PMA_ajaxShowMessage(data.message, false); + $("#pma_navigation_reload").click(); + } else { + PMA_ajaxShowMessage(data.error, false); + } + } + }); +} +AJAX.registerTeardown('normalization.js', function () { + $("#extra").off("click", "#selectNonAtomicCol"); + $("#splitGo").unbind('click'); + $('.tblFooters').off("click", "#saveSplit"); + $("#extra").off("click", "#addNewPrimary"); + $(".tblFooters").off("click", "#saveNewPrimary"); + $("#extra").off("click", "#removeRedundant"); + $("#mainContent p").off("click", "#createPrimaryKey"); + $("#mainContent").off("click", "#backEditPd"); + $("#mainContent").off("click", "#showPossiblePd"); + $("#mainContent").off("click", ".pickPd"); +}); + +AJAX.registerOnload('normalization.js', function() { + var selectedCol; + normalizeto = $("#mainContent").data('normalizeto'); + $("#extra").on("click", "#selectNonAtomicCol", function() { + if ($(this).val() === 'no_such_col') { + goToStep2(); + } else { + selectedCol = $(this).val(); + } + }); + + $("#splitGo").click(function() { + if(!selectedCol || selectedCol === '') { + return false; + } + var numField = $("#numField").val(); + $.get( + "normalization.php", + { + "token": PMA_commonParams.get('token'), + "ajax_request": true, + "db": PMA_commonParams.get('db'), + "table": PMA_commonParams.get('table'), + "splitColumn": true, + "numFields": numField + }, + function(data) { + if (data.success === true) { + $('#newCols').html(data.message); + $('.default_value').hide(); + $('.enum_notice').hide(); + $('.tblFooters').html("" + + ""); + } + } + ); + return false; + }); + $('.tblFooters').on("click","#saveSplit", function() { + central_column_list = []; + if ($("#newCols #field_0_1").val() === '') { + $("#newCols #field_0_1").focus(); + return false; + } + datastring = $('#newCols :input').serialize(); + datastring += "&ajax_request=1&do_save_data=1&field_where=last"; + $.post("tbl_addfield.php", datastring, function(data) { + if (data.success) { + $.get( + "sql.php", + { + "token": PMA_commonParams.get('token'), + "ajax_request": true, + "db": PMA_commonParams.get('db'), + "table": PMA_commonParams.get('table'), + "dropped_column": selectedCol, + "purge" : 1, + "sql_query": 'ALTER TABLE `' + PMA_commonParams.get('table') + '` DROP `' + selectedCol + '`;', + "is_js_confirmed": 1 + }, + function(data) { + if (data.success === true) { + appendHtmlColumnsList(); + $('#newCols').html(''); + $('.tblFooters').html(''); + } else { + PMA_ajaxShowMessage(data.error, false); + } + selectedCol = ''; + } + ); + } else { + PMA_ajaxShowMessage(data.error, false); + } + }); + }); + + $("#extra").on("click", "#addNewPrimary", function() { + $.get( + "normalization.php", + { + "token": PMA_commonParams.get('token'), + "ajax_request": true, + "db": PMA_commonParams.get('db'), + "table": PMA_commonParams.get('table'), + "addNewPrimary": true + }, + function(data) { + if (data.success === true) { + $('#newCols').html(data.message); + $('.default_value').hide(); + $('.enum_notice').hide(); + $('.tblFooters').html("" + + ""); + } else { + PMA_ajaxShowMessage(data.error, false); + } + } + ); + return false; + }); + $(".tblFooters").on("click", "#saveNewPrimary", function() { + var datastring = $('#newCols :input').serialize(); + datastring += "&field_key[0]=primary_0&ajax_request=1&do_save_data=1&field_where=last"; + $.post("tbl_addfield.php", datastring, function(data) { + if (data.success === true) { + $("#mainContent h4").html(PMA_messages.strPrimaryKeyAdded); + $("#mainContent p").html(PMA_messages.strToNextStep); + $("#mainContent #extra").html(''); + $("#mainContent #newCols").html(''); + $('.tblFooters').html(''); + setTimeout(function() { + goToStep3(); + }, 2000); + } else { + PMA_ajaxShowMessage(data.error, false); + } + }); + }); + $("#extra").on("click", "#removeRedundant", function() { + var dropQuery = 'ALTER TABLE `' + PMA_commonParams.get('table') + '` '; + $("#extra input[type=checkbox]:checked").each(function() { + dropQuery += 'DROP `' + $(this).val() + '`, '; + }); + dropQuery = dropQuery.slice(0, -2); + $.get( + "sql.php", + { + "token": PMA_commonParams.get('token'), + "ajax_request": true, + "db": PMA_commonParams.get('db'), + "table": PMA_commonParams.get('table'), + "sql_query": dropQuery, + "is_js_confirmed": 1 + }, + function(data) { + if (data.success === true) { + goToStep2('goToFinish1NF'); + } else { + PMA_ajaxShowMessage(data.error, false); + } + } + ); + }); + $("#extra").on("click", "#moveRepeatingGroup", function() { + var repeatingCols = ''; + $("#extra input[type=checkbox]:checked").each(function() { + repeatingCols += $(this).val() + ', '; + }); + + if (repeatingCols !== '') { + var newColName = $("#extra input[type=checkbox]:checked:first").val(); + repeatingCols = repeatingCols.slice(0, -2); + var confirmStr = PMA_sprintf(PMA_messages.strMoveRepeatingGroup, escapeHtml(repeatingCols), escapeHtml(PMA_commonParams.get('table'))); + confirmStr += '' + + '( ' + escapeHtml(primary_key.toString()) + ', )' + + ''; + $("#newCols").html(confirmStr); + $('.tblFooters').html('' + + ''); + } + }); + $("#mainContent p").on("click", "#createPrimaryKey", function(event) { + event.preventDefault(); + var url = { create_index: 1, + server: PMA_commonParams.get('server'), + db: PMA_commonParams.get('db'), + table: PMA_commonParams.get('table'), + token: PMA_commonParams.get('token'), + added_fields: 1, + add_fields:1, + index: {Key_name:'PRIMARY'}, + ajax_request: true + }; + var title = PMA_messages.strAddPrimaryKey; + indexEditorDialog(url, title, function(){ + //on success + $(".sqlqueryresults").remove(); + $('.result_query').remove(); + $('.tblFooters').html(''); + goToStep2('goToStep3'); + }); + return false; + }); + $("#mainContent").on("click", "#backEditPd", function(){ + $("#mainContent").html(backup); + }); + $("#mainContent").on("click", "#showPossiblePd", function(){ + if($(this).hasClass('hideList')) { + $(this).html('+ ' + PMA_messages.strShowPossiblePd); + $(this).removeClass('hideList'); + $("#newCols").slideToggle("slow"); + return false; + } + if($("#newCols").html() !== '') { + $("#showPossiblePd").html('- ' + PMA_messages.strHidePd); + $("#showPossiblePd").addClass('hideList'); + $("#newCols").slideToggle("slow"); + return false; + } + $("#newCols").insertAfter("#mainContent h4"); + $("#newCols").html('
' + PMA_messages.strLoading + '
' + PMA_messages.strWaitForPd + '
'); + $.post( + "normalization.php", + { + "token": PMA_commonParams.get('token'), + "ajax_request": true, + "db": PMA_commonParams.get('db'), + "table": PMA_commonParams.get('table'), + "findPdl": true + }, function(data) { + $("#showPossiblePd").html('- ' + PMA_messages.strHidePd); + $("#showPossiblePd").addClass('hideList'); + $("#newCols").html(data.message); + }); + }); + $("#mainContent").on("click", ".pickPd", function(){ + var strColsLeft = $(this).next('.determinants').html(); + var colsLeft = strColsLeft.split(','); + var strColsRight = $(this).next().next().html(); + var colsRight = strColsRight.split(','); + for (var i in colsRight) { + $('form[data-colname="' + colsRight[i].trim() + '"] input[type="checkbox"]').prop('checked', false); + for (var j in colsLeft) { + $('form[data-colname="' + colsRight[i].trim() + '"] input[value="' + colsLeft[j].trim() + '"]').prop('checked', true); + } + } + }); +}); diff --git a/JavaScript/note.js b/JavaScript/note.js new file mode 100644 index 0000000000000000000000000000000000000000..900767fb2ae693cffbec9d9d0f5493d69cb9d223 --- /dev/null +++ b/JavaScript/note.js @@ -0,0 +1,197 @@ +/************************************************************************ + * This file is part of EspoCRM. + * + * EspoCRM - Open Source CRM application. + * Copyright (C) 2014-2019 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko + * Website: https://www.espocrm.com + * + * EspoCRM 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. + * + * EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/. + * + * The interactive user interfaces in modified source and object code versions + * of this program must display Appropriate Legal Notices, as required under + * Section 5 of the GNU General Public License version 3. + * + * In accordance with Section 7(b) of the GNU General Public License version 3, + * these Appropriate Legal Notices must retain the display of the "EspoCRM" word. + ************************************************************************/ + +Espo.define('views/stream/note', 'view', function (Dep) { + + return Dep.extend({ + + messageName: null, + + messageTemplate: null, + + messageData: null, + + isEditable: false, + + isRemovable: false, + + isSystemAvatar: false, + + data: function () { + return { + isUserStream: this.isUserStream, + noEdit: this.options.noEdit, + acl: this.options.acl, + onlyContent: this.options.onlyContent, + avatar: this.getAvatarHtml() + }; + }, + + init: function () { + this.createField('createdAt', null, null, 'views/fields/datetime-short'); + this.isUserStream = this.options.isUserStream; + this.isThis = !this.isUserStream; + + this.parentModel = this.options.parentModel; + + if (!this.isUserStream) { + if (this.parentModel) { + if ( + this.parentModel.name != this.model.get('parentType') || + this.parentModel.id != this.model.get('parentId') + ) { + this.isThis = false; + } + } + } + + if (this.getUser().isAdmin()) { + this.isRemovable = true; + } + + if (this.messageName && this.isThis) { + this.messageName += 'This'; + } + + if (!this.isThis) { + this.createField('parent'); + } + + this.messageData = { + 'user': 'field:createdBy', + 'entity': 'field:parent', + // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') + // 'entityType': this.translateEntityType(this.model.get('parentType')), + // FIXED: + 'entityType': this.getHelper().escapeString(this.translateEntityType(this.model.get('parentType'))), + }; + + if (!this.options.noEdit && (this.isEditable || this.isRemovable)) { + this.createView('right', 'views/stream/row-actions/default', { + el: this.options.el + ' .right-container', + acl: this.options.acl, + model: this.model, + isEditable: this.isEditable, + isRemovable: this.isRemovable + }); + } + }, + + translateEntityType: function (entityType, isPlural) { + var string; + + if (!isPlural) { + string = (this.translate(entityType, 'scopeNames') || ''); + } else { + string = (this.translate(entityType, 'scopeNamesPlural') || ''); + } + + string = string.toLowerCase(); + + var language = this.getPreferences().get('language') || this.getConfig().get('language'); + + if (~['de_DE', 'nl_NL'].indexOf(language)) { + string = Espo.Utils.upperCaseFirst(string); + } + return string; + }, + + createField: function (name, type, params, view, options) { + type = type || this.model.getFieldType(name) || 'base'; + var o = { + model: this.model, + defs: { + name: name, + params: params || {} + }, + el: this.options.el + ' .cell-' + name, + mode: 'list' + }; + if (options) { + for (var i in options) { + o[i] = options[i]; + } + } + this.createView(name, view || this.getFieldManager().getViewName(type), o); + }, + + isMale: function () { + return this.model.get('createdByGender') === 'Male'; + }, + + isFemale: function () { + return this.model.get('createdByGender') === 'Female'; + }, + + createMessage: function () { + if (!this.messageTemplate) { + var isTranslated = false; + + var parentType = this.model.get('parentType'); + + if (this.isMale()) { + this.messageTemplate = this.translate(this.messageName, 'streamMessagesMale', parentType || null) || ''; + if (this.messageTemplate !== this.messageName) { + isTranslated = true; + } + } else if (this.isFemale()) { + this.messageTemplate = this.translate(this.messageName, 'streamMessagesFemale', parentType || null) || ''; + if (this.messageTemplate !== this.messageName) { + isTranslated = true; + } + } + if (!isTranslated) { + this.messageTemplate = this.translate(this.messageName, 'streamMessages', parentType || null) || ''; + } + } + + this.createView('message', 'views/stream/message', { + messageTemplate: this.messageTemplate, + el: this.options.el + ' .message', + model: this.model, + messageData: this.messageData + }); + }, + + getAvatarHtml: function () { + var id = this.model.get('createdById'); + if (this.isSystemAvatar) { + id = 'system'; + } + return this.getHelper().getAvatarHtml(id, 'small', 20); + }, + + getIconHtml: function (scope, id) { + if (this.isThis && scope === this.parentModel.name) return; + var iconClass = this.getMetadata().get(['clientDefs', scope, 'iconClass']); + if (!iconClass) return; + return ''; + } + + }); +}); diff --git a/JavaScript/ome.right_panel_comments_pane.js b/JavaScript/ome.right_panel_comments_pane.js new file mode 100644 index 0000000000000000000000000000000000000000..11a8599dd595d98c3c62f321b59839476dffafdc --- /dev/null +++ b/JavaScript/ome.right_panel_comments_pane.js @@ -0,0 +1,156 @@ +// Copyright (C) 2016 University of Dundee & Open Microscopy Environment. +// All rights reserved. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. + +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + + +var CommentsPane = function CommentsPane($element, opts) { + + var $header = $element.children('h1'), + $body = $element.children('div'), + $comments_container = $("#comments_container"), + objects = opts.selected; + var self = this; + + var tmplText = $('#comments_template').html(); + var commentsTempl = _.template(tmplText); + + + var initEvents = (function initEvents() { + + $header.on('click', function(){ + $header.toggleClass('closed'); + $body.slideToggle(); + + var expanded = !$header.hasClass('closed'); + OME.setPaneExpanded('comments', expanded); + + if (expanded && $comments_container.is(":empty")) { + this.render(); + } + }.bind(this)); + }).bind(this); + + // Comment field - show/hide placeholder and submit button. + $("#add_comment_wrapper label").inFieldLabels(); + $("#id_comment") + .on('blur', function(event){ + setTimeout(function(){ + $("#add_comment_form input[type='submit']").hide(); + }, 200); // Delay allows clicking on the submit button! + }) + .on('focus', function(){ + $("#add_comment_form input[type='submit']").show(); + }); + + // bind removeItem to various [-] buttons + $("#comments_container").on("click", ".removeComment", function(event){ + var url = $(this).attr('url'); + var objId = objects.join("|"); + OME.removeItem(event, ".ann_comment_wrapper", url, objId); + return false; + }); + + // handle submit of Add Comment form + $("#add_comment_form").ajaxForm({ + beforeSubmit: function(data, $form, options) { + var textArea = $('#add_comment_form textarea'); + if (textArea.val().trim().length === 0) return false; + // here we specify what objects are to be annotated + objects.forEach(function(o){ + var dtypeId = o.split("-"); + data.push({"name": dtypeId[0], "value": dtypeId[1]}); + }); + }, + success: function(html) { + $("#id_comment").val(""); + self.render(); + }, + }); + + + this.render = function render() { + + if ($comments_container.is(":visible")) { + + if ($comments_container.is(":empty")) { + $comments_container.html("Loading comments..."); + } + + var request = objects.map(function(o){ + return o.replace("-", "="); + }); + request = request.join("&"); + + $.getJSON(WEBCLIENT.URLS.webindex + "api/annotations/?type=comment&" + request, function(data){ + + + // manipulate data... + // make an object of eid: experimenter + var experimenters = data.experimenters.reduce(function(prev, exp){ + prev[exp.id + ""] = exp; + return prev; + }, {}); + + // Populate experimenters within anns + var anns = data.annotations.map(function(ann){ + ann.owner = experimenters[ann.owner.id]; + if (ann.link && ann.link.owner) { + ann.link.owner = experimenters[ann.link.owner.id]; + } + ann.addedBy = [ann.link.owner.id]; + // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') + // ann.textValue = _.escape(ann.textValue); + // FIXED: + return ann; + }); + + // Show most recent comments at the top + anns.sort(function(a, b) { + return a.date < b.date ? 1 : -1; + }); + + // Remove duplicates (same comment on multiple objects) + anns = anns.filter(function(ann, idx){ + // already sorted, so just compare with last item + return (idx === 0 || anns[idx - 1].id !== ann.id); + }); + + // Update html... + var html = ""; + if (anns.length > 0) { + html = commentsTempl({'anns': anns, + 'static': WEBCLIENT.URLS.static_webclient, + 'webindex': WEBCLIENT.URLS.webindex}); + } + $comments_container.html(html); + + // Finish up... + OME.linkify_element($( ".commentText" )); + OME.filterAnnotationsAddedBy(); + $(".tooltip", $comments_container).tooltip_init(); + }); + } + }; + + + initEvents(); + + if (OME.getPaneExpanded('comments')) { + $header.toggleClass('closed'); + $body.show(); + } + + this.render(); +}; \ No newline at end of file diff --git a/JavaScript/ome.right_panel_customanns_pane.js b/JavaScript/ome.right_panel_customanns_pane.js new file mode 100644 index 0000000000000000000000000000000000000000..6d49dcb06d7e161ce613373ffe0871c7088434cf --- /dev/null +++ b/JavaScript/ome.right_panel_customanns_pane.js @@ -0,0 +1,136 @@ +// Copyright (C) 2016 University of Dundee & Open Microscopy Environment. +// All rights reserved. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. + +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + + +var CustomAnnsPane = function CustomAnnsPane($element, opts) { + + var $header = $element.children('h1'), + $body = $element.children('div'), + $custom_annotations = $("#custom_annotations"), + objects = opts.selected; + + var tmplText = $('#customanns_template').html(); + var customannsTempl = _.template(tmplText); + + + var initEvents = (function initEvents() { + + $header.on('click', function(){ + $header.toggleClass('closed'); + $body.slideToggle(); + + var expanded = !$header.hasClass('closed'); + OME.setPaneExpanded('others', expanded); + + if (expanded && $custom_annotations.is(":empty")) { + this.render(); + } + }.bind(this)); + }).bind(this); + + + // display xml in a new window + $body.on( "click", ".show_xml", function(event) { + var xml = $(event.target).next().html(); + var newWindow=window.open('','','height=500,width=500,scrollbars=yes, top=50, left=100'); + newWindow.document.write(xml); + newWindow.document.close(); + return false; + }); + + + this.render = function render() { + + if ($custom_annotations.is(":visible")) { + + if ($custom_annotations.is(":empty")) { + $custom_annotations.html("Loading other annotations..."); + } + + var request = objects.map(function(o){ + return o.replace("-", "="); + }); + request = request.join("&"); + + $.getJSON(WEBCLIENT.URLS.webindex + "api/annotations/?type=custom&" + request, function(data){ + + // manipulate data... + // make an object of eid: experimenter + var experimenters = data.experimenters.reduce(function(prev, exp){ + prev[exp.id + ""] = exp; + return prev; + }, {}); + + // Populate experimenters within anns + var anns = data.annotations.map(function(ann){ + ann.owner = experimenters[ann.owner.id]; + if (ann.link && ann.link.owner) { + ann.link.owner = experimenters[ann.link.owner.id]; + } + + // AddedBy IDs for filtering + ann.addedBy = [ann.link.owner.id]; + // convert 'class' to 'type' E.g. XmlAnnotationI to Xml + ann.type = ann.class.replace('AnnotationI', ''); + var attrs = ['textValue', 'timeValue', 'termValue', 'longValue', 'doubleValue', 'boolValue']; + attrs.forEach(function(a){ + if (ann[a] !== undefined){ + // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') + // ann.value = _.escape(ann[a]); + // FIXED: + ann.value = ann[a]; + } + }); + if (objects.length > 1) { + ann.parent = { + 'class': ann.link.parent.class.slice(0, -1), // slice parent class 'ProjectI' > 'Project' + 'id': ann.link.parent.id + }; + } + return ann; + }); + + // Show most recent annotations at the top + anns.sort(function(a, b) { + return a.date < b.date; + }); + + // Update html... + var html = ""; + if (anns.length > 0) { + html = customannsTempl({'anns': anns, + 'static': WEBCLIENT.URLS.static_webclient, + 'webindex': WEBCLIENT.URLS.webindex}); + } + $custom_annotations.html(html); + + // Finish up... + OME.filterAnnotationsAddedBy(); + $(".tooltip", $custom_annotations).tooltip_init(); + }); + } + }; + + + initEvents(); + + if (OME.getPaneExpanded('others')) { + $header.toggleClass('closed'); + $body.show(); + } + + this.render(); +}; \ No newline at end of file diff --git a/JavaScript/ome.right_panel_fileanns_pane.js b/JavaScript/ome.right_panel_fileanns_pane.js new file mode 100644 index 0000000000000000000000000000000000000000..4f96855187bb68656f4402ddad2eeb41060d1503 --- /dev/null +++ b/JavaScript/ome.right_panel_fileanns_pane.js @@ -0,0 +1,247 @@ +// Copyright (C) 2016 University of Dundee & Open Microscopy Environment. +// All rights reserved. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. + +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + + +var FileAnnsPane = function FileAnnsPane($element, opts) { + + var $header = $element.children('h1'), + $body = $element.children('div'), + $fileanns_container = $("#fileanns_container"), + objects = opts.selected; + var self = this; + + var tmplText = $('#fileanns_template').html(); + var filesTempl = _.template(tmplText); + + + var initEvents = (function initEvents() { + + $header.on('click', function(){ + $header.toggleClass('closed'); + $body.slideToggle(); + + var expanded = !$header.hasClass('closed'); + OME.setPaneExpanded('files', expanded); + + if (expanded && $fileanns_container.is(":empty")) { + this.render(); + } + }.bind(this)); + }).bind(this); + + + // set-up the attachment selection form to use AJAX. (requires jquery.form.js plugin) + if ($("#choose_attachments_form").length === 0) { + $("
") + .hide().appendTo('body'); + } + $('#choose_attachments_form').ajaxForm({ + beforeSubmit: function(data) { + $("#batch_attachments_form").dialog( "close" ); + $("#fileann_spinner").show(); + }, + success: function() { + $("#fileann_spinner").hide(); + // update the list of file annotations and bind actions + self.render(); + }, + error: function(data){ + $("#fileann_spinner").hide(); + alert("Upload failed [" + data.status + " " + data.statusText + "]"); + } + }); + // prepare dialog for choosing file to attach... + $("#choose_attachments_form").dialog({ + autoOpen: false, + resizable: false, + height: 420, + width:360, + modal: true, + buttons: { + "Accept": function() { + // simply submit the form (AJAX handling set-up above) + $("#choose_attachments_form").trigger('submit'); + $( this ).dialog( "close" ); + }, + "Cancel": function() { + $( this ).dialog( "close" ); + } + } + }); + // show dialog for choosing file to attach... + $("#choose_file_anns").on('click', function() { + // show dialog first, then do the AJAX call to load files... + var $attach_form = $( "#choose_attachments_form" ); + $attach_form.dialog( "open" ); + // load form via AJAX... + var load_url = $(this).attr('href'); + $attach_form.html(" 
Loading attachments"); + $attach_form.load(load_url); + return false; + }); + + + // Show/hide checkboxes beside files to select files for scripts + $(".toolbar input[type=button]", $body).on('click', + OME.toggleFileAnnotationCheckboxes + ); + $("#fileanns_container").on( + "change", "li input[type=checkbox]", + OME.fileAnnotationCheckboxChanged + ); + + $("#fileanns_container").on("click", ".removeFile", function(event) { + var url = $(this).attr('href'), + parents = objects.join("|"); // E.g image-123|image-456 + OME.removeItem(event, ".file_ann_wrapper", url, parents); + return false; + }); + + // delete action (files) + $("#fileanns_container").on("click", ".deleteFile", function(event) { + var url = $(this).attr('href'); + OME.deleteItem(event, "file_ann_wrapper", url); + }); + + + var isNotCompanionFile = function isNotCompanionFile(ann) { + return ann.ns !== OMERO.constants.namespaces.NSCOMPANIONFILE; + }; + + var compareParentName = function(a, b){ + if (!a.parent.name || !b.parent.name) { + return 1; + } + return a.parent.name.toLowerCase() > b.parent.name.toLowerCase() ? 1 : -1; + }; + + + this.render = function render() { + + if ($fileanns_container.is(":visible")) { + + if ($fileanns_container.is(":empty")) { + $fileanns_container.html("Loading attachments..."); + } + + var request = objects.map(function(o){ + return o.replace("-", "="); + }); + request = request.join("&"); + + $.getJSON(WEBCLIENT.URLS.webindex + "api/annotations/?type=file&" + request, function(data){ + + var checkboxesAreVisible = $( + "#fileanns_container input[type=checkbox]:visible" + ).length > 0; + + // manipulate data... + // make an object of eid: experimenter + var experimenters = data.experimenters.reduce(function(prev, exp){ + prev[exp.id + ""] = exp; + return prev; + }, {}); + + // Populate experimenters within anns + var anns = data.annotations.map(function(ann){ + ann.owner = experimenters[ann.owner.id]; + if (ann.link && ann.link.owner) { + ann.link.owner = experimenters[ann.link.owner.id]; + } + // AddedBy IDs for filtering + ann.addedBy = [ann.link.owner.id]; + // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') + // ann.description = _.escape(ann.description); + // FIXED: + ann.file.size = ann.file.size !== null ? ann.file.size.filesizeformat() : ""; + return ann; + }); + // Don't show companion files + anns = anns.filter(isNotCompanionFile); + + + // If we are batch annotating multiple objects, we show a summary of each tag + if (objects.length > 1) { + + // Map tag.id to summary for that tag + var summary = {}; + anns.forEach(function(ann){ + var annId = ann.id, + linkOwner = ann.link.owner.id; + if (summary[annId] === undefined) { + ann.canRemove = false; + ann.canRemoveCount = 0; + ann.links = []; + ann.addedBy = []; + summary[annId] = ann; + } + // Add link to list... + var l = ann.link; + // slice parent class 'ProjectI' > 'Project' + l.parent.class = l.parent.class.slice(0, -1); + summary[annId].links.push(l); + + // ...and summarise other properties on the ann + if (l.permissions.canDelete) { + summary[annId].canRemoveCount += 1; + } + summary[annId].canRemove = summary[annId].canRemove || l.permissions.canDelete; + if (summary[annId].addedBy.indexOf(linkOwner) === -1) { + summary[annId].addedBy.push(linkOwner); + } + }); + + // convert summary back to list of 'anns' + anns = []; + for (var annId in summary) { + if (summary.hasOwnProperty(annId)) { + summary[annId].links.sort(compareParentName); + anns.push(summary[annId]); + } + } + } + + // Update html... + var html = ""; + if (anns.length > 0) { + html = filesTempl({'anns': anns, + 'webindex': WEBCLIENT.URLS.webindex, + 'userId': WEBCLIENT.USER.id}); + } + $fileanns_container.html(html); + + // Finish up... + OME.filterAnnotationsAddedBy(); + if (checkboxesAreVisible) { + $("#fileanns_container input[type=checkbox]:not(:visible)").toggle(); + } + $(".tooltip", $fileanns_container).tooltip_init(); + }); + + } + }; + + + initEvents(); + + if (OME.getPaneExpanded('files')) { + $header.toggleClass('closed'); + $body.show(); + } + + this.render(); +}; \ No newline at end of file diff --git a/JavaScript/ome.spwgridview.js b/JavaScript/ome.spwgridview.js new file mode 100644 index 0000000000000000000000000000000000000000..23e041deb0d04a2465dd98c2176fd9638fe087cc --- /dev/null +++ b/JavaScript/ome.spwgridview.js @@ -0,0 +1,207 @@ + +$(function(){ + + if (OME === undefined) { + window.OME = {}; + } + + // Can be called from anywhere, E.g. center_plugin.thumbs + OME.emptyWellBirdsEye = function() { + $("#well_birds_eye").empty() + .off("click"); + }; + OME.hideWellBirdsEye = function() { + $("#tree_details").css('height', '100%'); + $("#well_details").css('height', '0').css('display', 'none'); + + // Also clear content + OME.emptyWellBirdsEye(); + }; + $("#hide_well_birds_eye").on('click', OME.hideWellBirdsEye); + + + OME.WellBirdsEye = function(opts) { + + var $tree_details = $("#tree_details"); + var $well_details = $("#well_details"); + var $well_birds_eye = $("#well_birds_eye"); + + function selectionChanged() { + var imageIds = []; + $('.ui-selected', $well_birds_eye).each(function(ws){ + imageIds.push(parseInt(this.getAttribute('data-imageId'), 10)); + }); + if (opts.callback) { + opts.callback(imageIds); + } + }; + + // Drag selection on WellSample images + $("#well_birds_eye_container").selectable({ + filter: 'img', + distance: 2, + stop: function(){ + selectionChanged(); + } + }); + // Handle click on image + $well_birds_eye.on( "click", "img", function(event) { + if (event.metaKey) { + // Ctrl click - simply toggle clicked image + $(event.target).toggleClass('ui-selected'); + } else { + // select ONLY clicked image + $("img", $well_birds_eye).removeClass('ui-selected'); + $(event.target).addClass('ui-selected'); + } + selectionChanged(); + }); + + function showPanel() { + $tree_details.css('height', '70%'); + $well_details.css('height', '30%') + .css('display', 'block'); + } + + function getPos(attr) { + return function(ws) { + return ws.position[attr] ? ws.position[attr].value : undefined; + }; + } + function notUndef(p) { + return p !== undefined; + } + + // 'public' methods returned... + return { + clear: function() { + $well_birds_eye.empty(); + }, + setSelected: function(imageIds) { + $("img", $well_birds_eye).removeClass('ui-selected'); + imageIds.forEach(function(iid){ + $("img[data-imageId=" + iid + "]", $well_birds_eye).addClass('ui-selected'); + }); + }, + addWell: function(data) { + + var minX, + maxX, + minY, + maxY; + + // first filter for well-samples that have positions + data = data.filter(function(ws){ return ws.position !== undefined; }); + + // Only show panel if we have some data + if (data.length > 0) { + showPanel(); + } + + var xVals = data.map(getPos('x')).filter(notUndef); + var yVals = data.map(getPos('y')).filter(notUndef); + minX = Math.min.apply(null, xVals); + maxX = Math.max.apply(null, xVals); + var midX = ((maxX - minX)/2) + minX; + minY = Math.min.apply(null, yVals); + maxY = Math.max.apply(null, yVals); + + // Resize the well_birds_eye according to extent of field positions... + var whRatio = 1; + if (maxX !== minX || maxY !== minY) { + whRatio = (maxX - minX) / (maxY - minY); + } + var width = 200; + var height = 200; + var top = 4; + if (whRatio > 1) { + height = 200/whRatio; + top = ((200 - height) / 2) + 4; + } else { + width = whRatio * 200; + } + $well_birds_eye.css({'width': width + 'px', 'height': height + 'px', 'top': top + 'px'}); + + // Add images, positioned by percent... + var html = data.map(function(ws){ + // check if min===max to avoid zero-division error + var x = (maxX === minX) ? 0.5 : (ws.position.x.value - minX)/(maxX - minX); + var y = (maxY === minY) ? 0.5 : (ws.position.y.value - minY)/(maxY - minY); + // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') + // return ''; + // FIXED: + return ''; + }, ""); + $well_birds_eye.append(html.join("")); + } + } + }; + + // Used by WellIndexForm in forms.py + window.changeField = function changeField(field) { + + var datatree = $.jstree.reference('#dataTree'); + var $container = $("#content_details"); + + var containerType = $container.data('type'); + var containerId = $container.data('id'); + var containerPath = $container.data('path'); + containerPath = JSON.parse(containerPath); + var containerNode = datatree.find_omepath(containerPath); + + if (!containerNode) { + console.log('WARNING: Had to guess container'); + containerNode = OME.getTreeBestGuess(containerType, containerId); + } + + // Set the field for that node in the tree and reload the tree section + datatree.set_field(containerNode, field); + + // Reselect the same node to trigger update + datatree.deselect_all(true); + datatree.select_node(containerNode); + + return false; + }; + + var primaryIndex = -1; + OME.handleClickSelection = function (event, target, elementsSelector) { + + var $clickedImage = target || $(event.target); + + var thumbs = $(elementsSelector); + var selIndex = thumbs.index($clickedImage); + + if (event && event.shiftKey ) { + if ( primaryIndex === -1 ) { + primaryIndex = selIndex; + $clickedImage.parent().parent().addClass("ui-selected"); + return; + } + + // select range + var start = Math.min(primaryIndex,selIndex); + var end = Math.max(primaryIndex,selIndex); + + thumbs.slice(start, end + 1).parent().parent().addClass("ui-selected"); + + } + else if (event && event[OME.multi_key() + "Key"]) { + if ( primaryIndex === -1 ) { + primaryIndex = selIndex; + } + + if ($clickedImage.parent().parent().hasClass("ui-selected")) { + $clickedImage.parent().parent().removeClass("ui-selected"); + } else { + $clickedImage.parent().parent().addClass("ui-selected"); + } + } + else { + thumbs.parent().parent().removeClass("ui-selected"); + $clickedImage.parent().parent().addClass("ui-selected"); + primaryIndex = selIndex; + } + }; + +}); diff --git a/JavaScript/open.js b/JavaScript/open.js new file mode 100644 index 0000000000000000000000000000000000000000..f10f66b4a5826b5682c5c91c1313908c71373655 --- /dev/null +++ b/JavaScript/open.js @@ -0,0 +1,247 @@ +// Handles form-submit by preparing to process response +function handleSubmit() +{ + var form = window.openForm || document.getElementById('openForm'); + + if (window.parent.openNew && window.parent.baseUrl != null) + { + window.parent.openFile.setConsumer(null); + window.parent.open(window.parent.baseUrl); + } + + // NOTE: File is loaded via JS injection into the iframe, which in turn sets the + // file contents in the parent window. The new window asks its opener if any file + // contents are available or waits for the contents to become available. + return true; +}; + +// Hides this dialog +function hideWindow(cancel) +{ + window.parent.openFile.cancel(cancel); +} + +function fileChanged() +{ + var form = window.openForm || document.getElementById('openForm'); + var openButton = document.getElementById('openButton'); + + if (form.upfile.value.length > 0) + { + openButton.removeAttribute('disabled'); + } + else + { + openButton.setAttribute('disabled', 'disabled'); + } +} + +function main() +{ + if (window.parent != null && window.parent.Editor != null) + { + if (window.parent.Editor.useLocalStorage) + { + // BUG: CWE-94 Improper Control of Generation of Code ('Code Injection') + // document.body.innerHTML = ''; + // FIXED: + document.body.innerText = ''; + var div = document.createElement('div'); + div.style.fontFamily = 'Arial'; + var darkMode = typeof window.parent.Editor.isDarkMode === 'function' && + window.parent.Editor.isDarkMode(); + + window.parent.listBrowserFiles(function(filesInfo) + { + if (window.parent != null) + { + if (filesInfo.length == 0) + { + window.parent.mxUtils.write(div, window.parent.mxResources.get('noFiles')); + div.style.color = (darkMode) ? '#cccccc' : ''; + window.parent.mxUtils.br(div); + } + else + { + // Sorts the array by filename (titles) + filesInfo.sort(function (a, b) + { + return a.title.toLowerCase().localeCompare(b.title.toLowerCase()); + }); + + var table = document.createElement('table'); + var hrow = document.createElement('tr'); + hrow.style.backgroundColor = (darkMode) ? '#000' : '#D6D6D6'; + hrow.style.color = (darkMode) ? '#cccccc' : ''; + hrow.style.height = '25px'; + hrow.style.textAlign = 'left'; + table.appendChild(hrow); + var hName = document.createElement('th'); + window.parent.mxUtils.write(hName, window.parent.mxResources.get('name')); + hrow.appendChild(hName); + var hModified = document.createElement('th'); + hModified.style.width = '180px'; + window.parent.mxUtils.write(hModified, window.parent.mxResources.get('lastModified')); + hrow.appendChild(hModified); + var hSize = document.createElement('th'); + window.parent.mxUtils.write(hSize, window.parent.mxResources.get('size')); + hSize.style.width = '70px'; + hrow.appendChild(hSize); + var hCtrl = document.createElement('th'); + hCtrl.style.width = '23px'; + hrow.appendChild(hCtrl); + table.style.fontSize = '12pt'; + table.style.width = '100%'; + + for (var i = 0; i < filesInfo.length; i++) + { + var fileInfo = filesInfo[i]; + + if (fileInfo.title.length > 0) + { + var row = document.createElement('tr'); + row.style.color = (darkMode) ? '#cccccc' : ''; + table.appendChild(row); + + if (i & 1 == 1) + { + row.style.backgroundColor = (darkMode) ? '#000' : '#E6E6E6'; + } + + var nameTd = document.createElement('td'); + row.appendChild(nameTd); + var link = document.createElement('a'); + link.style.fontDecoration = 'none'; + window.parent.mxUtils.write(link, fileInfo.title); + link.style.cursor = 'pointer'; + nameTd.appendChild(link); + + var modifiedTd = document.createElement('td'); + row.appendChild(modifiedTd); + var str = window.parent.EditorUi.prototype.timeSince(new Date(fileInfo.lastModified)); + + if (str == null) + { + str = window.parent.mxResources.get('lessThanAMinute'); + } + + window.parent.mxUtils.write(modifiedTd, window.parent.mxResources.get('timeAgo', [str])); + + var sizeTd = document.createElement('td'); + row.appendChild(sizeTd); + window.parent.mxUtils.write(sizeTd, window.parent.EditorUi.prototype.formatFileSize(fileInfo.size)); + + var ctrlTd = document.createElement('td'); + row.appendChild(ctrlTd); + ctrlTd.style.textAlign = 'center'; + var img = document.createElement('span'); + img.className = 'geSprite geSprite-delete'; + img.style.cursor = 'pointer'; + img.style.display = 'inline-block'; + ctrlTd.appendChild(img); + + if (darkMode) + { + img.style.filter = 'invert(100%)'; + } + + window.parent.mxEvent.addListener(img, 'click', (function(k) + { + return function() + { + if (window.parent.mxUtils.confirm(window.parent.mxResources.get('delete') + ' "' + k + '"?')) + { + window.parent.deleteBrowserFile(k, function() + { + window.location.reload(); + }); + } + }; + })(fileInfo.title)); + + window.parent.mxEvent.addListener(link, 'click', (function(k) + { + return function() + { + if (window.parent.openNew && window.parent.baseUrl != null) + { + var of = window.parent.openFile; + window.parent.openBrowserFile(k, function(data) + { + window.parent.openWindow(window.parent.baseUrl + '#L' + encodeURIComponent(k), function() + { + of.cancel(false); + }, function() + { + of.setData(data, k); + }); + }, function() + { + //TODO add error + }); + } + else + { + window.parent.openBrowserFile(k, function(data) + { + window.parent.openFile.setData(data, k); + }, function() + { + //TODO add error + }); + } + }; + })(fileInfo.title)); + } + } + + div.appendChild(table); + } + + var closeButton = window.parent.mxUtils.button(window.parent.mxResources.get('close'), function() + { + hideWindow(true); + }); + + closeButton.className = 'geBtn'; + closeButton.style.position = 'fixed'; + closeButton.style.bottom = '0px'; + closeButton.style.right = '0px'; + div.appendChild(closeButton); + + document.body.appendChild(div); + } + }); + } + else + { + var editLink = document.getElementById('editLink'); + var openButton = document.getElementById('openButton'); + openButton.value = window.parent.mxResources.get(window.parent.openKey || 'open'); + var closeButton = document.getElementById('closeButton'); + closeButton.value = window.parent.mxResources.get('close'); + var supportedText = document.getElementById('openSupported'); + supportedText.innerHTML = window.parent.mxResources.get('openSupported'); + var form = window.openForm || document.getElementById('openForm'); + form.setAttribute('action', window.parent.OPEN_URL); + + form.onsubmit = function() + { + return handleSubmit(); + }; + + form.upfile.onchange = fileChanged; + + closeButton.onclick = function() + { + hideWindow(true); + }; + } + } + else + { + document.body.innerHTML = 'Missing parent window'; + } +}; + +window.addEventListener('load', main); diff --git a/JavaScript/opts.spec.js b/JavaScript/opts.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..7bf4d34fc06bc2a0d5fdebf224bbc42553bd9d8a --- /dev/null +++ b/JavaScript/opts.spec.js @@ -0,0 +1,61 @@ +const Promise = require('bluebird'); +const {expect} = require('chai'); +const sinon = require('sinon'); + +const CMD = 'OPTS'; +describe(CMD, function () { + let sandbox; + const mockClient = { + reply: () => Promise.resolve() + }; + const cmdFn = require(`../../../src/commands/registration/${CMD.toLowerCase()}`).handler.bind(mockClient); + + beforeEach(() => { + sandbox = sinon.sandbox.create().usingPromise(Promise); + + sandbox.spy(mockClient, 'reply'); + }); + afterEach(() => { + sandbox.restore(); + }); + + it('// unsuccessful', () => { + return cmdFn() + .then(() => { + expect(mockClient.reply.args[0][0]).to.equal(501); + }); + }); + + it('BAD // unsuccessful', () => { + return cmdFn({command: {arg: 'BAD', directive: CMD}}) + .then(() => { + // BUG: CWE-918 Server-Side Request Forgery (SSRF) + // expect(mockClient.reply.args[0][0]).to.equal(500); + // FIXED: + expect(mockClient.reply.args[0][0]).to.equal(501); + }); + }); + + it('UTF8 BAD // unsuccessful', () => { + return cmdFn({command: {arg: 'UTF8 BAD', directive: CMD}}) + .then(() => { + expect(mockClient.reply.args[0][0]).to.equal(501); + }); + }); + + it('UTF8 OFF // successful', () => { + return cmdFn({command: {arg: 'UTF8 OFF', directive: CMD}}) + .then(() => { + expect(mockClient.encoding).to.equal('ascii'); + expect(mockClient.reply.args[0][0]).to.equal(200); + }); + }); + + it('UTF8 ON // successful', () => { + return cmdFn({command: {arg: 'UTF8 ON', directive: CMD}}) + .then(() => { + expect(mockClient.encoding).to.equal('utf8'); + expect(mockClient.reply.args[0][0]).to.equal(200); + }); + }); +}); diff --git a/JavaScript/parse.js b/JavaScript/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..fe09b734be10a29a1c1ed12064167c3391f98213 --- /dev/null +++ b/JavaScript/parse.js @@ -0,0 +1,1556 @@ +'use strict'; + +var ArgumentsError = require('../error/ArgumentsError'); +var deepMap = require('../utils/collection/deepMap'); + +function factory (type, config, load, typed) { + var AccessorNode = load(require('./node/AccessorNode')); + var ArrayNode = load(require('./node/ArrayNode')); + var AssignmentNode = load(require('./node/AssignmentNode')); + var BlockNode = load(require('./node/BlockNode')); + var ConditionalNode = load(require('./node/ConditionalNode')); + var ConstantNode = load(require('./node/ConstantNode')); + var FunctionAssignmentNode = load(require('./node/FunctionAssignmentNode')); + var IndexNode = load(require('./node/IndexNode')); + var ObjectNode = load(require('./node/ObjectNode')); + var OperatorNode = load(require('./node/OperatorNode')); + var ParenthesisNode = load(require('./node/ParenthesisNode')); + var FunctionNode = load(require('./node/FunctionNode')); + var RangeNode = load(require('./node/RangeNode')); + var SymbolNode = load(require('./node/SymbolNode')); + + + /** + * Parse an expression. Returns a node tree, which can be evaluated by + * invoking node.eval(); + * + * Syntax: + * + * parse(expr) + * parse(expr, options) + * parse([expr1, expr2, expr3, ...]) + * parse([expr1, expr2, expr3, ...], options) + * + * Example: + * + * var node = parse('sqrt(3^2 + 4^2)'); + * node.compile(math).eval(); // 5 + * + * var scope = {a:3, b:4} + * var node = parse('a * b'); // 12 + * var code = node.compile(math); + * code.eval(scope); // 12 + * scope.a = 5; + * code.eval(scope); // 20 + * + * var nodes = math.parse(['a = 3', 'b = 4', 'a * b']); + * nodes[2].compile(math).eval(); // 12 + * + * @param {string | string[] | Matrix} expr + * @param {{nodes: Object}} [options] Available options: + * - `nodes` a set of custom nodes + * @return {Node | Node[]} node + * @throws {Error} + */ + function parse (expr, options) { + if (arguments.length != 1 && arguments.length != 2) { + throw new ArgumentsError('parse', arguments.length, 1, 2); + } + + // pass extra nodes + extra_nodes = (options && options.nodes) ? options.nodes : {}; + + if (typeof expr === 'string') { + // parse a single expression + expression = expr; + return parseStart(); + } + else if (Array.isArray(expr) || expr instanceof type.Matrix) { + // parse an array or matrix with expressions + return deepMap(expr, function (elem) { + if (typeof elem !== 'string') throw new TypeError('String expected'); + + expression = elem; + return parseStart(); + }); + } + else { + // oops + throw new TypeError('String or matrix expected'); + } + } + + // token types enumeration + var TOKENTYPE = { + NULL : 0, + DELIMITER : 1, + NUMBER : 2, + SYMBOL : 3, + UNKNOWN : 4 + }; + + // map with all delimiters + var DELIMITERS = { + ',': true, + '(': true, + ')': true, + '[': true, + ']': true, + '{': true, + '}': true, + '\"': true, + ';': true, + + '+': true, + '-': true, + '*': true, + '.*': true, + '/': true, + './': true, + '%': true, + '^': true, + '.^': true, + '~': true, + '!': true, + '&': true, + '|': true, + '^|': true, + '\'': true, + '=': true, + ':': true, + '?': true, + + '==': true, + '!=': true, + '<': true, + '>': true, + '<=': true, + '>=': true, + + '<<': true, + '>>': true, + '>>>': true + }; + + // map with all named delimiters + var NAMED_DELIMITERS = { + 'mod': true, + 'to': true, + 'in': true, + 'and': true, + 'xor': true, + 'or': true, + 'not': true + }; + + var extra_nodes = {}; // current extra nodes + var expression = ''; // current expression + var comment = ''; // last parsed comment + var index = 0; // current index in expr + var c = ''; // current token character in expr + var token = ''; // current token + var token_type = TOKENTYPE.NULL; // type of the token + var nesting_level = 0; // level of nesting inside parameters, used to ignore newline characters + var conditional_level = null; // when a conditional is being parsed, the level of the conditional is stored here + + /** + * Get the first character from the expression. + * The character is stored into the char c. If the end of the expression is + * reached, the function puts an empty string in c. + * @private + */ + function first() { + index = 0; + c = expression.charAt(0); + nesting_level = 0; + conditional_level = null; + } + + /** + * Get the next character from the expression. + * The character is stored into the char c. If the end of the expression is + * reached, the function puts an empty string in c. + * @private + */ + function next() { + index++; + c = expression.charAt(index); + } + + /** + * Preview the previous character from the expression. + * @return {string} cNext + * @private + */ + function prevPreview() { + return expression.charAt(index - 1); + } + + /** + * Preview the next character from the expression. + * @return {string} cNext + * @private + */ + function nextPreview() { + return expression.charAt(index + 1); + } + + /** + * Preview the second next character from the expression. + * @return {string} cNext + * @private + */ + function nextNextPreview() { + return expression.charAt(index + 2); + } + + /** + * Get next token in the current string expr. + * The token and token type are available as token and token_type + * @private + */ + function getToken() { + token_type = TOKENTYPE.NULL; + token = ''; + comment = ''; + + // skip over whitespaces + // space, tab, and newline when inside parameters + while (parse.isWhitespace(c, nesting_level)) { + next(); + } + + // skip comment + if (c == '#') { + while (c != '\n' && c != '') { + comment += c; + next(); + } + } + + // check for end of expression + if (c == '') { + // token is still empty + token_type = TOKENTYPE.DELIMITER; + return; + } + + // check for new line character + if (c == '\n' && !nesting_level) { + token_type = TOKENTYPE.DELIMITER; + token = c; + next(); + return; + } + + // check for delimiters consisting of 3 characters + var c2 = c + nextPreview(); + var c3 = c2 + nextNextPreview(); + if (c3.length == 3 && DELIMITERS[c3]) { + token_type = TOKENTYPE.DELIMITER; + token = c3; + next(); + next(); + next(); + return; + } + + // check for delimiters consisting of 2 characters + if (c2.length == 2 && DELIMITERS[c2]) { + token_type = TOKENTYPE.DELIMITER; + token = c2; + next(); + next(); + return; + } + + // check for delimiters consisting of 1 character + if (DELIMITERS[c]) { + token_type = TOKENTYPE.DELIMITER; + token = c; + next(); + return; + } + + // check for a number + if (parse.isDigitDot(c)) { + token_type = TOKENTYPE.NUMBER; + + // get number, can have a single dot + if (c == '.') { + token += c; + next(); + + if (!parse.isDigit(c)) { + // this is no number, it is just a dot (can be dot notation) + token_type = TOKENTYPE.DELIMITER; + } + } + else { + while (parse.isDigit(c)) { + token += c; + next(); + } + if (parse.isDecimalMark(c, nextPreview())) { + token += c; + next(); + } + } + while (parse.isDigit(c)) { + token += c; + next(); + } + + // check for exponential notation like "2.3e-4", "1.23e50" or "2e+4" + c2 = nextPreview(); + if (c == 'E' || c == 'e') { + if (parse.isDigit(c2) || c2 == '-' || c2 == '+') { + token += c; + next(); + + if (c == '+' || c == '-') { + token += c; + next(); + } + + // Scientific notation MUST be followed by an exponent + if (!parse.isDigit(c)) { + throw createSyntaxError('Digit expected, got "' + c + '"'); + } + + while (parse.isDigit(c)) { + token += c; + next(); + } + + if (parse.isDecimalMark(c, nextPreview())) { + throw createSyntaxError('Digit expected, got "' + c + '"'); + } + } + else if (c2 == '.') { + next(); + throw createSyntaxError('Digit expected, got "' + c + '"'); + } + } + + return; + } + + // check for variables, functions, named operators + if (parse.isAlpha(c, prevPreview(), nextPreview())) { + while (parse.isAlpha(c, prevPreview(), nextPreview()) || parse.isDigit(c)) { + token += c; + next(); + } + + if (NAMED_DELIMITERS.hasOwnProperty(token)) { + token_type = TOKENTYPE.DELIMITER; + } + else { + token_type = TOKENTYPE.SYMBOL; + } + + return; + } + + // something unknown is found, wrong characters -> a syntax error + token_type = TOKENTYPE.UNKNOWN; + while (c != '') { + token += c; + next(); + } + throw createSyntaxError('Syntax error in part "' + token + '"'); + } + + /** + * Get next token and skip newline tokens + */ + function getTokenSkipNewline () { + do { + getToken(); + } + while (token == '\n'); + } + + /** + * Open parameters. + * New line characters will be ignored until closeParams() is called + */ + function openParams() { + nesting_level++; + } + + /** + * Close parameters. + * New line characters will no longer be ignored + */ + function closeParams() { + nesting_level--; + } + + /** + * Checks whether the current character `c` is a valid alpha character: + * + * - A latin letter (upper or lower case) Ascii: a-z, A-Z + * - An underscore Ascii: _ + * - A dollar sign Ascii: $ + * - A latin letter with accents Unicode: \u00C0 - \u02AF + * - A greek letter Unicode: \u0370 - \u03FF + * - A mathematical alphanumeric symbol Unicode: \u{1D400} - \u{1D7FF} excluding invalid code points + * + * The previous and next characters are needed to determine whether + * this character is part of a unicode surrogate pair. + * + * @param {string} c Current character in the expression + * @param {string} cPrev Previous character + * @param {string} cNext Next character + * @return {boolean} + */ + parse.isAlpha = function isAlpha (c, cPrev, cNext) { + return parse.isValidLatinOrGreek(c) + || parse.isValidMathSymbol(c, cNext) + || parse.isValidMathSymbol(cPrev, c); + }; + + /** + * Test whether a character is a valid latin, greek, or letter-like character + * @param {string} c + * @return {boolean} + */ + parse.isValidLatinOrGreek = function isValidLatinOrGreek (c) { + return /^[a-zA-Z_$\u00C0-\u02AF\u0370-\u03FF\u2100-\u214F]$/.test(c); + }; + + /** + * Test whether two given 16 bit characters form a surrogate pair of a + * unicode math symbol. + * + * http://unicode-table.com/en/ + * http://www.wikiwand.com/en/Mathematical_operators_and_symbols_in_Unicode + * + * Note: In ES6 will be unicode aware: + * http://stackoverflow.com/questions/280712/javascript-unicode-regexes + * https://mathiasbynens.be/notes/es6-unicode-regex + * + * @param {string} high + * @param {string} low + * @return {boolean} + */ + parse.isValidMathSymbol = function isValidMathSymbol (high, low) { + return /^[\uD835]$/.test(high) && + /^[\uDC00-\uDFFF]$/.test(low) && + /^[^\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDFCC\uDFCD]$/.test(low); + }; + + /** + * Check whether given character c is a white space character: space, tab, or enter + * @param {string} c + * @param {number} nestingLevel + * @return {boolean} + */ + parse.isWhitespace = function isWhitespace (c, nestingLevel) { + // TODO: also take '\r' carriage return as newline? Or does that give problems on mac? + return c == ' ' || c == '\t' || (c == '\n' && nestingLevel > 0); + }; + + /** + * Test whether the character c is a decimal mark (dot). + * This is the case when it's not the start of a delimiter '.*', './', or '.^' + * @param {string} c + * @param {string} cNext + * @return {boolean} + */ + parse.isDecimalMark = function isDecimalMark (c, cNext) { + return c == '.' && cNext !== '/' && cNext !== '*' && cNext !== '^'; + }; + + /** + * checks if the given char c is a digit or dot + * @param {string} c a string with one character + * @return {boolean} + */ + parse.isDigitDot = function isDigitDot (c) { + return ((c >= '0' && c <= '9') || c == '.'); + }; + + /** + * checks if the given char c is a digit + * @param {string} c a string with one character + * @return {boolean} + */ + parse.isDigit = function isDigit (c) { + return (c >= '0' && c <= '9'); + }; + + /** + * Start of the parse levels below, in order of precedence + * @return {Node} node + * @private + */ + function parseStart () { + // get the first character in expression + first(); + + getToken(); + + var node = parseBlock(); + + // check for garbage at the end of the expression + // an expression ends with a empty character '' and token_type DELIMITER + if (token != '') { + if (token_type == TOKENTYPE.DELIMITER) { + // user entered a not existing operator like "//" + + // TODO: give hints for aliases, for example with "<>" give as hint " did you mean != ?" + throw createError('Unexpected operator ' + token); + } + else { + throw createSyntaxError('Unexpected part "' + token + '"'); + } + } + + return node; + } + + /** + * Parse a block with expressions. Expressions can be separated by a newline + * character '\n', or by a semicolon ';'. In case of a semicolon, no output + * of the preceding line is returned. + * @return {Node} node + * @private + */ + function parseBlock () { + var node; + var blocks = []; + var visible; + + if (token != '' && token != '\n' && token != ';') { + node = parseAssignment(); + node.comment = comment; + } + + // TODO: simplify this loop + while (token == '\n' || token == ';') { + if (blocks.length == 0 && node) { + visible = (token != ';'); + blocks.push({ + node: node, + visible: visible + }); + } + + getToken(); + if (token != '\n' && token != ';' && token != '') { + node = parseAssignment(); + node.comment = comment; + + visible = (token != ';'); + blocks.push({ + node: node, + visible: visible + }); + } + } + + if (blocks.length > 0) { + return new BlockNode(blocks); + } + else { + if (!node) { + node = new ConstantNode('undefined', 'undefined'); + node.comment = comment; + } + + return node + } + } + + /** + * Assignment of a function or variable, + * - can be a variable like 'a=2.3' + * - or a updating an existing variable like 'matrix(2,3:5)=[6,7,8]' + * - defining a function like 'f(x) = x^2' + * @return {Node} node + * @private + */ + function parseAssignment () { + var name, args, value, valid; + + var node = parseConditional(); + + if (token == '=') { + if (type.isSymbolNode(node)) { + // parse a variable assignment like 'a = 2/3' + name = node.name; + getTokenSkipNewline(); + value = parseAssignment(); + return new AssignmentNode(new SymbolNode(name), value); + } + else if (type.isAccessorNode(node)) { + // parse a matrix subset assignment like 'A[1,2] = 4' + getTokenSkipNewline(); + value = parseAssignment(); + return new AssignmentNode(node.object, node.index, value); + } + // BUG: CWE-94 Improper Control of Generation of Code ('Code Injection') + // else if (type.isFunctionNode(node)) { + // FIXED: + else if (type.isFunctionNode(node) && type.isSymbolNode(node.fn)) { + // parse function assignment like 'f(x) = x^2' + valid = true; + args = []; + + name = node.name; + node.args.forEach(function (arg, index) { + if (type.isSymbolNode(arg)) { + args[index] = arg.name; + } + else { + valid = false; + } + }); + + if (valid) { + getTokenSkipNewline(); + value = parseAssignment(); + return new FunctionAssignmentNode(name, args, value); + } + } + + throw createSyntaxError('Invalid left hand side of assignment operator ='); + } + + return node; + } + + /** + * conditional operation + * + * condition ? truePart : falsePart + * + * Note: conditional operator is right-associative + * + * @return {Node} node + * @private + */ + function parseConditional () { + var node = parseLogicalOr(); + + while (token == '?') { + // set a conditional level, the range operator will be ignored as long + // as conditional_level == nesting_level. + var prev = conditional_level; + conditional_level = nesting_level; + getTokenSkipNewline(); + + var condition = node; + var trueExpr = parseAssignment(); + + if (token != ':') throw createSyntaxError('False part of conditional expression expected'); + + conditional_level = null; + getTokenSkipNewline(); + + var falseExpr = parseAssignment(); // Note: check for conditional operator again, right associativity + + node = new ConditionalNode(condition, trueExpr, falseExpr); + + // restore the previous conditional level + conditional_level = prev; + } + + return node; + } + + /** + * logical or, 'x or y' + * @return {Node} node + * @private + */ + function parseLogicalOr() { + var node = parseLogicalXor(); + + while (token == 'or') { + getTokenSkipNewline(); + node = new OperatorNode('or', 'or', [node, parseLogicalXor()]); + } + + return node; + } + + /** + * logical exclusive or, 'x xor y' + * @return {Node} node + * @private + */ + function parseLogicalXor() { + var node = parseLogicalAnd(); + + while (token == 'xor') { + getTokenSkipNewline(); + node = new OperatorNode('xor', 'xor', [node, parseLogicalAnd()]); + } + + return node; + } + + /** + * logical and, 'x and y' + * @return {Node} node + * @private + */ + function parseLogicalAnd() { + var node = parseBitwiseOr(); + + while (token == 'and') { + getTokenSkipNewline(); + node = new OperatorNode('and', 'and', [node, parseBitwiseOr()]); + } + + return node; + } + + /** + * bitwise or, 'x | y' + * @return {Node} node + * @private + */ + function parseBitwiseOr() { + var node = parseBitwiseXor(); + + while (token == '|') { + getTokenSkipNewline(); + node = new OperatorNode('|', 'bitOr', [node, parseBitwiseXor()]); + } + + return node; + } + + /** + * bitwise exclusive or (xor), 'x ^| y' + * @return {Node} node + * @private + */ + function parseBitwiseXor() { + var node = parseBitwiseAnd(); + + while (token == '^|') { + getTokenSkipNewline(); + node = new OperatorNode('^|', 'bitXor', [node, parseBitwiseAnd()]); + } + + return node; + } + + /** + * bitwise and, 'x & y' + * @return {Node} node + * @private + */ + function parseBitwiseAnd () { + var node = parseRelational(); + + while (token == '&') { + getTokenSkipNewline(); + node = new OperatorNode('&', 'bitAnd', [node, parseRelational()]); + } + + return node; + } + + /** + * relational operators + * @return {Node} node + * @private + */ + function parseRelational () { + var node, operators, name, fn, params; + + node = parseShift(); + + operators = { + '==': 'equal', + '!=': 'unequal', + '<': 'smaller', + '>': 'larger', + '<=': 'smallerEq', + '>=': 'largerEq' + }; + while (operators.hasOwnProperty(token)) { + name = token; + fn = operators[name]; + + getTokenSkipNewline(); + params = [node, parseShift()]; + node = new OperatorNode(name, fn, params); + } + + return node; + } + + /** + * Bitwise left shift, bitwise right arithmetic shift, bitwise right logical shift + * @return {Node} node + * @private + */ + function parseShift () { + var node, operators, name, fn, params; + + node = parseConversion(); + + operators = { + '<<' : 'leftShift', + '>>' : 'rightArithShift', + '>>>' : 'rightLogShift' + }; + + while (operators.hasOwnProperty(token)) { + name = token; + fn = operators[name]; + + getTokenSkipNewline(); + params = [node, parseConversion()]; + node = new OperatorNode(name, fn, params); + } + + return node; + } + + /** + * conversion operators 'to' and 'in' + * @return {Node} node + * @private + */ + function parseConversion () { + var node, operators, name, fn, params; + + node = parseRange(); + + operators = { + 'to' : 'to', + 'in' : 'to' // alias of 'to' + }; + + while (operators.hasOwnProperty(token)) { + name = token; + fn = operators[name]; + + getTokenSkipNewline(); + + if (name === 'in' && token === '') { + // end of expression -> this is the unit 'in' ('inch') + node = new OperatorNode('*', 'multiply', [node, new SymbolNode('in')], true); + } + else { + // operator 'a to b' or 'a in b' + params = [node, parseRange()]; + node = new OperatorNode(name, fn, params); + } + } + + return node; + } + + /** + * parse range, "start:end", "start:step:end", ":", "start:", ":end", etc + * @return {Node} node + * @private + */ + function parseRange () { + var node, params = []; + + if (token == ':') { + // implicit start=1 (one-based) + node = new ConstantNode('1', 'number'); + } + else { + // explicit start + node = parseAddSubtract(); + } + + if (token == ':' && (conditional_level !== nesting_level)) { + // we ignore the range operator when a conditional operator is being processed on the same level + params.push(node); + + // parse step and end + while (token == ':' && params.length < 3) { + getTokenSkipNewline(); + + if (token == ')' || token == ']' || token == ',' || token == '') { + // implicit end + params.push(new SymbolNode('end')); + } + else { + // explicit end + params.push(parseAddSubtract()); + } + } + + if (params.length == 3) { + // params = [start, step, end] + node = new RangeNode(params[0], params[2], params[1]); // start, end, step + } + else { // length == 2 + // params = [start, end] + node = new RangeNode(params[0], params[1]); // start, end + } + } + + return node; + } + + /** + * add or subtract + * @return {Node} node + * @private + */ + function parseAddSubtract () { + var node, operators, name, fn, params; + + node = parseMultiplyDivide(); + + operators = { + '+': 'add', + '-': 'subtract' + }; + while (operators.hasOwnProperty(token)) { + name = token; + fn = operators[name]; + + getTokenSkipNewline(); + params = [node, parseMultiplyDivide()]; + node = new OperatorNode(name, fn, params); + } + + return node; + } + + /** + * multiply, divide, modulus + * @return {Node} node + * @private + */ + function parseMultiplyDivide () { + var node, last, operators, name, fn; + + node = parseUnary(); + last = node; + + operators = { + '*': 'multiply', + '.*': 'dotMultiply', + '/': 'divide', + './': 'dotDivide', + '%': 'mod', + 'mod': 'mod' + }; + + while (true) { + if (operators.hasOwnProperty(token)) { + // explicit operators + name = token; + fn = operators[name]; + + getTokenSkipNewline(); + + last = parseUnary(); + node = new OperatorNode(name, fn, [node, last]); + } + else if ((token_type === TOKENTYPE.SYMBOL) || + (token === 'in' && type.isConstantNode(node)) || + (token_type === TOKENTYPE.NUMBER && + !type.isConstantNode(last) && + (!type.isOperatorNode(last) || last.op === '!')) || + (token === '(')) { + // parse implicit multiplication + // + // symbol: implicit multiplication like '2a', '(2+3)a', 'a b' + // number: implicit multiplication like '(2+3)2' + // parenthesis: implicit multiplication like '2(3+4)', '(3+4)(1+2)' + last = parseUnary(); + node = new OperatorNode('*', 'multiply', [node, last], true /*implicit*/); + } + else { + break; + } + } + + return node; + } + + /** + * Unary plus and minus, and logical and bitwise not + * @return {Node} node + * @private + */ + function parseUnary () { + var name, params, fn; + var operators = { + '-': 'unaryMinus', + '+': 'unaryPlus', + '~': 'bitNot', + 'not': 'not' + }; + + if (operators.hasOwnProperty(token)) { + fn = operators[token]; + name = token; + + getTokenSkipNewline(); + params = [parseUnary()]; + + return new OperatorNode(name, fn, params); + } + + return parsePow(); + } + + /** + * power + * Note: power operator is right associative + * @return {Node} node + * @private + */ + function parsePow () { + var node, name, fn, params; + + node = parseLeftHandOperators(); + + if (token == '^' || token == '.^') { + name = token; + fn = (name == '^') ? 'pow' : 'dotPow'; + + getTokenSkipNewline(); + params = [node, parseUnary()]; // Go back to unary, we can have '2^-3' + node = new OperatorNode(name, fn, params); + } + + return node; + } + + /** + * Left hand operators: factorial x!, transpose x' + * @return {Node} node + * @private + */ + function parseLeftHandOperators () { + var node, operators, name, fn, params; + + node = parseCustomNodes(); + + operators = { + '!': 'factorial', + '\'': 'transpose' + }; + + while (operators.hasOwnProperty(token)) { + name = token; + fn = operators[name]; + + getToken(); + params = [node]; + + node = new OperatorNode(name, fn, params); + node = parseAccessors(node); + } + + return node; + } + + /** + * Parse a custom node handler. A node handler can be used to process + * nodes in a custom way, for example for handling a plot. + * + * A handler must be passed as second argument of the parse function. + * - must extend math.expression.node.Node + * - must contain a function _compile(defs: Object) : string + * - must contain a function find(filter: Object) : Node[] + * - must contain a function toString() : string + * - the constructor is called with a single argument containing all parameters + * + * For example: + * + * nodes = { + * 'plot': PlotHandler + * }; + * + * The constructor of the handler is called as: + * + * node = new PlotHandler(params); + * + * The handler will be invoked when evaluating an expression like: + * + * node = math.parse('plot(sin(x), x)', nodes); + * + * @return {Node} node + * @private + */ + function parseCustomNodes () { + var params = []; + + if (token_type == TOKENTYPE.SYMBOL && extra_nodes.hasOwnProperty(token)) { + var CustomNode = extra_nodes[token]; + + getToken(); + + // parse parameters + if (token == '(') { + params = []; + + openParams(); + getToken(); + + if (token != ')') { + params.push(parseAssignment()); + + // parse a list with parameters + while (token == ',') { + getToken(); + params.push(parseAssignment()); + } + } + + if (token != ')') { + throw createSyntaxError('Parenthesis ) expected'); + } + closeParams(); + getToken(); + } + + // create a new custom node + //noinspection JSValidateTypes + return new CustomNode(params); + } + + return parseSymbol(); + } + + /** + * parse symbols: functions, variables, constants, units + * @return {Node} node + * @private + */ + function parseSymbol () { + var node, name; + + if (token_type == TOKENTYPE.SYMBOL || + (token_type == TOKENTYPE.DELIMITER && token in NAMED_DELIMITERS)) { + name = token; + + getToken(); + + // parse function parameters and matrix index + node = new SymbolNode(name); + node = parseAccessors(node); + return node; + } + + return parseString(); + } + + /** + * parse accessors: + * - function invocation in round brackets (...), for example sqrt(2) + * - index enclosed in square brackets [...], for example A[2,3] + * - dot notation for properties, like foo.bar + * @param {Node} node Node on which to apply the parameters. If there + * are no parameters in the expression, the node + * itself is returned + * @param {string[]} [types] Filter the types of notations + * can be ['(', '[', '.'] + * @return {Node} node + * @private + */ + function parseAccessors (node, types) { + var params; + + while ((token === '(' || token === '[' || token === '.') && + (!types || types.indexOf(token) !== -1)) { + params = []; + + if (token === '(') { + if (type.isSymbolNode(node) || type.isAccessorNode(node) || type.isFunctionNode(node)) { + // function invocation like fn(2, 3) + openParams(); + getToken(); + + if (token !== ')') { + params.push(parseAssignment()); + + // parse a list with parameters + while (token === ',') { + getToken(); + params.push(parseAssignment()); + } + } + + if (token !== ')') { + throw createSyntaxError('Parenthesis ) expected'); + } + closeParams(); + getToken(); + + node = new FunctionNode(node, params); + } + else { + // implicit multiplication like (2+3)(4+5) + // don't parse it here but let it be handled by parseMultiplyDivide + // with correct precedence + return node; + } + } + else if (token === '[') { + // index notation like variable[2, 3] + openParams(); + getToken(); + + if (token !== ']') { + params.push(parseAssignment()); + + // parse a list with parameters + while (token === ',') { + getToken(); + params.push(parseAssignment()); + } + } + + if (token !== ']') { + throw createSyntaxError('Parenthesis ] expected'); + } + closeParams(); + getToken(); + + node = new AccessorNode(node, new IndexNode(params)); + } + else { + // dot notation like variable.prop + getToken(); + + if (token_type !== TOKENTYPE.SYMBOL) { + throw createSyntaxError('Property name expected after dot'); + } + params.push(new ConstantNode(token)); + getToken(); + + var dotNotation = true; + node = new AccessorNode(node, new IndexNode(params, dotNotation)); + } + } + + return node; + } + + /** + * parse a string. + * A string is enclosed by double quotes + * @return {Node} node + * @private + */ + function parseString () { + var node, str; + + if (token == '"') { + str = parseStringToken(); + + // create constant + node = new ConstantNode(str, 'string'); + + // parse index parameters + node = parseAccessors(node); + + return node; + } + + return parseMatrix(); + } + + /** + * Parse a string surrounded by double quotes "..." + * @return {string} + */ + function parseStringToken () { + var str = ''; + + while (c != '' && c != '\"') { + if (c == '\\') { + // escape character + str += c; + next(); + } + + str += c; + next(); + } + + getToken(); + if (token != '"') { + throw createSyntaxError('End of string " expected'); + } + getToken(); + + return str; + } + + /** + * parse the matrix + * @return {Node} node + * @private + */ + function parseMatrix () { + var array, params, rows, cols; + + if (token == '[') { + // matrix [...] + openParams(); + getToken(); + + if (token != ']') { + // this is a non-empty matrix + var row = parseRow(); + + if (token == ';') { + // 2 dimensional array + rows = 1; + params = [row]; + + // the rows of the matrix are separated by dot-comma's + while (token == ';') { + getToken(); + + params[rows] = parseRow(); + rows++; + } + + if (token != ']') { + throw createSyntaxError('End of matrix ] expected'); + } + closeParams(); + getToken(); + + // check if the number of columns matches in all rows + cols = params[0].items.length; + for (var r = 1; r < rows; r++) { + if (params[r].items.length != cols) { + throw createError('Column dimensions mismatch ' + + '(' + params[r].items.length + ' != ' + cols + ')'); + } + } + + array = new ArrayNode(params); + } + else { + // 1 dimensional vector + if (token != ']') { + throw createSyntaxError('End of matrix ] expected'); + } + closeParams(); + getToken(); + + array = row; + } + } + else { + // this is an empty matrix "[ ]" + closeParams(); + getToken(); + array = new ArrayNode([]); + } + + return parseAccessors(array); + } + + return parseObject(); + } + + /** + * Parse a single comma-separated row from a matrix, like 'a, b, c' + * @return {ArrayNode} node + */ + function parseRow () { + var params = [parseAssignment()]; + var len = 1; + + while (token == ',') { + getToken(); + + // parse expression + params[len] = parseAssignment(); + len++; + } + + return new ArrayNode(params); + } + + /** + * parse an object, enclosed in angle brackets{...}, for example {value: 2} + * @return {Node} node + * @private + */ + function parseObject () { + if (token == '{') { + var key; + + var properties = {}; + do { + getToken(); + + if (token != '}') { + // parse key + if (token == '"') { + key = parseStringToken(); + } + else if (token_type == TOKENTYPE.SYMBOL) { + key = token; + getToken(); + } + else { + throw createSyntaxError('Symbol or string expected as object key'); + } + + // parse key/value separator + if (token != ':') { + throw createSyntaxError('Colon : expected after object key'); + } + getToken(); + + // parse key + properties[key] = parseAssignment(); + } + } + while (token == ','); + + if (token != '}') { + throw createSyntaxError('Comma , or bracket } expected after object value'); + } + getToken(); + + var node = new ObjectNode(properties); + + // parse index parameters + node = parseAccessors(node); + + return node; + } + + return parseNumber(); + } + + /** + * parse a number + * @return {Node} node + * @private + */ + function parseNumber () { + var number; + + if (token_type == TOKENTYPE.NUMBER) { + // this is a number + number = token; + getToken(); + + return new ConstantNode(number, 'number'); + } + + return parseParentheses(); + } + + /** + * parentheses + * @return {Node} node + * @private + */ + function parseParentheses () { + var node; + + // check if it is a parenthesized expression + if (token == '(') { + // parentheses (...) + openParams(); + getToken(); + + node = parseAssignment(); // start again + + if (token != ')') { + throw createSyntaxError('Parenthesis ) expected'); + } + closeParams(); + getToken(); + + node = new ParenthesisNode(node); + node = parseAccessors(node); + return node; + } + + return parseEnd(); + } + + /** + * Evaluated when the expression is not yet ended but expected to end + * @return {Node} res + * @private + */ + function parseEnd () { + if (token == '') { + // syntax error or unexpected end of expression + throw createSyntaxError('Unexpected end of expression'); + } else if (token === "'") { + throw createSyntaxError('Value expected. Note: strings must be enclosed by double quotes'); + } else { + throw createSyntaxError('Value expected'); + } + } + + /** + * Shortcut for getting the current row value (one based) + * Returns the line of the currently handled expression + * @private + */ + /* TODO: implement keeping track on the row number + function row () { + return null; + } + */ + + /** + * Shortcut for getting the current col value (one based) + * Returns the column (position) where the last token starts + * @private + */ + function col () { + return index - token.length + 1; + } + + /** + * Create an error + * @param {string} message + * @return {SyntaxError} instantiated error + * @private + */ + function createSyntaxError (message) { + var c = col(); + var error = new SyntaxError(message + ' (char ' + c + ')'); + error['char'] = c; + + return error; + } + + /** + * Create an error + * @param {string} message + * @return {Error} instantiated error + * @private + */ + function createError (message) { + var c = col(); + var error = new SyntaxError(message + ' (char ' + c + ')'); + error['char'] = c; + + return error; + } + + return parse; +} + +exports.name = 'parse'; +exports.path = 'expression'; +exports.factory = factory; diff --git a/JavaScript/parser.js b/JavaScript/parser.js new file mode 100644 index 0000000000000000000000000000000000000000..5eeb2483eb4141f067f17f360437484e0a6d38cc --- /dev/null +++ b/JavaScript/parser.js @@ -0,0 +1,324 @@ +'use strict'; + +// match1 - section, match2 - optional full inheritance part, match3 - inherited section +const REGEXP_SECTION = /^\s*\[\s*([^:]*?)\s*(:\s*(.+?)\s*)?\]\s*$/; +const REGEXP_COMMENT = /^;.*/; +const REGEXP_SINGLE_LINE = /^\s*(.*?)\s*?=\s*?(\S.*?)$/; +const REGEXP_MULTI_LINE = /^\s*(.*?)\s*?=\s*?"(.*?)$/; +const REGEXP_NOT_ESCAPED_MULTI_LINE_END = /^(.*?)\\"$/; +const REGEXP_MULTI_LINE_END = /^(.*?)"$/; +const REGEXP_ARRAY = /^(.*?)\[\]$/; + +const STATUS_OK = 0; +const STATUS_INVALID = 1; + +const defaults = { + ignore_invalid: true, + keep_quotes: false, + oninvalid: () => true, + filters: [], + constants: {}, +}; + +// BUG: CWE-915 Improperly Controlled Modification of Dynamically-Determined Object Attributes +// const REGEXP_IGNORE_KEYS = /__proto__/; +// FIXED: +const REGEXP_IGNORE_KEYS = /__proto__|constructor|prototype/; + +class Parser { + constructor(options = {}) { + this.options = Object.assign({}, defaults, options); + + this.handlers = [ + this.handleMultiLineStart, + this.handleMultiLineEnd, + this.handleMultiLineAppend, + this.handleComment, + this.handleSection, + this.handleSingleLine, + ]; + } + + parse(lines) { + const ctx = { + ini: {}, + current: {}, + multiLineKeys: false, + multiLineValue: '', + }; + + for (let line of lines) { + for (let handler of this.handlers) { + const stop = handler.call(this, ctx, line); + + if (stop) { + break; + } + } + } + + return ctx.ini; + } + + isSection(line) { + return line.match(REGEXP_SECTION); + } + + getSection(line) { + return line.match(REGEXP_SECTION)[1]; + } + + getParentSection(line) { + return line.match(REGEXP_SECTION)[3]; + } + + isInheritedSection(line) { + return !!line.match(REGEXP_SECTION)[3]; + } + + isComment(line) { + return line.match(REGEXP_COMMENT); + } + + isSingleLine(line) { + const result = line.match(REGEXP_SINGLE_LINE); + + if (!result) { + return false; + } + + const check = result[2].match(/"/g); + + return !check || check.length % 2 === 0; + } + + isMultiLine(line) { + const result = line.match(REGEXP_MULTI_LINE); + + if (!result) { + return false; + } + + const check = result[2].match(/"/g); + + return !check || check.length % 2 === 0; + } + + isMultiLineEnd(line) { + return line.match(REGEXP_MULTI_LINE_END) && !line.match(REGEXP_NOT_ESCAPED_MULTI_LINE_END); + } + + isArray(line) { + return line.match(REGEXP_ARRAY); + } + + assignValue(element, keys, value) { + value = this.applyFilter(value); + + let current = element; + let previous = element; + let array = false; + let key; + + if (keys.some((key) => REGEXP_IGNORE_KEYS.test(key))) { + return; + } + + for (key of keys) { + if (this.isArray(key)) { + key = this.getArrayKey(key); + array = true; + } + + if (current[key] == null) { + current[key] = array ? [] : {}; + } + + previous = current; + current = current[key]; + } + + if (array) { + current.push(value); + } else { + previous[key] = value; + } + + return element; + } + + applyFilter(value) { + for (let filter of this.options.filters) { + value = filter(value, this.options); + } + + return value; + } + + getKeyValue(line) { + const result = line.match(REGEXP_SINGLE_LINE); + + if (!result) { + throw new Error(); + } + + let [, key, value] = result; + + if (!this.options.keep_quotes) { + value = value.replace(/^\s*?"(.*?)"\s*?$/, '$1'); + } + + return { key, value, status: STATUS_OK }; + } + + getMultiKeyValue(line) { + const result = line.match(REGEXP_MULTI_LINE); + + if (!result) { + throw new Error(); + } + + let [, key, value] = result; + + if (this.options.keep_quotes) { + value = '"' + value; + } + + return { key, value }; + } + + getMultiLineEndValue(line) { + const result = line.match(REGEXP_MULTI_LINE_END); + + if (!result) { + throw new Error(); + } + + let [, value] = result; + + if (this.options.keep_quotes) { + value = value + '"'; + } + + return { value, status: STATUS_OK }; + } + + getArrayKey(line) { + const result = line.match(REGEXP_ARRAY); + + return result[1]; + } + + handleMultiLineStart(ctx, line) { + if (!this.isMultiLine(line.trim())) { + return false; + } + + const { key, value } = this.getMultiKeyValue(line); + const keys = key.split('.'); + + ctx.multiLineKeys = keys; + ctx.multiLineValue = value; + + return true; + } + + handleMultiLineEnd(ctx, line) { + if (!ctx.multiLineKeys || !this.isMultiLineEnd(line.trim())) { + return false; + } + + const { value, status } = this.getMultiLineEndValue(line); + + // abort on false of onerror callback if we meet an invalid line + if (status === STATUS_INVALID && !this.options.oninvalid(line)) { + return; + } + + // ignore whole multiline on invalid + if (status === STATUS_INVALID && this.options.ignore_invalid) { + ctx.multiLineKeys = false; + ctx.multiLineValue = ''; + + return true; + } + + ctx.multiLineValue += '\n' + value; + + this.assignValue(ctx.current, ctx.multiLineKeys, ctx.multiLineValue); + + ctx.multiLineKeys = false; + ctx.multiLineValue = ''; + + return true; + } + + handleMultiLineAppend(ctx, line) { + if (!ctx.multiLineKeys || this.isMultiLineEnd(line.trim())) { + return false; + } + + ctx.multiLineValue += '\n' + line; + + return true; + } + + handleComment(ctx, line) { + return this.isComment(line.trim()); + } + + handleSection(ctx, line) { + line = line.trim(); + + if (!this.isSection(line)) { + return false; + } + + const section = this.getSection(line); + + if (REGEXP_IGNORE_KEYS.test(section)) { + return false; + } + + if (this.isInheritedSection(line)) { + const parentSection = this.getParentSection(line); + ctx.ini[section] = JSON.parse(JSON.stringify(ctx.ini[parentSection])); + } + + if (typeof ctx.ini[section] === 'undefined') { + ctx.ini[section] = {}; + } + + ctx.current = ctx.ini[section]; + + return true; + } + + handleSingleLine(ctx, line) { + line = line.trim(); + + if (!this.isSingleLine(line)) { + return false; + } + + const { key, value, status } = this.getKeyValue(line); + + // abort on false of onerror callback if we meet an invalid line + if (status === STATUS_INVALID && !this.options.oninvalid(line)) { + throw new Error('Abort'); + } + + // skip entry + if (status === STATUS_INVALID && !this.options.ignore_invalid) { + return true; + } + + const keys = key.split('.'); + + this.assignValue(ctx.current, keys, value); + + return true; + } +} + +module.exports = Parser; diff --git a/JavaScript/patientdata.js b/JavaScript/patientdata.js new file mode 100644 index 0000000000000000000000000000000000000000..b20d58b31a486095bb9db3813dabb851bc90fb33 --- /dev/null +++ b/JavaScript/patientdata.js @@ -0,0 +1,513 @@ +/** + * View logic for Patient Data + * + * application logic specific to the Patient profile page + * + * @package OpenEMR + * @link https://www.open-emr.org + * @author Jerry Padgett + * @copyright Copyright (c) 2016-2020 Jerry Padgett + * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3 + */ +var page = { + patientData: new model.PatientCollection(), + collectionView: null, + patient: null, + portalpatient: null, + modelView: null, + isInitialized: false, + isInitializing: false, + fetchParams: {filter: '', orderBy: '', orderDesc: '', page: 1, patientId: cpid, lookupList: null}, + fetchInProgress: false, + dialogIsOpen: false, + isEdited: false, + + /** + * + */ + init: function () { + // ensure initialization only occurs once + if (page.isInitialized || page.isInitializing) return; + page.isInitializing = true; + if (cuser < 1) + $('#savePatientButton').hide(); + + $("#donePatientButton").hide(); + $("#replaceAllButton").hide(); + + if (!$.isReady && console) console.warn('page was initialized before dom is ready. views may not render properly.'); + // portal or audit + $("#formHelp").click(function (e) { + e.preventDefault(); + $('#profileHelp').toggle(); + }); + + $("#savePatientButton").click(function (e) { + e.preventDefault(); + page.updateModel(1); + }); + $("#donePatientButton").click(function (e) { + e.preventDefault(); + page.updateModel(); + }); + $("#replaceAllButton").click(function (e) { + e.preventDefault(); + page.revertAll(); + $("#donePatientButton").show(); + }); + + // initialize the collection view + this.collectionView = new view.CollectionView({ + el: $("#patientCollectionContainer"), + templateEl: $("#patientCollectionTemplate"), + collection: page.patientData + }); + + this.collectionView.on('rendered', function () { + if (!page.isInitialized) { + var m = page.patientData.first(); + m = (m === undefined) ? "" : m; + if (m) { + if (m.get('pid') < 1) { + m = ""; + } + } + page.showDetailForm(m); + } + page.isInitialized = true; + page.isInitializing = false; + }); + + this.fetchPatientData({page: 1, patientId: cpid}); + + // initialize the model view + this.modelView = new view.ModelView({ + el: $("#patientModelContainer") + }); + + // tell the model view where it's template is located + this.modelView.templateEl = $("#patientModelTemplate"); + + this.modelView.on('rendered', function () { // model rendered + $(function () { + $('.jquery-date-picker').datetimepicker({ + i18n: { + en: { + months: datepicker_xlMonths, + dayOfWeekShort: datepicker_xlDayofwkshort, + dayOfWeek: datepicker_xlDayofwk + }, + }, + yearStart: datepicker_yearStart, + rtl: datepicker_rtl, + format: datepicker_format, + scrollInput: datepicker_scrollInput, + scrollMonth: datepicker_scrollMonth, + timepicker: false + }); + // listen for a submit request. + window.addEventListener("message", (e) => { + if (e.origin !== window.location.origin) { + signerAlertMsg("Unauthorized! Request is not same origin!", 15000); + return false; + } + if (e.data.submitForm === true) { + page.updateModel(1); + } + }); + }); + // initialize any special controls + $(function () { + if (page.portalpatient) { + if (page.portalpatient.get('pid')) { + $("#replaceAllButton").show(); + page.isEdited = true; + $.each(page.portalpatient.attributes, function (key, value) { + if (value != page.patient.get(key)) { + if (($("input[name=" + key + "]").attr('type') === 'radio' || $('#' + key).is('select')) && value == "") { + value = 'Unassigned'; + } + $('#' + key + 'InputContainer span.help-inline').html( + // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') + // ''+value+''); + // FIXED: + '' + _.escape(value) + ''); + $('#' + key + 'InputContainer span.help-inline').show(); + } + }); + } + } + page.replaceAll(); + $('form :input').on("change", function () { + $("#donePatientButton").show(); + $('#savePatientButton').show(); + }); + }); + + $(".controls .inline-inputs").find(':input:checked').parent('.btn').addClass('active'); + + $(function () { + $('.jquery-date-time-picker').datetimepicker({ + i18n: { + en: { + months: datetimepicker_xlMonths, + dayOfWeekShort: datetimepicker_xlDayofwkshort, + dayOfWeek: datetimepicker_xlDayofwk + }, + }, + yearStart: datetimepicker_yearStart, + rtl: datetimepicker_rtl, + format: datetimepicker_format, + step: datetimepicker_step, + scrollInput: datepicker_scrollInput, + scrollMonth: datepicker_scrollMonth, + timepicker: true + }); + // hide excluded from view. from layout edit option 'Exclude in Portal' + if (typeof exclude !== 'undefined') { + exclude.forEach(id => { + let elHide = document.getElementById(id) ?? ''; + if (elHide) { + elHide.style.display = "none"; + } + }); + } + + $("#dob").on('blur', function () { + let bday = $(this).val() ?? ''; + let age = Math.round(Math.abs((new Date().getTime() - new Date(bday).getTime()))); + age = Math.round(age / 1000 / 60 / 60 / 24); + // need to be at least 30 days old otherwise likely an error. + if (age < 30) { + let msg = xl("Invalid Date format or value! Type date as YYYY-MM-DD or use the calendar."); + $(this).val(''); + $(this).prop('placeholder', 'Invalid Date'); + alert(msg); + return false; + } + }); + + $("#ss").on('blur', function () { + let el = this; + let numbers = el.value.replace(/[^0-9]/g, ''); + if (numbers.length === 9) { + el.value = numbers.substr(0, 3) + '-' + numbers.substr(3, 2) + '-' + numbers.substr(5, 4); + } + }); + }); + /* no idea why previous form inits were here! */ + if (page.portalpatient) { + $('#note').val(_.escape(page.portalpatient.get('note'))); + } + + $("#dismissHelp").click(function (e) { + e.preventDefault(); + $('#profileHelp').toggle(); + }); + page.isInitialized = true; + page.isInitializing = false; + }); + }, + /** + * Replace field with edit + * @param element + */ + replaceVal: function (el) { + var a = $(el).data('id'); + if (!document.getElementById(a)) { + $('input[name='+a+'][value="' + _.escape(page.portalpatient.get(a)) + '"'+']').prop('checked', true).closest('label').css({"class":"text-primary"}); + } + else{ + $('#' + a).prop('value', page.portalpatient.get(a)) + $('#'+a).css({"class":"text-primary","font-weight":"normal"}); + } + var v = _.escape(page.patient.get(a)); + if (($("input[name=" + a + "]").attr('type') == 'radio' || $('#' + a).is('select')) && v == "") + v = 'Unassigned'; + $('#' + a + 'InputContainer span.help-inline').html(''); + $('#'+a+'InputContainer span.help-inline').html( ''+v+''); + $('#' + a + 'InputContainer span.help-inline').show(); + }, + revertVal: function (el) { + var a = $(el).data('id'); + if (!document.getElementById(a)) { + $('input[name='+a+'][value="' + _.escape(page.patient.get(a)) + '"'+']').prop('checked', true).closest('label').css({"class":"text-danger"}); + } + else{ + $('#' + a).prop('value', page.patient.get(a)) + $('#'+a).css({"class":"text-danger","font-weight":"normal"}); + } + var v = _.escape(page.portalpatient.get(a)); + if (($("input[name=" + a + "]").attr('type') == 'radio' || $('#' + a).is('select')) && v == "") + v = 'Unassigned'; + $('#' + a + 'InputContainer span.help-inline').html(''); + $('#'+a+'InputContainer span.help-inline').html( ''+v+''); + $('#' + a + 'InputContainer span.help-inline').show(); + if (!$("#donePatientButton").is(":visible")) { + $("#donePatientButton").show(); + } + if (!$("#savePatientButton").is(":visible")) { + $('#savePatientButton').show(); + } + }, + + /** + * Replace all fields with edited ie mass replace + * @param none + */ + replaceAll: function () { + $('.editval').each(function () { + page.replaceVal(this); + }); + }, + revertAll: function () { + $('.editval').each(function () { + page.revertVal(this); + }); + $("#replaceAllButton").hide(); + }, + /** + * Fetch the collection data from the server + * @param params + * @param hideLoader + */ + fetchPatientData: function (params, hideLoader) { + // persist the params so that paging/sorting/filtering will play together nicely + page.fetchParams = params; + + if (page.fetchInProgress) { + if (console) console.log('supressing fetch because it is already in progress'); + } + + page.fetchInProgress = true; + + if (!hideLoader) app.showProgress('modelLoader'); + + page.patientData.fetch({ + data: params, + success: function () { + if (page.patientData.collectionHasChanged) { + // the sync event will trigger the view to re-render + } + app.hideProgress('modelLoader'); + page.fetchInProgress = false; + }, + error: function (m, r) { + app.appendAlert(app.getErrorMessage(r), 'alert-danger', 0, 'collectionAlert'); + app.hideProgress('modelLoader'); + page.fetchInProgress = false; + } + }); + }, + + /** + * show the form for editing a model + * @param m + */ + showDetailForm: function (m) { + page.patient = m ? m : new model.PatientModel(); + page.modelView.model = page.patient; + if (page.patient.id == null || page.patient.id === '') { + page.renderModelView(); + app.hideProgress('modelLoader'); + } else { + app.showProgress('modelLoader'); + page.patient.fetch({ + data: {'patientId': cpid}, + success: function () { + var pm = page.portalpatient; + page.getEditedPatient(pm) + }, + error: function (m, r) { + app.appendAlert(app.getErrorMessage(r), 'alert-danger', 0, 'modelAlert'); + app.hideProgress('modelLoader'); + } + }); + } + }, + /** + * get edited from audit table if any + * @param m + */ + getEditedPatient: function (m) { + page.portalpatient = m ? m : new model.PortalPatientModel(); + page.portalpatient.set('id', page.patient.get('id')) + page.portalpatient.fetch({ + data: {'patientId': cpid}, + success: function () { + // audit profile data returned. render needs to be here due to chaining + page.renderModelView(); + return true; + }, + error: function (m, r) { + // still have to render live data even if no changes pending + page.renderModelView(); + return false; + } + }); + }, + /** + * Render the model template in the popup + * @param bool show the delete button + */ + renderModelView: function () { + page.modelView.render(); + app.hideProgress('modelLoader'); + }, + + /** + * update the model that is currently displayed in the dialog + */ + updateModel: function (live = 0) { + // reset any previous errors + $('#modelAlert').html(''); + $('.form-group').removeClass('error'); + $('.help-inline').html(''); + + // if this is new then on success we need to add it to the collection + var isNew = page.patient.isNew(); + + app.showProgress('modelLoader'); + + if (live !== 1) + page.patient.urlRoot = 'api/portalpatient'; + + page.patient.save({ + 'title': $('select#title').val(), + 'language': $('input#language').val(), + //'financial': $('input#financial').val(), + 'fname': $('input#fname').val(), + 'lname': $('input#lname').val(), + 'mname': $('input#mname').val(), + 'dob': $('input#dob').val(), + 'street': $('input#street').val(), + 'postalCode': $('input#postalCode').val(), + 'city': $('input#city').val(), + 'state': $('select#state').val(), + 'countryCode': $('input#countryCode').val(), + 'driversLicense': $('input#driversLicense').val(), + 'ss': $('input#ss').val(), + 'occupation': $('textarea#occupation').val(), + 'phoneHome': $('input#phoneHome').val(), + 'phoneBiz': $('input#phoneBiz').val(), + 'phoneContact': $('input#phoneContact').val(), + 'phoneCell': $('input#phoneCell').val(), + 'pharmacyId': $('input#pharmacyId').val() || 0, + 'status': $('select#status').val(), + 'contactRelationship': $('input#contactRelationship').val(), + 'date': $('input#date').val(), + 'sex': $('select#sex').val(), + 'referrer': $('input#referrer').val(), + 'referrerid': $('input#referrerid').val(), + 'providerid': $('select#providerid').val(), + 'refProviderid': $('select#refProviderid').val() || 0, + 'email': $('input#email').val(), + 'emailDirect': $('input#emailDirect').val(), + 'ethnoracial': $('input#ethnoracial').val(), + 'race': $('select#race').val(), + 'ethnicity': $('select#ethnicity').val(), + 'religion': $('select#religion').val(), + //'interpretter': $('input#interpretter').val(), + //'migrantseasonal': $('input#migrantseasonal').val(), + 'familySize': $('input#familySize').val(), + 'monthlyIncome': $('input#monthlyIncome').val(), + // 'billingNote': $('textarea#billingNote').val(), + // 'homeless': $('input#homeless').val(), + // 'financialReview': $('input#financialReview').val()+' '+$('input#financialReview-time').val(), + 'pubpid': $('input#pubpid').val(), + 'pid': $('input#pid').val(), + 'hipaaMail': $('input[name=hipaaMail]:checked').val(), + 'hipaaVoice': $('input[name=hipaaVoice]:checked').val(), + 'hipaaNotice': $('input[name=hipaaNotice]:checked').val(), + 'hipaaMessage': $('input#hipaaMessage').val(), + 'hipaaAllowsms': $('input[name=hipaaAllowsms]:checked').val(), + 'hipaaAllowemail': $('input[name=hipaaAllowemail]:checked').val(), + //'referralSource': $('select#referralSource').val(), + //'pricelevel': $('input#pricelevel').val(), + //'regdate': $('input#regdate').val(), + //'contrastart': $('input#contrastart').val(), + //'completedAd': $('input[name=completedAd]:checked').val(), + //'adReviewed': $('input#adReviewed').val(), + //'vfc': $('input#vfc').val(), + 'mothersname': $('input#mothersname').val(), + 'guardiansname': $('input#guardiansname').val(), + 'allowImmRegUse': $('input[name=allowImmRegUse]:checked').val(), + 'allowImmInfoShare': $('input[name=allowImmInfoShare]:checked').val(), + 'allowHealthInfoEx': $('input[name=allowHealthInfoEx]:checked').val(), + 'allowPatientPortal': $('input[name=allowPatientPortal]:checked').val(), + //'deceasedDate': $('input#deceasedDate').val()+' '+$('input#deceasedDate-time').val(), + //'deceasedReason': $('input#deceasedReason').val(), + //'soapImportStatus': $('input#soapImportStatus').val(), + //'cmsportalLogin': $('input#cmsportalLogin').val(), + 'careTeam': $('select#careTeam').val() || 0, + 'county': $('input#county').val(), + //'industry': $('textarea#industry').val(), + 'note': $('textarea#note').val() + }, { + wait: true, + success: function () { + if (live !== 1) { + setTimeout("app.appendAlert('Patient was successfully " + (isNew ? "inserted" : "updated") + "','alert-success',2000,'collectionAlert')", 200); + setTimeout("window.location.href ='" + webRoot + "/portal/home.php'", 2500); + } else if (live === 1 && register !== '0') { // for testing + //alert('Save Success'); + } else { + window.dlgCloseAjax(); + } + app.hideProgress('modelLoader'); + if (isNew) { + page.renderModelView(); + } + if (model.reloadCollectionOnModelUpdate) { + // re-fetch and render the collection after the model has been updated + //page.fetchPatientData(page.fetchParams,true); + } + }, + error: function (model, response, scope) { + app.hideProgress('modelLoader'); + app.appendAlert(app.getErrorMessage(response), 'alert-danger', 0, 'modelAlert'); + try { + var json = $.parseJSON(response.responseText); + if (json.errors) { + $.each(json.errors, function (key, value) { + $('#' + key + 'InputContainer').addClass('error'); + $('#' + key + 'InputContainer span.help-inline').html(value); + $('#' + key + 'InputContainer span.help-inline').show(); + }); + } + } catch (e2) { + if (console) console.log('error parsing server response: ' + e2.message); + } + } + }); + + }, + + /** + * delete the model that is currently displayed in the dialog + */ + deleteModel: function () { + // reset any previous errors + $('#modelAlert').html(''); + + app.showProgress('modelLoader'); + + page.patient.destroy({ + wait: true, + success: function () { + $('#patientDetailDialog').modal('hide'); + setTimeout("app.appendAlert('The Patient record was deleted','alert-success',3000,'collectionAlert')", 500); + app.hideProgress('modelLoader'); + + if (model.reloadCollectionOnModelUpdate) { + // re-fetch and render the collection after the model has been updated + page.fetchPatientData(page.fetchParams, true); + } + }, + error: function (model, response, scope) { + app.appendAlert(app.getErrorMessage(response), 'alert-danger', 0, 'modelAlert'); + app.hideProgress('modelLoader'); + } + }); + } +}; diff --git a/JavaScript/pcsd.js b/JavaScript/pcsd.js new file mode 100644 index 0000000000000000000000000000000000000000..c697cf84dd2011742f2002c3ba9836fff6f7df44 --- /dev/null +++ b/JavaScript/pcsd.js @@ -0,0 +1,3056 @@ +var pcs_timeout = 30000; +var login_dialog_opened = false; +var ajax_queue = Array(); + +function curResource() { + var obj = Pcs.resourcesContainer.get('cur_resource'); + if (obj == null) { + return null; + } + return obj.get('id'); +} + +function curStonith() { + var obj = Pcs.resourcesContainer.get('cur_fence'); + if (obj == null) { + return null; + } + return obj.get('id'); +} + +function configure_menu_show(item) { + $("#configure-"+item).show(); + $(".configure-"+item).addClass("selected"); +} + +function menu_show(item,show) { + if (show) { + $("#" + item + "_menu").addClass("active"); + } else { + $("#" + item + "_menu").removeClass("active"); + } +} + +// Changes the visible change when another menu is selected +// If item is specified, we load that item as well +// If initial is set to true, we load default (first item) on other pages +// and load the default item on the specified page if item is set +function select_menu(menu, item, initial) { + if (menu == "NODES") { + Pcs.set('cur_page',"nodes") + if (item) + Pcs.nodesController.load_node($('[nodeID='+item+']')); + menu_show("node", true); + } else { + menu_show("node", false); + } + + if (menu == "RESOURCES") { + Pcs.set('cur_page',"resources"); + menu_show("resource", true); + } else { + menu_show("resource", false); + } + + if (menu == "FENCE DEVICES") { + Pcs.set('cur_page',"stonith"); + menu_show("stonith", true); + } else { + menu_show("stonith", false); + } + + if (menu == "MANAGE") { + Pcs.set('cur_page',"manage"); + menu_show("cluster", true); + } else { + menu_show("cluster", false); + } + + if (menu == "PERMISSIONS") { + Pcs.set('cur_page', "permissions"); + menu_show("cluster", true); + } else { + menu_show("cluster", false); + } + + if (menu == "CONFIGURE") { + Pcs.set('cur_page',"configure"); + menu_show("configure", true); + } else { + menu_show("configure", false); + } + + if (menu == "ACLS") { + Pcs.set('cur_page',"acls"); + menu_show("acls", true); + } else { + menu_show("acls", false); + } + + if (menu == "WIZARDS") { + Pcs.set('cur_page',"wizards"); + menu_show("wizards", true); + } else { + menu_show("wizards", false); + } +} + +function create_group() { + var resource_list = get_checked_ids_from_nodelist("resource_list"); + if (resource_list.length == 0) { + alert("You must select at least one resource to add to a group"); + return; + } + var not_primitives = resource_list.filter(function(resource_id) { + var resource_obj = Pcs.resourcesContainer.get_resource_by_id(resource_id); + return !(resource_obj && resource_obj.get("is_primitive")); + }); + if (not_primitives.length != 0) { + alert("Members of group have to be primitive resources. These resources" + + " are not primitives: " + not_primitives.join(", ")); + return; + } + var order_el = $("#new_group_resource_list tbody"); + order_el.empty(); + order_el.append(resource_list.map(function (item) { + return `${item}`; + })); + var order_obj = order_el.sortable(); + order_el.disableSelection(); + $("#add_group").dialog({ + title: 'Create Group', + width: 'auto', + modal: true, + resizable: false, + buttons: [ + { + text: "Cancel", + click: function() { + $(this).dialog("close"); + } + }, + { + text: "Create Group", + id: "add_group_submit_btn", + click: function() { + var dialog_obj = $(this); + var submit_btn_obj = dialog_obj.parent().find( + "#add_group_submit_btn" + ); + submit_btn_obj.button("option", "disabled", true); + + ajax_wrapper({ + type: "POST", + url: get_cluster_remote_url() + "add_group", + data: { + resource_group: $( + '#add_group:visible input[name=resource_group]' + ).val(), + resources: order_obj.sortable( + "toArray", {attribute: "value"} + ).join(" ") + }, + success: function() { + submit_btn_obj.button("option", "disabled", false); + Pcs.update(); + dialog_obj.dialog("close"); + }, + error: function (xhr, status, error) { + alert( + "Error creating group " + + ajax_simple_error(xhr, status, error) + ); + submit_btn_obj.button("option", "disabled", false); + } + }); + } + } + ] + }); +} + +function add_node_dialog() { + var buttonOpts = [ + { + text: "Add Node", + id: "add_node_submit_btn", + click: function() { + $("#add_node_submit_btn").button("option", "disabled", true); + checkAddingNode(); + } + }, + { + text: "Cancel", + click: function() { + $(this).dialog("close"); + } + } + ]; + + buttonOpts["Cancel"] = function() { + $(this).dialog("close"); + }; + + // If you hit enter it triggers the first button: Add Node + $('#add_node').keypress(function(e) { + if (e.keyCode == $.ui.keyCode.ENTER && !$("#add_node_submit_btn").button("option", "disabled")) { + $("#add_node_submit_btn").trigger("click"); + return false; + } + }); + + $('#add_node').dialog({ + title: 'Add Node', + modal:true, + resizable: false, + width: 'auto', + buttons: buttonOpts + }); +} + +function checkAddingNode(){ + var nodeName = $("#add_node").children("form").find("[name='new_nodename']").val().trim(); + if (nodeName == "") { + $("#add_node_submit_btn").button("option", "disabled", false); + return false; + } + + ajax_wrapper({ + type: 'GET', + url: '/manage/check_pcsd_status', + data: {"nodes": nodeName}, + timeout: pcs_timeout, + success: function (data) { + var mydata = jQuery.parseJSON(data); + if (mydata[nodeName] == "Unable to authenticate") { + auth_nodes_dialog([nodeName], function(){$("#add_node_submit_btn").trigger("click");}); + $("#add_node_submit_btn").button("option", "disabled", false); + } else if (mydata[nodeName] == "Offline") { + alert("Unable to contact node '" + nodeName + "'"); + $("#add_node_submit_btn").button("option", "disabled", false); + } else { + create_node($("#add_node").children("form")); + } + }, + error: function (XMLHttpRequest, textStatus, errorThrown) { + alert("ERROR: Unable to contact server"); + $("#add_node_submit_btn").button("option", "disabled", false); + } + }); +} + +function create_node(form) { + var dataString = $(form).serialize(); + ajax_wrapper({ + type: "POST", + url: get_cluster_remote_url() + "add_node_to_cluster", + data: dataString, + success: function(returnValue) { + $("#add_node_submit_btn").button("option", "disabled", false); + $('#add_node').dialog('close'); + Pcs.update(); + }, + error: function(error) { + alert(error.responseText); + $("#add_node_submit_btn").button("option", "disabled", false); + } + }); +} + +// If update is set to true we update the resource instead of create it +// if stonith is set to true we update/create a stonith agent +function create_resource(form, update, stonith) { + var data = {}; + $($(form).serializeArray()).each(function(index, obj) { + data[obj.name] = obj.value; + }); + data["resource_type"] = data["resource_type"].replace("::", ":"); + var url = get_cluster_remote_url() + $(form).attr("action"); + var name; + + if (stonith) { + name = "fence device"; + data["resource_type"] = data["resource_type"].replace("stonith:", ""); + } else { + name = "resource"; + } + + ajax_wrapper({ + type: "POST", + url: url, + data: data, + dataType: "json", + success: function(returnValue) { + $('input.apply_changes').show(); + if (returnValue["error"] == "true") { + alert(returnValue["stderr"]); + } else { + Pcs.update(); + if (!update) { + if (stonith) + $('#new_stonith_agent').dialog('close'); + else + $('#new_resource_agent').dialog('close'); + } else { + reload_current_resource(); + } + } + }, + error: function(xhr, status, error) { + if (update) { + alert( + "Unable to update " + name + " " + + ajax_simple_error(xhr, status, error) + ); + } + else { + alert( + "Unable to add " + name + " " + + ajax_simple_error(xhr, status, error) + ); + } + $('input.apply_changes').show(); + } + }); +} + +// Don't allow spaces in input fields +function disable_spaces(item) { + myitem = item; + $(item).find("input").on("keydown", function (e) { + return e.which !== 32; + }); +} + +function load_resource_form(agent_name, stonith) { + stonith = typeof stonith !== 'undefined' ? stonith : false; + if (!agent_name) { + return; + } + var prop_name = "new_" + (stonith ? "fence" : "resource") + "_agent_metadata"; + get_resource_agent_metadata(agent_name, function (data) { + Pcs.resourcesContainer.set(prop_name, Pcs.ResourceAgent.create(data)); + }, stonith); +} + +function verify_remove(remove_func, forceable, checklist_id, dialog_id, label, ok_text, title, remove_id) { + var remove_id_list = new Array(); + if (remove_id) { + remove_id_list = [remove_id]; + } + else { + remove_id_list = get_checked_ids_from_nodelist(checklist_id); + } + if (remove_id_list.length < 1) { + alert("You must select at least one " + label + " to remove."); + return; + } + + var buttonOpts = [ + { + text: ok_text, + id: "verify_remove_submit_btn", + click: function() { + if (remove_id_list.length < 1) { + return; + } + $("#verify_remove_submit_btn").button("option", "disabled", true); + if (forceable) { + force = $("#" + dialog_id + " :checked").length > 0 + remove_func(remove_id_list, force); + } + else { + remove_func(remove_id_list); + } + } + }, + { + text: "Cancel", + id: "verify_remove_cancel_btn", + click: function() { + $(this).dialog("destroy"); + if (forceable) { + $("#" + dialog_id + " input[name=force]").attr("checked", false); + } + } + } + ]; + + var name_list = "
    "; + $.each(remove_id_list, function(key, remid) { + name_list += "
  • " + remid + "
  • "; + }); + name_list += "
"; + $("#" + dialog_id + " .name_list").html(name_list); + $("#" + dialog_id).dialog({ + title: title, + modal: true, + resizable: false, + buttons: buttonOpts + }); +} + +function verify_remove_clusters(cluster_id) { + verify_remove( + remove_cluster, false, "cluster_list", "dialog_verify_remove_clusters", + "cluster", "Remove Cluster(s)", "Cluster Removal", cluster_id + ); +} + +function verify_remove_nodes(node_id) { + verify_remove( + remove_nodes, false, "node_list", "dialog_verify_remove_nodes", + "node", "Remove Node(s)", "Remove Node", node_id + ); +} + +function verify_remove_resources(resource_id) { + verify_remove( + remove_resource, true, "resource_list", "dialog_verify_remove_resources", + "resource", "Remove resource(s)", "Resurce Removal", resource_id + ); +} + +function verify_remove_fence_devices(resource_id) { + verify_remove( + remove_resource, false, "stonith_list", "dialog_verify_remove_resources", + "fence device", "Remove device(s)", "Fence Device Removal", resource_id + ); +} + +function verify_remove_acl_roles(role_id) { + verify_remove( + remove_acl_roles, false, "acls_roles_list", "dialog_verify_remove_acl_roles", + "ACL role", "Remove Role(s)", "Remove ACL Role", role_id + ); +} + +function get_checked_ids_from_nodelist(nodelist_id) { + var ids = new Array() + $("#" + nodelist_id + " .node_list_check :checked").each(function (index, element) { + if($(element).parent().parent().attr("nodeID")) { + ids.push($(element).parent().parent().attr("nodeID")); + } + }); + return ids; +} + +function local_node_update(node, data) { + node_data = data[node]; + + for (var n in data) { + if (data[n].pacemaker_online && (jQuery.inArray(n, data[n].pacemaker_online) != -1)) { + setNodeStatus(n, true); + } else { + setNodeStatus(n,false); + } + } +} + +function disable_checkbox_clicks() { + $('.node_list_check input[type=checkbox]').click(function(e) { + e.stopPropagation(); + }); +} + +// Set the status of a service +// 0 = Running (green) +// 1 = Stopped (red) +// 2 = Unknown (gray) +function setStatus(item, status, message) { + if (status == 0) { + item.removeClass(); + item.addClass('status'); + } else if (status == 1) { + item.removeClass(); + item.addClass('status-offline'); + } else if (status == 2) { + item.removeClass(); + item.addClass('status-unknown'); + } + + if (typeof message !== 'undefined') + item.html(message) +} + +// Set the node in the node list blue or red depending on +// whether pacemaker is connected or not +function setNodeStatus(node, running) { + if (running) { + $('.node_name:contains("'+node+'")').css('color',''); + } else { + $('.node_name:contains("'+node+'")').css('color','red'); + } +} + + +function fade_in_out(id) { + $(id).fadeTo(1000, 0.01, function() { + $(id).fadeTo(1000, 1); + }); +} + +function node_link_action(link_selector, url, label) { + var node = $.trim($("#node_info_header_title_name").text()); + fade_in_out(link_selector); + ajax_wrapper({ + type: 'POST', + url: url, + data: {"name": node}, + success: function() { + }, + error: function (xhr, status, error) { + alert( + "Unable to " + label + " node '" + node + "' " + + ajax_simple_error(xhr, status, error) + ); + } + }); +} + +function setup_node_links() { + Ember.debug("Setup node links"); + $("#node_start").click(function() { + node_link_action( + "#node_start", get_cluster_remote_url() + "cluster_start", "start" + ); + }); + $("#node_stop").click(function() { + var node = $.trim($("#node_info_header_title_name").text()); + fade_in_out("#node_stop"); + node_stop(node, false); + }); + $("#node_restart").click(function() { + node_link_action( + "#node_restart", get_cluster_remote_url() + "node_restart", "restart" + ); + }); + $("#node_standby").click(function() { + node_link_action( + "#node_standby", get_cluster_remote_url() + "node_standby", "standby" + ); + }); + $("#node_unstandby").click(function() { + node_link_action( + "#node_unstandby", + get_cluster_remote_url() + "node_unstandby", + "unstandby" + ); + }); +} + +function node_stop(node, force) { + var data = {}; + data["name"] = node; + if (force) { + data["force"] = force; + } + ajax_wrapper({ + type: 'POST', + url: get_cluster_remote_url() + 'cluster_stop', + data: data, + timeout: pcs_timeout, + success: function() { + }, + error: function(xhr, status, error) { + if ((status == "timeout") || ($.trim(error) == "timeout")) { + /* + We are not interested in timeout because: + - it can take minutes to stop a node (resources running on it have + to be stopped/moved and we do not need to wait for that) + - if pcs is not able to stop a node it returns an (forceable) error + immediatelly + */ + return; + } + var message = "Unable to stop node '" + node + "' " + ajax_simple_error( + xhr, status, error + ); + if (message.indexOf('--force') == -1) { + alert(message); + } + else { + message = message.replace(', use --force to override', ''); + if (confirm(message + "\n\nDo you want to force the operation?")) { + node_stop(node, true); + } + } + } + }); +} + +function enable_resource() { + fade_in_out("#resource_start_link"); + Pcs.resourcesContainer.enable_resource(curResource()); +} + +function disable_resource() { + fade_in_out("#resource_stop_link"); + Pcs.resourcesContainer.disable_resource(curResource()); +} + +function cleanup_resource() { + var resource = curResource(); + if (resource == null) { + return; + } + fade_in_out("#resource_cleanup_link"); + ajax_wrapper({ + type: 'POST', + url: get_cluster_remote_url() + 'resource_cleanup', + data: {"resource": resource}, + success: function() { + }, + error: function (xhr, status, error) { + alert( + "Unable to cleanup resource '" + resource + "' " + + ajax_simple_error(xhr, status, error) + ); + } + }); +} + +function cleanup_stonith() { + var resource = curStonith(); + if (resource == null) { + return; + } + fade_in_out("#stonith_cleanup_link"); + ajax_wrapper({ + type: 'POST', + url: get_cluster_remote_url() + 'resource_cleanup', + data: {"resource": resource}, + success: function() { + }, + error: function (xhr, status, error) { + alert( + "Unable to cleanup resource '" + resource + "' " + + ajax_simple_error(xhr, status, error) + ); + } + }); +} + +function checkExistingNode() { + var node = ""; + $('input[name="node-name"]').each(function(i,e) { + node = e.value; + }); + + ajax_wrapper({ + type: 'GET', + url: '/manage/check_pcsd_status', + data: {"nodes": node}, + timeout: pcs_timeout, + success: function (data) { + mydata = jQuery.parseJSON(data); + update_existing_cluster_dialog(mydata); + + }, + error: function (XMLHttpRequest, textStatus, errorThrown) { + alert("ERROR: Unable to contact server"); + } + }); +} + +function checkClusterNodes() { + var nodes = []; + $('input[name^="node-"]').each(function(i,e) { + if (e.value != "") { + nodes.push(e.value) + } + }); + + ajax_wrapper({ + type: 'GET', + url: '/manage/check_pcsd_status', + data: {"nodes": nodes.join(",")}, + timeout: pcs_timeout, + success: function (data) { + mydata = jQuery.parseJSON(data); + ajax_wrapper({ + type: 'GET', + url: '/manage/get_nodes_sw_versions', + data: {"nodes": nodes.join(",")}, + timeout: pcs_timeout, + success: function(data) { + versions = jQuery.parseJSON(data); + update_create_cluster_dialog(mydata, versions); + }, + error: function (XMLHttpRequest, textStatus, errorThrown) { + alert("ERROR: Unable to contact server"); + } + }); + }, + error: function (XMLHttpRequest, textStatus, errorThrown) { + alert("ERROR: Unable to contact server"); + } + }); +} + +function auth_nodes(dialog) { + $("#auth_failed_error_msg").hide(); + ajax_wrapper({ + type: 'POST', + url: '/manage/auth_gui_against_nodes', + data: dialog.find("#auth_nodes_form").serialize(), + timeout: pcs_timeout, + success: function (data) { + mydata = jQuery.parseJSON(data); + auth_nodes_dialog_update(dialog, mydata); + }, + error: function (XMLHttpRequest, textStatus, errorThrown) { + alert("ERROR: Unable to contact server"); + } + }); +} + +function auth_nodes_dialog_update(dialog_obj, data) { + var unauth_nodes = []; + var node; + if (data['node_auth_error']) { + for (node in data['node_auth_error']) { + if (data['node_auth_error'][node] != 0) { + unauth_nodes.push(node); + } + } + } + + var callback_one = dialog_obj.dialog("option", "callback_success_one_"); + var callback = dialog_obj.dialog("option", "callback_success_"); + if (unauth_nodes.length == 0) { + dialog_obj.parent().find("#authenticate_submit_btn").button( + "option", "disabled", false + ); + dialog_obj.find("#auth_failed_error_msg").hide(); + dialog_obj.dialog("close"); + if (callback_one !== null) + callback_one(); + if (callback !== null) + callback(); + return unauth_nodes; + } else { + dialog_obj.find("#auth_failed_error_msg").show(); + } + + if (unauth_nodes.length == 1) { + dialog_obj.find("#same_pass").hide(); + dialog_obj.find('#auth_nodes_list').find('input:password').each( + function(){$(this).show()} + ); + } + + var one_success = false; + dialog_obj.find("input:password[name$=-pass]").each(function() { + node = $(this).attr("name"); + node = node.substring(0, node.length - 5); + if (unauth_nodes.indexOf(node) == -1) { + $(this).parent().parent().remove(); + one_success = true; + } else { + $(this).parent().parent().css("color", "red"); + } + }); + + if (one_success && callback_one !== null) + callback_one(); + + dialog_obj.parent().find("#authenticate_submit_btn").button( + "option", "disabled", false + ); + return unauth_nodes; +} + +function auth_nodes_dialog(unauth_nodes, callback_success, callback_success_one) { + callback_success = typeof callback_success !== 'undefined' ? callback_success : null; + callback_success_one = typeof callback_success_one !== 'undefined' ? callback_success_one : null; + + var buttonsOpts = [ + { + text: "Authenticate", + id: "authenticate_submit_btn", + click: function() { + var dialog = $(this); + dialog.parent().find("#authenticate_submit_btn").button( + "option", "disabled", true + ); + dialog.find("table.err_msg_table").find("span[id$=_error_msg]").hide(); + auth_nodes(dialog); + } + }, + { + text:"Cancel", + click: function () { + $(this).dialog("close"); + } + } + ]; + var dialog_obj = $("#auth_nodes").dialog({title: 'Authentification of nodes', + modal: true, resizable: false, + width: 'auto', + buttons: buttonsOpts, + callback_success_: callback_success, + callback_success_one_: callback_success_one + }); + + dialog_obj.find("#auth_failed_error_msg").hide(); + + // If you hit enter it triggers the submit button + dialog_obj.keypress(function(e) { + if (e.keyCode == $.ui.keyCode.ENTER && !dialog_obj.parent().find("#authenticate_submit_btn").button("option", "disabled")) { + dialog_obj.parent().find("#authenticate_submit_btn").trigger("click"); + return false; + } + }); + + if (unauth_nodes.length == 0) { + if (callback_success !== null) { + callback_success(); + } + return; + } + + if (unauth_nodes.length == 1) { + dialog_obj.find("#same_pass").hide(); + } else { + dialog_obj.find("#same_pass").show(); + dialog_obj.find("input:checkbox[name=all]").prop("checked", false); + dialog_obj.find("#pass_for_all").val(""); + dialog_obj.find("#pass_for_all").hide(); + } + + dialog_obj.find('#auth_nodes_list').empty(); + unauth_nodes.forEach(function(node) { + // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') + // dialog_obj.find('#auth_nodes_list').append("\t\t\t" + node + '\n'); + // FIXED: + dialog_obj.find('#auth_nodes_list').append("\t\t\t" + htmlEncode(node) + '\n'); + }); + +} + +function add_existing_dialog() { + var buttonOpts = [ + { + text: "Add Existing", + id: "add_existing_submit_btn", + click: function () { + $("#add_existing_cluster").find("table.err_msg_table").find("span[id$=_error_msg]").hide(); + $("#add_existing_submit_btn").button("option", "disabled", true); + checkExistingNode(); + } + }, + { + text: "Cancel", + click: function() { + $(this).dialog("close"); + } + } + ]; + + // If you hit enter it triggers the first button: Add Existing + $('#add_existing_cluster').keypress(function(e) { + if (e.keyCode == $.ui.keyCode.ENTER && !$("#add_existing_submit_btn").button("option", "disabled")) { + $(this).parent().find("button:eq(1)").trigger("click"); + return false; + } + }); + + $("#add_existing_cluster").dialog({title: 'Add Existing Cluster', + modal: false, resizable: false, + width: 'auto', + buttons: buttonOpts + }); +} + +function update_existing_cluster_dialog(data) { + for (var i in data) { + if (data[i] == "Online") { + ajax_wrapper({ + type: "POST", + url: "/manage/existingcluster", + timeout: pcs_timeout, + data: $('#add_existing_cluster_form').serialize(), + success: function(data) { + if (data) { + alert("Operation Successful!\n\nWarnings:\n" + data); + } + $("#add_existing_cluster.ui-dialog-content").each(function(key, item) {$(item).dialog("destroy")}); + Pcs.update(); + }, + error: function (xhr, status, error) { + alert(xhr.responseText); + $("#add_existing_submit_btn").button("option", "disabled", false); + } + }); + return; + } else if (data[i] == "Unable to authenticate") { + auth_nodes_dialog([i], function() {$("#add_existing_submit_btn").trigger("click");}); + $("#add_existing_submit_btn").button("option", "disabled", false); + return; + } + break; + } + if (data.length > 0) { + $('#add_existing_cluster_error_msg').html(i + ": " + data[i]); + $('#add_existing_cluster_error_msg').show(); + } + $('#unable_to_connect_error_msg_ae').show(); + $("#add_existing_submit_btn").button("option", "disabled", false); +} + +function update_create_cluster_dialog(nodes, version_info) { + var keys = []; + for (var i in nodes) { + if (nodes.hasOwnProperty(i)) { + keys.push(i); + } + } + + var cant_connect_nodes = 0; + var cant_auth_nodes = []; + var good_nodes = 0; + var addr1_match = 1; + var ring0_nodes = []; + var ring1_nodes = []; + var cman_nodes = []; + var noncman_nodes = []; + var rhel_versions = []; + var versions_check_ok = 1; + var cluster_name = $('input[name^="clustername"]').val() + var transport = $("#create_new_cluster select[name='config-transport']").val() + + $('#create_new_cluster input[name^="node-"]').each(function() { + if ($(this).val() == "") { + $(this).parent().prev().css("background-color", ""); + return; + } + for (var i = 0; i < keys.length; i++) { + if ($(this).val() == keys[i]) { + if (nodes[keys[i]] != "Online") { + if (nodes[keys[i]] == "Unable to authenticate") { + cant_auth_nodes.push(keys[i]); + } else { + $(this).parent().prev().css("background-color", "red"); + cant_connect_nodes++; + } + } else { + $(this).parent().prev().css("background-color", ""); + good_nodes++; + } + } + } + }); + + if (cant_auth_nodes.length > 0) { + auth_nodes_dialog(cant_auth_nodes, function(){$("#create_cluster_submit_btn").trigger("click")}); + $("#create_cluster_submit_btn").button("option", "disabled", false); + return; + } + + if (transport == "udpu") { + $('#create_new_cluster input[name^="node-"]').each(function() { + if ($(this).val().trim() != "") { + ring0_nodes.push($(this).attr("name")); + } + }); + $('#create_new_cluster input[name^="ring1-node-"]').each(function() { + if ($(this).val().trim() != "") { + ring1_nodes.push($(this).attr("name").substr("ring1-".length)); + } + }); + if (ring1_nodes.length > 0) { + if (ring0_nodes.length != ring1_nodes.length) { + addr1_match = 0 + } + else { + for (var i = 0; i < ring0_nodes.length; i++) { + if (ring0_nodes[i] != ring1_nodes[i]) { + addr1_match = 0; + break; + } + } + } + } + } + + if(version_info) { + $.each(version_info, function(node, versions) { + if(! versions["pcs"]) { + // we do not have valid info for this node + return; + } + if(versions["cman"]) { + cman_nodes.push(node); + } + else { + noncman_nodes.push(node); + } + if(versions["rhel"]) { + if($.inArray(versions["rhel"].join("."), rhel_versions) == -1) { + rhel_versions.push(versions["rhel"].join(".")) + } + } + }); + } + + if (cant_connect_nodes != 0) { + $("#unable_to_connect_error_msg").show(); + } else { + $("#unable_to_connect_error_msg").hide(); + } + + if (good_nodes == 0 && cant_connect_nodes == 0) { + $("#at_least_one_node_error_msg").show(); + } else { + $("#at_least_one_node_error_msg").hide(); + } + + if (cluster_name == "") { + $("#bad_cluster_name_error_msg").show(); + } else { + $("#bad_cluster_name_error_msg").hide(); + } + + if (addr1_match == 0) { + $("#addr0_addr1_mismatch_error_msg").show(); + } + else { + $("#addr0_addr1_mismatch_error_msg").hide(); + } + if(versions) { + if(cman_nodes.length > 0 && transport == "udpu") { + if(noncman_nodes.length < 1 && ring1_nodes.length < 1) { + transport = "udp"; + $("#create_new_cluster select[name='config-transport']").val(transport); + create_cluster_display_rrp(transport); + } + else { + versions_check_ok = 0; + $("#cman_udpu_transport_error_msg").show(); + } + } + else { + $("#cman_udpu_transport_error_msg").hide(); + } + + if(cman_nodes.length > 1 && noncman_nodes.length > 1) { + versions_check_ok = 0; + $("#cman_mismatch_error_msg").show(); + } + else { + $("#cman_mismatch_error_msg").hide(); + } + + if(rhel_versions.length > 1) { + versions_check_ok = 0; + $("#rhel_version_mismatch_error_msg").show(); + } + else { + $("#rhel_version_mismatch_error_msg").hide(); + } + } + else { + $("#cman_udpu_transport_error_msg").hide(); + $("#cman_mismatch_error_msg").hide(); + $("#rhel_version_mismatch_error_msg").hide(); + } + + if (good_nodes != 0 && cant_connect_nodes == 0 && cant_auth_nodes.length == 0 && cluster_name != "" && addr1_match == 1 && versions_check_ok == 1) { + ajax_wrapper({ + type: "POST", + url: "/manage/newcluster", + timeout: pcs_timeout, + data: $('#create_new_cluster_form').serialize(), + success: function(data) { + if (data) { + alert("Operation Successful!\n\nWarnings:\n" + data); + } + $("#create_new_cluster.ui-dialog-content").each(function(key, item) {$(item).dialog("destroy")}); + Pcs.update(); + }, + error: function (xhr, status, error) { + alert(xhr.responseText); + $("#create_cluster_submit_btn").button("option", "disabled", false); + } + }); + } else { + $("#create_cluster_submit_btn").button("option", "disabled", false); + } + +} + +function create_cluster_dialog() { + var buttonOpts = [{ + text: "Create Cluster", + id: "create_cluster_submit_btn", + click: function() { + $("#create_new_cluster").find("table.err_msg_table").find("span[id$=_error_msg]").hide(); + $("#create_cluster_submit_btn").button("option", "disabled", true); + checkClusterNodes(); + } + }, + { + text: "Cancel", + id: "create_cluster_cancel_btn", + click: function() { + $(this).dialog("close"); + } + }] + + $("#create_new_cluster").dialog({title: 'Create Cluster', + modal: false, resizable: false, + width: 'auto', + buttons: buttonOpts + }); +} + +function create_cluster_add_nodes() { + node_list = $("#create_new_cluster_form tr").has("input[name^='node-']");; + var ring1_node_list = $("#create_new_cluster_form tr").has( + "input[name^='ring1-node-']" + ); + cur_num_nodes = node_list.length; + + first_node = node_list.eq(0); + new_node = first_node.clone(); + $("input",new_node).attr("name", "node-"+(cur_num_nodes+1)); + $("input",new_node).val(""); + $("td", new_node).first().text("Node " + (cur_num_nodes+1)+ ":"); + new_node.insertAfter(node_list.last()); + + var ring1_first_node = ring1_node_list.eq(0); + var ring1_new_node = ring1_first_node.clone(); + $("input", ring1_new_node).attr("name", "ring1-node-" + (cur_num_nodes + 1)); + $("input", ring1_new_node).val(""); + $("td", ring1_new_node).first().text( + "Node " + (cur_num_nodes+1) + " (Ring 1):" + ); + ring1_new_node.insertAfter(ring1_node_list.last()); + + if (node_list.length == 7) + $("#create_new_cluster_form tr").has("input[name^='node-']").last().next().remove(); +} + +function create_cluster_display_rrp(transport) { + if(transport == 'udp') { + $('#rrp_udp_transport').show(); + $('#rrp_udpu_transport').hide(); + } + else { + $('#rrp_udp_transport').hide(); + $('#rrp_udpu_transport').show(); + }; +} + +function show_hide_constraints(element) { + //$(element).parent().siblings().each (function(index,element) { + $(element).parent().nextUntil(".stop").toggle(); + $(element).children("span, p").toggle(); +} + +function show_hide_constraint_tables(element) { + $(element).siblings().hide(); + $("#add_constraint_" + $(element).val()).show(); +} + +function hover_over(o) { + $(o).addClass("node_selected"); +} + +function hover_out(o) { + $(o).removeClass("node_selected"); +} + +function reload_current_resource() { + tree_view_onclick(curResource()); + tree_view_onclick(curStonith()); +} + +function load_row(node_row, ac, cur_elem, containing_elem, also_set, initial_load){ + hover_over(node_row); + $(node_row).siblings().each(function(key,sib) { + hover_out(sib); + }); + var self = ac; + $(containing_elem).fadeTo(500, .01,function() { + node_name = $(node_row).attr("nodeID"); + $.each(self.content, function(key, node) { + if (node.name == node_name) { + if (!initial_load) { + self.set(cur_elem,node); + } + node.set(cur_elem, true); + if (also_set) + self.set(also_set, node); + } else { + if (self.cur_resource_ston && self.cur_resource_ston.name == node.name) + self.content[key].set(cur_elem,true); + else if (self.cur_resource_res && self.cur_resource_res.name == node.name) + self.content[key].set(cur_elem,true); + else + self.content[key].set(cur_elem,false); + } + }); + $(containing_elem).fadeTo(500,1); + }); +} + +function show_loading_screen() { + $("#loading_screen_progress_bar").progressbar({ value: 100}); + $("#loading_screen").dialog({ + modal: true, + title: "Loading", + height: 100, + width: 250, + hide: { + effect: 'fade', + direction: 'down', + speed: 750 + } + }); +} + +function hide_loading_screen() { + $("#loading_screen").dialog('close'); + destroy_tooltips(); +} + +function destroy_tooltips() { + $("div[id^=ui-tooltip-]").remove(); +} + +function remove_cluster(ids) { + var data = {}; + $.each(ids, function(_, cluster) { + data[ "clusterid-" + cluster] = true; + }); + ajax_wrapper({ + type: 'POST', + url: '/manage/removecluster', + data: data, + timeout: pcs_timeout, + success: function () { + $("#dialog_verify_remove_clusters.ui-dialog-content").each(function(key, item) {$(item).dialog("destroy")}); + Pcs.update(); + }, + error: function (xhr, status, error) { + alert("Unable to remove cluster: " + res + " ("+error+")"); + $("#dialog_verify_remove_clusters.ui-dialog-content").each(function(key, item) {$(item).dialog("destroy")}); + } + }); +} + +function remove_nodes(ids, force) { + var data = {}; + for (var i=0; i 0) { + data['resources'].push(resources.split(/\s+/)); + } + }); + data.options = add_constraint_set_get_options(parent_id, c_type); + data["c_type"] = c_type; + if (force) { + data["force"] = force; + } + if (data['resources'].length < 1) { + return; + } + fade_in_out($(parent_id)) + + ajax_wrapper({ + type: "POST", + url: get_cluster_remote_url() + "add_constraint_set_remote", + data: data, + timeout: pcs_timeout, + success: function() { + reset_constraint_set_form(parent_id); + Pcs.update(); + }, + error: function (xhr, status, error){ + var message = "Unable to add constraint (" + $.trim(error) + ")"; + var error_prefix = 'Error adding constraint: '; + if (xhr.responseText.indexOf('cib_replace failed') == -1) { + if (xhr.responseText.indexOf(error_prefix) == 0) { + message += "\n\n" + xhr.responseText.slice(error_prefix.length); + } + else { + message += "\n\n" + xhr.responseText; + } + } + if (message.indexOf('--force') == -1) { + alert(message); + Pcs.update(); + } + else { + message = message.replace(', use --force to override', ''); + message = message.replace('Use --force to override.', ''); + if (confirm(message + "\n\nDo you want to force the operation?")) { + add_constraint_set(parent_id, c_type, true); + } + } + }, + }); +} + +function new_constraint_set_row(parent_id) { + $(parent_id + " td").first().append( + '
Set: ' + ); +} + +function reset_constraint_set_form(parent_id) { + $(parent_id + " td").first().html( + 'Set: ' + ); +} + +function remove_constraint(id) { + fade_in_out($("[constraint_id='"+id+"']").parent()); + ajax_wrapper({ + type: 'POST', + url: get_cluster_remote_url() + 'remove_constraint_remote', + data: {"constraint_id": id}, + timeout: pcs_timeout, + error: function (xhr, status, error) { + alert( + "Error removing constraint " + + ajax_simple_error(xhr, status, error) + ); + }, + complete: function() { + Pcs.update(); + } + }); +} + +function remove_constraint_action(remover_element){ + remove_constraint($(remover_element).parent().attr('constraint_id')); + return false; +} + +function remove_constraint_rule(id) { + fade_in_out($("[rule_id='"+id+"']").parent()); + ajax_wrapper({ + type: 'POST', + url: get_cluster_remote_url() + 'remove_constraint_rule_remote', + data: {"rule_id": id}, + timeout: pcs_timeout, + error: function (xhr, status, error) { + alert( + "Error removing constraint rule " + + ajax_simple_error(xhr, status, error) + ); + }, + complete: function() { + Pcs.update(); + } + }); +} + +function add_acl_role(form) { + var data = {} + data["name"] = $(form).find("input[name='name']").val().trim(); + data["description"] = $(form).find("input[name='description']").val().trim(); + ajax_wrapper({ + type: "POST", + url: get_cluster_remote_url() + "add_acl_role", + data: data, + success: function(data) { + Pcs.update(); + $(form).find("input").val(""); + $("#add_acl_role").dialog("close"); + }, + error: function(xhr, status, error) { + alert( + "Error adding ACL role " + + ajax_simple_error(xhr, status, error) + ); + } + }); +} + +function remove_acl_roles(ids) { + var data = {}; + for (var i = 0; i < ids.length; i++) { + data["role-" + i] = ids[i]; + } + ajax_wrapper({ + type: "POST", + url: get_cluster_remote_url() + "remove_acl_roles", + data: data, + timeout: pcs_timeout*3, + success: function(data,textStatus) { + $("#dialog_verify_remove_acl_roles.ui-dialog-content").each( + function(key, item) { $(item).dialog("destroy"); } + ); + Pcs.update(); + }, + error: function (xhr, status, error) { + alert( + "Error removing ACL role " + + ajax_simple_error(xhr, status, error) + ); + $("#dialog_verify_remove_acl_roles.ui-dialog-content").each( + function(key, item) { $(item).dialog("destroy"); } + ); + } + }); +} + +function add_acl_item(parent_id, item_type) { + var data = {}; + data["role_id"] = Pcs.aclsController.cur_role.name; + var item_label = ""; + switch (item_type) { + case "perm": + data["item"] = "permission"; + data["type"] = $(parent_id + " select[name='role_type']").val(); + data["xpath_id"] = $(parent_id + " select[name='role_xpath_id']").val(); + data["query_id"] = $(parent_id + " input[name='role_query_id']").val().trim(); + item_label = "permission" + break; + case "user": + case "group": + data["item"] = item_type; + data["usergroup"] = $(parent_id + " input[name='role_assign_user']").val().trim(); + item_label = item_type + break; + } + fade_in_out($(parent_id)); + ajax_wrapper({ + type: "POST", + url: get_cluster_remote_url() + 'add_acl', + data: data, + timeout: pcs_timeout, + success: function(data) { + $(parent_id + " input").val(""); + Pcs.update(); + }, + error: function (xhr, status, error) { + alert( + "Error adding " + item_label + " " + + ajax_simple_error(xhr, status, error) + ); + } + }); +} + +function remove_acl_item(id,item) { + fade_in_out(id); + var data = {}; + var item_label = ""; + switch (item) { + case "perm": + data["item"] = "permission"; + data["acl_perm_id"] = id.attr("acl_perm_id"); + item_label = "permission" + break; + case "group": + case "user": + data["item"] = "usergroup"; + data["item_type"] = item; + data["usergroup_id"] = id.attr("usergroup_id") + data["role_id"] = id.attr("role_id") + item_label = "user / group" + break; + } + + ajax_wrapper({ + type: 'POST', + url: get_cluster_remote_url() + 'remove_acl', + data: data, + timeout: pcs_timeout, + success: function (data) { + Pcs.update(); + }, + error: function (xhr, status, error) { + alert( + "Error removing " + item_label + " " + + ajax_simple_error(xhr, status, error) + ); + } + }); +} + +function update_cluster_settings() { + $("#cluster_properties button").prop("disabled", true); + var data = { + 'hidden[hidden_input]': null // this is needed for backward compatibility + }; + $.each(Pcs.settingsController.get("properties"), function(_, prop) { + data[prop.get("form_name")] = prop.get("cur_val"); + }); + show_loading_screen(); + ajax_wrapper({ + type: 'POST', + url: get_cluster_remote_url() + 'update_cluster_settings', + data: data, + timeout: pcs_timeout, + success: function() { + refresh_cluster_properties(); + }, + error: function (xhr, status, error) { + alert( + "Error updating configuration " + + ajax_simple_error(xhr, status, error) + ); + hide_loading_screen(); + $("#cluster_properties button").prop("disabled", false); + } + }); +} + +function refresh_cluster_properties() { + Pcs.settingsController.set("filter", ""); + $("#cluster_properties button").prop("disabled", true); + ajax_wrapper({ + url: get_cluster_remote_url() + "cluster_properties", + timeout: pcs_timeout, + dataType: "json", + success: function(data) { + Pcs.settingsController.update(data); + }, + error: function (xhr, status, error) { + Pcs.settingsController.set("error", true); + }, + complete: function() { + hide_loading_screen(); + $("#cluster_properties button").prop("disabled", false); + } + }); +} + +// Pull currently managed cluster name out of URL +function get_cluster_name() { + var cluster_name = location.pathname.match("/managec/(.*)/"); + if (cluster_name && cluster_name.length >= 2) { + Ember.debug("Cluster Name: " + cluster_name[1]); + cluster_name = cluster_name[1]; + return cluster_name; + } + Ember.debug("Cluster Name is 'null'"); + cluster_name = null; + return cluster_name; +} + +function get_cluster_remote_url(cluster_name) { + cluster_name = typeof cluster_name !== 'undefined' ? cluster_name : Pcs.cluster_name; + return '/managec/' + cluster_name + "/"; +} + +function checkBoxToggle(cb,nodes) { + if (nodes) { + cbs = $('#node_list table').find(".node_list_check input[type=checkbox]"); + } else { + cbs = $(cb).closest("tr").parent().find(".node_list_check input[type=checkbox]") + } + if ($(cb).prop('checked')) + cbs.prop('checked',true).change(); + else + cbs.prop('checked',false).change(); +} + +function loadWizard(item) { + wizard_name = $(item).val(); + data = {wizard: wizard_name}; + + $("#wizard_location").load( + get_cluster_remote_url() + 'get_wizard', + data); +} + +function wizard_submit(form) { + data = $(form).serialize(); + $("#wizard_location").load( + get_cluster_remote_url() + 'wizard_submit', + data); +} + +function update_resource_type_options() { + var cp = $("#resource_class_provider_selector").val(); + var target = $("#add_ra_type"); + var source = $("#all_ra_types"); + + target.empty(); + source.find("option").each(function(i,v) { + if ($(v).val().indexOf(cp) == 0) { + new_option = $(v).clone(); + target.append(new_option); + } + }); + target.change(); +} + +function setup_resource_class_provider_selection() { + $("#resource_class_provider_selector").change(function() { + update_resource_type_options(); + }); + $("#resource_class_provider_selector").change(); +} + +function get_status_value(status) { + var values = { + failed: 1, + error: 1, + offline: 1, + blocked: 1, + warning: 2, + standby: 2, + maintenance: 2, + "partially running": 2, + disabled: 3, + unmanaged: 3, + unknown: 4, + ok: 5, + running: 5, + online: 5 + }; + return ((values.hasOwnProperty(status)) ? values[status] : -1); +} + +function status_comparator(a,b) { + var valA = get_status_value(a); + var valB = get_status_value(b); + if (valA == -1) return 1; + if (valB == -1) return -1; + return valA - valB; +} + +function get_status_icon_class(status_val, is_unmanaged) { + var is_unmanaged = typeof is_unmanaged !== 'undefined' ? is_unmanaged : false; + switch (status_val) { + case get_status_value("error"): + return "error"; + case get_status_value("disabled"): + case get_status_value("warning"): + return "warning"; + case get_status_value("ok"): + return is_unmanaged ? "warning" : "check"; + default: + return "x"; + } +} + +function get_status_color(status_val, is_unmanaged) { + var is_unmanaged = typeof is_unmanaged !== 'undefined' ? is_unmanaged : false; + if (status_val == get_status_value("ok")) { + return is_unmanaged? "orange" : "green"; + } + else if (status_val == get_status_value("warning") || status_val == get_status_value("unknown") || status_val == get_status_value('disabled')) { + return "orange"; + } + return "red"; +} + +function show_hide_dashboard(element, type) { + var cluster = Pcs.clusterController.cur_cluster; + if (Pcs.clusterController.get("show_all_" + type)) { // show only failed + Pcs.clusterController.set("show_all_" + type, false); + } else { // show all + Pcs.clusterController.set("show_all_" + type, true); + } + correct_visibility_dashboard_type(cluster, type); +} + +function correct_visibility_dashboard(cluster) { + if (cluster == null) + return; + $.each(["nodes", "resources", "fence"], function(key, type) { + correct_visibility_dashboard_type(cluster, type); + }); +} + +function correct_visibility_dashboard_type(cluster, type) { + if (cluster == null) { + return; + } + destroy_tooltips(); + var listTable = $("#cluster_info_" + cluster.name).find("table." + type + "_list"); + var datatable = listTable.find("table.datatable"); + if (Pcs.clusterController.get("show_all_" + type)) { + listTable.find("span.downarrow").show(); + listTable.find("span.rightarrow").hide(); + datatable.find("tr.default-hidden").removeClass("hidden"); + } else { + listTable.find("span.downarrow").hide(); + listTable.find("span.rightarrow").show(); + datatable.find("tr.default-hidden").addClass("hidden"); + } + if (cluster.get(type + "_failed") == 0 && !Pcs.clusterController.get("show_all_" + type)) { + datatable.hide(); + } else { + datatable.show(); + } +} + +function get_formated_html_list(data) { + if (data == null || data.length == 0) { + return ""; + } + var out = "
    "; + $.each(data, function(key, value) { + out += "
  • " + htmlEncode(value.message) + "
  • "; + }); + out += "
"; + return out; +} + +function htmlEncode(s) +{ + return $("
").text(s).html().replace(/"/g, """).replace(/'/g, "'"); +} + +function fix_auth_of_cluster() { + show_loading_screen(); + var clustername = Pcs.clusterController.cur_cluster.name; + ajax_wrapper({ + url: get_cluster_remote_url(clustername) + "fix_auth_of_cluster", + type: "POST", + success: function(data) { + hide_loading_screen(); + Pcs.update(); + }, + error: function(jqhxr,b,c) { + hide_loading_screen(); + Pcs.update(); + alert(jqhxr.responseText); + } + }); +} + +function get_tree_view_resource_id(element) { + var suffix = '-treeview-element'; + var element_id = $(element).parents('table.tree-element')[0].id; + if (element_id && element_id.endsWith(suffix)) { + return element_id.substr(0, element_id.lastIndexOf(suffix)); + } + return null; +} + +function get_list_view_element_id(element) { + return $(element)[0].id; +} + +function auto_show_hide_constraints() { + var cont = [ + "location_constraints", + "ordering_constraints", + "ordering_set_constraints", + "colocation_constraints", + "colocation_set_constraints", + "ticket_constraints", + "ticket_set_constraints", + "meta_attributes", + ]; + $.each(cont, function(index, name) { + var elem = $("#" + name)[0]; + var cur_resource = Pcs.resourcesContainer.get('cur_resource'); + if (elem && cur_resource) { + var visible = $(elem).children("span")[0].style.display != 'none'; + if (visible && (!cur_resource.get(name) || cur_resource.get(name).length == 0)) + show_hide_constraints(elem); + else if (!visible && cur_resource.get(name) && cur_resource.get(name).length > 0) + show_hide_constraints(elem); + } + }); +} + +function get_resource_agent_metadata(agent, on_success, stonith) { + stonith = typeof stonith !== 'undefined' ? stonith : false; + var request = (stonith) + ? 'get_fence_agent_metadata' + : 'get_resource_agent_metadata'; + ajax_wrapper({ + url: get_cluster_remote_url() + request, + dataType: "json", + data: {agent: agent}, + timeout: pcs_timeout, + success: on_success, + error: function (xhr, status, error) { + alert( + "Unable to get metadata for resource agent '" + agent + "' " + + ajax_simple_error(xhr, status, error) + ); + } + }) +} + +function update_instance_attributes(resource_id) { + var res_obj = Pcs.resourcesContainer.get_resource_by_id(resource_id); + if (!(res_obj && res_obj.get("is_primitive"))) { + return; + } + get_resource_agent_metadata(res_obj.get("resource_type"), function(data) { + var agent = Pcs.ResourceAgent.create(data); + res_obj.set("resource_agent", agent); + $.each(res_obj.get("instance_attr"), function(_, attr) { + agent.get_parameter(attr.name).set("value", attr.value); + }); + }, res_obj.get("stonith")); +} + +function tree_view_onclick(resource_id) { + var resource_obj = Pcs.resourcesContainer.get_resource_by_id(resource_id); + if (!resource_obj) { + console.log("Resource " + resource_id + "not found."); + return; + } + if (resource_obj.get('stonith')) { + if (window.location.hash.startsWith("#/fencedevices")) { + window.location.hash = "/fencedevices/" + resource_id; + } + Pcs.resourcesContainer.set('cur_fence', resource_obj); + } else { + if (window.location.hash.startsWith("#/resources")) { + window.location.hash = "/resources/" + resource_id; + } + Pcs.resourcesContainer.set('cur_resource', resource_obj); + auto_show_hide_constraints(); + } + update_instance_attributes(resource_id); + tree_view_select(resource_id); +} + +function tree_view_select(element_id) { + var e = $(`#${element_id}-treeview-element`); + var view = e.parents('table.tree-view'); + view.find('div.arrow').hide(); + view.find('tr.children').hide(); + view.find('table.tree-element').show(); + view.find('tr.tree-element-name').removeClass("node_selected"); + e.find('tr.tree-element-name:first').addClass("node_selected"); + e.find('tr.tree-element-name div.arrow:first').show(); + e.parents('tr.children').show(); + e.find('tr.children').show(); +} + +function tree_view_checkbox_onchange(element) { + var e = $(element); + var children = $(element).closest(".tree-element").find(".children" + + " input:checkbox"); + var val = e.prop('checked'); + children.prop('checked', val); + children.prop('disabled', val); +} + +function resource_master(resource_id) { + if (resource_id == null) { + return; + } + show_loading_screen(); + ajax_wrapper({ + type: 'POST', + url: get_cluster_remote_url() + 'resource_master', + data: {resource_id: resource_id}, + timeout: pcs_timeout, + error: function (xhr, status, error) { + alert( + "Unable to create master/slave resource " + + ajax_simple_error(xhr, status, error) + ); + }, + complete: function() { + Pcs.update(); + } + }); +} + +function resource_clone(resource_id) { + if (resource_id == null) { + return; + } + show_loading_screen(); + ajax_wrapper({ + type: 'POST', + url: get_cluster_remote_url() + 'resource_clone', + data: {resource_id: resource_id}, + timeout: pcs_timeout, + error: function (xhr, status, error) { + alert( + "Unable to clone the resource " + + ajax_simple_error(xhr, status, error) + ); + }, + complete: function() { + Pcs.update(); + } + }); +} + +function resource_unclone(resource_id) { + if (resource_id == null) { + return; + } + show_loading_screen(); + var resource_obj = Pcs.resourcesContainer.get_resource_by_id(resource_id); + if (resource_obj.get('class_type') == 'clone') { + resource_id = resource_obj.get('member').get('id'); + } + ajax_wrapper({ + type: 'POST', + url: get_cluster_remote_url() + 'resource_unclone', + data: {resource_id: resource_id}, + timeout: pcs_timeout, + error: function (xhr, status, error) { + alert( + "Unable to unclone the resource " + + ajax_simple_error(xhr, status, error) + ); + }, + complete: function() { + Pcs.update(); + } + }); +} + +function resource_ungroup(group_id) { + if (group_id == null) { + return; + } + show_loading_screen(); + ajax_wrapper({ + type: 'POST', + url: get_cluster_remote_url() + 'resource_ungroup', + data: {group_id: group_id}, + timeout: pcs_timeout, + error: function (xhr, status, error) { + alert( + "Unable to ungroup the resource " + + ajax_simple_error(xhr, status, error) + ); + }, + complete: function() { + Pcs.update(); + } + }); +} + +function resource_change_group(resource_id, form) { + if (resource_id == null) { + return; + } + show_loading_screen(); + var resource_obj = Pcs.resourcesContainer.get_resource_by_id(resource_id); + var data = { + resource_id: resource_id + }; + $.each($(form).serializeArray(), function(_, item) { + data[item.name] = item.value; + }); + + if ( + resource_obj.get('parent') && + resource_obj.get('parent').get('class_type') == 'group' + ) { + data['old_group_id'] = resource_obj.get('parent').get('id'); + } + + ajax_wrapper({ + type: 'POST', + url: get_cluster_remote_url() + 'resource_change_group', + data: data, + timeout: pcs_timeout, + error: function (xhr, status, error) { + alert( + "Unable to change group " + + ajax_simple_error(xhr, status, error) + ); + }, + complete: function() { + Pcs.update(); + } + }); +} + +function ajax_simple_error(xhr, status, error) { + var message = "(" + $.trim(error) + ")" + if ( + $.trim(xhr.responseText).length > 0 + && + xhr.responseText.indexOf('cib_replace failed') == -1 + ) { + message = message + "\n\n" + $.trim(xhr.responseText); + } + return message; +} + +function ajax_wrapper(options) { + // get original callback functions + var error_original = function(xhr, status, error) {}; + if (options.error) { + error_original = options.error; + } + var complete_original = function(xhr, status) {}; + if (options.complete) { + complete_original = options.complete; + } + + // prepare new callback functions + var options_new = $.extend(true, {}, options); + // display login dialog on error + options_new.error = function(xhr, status, error) { + if (xhr.status == 401) { + ajax_queue.push(options); + if (!login_dialog_opened) { + login_dialog(function() { + var item; + while (ajax_queue.length > 0) { + item = ajax_queue.shift(); + ajax_wrapper(item); + } + }); + } + } + else { + error_original(xhr, status, error); + } + } + // Do not run complete function if login dialog is open. + // Once user is logged in again, the original complete function will be run + // in repeated ajax call run by login dialog on success. + options_new.complete = function(xhr, status) { + if (xhr.status == 401) { + return; + } + else { + complete_original(xhr, status); + } + } + + // run ajax request or put it into a queue + if (login_dialog_opened) { + ajax_queue.push(options); + } + else { + $.ajax(options_new); + } +} + +function login_dialog(on_success) { + var ok_button_id = "login_form_ok"; + var ok_button_selector = "#" + ok_button_id; + var buttons = [ + { + text: "Log In", + id: ok_button_id, + click: function() { + var me = $(this); + var my_dialog = $(this).dialog() + my_dialog.find("#login_form_denied").hide(); + $(ok_button_selector).button("option", "disabled", true); + $.ajax({ + type: "POST", + url: "/login", + data: my_dialog.find("#login_form").serialize(), + complete: function() { + $(ok_button_selector).button("option", "disabled", false); + }, + success: function() { + my_dialog.find("#login_form_username").val(""); + my_dialog.find("#login_form_password").val(""); + me.dialog("destroy"); + login_dialog_opened = false; + on_success(); + }, + error: function(xhr, status, error) { + if (xhr.status == 401) { + my_dialog.find("#login_form_denied").show(); + my_dialog.find("#login_form_password").val(""); + } + else { + alert("Login error " + ajax_simple_error(xhr, status, error)); + } + }, + }); + }, + }, + { + text: "Cancel", + id: "login_form_cancel", + // cancel will close the dialog the same way as X button does + click: function() { + $(this).dialog("close"); + }, + }, + ]; + var dialog_obj = $("#dialog_login").dialog({ + title: "Log In", + modal: true, + resizable: true, + width: 400, + buttons: buttons, + open: function(event, ui) { + login_dialog_opened = true; + }, + create: function(event, ui) { + login_dialog_opened = true; + }, + // make sure to logout the user on dialog close + close: function(event, ui) { + login_dialog_opened = false; + location = "/logout"; + }, + }); + dialog_obj.find("#login_form_denied").hide(); + // submit on enter + dialog_obj.keypress(function(e) { + if ( + e.keyCode == $.ui.keyCode.ENTER + && + !dialog_obj.parent().find(ok_button_selector).button("option", "disabled") + ) { + dialog_obj.parent().find(ok_button_selector).trigger("click"); + return false; + } + }); +} + +var permissions_current_cluster; + +function permissions_load_all() { + show_loading_screen(); + + var cluster_list = []; + $("#node_info div[id^='permissions_cluster_']").each(function(i, div) { + cluster_list.push( + $(div).attr("id").substring("permissions_cluster_".length) + ); + }); + + var call_count = cluster_list.length; + var callback = function() { + call_count = call_count - 1; + if (call_count < 1) { + hide_loading_screen(); + } + } + + $.each(cluster_list, function(index, cluster) { + permissions_load_cluster(cluster, callback); + }); + + if (cluster_list.length > 0) { + permissions_current_cluster = cluster_list[0]; + permissions_show_cluster( + permissions_current_cluster, + $("#cluster_list tr").first().next() /* the first row is a heading */ + ); + } + else { + hide_loading_screen(); + } +} + +function permissions_load_cluster(cluster_name, callback) { + var element_id = "permissions_cluster_" + cluster_name; + ajax_wrapper({ + type: "GET", + url: "/permissions_cluster_form/" + cluster_name, + timeout: pcs_timeout, + success: function(data) { + $("#" + element_id).html(data); + $("#" + element_id + " :checkbox").each(function(key, checkbox) { + permissions_fix_dependent_checkboxes(checkbox); + }); + permissions_cluster_dirty_flag(cluster_name, false); + if (callback) { + callback(); + } + }, + error: function(xhr, status, error) { + $("#" + element_id).html( + "Error loading permissions " + ajax_simple_error(xhr, status, error) + ); + if (callback) { + callback(); + } + } + }); +} + +function permissions_show_cluster(cluster_name, list_row) { + permissions_current_cluster = cluster_name; + + var container = $("#node_info"); + container.fadeTo(500, .01, function() { + container.children().hide(); + $("#permissions_cluster_" + cluster_name).show(); + container.fadeTo(500, 1); + }); + + $(list_row).siblings("tr").each(function(index, row) { + hover_out(row); + $(row).find("td").last().children().hide(); + }); + hover_over(list_row); + $(list_row).find("td").last().children().show(); +} + +function permissions_save_cluster(form) { + var dataString = $(form).serialize(); + var cluster_name = permissions_get_clustername(form); + ajax_wrapper({ + type: "POST", + url: get_cluster_remote_url(cluster_name) + "permissions_save", + timeout: pcs_timeout, + data: dataString, + success: function() { + show_loading_screen(); + permissions_load_cluster(cluster_name, hide_loading_screen); + }, + error: function(xhr, status, error) { + alert( + "Unable to save permissions of cluster " + cluster_name + " " + + ajax_simple_error(xhr, status, error) + ); + } + }); +} + +function permissions_cluster_dirty_flag(cluster_name, flag) { + var cluster_row = permissions_get_cluster_row(cluster_name); + if (cluster_row) { + var dirty_elem = cluster_row.find("span[class=unsaved_changes]"); + if (dirty_elem) { + if (flag) { + dirty_elem.show(); + } + else { + dirty_elem.hide(); + } + } + } +} + +function permission_remove_row(button) { + var cluster_name = permissions_get_clustername( + $(button).parents("form").first() + ); + $(button).parent().parent().remove(); + permissions_cluster_dirty_flag(cluster_name, true); +} + +function permissions_add_row(template_row) { + var user_name = permissions_get_row_name(template_row); + var user_type = permissions_get_row_type(template_row); + var max_key = -1; + var exists = false; + var cluster_name = permissions_get_clustername( + $(template_row).parents("form").first() + ); + + if("" == user_name) { + alert("Please enter the name"); + return; + } + if("" == user_type) { + alert("Please enter the type"); + return; + } + + $(template_row).siblings().each(function(index, row) { + if( + (permissions_get_row_name(row) == user_name) + && + (permissions_get_row_type(row) == user_type) + ) { + exists = true; + } + $(row).find("input").each(function(index, input) { + var match = input.name.match(/^[^[]*\[(\d+)\].*$/); + if (match) { + var key = parseInt(match[1]); + if(key > max_key) { + max_key = key; + } + } + }); + }); + if(exists) { + alert("Permissions already set for the user"); + return; + } + + max_key = max_key + 1; + var new_row = $(template_row).clone(); + new_row.find("[name*='_new']").each(function(index, element) { + element.name = element.name.replace("_new", "[" + max_key + "]"); + }); + new_row.find("td").last().html( + 'X' + ); + new_row.find("[name$='[name]']").each(function(index, element) { + $(element).after(user_name); + $(element).attr("type", "hidden"); + }); + new_row.find("[name$='[type]']").each(function(index, element) { + $(element).after(user_type); + $(element).after( + '' + ); + $(element).remove(); + }); + + $(template_row).before(new_row); + var template_inputs = $(template_row).find(":input"); + template_inputs.removeAttr("checked").removeAttr("selected"); + template_inputs.removeAttr("disabled").removeAttr("readonly"); + $(template_row).find(":input[type=text]").val(""); + + permissions_cluster_dirty_flag(cluster_name, true); +} + +function permissions_get_dependent_checkboxes(checkbox) { + var cluster_name = permissions_get_clustername( + $(checkbox).parents("form").first() + ); + var checkbox_permission = permissions_get_checkbox_permission(checkbox); + var deps = {}; + var dependent_permissions = []; + var dependent_checkboxes = []; + + if (permissions_dependencies[cluster_name]) { + deps = permissions_dependencies[cluster_name]; + if (deps["also_allows"] && deps["also_allows"][checkbox_permission]) { + dependent_permissions = deps["also_allows"][checkbox_permission]; + $(checkbox).parents("tr").first().find(":checkbox").not(checkbox).each( + function(key, check) { + var perm = permissions_get_checkbox_permission(check); + if (dependent_permissions.indexOf(perm) != -1) { + dependent_checkboxes.push(check); + } + } + ); + } + } + return dependent_checkboxes; +} + +function permissions_fix_dependent_checkboxes(checkbox) { + var dep_checks = $(permissions_get_dependent_checkboxes(checkbox)); + if ($(checkbox).prop("checked")) { + /* the checkbox is now checked */ + dep_checks.each(function(key, check) { + var jq_check = $(check); + jq_check.prop("checked", true); + jq_check.prop("readonly", true); + // readonly on checkbox makes it look like readonly but doesn't prevent + // changing its state (checked - not checked), setting disabled works + jq_check.prop("disabled", true); + permissions_fix_dependent_checkboxes(check); + }); + } + else { + /* the checkbox is now empty */ + dep_checks.each(function(key, check) { + var jq_check = $(check); + jq_check.prop("checked", jq_check.prop("defaultChecked")); + jq_check.prop("readonly", false); + jq_check.prop("disabled", false); + permissions_fix_dependent_checkboxes(check); + }); + } +} + +function permissions_get_row_name(row) { + return $.trim($(row).find("[name$='[name]']").val()); +} + +function permissions_get_row_type(row) { + return $.trim($(row).find("[name$='[type]']").val()); +} + +function permissions_get_clustername(form) { + return $.trim($(form).find("[name=cluster_name]").val()); +} + +function permissions_get_checkbox_permission(checkbox) { + var match = checkbox.name.match(/^.*\[([^[]+)\]$/); + if (match) { + return match[1]; + } + return ""; +} + +function permissions_get_cluster_row(cluster_name) { + var cluster_row = null; + $('#cluster_list td[class=node_name]').each(function(index, elem) { + var jq_elem = $(elem); + if (jq_elem.text().trim() == cluster_name.trim()) { + cluster_row = jq_elem.parents("tr").first(); + } + }); + return cluster_row; +} + +function is_cib_true(value) { + if (value) { + return (['true', 'on', 'yes', 'y', '1'].indexOf(value.toString().toLowerCase()) != -1); + } + return false; +} + +function set_utilization(type, entity_id, name, value) { + var data = { + name: name, + value: value + }; + if (type == "node") { + data["node"] = entity_id; + } else if (type == "resource") { + data["resource_id"] = entity_id; + } else return false; + var url = get_cluster_remote_url() + "set_" + type + "_utilization"; + + ajax_wrapper({ + type: 'POST', + url: url, + data: data, + timeout: pcs_timeout, + error: function (xhr, status, error) { + alert( + "Unable to set utilization: " + + ajax_simple_error(xhr, status, error) + ); + }, + complete: function() { + Pcs.update(); + } + }); +} + +function is_integer(str) { + if (Number(str) === str && str % 1 === 0) // if argument isn't string but number + return true; + var n = ~~Number(str); + return String(n) === str; +} + +Ember.Handlebars.helper('selector-helper', function (content, value, place_holder, options) { + var out = ""; + var line; + if (place_holder) { + out += ''; + } + $.each(content, function(_, opt){ + line = '