protected Transaction getSaveTransaction(String storeName, boolean useCurrentTransaction) { return useCurrentTransaction ? persistence.getTransaction(storeName) : persistence.createTransaction(storeName); }
@Override public void storeDynamicAttributes(BaseGenericIdEntity entity) { try (Transaction tx = persistence.getTransaction()) { doStoreDynamicAttributes(entity); tx.commit(); } }
protected void transactional(Closure closure) { Persistence persistence = AppBeans.get(Persistence.class); Transaction tx = persistence.getTransaction(); try { closure.call(persistence.getEntityManager()); tx.commit(); } finally { tx.end(); } } }
protected void sendResetPasswordEmail(User user, String password, Template subjectTemplate, Template bodyTemplate) { Transaction tx = persistence.getTransaction(); String emailBody; String emailSubject; try { Map<String, Object> binding = new HashMap<>(); binding.put("user", user); binding.put("password", password); binding.put("persistence", persistence); emailBody = bodyTemplate.make(binding).writeTo(new StringWriter(0)).toString(); emailSubject = subjectTemplate.make(binding).writeTo(new StringWriter(0)).toString(); tx.commit(); } catch (IOException e) { throw new RuntimeException("Unable to write Groovy template content", e); } finally { tx.end(); } EmailInfo emailInfo = new EmailInfo(user.getEmail(), emailSubject, emailBody); emailerAPI.sendEmailAsync(emailInfo); }
@Override public void deleteSequence(Sequence sequence) { Preconditions.checkNotNull(sequence, "Sequence can't be null"); checkSequenceName(sequence.getName()); String sequenceName = sequence.getName(); if (!existingSequences.contains(sequenceName)) { throw new IllegalStateException(String.format("Attempt to delete nonexistent sequence '%s'", sequence)); } String sqlScript = getSequenceSupport(sequence).deleteSequenceSql(sequenceName); lock.writeLock().lock(); try { if (!existingSequences.contains(sequenceName)) { return; } Transaction tx = persistence.getTransaction(getDataStore(sequence)); try { executeScript(sequence, sqlScript); existingSequences.remove(sequenceName); tx.commit(); } finally { tx.end(); } } finally { lock.writeLock().unlock(); } }
protected Transaction getLoadTransaction(boolean useCurrentTransaction) { TransactionParams txParams = new TransactionParams(); if (serverConfig.getUseReadOnlyTransactionForLoad()) { txParams.setReadOnly(true); } return useCurrentTransaction ? persistence.getTransaction(storeName) : persistence.createTransaction(storeName, txParams); }
@Override public void setCurrentValue(Sequence sequence, long value) { Preconditions.checkNotNull(sequence, "Sequence can't be null"); checkSequenceName(sequence.getName()); String sqlScript = getSequenceSupport(sequence).modifySequenceSql(sequence.getName(), value); lock.readLock().lock(); try { Transaction tx = persistence.getTransaction(getDataStore(sequence)); try { checkSequenceExists(sequence); executeScript(sequence, sqlScript); tx.commit(); } finally { tx.end(); } } finally { lock.readLock().unlock(); } }
protected void removeAccessTokenFromDatabase(String accessTokenValue) { try (Transaction tx = persistence.getTransaction()) { EntityManager em = persistence.getEntityManager(); em.createQuery("delete from sys$AccessToken t where t.tokenValue = :tokenValue") .setParameter("tokenValue", accessTokenValue) .executeUpdate(); tx.commit(); } }
@Override public void enqueue(String entityName, Object entityId, FtsChangeType changeType) { if (!manager.isEntityCanBeIndexed(metadata.getClassNN(entityName))) return; // Join to an existing transaction in main DB or create a new one if we came here with a tx for an additional DB try (Transaction tx = persistence.getTransaction()) { List<String> indexingHosts = coreConfig.getIndexingHosts(); if (indexingHosts.isEmpty()) { persistQueueItem(entityName, entityId, changeType, null); } else { for (String indexingHost : indexingHosts) { persistQueueItem(entityName, entityId, changeType, indexingHost); } } tx.commit(); } }
protected void removeRefreshTokenFromDatabase(String refreshTokenValue) { try (Transaction tx = persistence.getTransaction()) { EntityManager em = persistence.getEntityManager(); em.createQuery("delete from sys$RefreshToken t where t.tokenValue = :tokenValue") .setParameter("tokenValue", refreshTokenValue) .executeUpdate(); tx.commit(); } }
@Override public void storeRefreshToken(String refreshTokenValue, byte[] refreshTokenBytes, byte[] authenticationBytes, Date tokenExpiry, String userLogin) { storeRefreshTokenToMemory(refreshTokenValue, refreshTokenBytes, authenticationBytes, tokenExpiry, userLogin); if (serverConfig.getRestStoreTokensInDb()) { try (Transaction tx = persistence.getTransaction()) { removeRefreshTokenFromDatabase(refreshTokenValue); storeRefreshTokenToDatabase(refreshTokenValue, refreshTokenBytes, authenticationBytes, tokenExpiry, userLogin); tx.commit(); } } }
@Override public boolean checkPassword(UUID userId, String passwordHash) { checkNotNullArgument(userId, "Null userId"); checkNotNullArgument(passwordHash, "Null new password hash"); User user; Transaction tx = persistence.getTransaction(); try { EntityManager em = persistence.getEntityManager(); user = em.find(User.class, userId, CHECK_PASSWORD_VIEW); if (user == null) throw new RuntimeException("Unable to find user with id: " + userId); tx.commit(); } finally { tx.end(); } return passwordEncryption.checkPassword(user, passwordHash); }
@Override public void resetRememberMeTokens(List<UUID> userIds) { Transaction tx = persistence.getTransaction(); try { EntityManager em = persistence.getEntityManager(); Query query = em.createQuery("delete from sec$RememberMeToken rt where rt.user.id in :userIds"); query.setParameter("userIds", userIds); query.executeUpdate(); tx.commit(); } finally { tx.end(); } }
protected void checkIfFileDescriptorExists(FileDescriptor fd) throws FileStorageException { try (Transaction tx = persistence.getTransaction()) { FileDescriptor existingFile = persistence.getEntityManager().find(FileDescriptor.class, fd.getId()); if (existingFile == null || entityStates.isDeleted(existingFile)) { throw new FileStorageException(FileStorageException.Type.FILE_NOT_FOUND, fd.getName()); } tx.commit(); } } }
protected Map<User, String> updateUserPasswords(List<UUID> userIds, boolean generatePassword) { Map<User, String> modifiedUsers = new LinkedHashMap<>(); Transaction tx = persistence.getTransaction(); try { EntityManager em = persistence.getEntityManager(); TypedQuery<User> query = em.createQuery("select u from sec$User u where u.id in :userIds", User.class); query.setParameter("userIds", userIds); query.setViewName(RESET_PASSWORD_VIEW); List<User> users = query.getResultList(); if (users == null || users.size() != userIds.size()) throw new IllegalStateException("Not all users found in database"); for (User user : users) { String password = null; if (generatePassword) { password = passwordEncryption.generateRandomPassword(); user.setPasswordEncryption(passwordEncryption.getHashMethod()); String passwordHash = passwordEncryption.getPasswordHash(user.getId(), password); user.setPassword(passwordHash); } user.setChangePasswordAtNextLogon(true); modifiedUsers.put(user, password); } resetRememberMeTokens(userIds); tx.commit(); } finally { tx.end(); } return modifiedUsers; }
@Override public Role copyRole(UUID roleId) { checkNotNullArgument(roleId, "Null access role id"); checkUpdatePermission(Role.class); Role clone; Transaction tx = persistence.getTransaction(); try { EntityManager em = persistence.getEntityManager(); Query roleNamesQuery = em.createQuery("select g.name from sec$Role g"); @SuppressWarnings("unchecked") Set<String> roleNames = new HashSet<>(roleNamesQuery.getResultList()); Role role = em.find(Role.class, roleId, ROLE_COPY_VIEW); if (role == null) throw new IllegalStateException("Unable to find specified role with id: " + roleId); clone = cloneRole(role, roleNames, em); clone.setDefaultRole(false); tx.commit(); } finally { tx.end(); } return clone; }
@Override public Group copyAccessGroup(UUID accessGroupId) { checkNotNullArgument(accessGroupId, "Null access group id"); checkUpdatePermission(Group.class); Group clone; Transaction tx = persistence.getTransaction(); try { EntityManager em = persistence.getEntityManager(); Query groupNamesQuery = em.createQuery("select g.name from sec$Group g"); @SuppressWarnings("unchecked") Set<String> groupNames = new HashSet<>(groupNamesQuery.getResultList()); Group accessGroup = em.find(Group.class, accessGroupId, GROUP_COPY_VIEW); if (accessGroup == null) throw new IllegalStateException("Unable to find specified access group with id: " + accessGroupId); clone = cloneGroup(accessGroup, accessGroup.getParent(), groupNames, em); tx.commit(); } finally { tx.end(); } return clone; }
protected void storeAccessTokenToDatabase(String tokenValue, byte[] accessTokenBytes, String authenticationKey, byte[] authenticationBytes, Date tokenExpiry, String userLogin, @Nullable Locale locale, @Nullable String refreshTokenValue) { try (Transaction tx = persistence.getTransaction()) { EntityManager em = persistence.getEntityManager(); AccessToken accessToken = metadata.create(AccessToken.class); accessToken.setCreateTs(timeSource.currentTimestamp()); accessToken.setTokenValue(tokenValue); accessToken.setTokenBytes(accessTokenBytes); accessToken.setAuthenticationKey(authenticationKey); accessToken.setAuthenticationBytes(authenticationBytes); accessToken.setExpiry(tokenExpiry); accessToken.setUserLogin(userLogin); accessToken.setLocale(locale != null ? locale.toString() : null); accessToken.setRefreshTokenValue(refreshTokenValue); em.persist(accessToken); tx.commit(); } }
@Override public void storeAccessToken(String tokenValue, byte[] accessTokenBytes, String authenticationKey, byte[] authenticationBytes, Date tokenExpiry, String userLogin, Locale locale, String refreshTokenValue) { storeAccessTokenToMemory(tokenValue, accessTokenBytes, authenticationKey, authenticationBytes, tokenExpiry, userLogin, refreshTokenValue); if (serverConfig.getRestStoreTokensInDb()) { try (Transaction tx = persistence.getTransaction()) { removeAccessTokenFromDatabase(tokenValue); storeAccessTokenToDatabase(tokenValue, accessTokenBytes, authenticationKey, authenticationBytes, tokenExpiry, userLogin, locale, refreshTokenValue); tx.commit(); } } clusterManagerAPI.send(new TokenStoreAddAccessTokenMsg(tokenValue, accessTokenBytes, authenticationKey, authenticationBytes, tokenExpiry, userLogin, refreshTokenValue)); }
protected void storeRefreshTokenToDatabase(String tokenValue, byte[] tokenBytes, byte[] authenticationBytes, Date tokenExpiry, String userLogin) { try (Transaction tx = persistence.getTransaction()) { EntityManager em = persistence.getEntityManager(); RefreshToken refreshToken = metadata.create(RefreshToken.class); refreshToken.setCreateTs(timeSource.currentTimestamp()); refreshToken.setTokenValue(tokenValue); refreshToken.setTokenBytes(tokenBytes); refreshToken.setAuthenticationBytes(authenticationBytes); refreshToken.setExpiry(tokenExpiry); refreshToken.setUserLogin(userLogin); em.persist(refreshToken); tx.commit(); } }