Skip to content

Commit

Permalink
refactorings
Browse files Browse the repository at this point in the history
  • Loading branch information
car031 committed Nov 21, 2024
1 parent ca0aafe commit 46438d0
Show file tree
Hide file tree
Showing 12 changed files with 54 additions and 81 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ protected void logQuery(String query) {
}

@Override
public List<?> findByQuery(String query, Map<String, Object> parameters, Integer max) throws PersistenceException {
public List<Object[]> findByQuery(String query, Map<String, Object> parameters, Integer max) throws PersistenceException {
try {
logQuery(query);
return prepareQuery(query, parameters, max).list();
Expand Down Expand Up @@ -312,23 +312,6 @@ protected <R> Query<R> prepareQuery(String expression, Map<String, Object> value
return queryObject;
}

/**
* Utility method useful for preparing an Hibernate query for updates
*
* @param expression The expression for the query
* @param values The parameters values to be used (optional, if the query is
* parametric)
* @param max Optional maximum number of wanted results
*
* @return The Hibernate query (for updates/deletes this query cannot by
* typed)
*/
protected Query<?> prepareQueryForUpdate(String expression, Map<String, Object> values, Integer max) {
Query<?> queryObject = sessionFactory.getCurrentSession().createQuery(expression);
applyParametersAndLimit(values, max, queryObject);
return queryObject;
}

private void applyParametersAndLimit(Map<String, Object> parameters, Integer max, Query<?> queryObject) {
if (parameters != null)
for (Map.Entry<String, Object> entry : parameters.entrySet())
Expand Down Expand Up @@ -558,8 +541,10 @@ public int bulkUpdate(String expression, Map<String, Object> parameters) throws
return 0;

try {
return prepareQueryForUpdate(UPDATE + entityClass.getCanonicalName() + " " + expression, parameters, null)
.executeUpdate();
Query<?> queryObject = sessionFactory.getCurrentSession()
.createQuery(UPDATE + entityClass.getCanonicalName() + " " + expression);
applyParametersAndLimit(parameters, null, queryObject);
return queryObject.executeUpdate();
} catch (Exception e) {
throw new PersistenceException(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ public List<T> findByObjectQuery(String query, Map<String, Object> parameters, I
*
* @throws PersistenceException raised in case of errors in the database
*/
public List<?> findByQuery(String query, Map<String, Object> parameters, Integer max) throws PersistenceException;
public List<Object[]> findByQuery(String query, Map<String, Object> parameters, Integer max) throws PersistenceException;

/**
* Find everything you want from the DB using the ORM query language
Expand Down Expand Up @@ -509,7 +509,7 @@ public <R> R queryForObject(String sql, Map<String, Object> parameters, Class<R>
public void deleteAll(Collection<T> entities, int code) throws PersistenceException;

/**
* Executes a bulk update as specified by the given expression
* Executes a bulk update as specified by the given HQL expression
*
* @param expression The update expression.
* @param parameters Optional map of parameters
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -847,18 +847,18 @@ public void restore(long folderId, long parentId, FolderHistory transaction) thr
// The parent folder
Folder parent = findFolder(parentId);

int count = bulkUpdate("set ld_deleted=0, ld_parentid=" + parent.getId()
int count = jdbcUpdate("update ld_folder set ld_deleted=0, ld_parentid=" + parent.getId()
+ ", ld_lastmodified=CURRENT_TIMESTAMP where not ld_type=" + Folder.TYPE_WORKSPACE + " and ld_id="
+ folderId, (Map<String, Object>) null);
+ folderId);

if (count == 0) {
// The root of folders in the current tenant
Folder root = findRoot(parent.getTenantId());

// Workspaces must always be restored under the root
bulkUpdate("set ld_deleted=0, ld_parentid=" + root.getId()
jdbcUpdate("update ld_folder set ld_deleted=0, ld_parentid=" + root.getId()
+ ", ld_lastmodified=CURRENT_TIMESTAMP where ld_type=" + Folder.TYPE_WORKSPACE + " and ld_id="
+ folderId, (Map<String, Object>) null);
+ folderId);
}

Folder fld = findFolder(folderId);
Expand All @@ -871,8 +871,9 @@ public void restore(long folderId, long parentId, FolderHistory transaction) thr
Set<Long> treeIds = findFolderIdInTree(folderId, true);
if (!treeIds.isEmpty()) {
String idsStr = treeIds.toString().replace('[', '(').replace(']', ')');
bulkUpdate("set ld_deleted=0, ld_lastmodified=CURRENT_TIMESTAMP where ld_deleted=1 and ld_id in " + idsStr,
(Map<String, Object>) null);
jdbcUpdate(
"update ld_folder set ld_deleted=0, ld_lastmodified=CURRENT_TIMESTAMP where ld_deleted=1 and ld_id in "
+ idsStr);
jdbcUpdate(
"update ld_document set ld_deleted=0, ld_lastmodified=CURRENT_TIMESTAMP where ld_deleted=1 and ld_folderid in "
+ idsStr);
Expand Down Expand Up @@ -2000,7 +2001,7 @@ public void updateSecurityRef(long folderId, long rightsFolderId, FolderHistory
store(f, transaction);

// Now all the folders that are referencing this one must be updated
bulkUpdate("set securityRef=" + securityRef + " where securityRef=" + folderId, (Map<String, Object>) null);
bulkUpdate("set securityRef=" + securityRef + " where securityRef=" + folderId, null);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ protected void runTask() throws TaskException {
Map<String, Object> params = new HashMap<>();
params.put("transactionId", transactionId);

documentDao.bulkUpdate("set ld_transactionid = null where ld_transactionId = :transactionId", params);
documentDao.jdbcUpdate("update ld_document set ld_transactionid = null where ld_transactionId = :transactionId", params);
} catch (PersistenceException e) {
log.error(e.getMessage(), e);
}
Expand Down Expand Up @@ -253,8 +253,8 @@ private void assignTransition(List<Long> docIds) throws PersistenceException {
Map<String, Object> params = new HashMap<>();
params.put("transactionId", transactionId);

documentDao.bulkUpdate(
" set ld_transactionid = :transactionId where ld_transactionid is null and ld_id in " + idsStr,
documentDao.jdbcUpdate(
" update ld_document set ld_transactionid = :transactionId where ld_transactionid is null and ld_id in " + idsStr,
params);
}
log.info("Documents marked for indexing in transaction {}", transactionId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,24 @@

public class HibernateSessionDAO extends HibernatePersistentObjectDAO<Session> implements SessionDAO {

private static final String AND = " and ";

protected HibernateSessionDAO() {
super(Session.class);
}

@Override
public void deleteCurrentNodeSessions() {
try {
Map<String, Object> params = new HashMap<>();
params.put("node", SystemInfo.get().getInstallationId());

bulkUpdate(" set deleted=1 where node = :node and deleted=0", params);
jdbcUpdate("update ld_session set ld_deleted=1 where ld_node = :node and ld_deleted=0",
Map.of("node", SystemInfo.get().getInstallationId()));
} catch (PersistenceException e) {
log.warn(e.getMessage(), e);
}

try {
Map<String, Object> params = new HashMap<>();
params.put("node", SystemInfo.get().getInstallationId());
params.put("status", Session.STATUS_OPEN);

bulkUpdate(" set status=" + Session.STATUS_EXPIRED + " where node = :node and status = :status", params);
jdbcUpdate("update ld_session set ld_status=" + Session.STATUS_EXPIRED + " where ld_node = :node and ld_status = :status",
Map.of("node", SystemInfo.get().getInstallationId(), "status", Session.STATUS_OPEN));
} catch (PersistenceException e) {
log.error(e.getMessage(), e);
}
Expand All @@ -43,13 +40,13 @@ public void deleteCurrentNodeSessions() {
public int countSessions(Long tenantId, Integer status) {
StringBuilder query = new StringBuilder(" 1=1 ");
if (tenantId != null)
query.append(" and " + ENTITY + ".tenantId = " + tenantId);
query.append(AND + ENTITY + ".tenantId = " + tenantId);
if (status != null) {
query.append(" and " + ENTITY + ".status = " + status);
if(status.intValue() == Session.STATUS_OPEN)
query.append(" and " + ENTITY + ".finished is null ");
query.append(AND + ENTITY + ".status = " + status);
if (status.intValue() == Session.STATUS_OPEN)
query.append(AND + ENTITY + ".finished is null ");
}

try {
List<Session> sessions = findByWhere(query.toString(), null, null);
return sessions.size();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,7 @@ public List<Menu> findParents(long menuId) {

@Override
public void restore(long menuId, boolean parents) throws PersistenceException {
bulkUpdate("set ld_deleted=0 where ld_id=" + menuId, (Map<String, Object>) null);
jdbcUpdate("update ld_menu set ld_deleted=0 where ld_id=" + menuId);

// Restore parents
if (parents) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import java.sql.SQLException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
Expand Down Expand Up @@ -84,8 +83,8 @@ private void processDocuments(List<Long> docIds, int max) throws PersistenceExce

// Mark all these documents as belonging to the current
// transaction
documentDao.bulkUpdate("set ld_transactionid='" + transactionId + "' where ld_id in " + idsStr,
(Map<String, Object>) null);
documentDao
.jdbcUpdate("update ld_document set ld_transactionid='" + transactionId + "' where ld_id in " + idsStr);

// Now we can release the lock
lockManager.release(getName(), transactionId);
Expand Down Expand Up @@ -130,8 +129,8 @@ public Object[] mapRow(ResultSet rs, int row) throws SQLException {

private void removeTransactionReference() {
try {
documentDao.bulkUpdate("set ld_transactionid=null where ld_transactionId='" + transactionId + "'",
(Map<String, Object>) null);
documentDao.jdbcUpdate(
"update ld_document set ld_transactionid=null where ld_transactionId='" + transactionId + "'");
} catch (PersistenceException e) {
log.warn(e.getMessage(), e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1303,12 +1303,14 @@ public void testUpdateSecurityRef() throws PersistenceException {

folder = testSubject.findById(1201L);
assertEquals(1200L, folder.getSecurityRef().longValue());
assertEquals(1200L, folder.getParentId());
folder = testSubject.findById(1202L);
assertEquals(1200L, folder.getSecurityRef().longValue());
assertEquals(1201L, folder.getParentId());

// The root has its own policies
testSubject.updateSecurityRef(1200L, 5L, transaction);

folder = testSubject.findById(1200L);
assertEquals(5L, folder.getSecurityRef().longValue());
folder = testSubject.findById(1201L);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -438,8 +438,7 @@ private List<Long> getForbiddenDocumentIds(User user, long folderId) throws Pers
forbiddenDocsQuery.append(") and ld_folderid = ");
forbiddenDocsQuery.append(Long.toString(folderId));

List<Long> forbiddenDocIds = docDao.queryForList(forbiddenDocsQuery.toString(), Long.class);
return forbiddenDocIds;
return docDao.queryForList(forbiddenDocsQuery.toString(), Long.class);
}

private List<Document> enrichRecords(List<?> records, List<String> extendedAttributes,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -956,7 +956,7 @@ public List<GUIVersion> getVersionsById(long id1, long id2) throws ServerExcepti
if (docVersion != null)
versDao.initialize(docVersion);
} catch (Exception e) {
return super.<List<GUIVersion>>throwServerException(session, log, e);
return super.<List<GUIVersion>> throwServerException(session, log, e);
}

GUIVersion version2 = null;
Expand Down Expand Up @@ -1146,16 +1146,14 @@ public void markUnindexable(List<Long> docIds) throws ServerException {
public void restore(List<Long> docIds, long folderId) throws ServerException {
Session session = validateSession();

DocumentDAO docDao = Context.get().getBean(DocumentDAO.class);

for (Long docId : docIds) {
if (docId == null)
continue;
DocumentHistory transaction = new DocumentHistory();
transaction.setSession(session);

try {
docDao.restore(docId, folderId, transaction);
Context.get().getBean(DocumentDAO.class).restore(docId, folderId, transaction);
} catch (PersistenceException e) {
log.error(e.getMessage(), e);
}
Expand Down Expand Up @@ -2261,9 +2259,9 @@ public void deleteFromTrash(List<Long> ids) throws ServerException {
return;

String idsStr = Arrays.asList(ids).toString().replace('[', '(').replace(']', ')');
DocumentDAO dao = Context.get().getBean(DocumentDAO.class);
try {
dao.bulkUpdate("set ld_deleted=2 where ld_id in " + idsStr, (Map<String, Object>) null);
Context.get().getBean(DocumentDAO.class)
.jdbcUpdate("update ld_document set ld_deleted=2 where ld_id in " + idsStr);
} catch (PersistenceException e) {
throwServerException(session, log, e);
}
Expand All @@ -2275,13 +2273,12 @@ public void emptyTrash() throws ServerException {
Session session = validateSession();

try {
DocumentDAO dao = Context.get().getBean(DocumentDAO.class);
dao.bulkUpdate("set ld_deleted=2 where ld_deleted=1 and ld_deleteuserid=" + session.getUserId(),
(Map<String, Object>) null);
Context.get().getBean(DocumentDAO.class)
.jdbcUpdate("update ld_document set ld_deleted=2 where ld_deleted=1 and ld_deleteuserid="
+ session.getUserId());

FolderDAO fdao = Context.get().getBean(FolderDAO.class);
fdao.bulkUpdate("set ld_deleted=2 where ld_deleted=1 and ld_deleteuserid=" + session.getUserId(),
(Map<String, Object>) null);
Context.get().getBean(FolderDAO.class).jdbcUpdate(
"update ld_folder set ld_deleted=2 where ld_deleted=1 and ld_deleteuserid=" + session.getUserId());
} catch (PersistenceException e) {
throwServerException(session, log, e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1074,12 +1074,9 @@ public void deleteFromTrash(List<Long> ids) throws ServerException {
if (ids.isEmpty())
return;

FolderDAO dao = Context.get().getBean(FolderDAO.class);
try {
dao.bulkUpdate(
"set ld_deleted=2 where ld_id in ("
+ ids.stream().map(id -> Long.toString(id)).collect(Collectors.joining(",")) + ")",
(Map<String, Object>) null);
Context.get().getBean(FolderDAO.class).jdbcUpdate("update ld_folder set ld_deleted=2 where ld_id in ("
+ ids.stream().map(id -> Long.toString(id)).collect(Collectors.joining(",")) + ")");
} catch (PersistenceException e) {
throwServerException(session, log, e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,26 +102,22 @@ public void rescheduleAll(final boolean dropIndex) throws ServerException {

if (dropIndex)
try {
SearchEngine indexer = Context.get().getBean(SearchEngine.class);
indexer.dropIndex();
Context.get().getBean(SearchEngine.class).dropIndex();
} catch (Exception e) {
throw new ServerException(e.getMessage(), e);
}

Runnable task = () -> {
try {
DocumentDAO documentDao = Context.get().getBean(DocumentDAO.class);
documentDao.bulkUpdate(
"set ld_indexed=0 where ld_indexed=1 "
+ (!dropIndex ? " and ld_tenantid=" + session.getTenantId() : ""),
(Map<String, Object>) null);
Context.get().getBean(DocumentDAO.class)
.jdbcUpdate("update ld_document set ld_indexed=0 where ld_indexed=1 "
+ (!dropIndex ? " and ld_tenantid=" + session.getTenantId() : ""));
} catch (Exception t) {
log.error(t.getMessage(), t);
}
};

Thread recreateThread = new Thread(task);
recreateThread.start();
new Thread(task).start();
}

@Override
Expand Down

0 comments on commit 46438d0

Please sign in to comment.