001 package org.cumulus4j.store.model;
002
003 import javax.jdo.JDOObjectNotFoundException;
004 import javax.jdo.PersistenceManager;
005 import javax.jdo.Query;
006 import javax.jdo.identity.IntIdentity;
007
008 public class KeyStoreRefDAO extends AbstractDAO {
009
010 public KeyStoreRefDAO() { }
011
012 /**
013 * @param pm the backend-{@link PersistenceManager} (the one used for data, if there is a separate index-DB used).
014 */
015 public KeyStoreRefDAO(PersistenceManager pm) {
016 super(pm);
017 }
018
019 /**
020 * {@inheritDoc}
021 * @param pm the backend-{@link PersistenceManager} (the one used for data, if there is a separate index-DB used).
022 */
023 @Override
024 public void setPersistenceManager(PersistenceManager pm) {
025 super.setPersistenceManager(pm);
026 }
027
028 public KeyStoreRef getKeyStoreRef(int keyStoreRefID) {
029 IntIdentity id = new IntIdentity(KeyStoreRef.class, keyStoreRefID);
030 try {
031 KeyStoreRef keyStoreRef = (KeyStoreRef) pm.getObjectById(id);
032 return keyStoreRef;
033 } catch (JDOObjectNotFoundException x) {
034 return null;
035 }
036 }
037
038 public KeyStoreRef getKeyStoreRef(String keyStoreID) {
039 if (keyStoreID == null)
040 throw new IllegalArgumentException("keyStoreID == null");
041
042 Query q = pm.newNamedQuery(KeyStoreRef.class, "getKeyStoreRefByKeyStoreID");
043 return (KeyStoreRef) q.execute(keyStoreID);
044 // UNIQUE query does not need to be closed, because there is no result list lingering.
045 }
046
047 public KeyStoreRef createKeyStoreRef(String keyStoreID) {
048 KeyStoreRef keyStoreRef = getKeyStoreRef(keyStoreID);
049 if (keyStoreRef == null) {
050 keyStoreRef = pm.makePersistent(new KeyStoreRef(keyStoreID));
051 // It does not matter, whether this ID is negative, or not, but we don't
052 // need so many IDs and thus we can use solely positive numbers. And as
053 // we *require* positive numbers in EncryptionCoordinateSet-IDs, the underlying
054 // datastore needs to support starting at 0, anyway, hence we can make this
055 // constraint for the sake of beauty (of the raw datastore).
056 // In many cases, 0 is the one and only ID, because we seldomly share
057 // one underlying database among multiple tenants (= key stores).
058 // Additionally, we use 0 as default value which is relevant for updates
059 // from older Cumulus4j versions.
060 if (keyStoreRef.getKeyStoreRefID() < 0)
061 throw new IllegalStateException("keyStoreRefID = " + keyStoreRef.getKeyStoreRefID() + " < 0!!!");
062 }
063 return keyStoreRef;
064 }
065 }