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:
+ *
+ *
+ * {@link AccessDialectEpsgFactory}
+ * {@link AnsiDialectEpsgFactory}
+ * {@link OracleDialectEpsgFactory}
+ *
+ *
+ * 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 extends CoordinateOperation> 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 extends IdentifiedObject> 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 extends IdentifiedObject> 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 extends Object> 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 extends XWikiForm> 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 extends CharSequence> 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
+ *
+ * @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
+ *
+ * @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("\\')+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;b this.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,"&").replace(/</g,"<").replace(/>/g,">").replace(/</g,"<").replace(/>/g,">").replace(//g,">");a=b.value.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/&/g,
+"&").replace(/ /g," ").replace(/ /g," ").replace(/( ]+)>/gm,"$1 />")}return a};
+mxSvgCanvas2D.prototype.createDiv=function(a){mxUtils.isNode(a)||(a="");if(mxClient.IS_IE||mxClient.IS_IE11||!document.createElementNS)return mxUtils.isNode(a)&&(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="",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 0 g+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&ðis.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;a